@voicenter-team/opensips-js 1.0.45 → 1.0.46

Sign up to get free protection for your applications and to get access to all the features.
@@ -152,4 +152,4 @@ t=0 0
152
152
  m=message 2856 TCP/TLS/MSRP *
153
153
  a=accept-types:text/plain text/html
154
154
  a=path:${r.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
155
- `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new nm(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=ye.STATUS_CONFIRMED,this.target_addr=t.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(r={}){console.log("terminate",this);const n=r.cause||Ie.causes.BYE,o=Ss.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===ye.STATUS_TERMINATED)throw new cm.InvalidStateError(this._status);switch(this.status="terminated",this._status){case ye.STATUS_NULL:case ye.STATUS_INVITE_SENT:case ye.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||Ie.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===ye.STATUS_NULL||this._status===ye.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===ye.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=ye.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,Ie.causes.CANCELED);break;case ye.STATUS_WAITING_FOR_ANSWER:case ye.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,Ie.causes.REJECTED);break;case ye.STATUS_WAITING_FOR_ACK:case ye.STATUS_CONFIRMED:if(p=r.reason_phrase||Ie.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===ye.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Nr.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===Ie.ACK&&(this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Nr.C.STATUS_TERMINATED&&(this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,n),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendRequest(r,n){return this._dialog.sendRequest(r,n)}authenticate(r){this.status="auth";let n=new In("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),r&&n.addHeader("Authorization",r.toString());let o=n.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(n.toString())}onmessage(r){console.log("onmessage",r);const n=new In(r.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new Gp(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Ss.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const r=new RTCPeerConnection({iceServers:[]});r.createDataChannel(""),r.createOffer().then(r.setLocalDescription.bind(r)),r.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(o);this.my_ip=a&&a[1],r.onicecandidate=()=>{},this.authenticate(null)}}onerror(r){console.log(r)}_receiveInviteResponse(r){if(console.log("resp0000000000000",r),this._dialog&&r.status_code>=200&&r.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===r.call_id&&this._dialog.id.local_tag===r.from_tag&&this._dialog.id.remote_tag===r.to_tag){this.sendRequest(Ie.ACK);return}else{const n=new Gl(this,r,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(Ie.ACK),this.sendRequest(Ie.BYE);return}if(this._is_canceled){r.status_code>=100&&r.status_code<200?this._request.cancel(this._cancel_reason):r.status_code>=200&&r.status_code<299&&this._acceptAndTerminate(r);return}if(!(this._status!==ye.STATUS_INVITE_SENT&&this._status!==ye.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(r.status_code):this._status=ye.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(r.status_code):{if(!r.to_tag){console.log("1xx response received without to tag");break}if(r.hasHeader("contact")&&!this._createDialog(r,"UAC",!0))break;if(this._status=ye.STATUS_1XX_RECEIVED,!r.body){this._progress("remote",r);break}const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",r)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(r.status_code):{if(console.log("maybe here???"),this._status=ye.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,Ie.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",r,Ie.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(r,"UAC"))break;const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(r,500,o.toString()),console.log("failed 4"),this._failed("local",r,Ie.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(Ie.ACK),this._confirmed("local",null)});break}default:{const n=Ss.sipErrorCause(r.status_code);console.log("failed 5"),this._failed("remote",r,n)}}}sendMSRP(r){const n=new In("");n.method="SEND",n.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",Ss.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=r;let o=n.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(r){let n=r.ident,o=r.getHeader("Message-ID"),a=new In("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=n;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(r){let n=r.ident,o=r.getHeader("Message-ID"),a=new In("");a.method="REPORT",a.addHeader("To-Path",`${r.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=n;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(r){const n={},o=r.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");n[t[0]]=t[1].match('^"(.+)"$')[1]}return n}init_incoming(r,n){let o;const a=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0;if(r.body&&a!=="application/sdp"){r.reply(415);return}if(this._status=ye.STATUS_INVITE_RECEIVED,this._from_tag=r.from_tag,this._id=r.call_id+this._from_tag,this._request=r,this._contact=this._ua.contact.toString(),r.hasHeader("expires")&&(o=r.getHeader("expires")*1e3),r.to_tag=Ss.newTag(),!this._createDialog(r,"UAS",!0)){r.reply(500,"Missing Contact header field");return}r.body?this._late_sdp=!1:this._late_sdp=!0,this._status=ye.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),console.log("failed 6"),this._failed("local",null,Ie.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===ye.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),console.log("failed 7"),this._failed("system",null,Ie.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from,n&&n(this),r.parseSDP(!0),this.target_addr=r.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",r),this._status!==ye.STATUS_TERMINATED&&(r.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(r,n,o){this.emit("_failed",{originator:r,message:n||null,cause:o}),this._close(),this.emit("failed",{originator:r,message:n||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==ye.STATUS_TERMINATED){if(this._status=ye.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(r){console.log("close() | error closing the RTCPeerConnection: %o",r)}for(const r in this._timers)Object.prototype.hasOwnProperty.call(this._timers,r)&&clearTimeout(this._timers[r]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const r in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,r)&&(this._earlyDialogs[r].terminate(),delete this._earlyDialogs[r]);for(const r in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,r)&&delete this._referSubscribers[r];this._ua.destroyMSRPSession(this)}}_createDialog(r,n,o){const a=n==="UAS"?r.to_tag:r.from_tag,t=n==="UAS"?r.from_tag:r.to_tag,s=r.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Gl(this,r,n,Gl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",r,Ie.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=r.from_tag,this._to_tag=r.to_tag,p)return p.update(r,n),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Gl(this,r,n);return _.error?(console.log("failed 9"),this._failed("remote",r,Ie.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(r,n){this._ua.newMSRPSession(this,{originator:r,session:this,request:n})}_progress(r,n){this.emit("progress",{originator:r,response:n||null})}isEnded(){switch(this._status){case ye.STATUS_CANCELED:case ye.STATUS_TERMINATED:return!0;default:return!1}}_accepted(r,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:r,response:n||null})}_confirmed(r,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:r,ack:n||null})}_ended(r,n,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:r,message:n||null,cause:o})}_handleSessionTimersInIncomingResponse(r){if(!this._sessionTimers.enabled)return;let n;r.session_expires&&r.session_expires>=Ie.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=r.session_expires,n=r.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(r){if(console.log("receiveRequest()"),r.method===Ie.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",r,Ie.causes.CANCELED));else switch(r.method){case Ie.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(!r.body){this.terminate({cause:Ie.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",r)}).catch(a=>{this.terminate({cause:Ie.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",r);break;case Ie.BYE:this._status===ye.STATUS_CONFIRMED||this._status===ye.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,Ie.causes.BYE)):this._status===ye.STATUS_INVITE_RECEIVED||this._status===ye.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,Ie.causes.BYE)):r.reply(403,"Wrong Status");break;case Ie.INVITE:this._status===ye.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case Ie.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?(r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Rm(this).init_incoming(r):r.reply(415):r.reply(403,"Wrong Status");break;case Ie.UPDATE:this._status===ye.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case Ie.REFER:this._status===ye.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case Ie.NOTIFY:this._status===ye.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ie.causes.CONNECTION_ERROR,cause:Ie.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ie.causes.REQUEST_TIMEOUT,cause:Ie.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ie.causes.DIALOG_ERROR,cause:Ie.causes.DIALOG_ERROR})}}const zt=console,xf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Ng=Og;class Ug extends Ng{constructor(r){console.log(r),super(r),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}}}call(r,n){return super.call(r,n)}newMSRPSession(r,n){r.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[r.id]=r,this.emit("newMSRPSession",n)}destroyMSRPSession(r){delete this._msrp_sessions[r.id]}receiveRequest(r){const n=r.method;if(console.log("-----------"),r.ruri.user!==this._configuration.uri.user&&r.ruri.user!==this._contact.uri.user){zt.debug("Request-URI does not point to us"),r.method!==we.ACK&&r.reply_sl(404);return}if(r.ruri.scheme===we.SIPS){r.reply_sl(416);return}if(Nr.checkTransaction(this,r))return;if(n===we.INVITE?new Nr.InviteServerTransaction(this,this._transport,r):n!==we.ACK&&n!==we.CANCEL&&new Nr.NonInviteServerTransaction(this,this._transport,r),n===we.OPTIONS){if(this.listeners("newOptions").length===0){r.reply(200);return}new Kc.Options(this).init_incoming(r)}else if(n===we.MESSAGE){if(this.listeners("newMessage").length===0){r.reply(405);return}new Kc.Message(this).init_incoming(r)}else if(n===we.INVITE&&!r.to_tag&&this.listeners("newRTCSession").length===0){r.reply(405);return}let o,a;if(r.to_tag)o=this._findDialog(r.call_id,r.from_tag,r.to_tag),o?o.receiveRequest(r):n===we.NOTIFY?(a=this._findSession(r),a?a.receiveRequest(r):(zt.debug("received NOTIFY request for a non existent subscription"),r.reply(481,"Subscription does not exist"))):n!==we.ACK&&r.reply(481);else switch(n){case we.INVITE:if(window.RTCPeerConnection)if(r.hasHeader("replaces")){const t=r.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?r.reply(603):a.receiveRequest(r)):r.reply(481)}else r.body.search(/MSRP/ig)>-1?(a=new Mf(this),a.init_incoming(r)):(a=new Hm(this),a.init_incoming(r));else zt.warn("INVITE received but WebRTC is not supported"),r.reply(488);break;case we.BYE:r.reply(481);break;case we.CANCEL:a=this._findSession(r),a?a.receiveRequest(r):zt.debug("received CANCEL request for a non existent session");break;case we.ACK:break;case we.NOTIFY:this.emit("sipEvent",{event:r.event,request:r}),r.reply(200);break;default:r.reply(405);break}}startMSRP(r,n){zt.debug("startMSRP()",n);const o=new Mf(this);return o.connect(r),o}terminateMSRPSessions(r){zt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(r)}stop(){if(zt.debug("stop()"),this._dynConfiguration={},this._status===xf.STATUS_USER_CLOSED){zt.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){zt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){zt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=xf.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}var pt={};pt.forEach=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>r.call(n||globalThis,s,a,c));o.push(t)}await Promise.all(o)},pt.forEachSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)o in c&&await r.call(n||globalThis,await c[o],o,c)},pt.map=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>r.call(n||globalThis,t,a,c)));return Promise.all(o)},pt.mapSeries=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await r.call(n||globalThis,await c[a],a,c));return o},pt.find=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.findSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(await r.call(n||globalThis,await c[o],o,c))return c[o]},pt.findIndex=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.findIndexSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(await r.call(n||globalThis,await c[o],o,c))return o},pt.some=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.someSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(o in c&&await r.call(n||globalThis,await c[o],o,c))return!0;return!1},pt.every=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.everySeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(o in c&&!await r.call(n||globalThis,await c[o],o,c))return!1;return!0},pt.filter=(c,r,n)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>r.call(n||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),pt.filterSeries=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await r.call(n||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},pt.reduce=async(c,r,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(n!==void 0?(a=n,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await r(await a,await c[o],o,c));return a};var Lf={};(function(c){const r=pt;Object.keys(r).forEach(n=>{const o=n.charAt(0).toUpperCase()+n.slice(1);c[`async${o}`]=async function(...a){return r[n](this,...a)}})})(Lf);var Pg=Object.assign(pt,{instanceMethods:Lf});function za(c){return c<10?`0${c}`:`${c}`}function kg(c){let r=c.hours||0,n=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,n++,n===60&&(n=0,r++));const a=`${za(r)}:${za(n)}:${za(o)}`;return{seconds:o,minutes:n,hours:r,formatted:a}}function Mg(c,r){return Object.keys(c).filter(n=>r.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const xg=["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"],Lg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function $f(c){const r={};return xg.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r.localHold=c._localHold,r}function Hf(c){const r={};return Lg.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r}function Zl(c,r){const n=new AudioContext,o=n.createMediaStreamSource(c),a=n.createMediaStreamDestination(),t=n.createGain();return o.connect(t),t.connect(a),t.gain.value=r,a.stream}function $g(c,r,n,o){const a=document.createElement("audio");a.id=r._id,a.className="audioTag",a.srcObject=c.stream,a.setSinkId(n),a.volume=o,a.play(),r.audioTag=a}function Hg(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}var Fg={exports:{}};(function(c){var r=function(n){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(Q,W,B){Q[W]=B.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function v(Q,W,B){return Object.defineProperty(Q,W,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[W]}try{v({},"")}catch{v=function(W,B,te){return W[B]=te}}function E(Q,W,B,te){var de=W&&W.prototype instanceof ie?W:ie,Ae=Object.create(de.prototype),Ue=new P(te||[]);return t(Ae,"_invoke",{value:Y(Q,B,Ue)}),Ae}n.wrap=E;function S(Q,W,B){try{return{type:"normal",arg:Q.call(W,B)}}catch(te){return{type:"throw",arg:te}}}var C="suspendedStart",I="suspendedYield",w="executing",F="completed",L={};function ie(){}function N(){}function H(){}var ve={};v(ve,_,function(){return this});var me=Object.getPrototypeOf,M=me&&me(me(Z([])));M&&M!==o&&a.call(M,_)&&(ve=M);var D=H.prototype=ie.prototype=Object.create(ve);N.prototype=H,t(D,"constructor",{value:H,configurable:!0}),t(H,"constructor",{value:N,configurable:!0}),N.displayName=v(H,g,"GeneratorFunction");function V(Q){["next","throw","return"].forEach(function(W){v(Q,W,function(B){return this._invoke(W,B)})})}n.isGeneratorFunction=function(Q){var W=typeof Q=="function"&&Q.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(Q){return Object.setPrototypeOf?Object.setPrototypeOf(Q,H):(Q.__proto__=H,v(Q,g,"GeneratorFunction")),Q.prototype=Object.create(D),Q},n.awrap=function(Q){return{__await:Q}};function j(Q,W){function B(Ae,Ue,Se,ne){var Te=S(Q[Ae],Q,Ue);if(Te.type==="throw")ne(Te.arg);else{var tt=Te.arg,st=tt.value;return st&&typeof st=="object"&&a.call(st,"__await")?W.resolve(st.__await).then(function(ge){B("next",ge,Se,ne)},function(ge){B("throw",ge,Se,ne)}):W.resolve(st).then(function(ge){tt.value=ge,Se(tt)},function(ge){return B("throw",ge,Se,ne)})}}var te;function de(Ae,Ue){function Se(){return new W(function(ne,Te){B(Ae,Ue,ne,Te)})}return te=te?te.then(Se,Se):Se()}t(this,"_invoke",{value:de})}V(j.prototype),v(j.prototype,d,function(){return this}),n.AsyncIterator=j,n.async=function(Q,W,B,te,de){de===void 0&&(de=Promise);var Ae=new j(E(Q,W,B,te),de);return n.isGeneratorFunction(W)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function Y(Q,W,B){var te=C;return function(Ae,Ue){if(te===w)throw new Error("Generator is already running");if(te===F){if(Ae==="throw")throw Ue;return et()}for(B.method=Ae,B.arg=Ue;;){var Se=B.delegate;if(Se){var ne=$(Se,B);if(ne){if(ne===L)continue;return ne}}if(B.method==="next")B.sent=B._sent=B.arg;else if(B.method==="throw"){if(te===C)throw te=F,B.arg;B.dispatchException(B.arg)}else B.method==="return"&&B.abrupt("return",B.arg);te=w;var Te=S(Q,W,B);if(Te.type==="normal"){if(te=B.done?F:I,Te.arg===L)continue;return{value:Te.arg,done:B.done}}else Te.type==="throw"&&(te=F,B.method="throw",B.arg=Te.arg)}}}function $(Q,W){var B=W.method,te=Q.iterator[B];if(te===s)return W.delegate=null,B==="throw"&&Q.iterator.return&&(W.method="return",W.arg=s,$(Q,W),W.method==="throw")||B!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+B+"' method")),L;var de=S(te,Q.iterator,W.arg);if(de.type==="throw")return W.method="throw",W.arg=de.arg,W.delegate=null,L;var Ae=de.arg;if(!Ae)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,L;if(Ae.done)W[Q.resultName]=Ae.value,W.next=Q.nextLoc,W.method!=="return"&&(W.method="next",W.arg=s);else return Ae;return W.delegate=null,L}V(D),v(D,g,"Generator"),v(D,_,function(){return this}),v(D,"toString",function(){return"[object Generator]"});function X(Q){var W={tryLoc:Q[0]};1 in Q&&(W.catchLoc=Q[1]),2 in Q&&(W.finallyLoc=Q[2],W.afterLoc=Q[3]),this.tryEntries.push(W)}function U(Q){var W=Q.completion||{};W.type="normal",delete W.arg,Q.completion=W}function P(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(X,this),this.reset(!0)}n.keys=function(Q){var W=Object(Q),B=[];for(var te in W)B.push(te);return B.reverse(),function de(){for(;B.length;){var Ae=B.pop();if(Ae in W)return de.value=Ae,de.done=!1,de}return de.done=!0,de}};function Z(Q){if(Q){var W=Q[_];if(W)return W.call(Q);if(typeof Q.next=="function")return Q;if(!isNaN(Q.length)){var B=-1,te=function de(){for(;++B<Q.length;)if(a.call(Q,B))return de.value=Q[B],de.done=!1,de;return de.value=s,de.done=!0,de};return te.next=te}}return{next:et}}n.values=Z;function et(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(Q){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!Q)for(var W in this)W.charAt(0)==="t"&&a.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=s)},stop:function(){this.done=!0;var Q=this.tryEntries[0],W=Q.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var W=this;function B(ne,Te){return Ae.type="throw",Ae.arg=Q,W.next=ne,Te&&(W.method="next",W.arg=s),!!Te}for(var te=this.tryEntries.length-1;te>=0;--te){var de=this.tryEntries[te],Ae=de.completion;if(de.tryLoc==="root")return B("end");if(de.tryLoc<=this.prev){var Ue=a.call(de,"catchLoc"),Se=a.call(de,"finallyLoc");if(Ue&&Se){if(this.prev<de.catchLoc)return B(de.catchLoc,!0);if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else if(Ue){if(this.prev<de.catchLoc)return B(de.catchLoc,!0)}else if(Se){if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,W){for(var B=this.tryEntries.length-1;B>=0;--B){var te=this.tryEntries[B];if(te.tryLoc<=this.prev&&a.call(te,"finallyLoc")&&this.prev<te.finallyLoc){var de=te;break}}de&&(Q==="break"||Q==="continue")&&de.tryLoc<=W&&W<=de.finallyLoc&&(de=null);var Ae=de?de.completion:{};return Ae.type=Q,Ae.arg=W,de?(this.method="next",this.next=de.finallyLoc,L):this.complete(Ae)},complete:function(Q,W){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"&&W&&(this.next=W),L},finish:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),U(B),L}},catch:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.tryLoc===Q){var te=B.completion;if(te.type==="throw"){var de=te.arg;U(B)}return de}}throw new Error("illegal catch attempt")},delegateYield:function(Q,W,B){return this.delegate={iterator:Z(Q),resultName:W,nextLoc:B},this.method==="next"&&(this.arg=s),L}},n}(c.exports);try{regeneratorRuntime=r}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}})(Fg);var Ff={exports:{}};(function(c){(function(r,n){c.exports?c.exports=n():r.log=n()})(lr,function(){var r=function(){},n="undefined",o=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(I,w){var F=I[w];if(typeof F.bind=="function")return F.bind(I);try{return Function.prototype.bind.call(F,I)}catch{return function(){return Function.prototype.apply.apply(F,[I,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(I){return I==="debug"&&(I="log"),typeof console===n?!1:I==="trace"&&o?s:console[I]!==void 0?t(console,I):console.log!==void 0?t(console,"log"):r}function _(I,w){for(var F=0;F<a.length;F++){var L=a[F];this[L]=F<I?r:this.methodFactory(L,I,w)}this.log=this.debug}function d(I,w,F){return function(){typeof console!==n&&(_.call(this,w,F),this[I].apply(this,arguments))}}function g(I,w,F){return p(I)||d.apply(this,arguments)}function v(I,w,F){var L=this,ie;w=w??"WARN";var N="loglevel";typeof I=="string"?N+=":"+I:typeof I=="symbol"&&(N=void 0);function H(D){var V=(a[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=V;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+V+";"}catch{}}}function ve(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var V=window.document.cookie,j=V.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(V.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function me(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=I,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=F||g,L.getLevel=function(){return ie},L.setLevel=function(D,V){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ie=D,V!==!1&&H(D),_.call(L,D,I),typeof console===n&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){w=D,ve()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(w,!1),me()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=ve();M==null&&(M=w),L.setLevel(M,!1)}var E=new v,S={};E.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var F=S[w];return F||(F=S[w]=new v(w,E.getLevel(),E.methodFactory)),F};var C=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=C),E},E.getLoggers=function(){return S},E.default=E,E})})(Ff);var Et=Ff.exports;const us=()=>`${new Date().toISOString()} | metrics`,cs=(c,r,n)=>`${c} | ${r} | ${n}`;Et.setDefaultLevel(Et.levels.TRACE);const qg=c=>{Et.info(cs(us(),"log ",`set log level to ${c?"verbose":"info"}`)),Et.setLevel(c?Et.levels.TRACE:Et.levels.INFO)},jg=c=>{const r=[...Object.keys(Et.levels)];r.includes(c)?(Et.info(cs(us(),"log ",`update log level to ${c.toLowerCase()}`)),Et.setLevel(c)):Et.warn(cs(us(),"log ","Incorrect log level please choose one of "),r)},Ne=(c,r,n)=>{n?Et.debug(cs(us(),c,r),n):Et.debug(cs(us(),c,r))},Ja=(c,r)=>{Et.info(cs(us(),c,r))},Ks=(c,r)=>{Et.info(cs(us(),c,r))},eo=(c,r)=>{Et.warn(cs(us(),c,r))},bn=(c,r)=>{Et.error(cs(us(),c,r))};function Vg(c){return Math.floor(Math.random()*c).toString()}function qf(c,r){let n=r;return c.forEach(o=>{n=n.replace(o,"")}),n}function Bg(c,r){let n="";for(let o=0;o<r;o+=1)n+=c[Vg(c.length)];return n}function Gg({length:c=20,useLetters:r=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return r&&(a.length&&(t=qf(a,t)),_=t.split("")),n&&(a.length&&(s=qf(a,s)),d=s.split("")),p=[..._,...d,...o],Bg(p,c)}var Kg=Gg;const Fr=vt(Kg),Wg=()=>"WebRTCMetrics",Yg=()=>"5.0.3",ke={INBOUND:"inbound",OUTBOUND:"outbound"},fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},qr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},zg=()=>({...{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:[]}}),jf={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:ke.INBOUND},Vf={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:ke.OUTBOUND},Bf={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:ke.INBOUND},Gf={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:ke.OUTBOUND},Jg=c=>{const r={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(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{n.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{n.video[o]={...c.video[o]}}),n}return{...r,audio:{},video:{},data:{...r.data},network:{...r.network},experimental:{...r.experimental}}},Xg={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Fr()}`,cid:`c-${Fr()}`,uid:`u-${Fr()}`,record:!1,ticket:!0},Ft={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"},k={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},jr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Xa={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ee={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Qa="config ",Qg=(c,r={},n)=>{const o={...n,...r};return r.pname||eo(Qa,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),r.cid||eo(Qa,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),r.uid||eo(Qa,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},Zg=(c={})=>{const r={...Xg,...c};return r.name=Wg(),r.version=Yg(),r},Vr=(c,r,n,o=!1,a)=>{let t=c.map(s=>{if(!n)return s[r];if(!a)return s[r][n];const p=s[r][a];return p?p[n]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},Cs=c=>c.reduce((r,n)=>r+n,0)/c.length,ev=()=>`probe-${Fr()}`,tv=()=>`coltr-${Fr()}`,Kf=c=>new Promise(r=>setTimeout(r,c)),Za=(c,r,n)=>{r?c.call(r,n):c(n)},je=(c,r,n,o)=>{const a=Vr(c,r,n,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},We=(c,r,n,o=!1,a)=>{const t=Vr(c,r,n,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Ws=(c,r,n)=>Vr(c,r,n).reduce((a,t)=>a+t,0),Ve=(c,r,n,o)=>{const a=Vr(c,r,n,!0,o);return a.length===0?null:Math.min(...a)},Be=(c,r,n,o)=>{const a=Vr(c,r,n,!1,o);return a.length===0?null:Math.max(...a)},mt=(c,r,n,o)=>{const a=c.slice().pop();if(!a)return null;if(!n)return a[r];if(!o)return a[r][n];const t=a[r][o];return t?t[n]:null},sv=c=>c.slice().pop(),lt=(c,r,n)=>{if(!r)return null;const o={};let a=r[k.AUDIO][c];a||(a=n===ke.INBOUND?{...jf}:{...Vf}),o[k.AUDIO]=a;let t=r[k.VIDEO][c];return t||(t=n===ke.INBOUND?{...Bf}:{...Gf}),o[k.VIDEO]=t,o},Br="exporter ",nv="2.0",Wf=(c,r,n)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[r][n];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?We(c,r,"delta_rtt_ms_out",!1,n):Number(t/s)}return null},rv=(c,r)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const o=n[r].total_rtt_connectivity_ms,a=n[r].total_rtt_connectivity_measure;return!a||!o?We(c,r,"delta_rtt_connectivity_ms"):Number(o/a)},iv=c=>mt(c,"network","local_candidate_type")!=="relay"?`direct/${mt(c,"network","local_candidate_protocol")}`:`turn/${mt(c,"network","local_candidate_relay_protocol")}`,lv=c=>{const r=mt(c,"network","remote_candidate_type"),n=mt(c,"network","remote_candidate_protocol");return r!=="relay"?`direct/${n}`:`turn/${n}`};class ov{constructor(r){this._start=null,this._end=null,this._cfg=r,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ja(Br,"start() - start exporter...");const r=new Date;return this._start=r.toJSON(),r}stop(){Ja(Br,"stop() - stop exporter...");const r=new Date;return this._end=r.toJSON(),r}saveReferenceReport(r){this._referenceReport=r}getReferenceReport(){return this._referenceReport}addReport(r){this._cfg.ticket&&(Ne(Br,`addReport() - add report to exporter at ${r.timestamp}`),this._reports.push(r))}addCustomEvent(r){this._events.push(r)}reset(){Ja(Br,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(Br,"ticket() - generate ticket");const r=mt(this._reports,"audio","total_packets_lost_in"),n=mt(this._reports,"audio","total_packets_in"),o=mt(this._reports,"video","total_packets_lost_in"),a=mt(this._reports,"video","total_packets_in"),t={},s=sv(this._reports);return s&&(Object.keys(s[k.AUDIO]).forEach(p=>{const _=s[k.AUDIO][p];if(t[_.ssrc]={type:k.AUDIO,direction:_.direction},_.direction===ke.INBOUND){const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_jitter_ms_in",p),max:Be(this._reports,k.AUDIO,"delta_jitter_ms_in",p),volatility:je(this._reports,k.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.AUDIO,"delta_kbs_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_kbs_in",p),max:Be(this._reports,k.AUDIO,"delta_kbs_in",p),volatility:je(this._reports,k.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.AUDIO,"delta_KBytes_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_KBytes_in",p),max:Be(this._reports,k.AUDIO,"delta_KBytes_in",p),volatility:je(this._reports,k.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:We(this._reports,k.AUDIO,"mos_emodel_in",!1,p),min:Ve(this._reports,k.AUDIO,"mos_emodel_in",p),max:Be(this._reports,k.AUDIO,"mos_emodel_in",p),volatility:je(this._reports,k.AUDIO,"mos_emodel_in",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_in",!1,p),min:Ve(this._reports,k.AUDIO,"mos_in",p),max:Be(this._reports,k.AUDIO,"mos_in",p),volatility:je(this._reports,k.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},S=mt(this._reports,k.AUDIO,"total_packets_lost_in",p),C=mt(this._reports,k.AUDIO,"total_packets_in",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I}else{const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_jitter_ms_out",p),max:Be(this._reports,k.AUDIO,"delta_jitter_ms_out",p),volatility:je(this._reports,k.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.AUDIO,"delta_kbs_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_kbs_out",p),max:Be(this._reports,k.AUDIO,"delta_kbs_out",p),volatility:je(this._reports,k.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.AUDIO,"delta_KBytes_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_KBytes_out",p),max:Be(this._reports,k.AUDIO,"delta_KBytes_out",p),volatility:je(this._reports,k.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Wf(this._reports,k.AUDIO,p),min:Ve(this._reports,k.AUDIO,"delta_rtt_ms_out",p),max:Be(this._reports,k.AUDIO,"delta_rtt_ms_out",p),volatility:je(this._reports,k.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=mt(this._reports,k.AUDIO,"total_packets_lost_out",p),C=mt(this._reports,k.AUDIO,"total_packets_out",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},w={emodel:{avg:We(this._reports,k.AUDIO,"mos_emodel_out",!1,p),min:Ve(this._reports,k.AUDIO,"mos_emodel_out",p),max:Be(this._reports,k.AUDIO,"mos_emodel_out",p),volatility:je(this._reports,k.AUDIO,"mos_emodel_out",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_out",!1,p),min:Ve(this._reports,k.AUDIO,"mos_out",p),max:Be(this._reports,k.AUDIO,"mos_out",p),volatility:je(this._reports,k.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I,t[p].mos=w}}),Object.keys(s[k.VIDEO]).forEach(p=>{const _=s[k.VIDEO][p];if(t[p]={type:k.VIDEO,direction:_.direction},_.direction===ke.INBOUND){const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_jitter_ms_in",p),max:Be(this._reports,k.VIDEO,"delta_jitter_ms_in",p),volatility:je(this._reports,k.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.VIDEO,"delta_kbs_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_kbs_in",p),max:Be(this._reports,k.VIDEO,"delta_kbs_in",p),volatility:je(this._reports,k.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.VIDEO,"delta_KBytes_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_KBytes_in",p),max:Be(this._reports,k.VIDEO,"delta_KBytes_in",p),volatility:je(this._reports,k.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=mt(this._reports,k.VIDEO,"total_packets_lost_in",p),S=mt(this._reports,k.VIDEO,"total_packets_in",p),C={lost:E,avg:Math.round((E/(E+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=v,t[p].bitrate=g,t[p].loss=C}else{const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_jitter_ms_out",p),max:Be(this._reports,k.VIDEO,"delta_jitter_ms_out",p),volatility:je(this._reports,k.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.VIDEO,"delta_kbs_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_kbs_out",p),max:Be(this._reports,k.VIDEO,"delta_kbs_out",p),volatility:je(this._reports,k.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.VIDEO,"delta_KBytes_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_KBytes_out",p),max:Be(this._reports,k.VIDEO,"delta_KBytes_out",p),volatility:je(this._reports,k.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Wf(this._reports,k.VIDEO,p),min:Ve(this._reports,k.VIDEO,"delta_rtt_ms_out",p),max:Be(this._reports,k.VIDEO,"delta_rtt_ms_out",p),volatility:je(this._reports,k.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=mt(this._reports,k.VIDEO,"total_packets_lost_out",p),C=mt(this._reports,k.VIDEO,"total_packets_out",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I}})),{version:nv,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:t,data:{rtt:{avg:rv(this._reports,"data"),min:Ve(this._reports,"data","delta_rtt_connectivity_ms"),max:Be(this._reports,"data","delta_rtt_connectivity_ms"),volatility:je(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((r/(r+n)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:We(this._reports,"data","delta_kbs_in"),min:Ve(this._reports,"data","delta_kbs_in"),max:Be(this._reports,"data","delta_kbs_in"),volatility:je(this._reports,"data","delta_kbs_in")},out:{avg:We(this._reports,"data","delta_kbs_out"),min:Ve(this._reports,"data","delta_kbs_out"),max:Be(this._reports,"data","delta_kbs_out"),volatility:je(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:We(this._reports,"data","delta_KBytes_in"),min:Ve(this._reports,"data","delta_KBytes_in"),max:Be(this._reports,"data","delta_KBytes_in"),volatility:je(this._reports,"data","delta_KBytes_in")},out:{avg:We(this._reports,"data","delta_KBytes_out"),min:Ve(this._reports,"data","delta_KBytes_out"),max:Be(this._reports,"data","delta_KBytes_out"),volatility:je(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:iv(this._reports),remoteConnection:lv(this._reports)}}}}updateConfig(r){this._cfg=r}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const r=this._reports.slice();return r.pop(),r.pop()||null}getReportsNumber(){return this._reports.length}}const As="extractor ",Yf=(c,r,n,o)=>{let a=!1;const t=o[r].total_rtt_ms_out,s=o[r].total_rtt_measure_out,p=n?n[r].total_rtt_ms_out:0,_=n?n[r].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[q.TIMESTAMP]===o[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let v=t+g,E=s+1;return a&&(v=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:v,totalRTTMeasurements:E}},av=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[r].total_rtt_connectivity_ms,totalRTTMeasurements:o[r].total_rtt_connectivity_measure};const a=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let t=o[r].total_rtt_connectivity_ms+a,s=o[r].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[r].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(s=Number(c[q.RESPONSES_RECEIVED])-(n?n[r].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},to=(c,r,n)=>c[q.TIMESTAMP]===n[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),uv=(c,r)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:r[k.VIDEO].delta_ms_decode_frame_in,frames_decoded:r[k.VIDEO].total_frames_decoded_in,total_decode_time:r[k.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],o=c[q.TOTAL_DECODE_TIME],a=o-r[k.VIDEO].total_time_decoded_in,t=n-r[k.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:n,total_decode_time:o}},cv=(c,r)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:r[k.VIDEO].delta_ms_encode_frame_out,frames_encoded:r[k.VIDEO].total_frames_encoded_out,total_encode_time:r[k.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],o=c[q.TOTAL_ENCODE_TIME],a=o-r[k.VIDEO].total_time_encoded_out,t=n-r[k.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:n,total_encode_time:o}},zf=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[r].total_packets_out,packetsLost:n[r].total_packets_lost_out,bytesSent:n[r].total_KBytes_out};const a=Number(c[q.PACKETS_SENT])||0-(o?o[r].total_packets_out:0),t=a-n[r].total_packets_out,s=Number(c[q.BYTES_SENT])/1024-(o?o[r].total_KBytes_out:0),p=s-n[r].total_KBytes_out,_=c[q.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=n.timestamp;!g&&d&&(g=d);const v=g?_-g:0,E=v>0?p*.008*1024/v*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},Jf=(c,r,n,o)=>{let a=n[r].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(a=Number(c[q.PACKETS_LOST])||0-(o?o[r].total_packets_lost_out:0),t=a-n[r].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(s=Number(100*c[q.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},Xf=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[r].percent_packets_lost_in,packetsReceived:n[r].total_packets_in,packetsLost:n[r].total_packets_lost_in,bytesReceived:n[r].total_KBytes_in};const a=Number(c[q.PACKETS_RECEIVED])||0-(o?o[r].total_packets_in:0),t=Number(c[q.PACKETS_LOST])||0-(o?o[r].total_packets_lost_in:0),s=t-n[r].total_packets_lost_in,p=a-n[r].total_packets_in,_=a!==n[r].total_packets_in?s*100/(s+p):0,d=Number(c[q.BYTES_RECEIVED])/1024-(o?o[r].total_KBytes_in:0),g=d-n[r].total_KBytes_in,v=c[q.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let S=n.timestamp;!S&&E&&(S=E);const C=S?v-S:0,I=C>0?g*.008*1024/C*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:I}},fv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",_v=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return jr.WIFI;switch(c[q.NETWORK_TYPE]){case Xa.ETHERNET:return jr.ETHERNET;case Xa.CELLULAR_4G:return jr.CELLULAR_4G;case Xa.WIFI:return jr.WIFI;default:return jr.CELLULAR}},Qf=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},hv=c=>{const r=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:r,durations:o,resolutionChanges:n}},dv=(c,r,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:r.total_pli_sent_in,nackCount:r.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[q.PLI]||0)-(n?n[k.VIDEO].total_pli_sent_in:0),a=(c[q.NACK]||0)-(n?n[k.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-r[k.VIDEO].total_pli_sent_in,deltaNackCount:a-r[k.VIDEO].total_nack_sent_in}},pv=(c,r,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:r.total_pli_received_out,nackCount:r.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[q.PLI]||0)-(n?n[k.VIDEO].total_pli_received_out:0),a=(c[q.NACK]||0)-(n?n[k.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-r[k.VIDEO].total_pli_received_out,deltaNackCount:a-r[k.VIDEO].total_nack_received_out}},mv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),gv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),vv=(c,r,n)=>{const o=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),t=c[q.TIMESTAMP]||Date.now(),s=o-r.data.total_KBytes_in,p=a-r.data.total_KBytes_out,_=n?n.timestamp:null;let d=r.timestamp;!d&&_&&(d=_);const g=d?t-d:0,v=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:v,kbs_speed_sent:E}},Tv=c=>{const r=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:r,kbs_outgoing_bandwidth:n}},Ev=(c,r,n,o)=>{if(!c)return[];switch(c[q.TYPE]){case Ft.CANDIDATE_PAIR:let a=!1;if(c[q.NOMINATED]&&c[q.STATE]===k.SUCCEEDED&&(a=!0,Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(a=!1)),a){const s=c[q.LOCAL_CANDIDATE_ID],p=c[q.REMOTE_CANDIDATE_ID],_=vv(c,r,o),d=Tv(c),g=av(c,"data",o,r);return[{type:ee.NETWORK,value:{local_candidate_id:s}},{type:ee.NETWORK,value:{remote_candidate_id:p}},{type:ee.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ee.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ee.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ee.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ee.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ee.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ee.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ee.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ee.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ee.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ee.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Ft.LOCAL_CANDIDATE:if(c[q.ID]===r.network.local_candidate_id)return[{type:ee.NETWORK,value:{infrastructure:_v(c)}},{type:ee.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ee.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ee.NETWORK,value:{local_candidate_relay_protocol:fv(c)}}];break;case Ft.REMOTE_CANDIDATE:if(c[q.ID]===r.network.remote_candidate_id)return[{type:ee.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ee.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case Ft.INBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.INBOUND);p&&(p.timestamp=r.timestamp);const _=lt(s,o,ke.INBOUND);if(_&&(_.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=Xf(c,k.AUDIO,p,_),g=to(c,k.AUDIO,p),v=c[q.CODEC_ID]||"";return[{ssrc:s,type:ee.AUDIO,value:{codec_id_in:v}},{ssrc:s,type:ee.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ee.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===k.VIDEO){const d=uv(c,p),g=Xf(c,k.VIDEO,p,_),v=to(c,k.VIDEO,p),E=c[q.DECODER_IMPLEMENTATION]||null,S=c[q.CODEC_ID]||null,C=Qf(c),I=dv(c,p,_);return[{ssrc:s,type:ee.VIDEO,value:{codec_id_in:S}},{ssrc:s,type:ee.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ee.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_jitter_ms_in:v}},{ssrc:s,type:ee.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ee.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ee.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ee.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ee.VIDEO,value:{total_nack_sent_in:I.nackCount}},{ssrc:s,type:ee.VIDEO,value:{delta_nack_sent_in:I.deltaNackCount}},{ssrc:s,type:ee.VIDEO,value:{total_pli_sent_in:I.pliCount}},{ssrc:s,type:ee.VIDEO,value:{delta_pli_sent_in:I.deltaPliCount}},{ssrc:s,type:ee.VIDEO,value:{size_in:C}}]}break}case Ft.OUTBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.OUTBOUND);p&&(p.timestamp=r.timestamp);const _=lt(s,o,ke.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=c[q.CODEC_ID]||null,g=zf(c,k.AUDIO,p,_);return[{ssrc:s,type:ee.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ee.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ee.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ee.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ee.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===k.VIDEO){const d=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,v=cv(c,p),E=Qf(c),S=hv(c),C=pv(c,p,_),I=zf(c,k.VIDEO,p,_);return[{ssrc:s,type:ee.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ee.VIDEO,value:{total_packets_out:I.packetsSent}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_out:I.deltaPacketsSent}},{ssrc:s,type:ee.VIDEO,value:{total_KBytes_out:I.KBytesSent}},{ssrc:s,type:ee.VIDEO,value:{delta_KBytes_out:I.deltaKBytesSent}},{ssrc:s,type:ee.VIDEO,value:{delta_kbs_out:I.kbsSent}},{ssrc:s,type:ee.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ee.VIDEO,value:{delta_ms_encode_frame_out:v.delta_ms_encode_frame}},{ssrc:s,type:ee.VIDEO,value:{total_frames_encoded_out:v.frames_encoded}},{ssrc:s,type:ee.VIDEO,value:{total_time_encoded_out:v.total_encode_time}},{ssrc:s,type:ee.VIDEO,value:{total_nack_received_out:C.nackCount}},{ssrc:s,type:ee.VIDEO,value:{delta_nack_received_out:C.deltaNackCount}},{ssrc:s,type:ee.VIDEO,value:{total_pli_received_out:C.pliCount}},{ssrc:s,type:ee.VIDEO,value:{delta_pli_received_out:C.deltaPliCount}},{ssrc:s,type:ee.VIDEO,value:{size_out:E}},{ssrc:s,type:ee.VIDEO,value:{limitation_out:S}}]}break}case Ft.MEDIA_SOURCE:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Ft.TRACK:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Ft.CODEC:const t=[];return Object.keys(r[k.AUDIO]).forEach(s=>{const p=r[k.AUDIO][s];if(p.codec_id_in===c[q.ID]||p.codec_id_out===c[q.ID]){Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const _=mv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_out:_}})}}),Object.keys(r[k.VIDEO]).forEach(s=>{const p=r[k.VIDEO][s];if(p.codec_id_in===c[q.ID]||p.codec_id_out===c[q.ID]){Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const _=gv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_out:_}})}}),t;case Ft.REMOTE_INBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.OUTBOUND),_=lt(s,o,ke.OUTBOUND);if(c[q.KIND]===k.AUDIO){const d=Yf(c,k.AUDIO,_,p),g=to(c,k.AUDIO,p),v=Jf(c,k.AUDIO,p,_);return[{ssrc:s,type:ee.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ee.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ee.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ee.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ee.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:s,type:ee.AUDIO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{percent_packets_lost_out:v.fractionLost}}]}if(c[q.KIND]===k.VIDEO){const d=Yf(c,k.VIDEO,_,p),g=to(c,k.VIDEO,p),v=Jf(c,k.VIDEO,p,_);return[{ssrc:s,type:ee.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ee.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ee.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ee.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ee.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:s,type:ee.VIDEO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{percent_packets_lost_out:v.fractionLost}}]}break}}return[]},so=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),yv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.INBOUND),s=lt(a,n,ke.INBOUND),p=lt(a,o,ke.INBOUND),_=[],d=[],g=t[r].percent_packets_lost_in,v=t[r].delta_jitter_ms_in,E=s&&s[r].delta_jitter_ms_in||null,S=p&&p[r].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,I=n&&n.data.delta_rtt_connectivity_ms||null,w=o&&o.data.delta_rtt_connectivity_ms||null;C&&_.push(C),I&&_.push(I),w&&_.push(w),v&&d.push(v),n&&E&&d.push(E),o&&S&&d.push(S);const F=_.length>0?Cs(_):100,L=d.length>0?Cs(d):10,ie=93.2-g,N=.18*ie*ie-27.9*ie+1126.62,H=(F+L)/2,ve=H-177.3<0?0:1,me=.024*H+.11*(H-177.3)*ve,M=N-me;return so(M)},Sv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.OUTBOUND),s=lt(a,n,ke.OUTBOUND),p=lt(a,o,ke.OUTBOUND),_=[],d=[],g=t[r].percent_packets_lost_out,v=t[r].delta_rtt_ms_out,E=s&&s[r].delta_rtt_ms_out||null,S=p&&p[r].delta_rtt_ms_out||null,C=t[r].delta_jitter_ms_out,I=s&&s[r].delta_jitter_ms_out||null,w=p&&p[r].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,L=n&&n.data.delta_rtt_connectivity_ms||null,ie=o&&o.data.delta_rtt_connectivity_ms||null;v?_.push(v):F&&_.push(F),E?_.push(E):L&&_.push(L),S?_.push(S):ie&&_.push(ie),C&&d.push(C),n&&I&&d.push(I),o&&w&&d.push(w);const N=_.length>0?Cs(_):100,H=d.length>0?Cs(d):10,ve=93.2-g,me=.18*ve*ve-27.9*ve+1126.62,M=(N+H)/2,D=M-177.3<0?0:1,V=.024*M+.11*(M-177.3)*D,j=me-V;return so(j)},Cv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.INBOUND),s=lt(a,n,ke.INBOUND),p=lt(a,o,ke.INBOUND),_=[],d=[],g=t[r].percent_packets_lost_in/100,v=t[r].delta_jitter_ms_in,E=s&&s[r].delta_jitter_ms_in||null,S=p&&p[r].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,I=n&&n.data.delta_rtt_connectivity_ms||null,w=o&&o.data.delta_rtt_connectivity_ms||null;C&&_.push(C),I&&_.push(I),w&&_.push(w),v&&d.push(v),s&&E&&d.push(E),p&&S&&d.push(S);const F=_.length>0?Cs(_):100,L=d.length>0?Cs(d):10,ie=0,N=19.8,H=29.7,ve=30,me=(F+L)/2+ve,M=me-177.3<0?0:1,D=.024*me+.11*(me-177.3)*M,j=93.2-(ie+N*Math.log(1+H*g)+D);return so(j)},Av=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.OUTBOUND),s=lt(a,n,ke.OUTBOUND),p=lt(a,o,ke.OUTBOUND),_=[],d=[],g=t[r].percent_packets_lost_out/100,v=t[r].delta_rtt_ms_out,E=s&&s[r].delta_rtt_ms_out||null,S=p&&p[r].delta_rtt_ms_out||null,C=t[r].delta_jitter_ms_out,I=s&&s[r].delta_jitter_ms_out||null,w=p&&p[r].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,L=n&&n.data.delta_rtt_connectivity_ms||null,ie=o&&o.data.delta_rtt_connectivity_ms||null;v?_.push(v):F&&_.push(F),E?_.push(E):L&&_.push(L),S?_.push(S):ie&&_.push(ie),C&&d.push(C),s&&I&&d.push(I),p&&w&&d.push(w);const N=_.length>0?Cs(_):100,H=d.length>0?Cs(d):10,ve=0,me=19.8,M=29.7,D=30,V=(N+H)/2+D,j=V-177.3<0?0:1,Y=.024*V+.11*(V-177.3)*j,X=93.2-(ve+me*Math.log(1+M*g)+Y);return so(X)};class Rv{constructor(r,n){this._callbacks={onreport:null,onticket:null},this._id=tv(),this._moduleName=this._id,this._probeId=n,this._config=r,this._exporter=new ov(r),this._state=fs.IDLE,this.registerToPCEvents(),Ks(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(r,n,o,a){const t=(_,d)=>_===k.AUDIO?d===Ft.INBOUND_RTP?{...jf}:{...Vf}:d===Ft.INBOUND_RTP?{...Bf}:{...Gf},s=Jg(n);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=n?n.count+1:1;let p=null;return r.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),Ev(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let v=s[g.type][g.ssrc];v||(v=t(g.type,_.type),v.ssrc=g.ssrc,s[g.type][g.ssrc]=v),Object.keys(g.value).forEach(E=>{v[E]=g.value[E]})}else Object.keys(g.value).forEach(v=>{s[g.type][v]=g.value[v]})})}),s.timestamp=p,Object.keys(s[k.AUDIO]).forEach(_=>{const d=s[k.AUDIO][_];d.direction===ke.INBOUND?(d.mos_emodel_in=yv(s,k.AUDIO,n,o,d.ssrc),d.mos_in=Cv(s,k.AUDIO,n,o,d.ssrc)):(d.mos_emodel_out=Sv(s,k.AUDIO,n,o,d.ssrc),d.mos_out=Av(s,k.AUDIO,n,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((r,n)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Ne(this._moduleName,`got reference report for probe ${this._probeId}`),r()}catch(a){n(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==fs.RUNNING||!this._config.pc)return Ne(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const r=Date.now(),n=await this._config.pc.getStats(),o=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-r,this._exporter.addReport(o),Ne(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(r){return bn(this._moduleName,`got error ${r}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=fs.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=fs.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=fs.RUNNING,Ne(this._moduleName,"unmuted")}async stop(r){if(Ne(this._moduleName,`stopping${r?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=fs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Ne(this._moduleName,"stopped")}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(this._moduleName,`registered callback '${r}'`)):bn(this._moduleName,`can't register callback for '${r}' - not found`)}unregisterCallback(r){r in this._callbacks?(this._callbacks[r]=null,delete this._callbacks[r],Ne(this._moduleName,`unregistered callback '${r}'`)):bn(this._moduleName,`can't unregister callback for '${r}' - not found`)}fireOnReport(r){this._callbacks.onreport&&Za(this._callbacks.onreport.callback,this._callbacks.onreport.context,r)}fireOnTicket(r){this._callbacks.onticket&&Za(this._callbacks.onticket.callback,this._callbacks.onticket.context,r)}updateConfig(r){this._config=r,this._exporter.updateConfig(r)}get state(){return this._state}set state(r){this._state=r,Ne(this._moduleName,`state changed to ${r}`)}addCustomEvent(r,n,o,a){this._exporter.addCustomEvent({at:typeof r=="object"?r.toJSON():r,category:n,name:o,description:a})}async registerToPCEvents(){const{pc:r}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{bn(this._moduleName,"can't get devices")}},r){r.oniceconnectionstatechange=()=>{const o=r.iceConnectionState;o===qr.CONNECTED||o===qr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===qr.DISCONNECTED||o===qr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===qr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},r.onicegatheringstatechange=()=>{const o=r.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},r.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},r.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=r.getReceivers();if(n&&n.length>0){const o=n[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Iv{constructor(r){this._id=r.pname&&r.pname.substr(0,12).padEnd(12," ")||ev(),this._moduleName=this._id,Ks(this._moduleName,"probe created"),this._config=r,this._collector=new Rv(this._config,this._id)}set onreport(r){r?this._collector.registerCallback("onreport",r):this._collector.unregisterCallback("onreport")}set onticket(r){r?this._collector.registerCallback("onticket",r):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(r){this._collector.state=r}addCustomEvent(r,n,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,r,o)}get isRunning(){return this._collector.state===fs.RUNNING}get isIdle(){return this._collector.state===fs.IDLE}updateUserId(r){this._config.uid=r,this._collector.updateConfig(this._config)}updateCallId(r){this._config.cid=r,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){eo(this._moduleName,"probe is already running");return}this._collector.start()}stop(r=!1){this.isRunning&&this._collector.stop(r)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const yt="engine ";class bv{constructor(r){this._config=r,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Ks(yt,`configured for probing every ${this._config.refreshEvery}ms`),Ks(yt,`configured for starting after ${this._config.startAfter}ms`),Ks(yt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(yt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(r=>r.isRunning)}get isIdle(){return this._probes.every(r=>r.isIdle)}addNewProbe(r,n){if(!r)throw new Error("undefined peer connection");const o=Qg(r,n,this._config),a=new Iv(o);return this._probes.push(a),Ne(yt,`${this._probes.length} probes registered`),a}removeExistingProbe(r){if(!r)throw new Error("undefined probe");r.state===fs.RUNNING&&r.stop(),this._probes=this._probes.filter(n=>r.id!==n.id)}async start(){const r=()=>{this._probes.forEach(t=>t.start())},n=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=zg(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Ne(yt,`got probe ${p.id}`),await Kf(0)}return t.delta_time_to_measure_probes_ms=Ws(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Ws(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Ws(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Ws(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Ws(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Ws(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Ws(t.probes,"video","total_time_encoded_out"),t};for(Ne(yt,"starting to collect"),r(),Ne(yt,"generating reference reports..."),await n(),Ne(yt,"reference reports generated"),this._startedTime=Date.now();o();)if(Ne(yt,`wait ${this._config.refreshEvery}ms before collecting`),await Kf(this._config.refreshEvery),o()){Ne(yt,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Ne(yt,"collected")}Ne(yt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(r){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};Ks(yt,"stop collecting"),n(r)}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(yt,`registered callback '${r}'`)):bn(yt,`can't register callback for '${r}' - not found`)}unregisterCallback(r){r in this._callbacks?(this._callbacks[r]=null,delete this._callbacks[r],Ne(this._moduleName,`unregistered callback '${r}'`)):bn(this._moduleName,`can't unregister callback for '${r}' - not found`)}fireOnReports(r){this._callbacks.onresult&&r.probes.length>0&&Za(this._callbacks.onresult.callback,this._callbacks.onresult.context,r)}}const wv="interface ";class Ov{constructor(r){this._config=Zg(r),Ks(wv,`welcome to ${this._config.name} version ${this._config.version}`),qg(this._config.verbose||!1),this._engine=new bv(this._config)}setupLogLevel(r){jg(r)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(r,n){return this._engine.addNewProbe(r,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(r){this._engine.removeExistingProbe(r)}set onresult(r){r?this._engine.registerCallback("onresult",r):this._engine.unregisterCallback("onresult")}}const Dv=it,Nv=Gt(),Ct=new Dv("WebSocketInterface");var Uv=class{constructor(r){Ct.debug('new() [url:"%s"]',r),this._url=r,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=Nv.parse(r,"absoluteURI");if(n===-1)throw Ct.warn(`invalid WebSocket URI: ${r}`),new TypeError(`Invalid argument: ${r}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ct.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${r}`);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(r){this._via_transport=r.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ct.debug("connect()"),this.isConnected()){Ct.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ct.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ct.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(r){this._onError(r)}}disconnect(){Ct.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(r){return Ct.debug("send()"),this.isConnected()?(this._ws.send(r),!0):(Ct.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(){Ct.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:r,code:n,reason:o}){Ct.debug(`WebSocket ${this._url} closed`),r===!1&&Ct.debug("WebSocket abrupt disconnection"),this.ondisconnect(!r,n,o)}_onMessage({data:r}){Ct.debug("received WebSocket message"),this.ondata(r)}_onError(r){Ct.warn(`WebSocket ${this._url} error: `,r)}};const eu=tl,Pv=we,kv=as,Mv=ft(),xv=kf,Lv=is(),$v=Ta(),Hv=Gt(),Fv=Uv;gn("JsSIP")("version %s",eu.version);var qv={C:Pv,Exceptions:kv,Utils:Mv,UA:xv,URI:Lv,NameAddrHeader:$v,WebSocketInterface:Fv,Grammar:Hv,debug:gn,get name(){return eu.title},get version(){return eu.version}};const jv=vt(qv),Vv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Jt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Bv=0,no={SELECTED_INPUT_DEVICE:"selectedInputDevice",SELECTED_OUTPUT_DEVICE:"selectedOutputDevice"};class Gv extends Ug{constructor(r,n){const o={...r.configuration,sockets:r.socketInterfaces.map(a=>new jv.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.muted=!1,this.isAutoAnswer=!1,this.isDNDEnabled=!1,this.muteWhenJoinEnabled=!1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.microphoneInputLevelValue=2,this.speakerVolumeValue=1,this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.originalStreamValue=null,this.isReconnecting=!1,this.listenersList={},this.options=r,n&&Hg(n)&&(this.logger=n)}on(r,n){return super.on(r,n)}off(r,n){return super.off(r,n)}emit(r,n){return super.emit(r,n)}get sipDomain(){return this.options.sipDomain}get sipOptions(){return{...this.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(r){this.currentActiveRoomIdValue=r,this.emit("currentActiveRoomChanged",r)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(r){this.isCallAddingInProgress=r,this.emit("callAddingInProgressChanged",r)}get isMSRPInitializing(){return this.isMSRPInitializingValue}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}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 getActiveMessages(){return this.activeMessages}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(r=>r.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(r=>r.kind==="audiooutput")}get getUserMediaConstraints(){return{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get getInputDefaultDevice(){return this.getInputDeviceList.find(r=>r.deviceId==="default")}get getOutputDefaultDevice(){return this.getOutputDeviceList.find(r=>r.deviceId==="default")}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get originalStream(){return this.originalStreamValue}setAvailableMediaDevices(r){this.availableMediaDevices=r,this.emit("changeAvailableDeviceList",r)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const r=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(r)}async setMediaDevices(r=!1){var t,s;this.selectedMediaDevices.input=localStorage.getItem(no.SELECTED_INPUT_DEVICE)||"default",this.selectedMediaDevices.output=localStorage.getItem(no.SELECTED_OUTPUT_DEVICE)||"default",await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n);const o=r&&((t=this.getInputDefaultDevice)==null?void 0:t.deviceId)||"",a=r&&((s=this.getOutputDefaultDevice)==null?void 0:s.deviceId)||"";await this.setMicrophone(o),await this.setSpeaker(a),navigator.mediaDevices.ondevicechange=async()=>{await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const p=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(p)}}setCallTime(r){const n={...r};delete n.callId,this.callTime={...this.callTime,[r.callId]:n},this.emit("changeCallTime",this.callTime)}removeCallTime(r){const n={...this.callTime};delete n[r],this.callTime={...n},this.emit("changeCallTime",this.callTime)}setTimeInterval(r,n){this.timeIntervals={...this.timeIntervals,[r]:n}}removeTimeInterval(r){const n={...this.timeIntervals};clearInterval(n[r]),delete n[r],this.timeIntervals={...n}}stopCallTimer(r){this.removeTimeInterval(r),this.removeCallTime(r)}setMetricsConfig(r){this.metricConfig={...this.metricConfig,...r}}sendDTMF(r,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[r].sendDTMF(n)}setIsMuted(r){this.muted=r,this.emit("changeIsMuted",r)}doMute(r){const n=this.currentActiveRoomId;this.setIsMuted(r),this.roomReconfigure(n)}doCallHold({callId:r,toHold:n,automatic:o}){const a=this.extendedCalls[r];a._automaticHold=o??!1,n?a.hold():a.unhold()}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(r=>r.direction==="outgoing"&&r.status===Bv).forEach(r=>this.callTerminate(r._id))}callAnswer(r){const n=this.extendedCalls[r];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setCurrentActiveRoomId(n.roomId),n.connection.addEventListener("addstream",async o=>{this.triggerAddStream(o,n)})}msrpAnswer(r){const n=this.extendedMessages[r];n.answer(this.sipOptions),this.updateMSRPSession(n)}async callMove(r,n){this.updateCallStatus({callId:r,isMoving:!0}),await this.callChangeRoom({callId:r,roomId:n}),this.updateCallStatus({callId:r,isMoving:!1})}updateCall(r){this.activeCalls[r._id]=$f(r),this.emit("changeActiveCalls",this.activeCalls)}updateMSRPSession(r){this.activeMessages[r._id]=Hf(r),this.emit("changeActiveMessages",this.activeMessages)}updateRoom(r){const o={...this.activeRooms[r.roomId],...r};this.activeRooms={...this.activeRooms,[r.roomId]:{...o}},this.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(r){const n=/answer-after=0/,a=r.request.getHeader("Call-Info");return a&&n.test(a)}_addCall(r,n=!0){this.activeCalls={...this.activeCalls,[r._id]:$f(r)},this.extendedCalls[r._id]=r,n&&this.emit("changeActiveCalls",this.activeCalls)}addCallStatus(r){this.callStatus={...this.callStatus,[r]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.emit("changeCallStatus",this.callStatus)}addMMSRPSession(r){this.activeMessages={...this.activeMessages,[r._id]:Hf(r)},this.extendedMessages[r._id]=r,this.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(r,n){const o=this.msrpHistory[n.id]||[];o.push(r),this.msrpHistory={...this.msrpHistory,[n.id]:[...o]},this.emit("newMSRPMessage",{message:r,session:n})}updateCallStatus(r){const o={...{...this.callStatus[r.callId]}};r.isMoving!==void 0&&(o.isMoving=r.isMoving),r.isTransferring!==void 0&&(o.isTransferring=r.isTransferring),r.isMerging!==void 0&&(o.isMerging=r.isMerging),this.callStatus={...this.callStatus,[r.callId]:{...o}},this.emit("changeCallStatus",this.callStatus)}removeCallStatus(r){const n={...this.callStatus};delete n[r],this.callStatus={...n},this.emit("changeCallStatus",this.callStatus)}addRoom(r){this.activeRooms={...this.activeRooms,[r.roomId]:r},this.emit("addRoom",{room:r,roomList:this.activeRooms})}async setMicrophone(r){if(!this.getInputDeviceList.find(({deviceId:a})=>a===r))return;this.setSelectedInputDevice(r);let n;try{n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)}catch(a){console.error(a)}if(Object.keys(this.getActiveCalls).length===0)return;const o=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?Object.values(o).forEach(a=>{const t=Zl(n,this.microphoneInputLevel);t.getTracks().forEach(s=>s.enabled=!this.isMuted),this.setOriginalStream(t),a.connection.getSenders()[0].replaceTrack(t.getTracks()[0]),this.updateCall(a)}):await this.doConference(o)}setOriginalStream(r){this.originalStreamValue=r,this.emit("changeOriginalStream",r)}async setSpeaker(r){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===r))return;this.setSelectedOutputDevice(r);const n=Object.values(this.extendedCalls);if(n.length===0)return;const o=n.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?n.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(r),this.updateCall(a)}):await this.doConference(o)}removeRoom(r){const n={...this.activeRooms},o={...n[r]};delete n[r],this.activeRooms={...n},this.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(r){r!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===r).length===0&&(this.removeRoom(r),this.currentActiveRoomId===r&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(r){this.muted?r.mute({audio:!0}):r.unmute({audio:!0})}async roomReconfigure(r){if(r===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===r);if(this.currentActiveRoomId===r?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(r);else if(n.length===1&&this.currentActiveRoomId!==r)n[0].isOnHold().local||this.doCallHold({callId:n[0].id,toHold:!0,automatic:!0});else if(n.length===1&&this.currentActiveRoomId===r){n[0].isOnHold().local&&n[0]._automaticHold&&this.doCallHold({callId:n[0].id,toHold:!1});let o;try{o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)}catch(a){console.error(a)}if(o&&n[0].connection&&n[0].connection.getSenders()[0]){const a=Zl(o,this.microphoneInputLevel);a.getTracks().forEach(t=>t.enabled=!this.muted),this.setOriginalStream(a),await n[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(r){r.forEach(t=>{t._localHold&&this.doCallHold({callId:t._id,toHold:!1})});const n=[];r.forEach(t=>{t!=null&&t.connection.getReceivers().forEach(s=>{n.push(s.track)})});const o=new AudioContext,a=new MediaStream;await Pg.forEach(r,async t=>{if(t==null)return;const s=o.createMediaStreamDestination();if(t.connection.getReceivers().forEach(p=>{n.forEach(_=>{a.addTrack(p.track),p.track.id!==_.id&&o.createMediaStreamSource(new MediaStream([_])).connect(s)})}),r[0].roomId===this.currentActiveRoomId){const p=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),_=Zl(p,this.microphoneInputLevel);_.getTracks().forEach(g=>g.enabled=!this.isMuted),this.setOriginalStream(_),o.createMediaStreamSource(_).connect(s)}t.connection.getSenders()[0]&&(await t.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(t))})}muteCaller(r,n){const o=this.extendedCalls[r];o&&o.connection.getReceivers().length&&(o.localMuted=n,o.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(o),this.roomReconfigure(o.roomId))}callTerminate(r){const n=this.extendedCalls[r];n._status!==8&&n.terminate()}messageTerminate(r){const n=this.extendedMessages[r];n._status!==8&&n.terminate()}callTransfer(r,n){if(n.toString().length===0)return console.error("Target must be passed");const o=this.extendedCalls[r];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${n}@${this.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:r,isTransferring:!0}),o.refer(`sip:${n}@${this.sipDomain}`),this.updateCall(o)}callMerge(r){const n=Object.values(this.extendedCalls).filter(t=>t.roomId===r);if(n.length!==2)return;const o=n[0],a=n[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(r){this.isDNDEnabled=r,this.emit("changeIsDND",r)}startCallTimer(r){const n={callId:r,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const o=setInterval(()=>{const a={...this.callTime[r]},t=kg(a);this.setCallTime({callId:r,...t})},1e3);this.setTimeInterval(r,o)}async setCurrentActiveRoomId(r){const n=this.currentActiveRoomId;r!==n&&(this.currentActiveRoomId=r,await this.roomReconfigure(n),await this.roomReconfigure(r))}getNewRoomId(){const r=Object.keys(this.activeRooms);return r.length===0?1:parseInt(r.sort()[r.length-1])+1}subscribe(r,n){const a=!this.listenersList[r]||!this.listenersList[r].length?[n]:[...this.listenersList[r],n];this.listenersList={...this.listenersList,[r]:a}}removeIListener(r){const n={...this.listenersList};delete n[r],this.listenersList={...n}}async addCall(r){var d,g;const n=r.session;if(this.getActiveCalls[n.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};n.direction==="incoming"?(this.logger.log("New incoming call from",(g=(d=n._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.subscribe(Jt.CALL_CONFIRMED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(n.id))}),this.subscribe(Jt.CALL_FAILED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):n.direction==="outgoing"&&this.startCallTimer(n.id);const s=n,p=this.hasAutoAnswerHeaders(r),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this._addCall(s,!1):this._addCall(s),this.addCallStatus(n.id),this.addRoom(t),_&&this.callAnswer(s._id)}addMessageSession(r){if(!r._id||this.getActiveMessages[r._id]!==void 0)return;const o=r;this.addMMSRPSession(o)}triggerListener({listenerType:r,session:n,event:o}){const a=this.listenersList[r];!a||!a.length||a.forEach(t=>{t(n,o)})}triggerMSRPListener({listenerType:r,session:n,event:o}){const a=this.listenersList[r];!a||!a.length||a.forEach(t=>{t(n,o)})}removeCall(r){const n={...this.activeCalls};delete n[r],this.activeCalls={...n};const o={...this.extendedCalls};delete o[r],this.extendedCalls={...o},this.emit("changeActiveCalls",this.activeCalls)}removeMMSRPSession(r){const n={...this.activeMessages};delete n[r],this.activeMessages={...n};const o={...this.extendedMessages};delete o[r],this.extendedMessages={...o},this.emit("changeActiveMessages",this.activeMessages)}activeCallListRemove(r){const n=this.extendedCalls[r._id].roomId;this.removeCall(r._id),this.roomReconfigure(n)}activeMessageListRemove(r){this.removeMMSRPSession(r._id)}newRTCSessionCallback(r){const n=r.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(n.on("ended",o=>{var t,s;this.logger.log("Session ended for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Jt.CALL_ENDED,session:n,event:o});const a=this.getActiveCalls[n.id];a&&this.activeCallListRemove(a),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||this.setIsMuted(!1)}),n.on("progress",o=>{var a,t;this.logger.log("Session in progress for",(t=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.triggerListener({listenerType:Jt.CALL_PROGRESS,session:n,event:o})}),n.on("failed",o=>{var t,s;this.logger.log("Session failed for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Jt.CALL_FAILED,session:n,event:o}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[n.id];a&&this.activeCallListRemove(a),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||this.setIsMuted(!1)}),n.on("confirmed",o=>{var a,t;this.logger.log("Session confirmed for",(t=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.triggerListener({listenerType:Jt.CALL_CONFIRMED,session:n,event:o}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),this.addCall(r),n.direction==="outgoing"){const o=this.getActiveCalls[n.id].roomId;this.setCurrentActiveRoomId(o)}}newMSRPSessionCallback(r){const n=r.session;n.on("ended",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_CONFIRMED,session:n,event:o}),this.updateMSRPSession(n)}),n.on("newMessage",o=>{this.addMSRPMessage(o,n)}),this.addMessageSession(n)}setInitialized(r){this.initialized=r,this.emit("ready",r)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return 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.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.on(this.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this)),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this.setMediaDevices(!0),this}setMuteWhenJoin(r){this.muteWhenJoinEnabled=r,this.emit("changeMuteWhenJoin",r)}setMicrophoneInputLevel(r){this.microphoneInputLevelValue=r,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(r){this.speakerVolumeValue=r,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=r)})}setAutoAnswer(r){this.isAutoAnswer=r}setSelectedInputDevice(r){localStorage.setItem(no.SELECTED_INPUT_DEVICE,r),this.selectedMediaDevices.input=r,this.emit("changeActiveInputMediaDevice",r)}setSelectedOutputDevice(r){localStorage.setItem(no.SELECTED_OUTPUT_DEVICE,r),this.selectedMediaDevices.output=r,this.emit("changeActiveOutputMediaDevice",r)}setIsMSRPInitializing(r){this.isMSRPInitializingValue=r,this.emit("isMSRPInitializingChanged",r)}setCallMetrics(r){const n={...r};delete n.callId,this.callMetrics={...this.callMetrics,[r.callId]:n},this.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(r){const n={...this.callMetrics};delete n[r],this.callMetrics={...n},this.emit("changeCallMetrics",this.callMetrics)}getCallQuality(r){const n=new Ov(this.metricConfig),o=n.createProbe(r.connection,{cid:r._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=Mg(p,Vv);_.callId=r._id,this.setCallMetrics(n)},this.subscribe(Jt.CALL_ENDED,s=>{s._id===r._id&&n.stopAllProbes()}),n.startAllProbes()}async triggerAddStream(r,n){this.setIsMuted(this.muteWhenJoin);const o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=Zl(o,this.microphoneInputLevel),t=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(s=>s.enabled=!t),this.setOriginalStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),$g(r,n,this.selectedOutputDevice,this.speakerVolume),this.getCallQuality(n),this.updateCall(n)}doCall({target:r,addToCurrentRoom:n}){if(this.checkInitialized(),r.length===0)return console.error("Target must be a valid string");this.logger.log(`Calling sip:${r}@${this.sipDomain}...`);const o=this.call(`sip:${r}@${this.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&this.callChangeRoom({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("addstream",a=>{this.triggerAddStream(a,o)})}initMSRP(r,n,o){if(this.checkInitialized(),r.length===0)return console.error("Target must be a valid string");const a=this.startMSRP(r,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(r,n){const o=this.extendedMessages[r];if(!o)throw new Error(`MSRP session with id ${r} doesn't exist!`);o.sendMSRP(n)}async callChangeRoom({callId:r,roomId:n}){const o=this.extendedCalls[r].roomId;return this.extendedCalls[r].roomId=n,await this.setCurrentActiveRoomId(n),Promise.all([this.roomReconfigure(o),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(n)})}}return Gv});
155
+ `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new nm(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=ye.STATUS_CONFIRMED,this.target_addr=t.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(r={}){console.log("terminate",this);const n=r.cause||Ie.causes.BYE,o=Ss.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===ye.STATUS_TERMINATED)throw new cm.InvalidStateError(this._status);switch(this.status="terminated",this._status){case ye.STATUS_NULL:case ye.STATUS_INVITE_SENT:case ye.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||Ie.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===ye.STATUS_NULL||this._status===ye.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===ye.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=ye.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,Ie.causes.CANCELED);break;case ye.STATUS_WAITING_FOR_ANSWER:case ye.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,Ie.causes.REJECTED);break;case ye.STATUS_WAITING_FOR_ACK:case ye.STATUS_CONFIRMED:if(p=r.reason_phrase||Ie.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===ye.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Nr.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===Ie.ACK&&(this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Nr.C.STATUS_TERMINATED&&(this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,n),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(Ie.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendRequest(r,n){return this._dialog.sendRequest(r,n)}authenticate(r){this.status="auth";let n=new In("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),r&&n.addHeader("Authorization",r.toString());let o=n.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(n.toString())}onmessage(r){console.log("onmessage",r);const n=new In(r.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new Gp(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Ss.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const r=new RTCPeerConnection({iceServers:[]});r.createDataChannel(""),r.createOffer().then(r.setLocalDescription.bind(r)),r.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(o);this.my_ip=a&&a[1],r.onicecandidate=()=>{},this.authenticate(null)}}onerror(r){console.log(r)}_receiveInviteResponse(r){if(console.log("resp0000000000000",r),this._dialog&&r.status_code>=200&&r.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===r.call_id&&this._dialog.id.local_tag===r.from_tag&&this._dialog.id.remote_tag===r.to_tag){this.sendRequest(Ie.ACK);return}else{const n=new Gl(this,r,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(Ie.ACK),this.sendRequest(Ie.BYE);return}if(this._is_canceled){r.status_code>=100&&r.status_code<200?this._request.cancel(this._cancel_reason):r.status_code>=200&&r.status_code<299&&this._acceptAndTerminate(r);return}if(!(this._status!==ye.STATUS_INVITE_SENT&&this._status!==ye.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(r.status_code):this._status=ye.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(r.status_code):{if(!r.to_tag){console.log("1xx response received without to tag");break}if(r.hasHeader("contact")&&!this._createDialog(r,"UAC",!0))break;if(this._status=ye.STATUS_1XX_RECEIVED,!r.body){this._progress("remote",r);break}const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",r)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(r.status_code):{if(console.log("maybe here???"),this._status=ye.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,Ie.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",r,Ie.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(r,"UAC"))break;const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(r,500,o.toString()),console.log("failed 4"),this._failed("local",r,Ie.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(Ie.ACK),this._confirmed("local",null)});break}default:{const n=Ss.sipErrorCause(r.status_code);console.log("failed 5"),this._failed("remote",r,n)}}}sendMSRP(r){const n=new In("");n.method="SEND",n.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",Ss.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=r;let o=n.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(r){let n=r.ident,o=r.getHeader("Message-ID"),a=new In("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=n;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(r){let n=r.ident,o=r.getHeader("Message-ID"),a=new In("");a.method="REPORT",a.addHeader("To-Path",`${r.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=n;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(r){const n={},o=r.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");n[t[0]]=t[1].match('^"(.+)"$')[1]}return n}init_incoming(r,n){let o;const a=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0;if(r.body&&a!=="application/sdp"){r.reply(415);return}if(this._status=ye.STATUS_INVITE_RECEIVED,this._from_tag=r.from_tag,this._id=r.call_id+this._from_tag,this._request=r,this._contact=this._ua.contact.toString(),r.hasHeader("expires")&&(o=r.getHeader("expires")*1e3),r.to_tag=Ss.newTag(),!this._createDialog(r,"UAS",!0)){r.reply(500,"Missing Contact header field");return}r.body?this._late_sdp=!1:this._late_sdp=!0,this._status=ye.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),console.log("failed 6"),this._failed("local",null,Ie.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===ye.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),console.log("failed 7"),this._failed("system",null,Ie.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from,n&&n(this),r.parseSDP(!0),this.target_addr=r.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",r),this._status!==ye.STATUS_TERMINATED&&(r.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(r,n,o){this.emit("_failed",{originator:r,message:n||null,cause:o}),this._close(),this.emit("failed",{originator:r,message:n||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==ye.STATUS_TERMINATED){if(this._status=ye.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(r){console.log("close() | error closing the RTCPeerConnection: %o",r)}for(const r in this._timers)Object.prototype.hasOwnProperty.call(this._timers,r)&&clearTimeout(this._timers[r]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const r in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,r)&&(this._earlyDialogs[r].terminate(),delete this._earlyDialogs[r]);for(const r in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,r)&&delete this._referSubscribers[r];this._ua.destroyMSRPSession(this)}}_createDialog(r,n,o){const a=n==="UAS"?r.to_tag:r.from_tag,t=n==="UAS"?r.from_tag:r.to_tag,s=r.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Gl(this,r,n,Gl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",r,Ie.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=r.from_tag,this._to_tag=r.to_tag,p)return p.update(r,n),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Gl(this,r,n);return _.error?(console.log("failed 9"),this._failed("remote",r,Ie.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(r,n){this._ua.newMSRPSession(this,{originator:r,session:this,request:n})}_progress(r,n){this.emit("progress",{originator:r,response:n||null})}isEnded(){switch(this._status){case ye.STATUS_CANCELED:case ye.STATUS_TERMINATED:return!0;default:return!1}}_accepted(r,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:r,response:n||null})}_confirmed(r,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:r,ack:n||null})}_ended(r,n,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:r,message:n||null,cause:o})}_handleSessionTimersInIncomingResponse(r){if(!this._sessionTimers.enabled)return;let n;r.session_expires&&r.session_expires>=Ie.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=r.session_expires,n=r.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(r){if(console.log("receiveRequest()"),r.method===Ie.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",r,Ie.causes.CANCELED));else switch(r.method){case Ie.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(!r.body){this.terminate({cause:Ie.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:r.body};console.log('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",r)}).catch(a=>{this.terminate({cause:Ie.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",r);break;case Ie.BYE:this._status===ye.STATUS_CONFIRMED||this._status===ye.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,Ie.causes.BYE)):this._status===ye.STATUS_INVITE_RECEIVED||this._status===ye.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,Ie.causes.BYE)):r.reply(403,"Wrong Status");break;case Ie.INVITE:this._status===ye.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case Ie.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?(r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Rm(this).init_incoming(r):r.reply(415):r.reply(403,"Wrong Status");break;case Ie.UPDATE:this._status===ye.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case Ie.REFER:this._status===ye.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case Ie.NOTIFY:this._status===ye.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ie.causes.CONNECTION_ERROR,cause:Ie.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ie.causes.REQUEST_TIMEOUT,cause:Ie.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ie.causes.DIALOG_ERROR,cause:Ie.causes.DIALOG_ERROR})}}const zt=console,xf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Ng=Og;class Ug extends Ng{constructor(r){console.log(r),super(r),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}}}call(r,n){return super.call(r,n)}newMSRPSession(r,n){r.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[r.id]=r,this.emit("newMSRPSession",n)}destroyMSRPSession(r){delete this._msrp_sessions[r.id]}receiveRequest(r){const n=r.method;if(console.log("-----------"),r.ruri.user!==this._configuration.uri.user&&r.ruri.user!==this._contact.uri.user){zt.debug("Request-URI does not point to us"),r.method!==we.ACK&&r.reply_sl(404);return}if(r.ruri.scheme===we.SIPS){r.reply_sl(416);return}if(Nr.checkTransaction(this,r))return;if(n===we.INVITE?new Nr.InviteServerTransaction(this,this._transport,r):n!==we.ACK&&n!==we.CANCEL&&new Nr.NonInviteServerTransaction(this,this._transport,r),n===we.OPTIONS){if(this.listeners("newOptions").length===0){r.reply(200);return}new Kc.Options(this).init_incoming(r)}else if(n===we.MESSAGE){if(this.listeners("newMessage").length===0){r.reply(405);return}new Kc.Message(this).init_incoming(r)}else if(n===we.INVITE&&!r.to_tag&&this.listeners("newRTCSession").length===0){r.reply(405);return}let o,a;if(r.to_tag)o=this._findDialog(r.call_id,r.from_tag,r.to_tag),o?o.receiveRequest(r):n===we.NOTIFY?(a=this._findSession(r),a?a.receiveRequest(r):(zt.debug("received NOTIFY request for a non existent subscription"),r.reply(481,"Subscription does not exist"))):n!==we.ACK&&r.reply(481);else switch(n){case we.INVITE:if(window.RTCPeerConnection)if(r.hasHeader("replaces")){const t=r.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?r.reply(603):a.receiveRequest(r)):r.reply(481)}else r.body.search(/MSRP/ig)>-1?(a=new Mf(this),a.init_incoming(r)):(a=new Hm(this),a.init_incoming(r));else zt.warn("INVITE received but WebRTC is not supported"),r.reply(488);break;case we.BYE:r.reply(481);break;case we.CANCEL:a=this._findSession(r),a?a.receiveRequest(r):zt.debug("received CANCEL request for a non existent session");break;case we.ACK:break;case we.NOTIFY:this.emit("sipEvent",{event:r.event,request:r}),r.reply(200);break;default:r.reply(405);break}}startMSRP(r,n){zt.debug("startMSRP()",n);const o=new Mf(this);return o.connect(r),o}terminateMSRPSessions(r){zt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(r)}stop(){if(zt.debug("stop()"),this._dynConfiguration={},this._status===xf.STATUS_USER_CLOSED){zt.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){zt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){zt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=xf.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}var pt={};pt.forEach=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>r.call(n||globalThis,s,a,c));o.push(t)}await Promise.all(o)},pt.forEachSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)o in c&&await r.call(n||globalThis,await c[o],o,c)},pt.map=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>r.call(n||globalThis,t,a,c)));return Promise.all(o)},pt.mapSeries=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await r.call(n||globalThis,await c[a],a,c));return o},pt.find=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.findSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(await r.call(n||globalThis,await c[o],o,c))return c[o]},pt.findIndex=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.findIndexSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(await r.call(n||globalThis,await c[o],o,c))return o},pt.some=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.someSeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(o in c&&await r.call(n||globalThis,await c[o],o,c))return!0;return!1},pt.every=(c,r,n)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>r.call(n||globalThis,_,s,c)).then(p).catch(a)}}),pt.everySeries=async(c,r,n)=>{for(let o=0;o<c.length;o++)if(o in c&&!await r.call(n||globalThis,await c[o],o,c))return!1;return!0},pt.filter=(c,r,n)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>r.call(n||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),pt.filterSeries=async(c,r,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await r.call(n||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},pt.reduce=async(c,r,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(n!==void 0?(a=n,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await r(await a,await c[o],o,c));return a};var Lf={};(function(c){const r=pt;Object.keys(r).forEach(n=>{const o=n.charAt(0).toUpperCase()+n.slice(1);c[`async${o}`]=async function(...a){return r[n](this,...a)}})})(Lf);var Pg=Object.assign(pt,{instanceMethods:Lf});function za(c){return c<10?`0${c}`:`${c}`}function kg(c){let r=c.hours||0,n=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,n++,n===60&&(n=0,r++));const a=`${za(r)}:${za(n)}:${za(o)}`;return{seconds:o,minutes:n,hours:r,formatted:a}}function Mg(c,r){return Object.keys(c).filter(n=>r.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const xg=["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"],Lg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function $f(c){const r={};return xg.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r.localHold=c._localHold,r}function Hf(c){const r={};return Lg.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r}function Zl(c,r){const n=new AudioContext,o=n.createMediaStreamSource(c),a=n.createMediaStreamDestination(),t=n.createGain();return o.connect(t),t.connect(a),t.gain.value=r,a.stream}function $g(c,r,n,o){const a=document.createElement("audio");a.id=r._id,a.className="audioTag",a.srcObject=c.stream,a.setSinkId(n),a.volume=o,a.play(),r.audioTag=a}function Hg(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}var Fg={exports:{}};(function(c){var r=function(n){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(Q,W,B){Q[W]=B.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function v(Q,W,B){return Object.defineProperty(Q,W,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[W]}try{v({},"")}catch{v=function(W,B,te){return W[B]=te}}function E(Q,W,B,te){var de=W&&W.prototype instanceof ie?W:ie,Ae=Object.create(de.prototype),Ue=new P(te||[]);return t(Ae,"_invoke",{value:Y(Q,B,Ue)}),Ae}n.wrap=E;function S(Q,W,B){try{return{type:"normal",arg:Q.call(W,B)}}catch(te){return{type:"throw",arg:te}}}var C="suspendedStart",I="suspendedYield",w="executing",F="completed",L={};function ie(){}function N(){}function H(){}var ve={};v(ve,_,function(){return this});var me=Object.getPrototypeOf,M=me&&me(me(Z([])));M&&M!==o&&a.call(M,_)&&(ve=M);var D=H.prototype=ie.prototype=Object.create(ve);N.prototype=H,t(D,"constructor",{value:H,configurable:!0}),t(H,"constructor",{value:N,configurable:!0}),N.displayName=v(H,g,"GeneratorFunction");function V(Q){["next","throw","return"].forEach(function(W){v(Q,W,function(B){return this._invoke(W,B)})})}n.isGeneratorFunction=function(Q){var W=typeof Q=="function"&&Q.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(Q){return Object.setPrototypeOf?Object.setPrototypeOf(Q,H):(Q.__proto__=H,v(Q,g,"GeneratorFunction")),Q.prototype=Object.create(D),Q},n.awrap=function(Q){return{__await:Q}};function j(Q,W){function B(Ae,Ue,Se,ne){var Te=S(Q[Ae],Q,Ue);if(Te.type==="throw")ne(Te.arg);else{var tt=Te.arg,st=tt.value;return st&&typeof st=="object"&&a.call(st,"__await")?W.resolve(st.__await).then(function(ge){B("next",ge,Se,ne)},function(ge){B("throw",ge,Se,ne)}):W.resolve(st).then(function(ge){tt.value=ge,Se(tt)},function(ge){return B("throw",ge,Se,ne)})}}var te;function de(Ae,Ue){function Se(){return new W(function(ne,Te){B(Ae,Ue,ne,Te)})}return te=te?te.then(Se,Se):Se()}t(this,"_invoke",{value:de})}V(j.prototype),v(j.prototype,d,function(){return this}),n.AsyncIterator=j,n.async=function(Q,W,B,te,de){de===void 0&&(de=Promise);var Ae=new j(E(Q,W,B,te),de);return n.isGeneratorFunction(W)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function Y(Q,W,B){var te=C;return function(Ae,Ue){if(te===w)throw new Error("Generator is already running");if(te===F){if(Ae==="throw")throw Ue;return et()}for(B.method=Ae,B.arg=Ue;;){var Se=B.delegate;if(Se){var ne=$(Se,B);if(ne){if(ne===L)continue;return ne}}if(B.method==="next")B.sent=B._sent=B.arg;else if(B.method==="throw"){if(te===C)throw te=F,B.arg;B.dispatchException(B.arg)}else B.method==="return"&&B.abrupt("return",B.arg);te=w;var Te=S(Q,W,B);if(Te.type==="normal"){if(te=B.done?F:I,Te.arg===L)continue;return{value:Te.arg,done:B.done}}else Te.type==="throw"&&(te=F,B.method="throw",B.arg=Te.arg)}}}function $(Q,W){var B=W.method,te=Q.iterator[B];if(te===s)return W.delegate=null,B==="throw"&&Q.iterator.return&&(W.method="return",W.arg=s,$(Q,W),W.method==="throw")||B!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+B+"' method")),L;var de=S(te,Q.iterator,W.arg);if(de.type==="throw")return W.method="throw",W.arg=de.arg,W.delegate=null,L;var Ae=de.arg;if(!Ae)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,L;if(Ae.done)W[Q.resultName]=Ae.value,W.next=Q.nextLoc,W.method!=="return"&&(W.method="next",W.arg=s);else return Ae;return W.delegate=null,L}V(D),v(D,g,"Generator"),v(D,_,function(){return this}),v(D,"toString",function(){return"[object Generator]"});function X(Q){var W={tryLoc:Q[0]};1 in Q&&(W.catchLoc=Q[1]),2 in Q&&(W.finallyLoc=Q[2],W.afterLoc=Q[3]),this.tryEntries.push(W)}function U(Q){var W=Q.completion||{};W.type="normal",delete W.arg,Q.completion=W}function P(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(X,this),this.reset(!0)}n.keys=function(Q){var W=Object(Q),B=[];for(var te in W)B.push(te);return B.reverse(),function de(){for(;B.length;){var Ae=B.pop();if(Ae in W)return de.value=Ae,de.done=!1,de}return de.done=!0,de}};function Z(Q){if(Q){var W=Q[_];if(W)return W.call(Q);if(typeof Q.next=="function")return Q;if(!isNaN(Q.length)){var B=-1,te=function de(){for(;++B<Q.length;)if(a.call(Q,B))return de.value=Q[B],de.done=!1,de;return de.value=s,de.done=!0,de};return te.next=te}}return{next:et}}n.values=Z;function et(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(Q){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!Q)for(var W in this)W.charAt(0)==="t"&&a.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=s)},stop:function(){this.done=!0;var Q=this.tryEntries[0],W=Q.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var W=this;function B(ne,Te){return Ae.type="throw",Ae.arg=Q,W.next=ne,Te&&(W.method="next",W.arg=s),!!Te}for(var te=this.tryEntries.length-1;te>=0;--te){var de=this.tryEntries[te],Ae=de.completion;if(de.tryLoc==="root")return B("end");if(de.tryLoc<=this.prev){var Ue=a.call(de,"catchLoc"),Se=a.call(de,"finallyLoc");if(Ue&&Se){if(this.prev<de.catchLoc)return B(de.catchLoc,!0);if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else if(Ue){if(this.prev<de.catchLoc)return B(de.catchLoc,!0)}else if(Se){if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,W){for(var B=this.tryEntries.length-1;B>=0;--B){var te=this.tryEntries[B];if(te.tryLoc<=this.prev&&a.call(te,"finallyLoc")&&this.prev<te.finallyLoc){var de=te;break}}de&&(Q==="break"||Q==="continue")&&de.tryLoc<=W&&W<=de.finallyLoc&&(de=null);var Ae=de?de.completion:{};return Ae.type=Q,Ae.arg=W,de?(this.method="next",this.next=de.finallyLoc,L):this.complete(Ae)},complete:function(Q,W){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"&&W&&(this.next=W),L},finish:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),U(B),L}},catch:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.tryLoc===Q){var te=B.completion;if(te.type==="throw"){var de=te.arg;U(B)}return de}}throw new Error("illegal catch attempt")},delegateYield:function(Q,W,B){return this.delegate={iterator:Z(Q),resultName:W,nextLoc:B},this.method==="next"&&(this.arg=s),L}},n}(c.exports);try{regeneratorRuntime=r}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}})(Fg);var Ff={exports:{}};(function(c){(function(r,n){c.exports?c.exports=n():r.log=n()})(lr,function(){var r=function(){},n="undefined",o=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(I,w){var F=I[w];if(typeof F.bind=="function")return F.bind(I);try{return Function.prototype.bind.call(F,I)}catch{return function(){return Function.prototype.apply.apply(F,[I,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(I){return I==="debug"&&(I="log"),typeof console===n?!1:I==="trace"&&o?s:console[I]!==void 0?t(console,I):console.log!==void 0?t(console,"log"):r}function _(I,w){for(var F=0;F<a.length;F++){var L=a[F];this[L]=F<I?r:this.methodFactory(L,I,w)}this.log=this.debug}function d(I,w,F){return function(){typeof console!==n&&(_.call(this,w,F),this[I].apply(this,arguments))}}function g(I,w,F){return p(I)||d.apply(this,arguments)}function v(I,w,F){var L=this,ie;w=w??"WARN";var N="loglevel";typeof I=="string"?N+=":"+I:typeof I=="symbol"&&(N=void 0);function H(D){var V=(a[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=V;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+V+";"}catch{}}}function ve(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var V=window.document.cookie,j=V.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(V.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function me(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=I,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=F||g,L.getLevel=function(){return ie},L.setLevel=function(D,V){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ie=D,V!==!1&&H(D),_.call(L,D,I),typeof console===n&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){w=D,ve()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(w,!1),me()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=ve();M==null&&(M=w),L.setLevel(M,!1)}var E=new v,S={};E.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var F=S[w];return F||(F=S[w]=new v(w,E.getLevel(),E.methodFactory)),F};var C=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=C),E},E.getLoggers=function(){return S},E.default=E,E})})(Ff);var Et=Ff.exports;const us=()=>`${new Date().toISOString()} | metrics`,cs=(c,r,n)=>`${c} | ${r} | ${n}`;Et.setDefaultLevel(Et.levels.TRACE);const qg=c=>{Et.info(cs(us(),"log ",`set log level to ${c?"verbose":"info"}`)),Et.setLevel(c?Et.levels.TRACE:Et.levels.INFO)},jg=c=>{const r=[...Object.keys(Et.levels)];r.includes(c)?(Et.info(cs(us(),"log ",`update log level to ${c.toLowerCase()}`)),Et.setLevel(c)):Et.warn(cs(us(),"log ","Incorrect log level please choose one of "),r)},Ne=(c,r,n)=>{n?Et.debug(cs(us(),c,r),n):Et.debug(cs(us(),c,r))},Ja=(c,r)=>{Et.info(cs(us(),c,r))},Ks=(c,r)=>{Et.info(cs(us(),c,r))},eo=(c,r)=>{Et.warn(cs(us(),c,r))},bn=(c,r)=>{Et.error(cs(us(),c,r))};function Vg(c){return Math.floor(Math.random()*c).toString()}function qf(c,r){let n=r;return c.forEach(o=>{n=n.replace(o,"")}),n}function Bg(c,r){let n="";for(let o=0;o<r;o+=1)n+=c[Vg(c.length)];return n}function Gg({length:c=20,useLetters:r=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return r&&(a.length&&(t=qf(a,t)),_=t.split("")),n&&(a.length&&(s=qf(a,s)),d=s.split("")),p=[..._,...d,...o],Bg(p,c)}var Kg=Gg;const Fr=vt(Kg),Wg=()=>"WebRTCMetrics",Yg=()=>"5.0.3",ke={INBOUND:"inbound",OUTBOUND:"outbound"},fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},qr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},zg=()=>({...{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:[]}}),jf={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:ke.INBOUND},Vf={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:ke.OUTBOUND},Bf={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:ke.INBOUND},Gf={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:ke.OUTBOUND},Jg=c=>{const r={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(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{n.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{n.video[o]={...c.video[o]}}),n}return{...r,audio:{},video:{},data:{...r.data},network:{...r.network},experimental:{...r.experimental}}},Xg={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Fr()}`,cid:`c-${Fr()}`,uid:`u-${Fr()}`,record:!1,ticket:!0},Ft={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"},k={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},jr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Xa={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ee={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Qa="config ",Qg=(c,r={},n)=>{const o={...n,...r};return r.pname||eo(Qa,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),r.cid||eo(Qa,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),r.uid||eo(Qa,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},Zg=(c={})=>{const r={...Xg,...c};return r.name=Wg(),r.version=Yg(),r},Vr=(c,r,n,o=!1,a)=>{let t=c.map(s=>{if(!n)return s[r];if(!a)return s[r][n];const p=s[r][a];return p?p[n]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},Cs=c=>c.reduce((r,n)=>r+n,0)/c.length,ev=()=>`probe-${Fr()}`,tv=()=>`coltr-${Fr()}`,Kf=c=>new Promise(r=>setTimeout(r,c)),Za=(c,r,n)=>{r?c.call(r,n):c(n)},je=(c,r,n,o)=>{const a=Vr(c,r,n,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},We=(c,r,n,o=!1,a)=>{const t=Vr(c,r,n,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Ws=(c,r,n)=>Vr(c,r,n).reduce((a,t)=>a+t,0),Ve=(c,r,n,o)=>{const a=Vr(c,r,n,!0,o);return a.length===0?null:Math.min(...a)},Be=(c,r,n,o)=>{const a=Vr(c,r,n,!1,o);return a.length===0?null:Math.max(...a)},mt=(c,r,n,o)=>{const a=c.slice().pop();if(!a)return null;if(!n)return a[r];if(!o)return a[r][n];const t=a[r][o];return t?t[n]:null},sv=c=>c.slice().pop(),lt=(c,r,n)=>{if(!r)return null;const o={};let a=r[k.AUDIO][c];a||(a=n===ke.INBOUND?{...jf}:{...Vf}),o[k.AUDIO]=a;let t=r[k.VIDEO][c];return t||(t=n===ke.INBOUND?{...Bf}:{...Gf}),o[k.VIDEO]=t,o},Br="exporter ",nv="2.0",Wf=(c,r,n)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[r][n];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?We(c,r,"delta_rtt_ms_out",!1,n):Number(t/s)}return null},rv=(c,r)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const o=n[r].total_rtt_connectivity_ms,a=n[r].total_rtt_connectivity_measure;return!a||!o?We(c,r,"delta_rtt_connectivity_ms"):Number(o/a)},iv=c=>mt(c,"network","local_candidate_type")!=="relay"?`direct/${mt(c,"network","local_candidate_protocol")}`:`turn/${mt(c,"network","local_candidate_relay_protocol")}`,lv=c=>{const r=mt(c,"network","remote_candidate_type"),n=mt(c,"network","remote_candidate_protocol");return r!=="relay"?`direct/${n}`:`turn/${n}`};class ov{constructor(r){this._start=null,this._end=null,this._cfg=r,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ja(Br,"start() - start exporter...");const r=new Date;return this._start=r.toJSON(),r}stop(){Ja(Br,"stop() - stop exporter...");const r=new Date;return this._end=r.toJSON(),r}saveReferenceReport(r){this._referenceReport=r}getReferenceReport(){return this._referenceReport}addReport(r){this._cfg.ticket&&(Ne(Br,`addReport() - add report to exporter at ${r.timestamp}`),this._reports.push(r))}addCustomEvent(r){this._events.push(r)}reset(){Ja(Br,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(Br,"ticket() - generate ticket");const r=mt(this._reports,"audio","total_packets_lost_in"),n=mt(this._reports,"audio","total_packets_in"),o=mt(this._reports,"video","total_packets_lost_in"),a=mt(this._reports,"video","total_packets_in"),t={},s=sv(this._reports);return s&&(Object.keys(s[k.AUDIO]).forEach(p=>{const _=s[k.AUDIO][p];if(t[_.ssrc]={type:k.AUDIO,direction:_.direction},_.direction===ke.INBOUND){const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_jitter_ms_in",p),max:Be(this._reports,k.AUDIO,"delta_jitter_ms_in",p),volatility:je(this._reports,k.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.AUDIO,"delta_kbs_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_kbs_in",p),max:Be(this._reports,k.AUDIO,"delta_kbs_in",p),volatility:je(this._reports,k.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.AUDIO,"delta_KBytes_in",!1,p),min:Ve(this._reports,k.AUDIO,"delta_KBytes_in",p),max:Be(this._reports,k.AUDIO,"delta_KBytes_in",p),volatility:je(this._reports,k.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:We(this._reports,k.AUDIO,"mos_emodel_in",!1,p),min:Ve(this._reports,k.AUDIO,"mos_emodel_in",p),max:Be(this._reports,k.AUDIO,"mos_emodel_in",p),volatility:je(this._reports,k.AUDIO,"mos_emodel_in",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_in",!1,p),min:Ve(this._reports,k.AUDIO,"mos_in",p),max:Be(this._reports,k.AUDIO,"mos_in",p),volatility:je(this._reports,k.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},S=mt(this._reports,k.AUDIO,"total_packets_lost_in",p),C=mt(this._reports,k.AUDIO,"total_packets_in",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I}else{const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_jitter_ms_out",p),max:Be(this._reports,k.AUDIO,"delta_jitter_ms_out",p),volatility:je(this._reports,k.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.AUDIO,"delta_kbs_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_kbs_out",p),max:Be(this._reports,k.AUDIO,"delta_kbs_out",p),volatility:je(this._reports,k.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.AUDIO,"delta_KBytes_out",!1,p),min:Ve(this._reports,k.AUDIO,"delta_KBytes_out",p),max:Be(this._reports,k.AUDIO,"delta_KBytes_out",p),volatility:je(this._reports,k.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Wf(this._reports,k.AUDIO,p),min:Ve(this._reports,k.AUDIO,"delta_rtt_ms_out",p),max:Be(this._reports,k.AUDIO,"delta_rtt_ms_out",p),volatility:je(this._reports,k.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=mt(this._reports,k.AUDIO,"total_packets_lost_out",p),C=mt(this._reports,k.AUDIO,"total_packets_out",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},w={emodel:{avg:We(this._reports,k.AUDIO,"mos_emodel_out",!1,p),min:Ve(this._reports,k.AUDIO,"mos_emodel_out",p),max:Be(this._reports,k.AUDIO,"mos_emodel_out",p),volatility:je(this._reports,k.AUDIO,"mos_emodel_out",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_out",!1,p),min:Ve(this._reports,k.AUDIO,"mos_out",p),max:Be(this._reports,k.AUDIO,"mos_out",p),volatility:je(this._reports,k.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I,t[p].mos=w}}),Object.keys(s[k.VIDEO]).forEach(p=>{const _=s[k.VIDEO][p];if(t[p]={type:k.VIDEO,direction:_.direction},_.direction===ke.INBOUND){const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_jitter_ms_in",p),max:Be(this._reports,k.VIDEO,"delta_jitter_ms_in",p),volatility:je(this._reports,k.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.VIDEO,"delta_kbs_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_kbs_in",p),max:Be(this._reports,k.VIDEO,"delta_kbs_in",p),volatility:je(this._reports,k.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.VIDEO,"delta_KBytes_in",!1,p),min:Ve(this._reports,k.VIDEO,"delta_KBytes_in",p),max:Be(this._reports,k.VIDEO,"delta_KBytes_in",p),volatility:je(this._reports,k.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=mt(this._reports,k.VIDEO,"total_packets_lost_in",p),S=mt(this._reports,k.VIDEO,"total_packets_in",p),C={lost:E,avg:Math.round((E/(E+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=v,t[p].bitrate=g,t[p].loss=C}else{const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_jitter_ms_out",p),max:Be(this._reports,k.VIDEO,"delta_jitter_ms_out",p),volatility:je(this._reports,k.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:We(this._reports,k.VIDEO,"delta_kbs_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_kbs_out",p),max:Be(this._reports,k.VIDEO,"delta_kbs_out",p),volatility:je(this._reports,k.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:We(this._reports,k.VIDEO,"delta_KBytes_out",!1,p),min:Ve(this._reports,k.VIDEO,"delta_KBytes_out",p),max:Be(this._reports,k.VIDEO,"delta_KBytes_out",p),volatility:je(this._reports,k.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Wf(this._reports,k.VIDEO,p),min:Ve(this._reports,k.VIDEO,"delta_rtt_ms_out",p),max:Be(this._reports,k.VIDEO,"delta_rtt_ms_out",p),volatility:je(this._reports,k.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=mt(this._reports,k.VIDEO,"total_packets_lost_out",p),C=mt(this._reports,k.VIDEO,"total_packets_out",p),I={lost:S,avg:Math.round((S/(S+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=v,t[p].bitrate=g,t[p].loss=I}})),{version:nv,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:t,data:{rtt:{avg:rv(this._reports,"data"),min:Ve(this._reports,"data","delta_rtt_connectivity_ms"),max:Be(this._reports,"data","delta_rtt_connectivity_ms"),volatility:je(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((r/(r+n)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:We(this._reports,"data","delta_kbs_in"),min:Ve(this._reports,"data","delta_kbs_in"),max:Be(this._reports,"data","delta_kbs_in"),volatility:je(this._reports,"data","delta_kbs_in")},out:{avg:We(this._reports,"data","delta_kbs_out"),min:Ve(this._reports,"data","delta_kbs_out"),max:Be(this._reports,"data","delta_kbs_out"),volatility:je(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:We(this._reports,"data","delta_KBytes_in"),min:Ve(this._reports,"data","delta_KBytes_in"),max:Be(this._reports,"data","delta_KBytes_in"),volatility:je(this._reports,"data","delta_KBytes_in")},out:{avg:We(this._reports,"data","delta_KBytes_out"),min:Ve(this._reports,"data","delta_KBytes_out"),max:Be(this._reports,"data","delta_KBytes_out"),volatility:je(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:iv(this._reports),remoteConnection:lv(this._reports)}}}}updateConfig(r){this._cfg=r}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const r=this._reports.slice();return r.pop(),r.pop()||null}getReportsNumber(){return this._reports.length}}const As="extractor ",Yf=(c,r,n,o)=>{let a=!1;const t=o[r].total_rtt_ms_out,s=o[r].total_rtt_measure_out,p=n?n[r].total_rtt_ms_out:0,_=n?n[r].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[q.TIMESTAMP]===o[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let v=t+g,E=s+1;return a&&(v=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:v,totalRTTMeasurements:E}},av=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[r].total_rtt_connectivity_ms,totalRTTMeasurements:o[r].total_rtt_connectivity_measure};const a=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let t=o[r].total_rtt_connectivity_ms+a,s=o[r].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[r].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(s=Number(c[q.RESPONSES_RECEIVED])-(n?n[r].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},to=(c,r,n)=>c[q.TIMESTAMP]===n[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),uv=(c,r)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:r[k.VIDEO].delta_ms_decode_frame_in,frames_decoded:r[k.VIDEO].total_frames_decoded_in,total_decode_time:r[k.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],o=c[q.TOTAL_DECODE_TIME],a=o-r[k.VIDEO].total_time_decoded_in,t=n-r[k.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:n,total_decode_time:o}},cv=(c,r)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:r[k.VIDEO].delta_ms_encode_frame_out,frames_encoded:r[k.VIDEO].total_frames_encoded_out,total_encode_time:r[k.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],o=c[q.TOTAL_ENCODE_TIME],a=o-r[k.VIDEO].total_time_encoded_out,t=n-r[k.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:n,total_encode_time:o}},zf=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[r].total_packets_out,packetsLost:n[r].total_packets_lost_out,bytesSent:n[r].total_KBytes_out};const a=Number(c[q.PACKETS_SENT])||0-(o?o[r].total_packets_out:0),t=a-n[r].total_packets_out,s=Number(c[q.BYTES_SENT])/1024-(o?o[r].total_KBytes_out:0),p=s-n[r].total_KBytes_out,_=c[q.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=n.timestamp;!g&&d&&(g=d);const v=g?_-g:0,E=v>0?p*.008*1024/v*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},Jf=(c,r,n,o)=>{let a=n[r].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(a=Number(c[q.PACKETS_LOST])||0-(o?o[r].total_packets_lost_out:0),t=a-n[r].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(s=Number(100*c[q.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},Xf=(c,r,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[r].percent_packets_lost_in,packetsReceived:n[r].total_packets_in,packetsLost:n[r].total_packets_lost_in,bytesReceived:n[r].total_KBytes_in};const a=Number(c[q.PACKETS_RECEIVED])||0-(o?o[r].total_packets_in:0),t=Number(c[q.PACKETS_LOST])||0-(o?o[r].total_packets_lost_in:0),s=t-n[r].total_packets_lost_in,p=a-n[r].total_packets_in,_=a!==n[r].total_packets_in?s*100/(s+p):0,d=Number(c[q.BYTES_RECEIVED])/1024-(o?o[r].total_KBytes_in:0),g=d-n[r].total_KBytes_in,v=c[q.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let S=n.timestamp;!S&&E&&(S=E);const C=S?v-S:0,I=C>0?g*.008*1024/C*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:I}},fv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",_v=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return jr.WIFI;switch(c[q.NETWORK_TYPE]){case Xa.ETHERNET:return jr.ETHERNET;case Xa.CELLULAR_4G:return jr.CELLULAR_4G;case Xa.WIFI:return jr.WIFI;default:return jr.CELLULAR}},Qf=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},hv=c=>{const r=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:r,durations:o,resolutionChanges:n}},dv=(c,r,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:r.total_pli_sent_in,nackCount:r.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[q.PLI]||0)-(n?n[k.VIDEO].total_pli_sent_in:0),a=(c[q.NACK]||0)-(n?n[k.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-r[k.VIDEO].total_pli_sent_in,deltaNackCount:a-r[k.VIDEO].total_nack_sent_in}},pv=(c,r,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:r.total_pli_received_out,nackCount:r.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[q.PLI]||0)-(n?n[k.VIDEO].total_pli_received_out:0),a=(c[q.NACK]||0)-(n?n[k.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-r[k.VIDEO].total_pli_received_out,deltaNackCount:a-r[k.VIDEO].total_nack_received_out}},mv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),gv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),vv=(c,r,n)=>{const o=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),t=c[q.TIMESTAMP]||Date.now(),s=o-r.data.total_KBytes_in,p=a-r.data.total_KBytes_out,_=n?n.timestamp:null;let d=r.timestamp;!d&&_&&(d=_);const g=d?t-d:0,v=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:v,kbs_speed_sent:E}},Tv=c=>{const r=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:r,kbs_outgoing_bandwidth:n}},Ev=(c,r,n,o)=>{if(!c)return[];switch(c[q.TYPE]){case Ft.CANDIDATE_PAIR:let a=!1;if(c[q.NOMINATED]&&c[q.STATE]===k.SUCCEEDED&&(a=!0,Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(a=!1)),a){const s=c[q.LOCAL_CANDIDATE_ID],p=c[q.REMOTE_CANDIDATE_ID],_=vv(c,r,o),d=Tv(c),g=av(c,"data",o,r);return[{type:ee.NETWORK,value:{local_candidate_id:s}},{type:ee.NETWORK,value:{remote_candidate_id:p}},{type:ee.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ee.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ee.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ee.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ee.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ee.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ee.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ee.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ee.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ee.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ee.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Ft.LOCAL_CANDIDATE:if(c[q.ID]===r.network.local_candidate_id)return[{type:ee.NETWORK,value:{infrastructure:_v(c)}},{type:ee.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ee.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ee.NETWORK,value:{local_candidate_relay_protocol:fv(c)}}];break;case Ft.REMOTE_CANDIDATE:if(c[q.ID]===r.network.remote_candidate_id)return[{type:ee.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ee.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case Ft.INBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.INBOUND);p&&(p.timestamp=r.timestamp);const _=lt(s,o,ke.INBOUND);if(_&&(_.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=Xf(c,k.AUDIO,p,_),g=to(c,k.AUDIO,p),v=c[q.CODEC_ID]||"";return[{ssrc:s,type:ee.AUDIO,value:{codec_id_in:v}},{ssrc:s,type:ee.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ee.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ee.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===k.VIDEO){const d=uv(c,p),g=Xf(c,k.VIDEO,p,_),v=to(c,k.VIDEO,p),E=c[q.DECODER_IMPLEMENTATION]||null,S=c[q.CODEC_ID]||null,C=Qf(c),I=dv(c,p,_);return[{ssrc:s,type:ee.VIDEO,value:{codec_id_in:S}},{ssrc:s,type:ee.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ee.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ee.VIDEO,value:{delta_jitter_ms_in:v}},{ssrc:s,type:ee.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ee.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ee.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ee.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ee.VIDEO,value:{total_nack_sent_in:I.nackCount}},{ssrc:s,type:ee.VIDEO,value:{delta_nack_sent_in:I.deltaNackCount}},{ssrc:s,type:ee.VIDEO,value:{total_pli_sent_in:I.pliCount}},{ssrc:s,type:ee.VIDEO,value:{delta_pli_sent_in:I.deltaPliCount}},{ssrc:s,type:ee.VIDEO,value:{size_in:C}}]}break}case Ft.OUTBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.OUTBOUND);p&&(p.timestamp=r.timestamp);const _=lt(s,o,ke.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=c[q.CODEC_ID]||null,g=zf(c,k.AUDIO,p,_);return[{ssrc:s,type:ee.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ee.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ee.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ee.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ee.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===k.VIDEO){const d=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,v=cv(c,p),E=Qf(c),S=hv(c),C=pv(c,p,_),I=zf(c,k.VIDEO,p,_);return[{ssrc:s,type:ee.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ee.VIDEO,value:{total_packets_out:I.packetsSent}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_out:I.deltaPacketsSent}},{ssrc:s,type:ee.VIDEO,value:{total_KBytes_out:I.KBytesSent}},{ssrc:s,type:ee.VIDEO,value:{delta_KBytes_out:I.deltaKBytesSent}},{ssrc:s,type:ee.VIDEO,value:{delta_kbs_out:I.kbsSent}},{ssrc:s,type:ee.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ee.VIDEO,value:{delta_ms_encode_frame_out:v.delta_ms_encode_frame}},{ssrc:s,type:ee.VIDEO,value:{total_frames_encoded_out:v.frames_encoded}},{ssrc:s,type:ee.VIDEO,value:{total_time_encoded_out:v.total_encode_time}},{ssrc:s,type:ee.VIDEO,value:{total_nack_received_out:C.nackCount}},{ssrc:s,type:ee.VIDEO,value:{delta_nack_received_out:C.deltaNackCount}},{ssrc:s,type:ee.VIDEO,value:{total_pli_received_out:C.pliCount}},{ssrc:s,type:ee.VIDEO,value:{delta_pli_received_out:C.deltaPliCount}},{ssrc:s,type:ee.VIDEO,value:{size_out:E}},{ssrc:s,type:ee.VIDEO,value:{limitation_out:S}}]}break}case Ft.MEDIA_SOURCE:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Ft.TRACK:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Ft.CODEC:const t=[];return Object.keys(r[k.AUDIO]).forEach(s=>{const p=r[k.AUDIO][s];if(p.codec_id_in===c[q.ID]||p.codec_id_out===c[q.ID]){Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const _=mv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_out:_}})}}),Object.keys(r[k.VIDEO]).forEach(s=>{const p=r[k.VIDEO][s];if(p.codec_id_in===c[q.ID]||p.codec_id_out===c[q.ID]){Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const _=gv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_out:_}})}}),t;case Ft.REMOTE_INBOUND_RTP:{Ne(As,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=lt(s,r,ke.OUTBOUND),_=lt(s,o,ke.OUTBOUND);if(c[q.KIND]===k.AUDIO){const d=Yf(c,k.AUDIO,_,p),g=to(c,k.AUDIO,p),v=Jf(c,k.AUDIO,p,_);return[{ssrc:s,type:ee.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ee.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ee.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ee.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ee.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:s,type:ee.AUDIO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:s,type:ee.AUDIO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:s,type:ee.AUDIO,value:{percent_packets_lost_out:v.fractionLost}}]}if(c[q.KIND]===k.VIDEO){const d=Yf(c,k.VIDEO,_,p),g=to(c,k.VIDEO,p),v=Jf(c,k.VIDEO,p,_);return[{ssrc:s,type:ee.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ee.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ee.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ee.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ee.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:s,type:ee.VIDEO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:s,type:ee.VIDEO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:s,type:ee.VIDEO,value:{percent_packets_lost_out:v.fractionLost}}]}break}}return[]},so=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),yv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.INBOUND),s=lt(a,n,ke.INBOUND),p=lt(a,o,ke.INBOUND),_=[],d=[],g=t[r].percent_packets_lost_in,v=t[r].delta_jitter_ms_in,E=s&&s[r].delta_jitter_ms_in||null,S=p&&p[r].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,I=n&&n.data.delta_rtt_connectivity_ms||null,w=o&&o.data.delta_rtt_connectivity_ms||null;C&&_.push(C),I&&_.push(I),w&&_.push(w),v&&d.push(v),n&&E&&d.push(E),o&&S&&d.push(S);const F=_.length>0?Cs(_):100,L=d.length>0?Cs(d):10,ie=93.2-g,N=.18*ie*ie-27.9*ie+1126.62,H=(F+L)/2,ve=H-177.3<0?0:1,me=.024*H+.11*(H-177.3)*ve,M=N-me;return so(M)},Sv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.OUTBOUND),s=lt(a,n,ke.OUTBOUND),p=lt(a,o,ke.OUTBOUND),_=[],d=[],g=t[r].percent_packets_lost_out,v=t[r].delta_rtt_ms_out,E=s&&s[r].delta_rtt_ms_out||null,S=p&&p[r].delta_rtt_ms_out||null,C=t[r].delta_jitter_ms_out,I=s&&s[r].delta_jitter_ms_out||null,w=p&&p[r].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,L=n&&n.data.delta_rtt_connectivity_ms||null,ie=o&&o.data.delta_rtt_connectivity_ms||null;v?_.push(v):F&&_.push(F),E?_.push(E):L&&_.push(L),S?_.push(S):ie&&_.push(ie),C&&d.push(C),n&&I&&d.push(I),o&&w&&d.push(w);const N=_.length>0?Cs(_):100,H=d.length>0?Cs(d):10,ve=93.2-g,me=.18*ve*ve-27.9*ve+1126.62,M=(N+H)/2,D=M-177.3<0?0:1,V=.024*M+.11*(M-177.3)*D,j=me-V;return so(j)},Cv=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.INBOUND),s=lt(a,n,ke.INBOUND),p=lt(a,o,ke.INBOUND),_=[],d=[],g=t[r].percent_packets_lost_in/100,v=t[r].delta_jitter_ms_in,E=s&&s[r].delta_jitter_ms_in||null,S=p&&p[r].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,I=n&&n.data.delta_rtt_connectivity_ms||null,w=o&&o.data.delta_rtt_connectivity_ms||null;C&&_.push(C),I&&_.push(I),w&&_.push(w),v&&d.push(v),s&&E&&d.push(E),p&&S&&d.push(S);const F=_.length>0?Cs(_):100,L=d.length>0?Cs(d):10,ie=0,N=19.8,H=29.7,ve=30,me=(F+L)/2+ve,M=me-177.3<0?0:1,D=.024*me+.11*(me-177.3)*M,j=93.2-(ie+N*Math.log(1+H*g)+D);return so(j)},Av=(c,r=k.AUDIO,n,o,a)=>{const t=lt(a,c,ke.OUTBOUND),s=lt(a,n,ke.OUTBOUND),p=lt(a,o,ke.OUTBOUND),_=[],d=[],g=t[r].percent_packets_lost_out/100,v=t[r].delta_rtt_ms_out,E=s&&s[r].delta_rtt_ms_out||null,S=p&&p[r].delta_rtt_ms_out||null,C=t[r].delta_jitter_ms_out,I=s&&s[r].delta_jitter_ms_out||null,w=p&&p[r].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,L=n&&n.data.delta_rtt_connectivity_ms||null,ie=o&&o.data.delta_rtt_connectivity_ms||null;v?_.push(v):F&&_.push(F),E?_.push(E):L&&_.push(L),S?_.push(S):ie&&_.push(ie),C&&d.push(C),s&&I&&d.push(I),p&&w&&d.push(w);const N=_.length>0?Cs(_):100,H=d.length>0?Cs(d):10,ve=0,me=19.8,M=29.7,D=30,V=(N+H)/2+D,j=V-177.3<0?0:1,Y=.024*V+.11*(V-177.3)*j,X=93.2-(ve+me*Math.log(1+M*g)+Y);return so(X)};class Rv{constructor(r,n){this._callbacks={onreport:null,onticket:null},this._id=tv(),this._moduleName=this._id,this._probeId=n,this._config=r,this._exporter=new ov(r),this._state=fs.IDLE,this.registerToPCEvents(),Ks(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(r,n,o,a){const t=(_,d)=>_===k.AUDIO?d===Ft.INBOUND_RTP?{...jf}:{...Vf}:d===Ft.INBOUND_RTP?{...Bf}:{...Gf},s=Jg(n);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=n?n.count+1:1;let p=null;return r.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),Ev(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let v=s[g.type][g.ssrc];v||(v=t(g.type,_.type),v.ssrc=g.ssrc,s[g.type][g.ssrc]=v),Object.keys(g.value).forEach(E=>{v[E]=g.value[E]})}else Object.keys(g.value).forEach(v=>{s[g.type][v]=g.value[v]})})}),s.timestamp=p,Object.keys(s[k.AUDIO]).forEach(_=>{const d=s[k.AUDIO][_];d.direction===ke.INBOUND?(d.mos_emodel_in=yv(s,k.AUDIO,n,o,d.ssrc),d.mos_in=Cv(s,k.AUDIO,n,o,d.ssrc)):(d.mos_emodel_out=Sv(s,k.AUDIO,n,o,d.ssrc),d.mos_out=Av(s,k.AUDIO,n,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((r,n)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Ne(this._moduleName,`got reference report for probe ${this._probeId}`),r()}catch(a){n(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==fs.RUNNING||!this._config.pc)return Ne(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const r=Date.now(),n=await this._config.pc.getStats(),o=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-r,this._exporter.addReport(o),Ne(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(r){return bn(this._moduleName,`got error ${r}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=fs.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=fs.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=fs.RUNNING,Ne(this._moduleName,"unmuted")}async stop(r){if(Ne(this._moduleName,`stopping${r?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=fs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Ne(this._moduleName,"stopped")}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(this._moduleName,`registered callback '${r}'`)):bn(this._moduleName,`can't register callback for '${r}' - not found`)}unregisterCallback(r){r in this._callbacks?(this._callbacks[r]=null,delete this._callbacks[r],Ne(this._moduleName,`unregistered callback '${r}'`)):bn(this._moduleName,`can't unregister callback for '${r}' - not found`)}fireOnReport(r){this._callbacks.onreport&&Za(this._callbacks.onreport.callback,this._callbacks.onreport.context,r)}fireOnTicket(r){this._callbacks.onticket&&Za(this._callbacks.onticket.callback,this._callbacks.onticket.context,r)}updateConfig(r){this._config=r,this._exporter.updateConfig(r)}get state(){return this._state}set state(r){this._state=r,Ne(this._moduleName,`state changed to ${r}`)}addCustomEvent(r,n,o,a){this._exporter.addCustomEvent({at:typeof r=="object"?r.toJSON():r,category:n,name:o,description:a})}async registerToPCEvents(){const{pc:r}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{bn(this._moduleName,"can't get devices")}},r){r.oniceconnectionstatechange=()=>{const o=r.iceConnectionState;o===qr.CONNECTED||o===qr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===qr.DISCONNECTED||o===qr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===qr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},r.onicegatheringstatechange=()=>{const o=r.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},r.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},r.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=r.getReceivers();if(n&&n.length>0){const o=n[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Iv{constructor(r){this._id=r.pname&&r.pname.substr(0,12).padEnd(12," ")||ev(),this._moduleName=this._id,Ks(this._moduleName,"probe created"),this._config=r,this._collector=new Rv(this._config,this._id)}set onreport(r){r?this._collector.registerCallback("onreport",r):this._collector.unregisterCallback("onreport")}set onticket(r){r?this._collector.registerCallback("onticket",r):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(r){this._collector.state=r}addCustomEvent(r,n,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,r,o)}get isRunning(){return this._collector.state===fs.RUNNING}get isIdle(){return this._collector.state===fs.IDLE}updateUserId(r){this._config.uid=r,this._collector.updateConfig(this._config)}updateCallId(r){this._config.cid=r,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){eo(this._moduleName,"probe is already running");return}this._collector.start()}stop(r=!1){this.isRunning&&this._collector.stop(r)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const yt="engine ";class bv{constructor(r){this._config=r,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Ks(yt,`configured for probing every ${this._config.refreshEvery}ms`),Ks(yt,`configured for starting after ${this._config.startAfter}ms`),Ks(yt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(yt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(r=>r.isRunning)}get isIdle(){return this._probes.every(r=>r.isIdle)}addNewProbe(r,n){if(!r)throw new Error("undefined peer connection");const o=Qg(r,n,this._config),a=new Iv(o);return this._probes.push(a),Ne(yt,`${this._probes.length} probes registered`),a}removeExistingProbe(r){if(!r)throw new Error("undefined probe");r.state===fs.RUNNING&&r.stop(),this._probes=this._probes.filter(n=>r.id!==n.id)}async start(){const r=()=>{this._probes.forEach(t=>t.start())},n=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=zg(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Ne(yt,`got probe ${p.id}`),await Kf(0)}return t.delta_time_to_measure_probes_ms=Ws(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Ws(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Ws(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Ws(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Ws(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Ws(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Ws(t.probes,"video","total_time_encoded_out"),t};for(Ne(yt,"starting to collect"),r(),Ne(yt,"generating reference reports..."),await n(),Ne(yt,"reference reports generated"),this._startedTime=Date.now();o();)if(Ne(yt,`wait ${this._config.refreshEvery}ms before collecting`),await Kf(this._config.refreshEvery),o()){Ne(yt,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Ne(yt,"collected")}Ne(yt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(r){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};Ks(yt,"stop collecting"),n(r)}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(yt,`registered callback '${r}'`)):bn(yt,`can't register callback for '${r}' - not found`)}unregisterCallback(r){r in this._callbacks?(this._callbacks[r]=null,delete this._callbacks[r],Ne(this._moduleName,`unregistered callback '${r}'`)):bn(this._moduleName,`can't unregister callback for '${r}' - not found`)}fireOnReports(r){this._callbacks.onresult&&r.probes.length>0&&Za(this._callbacks.onresult.callback,this._callbacks.onresult.context,r)}}const wv="interface ";class Ov{constructor(r){this._config=Zg(r),Ks(wv,`welcome to ${this._config.name} version ${this._config.version}`),qg(this._config.verbose||!1),this._engine=new bv(this._config)}setupLogLevel(r){jg(r)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(r,n){return this._engine.addNewProbe(r,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(r){this._engine.removeExistingProbe(r)}set onresult(r){r?this._engine.registerCallback("onresult",r):this._engine.unregisterCallback("onresult")}}const Dv=it,Nv=Gt(),Ct=new Dv("WebSocketInterface");var Uv=class{constructor(r){Ct.debug('new() [url:"%s"]',r),this._url=r,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=Nv.parse(r,"absoluteURI");if(n===-1)throw Ct.warn(`invalid WebSocket URI: ${r}`),new TypeError(`Invalid argument: ${r}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ct.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${r}`);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(r){this._via_transport=r.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ct.debug("connect()"),this.isConnected()){Ct.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ct.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ct.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(r){this._onError(r)}}disconnect(){Ct.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(r){return Ct.debug("send()"),this.isConnected()?(this._ws.send(r),!0):(Ct.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(){Ct.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:r,code:n,reason:o}){Ct.debug(`WebSocket ${this._url} closed`),r===!1&&Ct.debug("WebSocket abrupt disconnection"),this.ondisconnect(!r,n,o)}_onMessage({data:r}){Ct.debug("received WebSocket message"),this.ondata(r)}_onError(r){Ct.warn(`WebSocket ${this._url} error: `,r)}};const eu=tl,Pv=we,kv=as,Mv=ft(),xv=kf,Lv=is(),$v=Ta(),Hv=Gt(),Fv=Uv;gn("JsSIP")("version %s",eu.version);var qv={C:Pv,Exceptions:kv,Utils:Mv,UA:xv,URI:Lv,NameAddrHeader:$v,WebSocketInterface:Fv,Grammar:Hv,debug:gn,get name(){return eu.title},get version(){return eu.version}};const jv=vt(qv),Vv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Jt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Bv=0,no={SELECTED_INPUT_DEVICE:"selectedInputDevice",SELECTED_OUTPUT_DEVICE:"selectedOutputDevice"};class Gv extends Ug{constructor(r,n){const o={...r.configuration,sockets:r.socketInterfaces.map(a=>new jv.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.muted=!1,this.isAutoAnswer=!1,this.isDNDEnabled=!1,this.muteWhenJoinEnabled=!1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.microphoneInputLevelValue=2,this.speakerVolumeValue=1,this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.originalStreamValue=null,this.isReconnecting=!1,this.listenersList={},this.options=r,n&&Hg(n)&&(this.logger=n)}on(r,n){return super.on(r,n)}off(r,n){return super.off(r,n)}emit(r,n){return super.emit(r,n)}get sipDomain(){return this.options.sipDomain}get sipOptions(){return{...this.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(r){this.currentActiveRoomIdValue=r,this.emit("currentActiveRoomChanged",r)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(r){this.isCallAddingInProgress=r,this.emit("callAddingInProgressChanged",r)}get isMSRPInitializing(){return this.isMSRPInitializingValue}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}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 getActiveMessages(){return this.activeMessages}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(r=>r.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(r=>r.kind==="audiooutput")}get getUserMediaConstraints(){return{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get getInputDefaultDevice(){return this.getInputDeviceList.find(r=>r.deviceId==="default")}get getOutputDefaultDevice(){return this.getOutputDeviceList.find(r=>r.deviceId==="default")}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get originalStream(){return this.originalStreamValue}setAvailableMediaDevices(r){this.availableMediaDevices=r,this.emit("changeAvailableDeviceList",r)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const r=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(r)}async setMediaDevices(r=!1){var t,s;this.selectedMediaDevices.input=localStorage.getItem(no.SELECTED_INPUT_DEVICE)||"default",this.selectedMediaDevices.output=localStorage.getItem(no.SELECTED_OUTPUT_DEVICE)||"default",await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n);const o=r&&((t=this.getInputDefaultDevice)==null?void 0:t.deviceId)||"",a=r&&((s=this.getOutputDefaultDevice)==null?void 0:s.deviceId)||"";await this.setMicrophone(o),await this.setSpeaker(a),navigator.mediaDevices.ondevicechange=async()=>{await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const p=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(p)}}setCallTime(r){const n={...r};delete n.callId,this.callTime={...this.callTime,[r.callId]:n},this.emit("changeCallTime",this.callTime)}removeCallTime(r){const n={...this.callTime};delete n[r],this.callTime={...n},this.emit("changeCallTime",this.callTime)}setTimeInterval(r,n){this.timeIntervals={...this.timeIntervals,[r]:n}}removeTimeInterval(r){const n={...this.timeIntervals};clearInterval(n[r]),delete n[r],this.timeIntervals={...n}}stopCallTimer(r){this.removeTimeInterval(r),this.removeCallTime(r)}setMetricsConfig(r){this.metricConfig={...this.metricConfig,...r}}sendDTMF(r,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[r].sendDTMF(n)}setIsMuted(r){this.muted=r,this.emit("changeIsMuted",r)}doMute(r){const n=this.currentActiveRoomId;this.setIsMuted(r),this.roomReconfigure(n)}doCallHold({callId:r,toHold:n,automatic:o}){const a=this.extendedCalls[r];a._automaticHold=o??!1,n?a.hold():a.unhold(),this.updateCall(a)}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(r=>r.direction==="outgoing"&&r.status===Bv).forEach(r=>this.callTerminate(r._id))}callAnswer(r){const n=this.extendedCalls[r];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setCurrentActiveRoomId(n.roomId),n.connection.addEventListener("addstream",async o=>{this.triggerAddStream(o,n)})}msrpAnswer(r){const n=this.extendedMessages[r];n.answer(this.sipOptions),this.updateMSRPSession(n)}async callMove(r,n){this.updateCallStatus({callId:r,isMoving:!0}),await this.callChangeRoom({callId:r,roomId:n}),this.updateCallStatus({callId:r,isMoving:!1})}updateCall(r){this.activeCalls[r._id]=$f(r),this.emit("changeActiveCalls",this.activeCalls)}updateMSRPSession(r){this.activeMessages[r._id]=Hf(r),this.emit("changeActiveMessages",this.activeMessages)}updateRoom(r){const o={...this.activeRooms[r.roomId],...r};this.activeRooms={...this.activeRooms,[r.roomId]:{...o}},this.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(r){const n=/answer-after=0/,a=r.request.getHeader("Call-Info");return a&&n.test(a)}_addCall(r,n=!0){this.activeCalls={...this.activeCalls,[r._id]:$f(r)},this.extendedCalls[r._id]=r,n&&this.emit("changeActiveCalls",this.activeCalls)}addCallStatus(r){this.callStatus={...this.callStatus,[r]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.emit("changeCallStatus",this.callStatus)}addMMSRPSession(r){this.activeMessages={...this.activeMessages,[r._id]:Hf(r)},this.extendedMessages[r._id]=r,this.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(r,n){const o=this.msrpHistory[n.id]||[];o.push(r),this.msrpHistory={...this.msrpHistory,[n.id]:[...o]},this.emit("newMSRPMessage",{message:r,session:n})}updateCallStatus(r){const o={...{...this.callStatus[r.callId]}};r.isMoving!==void 0&&(o.isMoving=r.isMoving),r.isTransferring!==void 0&&(o.isTransferring=r.isTransferring),r.isMerging!==void 0&&(o.isMerging=r.isMerging),this.callStatus={...this.callStatus,[r.callId]:{...o}},this.emit("changeCallStatus",this.callStatus)}removeCallStatus(r){const n={...this.callStatus};delete n[r],this.callStatus={...n},this.emit("changeCallStatus",this.callStatus)}addRoom(r){this.activeRooms={...this.activeRooms,[r.roomId]:r},this.emit("addRoom",{room:r,roomList:this.activeRooms})}async setMicrophone(r){if(!this.getInputDeviceList.find(({deviceId:a})=>a===r))return;this.setSelectedInputDevice(r);let n;try{n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)}catch(a){console.error(a)}if(Object.keys(this.getActiveCalls).length===0)return;const o=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?Object.values(o).forEach(a=>{const t=Zl(n,this.microphoneInputLevel);t.getTracks().forEach(s=>s.enabled=!this.isMuted),this.setOriginalStream(t),a.connection.getSenders()[0].replaceTrack(t.getTracks()[0]),this.updateCall(a)}):await this.doConference(o)}setOriginalStream(r){this.originalStreamValue=r,this.emit("changeOriginalStream",r)}async setSpeaker(r){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===r))return;this.setSelectedOutputDevice(r);const n=Object.values(this.extendedCalls);if(n.length===0)return;const o=n.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?n.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(r),this.updateCall(a)}):await this.doConference(o)}removeRoom(r){const n={...this.activeRooms},o={...n[r]};delete n[r],this.activeRooms={...n},this.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(r){r!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===r).length===0&&(this.removeRoom(r),this.currentActiveRoomId===r&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(r){this.muted?r.mute({audio:!0}):r.unmute({audio:!0})}async roomReconfigure(r){if(r===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===r);if(this.currentActiveRoomId===r?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(r);else if(n.length===1&&this.currentActiveRoomId!==r)n[0].isOnHold().local||this.doCallHold({callId:n[0].id,toHold:!0,automatic:!0});else if(n.length===1&&this.currentActiveRoomId===r){n[0].isOnHold().local&&n[0]._automaticHold&&this.doCallHold({callId:n[0].id,toHold:!1});let o;try{o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)}catch(a){console.error(a)}if(o&&n[0].connection&&n[0].connection.getSenders()[0]){const a=Zl(o,this.microphoneInputLevel);a.getTracks().forEach(t=>t.enabled=!this.muted),this.setOriginalStream(a),await n[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(r){r.forEach(t=>{t._localHold&&this.doCallHold({callId:t._id,toHold:!1})});const n=[];r.forEach(t=>{t!=null&&t.connection.getReceivers().forEach(s=>{n.push(s.track)})});const o=new AudioContext,a=new MediaStream;await Pg.forEach(r,async t=>{if(t==null)return;const s=o.createMediaStreamDestination();if(t.connection.getReceivers().forEach(p=>{n.forEach(_=>{a.addTrack(p.track),p.track.id!==_.id&&o.createMediaStreamSource(new MediaStream([_])).connect(s)})}),r[0].roomId===this.currentActiveRoomId){const p=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),_=Zl(p,this.microphoneInputLevel);_.getTracks().forEach(g=>g.enabled=!this.isMuted),this.setOriginalStream(_),o.createMediaStreamSource(_).connect(s)}t.connection.getSenders()[0]&&(await t.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(t))})}muteCaller(r,n){const o=this.extendedCalls[r];o&&o.connection.getReceivers().length&&(o.localMuted=n,o.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(o),this.roomReconfigure(o.roomId))}callTerminate(r){const n=this.extendedCalls[r];n._status!==8&&n.terminate()}messageTerminate(r){const n=this.extendedMessages[r];n._status!==8&&n.terminate()}callTransfer(r,n){if(n.toString().length===0)return console.error("Target must be passed");const o=this.extendedCalls[r];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${n}@${this.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:r,isTransferring:!0}),o.refer(`sip:${n}@${this.sipDomain}`),this.updateCall(o)}callMerge(r){const n=Object.values(this.extendedCalls).filter(t=>t.roomId===r);if(n.length!==2)return;const o=n[0],a=n[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(r){this.isDNDEnabled=r,this.emit("changeIsDND",r)}startCallTimer(r){const n={callId:r,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const o=setInterval(()=>{const a={...this.callTime[r]},t=kg(a);this.setCallTime({callId:r,...t})},1e3);this.setTimeInterval(r,o)}async setCurrentActiveRoomId(r){const n=this.currentActiveRoomId;r!==n&&(this.currentActiveRoomId=r,await this.roomReconfigure(n),await this.roomReconfigure(r))}getNewRoomId(){const r=Object.keys(this.activeRooms);return r.length===0?1:parseInt(r.sort()[r.length-1])+1}subscribe(r,n){const a=!this.listenersList[r]||!this.listenersList[r].length?[n]:[...this.listenersList[r],n];this.listenersList={...this.listenersList,[r]:a}}removeIListener(r){const n={...this.listenersList};delete n[r],this.listenersList={...n}}async addCall(r){var d,g;const n=r.session;if(this.getActiveCalls[n.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};n.direction==="incoming"?(this.logger.log("New incoming call from",(g=(d=n._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.subscribe(Jt.CALL_CONFIRMED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(n.id))}),this.subscribe(Jt.CALL_FAILED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):n.direction==="outgoing"&&this.startCallTimer(n.id);const s=n,p=this.hasAutoAnswerHeaders(r),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this._addCall(s,!1):this._addCall(s),this.addCallStatus(n.id),this.addRoom(t),_&&this.callAnswer(s._id)}addMessageSession(r){if(!r._id||this.getActiveMessages[r._id]!==void 0)return;const o=r;this.addMMSRPSession(o)}triggerListener({listenerType:r,session:n,event:o}){const a=this.listenersList[r];!a||!a.length||a.forEach(t=>{t(n,o)})}triggerMSRPListener({listenerType:r,session:n,event:o}){const a=this.listenersList[r];!a||!a.length||a.forEach(t=>{t(n,o)})}removeCall(r){const n={...this.activeCalls};delete n[r],this.activeCalls={...n};const o={...this.extendedCalls};delete o[r],this.extendedCalls={...o},this.emit("changeActiveCalls",this.activeCalls)}removeMMSRPSession(r){const n={...this.activeMessages};delete n[r],this.activeMessages={...n};const o={...this.extendedMessages};delete o[r],this.extendedMessages={...o},this.emit("changeActiveMessages",this.activeMessages)}activeCallListRemove(r){const n=this.extendedCalls[r._id].roomId;this.removeCall(r._id),this.roomReconfigure(n)}activeMessageListRemove(r){this.removeMMSRPSession(r._id)}async newRTCSessionCallback(r){const n=r.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(n.on("ended",o=>{var t,s;this.logger.log("Session ended for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Jt.CALL_ENDED,session:n,event:o});const a=this.getActiveCalls[n.id];a&&this.activeCallListRemove(a),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||this.setIsMuted(!1)}),n.on("progress",o=>{var a,t;this.logger.log("Session in progress for",(t=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.triggerListener({listenerType:Jt.CALL_PROGRESS,session:n,event:o})}),n.on("failed",o=>{var t,s;this.logger.log("Session failed for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Jt.CALL_FAILED,session:n,event:o}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[n.id];a&&this.activeCallListRemove(a),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||this.setIsMuted(!1)}),n.on("confirmed",o=>{var a,t;this.logger.log("Session confirmed for",(t=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.triggerListener({listenerType:Jt.CALL_CONFIRMED,session:n,event:o}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.addCall(r),n.direction==="outgoing"){const o=this.getActiveCalls[n.id].roomId;this.setCurrentActiveRoomId(o)}}newMSRPSessionCallback(r){const n=r.session;n.on("ended",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Jt.CALL_CONFIRMED,session:n,event:o}),this.updateMSRPSession(n)}),n.on("newMessage",o=>{this.addMSRPMessage(o,n)}),this.addMessageSession(n)}setInitialized(r){this.initialized=r,this.emit("ready",r)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return 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.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.on(this.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this)),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this.setMediaDevices(!0),this}setMuteWhenJoin(r){this.muteWhenJoinEnabled=r,this.emit("changeMuteWhenJoin",r)}setMicrophoneInputLevel(r){this.microphoneInputLevelValue=r,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(r){this.speakerVolumeValue=r,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=r,this.updateCall(n))})}setAutoAnswer(r){this.isAutoAnswer=r}setSelectedInputDevice(r){localStorage.setItem(no.SELECTED_INPUT_DEVICE,r),this.selectedMediaDevices.input=r,this.emit("changeActiveInputMediaDevice",r)}setSelectedOutputDevice(r){localStorage.setItem(no.SELECTED_OUTPUT_DEVICE,r),this.selectedMediaDevices.output=r,this.emit("changeActiveOutputMediaDevice",r)}setIsMSRPInitializing(r){this.isMSRPInitializingValue=r,this.emit("isMSRPInitializingChanged",r)}setCallMetrics(r){const n={...r};delete n.callId,this.callMetrics={...this.callMetrics,[r.callId]:n},this.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(r){const n={...this.callMetrics};delete n[r],this.callMetrics={...n},this.emit("changeCallMetrics",this.callMetrics)}getCallQuality(r){const n=new Ov(this.metricConfig),o=n.createProbe(r.connection,{cid:r._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=Mg(p,Vv);_.callId=r._id,this.setCallMetrics(n)},this.subscribe(Jt.CALL_ENDED,s=>{s._id===r._id&&n.stopAllProbes()}),n.startAllProbes()}async triggerAddStream(r,n){this.setIsMuted(this.muteWhenJoin);const o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=Zl(o,this.microphoneInputLevel),t=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(s=>s.enabled=!t),this.setOriginalStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),$g(r,n,this.selectedOutputDevice,this.speakerVolume),this.getCallQuality(n),this.updateCall(n)}doCall({target:r,addToCurrentRoom:n}){if(this.checkInitialized(),r.length===0)return console.error("Target must be a valid string");this.logger.log(`Calling sip:${r}@${this.sipDomain}...`);const o=this.call(`sip:${r}@${this.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&this.callChangeRoom({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("addstream",a=>{this.triggerAddStream(a,o)})}initMSRP(r,n,o){if(this.checkInitialized(),r.length===0)return console.error("Target must be a valid string");const a=this.startMSRP(r,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(r,n){const o=this.extendedMessages[r];if(!o)throw new Error(`MSRP session with id ${r} doesn't exist!`);o.sendMSRP(n)}async callChangeRoom({callId:r,roomId:n}){const o=this.extendedCalls[r].roomId;this.extendedCalls[r].roomId=n;const a=this.extendedCalls[r];return this.updateCall(a),await this.setCurrentActiveRoomId(n),Promise.all([this.roomReconfigure(o),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(n)})}}return Gv});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicenter-team/opensips-js",
3
- "version": "1.0.45",
3
+ "version": "1.0.46",
4
4
  "description": "The JS package for opensips",
5
5
  "default": "src/index.ts",
6
6
  "jsdelivr": "dist/opensips-js.umd.js",