@voicenter-team/opensips-js 1.0.76 → 1.0.77

Sign up to get free protection for your applications and to get access to all the features.
@@ -47,7 +47,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
47
47
  `);h+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest($_.INFO,{extraHeaders:p,eventHandlers:{onSuccessResponse:function(g){t.emit("succeeded",{originator:"remote",response:g})},onErrorResponse:function(g){t.eventHandlers.onFailed&&t.eventHandlers.onFailed(),t.emit("failed",{originator:"remote",response:g})},onRequestTimeout:function(){t._session.onRequestTimeout()},onTransportError:function(){t._session.onTransportError()},onDialogError:function(){t._session.onDialogError()}},body:h})}},{key:"init_incoming",value:function(a){var t=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,s=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=a,a.reply(200),a.body){var p=a.body.split(`
48
48
  `);p.length>=1&&t.test(p[0])&&(this._tone=p[0].replace(t,"$2")),p.length>=2&&s.test(p[1])&&(this._duration=parseInt(p[1].replace(s,"$2"),10))}this._duration||(this._duration=Nf.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:a}):F_.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),n}(x_);iu.exports.C=Nf;var q_=iu.exports;function eo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?eo=function(n){return typeof n}:eo=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},eo(c)}function V_(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function Wu(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function j_(c,r,n){return r&&Wu(c.prototype,r),n&&Wu(c,n),c}function B_(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&qa(c,r)}function qa(c,r){return qa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},qa(c,r)}function G_(c){var r=Y_();return function(){var o=fo(c),a;if(r){var t=fo(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return K_(this,a)}}function K_(c,r){return r&&(eo(r)==="object"||typeof r=="function")?r:W_(c)}function W_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Y_(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function fo(c){return fo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},fo(c)}var z_=pt.EventEmitter,J_=tt,X_=xs,Q_=Et(),Z_=function(c){B_(n,c);var r=G_(n);function n(o){var a;return V_(this,n),a=r.call(this),a._session=o,a._direction=null,a._contentType=null,a._body=null,a}return j_(n,[{key:"send",value:function(a,t){var s=this,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this._direction="outgoing",a===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new X_.InvalidStateError(this._session.status);this._contentType=a,this._body=t;var h=Q_.cloneArray(p.extraHeaders);h.push("Content-Type: ".concat(a)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(J_.INFO,{extraHeaders:h,eventHandlers:{onSuccessResponse:function(g){s.emit("succeeded",{originator:"remote",response:g})},onErrorResponse:function(g){s.emit("failed",{originator:"remote",response:g})},onTransportError:function(){s._session.onTransportError()},onRequestTimeout:function(){s._session.onRequestTimeout()},onDialogError:function(){s._session.onDialogError()}},body:t})}},{key:"init_incoming",value:function(a){this._direction="incoming",this.request=a,a.reply(200),this._contentType=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,this._body=a.body,this._session.newInfo({originator:"remote",info:this,request:a})}},{key:"contentType",get:function(){return this._contentType}},{key:"body",get:function(){return this._body}}]),n}(z_);function ed(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function Yu(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function td(c,r,n){return r&&Yu(c.prototype,r),n&&Yu(c,n),c}var sd=it,zu=tt,nd=new sd("RTCSession:ReferNotifier"),ta={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},rd=function(){function c(r,n,o){ed(this,c),this._session=r,this._id=n,this._expires=o||ta.expires,this._active=!0,this.notify(100)}return td(c,[{key:"notify",value:function(n,o){if(nd.debug("notify()"),this._active!==!1){o=o||zu.REASON_PHRASE[n]||"";var a;n>=200?a="terminated;reason=noresource":a="active;expires=".concat(this._expires),this._session.sendRequest(zu.NOTIFY,{extraHeaders:["Event: ".concat(ta.event_type,";id=").concat(this._id),"Subscription-State: ".concat(a),"Content-Type: ".concat(ta.body_type)],body:"SIP/2.0 ".concat(n," ").concat(o),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),c}();function to(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?to=function(n){return typeof n}:to=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},to(c)}function id(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function Ju(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function ld(c,r,n){return r&&Ju(c.prototype,r),n&&Ju(c,n),c}function od(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&Va(c,r)}function Va(c,r){return Va=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Va(c,r)}function ad(c){var r=fd();return function(){var o=ho(c),a;if(r){var t=ho(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return ud(this,a)}}function ud(c,r){return r&&(to(r)==="object"||typeof r=="function")?r:cd(c)}function cd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function fd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function ho(c){return ho=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},ho(c)}var hd=pt.EventEmitter,_d=it,Ei=tt,dd=Zt(),Xu=Et(),ln=new _d("RTCSession:ReferSubscriber"),pd=function(c){od(n,c);var r=ad(n);function n(o){var a;return id(this,n),a=r.call(this),a._id=null,a._session=o,a}return ld(n,[{key:"sendRefer",value:function(a){var t=this,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};ln.debug("sendRefer()");var p=Xu.cloneArray(s.extraHeaders),h=Xu.cloneObject(s.eventHandlers);for(var d in h)Object.prototype.hasOwnProperty.call(h,d)&&this.on(d,h[d]);var g=null;s.replaces&&(g=s.replaces._request.call_id,g+=";to-tag=".concat(s.replaces._to_tag),g+=";from-tag=".concat(s.replaces._from_tag),g=encodeURIComponent(g));var v="Refer-To: <".concat(a).concat(g?"?Replaces=".concat(g):"",">");if(p.push(v),!p.some(function(C){return C.toLowerCase().startsWith("referred-by:")})){var E="Referred-By: <".concat(this._session._ua._configuration.uri._scheme,":").concat(this._session._ua._configuration.uri._user,"@").concat(this._session._ua._configuration.uri._host,">");p.push(E)}p.push("Contact: ".concat(this._session.contact));var S=this._session.sendRequest(Ei.REFER,{extraHeaders:p,eventHandlers:{onSuccessResponse:function(I){t._requestSucceeded(I)},onErrorResponse:function(I){t._requestFailed(I,Ei.causes.REJECTED)},onTransportError:function(){t._requestFailed(null,Ei.causes.CONNECTION_ERROR)},onRequestTimeout:function(){t._requestFailed(null,Ei.causes.REQUEST_TIMEOUT)},onDialogError:function(){t._requestFailed(null,Ei.causes.DIALOG_ERROR)}}});this._id=S.cseq}},{key:"receiveNotify",value:function(a){if(ln.debug("receiveNotify()"),!!a.body){var t=dd.parse(a.body.trim().split(`\r
49
49
  `,1)[0],"Status_Line");if(t===-1){ln.debug('receiveNotify() | error parsing NOTIFY body: "'.concat(a.body,'"'));return}switch(!0){case/^100$/.test(t.status_code):this.emit("trying",{request:a,status_line:t});break;case/^1[0-9]{2}$/.test(t.status_code):this.emit("progress",{request:a,status_line:t});break;case/^2[0-9]{2}$/.test(t.status_code):this.emit("accepted",{request:a,status_line:t});break;default:this.emit("failed",{request:a,status_line:t});break}}}},{key:"_requestSucceeded",value:function(a){ln.debug("REFER succeeded"),ln.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:a})}},{key:"_requestFailed",value:function(a,t){ln.debug("REFER failed"),ln.debug('emit "requestFailed"'),this.emit("requestFailed",{response:a||null,cause:t})}},{key:"id",get:function(){return this._id}}]),n}(hd);function so(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?so=function(n){return typeof n}:so=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},so(c)}function os(c,r){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=md(c))||r&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(d){throw d},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
50
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var t=!0,s=!1,p;return{s:function(){n=c[Symbol.iterator]()},n:function(){var d=n.next();return t=d.done,d},e:function(d){s=!0,p=d},f:function(){try{!t&&n.return!=null&&n.return()}finally{if(s)throw p}}}}function md(c,r){if(c){if(typeof c=="string")return Qu(c,r);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Qu(c,r)}}function Qu(c,r){(r==null||r>c.length)&&(r=c.length);for(var n=0,o=new Array(r);n<r;n++)o[n]=c[n];return o}function gd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function Zu(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function ec(c,r,n){return r&&Zu(c.prototype,r),n&&Zu(c,n),c}function vd(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&ja(c,r)}function ja(c,r){return ja=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ja(c,r)}function Td(c){var r=Sd();return function(){var o=_o(c),a;if(r){var t=_o(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return Ed(this,a)}}function Ed(c,r){return r&&(so(r)==="object"||typeof r=="function")?r:yd(c)}function yd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Sd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function _o(c){return _o=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},_o(c)}var Cd=pt.EventEmitter,tc=Lt,Ad=it,oe=tt,on=xs,sc=Ji,Fe=Et(),yi=Df,Rd=_s,bl=w_,Id=Xi,It=q_,nc=Z_,bd=rd,wd=pd,rc=Ls(),K=new Ad("RTCSession"),J={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},wl=["audio","video"],Od=function(c){vd(n,c);var r=Td(n);ec(n,null,[{key:"C",get:function(){return J}}]);function n(o){var a;return gd(this,n),K.debug("new"),a=r.call(this),a._id=null,a._ua=o,a._status=J.STATUS_NULL,a._dialog=null,a._earlyDialogs={},a._contact=null,a._from_tag=null,a._to_tag=null,a._connection=null,a._connectionPromiseQueue=Promise.resolve(),a._request=null,a._is_canceled=!1,a._cancel_reason="",a._is_confirmed=!1,a._late_sdp=!1,a._rtcOfferConstraints=null,a._rtcAnswerConstraints=null,a._localMediaStream=null,a._localMediaStreamLocallyGenerated=!1,a._rtcReady=!0,a._iceReady=!1,a._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},a._direction=null,a._local_identity=null,a._remote_identity=null,a._start_time=null,a._end_time=null,a._tones=null,a._audioMuted=!1,a._videoMuted=!1,a._localHold=!1,a._remoteHold=!1,a._sessionTimers={enabled:a._ua.configuration.session_timers,refreshMethod:a._ua.configuration.session_timers_refresh_method,defaultExpires:oe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},a._referSubscribers={},a._data={},a}return ec(n,[{key:"isInProgress",value:function(){switch(this._status){case J.STATUS_NULL:case J.STATUS_INVITE_SENT:case J.STATUS_1XX_RECEIVED:case J.STATUS_INVITE_RECEIVED:case J.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case J.STATUS_ANSWERED:case J.STATUS_WAITING_FOR_ACK:case J.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case J.STATUS_CANCELED:case J.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(a){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;K.debug("connect()");var p=a,h=Fe.cloneObject(t.eventHandlers),d=Fe.cloneArray(t.extraHeaders),g=Fe.cloneObject(t.mediaConstraints,{audio:!0,video:!0}),v=t.mediaStream||null,E=Fe.cloneObject(t.pcConfig,{iceServers:[]}),S=t.rtcConstraints||null,C=t.rtcOfferConstraints||null;if(this._rtcOfferConstraints=C,this._rtcAnswerConstraints=t.rtcAnswerConstraints||null,this._data=t.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==J.STATUS_NULL)throw new on.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new on.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(p));this._sessionTimers.enabled&&Fe.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES);for(var I in h)Object.prototype.hasOwnProperty.call(h,I)&&this.on(I,h[I]);this._from_tag=Fe.newTag();var w=t.anonymous||!1,F={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:w,outbound:!0}),w?(F.from_display_name="Anonymous",F.from_uri=new rc("sip","anonymous","anonymous.invalid"),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),d.push("Privacy: id")):t.fromUserName&&(F.from_uri=new rc("sip",t.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),t.fromDisplayName&&(F.from_display_name=t.fromDisplayName),d.push("Contact: ".concat(this._contact)),d.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&d.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new Rd.InitialOutgoingInviteRequest(a,this._ua,F,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(E,S),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,s&&s(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,C,v)}},{key:"init_incoming",value:function(a,t){var s=this;K.debug("init_incoming()");var p,h=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&h!=="application/sdp"){a.reply(415);return}if(this._status=J.STATUS_INVITE_RECEIVED,this._from_tag=a.from_tag,this._id=a.call_id+this._from_tag,this._request=a,this._contact=this._ua.contact.toString(),a.hasHeader("expires")&&(p=a.getHeader("expires")*1e3),a.to_tag=Fe.newTag(),!this._createDialog(a,"UAS",!0)){a.reply(500,"Missing Contact header field");return}a.body?this._late_sdp=!1:this._late_sdp=!0,this._status=J.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){a.reply(408),s._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),p&&(this._timers.expiresTimer=setTimeout(function(){s._status===J.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),s._failed("system",null,oe.causes.EXPIRES))},p)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,t&&t(this),this._newRTCSession("remote",a),this._status!==J.STATUS_TERMINATED&&(a.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("answer()");var s=this._request,p=Fe.cloneArray(t.extraHeaders),h=Fe.cloneObject(t.mediaConstraints),d=t.mediaStream||null,g=Fe.cloneObject(t.pcConfig,{iceServers:[]}),v=t.rtcConstraints||null,E=t.rtcAnswerConstraints||null,S=Fe.cloneObject(t.rtcOfferConstraints),C,I=!1,w=!1,F=!1,L=!1;if(this._rtcAnswerConstraints=E,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new on.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==J.STATUS_WAITING_FOR_ANSWER)throw new on.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Fe.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES),this._status=J.STATUS_ANSWERED,!this._createDialog(s,"UAS")){s.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),p.unshift("Contact: ".concat(this._contact));var ie=s.parseSDP();Array.isArray(ie.media)||(ie.media=[ie.media]);var N=os(ie.media),H;try{for(N.s();!(H=N.n()).done;){var ve=H.value;ve.type==="audio"&&(I=!0,(!ve.direction||ve.direction==="sendrecv")&&(F=!0)),ve.type==="video"&&(w=!0,(!ve.direction||ve.direction==="sendrecv")&&(L=!0))}}catch($){N.e($)}finally{N.f()}if(d&&h.audio===!1){C=d.getAudioTracks();var me=os(C),M;try{for(me.s();!(M=me.n()).done;){var D=M.value;d.removeTrack(D)}}catch($){me.e($)}finally{me.f()}}if(d&&h.video===!1){C=d.getVideoTracks();var j=os(C),V;try{for(j.s();!(V=j.n()).done;){var Y=V.value;d.removeTrack(Y)}}catch($){j.e($)}finally{j.f()}}!d&&h.audio===void 0&&(h.audio=F),!d&&h.video===void 0&&(h.video=L),!d&&!I&&!S.offerToReceiveAudio&&(h.audio=!1),!d&&!w&&!S.offerToReceiveVideo&&(h.video=!1),this._createRTCConnection(g,v),Promise.resolve().then(function(){if(d)return d;if(h.audio||h.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(h).catch(function($){throw a._status===J.STATUS_TERMINATED?new Error("terminated"):(s.reply(480),a._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),K.warn('emit "getusermediafailed" [error:%o]',$),a.emit("getusermediafailed",$),new Error("getUserMedia() failed"))})}).then(function($){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=$,$&&$.getTracks().forEach(function(z){a._connection.addTrack(z,$)})}).then(function(){if(!a._late_sdp){var $={originator:"remote",type:"offer",sdp:s.body};K.debug('emit "sdp"'),a.emit("sdp",$);var z=new RTCSessionDescription({type:"offer",sdp:$.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(z)}).catch(function(U){throw s.reply(488),a._failed("system",null,oe.causes.WEBRTC_ERROR),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',U),a.emit("peerconnection:setremotedescriptionfailed",U),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(s),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw s.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",E).catch(function(){throw s.reply(500),new Error("_createLocalDescription() failed")})}).then(function($){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(s,p),s.reply(200,null,p,$,function(){a._status=J.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(s,$),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,oe.causes.CONNECTION_ERROR)})}).catch(function($){a._status!==J.STATUS_TERMINATED&&K.warn($)})}},{key:"terminate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("terminate()");var s=t.cause||oe.causes.BYE,p=Fe.cloneArray(t.extraHeaders),h=t.body,d,g=t.status_code,v=t.reason_phrase;if(this._status===J.STATUS_TERMINATED)throw new on.InvalidStateError(this._status);switch(this._status){case J.STATUS_NULL:case J.STATUS_INVITE_SENT:case J.STATUS_1XX_RECEIVED:if(K.debug("canceling session"),g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));g&&(v=v||oe.REASON_PHRASE[g]||"",d="SIP ;cause=".concat(g,' ;text="').concat(v,'"')),this._status===J.STATUS_NULL||this._status===J.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=d):this._status===J.STATUS_1XX_RECEIVED&&this._request.cancel(d),this._status=J.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case J.STATUS_WAITING_FOR_ANSWER:case J.STATUS_ANSWERED:if(K.debug("rejecting session"),g=g||480,g<300||g>=700)throw new TypeError("Invalid status_code: ".concat(g));this._request.reply(g,v,p,h),this._failed("local",null,oe.causes.REJECTED);break;case J.STATUS_WAITING_FOR_ACK:case J.STATUS_CONFIRMED:if(K.debug("terminating session"),v=t.reason_phrase||oe.REASON_PHRASE[g]||"",g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));if(g&&p.push("Reason: SIP ;cause=".concat(g,'; text="').concat(v,'"')),this._status===J.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==sc.C.STATUS_TERMINATED){var E=this._dialog;this.receiveRequest=function(S){var C=S.method;C===oe.ACK&&(a.sendRequest(oe.BYE,{extraHeaders:p,body:h}),E.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===sc.C.STATUS_TERMINATED&&(a.sendRequest(oe.BYE,{extraHeaders:p,body:h}),E.terminate())}),this._ended("local",null,s),this._dialog=E,this._ua.newDialog(E)}else this.sendRequest(oe.BYE,{extraHeaders:p,body:h}),this._ended("local",null,s)}}},{key:"sendDTMF",value:function(a){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};K.debug("sendDTMF() | tones: %s",a);var s=0,p=t.duration||null,h=t.interToneGap||null,d=t.transportType||oe.DTMF_TRANSPORT.INFO;if(a===void 0)throw new TypeError("Not enough arguments");if(this._status!==J.STATUS_CONFIRMED&&this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_1XX_RECEIVED)throw new on.InvalidStateError(this._status);if(d!==oe.DTMF_TRANSPORT.INFO&&d!==oe.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(d));if(typeof a=="number"&&(a=a.toString()),!a||typeof a!="string"||!a.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(a));if(p&&!Fe.isDecimal(p))throw new TypeError("Invalid tone duration: ".concat(p));if(p?p<It.C.MIN_DURATION?(K.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(It.C.MIN_DURATION," milliseconds")),p=It.C.MIN_DURATION):p>It.C.MAX_DURATION?(K.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(It.C.MAX_DURATION," milliseconds")),p=It.C.MAX_DURATION):p=Math.abs(p):p=It.C.DEFAULT_DURATION,t.duration=p,h&&!Fe.isDecimal(h))throw new TypeError("Invalid interToneGap: ".concat(h));if(h?h<It.C.MIN_INTER_TONE_GAP?(K.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(It.C.MIN_INTER_TONE_GAP," milliseconds")),h=It.C.MIN_INTER_TONE_GAP):h=Math.abs(h):h=It.C.DEFAULT_INTER_TONE_GAP,d===oe.DTMF_TRANSPORT.RFC2833){var g=this._getDTMFRTPSender();g&&(a=g.toneBuffer+a,g.insertDTMF(a,p,h));return}if(this._tones){this._tones+=a;return}this._tones=a,v.call(this);function v(){var E=this,S;if(this._status===J.STATUS_TERMINATED||!this._tones||s>=this._tones.length){this._tones=null;return}var C=this._tones[s];if(s+=1,C===",")S=2e3;else{var I=new It(this);t.eventHandlers={onFailed:function(){E._tones=null}},I.send(C,t),S=p+h}setTimeout(v.bind(this),S)}}},{key:"sendInfo",value:function(a,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(K.debug("sendInfo()"),this._status!==J.STATUS_CONFIRMED&&this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_1XX_RECEIVED)throw new on.InvalidStateError(this._status);var p=new nc(this);p.send(a,t,s)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};K.debug("mute()");var t=!1,s=!1;this._audioMuted===!1&&a.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(s=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||s===!0)&&this._onmute({audio:t,video:s})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};K.debug("unmute()");var t=!1,s=!1;this._audioMuted===!0&&a.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(s=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||s===!0)&&this._onunmute({audio:t,video:s})}},{key:"hold",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;if(K.debug("hold()"),this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var p={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:p,extraHeaders:t.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;if(K.debug("unhold()"),this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var p={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:p,extraHeaders:t.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;K.debug("renegotiate()");var p=t.rtcOfferConstraints||null;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var h={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,rtcOfferConstraints:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:h,rtcOfferConstraints:p,extraHeaders:t.extraHeaders}),!0}},{key:"refer",value:function(a,t){var s=this;K.debug("refer()");var p=a;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(p));var h=new wd(this);h.sendRefer(a,t);var d=h.id;return this._referSubscribers[d]=h,h.on("requestFailed",function(){delete s._referSubscribers[d]}),h.on("accepted",function(){delete s._referSubscribers[d]}),h.on("failed",function(){delete s._referSubscribers[d]}),h}},{key:"sendRequest",value:function(a,t){return K.debug("sendRequest()"),this._dialog.sendRequest(a,t)}},{key:"receiveRequest",value:function(a){var t=this;if(K.debug("receiveRequest()"),a.method===oe.CANCEL)(this._status===J.STATUS_WAITING_FOR_ANSWER||this._status===J.STATUS_ANSWERED)&&(this._status=J.STATUS_CANCELED,this._request.reply(487),this._failed("remote",a,oe.causes.CANCELED));else switch(a.method){case oe.ACK:if(this._status!==J.STATUS_WAITING_FOR_ACK)return;if(this._status=J.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!a.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}var s={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",s);var p=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._connection.setRemoteDescription(p)}).then(function(){t._is_confirmed||t._confirmed("remote",a)}).catch(function(d){t.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',d),t.emit("peerconnection:setremotedescriptionfailed",d)})}else this._is_confirmed||this._confirmed("remote",a);break;case oe.BYE:this._status===J.STATUS_CONFIRMED||this._status===J.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,oe.causes.BYE)):this._status===J.STATUS_INVITE_RECEIVED||this._status===J.STATUS_WAITING_FOR_ANSWER?(a.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",a,oe.causes.BYE)):a.reply(403,"Wrong Status");break;case oe.INVITE:this._status===J.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case oe.INFO:if(this._status===J.STATUS_1XX_RECEIVED||this._status===J.STATUS_WAITING_FOR_ANSWER||this._status===J.STATUS_ANSWERED||this._status===J.STATUS_WAITING_FOR_ACK||this._status===J.STATUS_CONFIRMED){var h=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;h&&h.match(/^application\/dtmf-relay/i)?new It(this).init_incoming(a):h!==void 0?new nc(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===J.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case oe.REFER:this._status===J.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===J.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){K.warn("onTransportError()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){K.warn("onRequestTimeout()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){K.warn("onDialogError()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){K.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){K.debug("newInfo()"),this.emit("newInfo",a)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(K.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(K.debug("_isReadyToReOffer() | session not established yet"),!1):(K.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(K.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(K.debug("close() | closing local MediaStream"),Fe.closeMediaStream(this._localMediaStream)),this._status!==J.STATUS_TERMINATED){if(this._status=J.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(p){K.warn("close() | error closing the RTCPeerConnection: %o",p)}for(var a in this._timers)Object.prototype.hasOwnProperty.call(this._timers,a)&&clearTimeout(this._timers[a]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(var s in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,s)&&delete this._referSubscribers[s];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,t){var s=yi.T1;function p(){this._status===J.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],t),s<yi.T2&&(s=s*2,s>yi.T2&&(s=yi.T2)),this._timers.invite2xxTimer=setTimeout(p.bind(this),s))}this._timers.invite2xxTimer=setTimeout(p.bind(this),s)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===J.STATUS_WAITING_FOR_ACK&&(K.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(oe.BYE),a._ended("remote",null,oe.causes.NO_ACK))},yi.TIMER_H)}},{key:"_createRTCConnection",value:function(a,t){var s=this;this._connection=new RTCPeerConnection(a,t),this._connection.addEventListener("iceconnectionstatechange",function(){var p=s._connection.iceConnectionState;p==="failed"&&s.terminate({cause:oe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:oe.causes.RTP_TIMEOUT})}),K.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,t){var s=this;if(K.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var p=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?p.createOffer(t).catch(function(h){return K.warn('emit "peerconnection:createofferfailed" [error:%o]',h),s.emit("peerconnection:createofferfailed",h),Promise.reject(h)}):p.createAnswer(t).catch(function(h){return K.warn('emit "peerconnection:createanswerfailed" [error:%o]',h),s.emit("peerconnection:createanswerfailed",h),Promise.reject(h)})}).then(function(h){return p.setLocalDescription(h).catch(function(d){return s._rtcReady=!0,K.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',d),s.emit("peerconnection:setlocaldescriptionfailed",d),Promise.reject(d)})}).then(function(){var h=t&&t.iceRestart;if(p.iceGatheringState==="complete"&&!h||p.iceGatheringState==="gathering"&&s._iceReady){s._rtcReady=!0;var d={originator:"local",type:a,sdp:p.localDescription.sdp};return K.debug('emit "sdp"'),s.emit("sdp",d),Promise.resolve(d.sdp)}return new Promise(function(g){var v=!1,E,S;s._iceReady=!1;var C=function(){p.removeEventListener("icecandidate",E),p.removeEventListener("icegatheringstatechange",S),v=!0,s._rtcReady=!0,s._iceReady=!0;var w={originator:"local",type:a,sdp:p.localDescription.sdp};K.debug('emit "sdp"'),s.emit("sdp",w),g(w.sdp)};p.addEventListener("icecandidate",E=function(w){var F=w.candidate;F?s.emit("icecandidate",{candidate:F,ready:C}):v||C()}),p.addEventListener("icegatheringstatechange",S=function(){p.iceGatheringState==="complete"&&!v&&C()})})})}},{key:"_createDialog",value:function(a,t,s){var p=t==="UAS"?a.to_tag:a.from_tag,h=t==="UAS"?a.from_tag:a.to_tag,d=a.call_id+p+h,g=this._earlyDialogs[d];if(s)return g?!0:(g=new bl(this,a,t,bl.C.STATUS_EARLY),g.error?(K.debug(g.error),this._failed("remote",a,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=g,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,g)return g.update(a,t),this._dialog=g,delete this._earlyDialogs[d],!0;var v=new bl(this,a,t);return v.error?(K.debug(v.error),this._failed("remote",a,oe.causes.INTERNAL_ERROR),!1):(this._dialog=v,!0)}},{key:"_receiveReinvite",value:function(a){var t=this;K.debug("receiveReinvite()");var s=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,p={request:a,callback:void 0,reject:d.bind(this)},h=!1;function d(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};h=!0;var E=v.status_code||403,S=v.reason_phrase||"",C=Fe.cloneArray(v.extraHeaders);if(this._status!==J.STATUS_CONFIRMED)return!1;if(E<300||E>=700)throw new TypeError("Invalid status_code: ".concat(E));a.reply(E,S,C)}if(this.emit("reinvite",p),h)return;if(this._late_sdp=!1,!a.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._createLocalDescription("offer",t._rtcOfferConstraints)}).then(function(v){g.call(t,v)}).catch(function(){a.reply(500)});return}if(s!=="application/sdp"){K.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(v){t._status!==J.STATUS_TERMINATED&&g.call(t,v)}).catch(function(v){K.warn(v)});function g(v){var E=this,S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),this._late_sdp&&(v=this._mangleOffer(v)),a.reply(200,null,S,v,function(){E._status=J.STATUS_WAITING_FOR_ACK,E._setInvite2xxTimer(a,v),E._setACKTimer()}),typeof p.callback=="function"&&p.callback()}}},{key:"_receiveUpdate",value:function(a){var t=this;K.debug("receiveUpdate()");var s=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,p={request:a,callback:void 0,reject:d.bind(this)},h=!1;function d(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};h=!0;var E=v.status_code||403,S=v.reason_phrase||"",C=Fe.cloneArray(v.extraHeaders);if(this._status!==J.STATUS_CONFIRMED)return!1;if(E<300||E>=700)throw new TypeError("Invalid status_code: ".concat(E));a.reply(E,S,C)}if(this.emit("update",p),h)return;if(!a.body){g.call(this,null);return}if(s!=="application/sdp"){K.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(v){t._status!==J.STATUS_TERMINATED&&g.call(t,v)}).catch(function(v){K.warn(v)});function g(v){var E=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,E),a.reply(200,null,E,v),typeof p.callback=="function"&&p.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var t=this;K.debug("_processInDialogSdpOffer()");var s=a.parseSDP(),p=!1,h=os(s.media),d;try{for(h.s();!(d=h.n()).done;){var g=d.value;if(wl.indexOf(g.type)!==-1){var v=g.direction||s.direction||"sendrecv";if(v==="sendonly"||v==="inactive")p=!0;else{p=!1;break}}}}catch(C){h.e(C)}finally{h.f()}var E={originator:"remote",type:"offer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",E);var S=new RTCSessionDescription({type:"offer",sdp:E.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");return t._connection.setRemoteDescription(S).catch(function(C){throw a.reply(488),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),t.emit("peerconnection:setremotedescriptionfailed",C),C})}).then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");t._remoteHold===!0&&p===!1?(t._remoteHold=!1,t._onunhold("remote")):t._remoteHold===!1&&p===!0&&(t._remoteHold=!0,t._onhold("remote"))}).then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");return t._createLocalDescription("answer",t._rtcAnswerConstraints).catch(function(C){throw a.reply(500),K.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',C),C})}).catch(function(C){K.warn("_processInDialogSdpOffer() failed [error: %o]",C)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var t=this;if(K.debug("receiveRefer()"),!a.refer_to){K.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==oe.SIP){K.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var s=new bd(this,a.cseq);K.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(g,v){p.call(t,g,v)},reject:function(){h.call(t)}});function p(d){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(d=typeof d=="function"?d:null,this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;var v=new n(this._ua);if(v.on("progress",function(S){var C=S.response;s.notify(C.status_code,C.reason_phrase)}),v.on("accepted",function(S){var C=S.response;s.notify(C.status_code,C.reason_phrase)}),v.on("_failed",function(S){var C=S.message,I=S.cause;C?s.notify(C.status_code,C.reason_phrase):s.notify(487,I)}),a.refer_to.uri.hasHeader("replaces")){var E=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));g.extraHeaders=Fe.cloneArray(g.extraHeaders),g.extraHeaders.push("Replaces: ".concat(E))}v.connect(a.refer_to.uri.toAor(),g,d)}function h(){s.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(K.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var t,s;if(a.event.params&&a.event.params.id)t=a.event.params.id,s=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)s=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!s){a.reply(481,"Subscription does not exist");return}s.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var t=this;K.debug("receiveReplaces()");function s(h){var d=this;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;var g=new n(this._ua);g.on("confirmed",function(){d.terminate()}),g.init_incoming(a,h)}function p(){K.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(d){s.call(t,d)},reject:function(){p.call(t)}})}},{key:"_sendInitialRequest",value:function(a,t,s){var p=this,h=new Id(this._ua,this._request,{onRequestTimeout:function(){p.onRequestTimeout()},onTransportError:function(){p.onTransportError()},onAuthenticated:function(g){p._request=g},onReceiveResponse:function(g){p._receiveInviteResponse(g)}});Promise.resolve().then(function(){if(s)return s;if(a.audio||a.video)return p._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(d){throw p._status===J.STATUS_TERMINATED?new Error("terminated"):(p._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),K.warn('emit "getusermediafailed" [error:%o]',d),p.emit("getusermediafailed",d),d)})}).then(function(d){if(p._status===J.STATUS_TERMINATED)throw new Error("terminated");return p._localMediaStream=d,d&&d.getTracks().forEach(function(g){p._connection.addTrack(g,d)}),p._connecting(p._request),p._createLocalDescription("offer",t).catch(function(g){throw p._failed("local",null,oe.causes.WEBRTC_ERROR),g})}).then(function(d){if(p._is_canceled||p._status===J.STATUS_TERMINATED)throw new Error("terminated");p._request.body=d,p._status=J.STATUS_INVITE_SENT,K.debug('emit "sending" [request:%o]',p._request),p.emit("sending",{request:p._request}),h.send()}).catch(function(d){p._status!==J.STATUS_TERMINATED&&K.warn(d)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(t){return t.track&&t.track.kind==="audio"});if(!(a&&a.dtmf)){K.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var t=this;if(K.debug("receiveInviteResponse()"),this._dialog&&a.status_code>=200&&a.status_code<=299)if(this._dialog.id.call_id===a.call_id&&this._dialog.id.local_tag===a.from_tag&&this._dialog.id.remote_tag===a.to_tag){this.sendRequest(oe.ACK);return}else{var s=new bl(this,a,"UAC");if(s.error!==void 0){K.debug(s.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this._is_canceled){a.status_code>=100&&a.status_code<200?this._request.cancel(this._cancel_reason):a.status_code>=200&&a.status_code<299&&this._acceptAndTerminate(a);return}if(!(this._status!==J.STATUS_INVITE_SENT&&this._status!==J.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(a.status_code):this._status=J.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(a.status_code):{if(!a.to_tag){K.debug("1xx response received without to tag");break}if(a.hasHeader("contact")&&!this._createDialog(a,"UAC",!0))break;if(this._status=J.STATUS_1XX_RECEIVED,!a.body){this._progress("remote",a);break}var p={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",p);var h=new RTCSessionDescription({type:"answer",sdp:p.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._connection.setRemoteDescription(h)}).then(function(){return t._progress("remote",a)}).catch(function(E){K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),t.emit("peerconnection:setremotedescriptionfailed",E)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=J.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,oe.causes.MISSING_SDP),this._failed("remote",a,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var d={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",d);var g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(t._connection.signalingState==="stable")return t._connection.createOffer(t._rtcOfferConstraints).then(function(E){return t._connection.setLocalDescription(E)}).catch(function(E){t._acceptAndTerminate(a,500,E.toString()),t._failed("local",a,oe.causes.WEBRTC_ERROR)})}).then(function(){t._connection.setRemoteDescription(g).then(function(){t._handleSessionTimersInIncomingResponse(a),t._accepted("remote",a),t.sendRequest(oe.ACK),t._confirmed("local",null)}).catch(function(E){t._acceptAndTerminate(a,488,"Not Acceptable Here"),t._failed("remote",a,oe.causes.BAD_MEDIA_DESCRIPTION),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),t.emit("peerconnection:setremotedescriptionfailed",E)})});break}default:{var v=Fe.sipErrorCause(a.status_code);this._failed("remote",a,v)}}}},{key:"_sendReinvite",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("sendReinvite()");var s=Fe.cloneArray(t.extraHeaders),p=Fe.cloneObject(t.eventHandlers),h=t.rtcOfferConstraints||this._rtcOfferConstraints||null,d=!1;s.push("Contact: ".concat(this._contact)),s.push("Content-Type: application/sdp"),this._sessionTimers.running&&s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",h)}).then(function(E){E=a._mangleOffer(E);var S={originator:"local",type:"offer",sdp:E};K.debug('emit "sdp"'),a.emit("sdp",S),a.sendRequest(oe.INVITE,{extraHeaders:s,body:E,eventHandlers:{onSuccessResponse:function(I){g.call(a,I),d=!0},onErrorResponse:function(I){v.call(a,I)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){v()});function g(E){var S=this;if(this._status!==J.STATUS_TERMINATED&&(this.sendRequest(oe.ACK),!d)){if(this._handleSessionTimersInIncomingResponse(E),E.body){if(!E.hasHeader("Content-Type")||E.getHeader("Content-Type").toLowerCase()!=="application/sdp"){v.call(this);return}}else{v.call(this);return}var C={originator:"remote",type:"answer",sdp:E.body};K.debug('emit "sdp"'),this.emit("sdp",C);var I=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return S._connection.setRemoteDescription(I)}).then(function(){p.succeeded&&p.succeeded(E)}).catch(function(w){v.call(S),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',w),S.emit("peerconnection:setremotedescriptionfailed",w)})}}function v(E){p.failed&&p.failed(E)}}},{key:"_sendUpdate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("sendUpdate()");var s=Fe.cloneArray(t.extraHeaders),p=Fe.cloneObject(t.eventHandlers),h=t.rtcOfferConstraints||this._rtcOfferConstraints||null,d=t.sdpOffer||!1,g=!1;s.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),d?(s.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",h)}).then(function(S){S=a._mangleOffer(S);var C={originator:"local",type:"offer",sdp:S};K.debug('emit "sdp"'),a.emit("sdp",C),a.sendRequest(oe.UPDATE,{extraHeaders:s,body:S,eventHandlers:{onSuccessResponse:function(w){v.call(a,w),g=!0},onErrorResponse:function(w){E.call(a,w)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){E.call(a)})):this.sendRequest(oe.UPDATE,{extraHeaders:s,eventHandlers:{onSuccessResponse:function(C){v.call(a,C)},onErrorResponse:function(C){E.call(a,C)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function v(S){var C=this;if(this._status!==J.STATUS_TERMINATED&&!g)if(this._handleSessionTimersInIncomingResponse(S),d){if(S.body){if(!S.hasHeader("Content-Type")||S.getHeader("Content-Type").toLowerCase()!=="application/sdp"){E.call(this);return}}else{E.call(this);return}var I={originator:"remote",type:"answer",sdp:S.body};K.debug('emit "sdp"'),this.emit("sdp",I);var w=new RTCSessionDescription({type:"answer",sdp:I.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return C._connection.setRemoteDescription(w)}).then(function(){p.succeeded&&p.succeeded(S)}).catch(function(F){E.call(C),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',F),C.emit("peerconnection:setremotedescriptionfailed",F)})}else p.succeeded&&p.succeeded(S)}function E(S){p.failed&&p.failed(S)}}},{key:"_acceptAndTerminate",value:function(a,t,s){K.debug("acceptAndTerminate()");var p=[];t&&(s=s||oe.REASON_PHRASE[t]||"",p.push("Reason: SIP ;cause=".concat(t,'; text="').concat(s,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(oe.ACK),this.sendRequest(oe.BYE,{extraHeaders:p})),this._status=J.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=tc.parse(a),this._localHold&&!this._remoteHold){K.debug("mangleOffer() | me on hold, mangling offer");var t=os(a.media),s;try{for(t.s();!(s=t.n()).done;){var p=s.value;wl.indexOf(p.type)!==-1&&(p.direction?p.direction==="sendrecv"?p.direction="sendonly":p.direction==="recvonly"&&(p.direction="inactive"):p.direction="sendonly")}}catch(C){t.e(C)}finally{t.f()}}else if(this._localHold&&this._remoteHold){K.debug("mangleOffer() | both on hold, mangling offer");var h=os(a.media),d;try{for(h.s();!(d=h.n()).done;){var g=d.value;wl.indexOf(g.type)!==-1&&(g.direction="inactive")}}catch(C){h.e(C)}finally{h.f()}}else if(this._remoteHold){K.debug("mangleOffer() | remote on hold, mangling offer");var v=os(a.media),E;try{for(v.s();!(E=v.n()).done;){var S=E.value;wl.indexOf(S.type)!==-1&&(S.direction?S.direction==="sendrecv"?S.direction="recvonly":S.direction==="recvonly"&&(S.direction="inactive"):S.direction="recvonly")}}catch(C){v.e(C)}finally{v.f()}}return tc.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,t=!0;(this._localHold||this._remoteHold)&&(a=!1,t=!1),this._audioMuted&&(a=!1),this._videoMuted&&(t=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!t)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,t){if(this._sessionTimers.enabled){var s;a.session_expires&&a.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,s=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uas"),t.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(s)),this._sessionTimers.refresher=s==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var t;a.session_expires&&a.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,t=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,t="uac"),this._sessionTimers.refresher=t==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){a._status!==J.STATUS_TERMINATED&&a._isReadyToReOffer()&&(K.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===oe.UPDATE?a._sendUpdate():a._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(function(){a._status!==J.STATUS_TERMINATED&&(K.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:oe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}},{key:"_toggleMuteAudio",value:function(a){var t=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="audio"}),s=os(t),p;try{for(s.s();!(p=s.n()).done;){var h=p.value;h.track.enabled=!a}}catch(d){s.e(d)}finally{s.f()}}},{key:"_toggleMuteVideo",value:function(a){var t=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="video"}),s=os(t),p;try{for(s.s();!(p=s.n()).done;){var h=p.value;h.track.enabled=!a}}catch(d){s.e(d)}finally{s.f()}}},{key:"_newRTCSession",value:function(a,t){K.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:t})}},{key:"_connecting",value:function(a){K.debug("session connecting"),K.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,t){K.debug("session progress"),K.debug('emit "progress"'),this.emit("progress",{originator:a,response:t||null})}},{key:"_accepted",value:function(a,t){K.debug("session accepted"),this._start_time=new Date,K.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:t||null})}},{key:"_confirmed",value:function(a,t){K.debug("session confirmed"),this._is_confirmed=!0,K.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:t||null})}},{key:"_ended",value:function(a,t,s){K.debug("session ended"),this._end_time=new Date,this._close(),K.debug('emit "ended"'),this.emit("ended",{originator:a,message:t||null,cause:s})}},{key:"_failed",value:function(a,t,s){K.debug("session failed"),K.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:t||null,cause:s}),this._close(),K.debug('emit "failed"'),this.emit("failed",{originator:a,message:t||null,cause:s})}},{key:"_onhold",value:function(a){K.debug("session onhold"),this._setLocalMediaStatus(),K.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){K.debug("session onunhold"),this._setLocalMediaStatus(),K.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var t=a.audio,s=a.video;K.debug("session onmute"),this._setLocalMediaStatus(),K.debug('emit "muted"'),this.emit("muted",{audio:t,video:s})}},{key:"_onunmute",value:function(a){var t=a.audio,s=a.video;K.debug("session onunmute"),this._setLocalMediaStatus(),K.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:s})}},{key:"C",get:function(){return J}},{key:"causes",get:function(){return oe.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(a){this._data=a}},{key:"status",get:function(){return this._status}}]),n}(Cd);function no(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?no=function(n){return typeof n}:no=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},no(c)}function Dd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function ic(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Nd(c,r,n){return r&&ic(c.prototype,r),n&&ic(c,n),c}function Ud(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&Ba(c,r)}function Ba(c,r){return Ba=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ba(c,r)}function Pd(c){var r=xd();return function(){var o=po(c),a;if(r){var t=po(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return kd(this,a)}}function kd(c,r){return r&&(no(r)==="object"||typeof r=="function")?r:Md(c)}function Md(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function xd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function po(c){return po=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},po(c)}var Ld=pt.EventEmitter,$d=it,sa=tt,Hd=_s,Si=Et(),Fd=Xi,lc=xs,qd=Ls(),Ol=new $d("Message"),Vd=function(c){Ud(n,c);var r=Pd(n);function n(o){var a;return Dd(this,n),a=r.call(this),a._ua=o,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Nd(n,[{key:"send",value:function(a,t){var s=this,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},h=a;if(a===void 0||t===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=Si.cloneArray(p.extraHeaders),g=Si.cloneObject(p.eventHandlers),v=p.contentType||"text/plain",E={};p.fromUserName&&(E.from_uri=new qd("sip",p.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),p.fromDisplayName&&(E.from_display_name=p.fromDisplayName);for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&this.on(S,g[S]);d.push("Content-Type: ".concat(v)),this._request=new Hd.OutgoingRequest(sa.MESSAGE,a,this._ua,E,d),t&&(this._request.body=t);var C=new Fd(this._ua,this._request,{onRequestTimeout:function(){s._onRequestTimeout()},onTransportError:function(){s._onTransportError()},onReceiveResponse:function(w){s._receiveResponse(w)}});this._newMessage("local",this._request),C.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newMessage("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Si.cloneArray(a.extraHeaders),s=a.body;if(this._direction!=="incoming")throw new lc.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,t,s)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=a.status_code||480,s=a.reason_phrase,p=Si.cloneArray(a.extraHeaders),h=a.body;if(this._direction!=="incoming")throw new lc.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(t<300||t>=700)throw new TypeError("Invalid status_code: ".concat(t));this._is_replied=!0,this._request.reply(t,s,p,h)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var t=Si.sipErrorCause(a.status_code);this._failed("remote",a,t);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,sa.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,sa.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,t){a==="remote"?(this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from):a==="local"&&(this._direction="outgoing",this._local_identity=t.from,this._remote_identity=t.to),this._ua.newMessage(this,{originator:a,message:this,request:t})}},{key:"_failed",value:function(a,t,s){Ol.debug("MESSAGE failed"),this._close(),Ol.debug('emit "failed"'),this.emit("failed",{originator:a,response:t||null,cause:s})}},{key:"_succeeded",value:function(a,t){Ol.debug("MESSAGE succeeded"),this._close(),Ol.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:t})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Ld);function ro(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ro=function(n){return typeof n}:ro=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},ro(c)}function jd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function oc(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Bd(c,r,n){return r&&oc(c.prototype,r),n&&oc(c,n),c}function Gd(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&Ga(c,r)}function Ga(c,r){return Ga=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ga(c,r)}function Kd(c){var r=zd();return function(){var o=mo(c),a;if(r){var t=mo(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return Wd(this,a)}}function Wd(c,r){return r&&(ro(r)==="object"||typeof r=="function")?r:Yd(c)}function Yd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function zd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function mo(c){return mo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},mo(c)}var Jd=pt.EventEmitter,Xd=it,na=tt,Qd=_s,Ci=Et(),Zd=Xi,ac=xs,Dl=new Xd("Options"),ep=function(c){Gd(n,c);var r=Kd(n);function n(o){var a;return jd(this,n),a=r.call(this),a._ua=o,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Bd(n,[{key:"send",value:function(a,t){var s=this,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},h=a;if(a===void 0)throw new TypeError("A target is required for OPTIONS");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=Ci.cloneArray(p.extraHeaders),g=Ci.cloneObject(p.eventHandlers),v=p.contentType||"application/sdp";for(var E in g)Object.prototype.hasOwnProperty.call(g,E)&&this.on(E,g[E]);d.push("Content-Type: ".concat(v)),this._request=new Qd.OutgoingRequest(na.OPTIONS,a,this._ua,null,d),t&&(this._request.body=t);var S=new Zd(this._ua,this._request,{onRequestTimeout:function(){s._onRequestTimeout()},onTransportError:function(){s._onTransportError()},onReceiveResponse:function(I){s._receiveResponse(I)}});this._newOptions("local",this._request),S.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newOptions("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Ci.cloneArray(a.extraHeaders),s=a.body;if(this._direction!=="incoming")throw new ac.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,t,s)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=a.status_code||480,s=a.reason_phrase,p=Ci.cloneArray(a.extraHeaders),h=a.body;if(this._direction!=="incoming")throw new ac.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(t<300||t>=700)throw new TypeError("Invalid status_code: ".concat(t));this._is_replied=!0,this._request.reply(t,s,p,h)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var t=Ci.sipErrorCause(a.status_code);this._failed("remote",a,t);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,na.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,na.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,t){a==="remote"?(this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from):a==="local"&&(this._direction="outgoing",this._local_identity=t.from,this._remote_identity=t.to),this._ua.newOptions(this,{originator:a,message:this,request:t})}},{key:"_failed",value:function(a,t,s){Dl.debug("OPTIONS failed"),this._close(),Dl.debug('emit "failed"'),this.emit("failed",{originator:a,response:t||null,cause:s})}},{key:"_succeeded",value:function(a,t){Dl.debug("OPTIONS succeeded"),this._close(),Dl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:t})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Jd),lu={},tp=it,ra=Et(),sp=Zt(),Ai=new tp("Socket");lu.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Ai.warn("undefined JsSIP.Socket instance"),!1;try{if(!ra.isString(c.url))throw Ai.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!ra.isString(c.via_transport))throw Ai.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(sp.parse(c.sip_uri,"SIP_URI")===-1)throw Ai.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(r){if(!ra.isFunction(c[r]))throw Ai.warn("missing or invalid JsSIP.Socket method: ".concat(r)),new Error("Missing or invalid JsSIP.Socket method: ".concat(r))})}catch{return!1}return!0};function np(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function uc(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function rp(c,r,n){return r&&uc(c.prototype,r),n&&uc(c,n),c}var ip=it,lp=lu,cc=tt,At=new ip("Transport"),Pt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:cc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:cc.CONNECTION_RECOVERY_MAX_INTERVAL}},op=function(){function c(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt.recovery_options;np(this,c),At.debug("new()"),this.status=Pt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(o){At.warn("cannot use TextDecoder: ".concat(o))}if(typeof r>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");r instanceof Array||(r=[r]),r.forEach(function(o){if(!lp.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:Pt.SOCKET_STATUS_READY})},this),this._getSocket()}return rp(c,[{key:"connect",value:function(){if(At.debug("connect()"),this.isConnected()){At.debug("Transport is already connected");return}else if(this.isConnecting()){At.debug("Transport is connecting");return}this.close_requested=!1,this.status=Pt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){At.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Pt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(n){if(At.debug("send()"),!this.isConnected())return At.warn("unable to send message, transport is not connected"),!1;var o=n.toString();return At.debug(`sending message:
50
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var t=!0,s=!1,p;return{s:function(){n=c[Symbol.iterator]()},n:function(){var d=n.next();return t=d.done,d},e:function(d){s=!0,p=d},f:function(){try{!t&&n.return!=null&&n.return()}finally{if(s)throw p}}}}function md(c,r){if(c){if(typeof c=="string")return Qu(c,r);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Qu(c,r)}}function Qu(c,r){(r==null||r>c.length)&&(r=c.length);for(var n=0,o=new Array(r);n<r;n++)o[n]=c[n];return o}function gd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function Zu(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function ec(c,r,n){return r&&Zu(c.prototype,r),n&&Zu(c,n),c}function vd(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&ja(c,r)}function ja(c,r){return ja=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ja(c,r)}function Td(c){var r=Sd();return function(){var o=_o(c),a;if(r){var t=_o(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return Ed(this,a)}}function Ed(c,r){return r&&(so(r)==="object"||typeof r=="function")?r:yd(c)}function yd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Sd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function _o(c){return _o=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},_o(c)}var Cd=pt.EventEmitter,tc=Lt,Ad=it,oe=tt,on=xs,sc=Ji,Fe=Et(),yi=Df,Rd=_s,bl=w_,Id=Xi,It=q_,nc=Z_,bd=rd,wd=pd,rc=Ls(),K=new Ad("RTCSession"),J={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},wl=["audio","video"],Od=function(c){vd(n,c);var r=Td(n);ec(n,null,[{key:"C",get:function(){return J}}]);function n(o){var a;return gd(this,n),K.debug("new"),a=r.call(this),a._id=null,a._ua=o,a._status=J.STATUS_NULL,a._dialog=null,a._earlyDialogs={},a._contact=null,a._from_tag=null,a._to_tag=null,a._connection=null,a._connectionPromiseQueue=Promise.resolve(),a._request=null,a._is_canceled=!1,a._cancel_reason="",a._is_confirmed=!1,a._late_sdp=!1,a._rtcOfferConstraints=null,a._rtcAnswerConstraints=null,a._localMediaStream=null,a._localMediaStreamLocallyGenerated=!1,a._rtcReady=!0,a._iceReady=!1,a._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},a._direction=null,a._local_identity=null,a._remote_identity=null,a._start_time=null,a._end_time=null,a._tones=null,a._audioMuted=!1,a._videoMuted=!1,a._localHold=!1,a._remoteHold=!1,a._sessionTimers={enabled:a._ua.configuration.session_timers,refreshMethod:a._ua.configuration.session_timers_refresh_method,defaultExpires:oe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},a._referSubscribers={},a._data={},a}return ec(n,[{key:"isInProgress",value:function(){switch(this._status){case J.STATUS_NULL:case J.STATUS_INVITE_SENT:case J.STATUS_1XX_RECEIVED:case J.STATUS_INVITE_RECEIVED:case J.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case J.STATUS_ANSWERED:case J.STATUS_WAITING_FOR_ACK:case J.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case J.STATUS_CANCELED:case J.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(a){console.log("rtcOfferConstraints connect");var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;K.debug("connect()");var p=a,h=Fe.cloneObject(t.eventHandlers),d=Fe.cloneArray(t.extraHeaders),g=Fe.cloneObject(t.mediaConstraints,{audio:!0,video:!0}),v=t.mediaStream||null,E=Fe.cloneObject(t.pcConfig,{iceServers:[]}),S=t.rtcConstraints||null,C=t.rtcOfferConstraints||null;if(this._rtcOfferConstraints=C,this._rtcAnswerConstraints=t.rtcAnswerConstraints||null,this._data=t.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==J.STATUS_NULL)throw new on.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new on.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(p));this._sessionTimers.enabled&&Fe.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES);for(var I in h)Object.prototype.hasOwnProperty.call(h,I)&&this.on(I,h[I]);this._from_tag=Fe.newTag();var w=t.anonymous||!1,F={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:w,outbound:!0}),w?(F.from_display_name="Anonymous",F.from_uri=new rc("sip","anonymous","anonymous.invalid"),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),d.push("Privacy: id")):t.fromUserName&&(F.from_uri=new rc("sip",t.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),t.fromDisplayName&&(F.from_display_name=t.fromDisplayName),d.push("Contact: ".concat(this._contact)),d.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&d.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new Rd.InitialOutgoingInviteRequest(a,this._ua,F,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(E,S),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,s&&s(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,C,v)}},{key:"init_incoming",value:function(a,t){var s=this;K.debug("init_incoming()");var p,h=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&h!=="application/sdp"){a.reply(415);return}if(this._status=J.STATUS_INVITE_RECEIVED,this._from_tag=a.from_tag,this._id=a.call_id+this._from_tag,this._request=a,this._contact=this._ua.contact.toString(),a.hasHeader("expires")&&(p=a.getHeader("expires")*1e3),a.to_tag=Fe.newTag(),!this._createDialog(a,"UAS",!0)){a.reply(500,"Missing Contact header field");return}a.body?this._late_sdp=!1:this._late_sdp=!0,this._status=J.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){a.reply(408),s._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),p&&(this._timers.expiresTimer=setTimeout(function(){s._status===J.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),s._failed("system",null,oe.causes.EXPIRES))},p)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,t&&t(this),this._newRTCSession("remote",a),this._status!==J.STATUS_TERMINATED&&(a.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("answer()");var s=this._request,p=Fe.cloneArray(t.extraHeaders),h=Fe.cloneObject(t.mediaConstraints),d=t.mediaStream||null,g=Fe.cloneObject(t.pcConfig,{iceServers:[]}),v=t.rtcConstraints||null,E=t.rtcAnswerConstraints||null,S=Fe.cloneObject(t.rtcOfferConstraints),C,I=!1,w=!1,F=!1,L=!1;if(this._rtcAnswerConstraints=E,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new on.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==J.STATUS_WAITING_FOR_ANSWER)throw new on.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Fe.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES),this._status=J.STATUS_ANSWERED,!this._createDialog(s,"UAS")){s.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),p.unshift("Contact: ".concat(this._contact));var ie=s.parseSDP();Array.isArray(ie.media)||(ie.media=[ie.media]);var N=os(ie.media),H;try{for(N.s();!(H=N.n()).done;){var ve=H.value;ve.type==="audio"&&(I=!0,(!ve.direction||ve.direction==="sendrecv")&&(F=!0)),ve.type==="video"&&(w=!0,(!ve.direction||ve.direction==="sendrecv")&&(L=!0))}}catch($){N.e($)}finally{N.f()}if(d&&h.audio===!1){C=d.getAudioTracks();var me=os(C),M;try{for(me.s();!(M=me.n()).done;){var D=M.value;d.removeTrack(D)}}catch($){me.e($)}finally{me.f()}}if(d&&h.video===!1){C=d.getVideoTracks();var j=os(C),V;try{for(j.s();!(V=j.n()).done;){var Y=V.value;d.removeTrack(Y)}}catch($){j.e($)}finally{j.f()}}!d&&h.audio===void 0&&(h.audio=F),!d&&h.video===void 0&&(h.video=L),!d&&!I&&!S.offerToReceiveAudio&&(h.audio=!1),!d&&!w&&!S.offerToReceiveVideo&&(h.video=!1),this._createRTCConnection(g,v),Promise.resolve().then(function(){if(d)return d;if(h.audio||h.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(h).catch(function($){throw a._status===J.STATUS_TERMINATED?new Error("terminated"):(s.reply(480),a._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),K.warn('emit "getusermediafailed" [error:%o]',$),a.emit("getusermediafailed",$),new Error("getUserMedia() failed"))})}).then(function($){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=$,$&&$.getTracks().forEach(function(z){a._connection.addTrack(z,$)})}).then(function(){if(!a._late_sdp){var $={originator:"remote",type:"offer",sdp:s.body};K.debug('emit "sdp"'),a.emit("sdp",$);var z=new RTCSessionDescription({type:"offer",sdp:$.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(z)}).catch(function(U){throw s.reply(488),a._failed("system",null,oe.causes.WEBRTC_ERROR),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',U),a.emit("peerconnection:setremotedescriptionfailed",U),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(s),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw s.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",E).catch(function(){throw s.reply(500),new Error("_createLocalDescription() failed")})}).then(function($){if(a._status===J.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(s,p),s.reply(200,null,p,$,function(){a._status=J.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(s,$),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,oe.causes.CONNECTION_ERROR)})}).catch(function($){a._status!==J.STATUS_TERMINATED&&K.warn($)})}},{key:"terminate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("terminate()");var s=t.cause||oe.causes.BYE,p=Fe.cloneArray(t.extraHeaders),h=t.body,d,g=t.status_code,v=t.reason_phrase;if(this._status===J.STATUS_TERMINATED)throw new on.InvalidStateError(this._status);switch(this._status){case J.STATUS_NULL:case J.STATUS_INVITE_SENT:case J.STATUS_1XX_RECEIVED:if(K.debug("canceling session"),g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));g&&(v=v||oe.REASON_PHRASE[g]||"",d="SIP ;cause=".concat(g,' ;text="').concat(v,'"')),this._status===J.STATUS_NULL||this._status===J.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=d):this._status===J.STATUS_1XX_RECEIVED&&this._request.cancel(d),this._status=J.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case J.STATUS_WAITING_FOR_ANSWER:case J.STATUS_ANSWERED:if(K.debug("rejecting session"),g=g||480,g<300||g>=700)throw new TypeError("Invalid status_code: ".concat(g));this._request.reply(g,v,p,h),this._failed("local",null,oe.causes.REJECTED);break;case J.STATUS_WAITING_FOR_ACK:case J.STATUS_CONFIRMED:if(K.debug("terminating session"),v=t.reason_phrase||oe.REASON_PHRASE[g]||"",g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));if(g&&p.push("Reason: SIP ;cause=".concat(g,'; text="').concat(v,'"')),this._status===J.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==sc.C.STATUS_TERMINATED){var E=this._dialog;this.receiveRequest=function(S){var C=S.method;C===oe.ACK&&(a.sendRequest(oe.BYE,{extraHeaders:p,body:h}),E.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===sc.C.STATUS_TERMINATED&&(a.sendRequest(oe.BYE,{extraHeaders:p,body:h}),E.terminate())}),this._ended("local",null,s),this._dialog=E,this._ua.newDialog(E)}else this.sendRequest(oe.BYE,{extraHeaders:p,body:h}),this._ended("local",null,s)}}},{key:"sendDTMF",value:function(a){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};K.debug("sendDTMF() | tones: %s",a);var s=0,p=t.duration||null,h=t.interToneGap||null,d=t.transportType||oe.DTMF_TRANSPORT.INFO;if(a===void 0)throw new TypeError("Not enough arguments");if(this._status!==J.STATUS_CONFIRMED&&this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_1XX_RECEIVED)throw new on.InvalidStateError(this._status);if(d!==oe.DTMF_TRANSPORT.INFO&&d!==oe.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(d));if(typeof a=="number"&&(a=a.toString()),!a||typeof a!="string"||!a.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(a));if(p&&!Fe.isDecimal(p))throw new TypeError("Invalid tone duration: ".concat(p));if(p?p<It.C.MIN_DURATION?(K.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(It.C.MIN_DURATION," milliseconds")),p=It.C.MIN_DURATION):p>It.C.MAX_DURATION?(K.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(It.C.MAX_DURATION," milliseconds")),p=It.C.MAX_DURATION):p=Math.abs(p):p=It.C.DEFAULT_DURATION,t.duration=p,h&&!Fe.isDecimal(h))throw new TypeError("Invalid interToneGap: ".concat(h));if(h?h<It.C.MIN_INTER_TONE_GAP?(K.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(It.C.MIN_INTER_TONE_GAP," milliseconds")),h=It.C.MIN_INTER_TONE_GAP):h=Math.abs(h):h=It.C.DEFAULT_INTER_TONE_GAP,d===oe.DTMF_TRANSPORT.RFC2833){var g=this._getDTMFRTPSender();g&&(a=g.toneBuffer+a,g.insertDTMF(a,p,h));return}if(this._tones){this._tones+=a;return}this._tones=a,v.call(this);function v(){var E=this,S;if(this._status===J.STATUS_TERMINATED||!this._tones||s>=this._tones.length){this._tones=null;return}var C=this._tones[s];if(s+=1,C===",")S=2e3;else{var I=new It(this);t.eventHandlers={onFailed:function(){E._tones=null}},I.send(C,t),S=p+h}setTimeout(v.bind(this),S)}}},{key:"sendInfo",value:function(a,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(K.debug("sendInfo()"),this._status!==J.STATUS_CONFIRMED&&this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_1XX_RECEIVED)throw new on.InvalidStateError(this._status);var p=new nc(this);p.send(a,t,s)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};K.debug("mute()");var t=!1,s=!1;this._audioMuted===!1&&a.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(s=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||s===!0)&&this._onmute({audio:t,video:s})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};K.debug("unmute()");var t=!1,s=!1;this._audioMuted===!0&&a.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(s=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||s===!0)&&this._onunmute({audio:t,video:s})}},{key:"hold",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;if(K.debug("hold()"),this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var p={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:p,extraHeaders:t.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;if(K.debug("unhold()"),this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var p={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:p,extraHeaders:t.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;K.debug("renegotiate()");var p=t.rtcOfferConstraints||null;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var h={succeeded:function(){s&&s()},failed:function(){a.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,rtcOfferConstraints:p,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:h,rtcOfferConstraints:p,extraHeaders:t.extraHeaders}),!0}},{key:"refer",value:function(a,t){var s=this;K.debug("refer()");var p=a;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(p));var h=new wd(this);h.sendRefer(a,t);var d=h.id;return this._referSubscribers[d]=h,h.on("requestFailed",function(){delete s._referSubscribers[d]}),h.on("accepted",function(){delete s._referSubscribers[d]}),h.on("failed",function(){delete s._referSubscribers[d]}),h}},{key:"sendRequest",value:function(a,t){return K.debug("sendRequest()"),this._dialog.sendRequest(a,t)}},{key:"receiveRequest",value:function(a){var t=this;if(K.debug("receiveRequest()"),a.method===oe.CANCEL)(this._status===J.STATUS_WAITING_FOR_ANSWER||this._status===J.STATUS_ANSWERED)&&(this._status=J.STATUS_CANCELED,this._request.reply(487),this._failed("remote",a,oe.causes.CANCELED));else switch(a.method){case oe.ACK:if(this._status!==J.STATUS_WAITING_FOR_ACK)return;if(this._status=J.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!a.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}var s={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",s);var p=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._connection.setRemoteDescription(p)}).then(function(){t._is_confirmed||t._confirmed("remote",a)}).catch(function(d){t.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',d),t.emit("peerconnection:setremotedescriptionfailed",d)})}else this._is_confirmed||this._confirmed("remote",a);break;case oe.BYE:this._status===J.STATUS_CONFIRMED||this._status===J.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,oe.causes.BYE)):this._status===J.STATUS_INVITE_RECEIVED||this._status===J.STATUS_WAITING_FOR_ANSWER?(a.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",a,oe.causes.BYE)):a.reply(403,"Wrong Status");break;case oe.INVITE:this._status===J.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case oe.INFO:if(this._status===J.STATUS_1XX_RECEIVED||this._status===J.STATUS_WAITING_FOR_ANSWER||this._status===J.STATUS_ANSWERED||this._status===J.STATUS_WAITING_FOR_ACK||this._status===J.STATUS_CONFIRMED){var h=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;h&&h.match(/^application\/dtmf-relay/i)?new It(this).init_incoming(a):h!==void 0?new nc(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===J.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case oe.REFER:this._status===J.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===J.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){K.warn("onTransportError()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){K.warn("onRequestTimeout()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){K.warn("onDialogError()"),this._status!==J.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){K.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){K.debug("newInfo()"),this.emit("newInfo",a)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(K.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(K.debug("_isReadyToReOffer() | session not established yet"),!1):(K.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(K.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(K.debug("close() | closing local MediaStream"),Fe.closeMediaStream(this._localMediaStream)),this._status!==J.STATUS_TERMINATED){if(this._status=J.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(p){K.warn("close() | error closing the RTCPeerConnection: %o",p)}for(var a in this._timers)Object.prototype.hasOwnProperty.call(this._timers,a)&&clearTimeout(this._timers[a]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(var s in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,s)&&delete this._referSubscribers[s];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,t){var s=yi.T1;function p(){this._status===J.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],t),s<yi.T2&&(s=s*2,s>yi.T2&&(s=yi.T2)),this._timers.invite2xxTimer=setTimeout(p.bind(this),s))}this._timers.invite2xxTimer=setTimeout(p.bind(this),s)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===J.STATUS_WAITING_FOR_ACK&&(K.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(oe.BYE),a._ended("remote",null,oe.causes.NO_ACK))},yi.TIMER_H)}},{key:"_createRTCConnection",value:function(a,t){var s=this;this._connection=new RTCPeerConnection(a,t),this._connection.addEventListener("iceconnectionstatechange",function(){var p=s._connection.iceConnectionState;p==="failed"&&s.terminate({cause:oe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:oe.causes.RTP_TIMEOUT})}),K.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,t){var s=this;if(K.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var p=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?p.createOffer(t).catch(function(h){return K.warn('emit "peerconnection:createofferfailed" [error:%o]',h),s.emit("peerconnection:createofferfailed",h),Promise.reject(h)}):p.createAnswer(t).catch(function(h){return K.warn('emit "peerconnection:createanswerfailed" [error:%o]',h),s.emit("peerconnection:createanswerfailed",h),Promise.reject(h)})}).then(function(h){return p.setLocalDescription(h).catch(function(d){return s._rtcReady=!0,K.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',d),s.emit("peerconnection:setlocaldescriptionfailed",d),Promise.reject(d)})}).then(function(){var h=t&&t.iceRestart;if(p.iceGatheringState==="complete"&&!h||p.iceGatheringState==="gathering"&&s._iceReady){s._rtcReady=!0;var d={originator:"local",type:a,sdp:p.localDescription.sdp};return K.debug('emit "sdp"'),s.emit("sdp",d),Promise.resolve(d.sdp)}return new Promise(function(g){var v=!1,E,S;s._iceReady=!1;var C=function(){p.removeEventListener("icecandidate",E),p.removeEventListener("icegatheringstatechange",S),v=!0,s._rtcReady=!0,s._iceReady=!0;var w={originator:"local",type:a,sdp:p.localDescription.sdp};K.debug('emit "sdp"'),s.emit("sdp",w),g(w.sdp)};p.addEventListener("icecandidate",E=function(w){var F=w.candidate;F?s.emit("icecandidate",{candidate:F,ready:C}):v||C()}),p.addEventListener("icegatheringstatechange",S=function(){p.iceGatheringState==="complete"&&!v&&C()})})})}},{key:"_createDialog",value:function(a,t,s){var p=t==="UAS"?a.to_tag:a.from_tag,h=t==="UAS"?a.from_tag:a.to_tag,d=a.call_id+p+h,g=this._earlyDialogs[d];if(s)return g?!0:(g=new bl(this,a,t,bl.C.STATUS_EARLY),g.error?(K.debug(g.error),this._failed("remote",a,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=g,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,g)return g.update(a,t),this._dialog=g,delete this._earlyDialogs[d],!0;var v=new bl(this,a,t);return v.error?(K.debug(v.error),this._failed("remote",a,oe.causes.INTERNAL_ERROR),!1):(this._dialog=v,!0)}},{key:"_receiveReinvite",value:function(a){var t=this;K.debug("receiveReinvite()");var s=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,p={request:a,callback:void 0,reject:d.bind(this)},h=!1;function d(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};h=!0;var E=v.status_code||403,S=v.reason_phrase||"",C=Fe.cloneArray(v.extraHeaders);if(this._status!==J.STATUS_CONFIRMED)return!1;if(E<300||E>=700)throw new TypeError("Invalid status_code: ".concat(E));a.reply(E,S,C)}if(this.emit("reinvite",p),h)return;if(this._late_sdp=!1,!a.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._createLocalDescription("offer",t._rtcOfferConstraints)}).then(function(v){g.call(t,v)}).catch(function(){a.reply(500)});return}if(s!=="application/sdp"){K.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(v){t._status!==J.STATUS_TERMINATED&&g.call(t,v)}).catch(function(v){K.warn(v)});function g(v){var E=this,S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),this._late_sdp&&(v=this._mangleOffer(v)),a.reply(200,null,S,v,function(){E._status=J.STATUS_WAITING_FOR_ACK,E._setInvite2xxTimer(a,v),E._setACKTimer()}),typeof p.callback=="function"&&p.callback()}}},{key:"_receiveUpdate",value:function(a){var t=this;K.debug("receiveUpdate()");var s=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,p={request:a,callback:void 0,reject:d.bind(this)},h=!1;function d(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};h=!0;var E=v.status_code||403,S=v.reason_phrase||"",C=Fe.cloneArray(v.extraHeaders);if(this._status!==J.STATUS_CONFIRMED)return!1;if(E<300||E>=700)throw new TypeError("Invalid status_code: ".concat(E));a.reply(E,S,C)}if(this.emit("update",p),h)return;if(!a.body){g.call(this,null);return}if(s!=="application/sdp"){K.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(v){t._status!==J.STATUS_TERMINATED&&g.call(t,v)}).catch(function(v){K.warn(v)});function g(v){var E=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,E),a.reply(200,null,E,v),typeof p.callback=="function"&&p.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var t=this;K.debug("_processInDialogSdpOffer()");var s=a.parseSDP(),p=!1,h=os(s.media),d;try{for(h.s();!(d=h.n()).done;){var g=d.value;if(wl.indexOf(g.type)!==-1){var v=g.direction||s.direction||"sendrecv";if(v==="sendonly"||v==="inactive")p=!0;else{p=!1;break}}}}catch(C){h.e(C)}finally{h.f()}var E={originator:"remote",type:"offer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",E);var S=new RTCSessionDescription({type:"offer",sdp:E.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");return t._connection.setRemoteDescription(S).catch(function(C){throw a.reply(488),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),t.emit("peerconnection:setremotedescriptionfailed",C),C})}).then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");t._remoteHold===!0&&p===!1?(t._remoteHold=!1,t._onunhold("remote")):t._remoteHold===!1&&p===!0&&(t._remoteHold=!0,t._onhold("remote"))}).then(function(){if(t._status===J.STATUS_TERMINATED)throw new Error("terminated");return t._createLocalDescription("answer",t._rtcAnswerConstraints).catch(function(C){throw a.reply(500),K.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',C),C})}).catch(function(C){K.warn("_processInDialogSdpOffer() failed [error: %o]",C)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var t=this;if(K.debug("receiveRefer()"),!a.refer_to){K.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==oe.SIP){K.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var s=new bd(this,a.cseq);K.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(g,v){p.call(t,g,v)},reject:function(){h.call(t)}});function p(d){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(d=typeof d=="function"?d:null,this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;var v=new n(this._ua);if(v.on("progress",function(S){var C=S.response;s.notify(C.status_code,C.reason_phrase)}),v.on("accepted",function(S){var C=S.response;s.notify(C.status_code,C.reason_phrase)}),v.on("_failed",function(S){var C=S.message,I=S.cause;C?s.notify(C.status_code,C.reason_phrase):s.notify(487,I)}),a.refer_to.uri.hasHeader("replaces")){var E=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));g.extraHeaders=Fe.cloneArray(g.extraHeaders),g.extraHeaders.push("Replaces: ".concat(E))}v.connect(a.refer_to.uri.toAor(),g,d)}function h(){s.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(K.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var t,s;if(a.event.params&&a.event.params.id)t=a.event.params.id,s=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)s=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!s){a.reply(481,"Subscription does not exist");return}s.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var t=this;K.debug("receiveReplaces()");function s(h){var d=this;if(this._status!==J.STATUS_WAITING_FOR_ACK&&this._status!==J.STATUS_CONFIRMED)return!1;var g=new n(this._ua);g.on("confirmed",function(){d.terminate()}),g.init_incoming(a,h)}function p(){K.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(d){s.call(t,d)},reject:function(){p.call(t)}})}},{key:"_sendInitialRequest",value:function(a,t,s){var p=this;console.log("rtcOfferConstraints",t);var h=new Id(this._ua,this._request,{onRequestTimeout:function(){p.onRequestTimeout()},onTransportError:function(){p.onTransportError()},onAuthenticated:function(g){p._request=g},onReceiveResponse:function(g){p._receiveInviteResponse(g)}});Promise.resolve().then(function(){if(s)return s;if(a.audio||a.video)return p._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(d){throw p._status===J.STATUS_TERMINATED?new Error("terminated"):(p._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),K.warn('emit "getusermediafailed" [error:%o]',d),p.emit("getusermediafailed",d),d)})}).then(function(d){if(p._status===J.STATUS_TERMINATED)throw new Error("terminated");return p._localMediaStream=d,d&&d.getTracks().forEach(function(g){p._connection.addTrack(g,d)}),p._connecting(p._request),p._createLocalDescription("offer",t).catch(function(g){throw p._failed("local",null,oe.causes.WEBRTC_ERROR),g})}).then(function(d){if(p._is_canceled||p._status===J.STATUS_TERMINATED)throw new Error("terminated");p._request.body=d,p._status=J.STATUS_INVITE_SENT,K.debug('emit "sending" [request:%o]',p._request),p.emit("sending",{request:p._request}),h.send()}).catch(function(d){p._status!==J.STATUS_TERMINATED&&K.warn(d)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(t){return t.track&&t.track.kind==="audio"});if(!(a&&a.dtmf)){K.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var t=this;if(K.debug("receiveInviteResponse()"),this._dialog&&a.status_code>=200&&a.status_code<=299)if(this._dialog.id.call_id===a.call_id&&this._dialog.id.local_tag===a.from_tag&&this._dialog.id.remote_tag===a.to_tag){this.sendRequest(oe.ACK);return}else{var s=new bl(this,a,"UAC");if(s.error!==void 0){K.debug(s.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this._is_canceled){a.status_code>=100&&a.status_code<200?this._request.cancel(this._cancel_reason):a.status_code>=200&&a.status_code<299&&this._acceptAndTerminate(a);return}if(!(this._status!==J.STATUS_INVITE_SENT&&this._status!==J.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(a.status_code):this._status=J.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(a.status_code):{if(!a.to_tag){K.debug("1xx response received without to tag");break}if(a.hasHeader("contact")&&!this._createDialog(a,"UAC",!0))break;if(this._status=J.STATUS_1XX_RECEIVED,!a.body){this._progress("remote",a);break}var p={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",p);var h=new RTCSessionDescription({type:"answer",sdp:p.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return t._connection.setRemoteDescription(h)}).then(function(){return t._progress("remote",a)}).catch(function(E){K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),t.emit("peerconnection:setremotedescriptionfailed",E)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=J.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,oe.causes.MISSING_SDP),this._failed("remote",a,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var d={originator:"remote",type:"answer",sdp:a.body};K.debug('emit "sdp"'),this.emit("sdp",d);var g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(t._connection.signalingState==="stable")return t._connection.createOffer(t._rtcOfferConstraints).then(function(E){return t._connection.setLocalDescription(E)}).catch(function(E){t._acceptAndTerminate(a,500,E.toString()),t._failed("local",a,oe.causes.WEBRTC_ERROR)})}).then(function(){t._connection.setRemoteDescription(g).then(function(){t._handleSessionTimersInIncomingResponse(a),t._accepted("remote",a),t.sendRequest(oe.ACK),t._confirmed("local",null)}).catch(function(E){t._acceptAndTerminate(a,488,"Not Acceptable Here"),t._failed("remote",a,oe.causes.BAD_MEDIA_DESCRIPTION),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),t.emit("peerconnection:setremotedescriptionfailed",E)})});break}default:{var v=Fe.sipErrorCause(a.status_code);this._failed("remote",a,v)}}}},{key:"_sendReinvite",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("sendReinvite()");var s=Fe.cloneArray(t.extraHeaders),p=Fe.cloneObject(t.eventHandlers),h=t.rtcOfferConstraints||this._rtcOfferConstraints||null,d=!1;s.push("Contact: ".concat(this._contact)),s.push("Content-Type: application/sdp"),this._sessionTimers.running&&s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",h)}).then(function(E){E=a._mangleOffer(E);var S={originator:"local",type:"offer",sdp:E};K.debug('emit "sdp"'),a.emit("sdp",S),a.sendRequest(oe.INVITE,{extraHeaders:s,body:E,eventHandlers:{onSuccessResponse:function(I){g.call(a,I),d=!0},onErrorResponse:function(I){v.call(a,I)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){v()});function g(E){var S=this;if(this._status!==J.STATUS_TERMINATED&&(this.sendRequest(oe.ACK),!d)){if(this._handleSessionTimersInIncomingResponse(E),E.body){if(!E.hasHeader("Content-Type")||E.getHeader("Content-Type").toLowerCase()!=="application/sdp"){v.call(this);return}}else{v.call(this);return}var C={originator:"remote",type:"answer",sdp:E.body};K.debug('emit "sdp"'),this.emit("sdp",C);var I=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return S._connection.setRemoteDescription(I)}).then(function(){p.succeeded&&p.succeeded(E)}).catch(function(w){v.call(S),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',w),S.emit("peerconnection:setremotedescriptionfailed",w)})}}function v(E){p.failed&&p.failed(E)}}},{key:"_sendUpdate",value:function(){var a=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};K.debug("sendUpdate()");var s=Fe.cloneArray(t.extraHeaders),p=Fe.cloneObject(t.eventHandlers),h=t.rtcOfferConstraints||this._rtcOfferConstraints||null,d=t.sdpOffer||!1,g=!1;s.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),d?(s.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",h)}).then(function(S){S=a._mangleOffer(S);var C={originator:"local",type:"offer",sdp:S};K.debug('emit "sdp"'),a.emit("sdp",C),a.sendRequest(oe.UPDATE,{extraHeaders:s,body:S,eventHandlers:{onSuccessResponse:function(w){v.call(a,w),g=!0},onErrorResponse:function(w){E.call(a,w)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){E.call(a)})):this.sendRequest(oe.UPDATE,{extraHeaders:s,eventHandlers:{onSuccessResponse:function(C){v.call(a,C)},onErrorResponse:function(C){E.call(a,C)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function v(S){var C=this;if(this._status!==J.STATUS_TERMINATED&&!g)if(this._handleSessionTimersInIncomingResponse(S),d){if(S.body){if(!S.hasHeader("Content-Type")||S.getHeader("Content-Type").toLowerCase()!=="application/sdp"){E.call(this);return}}else{E.call(this);return}var I={originator:"remote",type:"answer",sdp:S.body};K.debug('emit "sdp"'),this.emit("sdp",I);var w=new RTCSessionDescription({type:"answer",sdp:I.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return C._connection.setRemoteDescription(w)}).then(function(){p.succeeded&&p.succeeded(S)}).catch(function(F){E.call(C),K.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',F),C.emit("peerconnection:setremotedescriptionfailed",F)})}else p.succeeded&&p.succeeded(S)}function E(S){p.failed&&p.failed(S)}}},{key:"_acceptAndTerminate",value:function(a,t,s){K.debug("acceptAndTerminate()");var p=[];t&&(s=s||oe.REASON_PHRASE[t]||"",p.push("Reason: SIP ;cause=".concat(t,'; text="').concat(s,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(oe.ACK),this.sendRequest(oe.BYE,{extraHeaders:p})),this._status=J.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=tc.parse(a),this._localHold&&!this._remoteHold){K.debug("mangleOffer() | me on hold, mangling offer");var t=os(a.media),s;try{for(t.s();!(s=t.n()).done;){var p=s.value;wl.indexOf(p.type)!==-1&&(p.direction?p.direction==="sendrecv"?p.direction="sendonly":p.direction==="recvonly"&&(p.direction="inactive"):p.direction="sendonly")}}catch(C){t.e(C)}finally{t.f()}}else if(this._localHold&&this._remoteHold){K.debug("mangleOffer() | both on hold, mangling offer");var h=os(a.media),d;try{for(h.s();!(d=h.n()).done;){var g=d.value;wl.indexOf(g.type)!==-1&&(g.direction="inactive")}}catch(C){h.e(C)}finally{h.f()}}else if(this._remoteHold){K.debug("mangleOffer() | remote on hold, mangling offer");var v=os(a.media),E;try{for(v.s();!(E=v.n()).done;){var S=E.value;wl.indexOf(S.type)!==-1&&(S.direction?S.direction==="sendrecv"?S.direction="recvonly":S.direction==="recvonly"&&(S.direction="inactive"):S.direction="recvonly")}}catch(C){v.e(C)}finally{v.f()}}return tc.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,t=!0;(this._localHold||this._remoteHold)&&(a=!1,t=!1),this._audioMuted&&(a=!1),this._videoMuted&&(t=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!t)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,t){if(this._sessionTimers.enabled){var s;a.session_expires&&a.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,s=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uas"),t.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(s)),this._sessionTimers.refresher=s==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var t;a.session_expires&&a.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,t=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,t="uac"),this._sessionTimers.refresher=t==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){a._status!==J.STATUS_TERMINATED&&a._isReadyToReOffer()&&(K.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===oe.UPDATE?a._sendUpdate():a._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(function(){a._status!==J.STATUS_TERMINATED&&(K.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:oe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}},{key:"_toggleMuteAudio",value:function(a){var t=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="audio"}),s=os(t),p;try{for(s.s();!(p=s.n()).done;){var h=p.value;h.track.enabled=!a}}catch(d){s.e(d)}finally{s.f()}}},{key:"_toggleMuteVideo",value:function(a){var t=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="video"}),s=os(t),p;try{for(s.s();!(p=s.n()).done;){var h=p.value;h.track.enabled=!a}}catch(d){s.e(d)}finally{s.f()}}},{key:"_newRTCSession",value:function(a,t){K.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:t})}},{key:"_connecting",value:function(a){K.debug("session connecting"),K.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,t){K.debug("session progress"),K.debug('emit "progress"'),this.emit("progress",{originator:a,response:t||null})}},{key:"_accepted",value:function(a,t){K.debug("session accepted"),this._start_time=new Date,K.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:t||null})}},{key:"_confirmed",value:function(a,t){K.debug("session confirmed"),this._is_confirmed=!0,K.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:t||null})}},{key:"_ended",value:function(a,t,s){K.debug("session ended"),this._end_time=new Date,this._close(),K.debug('emit "ended"'),this.emit("ended",{originator:a,message:t||null,cause:s})}},{key:"_failed",value:function(a,t,s){K.debug("session failed"),K.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:t||null,cause:s}),this._close(),K.debug('emit "failed"'),this.emit("failed",{originator:a,message:t||null,cause:s})}},{key:"_onhold",value:function(a){K.debug("session onhold"),this._setLocalMediaStatus(),K.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){K.debug("session onunhold"),this._setLocalMediaStatus(),K.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var t=a.audio,s=a.video;K.debug("session onmute"),this._setLocalMediaStatus(),K.debug('emit "muted"'),this.emit("muted",{audio:t,video:s})}},{key:"_onunmute",value:function(a){var t=a.audio,s=a.video;K.debug("session onunmute"),this._setLocalMediaStatus(),K.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:s})}},{key:"C",get:function(){return J}},{key:"causes",get:function(){return oe.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(a){this._data=a}},{key:"status",get:function(){return this._status}}]),n}(Cd);function no(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?no=function(n){return typeof n}:no=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},no(c)}function Dd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function ic(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Nd(c,r,n){return r&&ic(c.prototype,r),n&&ic(c,n),c}function Ud(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&Ba(c,r)}function Ba(c,r){return Ba=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ba(c,r)}function Pd(c){var r=xd();return function(){var o=po(c),a;if(r){var t=po(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return kd(this,a)}}function kd(c,r){return r&&(no(r)==="object"||typeof r=="function")?r:Md(c)}function Md(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function xd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function po(c){return po=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},po(c)}var Ld=pt.EventEmitter,$d=it,sa=tt,Hd=_s,Si=Et(),Fd=Xi,lc=xs,qd=Ls(),Ol=new $d("Message"),Vd=function(c){Ud(n,c);var r=Pd(n);function n(o){var a;return Dd(this,n),a=r.call(this),a._ua=o,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Nd(n,[{key:"send",value:function(a,t){var s=this,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},h=a;if(a===void 0||t===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=Si.cloneArray(p.extraHeaders),g=Si.cloneObject(p.eventHandlers),v=p.contentType||"text/plain",E={};p.fromUserName&&(E.from_uri=new qd("sip",p.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),p.fromDisplayName&&(E.from_display_name=p.fromDisplayName);for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&this.on(S,g[S]);d.push("Content-Type: ".concat(v)),this._request=new Hd.OutgoingRequest(sa.MESSAGE,a,this._ua,E,d),t&&(this._request.body=t);var C=new Fd(this._ua,this._request,{onRequestTimeout:function(){s._onRequestTimeout()},onTransportError:function(){s._onTransportError()},onReceiveResponse:function(w){s._receiveResponse(w)}});this._newMessage("local",this._request),C.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newMessage("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Si.cloneArray(a.extraHeaders),s=a.body;if(this._direction!=="incoming")throw new lc.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,t,s)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=a.status_code||480,s=a.reason_phrase,p=Si.cloneArray(a.extraHeaders),h=a.body;if(this._direction!=="incoming")throw new lc.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(t<300||t>=700)throw new TypeError("Invalid status_code: ".concat(t));this._is_replied=!0,this._request.reply(t,s,p,h)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var t=Si.sipErrorCause(a.status_code);this._failed("remote",a,t);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,sa.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,sa.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,t){a==="remote"?(this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from):a==="local"&&(this._direction="outgoing",this._local_identity=t.from,this._remote_identity=t.to),this._ua.newMessage(this,{originator:a,message:this,request:t})}},{key:"_failed",value:function(a,t,s){Ol.debug("MESSAGE failed"),this._close(),Ol.debug('emit "failed"'),this.emit("failed",{originator:a,response:t||null,cause:s})}},{key:"_succeeded",value:function(a,t){Ol.debug("MESSAGE succeeded"),this._close(),Ol.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:t})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Ld);function ro(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ro=function(n){return typeof n}:ro=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},ro(c)}function jd(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function oc(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Bd(c,r,n){return r&&oc(c.prototype,r),n&&oc(c,n),c}function Gd(c,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(r&&r.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),r&&Ga(c,r)}function Ga(c,r){return Ga=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ga(c,r)}function Kd(c){var r=zd();return function(){var o=mo(c),a;if(r){var t=mo(this).constructor;a=Reflect.construct(o,arguments,t)}else a=o.apply(this,arguments);return Wd(this,a)}}function Wd(c,r){return r&&(ro(r)==="object"||typeof r=="function")?r:Yd(c)}function Yd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function zd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function mo(c){return mo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},mo(c)}var Jd=pt.EventEmitter,Xd=it,na=tt,Qd=_s,Ci=Et(),Zd=Xi,ac=xs,Dl=new Xd("Options"),ep=function(c){Gd(n,c);var r=Kd(n);function n(o){var a;return jd(this,n),a=r.call(this),a._ua=o,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Bd(n,[{key:"send",value:function(a,t){var s=this,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},h=a;if(a===void 0)throw new TypeError("A target is required for OPTIONS");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=Ci.cloneArray(p.extraHeaders),g=Ci.cloneObject(p.eventHandlers),v=p.contentType||"application/sdp";for(var E in g)Object.prototype.hasOwnProperty.call(g,E)&&this.on(E,g[E]);d.push("Content-Type: ".concat(v)),this._request=new Qd.OutgoingRequest(na.OPTIONS,a,this._ua,null,d),t&&(this._request.body=t);var S=new Zd(this._ua,this._request,{onRequestTimeout:function(){s._onRequestTimeout()},onTransportError:function(){s._onTransportError()},onReceiveResponse:function(I){s._receiveResponse(I)}});this._newOptions("local",this._request),S.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newOptions("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Ci.cloneArray(a.extraHeaders),s=a.body;if(this._direction!=="incoming")throw new ac.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,t,s)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=a.status_code||480,s=a.reason_phrase,p=Ci.cloneArray(a.extraHeaders),h=a.body;if(this._direction!=="incoming")throw new ac.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(t<300||t>=700)throw new TypeError("Invalid status_code: ".concat(t));this._is_replied=!0,this._request.reply(t,s,p,h)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var t=Ci.sipErrorCause(a.status_code);this._failed("remote",a,t);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,na.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,na.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,t){a==="remote"?(this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from):a==="local"&&(this._direction="outgoing",this._local_identity=t.from,this._remote_identity=t.to),this._ua.newOptions(this,{originator:a,message:this,request:t})}},{key:"_failed",value:function(a,t,s){Dl.debug("OPTIONS failed"),this._close(),Dl.debug('emit "failed"'),this.emit("failed",{originator:a,response:t||null,cause:s})}},{key:"_succeeded",value:function(a,t){Dl.debug("OPTIONS succeeded"),this._close(),Dl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:t})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Jd),lu={},tp=it,ra=Et(),sp=Zt(),Ai=new tp("Socket");lu.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Ai.warn("undefined JsSIP.Socket instance"),!1;try{if(!ra.isString(c.url))throw Ai.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!ra.isString(c.via_transport))throw Ai.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(sp.parse(c.sip_uri,"SIP_URI")===-1)throw Ai.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(r){if(!ra.isFunction(c[r]))throw Ai.warn("missing or invalid JsSIP.Socket method: ".concat(r)),new Error("Missing or invalid JsSIP.Socket method: ".concat(r))})}catch{return!1}return!0};function np(c,r){if(!(c instanceof r))throw new TypeError("Cannot call a class as a function")}function uc(c,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function rp(c,r,n){return r&&uc(c.prototype,r),n&&uc(c,n),c}var ip=it,lp=lu,cc=tt,At=new ip("Transport"),Pt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:cc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:cc.CONNECTION_RECOVERY_MAX_INTERVAL}},op=function(){function c(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt.recovery_options;np(this,c),At.debug("new()"),this.status=Pt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(o){At.warn("cannot use TextDecoder: ".concat(o))}if(typeof r>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");r instanceof Array||(r=[r]),r.forEach(function(o){if(!lp.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:Pt.SOCKET_STATUS_READY})},this),this._getSocket()}return rp(c,[{key:"connect",value:function(){if(At.debug("connect()"),this.isConnected()){At.debug("Transport is already connected");return}else if(this.isConnecting()){At.debug("Transport is connecting");return}this.close_requested=!1,this.status=Pt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){At.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Pt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(n){if(At.debug("send()"),!this.isConnected())return At.warn("unable to send message, transport is not connected"),!1;var o=n.toString();return At.debug(`sending message:
51
51
 
52
52
  `.concat(o,`
53
53
  `)),this.socket.send(o)}},{key:"isConnected",value:function(){return this.status===Pt.STATUS_CONNECTED}},{key:"isConnecting",value:function(){return this.status===Pt.STATUS_CONNECTING}},{key:"_reconnect",value:function(){var n=this;this.recover_attempts+=1;var o=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);o<this.recovery_options.min_interval?o=this.recovery_options.min_interval:o>this.recovery_options.max_interval&&(o=this.recovery_options.max_interval),At.debug("reconnection attempt: ".concat(this.recover_attempts,". next connection attempt in ").concat(o," seconds")),this.recovery_timer=setTimeout(function(){!n.close_requested&&!(n.isConnected()||n.isConnecting())&&(n._getSocket(),n.connect())},o*1e3)}},{key:"_getSocket",value:function(){var n=[];if(this.sockets.forEach(function(a){a.status!==Pt.SOCKET_STATUS_ERROR&&(n.length===0?n.push(a):a.weight>n[0].weight?n=[a]:a.weight===n[0].weight&&n.push(a))}),n.length===0){this.sockets.forEach(function(a){a.status=Pt.SOCKET_STATUS_READY}),this._getSocket();return}var o=Math.floor(Math.random()*n.length);this.socket=n[o].socket}},{key:"_onConnect",value:function(){this.recover_attempts=0,this.status=Pt.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}},{key:"_onDisconnect",value:function(n,o,a){this.status=Pt.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:n,code:o,reason:a}),!this.close_requested&&(this.sockets.forEach(function(t){this.socket===t.socket&&(t.status=Pt.SOCKET_STATUS_ERROR)},this),this._reconnect(n))}},{key:"_onData",value:function(n){if(n===`\r
@@ -109,10 +109,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
109
109
  `,this.ua.configuration.extra_headers)for(const s of this.ua.configuration.extra_headers)a+=`${s.trim()}\r
110
110
  `;a+=`Content-Length: 0\r
111
111
  \r
112
- `,this.transport.send(a)}}class om extends Hf{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var ts={OutgoingRequest:Ao,InitialOutgoingInviteRequest:fu,IncomingRequest:lm,IncomingResponse:om};const am=lt,as=mt(),Ft=new am("DigestAuthentication");var Ff=class{constructor(r){this._credentials=r,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(r){switch(r){case"realm":return this._realm;case"ha1":return this._ha1;default:Ft.warn('get() | cannot get "%s" parameter',r);return}}authenticate({method:r,ruri:n,body:o},a,t=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!=="MD5")return Ft.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Ft.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Ft.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Ft.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Ft.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop)if(a.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(a.qop.indexOf("auth")>-1)this._qop="auth";else return Ft.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=r,this._uri=n,this._cnonce=t||as.createRandomToken(12),this._nc+=1;const s=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-s.length)+s,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=as.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let p,h;return this._qop==="auth"?(p=`${this._method}:${this._uri}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=auth [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${h}`)):this._qop==="auth-int"?(p=`${this._method}:${this._uri}:${as.calculateMD5(o||"")}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=auth-int [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${h}`)):this._qop===null&&(p=`${this._method}:${this._uri}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=null [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${h}`)),Ft.debug("authenticate() | response generated"),!0}toString(){const r=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return r.push(`algorithm=${this._algorithm}`),r.push(`username="${this._credentials.username}"`),r.push(`realm="${this._realm}"`),r.push(`nonce="${this._nonce}"`),r.push(`uri="${this._uri}"`),r.push(`response="${this._response}"`),this._opaque&&r.push(`opaque="${this._opaque}"`),this._qop&&(r.push(`qop=${this._qop}`),r.push(`cnonce="${this._cnonce}"`),r.push(`nc=${this._ncHex}`)),`Digest ${r.join(", ")}`}};const um=xt(Ff),us=500,cm=4e3,Nc=5e3;var qf={T1:us,T2:cm,T4:Nc,TIMER_B:64*us,TIMER_D:0*us,TIMER_F:64*us,TIMER_H:64*us,TIMER_I:0*us,TIMER_J:0*us,TIMER_K:0*Nc,TIMER_L:64*us,TIMER_M:64*us,PROVISIONAL_RESPONSE_INTERVAL:6e4};const Qi=pt.EventEmitter,Zi=lt,xi=De,Uc=ts,Qt=qf,Pc=new Zi("NonInviteClientTransaction"),kl=new Zi("InviteClientTransaction"),fm=new Zi("AckClientTransaction"),kc=new Zi("NonInviteServerTransaction"),Ml=new Zi("InviteServerTransaction"),ce={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class hm extends Qi{constructor(r,n,o,a){super(),this.type=ce.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=r,this.transport=n,this.request=o,this.eventHandlers=a;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t),this.ua.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}send(){this.stateChanged(ce.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},Qt.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){Pc.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){Pc.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(r){const n=r.status_code;if(n<200)switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(r);break}else switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(r),this.K=setTimeout(()=>{this.timer_K()},Qt.TIMER_K);break;case ce.STATUS_COMPLETED:break}}}class _m extends Qi{constructor(r,n,o,a){super(),this.type=ce.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=r,this.transport=n,this.request=o,this.eventHandlers=a,o.transaction=this;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t),this.ua.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}send(){this.stateChanged(ce.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},Qt.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ce.STATUS_ACCEPTED&&(kl.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){kl.debug(`Timer M expired for transaction ${this.id}`),this.state===ce.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){kl.debug(`Timer B expired for transaction ${this.id}`),this.state===ce.STATUS_CALLING&&(this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){kl.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(r){const n=new Uc.OutgoingRequest(xi.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",r.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},Qt.TIMER_D),this.transport.send(n)}cancel(r){if(this.state!==ce.STATUS_PROCEEDING)return;const n=new Uc.OutgoingRequest(xi.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",this.request.getHeader("to")),r&&n.setHeader("reason",r),this.transport.send(n)}receiveResponse(r){const n=r.status_code;if(n>=100&&n<=199)switch(this.state){case ce.STATUS_CALLING:this.stateChanged(ce.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(r);break}else if(n>=200&&n<=299)switch(this.state){case ce.STATUS_CALLING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},Qt.TIMER_M),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(r);break}else if(n>=300&&n<=699)switch(this.state){case ce.STATUS_CALLING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),this.sendACK(r),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_COMPLETED:this.sendACK(r);break}}}class dm extends Qi{constructor(r,n,o,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=n,this.request=o,this.eventHandlers=a;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t)}get C(){return ce}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){fm.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class pm extends Qi{constructor(r,n,o){super(),this.type=ce.NON_INVITE_SERVER,this.id=o.via_branch,this.ua=r,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=ce.STATUS_TRYING,r.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}timer_J(){kc.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,kc.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(r,n,o,a){if(r===100)switch(this.state){case ce.STATUS_TRYING:this.stateChanged(ce.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case ce.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(r>=200&&r<=699)switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(()=>{this.timer_J()},Qt.TIMER_J),this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break;case ce.STATUS_COMPLETED:break}}}class mm extends Qi{constructor(r,n,o){super(),this.type=ce.INVITE_SERVER,this.id=o.via_branch,this.ua=r,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=ce.STATUS_PROCEEDING,r.newTransaction(this),this.resendProvisionalTimer=null,o.reply(100)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}timer_H(){Ml.debug(`Timer H expired for transaction ${this.id}`),this.state===ce.STATUS_COMPLETED&&Ml.debug("ACK not received, dialog will be terminated"),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Ml.debug(`Timer L expired for transaction ${this.id}`),this.state===ce.STATUS_ACCEPTED&&(this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Ml.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(r,n,o,a){if(r>=100&&r<=199)switch(this.state){case ce.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(r>100&&r<=199&&this.state===ce.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},Qt.PROVISIONAL_RESPONSE_INTERVAL));else if(r>=200&&r<=299)switch(this.state){case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(()=>{this.timer_L()},Qt.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ce.STATUS_ACCEPTED:this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(r>=300&&r<=699)switch(this.state){case ce.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(ce.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},Qt.TIMER_H),o&&o()):(this.onTransportError(),a&&a());break}}}function gm({_transactions:c},r){let n;switch(r.method){case xi.INVITE:if(n=c.ist[r.via_branch],n){switch(n.state){case ce.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case ce.STATUS_ACCEPTED:break}return!0}break;case xi.ACK:if(n=c.ist[r.via_branch],n){if(n.state===ce.STATUS_ACCEPTED)return!1;if(n.state===ce.STATUS_COMPLETED)return n.state=ce.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},Qt.TIMER_I),!0}else return!1;break;case xi.CANCEL:return n=c.ist[r.via_branch],n?(r.reply_sl(200),n.state!==ce.STATUS_PROCEEDING):(r.reply_sl(481),!0);default:if(n=c.nist[r.via_branch],n){switch(n.state){case ce.STATUS_TRYING:break;case ce.STATUS_PROCEEDING:case ce.STATUS_COMPLETED:n.transport.send(n.last_response);break}return!0}break}}var ir={C:ce,NonInviteClientTransaction:hm,InviteClientTransaction:_m,AckClientTransaction:dm,NonInviteServerTransaction:pm,InviteServerTransaction:mm,checkTransaction:gm};const Li=xt(ir),vm=lt,Mc=De,Tm=Ff,pa=ir,Em=new vm("RequestSender"),ma={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var lr=class{constructor(r,n,o){this._ua=r,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in ma)Object.prototype.hasOwnProperty.call(ma,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ma[a]));r.status===r.C.STATUS_USER_CLOSED&&(this._method!==Mc.BYE||this._method!==Mc.ACK)&&this._eventHandlers.onTransportError()}send(){const r={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:n=>{this._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new pa.InviteClientTransaction(this._ua,this._ua.transport,this._request,r);break;case"ACK":this.clientTransaction=new pa.AckClientTransaction(this._ua,this._ua.transport,this._request,r);break;default:this.clientTransaction=new pa.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,r)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(r){let n,o;const a=r.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(r.status_code===401?(n=r.parseHeader("www-authenticate"),o="authorization"):(n=r.parseHeader("proxy-authenticate"),o="proxy-authorization"),!n){Em.debug(`${r.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(r);return}if(!this._challenged||!this._staled&&n.stale===!0){if(this._auth||(this._auth=new Tm({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,n)){this._eventHandlers.onReceiveResponse(r);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),n.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(o,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(r)}else this._eventHandlers.onReceiveResponse(r)}};const ym=xt(lr),Sm=lt,ga=mt(),an=De,xc=ts,Lc=lr,Ri=new Sm("Registrator"),xl=10;var Cm=class{constructor(r,n){this._reg_id=1,this._ua=r,this._transport=n,this._registrar=r.configuration.registrar_server,this._expires=r.configuration.register_expires,this._call_id=ga.createRandomToken(22),this._cseq=0,this._to_uri=r.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(r){Array.isArray(r)||(r=[]),this._extraHeaders=r.slice()}setExtraContactParams(r){r instanceof Object||(r={}),this._extraContactParams="";for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const o=r[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){Ri.debug("Register request in progress...");return}const r=this._extraHeaders.slice();r.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),r.push(`Expires: ${this._expires}`);const n=new xc.OutgoingRequest(an.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r),o=new Lc(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,an.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,an.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Ri.debug("no Contact header in response to REGISTER, response ignored");break}const t=a.headers.Contact.reduce((d,g)=>d.concat(g.parsed),[]);let s=t.find(d=>this._sipInstance===d.getParam("+sip.instance")&&this._reg_id===parseInt(d.getParam("reg-id")));if(s||(s=t.find(d=>d.uri.user===this._ua.contact.uri.user)),!s){Ri.debug("no Contact header pointing to us, response ignored");break}let p=s.getParam("expires");!p&&a.hasHeader("expires")&&(p=a.getHeader("expires")),p||(p=this._expires),p=Number(p),p<xl&&(p=xl);const h=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),s.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=s.getParam("temp-gruu").replace(/"/g,"")),s.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=s.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<xl&&(this._expires=xl),this.register()):(Ri.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,an.causes.SIP_FAILURE_CODE));break}default:{const t=ga.sipErrorCause(a.status_code);this._registrationFailure(a,t)}}}});this._registering=!0,o.send()}unregister(r={}){if(!this._registered){Ri.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();r.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),n.push("Expires: 0");const o=new xc.OutgoingRequest(an.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Lc(this._ua,o,{onRequestTimeout:()=>{this._unregistered(null,an.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,an.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:t=>{switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._unregistered(t);break;default:{const s=ga.sipErrorCause(t.status_code);this._unregistered(t,s)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(r,n){this._registering=!1,this._ua.registrationFailed({response:r||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:r||null,cause:n}))}_unregistered(r,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:r||null,cause:n||null})}};class Am extends Error{constructor(r,n){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=r,this.value=n,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class Rm extends Error{constructor(r){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=r,this.message=`Invalid status: ${r}`}}class Im extends Error{constructor(r){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=r}}class bm extends Error{constructor(r){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=r}}var ps={ConfigurationError:Am,InvalidStateError:Rm,NotSupportedError:Im,NotReadyError:bm};const wm=xt(ps),va=De,Ll=ir,Om=lr,Ta={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var Dm=class{constructor(r,n,o){this._dialog=r,this._ua=r._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(const a in Ta)Object.prototype.hasOwnProperty.call(Ta,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ta[a]))}get request(){return this._request}send(){const r=new Om(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:n=>{this._eventHandlers.onAuthenticated(n)},onReceiveResponse:n=>{this._receiveResponse(n)}});if(r.send(),(this._request.method===va.INVITE||this._request.method===va.UPDATE&&this._request.body)&&r.clientTransaction.state!==Ll.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(r.clientTransaction.state===Ll.C.STATUS_ACCEPTED||r.clientTransaction.state===Ll.C.STATUS_COMPLETED||r.clientTransaction.state===Ll.C.STATUS_TERMINATED)&&(r.clientTransaction.removeListener("stateChanged",n),this._dialog.uac_pending_reply=!1)};r.clientTransaction.on("stateChanged",n)}}_receiveResponse(r){r.status_code===408||r.status_code===481?this._eventHandlers.onDialogError(r):r.method===va.INVITE&&r.status_code===491?this._reattempt?r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r)}};const Nm=lt,$c=ts,Ds=De,Ii=ir,Um=Dm,Ea=mt(),ya=new Nm("Dialog"),Ns={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var Vf=class{static get C(){return Ns}constructor(r,n,o,a=Ns.STATUS_CONFIRMED){if(this._owner=r,this._ua=r._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!n.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};n instanceof $c.IncomingResponse&&(a=n.status_code<200?Ns.STATUS_EARLY:Ns.STATUS_CONFIRMED);const t=n.parseHeader("contact");o==="UAS"?(this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri,this._remote_target=t.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):o==="UAC"&&(this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri,this._remote_target=t.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),ya.debug(`new ${o} dialog created with status ${this._state===Ns.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(r){this._local_seqnum=r}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(r){this._uac_pending_reply=r}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ns.STATUS_TERMINATED}update(r,n){this._state=Ns.STATUS_CONFIRMED,ya.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=r.getHeaders("record-route").reverse())}terminate(){ya.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ns.STATUS_TERMINATED}sendRequest(r,n={}){const o=Ea.cloneArray(n.extraHeaders),a=Ea.cloneObject(n.eventHandlers),t=n.body||null,s=this._createRequest(r,o,t);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Um(this,s,a).send(),s}receiveRequest(r){this._checkInDialogRequest(r)&&(r.method===Ds.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:r.method===Ds.INVITE&&(this._ack_seqnum=r.cseq),this._owner.receiveRequest(r))}_createRequest(r,n,o){n=Ea.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=r===Ds.CANCEL||r===Ds.ACK?this._local_seqnum:this._local_seqnum+=1;return new $c.OutgoingRequest(r,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,o)}_checkInDialogRequest(r){if(!this._remote_seqnum)this._remote_seqnum=r.cseq;else if(r.cseq<this._remote_seqnum)if(r.method===Ds.ACK){if(this._ack_seqnum===null||r.cseq!==this._ack_seqnum)return!1}else return r.reply(500),!1;else r.cseq>this._remote_seqnum&&(this._remote_seqnum=r.cseq);if(r.method===Ds.INVITE||r.method===Ds.UPDATE&&r.body){if(this._uac_pending_reply===!0)r.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return r.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(r.server_transaction.state===Ii.C.STATUS_ACCEPTED||r.server_transaction.state===Ii.C.STATUS_COMPLETED||r.server_transaction.state===Ii.C.STATUS_TERMINATED)&&(r.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};r.server_transaction.on("stateChanged",n)}r.hasHeader("contact")&&r.server_transaction.on("stateChanged",()=>{r.server_transaction.state===Ii.C.STATUS_ACCEPTED&&(this._remote_target=r.parseHeader("contact").uri)})}else r.method===Ds.NOTIFY&&r.hasHeader("contact")&&r.server_transaction.on("stateChanged",()=>{r.server_transaction.state===Ii.C.STATUS_COMPLETED&&(this._remote_target=r.parseHeader("contact").uri)});return!0}};const $l=xt(Vf);var hu={exports:{}};const Pm=pt.EventEmitter,km=lt,Mm=De,xm=ps,Hc=mt(),Lm=new km("RTCSession:DTMF"),jf={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};hu.exports=class extends Pm{constructor(r){super(),this._session=r,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(r,n={}){if(r===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new xm.InvalidStateError(this._session.status);const o=Hc.cloneArray(n.extraHeaders);if(this.eventHandlers=Hc.cloneObject(n.eventHandlers),typeof r=="string")r=r.toUpperCase();else if(typeof r=="number")r=r.toString();else throw new TypeError(`Invalid tone: ${r}`);if(r.match(/^[0-9A-DR#*]$/))this._tone=r;else throw new TypeError(`Invalid tone: ${r}`);this._duration=n.duration,o.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
112
+ `,this.transport.send(a)}}class om extends Hf{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var ts={OutgoingRequest:Ao,InitialOutgoingInviteRequest:fu,IncomingRequest:lm,IncomingResponse:om};const am=lt,as=mt(),Ft=new am("DigestAuthentication");var Ff=class{constructor(r){this._credentials=r,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(r){switch(r){case"realm":return this._realm;case"ha1":return this._ha1;default:Ft.warn('get() | cannot get "%s" parameter',r);return}}authenticate({method:r,ruri:n,body:o},a,t=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!=="MD5")return Ft.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Ft.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Ft.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Ft.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Ft.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop)if(a.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(a.qop.indexOf("auth")>-1)this._qop="auth";else return Ft.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=r,this._uri=n,this._cnonce=t||as.createRandomToken(12),this._nc+=1;const s=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-s.length)+s,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=as.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let p,h;return this._qop==="auth"?(p=`${this._method}:${this._uri}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=auth [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${h}`)):this._qop==="auth-int"?(p=`${this._method}:${this._uri}:${as.calculateMD5(o||"")}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=auth-int [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${h}`)):this._qop===null&&(p=`${this._method}:${this._uri}`,h=as.calculateMD5(p),Ft.debug('authenticate() | using qop=null [a2:"%s"]',p),this._response=as.calculateMD5(`${this._ha1}:${this._nonce}:${h}`)),Ft.debug("authenticate() | response generated"),!0}toString(){const r=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return r.push(`algorithm=${this._algorithm}`),r.push(`username="${this._credentials.username}"`),r.push(`realm="${this._realm}"`),r.push(`nonce="${this._nonce}"`),r.push(`uri="${this._uri}"`),r.push(`response="${this._response}"`),this._opaque&&r.push(`opaque="${this._opaque}"`),this._qop&&(r.push(`qop=${this._qop}`),r.push(`cnonce="${this._cnonce}"`),r.push(`nc=${this._ncHex}`)),`Digest ${r.join(", ")}`}};const um=xt(Ff),us=500,cm=4e3,Nc=5e3;var qf={T1:us,T2:cm,T4:Nc,TIMER_B:64*us,TIMER_D:0*us,TIMER_F:64*us,TIMER_H:64*us,TIMER_I:0*us,TIMER_J:0*us,TIMER_K:0*Nc,TIMER_L:64*us,TIMER_M:64*us,PROVISIONAL_RESPONSE_INTERVAL:6e4};const Qi=pt.EventEmitter,Zi=lt,xi=De,Uc=ts,Qt=qf,Pc=new Zi("NonInviteClientTransaction"),kl=new Zi("InviteClientTransaction"),fm=new Zi("AckClientTransaction"),kc=new Zi("NonInviteServerTransaction"),Ml=new Zi("InviteServerTransaction"),ce={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class hm extends Qi{constructor(r,n,o,a){super(),this.type=ce.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=r,this.transport=n,this.request=o,this.eventHandlers=a;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t),this.ua.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}send(){this.stateChanged(ce.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},Qt.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){Pc.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){Pc.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(r){const n=r.status_code;if(n<200)switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(r);break}else switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(r),this.K=setTimeout(()=>{this.timer_K()},Qt.TIMER_K);break;case ce.STATUS_COMPLETED:break}}}class _m extends Qi{constructor(r,n,o,a){super(),this.type=ce.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=r,this.transport=n,this.request=o,this.eventHandlers=a,o.transaction=this;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t),this.ua.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}send(){this.stateChanged(ce.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},Qt.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ce.STATUS_ACCEPTED&&(kl.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){kl.debug(`Timer M expired for transaction ${this.id}`),this.state===ce.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){kl.debug(`Timer B expired for transaction ${this.id}`),this.state===ce.STATUS_CALLING&&(this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){kl.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(r){const n=new Uc.OutgoingRequest(xi.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",r.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},Qt.TIMER_D),this.transport.send(n)}cancel(r){if(this.state!==ce.STATUS_PROCEEDING)return;const n=new Uc.OutgoingRequest(xi.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",this.request.getHeader("to")),r&&n.setHeader("reason",r),this.transport.send(n)}receiveResponse(r){const n=r.status_code;if(n>=100&&n<=199)switch(this.state){case ce.STATUS_CALLING:this.stateChanged(ce.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(r);break}else if(n>=200&&n<=299)switch(this.state){case ce.STATUS_CALLING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},Qt.TIMER_M),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(r);break}else if(n>=300&&n<=699)switch(this.state){case ce.STATUS_CALLING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),this.sendACK(r),this.eventHandlers.onReceiveResponse(r);break;case ce.STATUS_COMPLETED:this.sendACK(r);break}}}class dm extends Qi{constructor(r,n,o,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=n,this.request=o,this.eventHandlers=a;let t=`SIP/2.0/${n.via_transport}`;t+=` ${r.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",t)}get C(){return ce}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){fm.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class pm extends Qi{constructor(r,n,o){super(),this.type=ce.NON_INVITE_SERVER,this.id=o.via_branch,this.ua=r,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=ce.STATUS_TRYING,r.newTransaction(this)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}timer_J(){kc.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,kc.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(r,n,o,a){if(r===100)switch(this.state){case ce.STATUS_TRYING:this.stateChanged(ce.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case ce.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(r>=200&&r<=699)switch(this.state){case ce.STATUS_TRYING:case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(()=>{this.timer_J()},Qt.TIMER_J),this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break;case ce.STATUS_COMPLETED:break}}}class mm extends Qi{constructor(r,n,o){super(),this.type=ce.INVITE_SERVER,this.id=o.via_branch,this.ua=r,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=ce.STATUS_PROCEEDING,r.newTransaction(this),this.resendProvisionalTimer=null,o.reply(100)}get C(){return ce}stateChanged(r){this.state=r,this.emit("stateChanged")}timer_H(){Ml.debug(`Timer H expired for transaction ${this.id}`),this.state===ce.STATUS_COMPLETED&&Ml.debug("ACK not received, dialog will be terminated"),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Ml.debug(`Timer L expired for transaction ${this.id}`),this.state===ce.STATUS_ACCEPTED&&(this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Ml.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(ce.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(r,n,o,a){if(r>=100&&r<=199)switch(this.state){case ce.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(r>100&&r<=199&&this.state===ce.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},Qt.PROVISIONAL_RESPONSE_INTERVAL));else if(r>=200&&r<=299)switch(this.state){case ce.STATUS_PROCEEDING:this.stateChanged(ce.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(()=>{this.timer_L()},Qt.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ce.STATUS_ACCEPTED:this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(r>=300&&r<=699)switch(this.state){case ce.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(ce.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},Qt.TIMER_H),o&&o()):(this.onTransportError(),a&&a());break}}}function gm({_transactions:c},r){let n;switch(r.method){case xi.INVITE:if(n=c.ist[r.via_branch],n){switch(n.state){case ce.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case ce.STATUS_ACCEPTED:break}return!0}break;case xi.ACK:if(n=c.ist[r.via_branch],n){if(n.state===ce.STATUS_ACCEPTED)return!1;if(n.state===ce.STATUS_COMPLETED)return n.state=ce.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},Qt.TIMER_I),!0}else return!1;break;case xi.CANCEL:return n=c.ist[r.via_branch],n?(r.reply_sl(200),n.state!==ce.STATUS_PROCEEDING):(r.reply_sl(481),!0);default:if(n=c.nist[r.via_branch],n){switch(n.state){case ce.STATUS_TRYING:break;case ce.STATUS_PROCEEDING:case ce.STATUS_COMPLETED:n.transport.send(n.last_response);break}return!0}break}}var ir={C:ce,NonInviteClientTransaction:hm,InviteClientTransaction:_m,AckClientTransaction:dm,NonInviteServerTransaction:pm,InviteServerTransaction:mm,checkTransaction:gm};const Li=xt(ir),vm=lt,Mc=De,Tm=Ff,pa=ir,Em=new vm("RequestSender"),ma={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var lr=class{constructor(r,n,o){this._ua=r,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in ma)Object.prototype.hasOwnProperty.call(ma,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ma[a]));r.status===r.C.STATUS_USER_CLOSED&&(this._method!==Mc.BYE||this._method!==Mc.ACK)&&this._eventHandlers.onTransportError()}send(){const r={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:n=>{this._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new pa.InviteClientTransaction(this._ua,this._ua.transport,this._request,r);break;case"ACK":this.clientTransaction=new pa.AckClientTransaction(this._ua,this._ua.transport,this._request,r);break;default:this.clientTransaction=new pa.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,r)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(r){let n,o;const a=r.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(r.status_code===401?(n=r.parseHeader("www-authenticate"),o="authorization"):(n=r.parseHeader("proxy-authenticate"),o="proxy-authorization"),!n){Em.debug(`${r.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(r);return}if(!this._challenged||!this._staled&&n.stale===!0){if(this._auth||(this._auth=new Tm({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,n)){this._eventHandlers.onReceiveResponse(r);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),n.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(o,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(r)}else this._eventHandlers.onReceiveResponse(r)}};const ym=xt(lr),Sm=lt,ga=mt(),an=De,xc=ts,Lc=lr,Ri=new Sm("Registrator"),xl=10;var Cm=class{constructor(r,n){this._reg_id=1,this._ua=r,this._transport=n,this._registrar=r.configuration.registrar_server,this._expires=r.configuration.register_expires,this._call_id=ga.createRandomToken(22),this._cseq=0,this._to_uri=r.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(r){Array.isArray(r)||(r=[]),this._extraHeaders=r.slice()}setExtraContactParams(r){r instanceof Object||(r={}),this._extraContactParams="";for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const o=r[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){Ri.debug("Register request in progress...");return}const r=this._extraHeaders.slice();r.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),r.push(`Expires: ${this._expires}`);const n=new xc.OutgoingRequest(an.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r),o=new Lc(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,an.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,an.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Ri.debug("no Contact header in response to REGISTER, response ignored");break}const t=a.headers.Contact.reduce((d,g)=>d.concat(g.parsed),[]);let s=t.find(d=>this._sipInstance===d.getParam("+sip.instance")&&this._reg_id===parseInt(d.getParam("reg-id")));if(s||(s=t.find(d=>d.uri.user===this._ua.contact.uri.user)),!s){Ri.debug("no Contact header pointing to us, response ignored");break}let p=s.getParam("expires");!p&&a.hasHeader("expires")&&(p=a.getHeader("expires")),p||(p=this._expires),p=Number(p),p<xl&&(p=xl);const h=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),s.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=s.getParam("temp-gruu").replace(/"/g,"")),s.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=s.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<xl&&(this._expires=xl),this.register()):(Ri.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,an.causes.SIP_FAILURE_CODE));break}default:{const t=ga.sipErrorCause(a.status_code);this._registrationFailure(a,t)}}}});this._registering=!0,o.send()}unregister(r={}){if(!this._registered){Ri.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();r.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),n.push("Expires: 0");const o=new xc.OutgoingRequest(an.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Lc(this._ua,o,{onRequestTimeout:()=>{this._unregistered(null,an.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,an.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:t=>{switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._unregistered(t);break;default:{const s=ga.sipErrorCause(t.status_code);this._unregistered(t,s)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(r,n){this._registering=!1,this._ua.registrationFailed({response:r||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:r||null,cause:n}))}_unregistered(r,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:r||null,cause:n||null})}};class Am extends Error{constructor(r,n){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=r,this.value=n,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class Rm extends Error{constructor(r){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=r,this.message=`Invalid status: ${r}`}}class Im extends Error{constructor(r){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=r}}class bm extends Error{constructor(r){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=r}}var ps={ConfigurationError:Am,InvalidStateError:Rm,NotSupportedError:Im,NotReadyError:bm};const wm=xt(ps),va=De,Ll=ir,Om=lr,Ta={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var Dm=class{constructor(r,n,o){this._dialog=r,this._ua=r._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(const a in Ta)Object.prototype.hasOwnProperty.call(Ta,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ta[a]))}get request(){return this._request}send(){const r=new Om(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:n=>{this._eventHandlers.onAuthenticated(n)},onReceiveResponse:n=>{this._receiveResponse(n)}});if(r.send(),(this._request.method===va.INVITE||this._request.method===va.UPDATE&&this._request.body)&&r.clientTransaction.state!==Ll.C.STATUS_TERMINATED){console.log("this._request.body",this._request.body),this._dialog.uac_pending_reply=!0;const n=()=>{(r.clientTransaction.state===Ll.C.STATUS_ACCEPTED||r.clientTransaction.state===Ll.C.STATUS_COMPLETED||r.clientTransaction.state===Ll.C.STATUS_TERMINATED)&&(r.clientTransaction.removeListener("stateChanged",n),this._dialog.uac_pending_reply=!1)};r.clientTransaction.on("stateChanged",n)}}_receiveResponse(r){r.status_code===408||r.status_code===481?this._eventHandlers.onDialogError(r):r.method===va.INVITE&&r.status_code===491?this._reattempt?r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r)}};const Nm=lt,$c=ts,Ds=De,Ii=ir,Um=Dm,Ea=mt(),ya=new Nm("Dialog"),Ns={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var Vf=class{static get C(){return Ns}constructor(r,n,o,a=Ns.STATUS_CONFIRMED){if(this._owner=r,this._ua=r._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!n.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};n instanceof $c.IncomingResponse&&(a=n.status_code<200?Ns.STATUS_EARLY:Ns.STATUS_CONFIRMED);const t=n.parseHeader("contact");o==="UAS"?(this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri,this._remote_target=t.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):o==="UAC"&&(this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri,this._remote_target=t.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),ya.debug(`new ${o} dialog created with status ${this._state===Ns.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(r){this._local_seqnum=r}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(r){this._uac_pending_reply=r}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ns.STATUS_TERMINATED}update(r,n){this._state=Ns.STATUS_CONFIRMED,ya.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=r.getHeaders("record-route").reverse())}terminate(){ya.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ns.STATUS_TERMINATED}sendRequest(r,n={}){const o=Ea.cloneArray(n.extraHeaders),a=Ea.cloneObject(n.eventHandlers),t=n.body||null,s=this._createRequest(r,o,t);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Um(this,s,a).send(),s}receiveRequest(r){this._checkInDialogRequest(r)&&(r.method===Ds.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:r.method===Ds.INVITE&&(this._ack_seqnum=r.cseq),this._owner.receiveRequest(r))}_createRequest(r,n,o){n=Ea.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=r===Ds.CANCEL||r===Ds.ACK?this._local_seqnum:this._local_seqnum+=1;return new $c.OutgoingRequest(r,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,o)}_checkInDialogRequest(r){if(!this._remote_seqnum)this._remote_seqnum=r.cseq;else if(r.cseq<this._remote_seqnum)if(r.method===Ds.ACK){if(this._ack_seqnum===null||r.cseq!==this._ack_seqnum)return!1}else return r.reply(500),!1;else r.cseq>this._remote_seqnum&&(this._remote_seqnum=r.cseq);if(r.method===Ds.INVITE||r.method===Ds.UPDATE&&r.body){if(this._uac_pending_reply===!0)r.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return r.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(r.server_transaction.state===Ii.C.STATUS_ACCEPTED||r.server_transaction.state===Ii.C.STATUS_COMPLETED||r.server_transaction.state===Ii.C.STATUS_TERMINATED)&&(r.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};r.server_transaction.on("stateChanged",n)}r.hasHeader("contact")&&r.server_transaction.on("stateChanged",()=>{r.server_transaction.state===Ii.C.STATUS_ACCEPTED&&(this._remote_target=r.parseHeader("contact").uri)})}else r.method===Ds.NOTIFY&&r.hasHeader("contact")&&r.server_transaction.on("stateChanged",()=>{r.server_transaction.state===Ii.C.STATUS_COMPLETED&&(this._remote_target=r.parseHeader("contact").uri)});return!0}};const $l=xt(Vf);var hu={exports:{}};const Pm=pt.EventEmitter,km=lt,Mm=De,xm=ps,Hc=mt(),Lm=new km("RTCSession:DTMF"),jf={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};hu.exports=class extends Pm{constructor(r){super(),this._session=r,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(r,n={}){if(r===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new xm.InvalidStateError(this._session.status);const o=Hc.cloneArray(n.extraHeaders);if(this.eventHandlers=Hc.cloneObject(n.eventHandlers),typeof r=="string")r=r.toUpperCase();else if(typeof r=="number")r=r.toString();else throw new TypeError(`Invalid tone: ${r}`);if(r.match(/^[0-9A-DR#*]$/))this._tone=r;else throw new TypeError(`Invalid tone: ${r}`);this._duration=n.duration,o.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
113
113
  `;a+=`Duration=${this._duration}`,this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(Mm.INFO,{extraHeaders:o,eventHandlers:{onSuccessResponse:t=>{this.emit("succeeded",{originator:"remote",response:t})},onErrorResponse:t=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:t})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:a})}init_incoming(r){const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,o=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=r,r.reply(200),r.body){const a=r.body.split(`
114
114
  `);a.length>=1&&n.test(a[0])&&(this._tone=a[0].replace(n,"$2")),a.length>=2&&o.test(a[1])&&(this._duration=parseInt(a[1].replace(o,"$2"),10))}this._duration||(this._duration=jf.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:r}):Lm.debug("invalid INFO DTMF received, discarded")}};hu.exports.C=jf;var $m=hu.exports;const Hm=pt.EventEmitter,Fm=De,qm=ps,Vm=mt();var Bf=class extends Hm{constructor(r){super(),this._session=r,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(r,n,o={}){if(this._direction="outgoing",r===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new qm.InvalidStateError(this._session.status);this._contentType=r,this._body=n;const a=Vm.cloneArray(o.extraHeaders);a.push(`Content-Type: ${r}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(Fm.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:t=>{this.emit("succeeded",{originator:"remote",response:t})},onErrorResponse:t=>{this.emit("failed",{originator:"remote",response:t})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:n})}init_incoming(r){this._direction="incoming",this.request=r,r.reply(200),this._contentType=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0,this._body=r.body,this._session.newInfo({originator:"remote",info:this,request:r})}};const jm=xt(Bf),Bm=lt,Fc=De,Gm=new Bm("RTCSession:ReferNotifier"),Sa={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var Km=class{constructor(r,n,o){this._session=r,this._id=n,this._expires=o||Sa.expires,this._active=!0,this.notify(100)}notify(r,n){if(Gm.debug("notify()"),this._active===!1)return;n=n||Fc.REASON_PHRASE[r]||"";let o;r>=200?o="terminated;reason=noresource":o=`active;expires=${this._expires}`,this._session.sendRequest(Fc.NOTIFY,{extraHeaders:[`Event: ${Sa.event_type};id=${this._id}`,`Subscription-State: ${o}`,`Content-Type: ${Sa.body_type}`],body:`SIP/2.0 ${r} ${n}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const Wm=pt.EventEmitter,Ym=lt,bi=De,zm=es(),qc=mt(),un=new Ym("RTCSession:ReferSubscriber");var Jm=class extends Wm{constructor(r){super(),this._id=null,this._session=r}get id(){return this._id}sendRefer(r,n={}){un.debug("sendRefer()");const o=qc.cloneArray(n.extraHeaders),a=qc.cloneObject(n.eventHandlers);for(const h in a)Object.prototype.hasOwnProperty.call(a,h)&&this.on(h,a[h]);let t=null;n.replaces&&(t=n.replaces._request.call_id,t+=`;to-tag=${n.replaces._to_tag}`,t+=`;from-tag=${n.replaces._from_tag}`,t=encodeURIComponent(t));const s=`Refer-To: <${r}${t?`?Replaces=${t}`:""}>`;if(o.push(s),!o.some(h=>h.toLowerCase().startsWith("referred-by:"))){const h=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;o.push(h)}o.push(`Contact: ${this._session.contact}`);const p=this._session.sendRequest(bi.REFER,{extraHeaders:o,eventHandlers:{onSuccessResponse:h=>{this._requestSucceeded(h)},onErrorResponse:h=>{this._requestFailed(h,bi.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,bi.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,bi.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,bi.causes.DIALOG_ERROR)}}});this._id=p.cseq}receiveNotify(r){if(un.debug("receiveNotify()"),!r.body)return;const n=zm.parse(r.body.trim().split(`\r
115
- `,1)[0],"Status_Line");if(n===-1){un.debug(`receiveNotify() | error parsing NOTIFY body: "${r.body}"`);return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:r,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:r,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:r,status_line:n});break;default:this.emit("failed",{request:r,status_line:n});break}}_requestSucceeded(r){un.debug("REFER succeeded"),un.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:r})}_requestFailed(r,n){un.debug("REFER failed"),un.debug('emit "requestFailed"'),this.emit("requestFailed",{response:r||null,cause:n})}};const Xm=pt.EventEmitter,Vc=Lt,Qm=lt,ae=De,cn=ps,jc=ir,qe=mt(),wi=qf,Zm=ts,Hl=Vf,eg=lr,bt=$m,Bc=Bf,tg=Km,sg=Jm,Gc=ds(),W=new Qm("RTCSession"),X={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},Fl=["audio","video"];var Gf=class Ja extends Xm{static get C(){return X}constructor(r){W.debug("new"),super(),this._id=null,this._ua=r,this._status=X.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:ae.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return X}get causes(){return ae.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(r){this._data=r}get status(){return this._status}isInProgress(){switch(this._status){case X.STATUS_NULL:case X.STATUS_INVITE_SENT:case X.STATUS_1XX_RECEIVED:case X.STATUS_INVITE_RECEIVED:case X.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case X.STATUS_ANSWERED:case X.STATUS_WAITING_FOR_ACK:case X.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case X.STATUS_CANCELED:case X.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(r,n={},o){W.debug("connect()");const a=r,t=qe.cloneObject(n.eventHandlers),s=qe.cloneArray(n.extraHeaders),p=qe.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),h=n.mediaStream||null,d=qe.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,v=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=v,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,r===void 0)throw new TypeError("Not enough arguments");if(this._status!==X.STATUS_NULL)throw new cn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new cn.NotSupportedError("WebRTC not supported");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&qe.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ae.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ae.SESSION_EXPIRES);for(const C in t)Object.prototype.hasOwnProperty.call(t,C)&&this.on(C,t[C]);this._from_tag=qe.newTag();const E=n.anonymous||!1,S={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(S.from_display_name="Anonymous",S.from_uri=new Gc("sip","anonymous","anonymous.invalid"),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push("Privacy: id")):n.fromUserName&&(S.from_uri=new Gc("sip",n.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(S.from_display_name=n.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Zm.InitialOutgoingInviteRequest(r,this._ua,S,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newRTCSession("local",this._request),this._sendInitialRequest(p,v,h)}init_incoming(r,n){W.debug("init_incoming()");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=X.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=qe.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=X.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),this._failed("local",null,ae.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===X.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),this._failed("system",null,ae.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from,n&&n(this),this._newRTCSession("remote",r),this._status!==X.STATUS_TERMINATED&&(r.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(r={}){W.debug("answer()");const n=this._request,o=qe.cloneArray(r.extraHeaders),a=qe.cloneObject(r.mediaConstraints),t=r.mediaStream||null,s=qe.cloneObject(r.pcConfig,{iceServers:[]}),p=r.rtcConstraints||null,h=r.rtcAnswerConstraints||null,d=qe.cloneObject(r.rtcOfferConstraints);let g,v=!1,E=!1,S=!1,C=!1;if(this._rtcAnswerConstraints=h,this._rtcOfferConstraints=r.rtcOfferConstraints||null,this._data=r.data||this._data,this._direction!=="incoming")throw new cn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==X.STATUS_WAITING_FOR_ANSWER)throw new cn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&qe.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=ae.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=ae.SESSION_EXPIRES),this._status=X.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const I=n.parseSDP();Array.isArray(I.media)||(I.media=[I.media]);for(const w of I.media)w.type==="audio"&&(v=!0,(!w.direction||w.direction==="sendrecv")&&(S=!0)),w.type==="video"&&(E=!0,(!w.direction||w.direction==="sendrecv")&&(C=!0));if(t&&a.audio===!1){g=t.getAudioTracks();for(const w of g)t.removeTrack(w)}if(t&&a.video===!1){g=t.getVideoTracks();for(const w of g)t.removeTrack(w)}!t&&a.audio===void 0&&(a.audio=S),!t&&a.video===void 0&&(a.video=C),!t&&!v&&!d.offerToReceiveAudio&&(a.audio=!1),!t&&!E&&!d.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(s,p),Promise.resolve().then(()=>{if(t)return t;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(w=>{throw this._status===X.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,ae.causes.USER_DENIED_MEDIA_ACCESS),W.warn('emit "getusermediafailed" [error:%o]',w),this.emit("getusermediafailed",w),new Error("getUserMedia() failed"))})}).then(w=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=w,w&&w.getTracks().forEach(F=>{this._connection.addTrack(F,w)})}).then(()=>{if(this._late_sdp)return;const w={originator:"remote",type:"offer",sdp:n.body};W.debug('emit "sdp"'),this.emit("sdp",w);const F=new RTCSessionDescription({type:"offer",sdp:w.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(F)).catch(L=>{throw n.reply(488),this._failed("system",null,ae.causes.WEBRTC_ERROR),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',L),this.emit("peerconnection:setremotedescriptionfailed",L),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",h).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(w=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,w,()=>{this._status=X.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,w),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,ae.causes.CONNECTION_ERROR)})}).catch(w=>{this._status!==X.STATUS_TERMINATED&&W.warn(w)})}terminate(r={}){W.debug("terminate()");const n=r.cause||ae.causes.BYE,o=qe.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===X.STATUS_TERMINATED)throw new cn.InvalidStateError(this._status);switch(this._status){case X.STATUS_NULL:case X.STATUS_INVITE_SENT:case X.STATUS_1XX_RECEIVED:if(W.debug("canceling session"),s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||ae.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===X.STATUS_NULL||this._status===X.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===X.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=X.STATUS_CANCELED,this._failed("local",null,ae.causes.CANCELED);break;case X.STATUS_WAITING_FOR_ANSWER:case X.STATUS_ANSWERED:if(W.debug("rejecting session"),s=s||480,s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),this._failed("local",null,ae.causes.REJECTED);break;case X.STATUS_WAITING_FOR_ACK:case X.STATUS_CONFIRMED:if(W.debug("terminating session"),p=r.reason_phrase||ae.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===X.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jc.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:d})=>{d===ae.ACK&&(this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===jc.C.STATUS_TERMINATED&&(this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendDTMF(r,n={}){W.debug("sendDTMF() | tones: %s",r);let o=0,a=n.duration||null,t=n.interToneGap||null;const s=n.transportType||ae.DTMF_TRANSPORT.INFO;if(r===void 0)throw new TypeError("Not enough arguments");if(this._status!==X.STATUS_CONFIRMED&&this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_1XX_RECEIVED)throw new cn.InvalidStateError(this._status);if(s!==ae.DTMF_TRANSPORT.INFO&&s!==ae.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${s}`);if(typeof r=="number"&&(r=r.toString()),!r||typeof r!="string"||!r.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${r}`);if(a&&!qe.isDecimal(a))throw new TypeError(`Invalid tone duration: ${a}`);if(a?a<bt.C.MIN_DURATION?(W.debug(`"duration" value is lower than the minimum allowed, setting it to ${bt.C.MIN_DURATION} milliseconds`),a=bt.C.MIN_DURATION):a>bt.C.MAX_DURATION?(W.debug(`"duration" value is greater than the maximum allowed, setting it to ${bt.C.MAX_DURATION} milliseconds`),a=bt.C.MAX_DURATION):a=Math.abs(a):a=bt.C.DEFAULT_DURATION,n.duration=a,t&&!qe.isDecimal(t))throw new TypeError(`Invalid interToneGap: ${t}`);if(t?t<bt.C.MIN_INTER_TONE_GAP?(W.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${bt.C.MIN_INTER_TONE_GAP} milliseconds`),t=bt.C.MIN_INTER_TONE_GAP):t=Math.abs(t):t=bt.C.DEFAULT_INTER_TONE_GAP,s===ae.DTMF_TRANSPORT.RFC2833){const h=this._getDTMFRTPSender();h&&(r=h.toneBuffer+r,h.insertDTMF(r,a,t));return}if(this._tones){this._tones+=r;return}this._tones=r,p.call(this);function p(){let h;if(this._status===X.STATUS_TERMINATED||!this._tones||o>=this._tones.length){this._tones=null;return}const d=this._tones[o];if(o+=1,d===",")h=2e3;else{const g=new bt(this);n.eventHandlers={onFailed:()=>{this._tones=null}},g.send(d,n),h=a+t}setTimeout(p.bind(this),h)}}sendInfo(r,n,o={}){if(W.debug("sendInfo()"),this._status!==X.STATUS_CONFIRMED&&this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_1XX_RECEIVED)throw new cn.InvalidStateError(this._status);new Bc(this).send(r,n,o)}mute(r={audio:!0,video:!1}){W.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&r.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&r.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(r={audio:!0,video:!0}){W.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&r.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&r.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}hold(r={},n){if(W.debug("hold()"),this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:r.extraHeaders}),!0}unhold(r={},n){if(W.debug("unhold()"),this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:r.extraHeaders}),!0}renegotiate(r={},n){W.debug("renegotiate()");const o=r.rtcOfferConstraints||null;if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:r.extraHeaders}),!0}refer(r,n){W.debug("refer()");const o=r;if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${o}`);const a=new sg(this);a.sendRefer(r,n);const t=a.id;return this._referSubscribers[t]=a,a.on("requestFailed",()=>{delete this._referSubscribers[t]}),a.on("accepted",()=>{delete this._referSubscribers[t]}),a.on("failed",()=>{delete this._referSubscribers[t]}),a}sendRequest(r,n){return W.debug("sendRequest()"),this._dialog.sendRequest(r,n)}receiveRequest(r){if(W.debug("receiveRequest()"),r.method===ae.CANCEL)(this._status===X.STATUS_WAITING_FOR_ANSWER||this._status===X.STATUS_ANSWERED)&&(this._status=X.STATUS_CANCELED,this._request.reply(487),this._failed("remote",r,ae.causes.CANCELED));else switch(r.method){case ae.ACK:if(this._status!==X.STATUS_WAITING_FOR_ACK)return;if(this._status=X.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!r.body){this.terminate({cause:ae.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:r.body};W.debug('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:ae.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",r);break;case ae.BYE:this._status===X.STATUS_CONFIRMED||this._status===X.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,ae.causes.BYE)):this._status===X.STATUS_INVITE_RECEIVED||this._status===X.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,ae.causes.BYE)):r.reply(403,"Wrong Status");break;case ae.INVITE:this._status===X.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case ae.INFO:if(this._status===X.STATUS_1XX_RECEIVED||this._status===X.STATUS_WAITING_FOR_ANSWER||this._status===X.STATUS_ANSWERED||this._status===X.STATUS_WAITING_FOR_ACK||this._status===X.STATUS_CONFIRMED){const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new bt(this).init_incoming(r):n!==void 0?new Bc(this).init_incoming(r):r.reply(415)}else r.reply(403,"Wrong Status");break;case ae.UPDATE:this._status===X.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case ae.REFER:this._status===X.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case ae.NOTIFY:this._status===X.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){W.warn("onTransportError()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ae.causes.CONNECTION_ERROR,cause:ae.causes.CONNECTION_ERROR})}onRequestTimeout(){W.warn("onRequestTimeout()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ae.causes.REQUEST_TIMEOUT,cause:ae.causes.REQUEST_TIMEOUT})}onDialogError(){W.warn("onDialogError()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ae.causes.DIALOG_ERROR,cause:ae.causes.DIALOG_ERROR})}newDTMF(r){W.debug("newDTMF()"),this.emit("newDTMF",r)}newInfo(r){W.debug("newInfo()"),this.emit("newInfo",r)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(W.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(W.debug("_isReadyToReOffer() | session not established yet"),!1):(W.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(W.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(W.debug("close() | closing local MediaStream"),qe.closeMediaStream(this._localMediaStream)),this._status!==X.STATUS_TERMINATED){if(this._status=X.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(r){W.warn("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.destroyRTCSession(this)}}_setInvite2xxTimer(r,n){let o=wi.T1;function a(){this._status===X.STATUS_WAITING_FOR_ACK&&(r.reply(200,null,[`Contact: ${this._contact}`],n),o<wi.T2&&(o=o*2,o>wi.T2&&(o=wi.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===X.STATUS_WAITING_FOR_ACK&&(W.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(ae.BYE),this._ended("remote",null,ae.causes.NO_ACK))},wi.TIMER_H)}_createRTCConnection(r,n){this._connection=new RTCPeerConnection(r,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:ae.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ae.causes.RTP_TIMEOUT})}),W.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(r,n){if(W.debug("createLocalDescription()"),r!=="offer"&&r!=="answer")throw new Error(`createLocalDescription() | invalid type "${r}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>r==="offer"?o.createOffer(n).catch(a=>(W.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(n).catch(a=>(W.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(t=>(this._rtcReady=!0,W.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',t),this.emit("peerconnection:setlocaldescriptionfailed",t),Promise.reject(t)))).then(()=>{const a=n&&n.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const t={originator:"local",type:r,sdp:o.localDescription.sdp};return W.debug('emit "sdp"'),this.emit("sdp",t),Promise.resolve(t.sdp)}return new Promise(t=>{let s=!1,p,h;this._iceReady=!1;const d=()=>{o.removeEventListener("icecandidate",p),o.removeEventListener("icegatheringstatechange",h),s=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:r,sdp:o.localDescription.sdp};W.debug('emit "sdp"'),this.emit("sdp",g),t(g.sdp)};o.addEventListener("icecandidate",p=g=>{const v=g.candidate;v?this.emit("icecandidate",{candidate:v,ready:d}):s||d()}),o.addEventListener("icegatheringstatechange",h=()=>{o.iceGatheringState==="complete"&&!s&&d()})})})}_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 Hl(this,r,n,Hl.C.STATUS_EARLY),p.error?(W.debug(p.error),this._failed("remote",r,ae.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 h=new Hl(this,r,n);return h.error?(W.debug(h.error),this._failed("remote",r,ae.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_receiveReinvite(r){W.debug("receiveReinvite()");const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0,o={request:r,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const h=p.status_code||403,d=p.reason_phrase||"",g=qe.cloneArray(p.extraHeaders);if(this._status!==X.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);r.reply(h,d,g)}if(this.emit("reinvite",o),a)return;if(this._late_sdp=!1,!r.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(p=>{s.call(this,p)}).catch(()=>{r.reply(500)});return}if(n!=="application/sdp"){W.debug("invalid Content-Type"),r.reply(415);return}this._processInDialogSdpOffer(r).then(p=>{this._status!==X.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{W.warn(p)});function s(p){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(r,h),this._late_sdp&&(p=this._mangleOffer(p)),r.reply(200,null,h,p,()=>{this._status=X.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,p),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(r){W.debug("receiveUpdate()");const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0,o={request:r,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const h=p.status_code||403,d=p.reason_phrase||"",g=qe.cloneArray(p.extraHeaders);if(this._status!==X.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);r.reply(h,d,g)}if(this.emit("update",o),a)return;if(!r.body){s.call(this,null);return}if(n!=="application/sdp"){W.debug("invalid Content-Type"),r.reply(415);return}this._processInDialogSdpOffer(r).then(p=>{this._status!==X.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{W.warn(p)});function s(p){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(r,h),r.reply(200,null,h,p),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(r){W.debug("_processInDialogSdpOffer()");const n=r.parseSDP();let o=!1;for(const s of n.media){if(Fl.indexOf(s.type)===-1)continue;const p=s.direction||n.direction||"sendrecv";if(p==="sendonly"||p==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:r.body};W.debug('emit "sdp"'),this.emit("sdp",a);const t=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(t).catch(s=>{throw r.reply(488),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',s),this.emit("peerconnection:setremotedescriptionfailed",s),s})}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(s=>{throw r.reply(500),W.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',s),s})}).catch(s=>{W.warn("_processInDialogSdpOffer() failed [error: %o]",s)}),this._connectionPromiseQueue}_receiveRefer(r){if(W.debug("receiveRefer()"),!r.refer_to){W.debug("no Refer-To header field present in REFER"),r.reply(400);return}if(r.refer_to.uri.scheme!==ae.SIP){W.debug("Refer-To header field points to a non-SIP URI scheme"),r.reply(416);return}r.reply(202);const n=new tg(this,r.cseq);W.debug('emit "refer"'),this.emit("refer",{request:r,accept:(t,s)=>{o.call(this,t,s)},reject:()=>{a.call(this)}});function o(t,s={}){if(t=typeof t=="function"?t:null,this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;const p=new Ja(this._ua);if(p.on("progress",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),p.on("accepted",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),p.on("_failed",({message:h,cause:d})=>{h?n.notify(h.status_code,h.reason_phrase):n.notify(487,d)}),r.refer_to.uri.hasHeader("replaces")){const h=decodeURIComponent(r.refer_to.uri.getHeader("replaces"));s.extraHeaders=qe.cloneArray(s.extraHeaders),s.extraHeaders.push(`Replaces: ${h}`)}p.connect(r.refer_to.uri.toAor(),s,t)}function a(){n.notify(603)}}_receiveNotify(r){switch(W.debug("receiveNotify()"),r.event||r.reply(400),r.event.event){case"refer":{let n,o;if(r.event.params&&r.event.params.id)n=r.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{r.reply(400,"Missing event id parameter");return}if(!o){r.reply(481,"Subscription does not exist");return}o.receiveNotify(r),r.reply(200);break}default:r.reply(489)}}_receiveReplaces(r){W.debug("receiveReplaces()");function n(a){if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;const t=new Ja(this._ua);t.on("confirmed",()=>{this.terminate()}),t.init_incoming(r,a)}function o(){W.debug("Replaced INVITE rejected by the user"),r.reply(486)}this.emit("replaces",{request:r,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_sendInitialRequest(r,n,o){const a=new eg(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t)}});Promise.resolve().then(()=>{if(o)return o;if(r.audio||r.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(r).catch(t=>{throw this._status===X.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,ae.causes.USER_DENIED_MEDIA_ACCESS),W.warn('emit "getusermediafailed" [error:%o]',t),this.emit("getusermediafailed",t),t)})}).then(t=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=t,t&&t.getTracks().forEach(s=>{this._connection.addTrack(s,t)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(s=>{throw this._failed("local",null,ae.causes.WEBRTC_ERROR),s})}).then(t=>{if(this._is_canceled||this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._request.body=t,this._status=X.STATUS_INVITE_SENT,W.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(t=>{this._status!==X.STATUS_TERMINATED&&W.warn(t)})}_getDTMFRTPSender(){const r=this._connection.getSenders().find(n=>n.track&&n.track.kind==="audio");if(!(r&&r.dtmf)){W.warn("sendDTMF() | no local audio track to send DTMF with");return}return r.dtmf}_receiveInviteResponse(r){if(W.debug("receiveInviteResponse()"),this._dialog&&r.status_code>=200&&r.status_code<=299)if(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(ae.ACK);return}else{const n=new Hl(this,r,"UAC");if(n.error!==void 0){W.debug(n.error);return}this.sendRequest(ae.ACK),this.sendRequest(ae.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!==X.STATUS_INVITE_SENT&&this._status!==X.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(r.status_code):this._status=X.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(r.status_code):{if(!r.to_tag){W.debug("1xx response received without to tag");break}if(r.hasHeader("contact")&&!this._createDialog(r,"UAC",!0))break;if(this._status=X.STATUS_1XX_RECEIVED,!r.body){this._progress("remote",r);break}const n={originator:"remote",type:"answer",sdp:r.body};W.debug('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=>{W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(r.status_code):{if(this._status=X.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,ae.causes.MISSING_SDP),this._failed("remote",r,ae.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(r,"UAC"))break;const n={originator:"remote",type:"answer",sdp:r.body};W.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(r,500,a.toString()),this._failed("local",r,ae.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(o).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(ae.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(r,488,"Not Acceptable Here"),this._failed("remote",r,ae.causes.BAD_MEDIA_DESCRIPTION),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const n=qe.sipErrorCause(r.status_code);this._failed("remote",r,n)}}}_sendReinvite(r={}){W.debug("sendReinvite()");const n=qe.cloneArray(r.extraHeaders),o=qe.cloneObject(r.eventHandlers),a=r.rtcOfferConstraints||this._rtcOfferConstraints||null;let t=!1;n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(h=>{h=this._mangleOffer(h);const d={originator:"local",type:"offer",sdp:h};W.debug('emit "sdp"'),this.emit("sdp",d),this.sendRequest(ae.INVITE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:g=>{s.call(this,g),t=!0},onErrorResponse:g=>{p.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{p()});function s(h){if(this._status===X.STATUS_TERMINATED||(this.sendRequest(ae.ACK),t))return;if(this._handleSessionTimersInIncomingResponse(h),h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){p.call(this);return}}else{p.call(this);return}const d={originator:"remote",type:"answer",sdp:h.body};W.debug('emit "sdp"'),this.emit("sdp",d);const g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(h)}).catch(v=>{p.call(this),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',v),this.emit("peerconnection:setremotedescriptionfailed",v)})}function p(h){o.failed&&o.failed(h)}}_sendUpdate(r={}){W.debug("sendUpdate()");const n=qe.cloneArray(r.extraHeaders),o=qe.cloneObject(r.eventHandlers),a=r.rtcOfferConstraints||this._rtcOfferConstraints||null,t=r.sdpOffer||!1;let s=!1;n.push(`Contact: ${this._contact}`),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),t?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const g={originator:"local",type:"offer",sdp:d};W.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(ae.UPDATE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:v=>{p.call(this,v),s=!0},onErrorResponse:v=>{h.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h.call(this)})):this.sendRequest(ae.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:d=>{p.call(this,d)},onErrorResponse:d=>{h.call(this,d)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function p(d){if(this._status!==X.STATUS_TERMINATED&&!s)if(this._handleSessionTimersInIncomingResponse(d),t){if(d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const g={originator:"remote",type:"answer",sdp:d.body};W.debug('emit "sdp"'),this.emit("sdp",g);const v=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(v)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(E=>{h.call(this),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),this.emit("peerconnection:setremotedescriptionfailed",E)})}else o.succeeded&&o.succeeded(d)}function h(d){o.failed&&o.failed(d)}}_acceptAndTerminate(r,n,o){W.debug("acceptAndTerminate()");const a=[];n&&(o=o||ae.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(this._dialog||this._createDialog(r,"UAC"))&&(this.sendRequest(ae.ACK),this.sendRequest(ae.BYE,{extraHeaders:a})),this._status=X.STATUS_TERMINATED}_mangleOffer(r){if(!this._localHold&&!this._remoteHold)return r;if(r=Vc.parse(r),this._localHold&&!this._remoteHold){W.debug("mangleOffer() | me on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="sendonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="sendonly")}else if(this._localHold&&this._remoteHold){W.debug("mangleOffer() | both on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){W.debug("mangleOffer() | remote on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Vc.write(r)}_setLocalMediaStatus(){let r=!0,n=!0;(this._localHold||this._remoteHold)&&(r=!1,n=!1),this._audioMuted&&(r=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!r),this._toggleMuteVideo(!n)}_handleSessionTimersInIncomingRequest(r,n){if(!this._sessionTimers.enabled)return;let o;r.session_expires&&r.session_expires>=ae.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=r.session_expires,o=r.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(r){if(!this._sessionTimers.enabled)return;let n;r.session_expires&&r.session_expires>=ae.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()}_runSessionTimer(){const r=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==X.STATUS_TERMINATED&&this._isReadyToReOffer()&&(W.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===ae.UPDATE?this._sendUpdate():this._sendReinvite())},r*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==X.STATUS_TERMINATED&&(W.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:ae.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},r*1100)}_toggleMuteAudio(r){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!r}_toggleMuteVideo(r){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.track.enabled=!r}_newRTCSession(r,n){W.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:r,session:this,request:n})}_connecting(r){W.debug("session connecting"),W.debug('emit "connecting"'),this.emit("connecting",{request:r})}_progress(r,n){W.debug("session progress"),W.debug('emit "progress"'),this.emit("progress",{originator:r,response:n||null})}_accepted(r,n){W.debug("session accepted"),this._start_time=new Date,W.debug('emit "accepted"'),this.emit("accepted",{originator:r,response:n||null})}_confirmed(r,n){W.debug("session confirmed"),this._is_confirmed=!0,W.debug('emit "confirmed"'),this.emit("confirmed",{originator:r,ack:n||null})}_ended(r,n,o){W.debug("session ended"),this._end_time=new Date,this._close(),W.debug('emit "ended"'),this.emit("ended",{originator:r,message:n||null,cause:o})}_failed(r,n,o){W.debug("session failed"),W.debug('emit "_failed"'),this.emit("_failed",{originator:r,message:n||null,cause:o}),this._close(),W.debug('emit "failed"'),this.emit("failed",{originator:r,message:n||null,cause:o})}_onhold(r){W.debug("session onhold"),this._setLocalMediaStatus(),W.debug('emit "hold"'),this.emit("hold",{originator:r})}_onunhold(r){W.debug("session onunhold"),this._setLocalMediaStatus(),W.debug('emit "unhold"'),this.emit("unhold",{originator:r})}_onmute({audio:r,video:n}){W.debug("session onmute"),this._setLocalMediaStatus(),W.debug('emit "muted"'),this.emit("muted",{audio:r,video:n})}_onunmute({audio:r,video:n}){W.debug("session onunmute"),this._setLocalMediaStatus(),W.debug('emit "unmuted"'),this.emit("unmuted",{audio:r,video:n})}};const ng=xt(Gf),rg=pt.EventEmitter,ig=lt,Ca=De,lg=ts,Oi=mt(),og=lr,Kc=ps,ag=ds(),ql=new ig("Message");var ug=class extends rg{constructor(r){super(),this._ua=r,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(r,n,o={}){const a=r;if(r===void 0||n===void 0)throw new TypeError("Not enough arguments");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);const t=Oi.cloneArray(o.extraHeaders),s=Oi.cloneObject(o.eventHandlers),p=o.contentType||"text/plain",h={};o.fromUserName&&(h.from_uri=new ag("sip",o.fromUserName,this._ua.configuration.uri.host),t.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(h.from_display_name=o.fromDisplayName);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&this.on(g,s[g]);t.push(`Content-Type: ${p}`),this._request=new lg.OutgoingRequest(Ca.MESSAGE,r,this._ua,h,t),n&&(this._request.body=n);const d=new og(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:g=>{this._receiveResponse(g)}});this._newMessage("local",this._request),d.send()}init_incoming(r){this._request=r,this._newMessage("remote",r),this._is_replied||(this._is_replied=!0,r.reply(200)),this._close()}accept(r={}){const n=Oi.cloneArray(r.extraHeaders),o=r.body;if(this._direction!=="incoming")throw new Kc.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,o)}reject(r={}){const n=r.status_code||480,o=r.reason_phrase,a=Oi.cloneArray(r.extraHeaders),t=r.body;if(this._direction!=="incoming")throw new Kc.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,o,a,t)}_receiveResponse(r){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(r.status_code):break;case/^2[0-9]{2}$/.test(r.status_code):this._succeeded("remote",r);break;default:{const n=Oi.sipErrorCause(r.status_code);this._failed("remote",r,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Ca.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Ca.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(r,n){r==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):r==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:r,message:this,request:n})}_failed(r,n,o){ql.debug("MESSAGE failed"),this._close(),ql.debug('emit "failed"'),this.emit("failed",{originator:r,response:n||null,cause:o})}_succeeded(r,n){ql.debug("MESSAGE succeeded"),this._close(),ql.debug('emit "succeeded"'),this.emit("succeeded",{originator:r,response:n})}};const cg=pt.EventEmitter,fg=lt,Aa=De,hg=ts,Di=mt(),_g=lr,Wc=ps,Vl=new fg("Options");var dg=class extends cg{constructor(r){super(),this._ua=r,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(r,n,o={}){const a=r;if(r===void 0)throw new TypeError("A target is required for OPTIONS");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);const t=Di.cloneArray(o.extraHeaders),s=Di.cloneObject(o.eventHandlers),p=o.contentType||"application/sdp";for(const d in s)Object.prototype.hasOwnProperty.call(s,d)&&this.on(d,s[d]);t.push(`Content-Type: ${p}`),this._request=new hg.OutgoingRequest(Aa.OPTIONS,r,this._ua,null,t),n&&(this._request.body=n);const h=new _g(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:d=>{this._receiveResponse(d)}});this._newOptions("local",this._request),h.send()}init_incoming(r){this._request=r,this._newOptions("remote",r),this._is_replied||(this._is_replied=!0,r.reply(200)),this._close()}accept(r={}){const n=Di.cloneArray(r.extraHeaders),o=r.body;if(this._direction!=="incoming")throw new Wc.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,o)}reject(r={}){const n=r.status_code||480,o=r.reason_phrase,a=Di.cloneArray(r.extraHeaders),t=r.body;if(this._direction!=="incoming")throw new Wc.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,o,a,t)}_receiveResponse(r){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(r.status_code):break;case/^2[0-9]{2}$/.test(r.status_code):this._succeeded("remote",r);break;default:{const n=Di.sipErrorCause(r.status_code);this._failed("remote",r,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Aa.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Aa.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(r,n){r==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):r==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:r,message:this,request:n})}_failed(r,n,o){Vl.debug("OPTIONS failed"),this._close(),Vl.debug('emit "failed"'),this.emit("failed",{originator:r,response:n||null,cause:o})}_succeeded(r,n){Vl.debug("OPTIONS succeeded"),this._close(),Vl.debug('emit "succeeded"'),this.emit("succeeded",{originator:r,response:n})}},_u={};const pg=lt,Ra=mt(),mg=es(),Ni=new pg("Socket");_u.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Ni.warn("undefined JsSIP.Socket instance"),!1;try{if(!Ra.isString(c.url))throw Ni.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Ra.isString(c.via_transport))throw Ni.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(mg.parse(c.sip_uri,"SIP_URI")===-1)throw Ni.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(r=>{if(!Ra.isFunction(c[r]))throw Ni.warn(`missing or invalid JsSIP.Socket method: ${r}`),new Error(`Missing or invalid JsSIP.Socket method: ${r}`)})}catch{return!1}return!0};const gg=lt,vg=_u,Yc=De,Rt=new gg("Transport"),kt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Yc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Yc.CONNECTION_RECOVERY_MAX_INTERVAL}};var Tg=class{constructor(r,n=kt.recovery_options){Rt.debug("new()"),this.status=kt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(o){Rt.warn(`cannot use TextDecoder: ${o}`)}if(typeof r>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");r instanceof Array||(r=[r]),r.forEach(function(o){if(!vg.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:kt.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(Rt.debug("connect()"),this.isConnected()){Rt.debug("Transport is already connected");return}else if(this.isConnecting()){Rt.debug("Transport is connecting");return}this.close_requested=!1,this.status=kt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){Rt.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=kt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(r){if(Rt.debug("send()"),!this.isConnected())return Rt.warn("unable to send message, transport is not connected"),!1;const n=r.toString();return Rt.debug(`sending message:
115
+ `,1)[0],"Status_Line");if(n===-1){un.debug(`receiveNotify() | error parsing NOTIFY body: "${r.body}"`);return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:r,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:r,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:r,status_line:n});break;default:this.emit("failed",{request:r,status_line:n});break}}_requestSucceeded(r){un.debug("REFER succeeded"),un.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:r})}_requestFailed(r,n){un.debug("REFER failed"),un.debug('emit "requestFailed"'),this.emit("requestFailed",{response:r||null,cause:n})}};const Xm=pt.EventEmitter,Vc=Lt,Qm=lt,ae=De,cn=ps,jc=ir,qe=mt(),wi=qf,Zm=ts,Hl=Vf,eg=lr,bt=$m,Bc=Bf,tg=Km,sg=Jm,Gc=ds(),W=new Qm("RTCSession"),X={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},Fl=["audio","video"];var Gf=class Ja extends Xm{static get C(){return X}constructor(r){W.debug("new"),super(),this._id=null,this._ua=r,this._status=X.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:ae.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return X}get causes(){return ae.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(r){this._data=r}get status(){return this._status}isInProgress(){switch(this._status){case X.STATUS_NULL:case X.STATUS_INVITE_SENT:case X.STATUS_1XX_RECEIVED:case X.STATUS_INVITE_RECEIVED:case X.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case X.STATUS_ANSWERED:case X.STATUS_WAITING_FOR_ACK:case X.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case X.STATUS_CANCELED:case X.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(r,n={},o){console.log("rtcOfferConstraints connect"),W.debug("connect()");const a=r,t=qe.cloneObject(n.eventHandlers),s=qe.cloneArray(n.extraHeaders),p=qe.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),h=n.mediaStream||null,d=qe.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,v=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=v,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,r===void 0)throw new TypeError("Not enough arguments");if(this._status!==X.STATUS_NULL)throw new cn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new cn.NotSupportedError("WebRTC not supported");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&qe.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ae.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ae.SESSION_EXPIRES);for(const C in t)Object.prototype.hasOwnProperty.call(t,C)&&this.on(C,t[C]);this._from_tag=qe.newTag();const E=n.anonymous||!1,S={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(S.from_display_name="Anonymous",S.from_uri=new Gc("sip","anonymous","anonymous.invalid"),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push("Privacy: id")):n.fromUserName&&(S.from_uri=new Gc("sip",n.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(S.from_display_name=n.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Zm.InitialOutgoingInviteRequest(r,this._ua,S,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newRTCSession("local",this._request),this._sendInitialRequest(p,v,h)}init_incoming(r,n){W.debug("init_incoming()");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=X.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=qe.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=X.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),this._failed("local",null,ae.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===X.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),this._failed("system",null,ae.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from,n&&n(this),this._newRTCSession("remote",r),this._status!==X.STATUS_TERMINATED&&(r.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(r={}){W.debug("answer()");const n=this._request,o=qe.cloneArray(r.extraHeaders),a=qe.cloneObject(r.mediaConstraints),t=r.mediaStream||null,s=qe.cloneObject(r.pcConfig,{iceServers:[]}),p=r.rtcConstraints||null,h=r.rtcAnswerConstraints||null,d=qe.cloneObject(r.rtcOfferConstraints);let g,v=!1,E=!1,S=!1,C=!1;if(this._rtcAnswerConstraints=h,this._rtcOfferConstraints=r.rtcOfferConstraints||null,this._data=r.data||this._data,this._direction!=="incoming")throw new cn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==X.STATUS_WAITING_FOR_ANSWER)throw new cn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&qe.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=ae.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=ae.SESSION_EXPIRES),this._status=X.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const I=n.parseSDP();Array.isArray(I.media)||(I.media=[I.media]);for(const w of I.media)w.type==="audio"&&(v=!0,(!w.direction||w.direction==="sendrecv")&&(S=!0)),w.type==="video"&&(E=!0,(!w.direction||w.direction==="sendrecv")&&(C=!0));if(t&&a.audio===!1){g=t.getAudioTracks();for(const w of g)t.removeTrack(w)}if(t&&a.video===!1){g=t.getVideoTracks();for(const w of g)t.removeTrack(w)}!t&&a.audio===void 0&&(a.audio=S),!t&&a.video===void 0&&(a.video=C),!t&&!v&&!d.offerToReceiveAudio&&(a.audio=!1),!t&&!E&&!d.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(s,p),Promise.resolve().then(()=>{if(t)return t;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(w=>{throw this._status===X.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,ae.causes.USER_DENIED_MEDIA_ACCESS),W.warn('emit "getusermediafailed" [error:%o]',w),this.emit("getusermediafailed",w),new Error("getUserMedia() failed"))})}).then(w=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=w,w&&w.getTracks().forEach(F=>{this._connection.addTrack(F,w)})}).then(()=>{if(this._late_sdp)return;const w={originator:"remote",type:"offer",sdp:n.body};W.debug('emit "sdp"'),this.emit("sdp",w);const F=new RTCSessionDescription({type:"offer",sdp:w.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(F)).catch(L=>{throw n.reply(488),this._failed("system",null,ae.causes.WEBRTC_ERROR),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',L),this.emit("peerconnection:setremotedescriptionfailed",L),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",h).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(w=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,w,()=>{this._status=X.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,w),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,ae.causes.CONNECTION_ERROR)})}).catch(w=>{this._status!==X.STATUS_TERMINATED&&W.warn(w)})}terminate(r={}){W.debug("terminate()");const n=r.cause||ae.causes.BYE,o=qe.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===X.STATUS_TERMINATED)throw new cn.InvalidStateError(this._status);switch(this._status){case X.STATUS_NULL:case X.STATUS_INVITE_SENT:case X.STATUS_1XX_RECEIVED:if(W.debug("canceling session"),s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||ae.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===X.STATUS_NULL||this._status===X.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===X.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=X.STATUS_CANCELED,this._failed("local",null,ae.causes.CANCELED);break;case X.STATUS_WAITING_FOR_ANSWER:case X.STATUS_ANSWERED:if(W.debug("rejecting session"),s=s||480,s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),this._failed("local",null,ae.causes.REJECTED);break;case X.STATUS_WAITING_FOR_ACK:case X.STATUS_CONFIRMED:if(W.debug("terminating session"),p=r.reason_phrase||ae.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===X.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jc.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:d})=>{d===ae.ACK&&(this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===jc.C.STATUS_TERMINATED&&(this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(ae.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendDTMF(r,n={}){W.debug("sendDTMF() | tones: %s",r);let o=0,a=n.duration||null,t=n.interToneGap||null;const s=n.transportType||ae.DTMF_TRANSPORT.INFO;if(r===void 0)throw new TypeError("Not enough arguments");if(this._status!==X.STATUS_CONFIRMED&&this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_1XX_RECEIVED)throw new cn.InvalidStateError(this._status);if(s!==ae.DTMF_TRANSPORT.INFO&&s!==ae.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${s}`);if(typeof r=="number"&&(r=r.toString()),!r||typeof r!="string"||!r.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${r}`);if(a&&!qe.isDecimal(a))throw new TypeError(`Invalid tone duration: ${a}`);if(a?a<bt.C.MIN_DURATION?(W.debug(`"duration" value is lower than the minimum allowed, setting it to ${bt.C.MIN_DURATION} milliseconds`),a=bt.C.MIN_DURATION):a>bt.C.MAX_DURATION?(W.debug(`"duration" value is greater than the maximum allowed, setting it to ${bt.C.MAX_DURATION} milliseconds`),a=bt.C.MAX_DURATION):a=Math.abs(a):a=bt.C.DEFAULT_DURATION,n.duration=a,t&&!qe.isDecimal(t))throw new TypeError(`Invalid interToneGap: ${t}`);if(t?t<bt.C.MIN_INTER_TONE_GAP?(W.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${bt.C.MIN_INTER_TONE_GAP} milliseconds`),t=bt.C.MIN_INTER_TONE_GAP):t=Math.abs(t):t=bt.C.DEFAULT_INTER_TONE_GAP,s===ae.DTMF_TRANSPORT.RFC2833){const h=this._getDTMFRTPSender();h&&(r=h.toneBuffer+r,h.insertDTMF(r,a,t));return}if(this._tones){this._tones+=r;return}this._tones=r,p.call(this);function p(){let h;if(this._status===X.STATUS_TERMINATED||!this._tones||o>=this._tones.length){this._tones=null;return}const d=this._tones[o];if(o+=1,d===",")h=2e3;else{const g=new bt(this);n.eventHandlers={onFailed:()=>{this._tones=null}},g.send(d,n),h=a+t}setTimeout(p.bind(this),h)}}sendInfo(r,n,o={}){if(W.debug("sendInfo()"),this._status!==X.STATUS_CONFIRMED&&this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_1XX_RECEIVED)throw new cn.InvalidStateError(this._status);new Bc(this).send(r,n,o)}mute(r={audio:!0,video:!1}){W.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&r.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&r.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(r={audio:!0,video:!0}){W.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&r.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&r.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}hold(r={},n){if(W.debug("hold()"),this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:r.extraHeaders}),!0}unhold(r={},n){if(W.debug("unhold()"),this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:r.extraHeaders}),!0}renegotiate(r={},n){W.debug("renegotiate()");const o=r.rtcOfferConstraints||null;if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:ae.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),r.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:r.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:r.extraHeaders}),!0}refer(r,n){W.debug("refer()");const o=r;if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${o}`);const a=new sg(this);a.sendRefer(r,n);const t=a.id;return this._referSubscribers[t]=a,a.on("requestFailed",()=>{delete this._referSubscribers[t]}),a.on("accepted",()=>{delete this._referSubscribers[t]}),a.on("failed",()=>{delete this._referSubscribers[t]}),a}sendRequest(r,n){return W.debug("sendRequest()"),this._dialog.sendRequest(r,n)}receiveRequest(r){if(W.debug("receiveRequest()"),r.method===ae.CANCEL)(this._status===X.STATUS_WAITING_FOR_ANSWER||this._status===X.STATUS_ANSWERED)&&(this._status=X.STATUS_CANCELED,this._request.reply(487),this._failed("remote",r,ae.causes.CANCELED));else switch(r.method){case ae.ACK:if(this._status!==X.STATUS_WAITING_FOR_ACK)return;if(this._status=X.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!r.body){this.terminate({cause:ae.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:r.body};W.debug('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:ae.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",r);break;case ae.BYE:this._status===X.STATUS_CONFIRMED||this._status===X.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,ae.causes.BYE)):this._status===X.STATUS_INVITE_RECEIVED||this._status===X.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,ae.causes.BYE)):r.reply(403,"Wrong Status");break;case ae.INVITE:this._status===X.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case ae.INFO:if(this._status===X.STATUS_1XX_RECEIVED||this._status===X.STATUS_WAITING_FOR_ANSWER||this._status===X.STATUS_ANSWERED||this._status===X.STATUS_WAITING_FOR_ACK||this._status===X.STATUS_CONFIRMED){const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new bt(this).init_incoming(r):n!==void 0?new Bc(this).init_incoming(r):r.reply(415)}else r.reply(403,"Wrong Status");break;case ae.UPDATE:this._status===X.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case ae.REFER:this._status===X.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case ae.NOTIFY:this._status===X.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){W.warn("onTransportError()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ae.causes.CONNECTION_ERROR,cause:ae.causes.CONNECTION_ERROR})}onRequestTimeout(){W.warn("onRequestTimeout()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ae.causes.REQUEST_TIMEOUT,cause:ae.causes.REQUEST_TIMEOUT})}onDialogError(){W.warn("onDialogError()"),this._status!==X.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ae.causes.DIALOG_ERROR,cause:ae.causes.DIALOG_ERROR})}newDTMF(r){W.debug("newDTMF()"),this.emit("newDTMF",r)}newInfo(r){W.debug("newInfo()"),this.emit("newInfo",r)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(W.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(W.debug("_isReadyToReOffer() | session not established yet"),!1):(W.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(W.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(W.debug("close() | closing local MediaStream"),qe.closeMediaStream(this._localMediaStream)),this._status!==X.STATUS_TERMINATED){if(this._status=X.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(r){W.warn("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.destroyRTCSession(this)}}_setInvite2xxTimer(r,n){let o=wi.T1;function a(){this._status===X.STATUS_WAITING_FOR_ACK&&(r.reply(200,null,[`Contact: ${this._contact}`],n),o<wi.T2&&(o=o*2,o>wi.T2&&(o=wi.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===X.STATUS_WAITING_FOR_ACK&&(W.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(ae.BYE),this._ended("remote",null,ae.causes.NO_ACK))},wi.TIMER_H)}_createRTCConnection(r,n){this._connection=new RTCPeerConnection(r,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:ae.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ae.causes.RTP_TIMEOUT})}),W.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(r,n){if(W.debug("createLocalDescription()"),r!=="offer"&&r!=="answer")throw new Error(`createLocalDescription() | invalid type "${r}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>r==="offer"?o.createOffer(n).catch(a=>(W.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(n).catch(a=>(W.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(t=>(this._rtcReady=!0,W.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',t),this.emit("peerconnection:setlocaldescriptionfailed",t),Promise.reject(t)))).then(()=>{const a=n&&n.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const t={originator:"local",type:r,sdp:o.localDescription.sdp};return W.debug('emit "sdp"'),this.emit("sdp",t),Promise.resolve(t.sdp)}return new Promise(t=>{let s=!1,p,h;this._iceReady=!1;const d=()=>{o.removeEventListener("icecandidate",p),o.removeEventListener("icegatheringstatechange",h),s=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:r,sdp:o.localDescription.sdp};W.debug('emit "sdp"'),this.emit("sdp",g),t(g.sdp)};o.addEventListener("icecandidate",p=g=>{const v=g.candidate;v?this.emit("icecandidate",{candidate:v,ready:d}):s||d()}),o.addEventListener("icegatheringstatechange",h=()=>{o.iceGatheringState==="complete"&&!s&&d()})})})}_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 Hl(this,r,n,Hl.C.STATUS_EARLY),p.error?(W.debug(p.error),this._failed("remote",r,ae.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 h=new Hl(this,r,n);return h.error?(W.debug(h.error),this._failed("remote",r,ae.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_receiveReinvite(r){W.debug("receiveReinvite()");const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0,o={request:r,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const h=p.status_code||403,d=p.reason_phrase||"",g=qe.cloneArray(p.extraHeaders);if(this._status!==X.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);r.reply(h,d,g)}if(this.emit("reinvite",o),a)return;if(this._late_sdp=!1,!r.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(p=>{s.call(this,p)}).catch(()=>{r.reply(500)});return}if(n!=="application/sdp"){W.debug("invalid Content-Type"),r.reply(415);return}this._processInDialogSdpOffer(r).then(p=>{this._status!==X.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{W.warn(p)});function s(p){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(r,h),this._late_sdp&&(p=this._mangleOffer(p)),r.reply(200,null,h,p,()=>{this._status=X.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,p),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(r){W.debug("receiveUpdate()");const n=r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0,o={request:r,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const h=p.status_code||403,d=p.reason_phrase||"",g=qe.cloneArray(p.extraHeaders);if(this._status!==X.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);r.reply(h,d,g)}if(this.emit("update",o),a)return;if(!r.body){s.call(this,null);return}if(n!=="application/sdp"){W.debug("invalid Content-Type"),r.reply(415);return}this._processInDialogSdpOffer(r).then(p=>{this._status!==X.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{W.warn(p)});function s(p){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(r,h),r.reply(200,null,h,p),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(r){W.debug("_processInDialogSdpOffer()");const n=r.parseSDP();let o=!1;for(const s of n.media){if(Fl.indexOf(s.type)===-1)continue;const p=s.direction||n.direction||"sendrecv";if(p==="sendonly"||p==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:r.body};W.debug('emit "sdp"'),this.emit("sdp",a);const t=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(t).catch(s=>{throw r.reply(488),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',s),this.emit("peerconnection:setremotedescriptionfailed",s),s})}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(s=>{throw r.reply(500),W.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',s),s})}).catch(s=>{W.warn("_processInDialogSdpOffer() failed [error: %o]",s)}),this._connectionPromiseQueue}_receiveRefer(r){if(W.debug("receiveRefer()"),!r.refer_to){W.debug("no Refer-To header field present in REFER"),r.reply(400);return}if(r.refer_to.uri.scheme!==ae.SIP){W.debug("Refer-To header field points to a non-SIP URI scheme"),r.reply(416);return}r.reply(202);const n=new tg(this,r.cseq);W.debug('emit "refer"'),this.emit("refer",{request:r,accept:(t,s)=>{o.call(this,t,s)},reject:()=>{a.call(this)}});function o(t,s={}){if(t=typeof t=="function"?t:null,this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;const p=new Ja(this._ua);if(p.on("progress",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),p.on("accepted",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),p.on("_failed",({message:h,cause:d})=>{h?n.notify(h.status_code,h.reason_phrase):n.notify(487,d)}),r.refer_to.uri.hasHeader("replaces")){const h=decodeURIComponent(r.refer_to.uri.getHeader("replaces"));s.extraHeaders=qe.cloneArray(s.extraHeaders),s.extraHeaders.push(`Replaces: ${h}`)}p.connect(r.refer_to.uri.toAor(),s,t)}function a(){n.notify(603)}}_receiveNotify(r){switch(W.debug("receiveNotify()"),r.event||r.reply(400),r.event.event){case"refer":{let n,o;if(r.event.params&&r.event.params.id)n=r.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{r.reply(400,"Missing event id parameter");return}if(!o){r.reply(481,"Subscription does not exist");return}o.receiveNotify(r),r.reply(200);break}default:r.reply(489)}}_receiveReplaces(r){W.debug("receiveReplaces()");function n(a){if(this._status!==X.STATUS_WAITING_FOR_ACK&&this._status!==X.STATUS_CONFIRMED)return!1;const t=new Ja(this._ua);t.on("confirmed",()=>{this.terminate()}),t.init_incoming(r,a)}function o(){W.debug("Replaced INVITE rejected by the user"),r.reply(486)}this.emit("replaces",{request:r,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_sendInitialRequest(r,n,o){const a=new eg(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t)}});Promise.resolve().then(()=>{if(o)return o;if(r.audio||r.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(r).catch(t=>{throw this._status===X.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,ae.causes.USER_DENIED_MEDIA_ACCESS),W.warn('emit "getusermediafailed" [error:%o]',t),this.emit("getusermediafailed",t),t)})}).then(t=>{if(this._status===X.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=t,t&&t.getTracks().forEach(s=>{this._connection.addTrack(s,t)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(s=>{throw this._failed("local",null,ae.causes.WEBRTC_ERROR),s})}).then(t=>{if(this._is_canceled||this._status===X.STATUS_TERMINATED)throw new Error("terminated");this._request.body=t,this._status=X.STATUS_INVITE_SENT,W.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(t=>{this._status!==X.STATUS_TERMINATED&&W.warn(t)})}_getDTMFRTPSender(){const r=this._connection.getSenders().find(n=>n.track&&n.track.kind==="audio");if(!(r&&r.dtmf)){W.warn("sendDTMF() | no local audio track to send DTMF with");return}return r.dtmf}_receiveInviteResponse(r){if(W.debug("receiveInviteResponse()"),this._dialog&&r.status_code>=200&&r.status_code<=299)if(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(ae.ACK);return}else{const n=new Hl(this,r,"UAC");if(n.error!==void 0){W.debug(n.error);return}this.sendRequest(ae.ACK),this.sendRequest(ae.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!==X.STATUS_INVITE_SENT&&this._status!==X.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(r.status_code):this._status=X.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(r.status_code):{if(!r.to_tag){W.debug("1xx response received without to tag");break}if(r.hasHeader("contact")&&!this._createDialog(r,"UAC",!0))break;if(this._status=X.STATUS_1XX_RECEIVED,!r.body){this._progress("remote",r);break}const n={originator:"remote",type:"answer",sdp:r.body};W.debug('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=>{W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(r.status_code):{if(this._status=X.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,ae.causes.MISSING_SDP),this._failed("remote",r,ae.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(r,"UAC"))break;const n={originator:"remote",type:"answer",sdp:r.body};W.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(r,500,a.toString()),this._failed("local",r,ae.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(o).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(ae.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(r,488,"Not Acceptable Here"),this._failed("remote",r,ae.causes.BAD_MEDIA_DESCRIPTION),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const n=qe.sipErrorCause(r.status_code);this._failed("remote",r,n)}}}_sendReinvite(r={}){W.debug("sendReinvite()");const n=qe.cloneArray(r.extraHeaders),o=qe.cloneObject(r.eventHandlers),a=r.rtcOfferConstraints||this._rtcOfferConstraints||null;let t=!1;n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(h=>{h=this._mangleOffer(h);const d={originator:"local",type:"offer",sdp:h};W.debug('emit "sdp"'),this.emit("sdp",d),this.sendRequest(ae.INVITE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:g=>{s.call(this,g),t=!0},onErrorResponse:g=>{p.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{p()});function s(h){if(this._status===X.STATUS_TERMINATED||(this.sendRequest(ae.ACK),t))return;if(this._handleSessionTimersInIncomingResponse(h),h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){p.call(this);return}}else{p.call(this);return}const d={originator:"remote",type:"answer",sdp:h.body};W.debug('emit "sdp"'),this.emit("sdp",d);const g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(h)}).catch(v=>{p.call(this),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',v),this.emit("peerconnection:setremotedescriptionfailed",v)})}function p(h){o.failed&&o.failed(h)}}_sendUpdate(r={}){W.debug("sendUpdate()");const n=qe.cloneArray(r.extraHeaders),o=qe.cloneObject(r.eventHandlers),a=r.rtcOfferConstraints||this._rtcOfferConstraints||null,t=r.sdpOffer||!1;let s=!1;n.push(`Contact: ${this._contact}`),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),t?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const g={originator:"local",type:"offer",sdp:d};W.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(ae.UPDATE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:v=>{p.call(this,v),s=!0},onErrorResponse:v=>{h.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h.call(this)})):this.sendRequest(ae.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:d=>{p.call(this,d)},onErrorResponse:d=>{h.call(this,d)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function p(d){if(this._status!==X.STATUS_TERMINATED&&!s)if(this._handleSessionTimersInIncomingResponse(d),t){if(d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const g={originator:"remote",type:"answer",sdp:d.body};W.debug('emit "sdp"'),this.emit("sdp",g);const v=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(v)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(E=>{h.call(this),W.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),this.emit("peerconnection:setremotedescriptionfailed",E)})}else o.succeeded&&o.succeeded(d)}function h(d){o.failed&&o.failed(d)}}_acceptAndTerminate(r,n,o){W.debug("acceptAndTerminate()");const a=[];n&&(o=o||ae.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(this._dialog||this._createDialog(r,"UAC"))&&(this.sendRequest(ae.ACK),this.sendRequest(ae.BYE,{extraHeaders:a})),this._status=X.STATUS_TERMINATED}_mangleOffer(r){if(!this._localHold&&!this._remoteHold)return r;if(r=Vc.parse(r),this._localHold&&!this._remoteHold){W.debug("mangleOffer() | me on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="sendonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="sendonly")}else if(this._localHold&&this._remoteHold){W.debug("mangleOffer() | both on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){W.debug("mangleOffer() | remote on hold, mangling offer");for(const n of r.media)Fl.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Vc.write(r)}_setLocalMediaStatus(){let r=!0,n=!0;(this._localHold||this._remoteHold)&&(r=!1,n=!1),this._audioMuted&&(r=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!r),this._toggleMuteVideo(!n)}_handleSessionTimersInIncomingRequest(r,n){if(!this._sessionTimers.enabled)return;let o;r.session_expires&&r.session_expires>=ae.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=r.session_expires,o=r.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(r){if(!this._sessionTimers.enabled)return;let n;r.session_expires&&r.session_expires>=ae.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()}_runSessionTimer(){const r=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==X.STATUS_TERMINATED&&this._isReadyToReOffer()&&(W.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===ae.UPDATE?this._sendUpdate():this._sendReinvite())},r*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==X.STATUS_TERMINATED&&(W.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:ae.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},r*1100)}_toggleMuteAudio(r){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!r}_toggleMuteVideo(r){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.track.enabled=!r}_newRTCSession(r,n){W.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:r,session:this,request:n})}_connecting(r){W.debug("session connecting"),W.debug('emit "connecting"'),this.emit("connecting",{request:r})}_progress(r,n){W.debug("session progress"),W.debug('emit "progress"'),this.emit("progress",{originator:r,response:n||null})}_accepted(r,n){W.debug("session accepted"),this._start_time=new Date,W.debug('emit "accepted"'),this.emit("accepted",{originator:r,response:n||null})}_confirmed(r,n){W.debug("session confirmed"),this._is_confirmed=!0,W.debug('emit "confirmed"'),this.emit("confirmed",{originator:r,ack:n||null})}_ended(r,n,o){W.debug("session ended"),this._end_time=new Date,this._close(),W.debug('emit "ended"'),this.emit("ended",{originator:r,message:n||null,cause:o})}_failed(r,n,o){W.debug("session failed"),W.debug('emit "_failed"'),this.emit("_failed",{originator:r,message:n||null,cause:o}),this._close(),W.debug('emit "failed"'),this.emit("failed",{originator:r,message:n||null,cause:o})}_onhold(r){W.debug("session onhold"),this._setLocalMediaStatus(),W.debug('emit "hold"'),this.emit("hold",{originator:r})}_onunhold(r){W.debug("session onunhold"),this._setLocalMediaStatus(),W.debug('emit "unhold"'),this.emit("unhold",{originator:r})}_onmute({audio:r,video:n}){W.debug("session onmute"),this._setLocalMediaStatus(),W.debug('emit "muted"'),this.emit("muted",{audio:r,video:n})}_onunmute({audio:r,video:n}){W.debug("session onunmute"),this._setLocalMediaStatus(),W.debug('emit "unmuted"'),this.emit("unmuted",{audio:r,video:n})}};const ng=xt(Gf),rg=pt.EventEmitter,ig=lt,Ca=De,lg=ts,Oi=mt(),og=lr,Kc=ps,ag=ds(),ql=new ig("Message");var ug=class extends rg{constructor(r){super(),this._ua=r,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(r,n,o={}){const a=r;if(r===void 0||n===void 0)throw new TypeError("Not enough arguments");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);const t=Oi.cloneArray(o.extraHeaders),s=Oi.cloneObject(o.eventHandlers),p=o.contentType||"text/plain",h={};o.fromUserName&&(h.from_uri=new ag("sip",o.fromUserName,this._ua.configuration.uri.host),t.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(h.from_display_name=o.fromDisplayName);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&this.on(g,s[g]);t.push(`Content-Type: ${p}`),this._request=new lg.OutgoingRequest(Ca.MESSAGE,r,this._ua,h,t),n&&(this._request.body=n);const d=new og(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:g=>{this._receiveResponse(g)}});this._newMessage("local",this._request),d.send()}init_incoming(r){this._request=r,this._newMessage("remote",r),this._is_replied||(this._is_replied=!0,r.reply(200)),this._close()}accept(r={}){const n=Oi.cloneArray(r.extraHeaders),o=r.body;if(this._direction!=="incoming")throw new Kc.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,o)}reject(r={}){const n=r.status_code||480,o=r.reason_phrase,a=Oi.cloneArray(r.extraHeaders),t=r.body;if(this._direction!=="incoming")throw new Kc.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,o,a,t)}_receiveResponse(r){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(r.status_code):break;case/^2[0-9]{2}$/.test(r.status_code):this._succeeded("remote",r);break;default:{const n=Oi.sipErrorCause(r.status_code);this._failed("remote",r,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Ca.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Ca.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(r,n){r==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):r==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:r,message:this,request:n})}_failed(r,n,o){ql.debug("MESSAGE failed"),this._close(),ql.debug('emit "failed"'),this.emit("failed",{originator:r,response:n||null,cause:o})}_succeeded(r,n){ql.debug("MESSAGE succeeded"),this._close(),ql.debug('emit "succeeded"'),this.emit("succeeded",{originator:r,response:n})}};const cg=pt.EventEmitter,fg=lt,Aa=De,hg=ts,Di=mt(),_g=lr,Wc=ps,Vl=new fg("Options");var dg=class extends cg{constructor(r){super(),this._ua=r,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(r,n,o={}){const a=r;if(r===void 0)throw new TypeError("A target is required for OPTIONS");if(r=this._ua.normalizeTarget(r),!r)throw new TypeError(`Invalid target: ${a}`);const t=Di.cloneArray(o.extraHeaders),s=Di.cloneObject(o.eventHandlers),p=o.contentType||"application/sdp";for(const d in s)Object.prototype.hasOwnProperty.call(s,d)&&this.on(d,s[d]);t.push(`Content-Type: ${p}`),this._request=new hg.OutgoingRequest(Aa.OPTIONS,r,this._ua,null,t),n&&(this._request.body=n);const h=new _g(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:d=>{this._receiveResponse(d)}});this._newOptions("local",this._request),h.send()}init_incoming(r){this._request=r,this._newOptions("remote",r),this._is_replied||(this._is_replied=!0,r.reply(200)),this._close()}accept(r={}){const n=Di.cloneArray(r.extraHeaders),o=r.body;if(this._direction!=="incoming")throw new Wc.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,o)}reject(r={}){const n=r.status_code||480,o=r.reason_phrase,a=Di.cloneArray(r.extraHeaders),t=r.body;if(this._direction!=="incoming")throw new Wc.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,o,a,t)}_receiveResponse(r){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(r.status_code):break;case/^2[0-9]{2}$/.test(r.status_code):this._succeeded("remote",r);break;default:{const n=Di.sipErrorCause(r.status_code);this._failed("remote",r,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Aa.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Aa.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(r,n){r==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):r==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:r,message:this,request:n})}_failed(r,n,o){Vl.debug("OPTIONS failed"),this._close(),Vl.debug('emit "failed"'),this.emit("failed",{originator:r,response:n||null,cause:o})}_succeeded(r,n){Vl.debug("OPTIONS succeeded"),this._close(),Vl.debug('emit "succeeded"'),this.emit("succeeded",{originator:r,response:n})}},_u={};const pg=lt,Ra=mt(),mg=es(),Ni=new pg("Socket");_u.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Ni.warn("undefined JsSIP.Socket instance"),!1;try{if(!Ra.isString(c.url))throw Ni.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Ra.isString(c.via_transport))throw Ni.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(mg.parse(c.sip_uri,"SIP_URI")===-1)throw Ni.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(r=>{if(!Ra.isFunction(c[r]))throw Ni.warn(`missing or invalid JsSIP.Socket method: ${r}`),new Error(`Missing or invalid JsSIP.Socket method: ${r}`)})}catch{return!1}return!0};const gg=lt,vg=_u,Yc=De,Rt=new gg("Transport"),kt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Yc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Yc.CONNECTION_RECOVERY_MAX_INTERVAL}};var Tg=class{constructor(r,n=kt.recovery_options){Rt.debug("new()"),this.status=kt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(o){Rt.warn(`cannot use TextDecoder: ${o}`)}if(typeof r>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");r instanceof Array||(r=[r]),r.forEach(function(o){if(!vg.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:kt.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(Rt.debug("connect()"),this.isConnected()){Rt.debug("Transport is already connected");return}else if(this.isConnecting()){Rt.debug("Transport is connecting");return}this.close_requested=!1,this.status=kt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){Rt.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=kt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(r){if(Rt.debug("send()"),!this.isConnected())return Rt.warn("unable to send message, transport is not connected"),!1;const n=r.toString();return Rt.debug(`sending message:
116
116
 
117
117
  ${n}
118
118
  `),this.socket.send(n)}isConnected(){return this.status===kt.STATUS_CONNECTED}isConnecting(){return this.status===kt.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let r=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);r<this.recovery_options.min_interval?r=this.recovery_options.min_interval:r>this.recovery_options.max_interval&&(r=this.recovery_options.max_interval),Rt.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${r} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},r*1e3)}_getSocket(){let r=[];if(this.sockets.forEach(o=>{o.status!==kt.SOCKET_STATUS_ERROR&&(r.length===0?r.push(o):o.weight>r[0].weight?r=[o]:o.weight===r[0].weight&&r.push(o))}),r.length===0){this.sockets.forEach(o=>{o.status=kt.SOCKET_STATUS_READY}),this._getSocket();return}const n=Math.floor(Math.random()*r.length);this.socket=r[n].socket}_onConnect(){this.recover_attempts=0,this.status=kt.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(r,n,o){this.status=kt.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:r,code:n,reason:o}),!this.close_requested&&(this.sockets.forEach(function(a){this.socket===a.socket&&(a.status=kt.SOCKET_STATUS_ERROR)},this),this._reconnect(r))}_onData(r){if(r===`\r
@@ -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 ym(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=Se.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=Se.STATUS_INVITE_SENT}terminate(r={}){console.log("terminate",this);const n=r.cause||be.causes.BYE,o=Ps.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===Se.STATUS_TERMINATED)throw new wm.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Se.STATUS_NULL:case Se.STATUS_INVITE_SENT:case Se.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||be.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Se.STATUS_NULL||this._status===Se.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Se.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Se.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,be.causes.CANCELED);break;case Se.STATUS_WAITING_FOR_ANSWER:case Se.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,be.causes.REJECTED);break;case Se.STATUS_WAITING_FOR_ACK:case Se.STATUS_CONFIRMED:if(p=r.reason_phrase||be.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===Se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Li.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:d})=>{d===be.ACK&&(this.sendRequest(be.BYE,{extraHeaders:o,body:a}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Li.C.STATUS_TERMINATED&&(this.sendRequest(be.BYE,{extraHeaders:o,body:a}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else console.log("here it is"),this.sendRequest(be.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 Qn("");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 Qn(r.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new um(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Ps.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(be.ACK);return}else{const n=new $l(this,r,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(be.ACK),this.sendRequest(be.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!==Se.STATUS_INVITE_SENT&&this._status!==Se.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(r.status_code):this._status=Se.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=Se.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=Se.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,be.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",r,be.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,be.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(be.ACK),this._confirmed("local",null)});break}default:{const n=Ps.sipErrorCause(r.status_code);console.log("failed 5"),this._failed("remote",r,n)}}}sendMSRP(r){const n=new Qn("");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",Ps.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 Qn("");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 Qn("");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=Se.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=Ps.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=Se.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),console.log("failed 6"),this._failed("local",null,be.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Se.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),console.log("failed 7"),this._failed("system",null,be.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!==Se.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!==Se.STATUS_TERMINATED){if(this._status=Se.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 $l(this,r,n,$l.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",r,be.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 h=new $l(this,r,n);return h.error?(console.log("failed 9"),this._failed("remote",r,be.causes.INTERNAL_ERROR),!1):(this._dialog=h,!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 Se.STATUS_CANCELED:case Se.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>=be.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===be.CANCEL)(this._status===Se.STATUS_WAITING_FOR_ANSWER||this._status===Se.STATUS_ANSWERED)&&(this._status=Se.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",r,be.causes.CANCELED));else switch(r.method){case be.ACK:if(this._status!==Se.STATUS_WAITING_FOR_ACK)return;if(this._status=Se.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!r.body){this.terminate({cause:be.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:be.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 be.BYE:this._status===Se.STATUS_CONFIRMED||this._status===Se.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,be.causes.BYE)):this._status===Se.STATUS_INVITE_RECEIVED||this._status===Se.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,be.causes.BYE)):r.reply(403,"Wrong Status");break;case be.INVITE:this._status===Se.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case be.INFO:this._status===Se.STATUS_1XX_RECEIVED||this._status===Se.STATUS_WAITING_FOR_ANSWER||this._status===Se.STATUS_ANSWERED||this._status===Se.STATUS_WAITING_FOR_ACK||this._status===Se.STATUS_CONFIRMED?(r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new jm(this).init_incoming(r):r.reply(415):r.reply(403,"Wrong Status");break;case be.UPDATE:this._status===Se.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case be.REFER:this._status===Se.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case be.NOTIFY:this._status===Se.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:be.causes.CONNECTION_ERROR,cause:be.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:be.causes.REQUEST_TIMEOUT,cause:be.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:be.causes.DIALOG_ERROR,cause:be.causes.DIALOG_ERROR})}}const Kt=console,tf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{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){Kt.debug("Request-URI does not point to us"),r.method!==De.ACK&&r.reply_sl(404);return}if(r.ruri.scheme===De.SIPS){r.reply_sl(416);return}if(Li.checkTransaction(this,r))return;if(n===De.INVITE?new Li.InviteServerTransaction(this,this._transport,r):n!==De.ACK&&n!==De.CANCEL&&new Li.NonInviteServerTransaction(this,this._transport,r),n===De.OPTIONS){if(this.listeners("newOptions").length===0){r.reply(200);return}new Ac.Options(this).init_incoming(r)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){r.reply(405);return}new Ac.Message(this).init_incoming(r)}else if(n===De.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===De.NOTIFY?(a=this._findSession(r),a?a.receiveRequest(r):(Kt.debug("received NOTIFY request for a non existent subscription"),r.reply(481,"Subscription does not exist"))):n!==De.ACK&&r.reply(481);else switch(n){case De.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 ef(this),a.init_incoming(r)):(a=new ng(this),a.init_incoming(r));else Kt.warn("INVITE received but WebRTC is not supported"),r.reply(488);break;case De.BYE:r.reply(481);break;case De.CANCEL:a=this._findSession(r),a?a.receiveRequest(r):Kt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:r.event,request:r}),r.reply(200);break;default:r.reply(405);break}}startMSRP(r,n){Kt.debug("startMSRP()",n);const o=new ef(this);return o.connect(r),o}terminateMSRPSessions(r){Kt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(r)}stop(){if(Kt.debug("stop()"),this._dynConfiguration={},this._status===tf.STATUS_USER_CLOSED){Kt.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)){Kt.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)){Kt.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=tf.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 gt={};gt.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)};gt.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)};gt.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)};gt.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};gt.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=h=>{h?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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]};gt.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=h=>{h?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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=h=>{h?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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=h=>{h?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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(h=>r.call(n||globalThis,h,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)});gt.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};gt.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 Jf={};(function(c){const r=gt;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)}})})(Jf);const Xg=gt,Qg=Jf;var sf=Object.assign(Xg,{instanceMethods:Qg});function Pa(c){return c<10?`0${c}`:`${c}`}function Zg(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=`${Pa(r)}:${Pa(n)}:${Pa(o)}`;return{seconds:o,minutes:n,hours:r,formatted:a}}function ev(c,r){return Object.keys(c).filter(n=>r.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const Jt=new AudioContext,tv=["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"],sv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function nf(c){const r={};return tv.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r.localHold=c._localHold,r}function rf(c){const r={};return sv.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r}function lf(c,r){const n=Jt.createMediaStreamSource(c),o=Jt.createMediaStreamDestination(),a=Jt.createGain();return n.connect(a),a.connect(o),a.gain.value=r,o.stream}function nv(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 rv(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}var iv={exports:{}};(function(c){var r=function(n){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(Q,G,B){Q[G]=B.value},s,p=typeof Symbol=="function"?Symbol:{},h=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function v(Q,G,B){return Object.defineProperty(Q,G,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[G]}try{v({},"")}catch{v=function(G,B,te){return G[B]=te}}function E(Q,G,B,te){var de=G&&G.prototype instanceof ie?G: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,G,B){try{return{type:"normal",arg:Q.call(G,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,h,function(){return this});var me=Object.getPrototypeOf,M=me&&me(me(Z([])));M&&M!==o&&a.call(M,h)&&(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 j(Q){["next","throw","return"].forEach(function(G){v(Q,G,function(B){return this._invoke(G,B)})})}n.isGeneratorFunction=function(Q){var G=typeof Q=="function"&&Q.constructor;return G?G===N||(G.displayName||G.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 V(Q,G){function B(Ae,Ue,ye,ne){var Te=S(Q[Ae],Q,Ue);if(Te.type==="throw")ne(Te.arg);else{var Qe=Te.arg,st=Qe.value;return st&&typeof st=="object"&&a.call(st,"__await")?G.resolve(st.__await).then(function(ge){B("next",ge,ye,ne)},function(ge){B("throw",ge,ye,ne)}):G.resolve(st).then(function(ge){Qe.value=ge,ye(Qe)},function(ge){return B("throw",ge,ye,ne)})}}var te;function de(Ae,Ue){function ye(){return new G(function(ne,Te){B(Ae,Ue,ne,Te)})}return te=te?te.then(ye,ye):ye()}t(this,"_invoke",{value:de})}j(V.prototype),v(V.prototype,d,function(){return this}),n.AsyncIterator=V,n.async=function(Q,G,B,te,de){de===void 0&&(de=Promise);var Ae=new V(E(Q,G,B,te),de);return n.isGeneratorFunction(G)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function Y(Q,G,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 Xe()}for(B.method=Ae,B.arg=Ue;;){var ye=B.delegate;if(ye){var ne=$(ye,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,G,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,G){var B=G.method,te=Q.iterator[B];if(te===s)return G.delegate=null,B==="throw"&&Q.iterator.return&&(G.method="return",G.arg=s,$(Q,G),G.method==="throw")||B!=="return"&&(G.method="throw",G.arg=new TypeError("The iterator does not provide a '"+B+"' method")),L;var de=S(te,Q.iterator,G.arg);if(de.type==="throw")return G.method="throw",G.arg=de.arg,G.delegate=null,L;var Ae=de.arg;if(!Ae)return G.method="throw",G.arg=new TypeError("iterator result is not an object"),G.delegate=null,L;if(Ae.done)G[Q.resultName]=Ae.value,G.next=Q.nextLoc,G.method!=="return"&&(G.method="next",G.arg=s);else return Ae;return G.delegate=null,L}j(D),v(D,g,"Generator"),v(D,h,function(){return this}),v(D,"toString",function(){return"[object Generator]"});function z(Q){var G={tryLoc:Q[0]};1 in Q&&(G.catchLoc=Q[1]),2 in Q&&(G.finallyLoc=Q[2],G.afterLoc=Q[3]),this.tryEntries.push(G)}function U(Q){var G=Q.completion||{};G.type="normal",delete G.arg,Q.completion=G}function P(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(z,this),this.reset(!0)}n.keys=function(Q){var G=Object(Q),B=[];for(var te in G)B.push(te);return B.reverse(),function de(){for(;B.length;){var Ae=B.pop();if(Ae in G)return de.value=Ae,de.done=!1,de}return de.done=!0,de}};function Z(Q){if(Q){var G=Q[h];if(G)return G.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:Xe}}n.values=Z;function Xe(){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 G in this)G.charAt(0)==="t"&&a.call(this,G)&&!isNaN(+G.slice(1))&&(this[G]=s)},stop:function(){this.done=!0;var Q=this.tryEntries[0],G=Q.completion;if(G.type==="throw")throw G.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var G=this;function B(ne,Te){return Ae.type="throw",Ae.arg=Q,G.next=ne,Te&&(G.method="next",G.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"),ye=a.call(de,"finallyLoc");if(Ue&&ye){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(ye){if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,G){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<=G&&G<=de.finallyLoc&&(de=null);var Ae=de?de.completion:{};return Ae.type=Q,Ae.arg=G,de?(this.method="next",this.next=de.finallyLoc,L):this.complete(Ae)},complete:function(Q,G){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"&&G&&(this.next=G),L},finish:function(Q){for(var G=this.tryEntries.length-1;G>=0;--G){var B=this.tryEntries[G];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),U(B),L}},catch:function(Q){for(var G=this.tryEntries.length-1;G>=0;--G){var B=this.tryEntries[G];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,G,B){return this.delegate={iterator:Z(Q),resultName:G,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)}})(iv);var Xf={exports:{}};(function(c){(function(r,n){c.exports?c.exports=n():r.log=n()})(nh,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 h(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&&(h.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 j=(a[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=j;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+j+";"}catch{}}}function ve(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var j=window.document.cookie,V=j.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(j.slice(V))[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,j){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,j!==!1&&H(D),h.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})})(Xf);var Tt=Xf.exports;const fs=()=>`${new Date().toISOString()} | metrics`,hs=(c,r,n)=>`${c} | ${r} | ${n}`;Tt.setDefaultLevel(Tt.levels.TRACE);const lv=c=>{Tt.info(hs(fs(),"log ",`set log level to ${c?"verbose":"info"}`)),Tt.setLevel(c?Tt.levels.TRACE:Tt.levels.INFO)},ov=c=>{const r=[...Object.keys(Tt.levels)];r.includes(c)?(Tt.info(hs(fs(),"log ",`update log level to ${c.toLowerCase()}`)),Tt.setLevel(c)):Tt.warn(hs(fs(),"log ","Incorrect log level please choose one of "),r)},Ne=(c,r,n)=>{n?Tt.debug(hs(fs(),c,r),n):Tt.debug(hs(fs(),c,r))},ka=(c,r)=>{Tt.info(hs(fs(),c,r))},dn=(c,r)=>{Tt.info(hs(fs(),c,r))},oo=(c,r)=>{Tt.warn(hs(fs(),c,r))},tr=(c,r)=>{Tt.error(hs(fs(),c,r))};function av(c){return Math.floor(Math.random()*c).toString()}function of(c,r){let n=r;return c.forEach(o=>{n=n.replace(o,"")}),n}function uv(c,r){let n="";for(let o=0;o<r;o+=1)n+=c[av(c.length)];return n}function cv({length:c=20,useLetters:r=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],h=[],d=[];return r&&(a.length&&(t=of(a,t)),h=t.split("")),n&&(a.length&&(s=of(a,s)),d=s.split("")),p=[...h,...d,...o],uv(p,c)}var fv=cv;const $i=xt(fv),hv=()=>"WebRTCMetrics",_v=()=>"5.0.3",Me={INBOUND:"inbound",OUTBOUND:"outbound"},cs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ui={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},dv=()=>({...{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:[]}}),Qf={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:Me.INBOUND},Zf={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:Me.OUTBOUND},eh={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:Me.INBOUND},th={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:Me.OUTBOUND},pv=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}}},mv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${$i()}`,cid:`c-${$i()}`,uid:`u-${$i()}`,record:!1,ticket:!0},qt={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"},Pi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Ma={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ee={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},xa="config ",gv=(c,r={},n)=>{const o={...n,...r};return r.pname||oo(xa,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),r.cid||oo(xa,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),r.uid||oo(xa,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},vv=(c={})=>{const r={...mv,...c};return r.name=hv(),r.version=_v(),r},el=(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},Ms=c=>c.reduce((r,n)=>r+n,0)/c.length,Tv=()=>`probe-${$i()}`,Ev=()=>`coltr-${$i()}`,af=c=>new Promise(r=>setTimeout(r,c)),Za=(c,r,n)=>{r?c.call(r,n):c(n)},Be=(c,r,n,o)=>{const a=el(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=el(c,r,n,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},fn=(c,r,n)=>el(c,r,n).reduce((a,t)=>a+t,0),Ge=(c,r,n,o)=>{const a=el(c,r,n,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,r,n,o)=>{const a=el(c,r,n,!1,o);return a.length===0?null:Math.max(...a)},ct=(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},yv=c=>c.slice().pop(),rt=(c,r,n)=>{if(!r)return null;const o={};let a=r[k.AUDIO][c];a||(a=n===Me.INBOUND?{...Qf}:{...Zf}),o[k.AUDIO]=a;let t=r[k.VIDEO][c];return t||(t=n===Me.INBOUND?{...eh}:{...th}),o[k.VIDEO]=t,o},ki="exporter ",Sv="2.0",uf=(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},Cv=(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)},Av=c=>ct(c,"network","local_candidate_type")!=="relay"?`direct/${ct(c,"network","local_candidate_protocol")}`:`turn/${ct(c,"network","local_candidate_relay_protocol")}`,Rv=c=>{const r=ct(c,"network","remote_candidate_type"),n=ct(c,"network","remote_candidate_protocol");return r!=="relay"?`direct/${n}`:`turn/${n}`};class Iv{constructor(r){this._start=null,this._end=null,this._cfg=r,this._referenceReport=null,this._reports=[],this._events=[]}start(){ka(ki,"start() - start exporter...");const r=new Date;return this._start=r.toJSON(),r}stop(){ka(ki,"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(ki,`addReport() - add report to exporter at ${r.timestamp}`),this._reports.push(r))}addCustomEvent(r){this._events.push(r)}reset(){ka(ki,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(ki,"ticket() - generate ticket");const r=ct(this._reports,"audio","total_packets_lost_in"),n=ct(this._reports,"audio","total_packets_in"),o=ct(this._reports,"video","total_packets_lost_in"),a=ct(this._reports,"video","total_packets_in"),t={},s=yv(this._reports);return s&&(Object.keys(s[k.AUDIO]).forEach(p=>{const h=s[k.AUDIO][p];if(t[h.ssrc]={type:k.AUDIO,direction:h.direction},h.direction===Me.INBOUND){const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_in",!1,p),min:Ge(this._reports,k.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,k.AUDIO,"delta_jitter_ms_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,k.AUDIO,"delta_kbs_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,k.AUDIO,"delta_KBytes_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,k.AUDIO,"mos_emodel_in",p),volatility:Be(this._reports,k.AUDIO,"mos_emodel_in",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_in",!1,p),min:Ge(this._reports,k.AUDIO,"mos_in",p),max:Ke(this._reports,k.AUDIO,"mos_in",p),volatility:Be(this._reports,k.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},S=ct(this._reports,k.AUDIO,"total_packets_lost_in",p),C=ct(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:Ge(this._reports,k.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,k.AUDIO,"delta_jitter_ms_out",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,k.AUDIO,"delta_kbs_out",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,k.AUDIO,"delta_KBytes_out",p),volatility:Be(this._reports,k.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:uf(this._reports,k.AUDIO,p),min:Ge(this._reports,k.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,k.AUDIO,"delta_rtt_ms_out",p),volatility:Be(this._reports,k.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=ct(this._reports,k.AUDIO,"total_packets_lost_out",p),C=ct(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:Ge(this._reports,k.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,k.AUDIO,"mos_emodel_out",p),volatility:Be(this._reports,k.AUDIO,"mos_emodel_out",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_out",!1,p),min:Ge(this._reports,k.AUDIO,"mos_out",p),max:Ke(this._reports,k.AUDIO,"mos_out",p),volatility:Be(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 h=s[k.VIDEO][p];if(t[p]={type:k.VIDEO,direction:h.direction},h.direction===Me.INBOUND){const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_in",!1,p),min:Ge(this._reports,k.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,k.VIDEO,"delta_jitter_ms_in",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,k.VIDEO,"delta_kbs_in",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,k.VIDEO,"delta_KBytes_in",p),volatility:Be(this._reports,k.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=ct(this._reports,k.VIDEO,"total_packets_lost_in",p),S=ct(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:Ge(this._reports,k.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,k.VIDEO,"delta_jitter_ms_out",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,k.VIDEO,"delta_kbs_out",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,k.VIDEO,"delta_KBytes_out",p),volatility:Be(this._reports,k.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:uf(this._reports,k.VIDEO,p),min:Ge(this._reports,k.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,k.VIDEO,"delta_rtt_ms_out",p),volatility:Be(this._reports,k.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=ct(this._reports,k.VIDEO,"total_packets_lost_out",p),C=ct(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:Sv,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:Cv(this._reports,"data"),min:Ge(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Be(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:Ge(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Be(this._reports,"data","delta_kbs_in")},out:{avg:We(this._reports,"data","delta_kbs_out"),min:Ge(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Be(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:Ge(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Be(this._reports,"data","delta_KBytes_in")},out:{avg:We(this._reports,"data","delta_KBytes_out"),min:Ge(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Be(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Av(this._reports),remoteConnection:Rv(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 Us="extractor ",cf=(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,h=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])-h===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])-h),{rtt:g,totalRTT:v,totalRTTMeasurements:E}},bv=(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}},Kl=(c,r,n)=>c[q.TIMESTAMP]===n[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),wv=(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}},Ov=(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}},ff=(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,h=c[q.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=n.timestamp;!g&&d&&(g=d);const v=g?h-g:0,E=v>0?p*.008*1024/v*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},hf=(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}},_f=(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,h=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:h,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:I}},Dv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",Nv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return Pi.WIFI;switch(c[q.NETWORK_TYPE]){case Ma.ETHERNET:return Pi.ETHERNET;case Ma.CELLULAR_4G:return Pi.CELLULAR_4G;case Ma.WIFI:return Pi.WIFI;default:return Pi.CELLULAR}},df=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]},Uv=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}},Pv=(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}},kv=(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}),xv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),Lv=(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,h=n?n.timestamp:null;let d=r.timestamp;!d&&h&&(d=h);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}},$v=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}},Hv=(c,r,n,o)=>{if(!c)return[];switch(c[q.TYPE]){case qt.CANDIDATE_PAIR:let a=!1;if(c[q.NOMINATED]&&c[q.STATE]===k.SUCCEEDED&&(a=!0,Ne(Us,`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],h=Lv(c,r,o),d=$v(c),g=bv(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:h.total_KBytes_received}},{type:ee.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ee.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ee.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ee.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ee.DATA,value:{delta_kbs_out:h.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 qt.LOCAL_CANDIDATE:if(c[q.ID]===r.network.local_candidate_id)return[{type:ee.NETWORK,value:{infrastructure:Nv(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:Dv(c)}}];break;case qt.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 qt.INBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.INBOUND);p&&(p.timestamp=r.timestamp);const h=rt(s,o,Me.INBOUND);if(h&&(h.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=_f(c,k.AUDIO,p,h),g=Kl(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=wv(c,p),g=_f(c,k.VIDEO,p,h),v=Kl(c,k.VIDEO,p),E=c[q.DECODER_IMPLEMENTATION]||null,S=c[q.CODEC_ID]||null,C=df(c),I=Pv(c,p,h);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 qt.OUTBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.OUTBOUND);p&&(p.timestamp=r.timestamp);const h=rt(s,o,Me.OUTBOUND);if(h&&(h.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=c[q.CODEC_ID]||null,g=ff(c,k.AUDIO,p,h);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=Ov(c,p),E=df(c),S=Uv(c),C=kv(c,p,h),I=ff(c,k.VIDEO,p,h);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 qt.MEDIA_SOURCE:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case qt.TRACK:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case qt.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(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Mv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_in:h}}):t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_out:h}})}}),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(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=xv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_in:h}}):t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_out:h}})}}),t;case qt.REMOTE_INBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.OUTBOUND),h=rt(s,o,Me.OUTBOUND);if(c[q.KIND]===k.AUDIO){const d=cf(c,k.AUDIO,h,p),g=Kl(c,k.AUDIO,p),v=hf(c,k.AUDIO,p,h);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=cf(c,k.VIDEO,h,p),g=Kl(c,k.VIDEO,p),v=hf(c,k.VIDEO,p,h);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[]},Ro=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Fv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.INBOUND),s=rt(a,n,Me.INBOUND),p=rt(a,o,Me.INBOUND),h=[],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&&h.push(C),I&&h.push(I),w&&h.push(w),v&&d.push(v),n&&E&&d.push(E),o&&S&&d.push(S);const F=h.length>0?Ms(h):100,L=d.length>0?Ms(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 Ro(M)},qv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.OUTBOUND),s=rt(a,n,Me.OUTBOUND),p=rt(a,o,Me.OUTBOUND),h=[],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?h.push(v):F&&h.push(F),E?h.push(E):L&&h.push(L),S?h.push(S):ie&&h.push(ie),C&&d.push(C),n&&I&&d.push(I),o&&w&&d.push(w);const N=h.length>0?Ms(h):100,H=d.length>0?Ms(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,j=.024*M+.11*(M-177.3)*D,V=me-j;return Ro(V)},Vv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.INBOUND),s=rt(a,n,Me.INBOUND),p=rt(a,o,Me.INBOUND),h=[],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&&h.push(C),I&&h.push(I),w&&h.push(w),v&&d.push(v),s&&E&&d.push(E),p&&S&&d.push(S);const F=h.length>0?Ms(h):100,L=d.length>0?Ms(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,V=93.2-(ie+N*Math.log(1+H*g)+D);return Ro(V)},jv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.OUTBOUND),s=rt(a,n,Me.OUTBOUND),p=rt(a,o,Me.OUTBOUND),h=[],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?h.push(v):F&&h.push(F),E?h.push(E):L&&h.push(L),S?h.push(S):ie&&h.push(ie),C&&d.push(C),s&&I&&d.push(I),p&&w&&d.push(w);const N=h.length>0?Ms(h):100,H=d.length>0?Ms(d):10,ve=0,me=19.8,M=29.7,D=30,j=(N+H)/2+D,V=j-177.3<0?0:1,Y=.024*j+.11*(j-177.3)*V,z=93.2-(ve+me*Math.log(1+M*g)+Y);return Ro(z)};class Bv{constructor(r,n){this._callbacks={onreport:null,onticket:null},this._id=Ev(),this._moduleName=this._id,this._probeId=n,this._config=r,this._exporter=new Iv(r),this._state=cs.IDLE,this.registerToPCEvents(),dn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(r,n,o,a){const t=(h,d)=>h===k.AUDIO?d===qt.INBOUND_RTP?{...Qf}:{...Zf}:d===qt.INBOUND_RTP?{...eh}:{...th},s=pv(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(h=>{!p&&h.timestamp&&(p=h.timestamp),Hv(h,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,h.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(h=>{const d=s[k.AUDIO][h];d.direction===Me.INBOUND?(d.mos_emodel_in=Fv(s,k.AUDIO,n,o,d.ssrc),d.mos_in=Vv(s,k.AUDIO,n,o,d.ssrc)):(d.mos_emodel_out=qv(s,k.AUDIO,n,o,d.ssrc),d.mos_out=jv(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),h=Date.now();p.experimental.time_to_measure_ms=h-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!==cs.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 tr(this._moduleName,`got error ${r}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=cs.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=cs.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=cs.RUNNING,Ne(this._moduleName,"unmuted")}async stop(r){if(Ne(this._moduleName,`stopping${r?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=cs.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}'`)):tr(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}'`)):tr(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{tr(this._moduleName,"can't get devices")}},r){r.oniceconnectionstatechange=()=>{const o=r.iceConnectionState;o===Ui.CONNECTED||o===Ui.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Ui.DISCONNECTED||o===Ui.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Ui.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 Gv{constructor(r){this._id=r.pname&&r.pname.substr(0,12).padEnd(12," ")||Tv(),this._moduleName=this._id,dn(this._moduleName,"probe created"),this._config=r,this._collector=new Bv(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===cs.RUNNING}get isIdle(){return this._collector.state===cs.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){oo(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 vt="engine ";class Kv{constructor(r){this._config=r,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},dn(vt,`configured for probing every ${this._config.refreshEvery}ms`),dn(vt,`configured for starting after ${this._config.startAfter}ms`),dn(vt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(vt,"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=gv(r,n,this._config),a=new Gv(o);return this._probes.push(a),Ne(vt,`${this._probes.length} probes registered`),a}removeExistingProbe(r){if(!r)throw new Error("undefined probe");r.state===cs.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=dv(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const h=await p.collectStats();h&&t.probes.push(h),Ne(vt,`got probe ${p.id}`),await af(0)}return t.delta_time_to_measure_probes_ms=fn(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=fn(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=fn(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=fn(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=fn(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=fn(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=fn(t.probes,"video","total_time_encoded_out"),t};for(Ne(vt,"starting to collect"),r(),Ne(vt,"generating reference reports..."),await n(),Ne(vt,"reference reports generated"),this._startedTime=Date.now();o();)if(Ne(vt,`wait ${this._config.refreshEvery}ms before collecting`),await af(this._config.refreshEvery),o()){Ne(vt,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Ne(vt,"collected")}Ne(vt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(r){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};dn(vt,"stop collecting"),n(r)}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(vt,`registered callback '${r}'`)):tr(vt,`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}'`)):tr(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 Yv{constructor(r){this._config=vv(r),dn(Wv,`welcome to ${this._config.name} version ${this._config.version}`),lv(this._config.verbose||!1),this._engine=new Kv(this._config)}setupLogLevel(r){ov(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")}}class zv{constructor(r){this.intervals={},this.emitInterval=r.emitInterval||200,this.onChangeFunction=r.onChangeFunction}start(r,n){r&&r.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(r,n))}stop(r){this.clearVolumeInterval(r)}clearVolumeInterval(r){console.log("clearVolumeInterval",r),clearInterval(this.intervals[r]),delete this.intervals[r]}clearAllIntervals(){Object.keys(this.intervals).forEach(r=>{clearInterval(this.intervals[r])}),this.intervals={}}beginCalculation(r,n){this.clearVolumeInterval(n);const o=Jt.createAnalyser(),a=Jt.createMediaStreamSource(r),t=Jt.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(Jt.destination),this.intervals[n]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const h=s.length;for(let g=0;g<h;g++)p+=s[g];const d=p/h;this.onChangeFunction(n,d)},this.emitInterval)}}const Jv=lt,Xv=es(),Ct=new Jv("WebSocketInterface");var Qv=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=Xv.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=vo,Zv=De,eT=ps,tT=mt(),sT=zf,nT=ds(),rT=cu(),iT=es(),lT=Qv,oT=rr("JsSIP");oT("version %s",eu.version);var aT={C:Zv,Exceptions:eT,Utils:tT,UA:sT,URI:nT,NameAddrHeader:rT,WebSocketInterface:lT,Grammar:iT,debug:rr,get name(){return eu.title},get version(){return eu.version}};const uT=xt(aT),cT=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Wt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},fT=0,Wl={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"};class hT extends Jg{constructor(r,n){const o={...r.configuration,sockets:r.socketInterfaces.map(a=>new uT.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=1,this.speakerVolumeValue=1,this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.isReconnecting=!1,this.listenersList={},this.options=r,this.VUMeter=new zv({onChangeFunction:this.emitVolumeChange.bind(this)}),n&&rv(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 selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}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 initializeMediaDevices(){const r=localStorage.getItem(Wl.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(Wl.SELECTED_OUTPUT_DEVICE)||"default";(await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)).getTracks().forEach(t=>t.stop());const a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(r),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)})}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)}emitVolumeChange(r,n){this.emit("changeCallVolume",{callId:r,volume:n})}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)}processMute(r){const n=this.currentActiveRoomId;this.setIsMuted(r),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!r),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:r,toHold:n,automatic:o}){const a=this.extendedCalls[r];a._automaticHold=o??!1,await new Promise(p=>{const h=()=>{p()};n?a.hold({},h):a.unhold({},h)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(n?r!==p._id:!0));s.length>1&&await this.doConference(s)}holdCall(r,n=!1){return this.processHold({callId:r,automatic:n,toHold:!0})}unholdCall(r){return this.processHold({callId:r,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(r=>r.direction==="outgoing"&&r.status===fT).forEach(r=>this.terminateCall(r._id))}answerCall(r){const n=this.extendedCalls[r];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(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 moveCall(r,n){this.updateCallStatus({callId:r,isMoving:!0}),await this.processRoomChange({callId:r,roomId:n}),this.updateCallStatus({callId:r,isMoving:!1})}updateCall(r){this.activeCalls[r._id]=nf(r),this.emit("changeActiveCalls",this.activeCalls)}updateMSRPSession(r){this.activeMessages[r._id]=rf(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]:nf(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]:rf(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})}getActiveStream(){const r=lf(this.initialStreamValue,this.microphoneInputLevel*2);return r.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(r),r}async setMicrophone(r){if(!this.getInputDeviceList.find(({deviceId:o})=>o===r)||(this.setSelectedInputDevice(r),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(n)}setActiveStream(r){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(r,"origin"),this.activeStreamValue=r,this.emit("changeActiveStream",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||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===r){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&n[0].connection.getSenders()[0]){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(r){await sf.forEach(r,async o=>{o._localHold&&await this.unholdCall(o._id)});const n=[];r.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{n.push(a.track)})}),await sf.forEach(r,async o=>{if(o==null)return;const a=new MediaStream,t=Jt.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{n.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&Jt.createMediaStreamSource(new MediaStream([p])).connect(t)})}),r[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();Jt.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(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))}muteCaller(r){this.processCallerMute(r,!0)}unmuteCaller(r){this.processCallerMute(r,!1)}terminateCall(r){const n=this.extendedCalls[r];n._status!==8&&n.terminate()}messageTerminate(r){const n=this.extendedMessages[r];n._status!==8&&n.terminate()}transferCall(r,n){if(n.toString().length===0)return new 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)}mergeCall(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=Zg(a);this.setCallTime({callId:r,...t})},1e3);this.setTimeInterval(r,o)}async setActiveRoom(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 setupCall(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(Wt.CALL_CONFIRMED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(n.id))}),this.subscribe(Wt.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),h=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=h,h?this.addCall(s,!1):this.addCall(s),this.addCallStatus(n.id),this.addRoom(t),h&&this.answerCall(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];this.stopVUMeter("origin"),n.connection.getSenders().forEach(a=>{a.track.stop()});const o=n.roomId;this.removeCall(r._id),this.roomReconfigure(o)}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.stopVUMeter(n.id),this.logger.log("Session ended for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Wt.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),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),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:Wt.CALL_PROGRESS,session:n,event:o})}),n.on("failed",o=>{var t,s;this.stopVUMeter(n.id),this.logger.log("Session failed for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Wt.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),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),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:Wt.CALL_CONFIRMED,session:n,event:o}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(r),n.direction==="outgoing"){const o=this.getActiveCalls[n.id].roomId;this.setActiveRoom(o)}}newMSRPSessionCallback(r){const n=r.session;n.on("ended",o=>{this.triggerMSRPListener({listenerType:Wt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Wt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Wt.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.initializeMediaDevices(),this}setMuteWhenJoin(r){this.muteWhenJoinEnabled=r,this.emit("changeMuteWhenJoin",r)}setMicrophoneSensitivity(r){if(r<0||r>1)throw new Error("Value should be in range from 0 to 1!");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(Wl.SELECTED_INPUT_DEVICE,r),this.selectedMediaDevices.input=r,this.emit("changeActiveInputMediaDevice",r)}setSelectedOutputDevice(r){localStorage.setItem(Wl.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 Yv(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],h=ev(p,cT);h.callId=r._id,this.setCallMetrics(n)},this.subscribe(Wt.CALL_ENDED,s=>{s._id===r._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(r,n){this.VUMeter.start(r,n)}stopVUMeter(r){this.VUMeter.stop(r)}async setupStream(){const r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=r}async triggerAddStream(r,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=lf(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(t=>t.enabled=!a),this.setActiveStream(o),await n.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),nv(r,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(r.stream,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(r,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.processRoomChange({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 processRoomChange({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.setActiveRoom(n),Promise.all([this.roomReconfigure(o),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(n)})}}module.exports=hT;
155
+ `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new ym(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=Se.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=Se.STATUS_INVITE_SENT}terminate(r={}){console.log("terminate",this);const n=r.cause||be.causes.BYE,o=Ps.cloneArray(r.extraHeaders),a=r.body;let t,s=r.status_code,p=r.reason_phrase;if(this._status===Se.STATUS_TERMINATED)throw new wm.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Se.STATUS_NULL:case Se.STATUS_INVITE_SENT:case Se.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||be.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Se.STATUS_NULL||this._status===Se.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Se.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Se.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,be.causes.CANCELED);break;case Se.STATUS_WAITING_FOR_ANSWER:case Se.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,be.causes.REJECTED);break;case Se.STATUS_WAITING_FOR_ACK:case Se.STATUS_CONFIRMED:if(p=r.reason_phrase||be.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===Se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Li.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:d})=>{d===be.ACK&&(this.sendRequest(be.BYE,{extraHeaders:o,body:a}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Li.C.STATUS_TERMINATED&&(this.sendRequest(be.BYE,{extraHeaders:o,body:a}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else console.log("here it is"),this.sendRequest(be.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 Qn("");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 Qn(r.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new um(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Ps.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(be.ACK);return}else{const n=new $l(this,r,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(be.ACK),this.sendRequest(be.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!==Se.STATUS_INVITE_SENT&&this._status!==Se.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(r.status_code):this._status=Se.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=Se.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=Se.STATUS_CONFIRMED,!r.body){this._acceptAndTerminate(r,400,be.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",r,be.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,be.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(r),this._accepted("remote",r),this.sendRequest(be.ACK),this._confirmed("local",null)});break}default:{const n=Ps.sipErrorCause(r.status_code);console.log("failed 5"),this._failed("remote",r,n)}}}sendMSRP(r){const n=new Qn("");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",Ps.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 Qn("");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 Qn("");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=Se.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=Ps.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=Se.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{r.reply(408),console.log("failed 6"),this._failed("local",null,be.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Se.STATUS_WAITING_FOR_ANSWER&&(r.reply(487),console.log("failed 7"),this._failed("system",null,be.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!==Se.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!==Se.STATUS_TERMINATED){if(this._status=Se.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 $l(this,r,n,$l.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",r,be.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 h=new $l(this,r,n);return h.error?(console.log("failed 9"),this._failed("remote",r,be.causes.INTERNAL_ERROR),!1):(this._dialog=h,!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 Se.STATUS_CANCELED:case Se.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>=be.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===be.CANCEL)(this._status===Se.STATUS_WAITING_FOR_ANSWER||this._status===Se.STATUS_ANSWERED)&&(this._status=Se.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",r,be.causes.CANCELED));else switch(r.method){case be.ACK:if(this._status!==Se.STATUS_WAITING_FOR_ACK)return;if(this._status=Se.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!r.body){this.terminate({cause:be.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:be.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 be.BYE:this._status===Se.STATUS_CONFIRMED||this._status===Se.STATUS_WAITING_FOR_ACK?(r.reply(200),this._ended("remote",r,be.causes.BYE)):this._status===Se.STATUS_INVITE_RECEIVED||this._status===Se.STATUS_WAITING_FOR_ANSWER?(r.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",r,be.causes.BYE)):r.reply(403,"Wrong Status");break;case be.INVITE:this._status===Se.STATUS_CONFIRMED?r.hasHeader("replaces")?this._receiveReplaces(r):this._receiveReinvite(r):r.reply(403,"Wrong Status");break;case be.INFO:this._status===Se.STATUS_1XX_RECEIVED||this._status===Se.STATUS_WAITING_FOR_ANSWER||this._status===Se.STATUS_ANSWERED||this._status===Se.STATUS_WAITING_FOR_ACK||this._status===Se.STATUS_CONFIRMED?(r.hasHeader("Content-Type")?r.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new jm(this).init_incoming(r):r.reply(415):r.reply(403,"Wrong Status");break;case be.UPDATE:this._status===Se.STATUS_CONFIRMED?this._receiveUpdate(r):r.reply(403,"Wrong Status");break;case be.REFER:this._status===Se.STATUS_CONFIRMED?this._receiveRefer(r):r.reply(403,"Wrong Status");break;case be.NOTIFY:this._status===Se.STATUS_CONFIRMED?this._receiveNotify(r):r.reply(403,"Wrong Status");break;default:r.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:be.causes.CONNECTION_ERROR,cause:be.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:be.causes.REQUEST_TIMEOUT,cause:be.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:be.causes.DIALOG_ERROR,cause:be.causes.DIALOG_ERROR})}}const Kt=console,tf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{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){Kt.debug("Request-URI does not point to us"),r.method!==De.ACK&&r.reply_sl(404);return}if(r.ruri.scheme===De.SIPS){r.reply_sl(416);return}if(Li.checkTransaction(this,r))return;if(n===De.INVITE?new Li.InviteServerTransaction(this,this._transport,r):n!==De.ACK&&n!==De.CANCEL&&new Li.NonInviteServerTransaction(this,this._transport,r),n===De.OPTIONS){if(this.listeners("newOptions").length===0){r.reply(200);return}new Ac.Options(this).init_incoming(r)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){r.reply(405);return}new Ac.Message(this).init_incoming(r)}else if(n===De.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===De.NOTIFY?(a=this._findSession(r),a?a.receiveRequest(r):(Kt.debug("received NOTIFY request for a non existent subscription"),r.reply(481,"Subscription does not exist"))):n!==De.ACK&&r.reply(481);else switch(n){case De.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 ef(this),a.init_incoming(r)):(a=new ng(this),a.init_incoming(r));else Kt.warn("INVITE received but WebRTC is not supported"),r.reply(488);break;case De.BYE:r.reply(481);break;case De.CANCEL:a=this._findSession(r),a?a.receiveRequest(r):Kt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:r.event,request:r}),r.reply(200);break;default:r.reply(405);break}}startMSRP(r,n){Kt.debug("startMSRP()",n);const o=new ef(this);return o.connect(r),o}terminateMSRPSessions(r){Kt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(r)}stop(){if(Kt.debug("stop()"),this._dynConfiguration={},this._status===tf.STATUS_USER_CLOSED){Kt.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)){Kt.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)){Kt.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=tf.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 gt={};gt.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)};gt.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)};gt.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)};gt.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};gt.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=h=>{h?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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]};gt.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=h=>{h?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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=h=>{h?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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=h=>{h?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(h=>r.call(n||globalThis,h,s,c)).then(p).catch(a)}});gt.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};gt.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(h=>r.call(n||globalThis,h,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)});gt.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};gt.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 Jf={};(function(c){const r=gt;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)}})})(Jf);const Xg=gt,Qg=Jf;var sf=Object.assign(Xg,{instanceMethods:Qg});function Pa(c){return c<10?`0${c}`:`${c}`}function Zg(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=`${Pa(r)}:${Pa(n)}:${Pa(o)}`;return{seconds:o,minutes:n,hours:r,formatted:a}}function ev(c,r){return Object.keys(c).filter(n=>r.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const Jt=new AudioContext,tv=["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"],sv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function nf(c){const r={};return tv.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r.localHold=c._localHold,r}function rf(c){const r={};return sv.forEach(n=>{c[n]!==void 0&&(r[n]=c[n])}),r}function lf(c,r){const n=Jt.createMediaStreamSource(c),o=Jt.createMediaStreamDestination(),a=Jt.createGain();return n.connect(a),a.connect(o),a.gain.value=r,o.stream}function nv(c,r,n,o){const a=document.createElement("audio");a.id=r._id,a.className="audioTag",a.srcObject=c,a.setSinkId(n),a.volume=o,a.play(),r.audioTag=a}function rv(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}var iv={exports:{}};(function(c){var r=function(n){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(Q,G,B){Q[G]=B.value},s,p=typeof Symbol=="function"?Symbol:{},h=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function v(Q,G,B){return Object.defineProperty(Q,G,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[G]}try{v({},"")}catch{v=function(G,B,te){return G[B]=te}}function E(Q,G,B,te){var de=G&&G.prototype instanceof ie?G: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,G,B){try{return{type:"normal",arg:Q.call(G,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,h,function(){return this});var me=Object.getPrototypeOf,M=me&&me(me(Z([])));M&&M!==o&&a.call(M,h)&&(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 j(Q){["next","throw","return"].forEach(function(G){v(Q,G,function(B){return this._invoke(G,B)})})}n.isGeneratorFunction=function(Q){var G=typeof Q=="function"&&Q.constructor;return G?G===N||(G.displayName||G.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 V(Q,G){function B(Ae,Ue,ye,ne){var Te=S(Q[Ae],Q,Ue);if(Te.type==="throw")ne(Te.arg);else{var Qe=Te.arg,st=Qe.value;return st&&typeof st=="object"&&a.call(st,"__await")?G.resolve(st.__await).then(function(ge){B("next",ge,ye,ne)},function(ge){B("throw",ge,ye,ne)}):G.resolve(st).then(function(ge){Qe.value=ge,ye(Qe)},function(ge){return B("throw",ge,ye,ne)})}}var te;function de(Ae,Ue){function ye(){return new G(function(ne,Te){B(Ae,Ue,ne,Te)})}return te=te?te.then(ye,ye):ye()}t(this,"_invoke",{value:de})}j(V.prototype),v(V.prototype,d,function(){return this}),n.AsyncIterator=V,n.async=function(Q,G,B,te,de){de===void 0&&(de=Promise);var Ae=new V(E(Q,G,B,te),de);return n.isGeneratorFunction(G)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function Y(Q,G,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 Xe()}for(B.method=Ae,B.arg=Ue;;){var ye=B.delegate;if(ye){var ne=$(ye,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,G,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,G){var B=G.method,te=Q.iterator[B];if(te===s)return G.delegate=null,B==="throw"&&Q.iterator.return&&(G.method="return",G.arg=s,$(Q,G),G.method==="throw")||B!=="return"&&(G.method="throw",G.arg=new TypeError("The iterator does not provide a '"+B+"' method")),L;var de=S(te,Q.iterator,G.arg);if(de.type==="throw")return G.method="throw",G.arg=de.arg,G.delegate=null,L;var Ae=de.arg;if(!Ae)return G.method="throw",G.arg=new TypeError("iterator result is not an object"),G.delegate=null,L;if(Ae.done)G[Q.resultName]=Ae.value,G.next=Q.nextLoc,G.method!=="return"&&(G.method="next",G.arg=s);else return Ae;return G.delegate=null,L}j(D),v(D,g,"Generator"),v(D,h,function(){return this}),v(D,"toString",function(){return"[object Generator]"});function z(Q){var G={tryLoc:Q[0]};1 in Q&&(G.catchLoc=Q[1]),2 in Q&&(G.finallyLoc=Q[2],G.afterLoc=Q[3]),this.tryEntries.push(G)}function U(Q){var G=Q.completion||{};G.type="normal",delete G.arg,Q.completion=G}function P(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(z,this),this.reset(!0)}n.keys=function(Q){var G=Object(Q),B=[];for(var te in G)B.push(te);return B.reverse(),function de(){for(;B.length;){var Ae=B.pop();if(Ae in G)return de.value=Ae,de.done=!1,de}return de.done=!0,de}};function Z(Q){if(Q){var G=Q[h];if(G)return G.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:Xe}}n.values=Z;function Xe(){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 G in this)G.charAt(0)==="t"&&a.call(this,G)&&!isNaN(+G.slice(1))&&(this[G]=s)},stop:function(){this.done=!0;var Q=this.tryEntries[0],G=Q.completion;if(G.type==="throw")throw G.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var G=this;function B(ne,Te){return Ae.type="throw",Ae.arg=Q,G.next=ne,Te&&(G.method="next",G.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"),ye=a.call(de,"finallyLoc");if(Ue&&ye){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(ye){if(this.prev<de.finallyLoc)return B(de.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,G){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<=G&&G<=de.finallyLoc&&(de=null);var Ae=de?de.completion:{};return Ae.type=Q,Ae.arg=G,de?(this.method="next",this.next=de.finallyLoc,L):this.complete(Ae)},complete:function(Q,G){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"&&G&&(this.next=G),L},finish:function(Q){for(var G=this.tryEntries.length-1;G>=0;--G){var B=this.tryEntries[G];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),U(B),L}},catch:function(Q){for(var G=this.tryEntries.length-1;G>=0;--G){var B=this.tryEntries[G];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,G,B){return this.delegate={iterator:Z(Q),resultName:G,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)}})(iv);var Xf={exports:{}};(function(c){(function(r,n){c.exports?c.exports=n():r.log=n()})(nh,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 h(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&&(h.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 j=(a[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=j;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+j+";"}catch{}}}function ve(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var j=window.document.cookie,V=j.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(j.slice(V))[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,j){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,j!==!1&&H(D),h.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})})(Xf);var Tt=Xf.exports;const fs=()=>`${new Date().toISOString()} | metrics`,hs=(c,r,n)=>`${c} | ${r} | ${n}`;Tt.setDefaultLevel(Tt.levels.TRACE);const lv=c=>{Tt.info(hs(fs(),"log ",`set log level to ${c?"verbose":"info"}`)),Tt.setLevel(c?Tt.levels.TRACE:Tt.levels.INFO)},ov=c=>{const r=[...Object.keys(Tt.levels)];r.includes(c)?(Tt.info(hs(fs(),"log ",`update log level to ${c.toLowerCase()}`)),Tt.setLevel(c)):Tt.warn(hs(fs(),"log ","Incorrect log level please choose one of "),r)},Ne=(c,r,n)=>{n?Tt.debug(hs(fs(),c,r),n):Tt.debug(hs(fs(),c,r))},ka=(c,r)=>{Tt.info(hs(fs(),c,r))},dn=(c,r)=>{Tt.info(hs(fs(),c,r))},oo=(c,r)=>{Tt.warn(hs(fs(),c,r))},tr=(c,r)=>{Tt.error(hs(fs(),c,r))};function av(c){return Math.floor(Math.random()*c).toString()}function of(c,r){let n=r;return c.forEach(o=>{n=n.replace(o,"")}),n}function uv(c,r){let n="";for(let o=0;o<r;o+=1)n+=c[av(c.length)];return n}function cv({length:c=20,useLetters:r=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],h=[],d=[];return r&&(a.length&&(t=of(a,t)),h=t.split("")),n&&(a.length&&(s=of(a,s)),d=s.split("")),p=[...h,...d,...o],uv(p,c)}var fv=cv;const $i=xt(fv),hv=()=>"WebRTCMetrics",_v=()=>"5.0.3",Me={INBOUND:"inbound",OUTBOUND:"outbound"},cs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ui={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},dv=()=>({...{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:[]}}),Qf={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:Me.INBOUND},Zf={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:Me.OUTBOUND},eh={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:Me.INBOUND},th={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:Me.OUTBOUND},pv=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}}},mv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${$i()}`,cid:`c-${$i()}`,uid:`u-${$i()}`,record:!1,ticket:!0},qt={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"},Pi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Ma={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ee={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},xa="config ",gv=(c,r={},n)=>{const o={...n,...r};return r.pname||oo(xa,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),r.cid||oo(xa,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),r.uid||oo(xa,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},vv=(c={})=>{const r={...mv,...c};return r.name=hv(),r.version=_v(),r},el=(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},Ms=c=>c.reduce((r,n)=>r+n,0)/c.length,Tv=()=>`probe-${$i()}`,Ev=()=>`coltr-${$i()}`,af=c=>new Promise(r=>setTimeout(r,c)),Za=(c,r,n)=>{r?c.call(r,n):c(n)},Be=(c,r,n,o)=>{const a=el(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=el(c,r,n,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},fn=(c,r,n)=>el(c,r,n).reduce((a,t)=>a+t,0),Ge=(c,r,n,o)=>{const a=el(c,r,n,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,r,n,o)=>{const a=el(c,r,n,!1,o);return a.length===0?null:Math.max(...a)},ct=(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},yv=c=>c.slice().pop(),rt=(c,r,n)=>{if(!r)return null;const o={};let a=r[k.AUDIO][c];a||(a=n===Me.INBOUND?{...Qf}:{...Zf}),o[k.AUDIO]=a;let t=r[k.VIDEO][c];return t||(t=n===Me.INBOUND?{...eh}:{...th}),o[k.VIDEO]=t,o},ki="exporter ",Sv="2.0",uf=(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},Cv=(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)},Av=c=>ct(c,"network","local_candidate_type")!=="relay"?`direct/${ct(c,"network","local_candidate_protocol")}`:`turn/${ct(c,"network","local_candidate_relay_protocol")}`,Rv=c=>{const r=ct(c,"network","remote_candidate_type"),n=ct(c,"network","remote_candidate_protocol");return r!=="relay"?`direct/${n}`:`turn/${n}`};class Iv{constructor(r){this._start=null,this._end=null,this._cfg=r,this._referenceReport=null,this._reports=[],this._events=[]}start(){ka(ki,"start() - start exporter...");const r=new Date;return this._start=r.toJSON(),r}stop(){ka(ki,"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(ki,`addReport() - add report to exporter at ${r.timestamp}`),this._reports.push(r))}addCustomEvent(r){this._events.push(r)}reset(){ka(ki,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(ki,"ticket() - generate ticket");const r=ct(this._reports,"audio","total_packets_lost_in"),n=ct(this._reports,"audio","total_packets_in"),o=ct(this._reports,"video","total_packets_lost_in"),a=ct(this._reports,"video","total_packets_in"),t={},s=yv(this._reports);return s&&(Object.keys(s[k.AUDIO]).forEach(p=>{const h=s[k.AUDIO][p];if(t[h.ssrc]={type:k.AUDIO,direction:h.direction},h.direction===Me.INBOUND){const d={avg:We(this._reports,k.AUDIO,"delta_jitter_ms_in",!1,p),min:Ge(this._reports,k.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,k.AUDIO,"delta_jitter_ms_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,k.AUDIO,"delta_kbs_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,k.AUDIO,"delta_KBytes_in",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,k.AUDIO,"mos_emodel_in",p),volatility:Be(this._reports,k.AUDIO,"mos_emodel_in",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_in",!1,p),min:Ge(this._reports,k.AUDIO,"mos_in",p),max:Ke(this._reports,k.AUDIO,"mos_in",p),volatility:Be(this._reports,k.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},S=ct(this._reports,k.AUDIO,"total_packets_lost_in",p),C=ct(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:Ge(this._reports,k.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,k.AUDIO,"delta_jitter_ms_out",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,k.AUDIO,"delta_kbs_out",p),volatility:Be(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:Ge(this._reports,k.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,k.AUDIO,"delta_KBytes_out",p),volatility:Be(this._reports,k.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:uf(this._reports,k.AUDIO,p),min:Ge(this._reports,k.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,k.AUDIO,"delta_rtt_ms_out",p),volatility:Be(this._reports,k.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=ct(this._reports,k.AUDIO,"total_packets_lost_out",p),C=ct(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:Ge(this._reports,k.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,k.AUDIO,"mos_emodel_out",p),volatility:Be(this._reports,k.AUDIO,"mos_emodel_out",p)},effective:{avg:We(this._reports,k.AUDIO,"mos_out",!1,p),min:Ge(this._reports,k.AUDIO,"mos_out",p),max:Ke(this._reports,k.AUDIO,"mos_out",p),volatility:Be(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 h=s[k.VIDEO][p];if(t[p]={type:k.VIDEO,direction:h.direction},h.direction===Me.INBOUND){const d={avg:We(this._reports,k.VIDEO,"delta_jitter_ms_in",!1,p),min:Ge(this._reports,k.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,k.VIDEO,"delta_jitter_ms_in",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,k.VIDEO,"delta_kbs_in",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,k.VIDEO,"delta_KBytes_in",p),volatility:Be(this._reports,k.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=ct(this._reports,k.VIDEO,"total_packets_lost_in",p),S=ct(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:Ge(this._reports,k.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,k.VIDEO,"delta_jitter_ms_out",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,k.VIDEO,"delta_kbs_out",p),volatility:Be(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:Ge(this._reports,k.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,k.VIDEO,"delta_KBytes_out",p),volatility:Be(this._reports,k.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:uf(this._reports,k.VIDEO,p),min:Ge(this._reports,k.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,k.VIDEO,"delta_rtt_ms_out",p),volatility:Be(this._reports,k.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S=ct(this._reports,k.VIDEO,"total_packets_lost_out",p),C=ct(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:Sv,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:Cv(this._reports,"data"),min:Ge(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Be(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:Ge(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Be(this._reports,"data","delta_kbs_in")},out:{avg:We(this._reports,"data","delta_kbs_out"),min:Ge(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Be(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:Ge(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Be(this._reports,"data","delta_KBytes_in")},out:{avg:We(this._reports,"data","delta_KBytes_out"),min:Ge(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Be(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Av(this._reports),remoteConnection:Rv(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 Us="extractor ",cf=(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,h=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])-h===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])-h),{rtt:g,totalRTT:v,totalRTTMeasurements:E}},bv=(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}},Kl=(c,r,n)=>c[q.TIMESTAMP]===n[r].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),wv=(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}},Ov=(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}},ff=(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,h=c[q.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=n.timestamp;!g&&d&&(g=d);const v=g?h-g:0,E=v>0?p*.008*1024/v*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},hf=(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}},_f=(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,h=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:h,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:I}},Dv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",Nv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return Pi.WIFI;switch(c[q.NETWORK_TYPE]){case Ma.ETHERNET:return Pi.ETHERNET;case Ma.CELLULAR_4G:return Pi.CELLULAR_4G;case Ma.WIFI:return Pi.WIFI;default:return Pi.CELLULAR}},df=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]},Uv=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}},Pv=(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}},kv=(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}),xv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),Lv=(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,h=n?n.timestamp:null;let d=r.timestamp;!d&&h&&(d=h);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}},$v=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}},Hv=(c,r,n,o)=>{if(!c)return[];switch(c[q.TYPE]){case qt.CANDIDATE_PAIR:let a=!1;if(c[q.NOMINATED]&&c[q.STATE]===k.SUCCEEDED&&(a=!0,Ne(Us,`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],h=Lv(c,r,o),d=$v(c),g=bv(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:h.total_KBytes_received}},{type:ee.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ee.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ee.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ee.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ee.DATA,value:{delta_kbs_out:h.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 qt.LOCAL_CANDIDATE:if(c[q.ID]===r.network.local_candidate_id)return[{type:ee.NETWORK,value:{infrastructure:Nv(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:Dv(c)}}];break;case qt.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 qt.INBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.INBOUND);p&&(p.timestamp=r.timestamp);const h=rt(s,o,Me.INBOUND);if(h&&(h.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=_f(c,k.AUDIO,p,h),g=Kl(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=wv(c,p),g=_f(c,k.VIDEO,p,h),v=Kl(c,k.VIDEO,p),E=c[q.DECODER_IMPLEMENTATION]||null,S=c[q.CODEC_ID]||null,C=df(c),I=Pv(c,p,h);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 qt.OUTBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.OUTBOUND);p&&(p.timestamp=r.timestamp);const h=rt(s,o,Me.OUTBOUND);if(h&&(h.timestamp=o.timestamp),c[q.MEDIA_TYPE]===k.AUDIO){const d=c[q.CODEC_ID]||null,g=ff(c,k.AUDIO,p,h);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=Ov(c,p),E=df(c),S=Uv(c),C=kv(c,p,h),I=ff(c,k.VIDEO,p,h);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 qt.MEDIA_SOURCE:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case qt.TRACK:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case qt.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(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Mv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_in:h}}):t.push({ssrc:p.ssrc,type:ee.AUDIO,value:{codec_out:h}})}}),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(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=xv(c);c[q.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_in:h}}):t.push({ssrc:p.ssrc,type:ee.VIDEO,value:{codec_out:h}})}}),t;case qt.REMOTE_INBOUND_RTP:{Ne(Us,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const s=c[q.SSRC],p=rt(s,r,Me.OUTBOUND),h=rt(s,o,Me.OUTBOUND);if(c[q.KIND]===k.AUDIO){const d=cf(c,k.AUDIO,h,p),g=Kl(c,k.AUDIO,p),v=hf(c,k.AUDIO,p,h);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=cf(c,k.VIDEO,h,p),g=Kl(c,k.VIDEO,p),v=hf(c,k.VIDEO,p,h);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[]},Ro=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Fv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.INBOUND),s=rt(a,n,Me.INBOUND),p=rt(a,o,Me.INBOUND),h=[],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&&h.push(C),I&&h.push(I),w&&h.push(w),v&&d.push(v),n&&E&&d.push(E),o&&S&&d.push(S);const F=h.length>0?Ms(h):100,L=d.length>0?Ms(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 Ro(M)},qv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.OUTBOUND),s=rt(a,n,Me.OUTBOUND),p=rt(a,o,Me.OUTBOUND),h=[],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?h.push(v):F&&h.push(F),E?h.push(E):L&&h.push(L),S?h.push(S):ie&&h.push(ie),C&&d.push(C),n&&I&&d.push(I),o&&w&&d.push(w);const N=h.length>0?Ms(h):100,H=d.length>0?Ms(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,j=.024*M+.11*(M-177.3)*D,V=me-j;return Ro(V)},Vv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.INBOUND),s=rt(a,n,Me.INBOUND),p=rt(a,o,Me.INBOUND),h=[],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&&h.push(C),I&&h.push(I),w&&h.push(w),v&&d.push(v),s&&E&&d.push(E),p&&S&&d.push(S);const F=h.length>0?Ms(h):100,L=d.length>0?Ms(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,V=93.2-(ie+N*Math.log(1+H*g)+D);return Ro(V)},jv=(c,r=k.AUDIO,n,o,a)=>{const t=rt(a,c,Me.OUTBOUND),s=rt(a,n,Me.OUTBOUND),p=rt(a,o,Me.OUTBOUND),h=[],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?h.push(v):F&&h.push(F),E?h.push(E):L&&h.push(L),S?h.push(S):ie&&h.push(ie),C&&d.push(C),s&&I&&d.push(I),p&&w&&d.push(w);const N=h.length>0?Ms(h):100,H=d.length>0?Ms(d):10,ve=0,me=19.8,M=29.7,D=30,j=(N+H)/2+D,V=j-177.3<0?0:1,Y=.024*j+.11*(j-177.3)*V,z=93.2-(ve+me*Math.log(1+M*g)+Y);return Ro(z)};class Bv{constructor(r,n){this._callbacks={onreport:null,onticket:null},this._id=Ev(),this._moduleName=this._id,this._probeId=n,this._config=r,this._exporter=new Iv(r),this._state=cs.IDLE,this.registerToPCEvents(),dn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(r,n,o,a){const t=(h,d)=>h===k.AUDIO?d===qt.INBOUND_RTP?{...Qf}:{...Zf}:d===qt.INBOUND_RTP?{...eh}:{...th},s=pv(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(h=>{!p&&h.timestamp&&(p=h.timestamp),Hv(h,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,h.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(h=>{const d=s[k.AUDIO][h];d.direction===Me.INBOUND?(d.mos_emodel_in=Fv(s,k.AUDIO,n,o,d.ssrc),d.mos_in=Vv(s,k.AUDIO,n,o,d.ssrc)):(d.mos_emodel_out=qv(s,k.AUDIO,n,o,d.ssrc),d.mos_out=jv(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),h=Date.now();p.experimental.time_to_measure_ms=h-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!==cs.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 tr(this._moduleName,`got error ${r}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=cs.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=cs.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=cs.RUNNING,Ne(this._moduleName,"unmuted")}async stop(r){if(Ne(this._moduleName,`stopping${r?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=cs.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}'`)):tr(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}'`)):tr(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{tr(this._moduleName,"can't get devices")}},r){r.oniceconnectionstatechange=()=>{const o=r.iceConnectionState;o===Ui.CONNECTED||o===Ui.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Ui.DISCONNECTED||o===Ui.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Ui.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 Gv{constructor(r){this._id=r.pname&&r.pname.substr(0,12).padEnd(12," ")||Tv(),this._moduleName=this._id,dn(this._moduleName,"probe created"),this._config=r,this._collector=new Bv(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===cs.RUNNING}get isIdle(){return this._collector.state===cs.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){oo(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 vt="engine ";class Kv{constructor(r){this._config=r,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},dn(vt,`configured for probing every ${this._config.refreshEvery}ms`),dn(vt,`configured for starting after ${this._config.startAfter}ms`),dn(vt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(vt,"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=gv(r,n,this._config),a=new Gv(o);return this._probes.push(a),Ne(vt,`${this._probes.length} probes registered`),a}removeExistingProbe(r){if(!r)throw new Error("undefined probe");r.state===cs.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=dv(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const h=await p.collectStats();h&&t.probes.push(h),Ne(vt,`got probe ${p.id}`),await af(0)}return t.delta_time_to_measure_probes_ms=fn(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=fn(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=fn(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=fn(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=fn(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=fn(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=fn(t.probes,"video","total_time_encoded_out"),t};for(Ne(vt,"starting to collect"),r(),Ne(vt,"generating reference reports..."),await n(),Ne(vt,"reference reports generated"),this._startedTime=Date.now();o();)if(Ne(vt,`wait ${this._config.refreshEvery}ms before collecting`),await af(this._config.refreshEvery),o()){Ne(vt,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Ne(vt,"collected")}Ne(vt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(r){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};dn(vt,"stop collecting"),n(r)}registerCallback(r,n,o){r in this._callbacks?(this._callbacks[r]={callback:n,context:o},Ne(vt,`registered callback '${r}'`)):tr(vt,`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}'`)):tr(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 Yv{constructor(r){this._config=vv(r),dn(Wv,`welcome to ${this._config.name} version ${this._config.version}`),lv(this._config.verbose||!1),this._engine=new Kv(this._config)}setupLogLevel(r){ov(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")}}class zv{constructor(r){this.intervals={},this.emitInterval=r.emitInterval||200,this.onChangeFunction=r.onChangeFunction}start(r,n){r&&r.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(r,n))}stop(r){this.clearVolumeInterval(r)}clearVolumeInterval(r){console.log("clearVolumeInterval",r),clearInterval(this.intervals[r]),delete this.intervals[r]}clearAllIntervals(){Object.keys(this.intervals).forEach(r=>{clearInterval(this.intervals[r])}),this.intervals={}}beginCalculation(r,n){this.clearVolumeInterval(n);const o=Jt.createAnalyser(),a=Jt.createMediaStreamSource(r),t=Jt.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(Jt.destination),this.intervals[n]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const h=s.length;for(let g=0;g<h;g++)p+=s[g];const d=p/h;this.onChangeFunction(n,d)},this.emitInterval)}}const Jv=lt,Xv=es(),Ct=new Jv("WebSocketInterface");var Qv=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=Xv.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=vo,Zv=De,eT=ps,tT=mt(),sT=zf,nT=ds(),rT=cu(),iT=es(),lT=Qv,oT=rr("JsSIP");oT("version %s",eu.version);var aT={C:Zv,Exceptions:eT,Utils:tT,UA:sT,URI:nT,NameAddrHeader:rT,WebSocketInterface:lT,Grammar:iT,debug:rr,get name(){return eu.title},get version(){return eu.version}};const uT=xt(aT),cT=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Wt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},fT=0,Wl={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"};class hT extends Jg{constructor(r,n){const o={...r.configuration,sockets:r.socketInterfaces.map(a=>new uT.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=1,this.speakerVolumeValue=1,this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.isReconnecting=!1,this.listenersList={},this.options=r,this.VUMeter=new zv({onChangeFunction:this.emitVolumeChange.bind(this)}),n&&rv(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 selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}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 initializeMediaDevices(){const r=localStorage.getItem(Wl.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(Wl.SELECTED_OUTPUT_DEVICE)||"default";(await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)).getTracks().forEach(t=>t.stop());const a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(r),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)})}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)}emitVolumeChange(r,n){this.emit("changeCallVolume",{callId:r,volume:n})}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)}processMute(r){const n=this.currentActiveRoomId;this.setIsMuted(r),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!r),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:r,toHold:n,automatic:o}){const a=this.extendedCalls[r];a._automaticHold=o??!1,await new Promise(p=>{const h=()=>{p()};n?a.hold({},h):a.unhold({},h)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(n?r!==p._id:!0));s.length>1&&await this.doConference(s)}holdCall(r,n=!1){return this.processHold({callId:r,automatic:n,toHold:!0})}unholdCall(r){return this.processHold({callId:r,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(r=>r.direction==="outgoing"&&r.status===fT).forEach(r=>this.terminateCall(r._id))}answerCall(r){const n=this.extendedCalls[r];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",o=>{this.triggerAddStream(o,n)})}msrpAnswer(r){const n=this.extendedMessages[r];n.answer(this.sipOptions),this.updateMSRPSession(n)}async moveCall(r,n){this.updateCallStatus({callId:r,isMoving:!0}),await this.processRoomChange({callId:r,roomId:n}),this.updateCallStatus({callId:r,isMoving:!1})}updateCall(r){this.activeCalls[r._id]=nf(r),this.emit("changeActiveCalls",this.activeCalls)}updateMSRPSession(r){this.activeMessages[r._id]=rf(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]:nf(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]:rf(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})}getActiveStream(){const r=lf(this.initialStreamValue,this.microphoneInputLevel*2);return r.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(r),r}async setMicrophone(r){if(!this.getInputDeviceList.find(({deviceId:o})=>o===r)||(this.setSelectedInputDevice(r),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(n)}setActiveStream(r){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(r,"origin"),this.activeStreamValue=r,this.emit("changeActiveStream",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||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===r){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&n[0].connection.getSenders()[0]){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(r){await sf.forEach(r,async o=>{o._localHold&&await this.unholdCall(o._id)});const n=[];r.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{n.push(a.track)})}),await sf.forEach(r,async o=>{if(o==null)return;const a=new MediaStream,t=Jt.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{n.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&Jt.createMediaStreamSource(new MediaStream([p])).connect(t)})}),r[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();Jt.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(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))}muteCaller(r){this.processCallerMute(r,!0)}unmuteCaller(r){this.processCallerMute(r,!1)}terminateCall(r){const n=this.extendedCalls[r];n._status!==8&&n.terminate()}messageTerminate(r){const n=this.extendedMessages[r];n._status!==8&&n.terminate()}transferCall(r,n){if(n.toString().length===0)return new 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)}mergeCall(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=Zg(a);this.setCallTime({callId:r,...t})},1e3);this.setTimeInterval(r,o)}async setActiveRoom(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 setupCall(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(Wt.CALL_CONFIRMED,v=>{n.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(n.id))}),this.subscribe(Wt.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),h=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=h,h?this.addCall(s,!1):this.addCall(s),this.addCallStatus(n.id),this.addRoom(t),h&&this.answerCall(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];this.stopVUMeter("origin"),n.connection.getSenders().forEach(a=>{a.track.stop()});const o=n.roomId;this.removeCall(r._id),this.roomReconfigure(o)}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.stopVUMeter(n.id),this.logger.log("Session ended for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Wt.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),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),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:Wt.CALL_PROGRESS,session:n,event:o})}),n.on("failed",o=>{var t,s;this.stopVUMeter(n.id),this.logger.log("Session failed for",(s=(t=n._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.triggerListener({listenerType:Wt.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),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),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:Wt.CALL_CONFIRMED,session:n,event:o}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(r),n.direction==="outgoing"){const o=this.getActiveCalls[n.id].roomId;this.setActiveRoom(o)}}newMSRPSessionCallback(r){const n=r.session;n.on("ended",o=>{this.triggerMSRPListener({listenerType:Wt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Wt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Wt.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.initializeMediaDevices(),this}setMuteWhenJoin(r){this.muteWhenJoinEnabled=r,this.emit("changeMuteWhenJoin",r)}setMicrophoneSensitivity(r){if(r<0||r>1)throw new Error("Value should be in range from 0 to 1!");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(Wl.SELECTED_INPUT_DEVICE,r),this.selectedMediaDevices.input=r,this.emit("changeActiveInputMediaDevice",r)}setSelectedOutputDevice(r){localStorage.setItem(Wl.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 Yv(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],h=ev(p,cT);h.callId=r._id,this.setCallMetrics(n)},this.subscribe(Wt.CALL_ENDED,s=>{s._id===r._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(r,n){this.VUMeter.start(r,n)}stopVUMeter(r){this.VUMeter.stop(r)}async setupStream(){const r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=r}async triggerAddStream(r,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=lf(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(s=>s.enabled=!a),this.setActiveStream(o),await n.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([r.track]);nv(t,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(r,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.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",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 processRoomChange({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.setActiveRoom(n),Promise.all([this.roomReconfigure(o),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(n)})}}module.exports=hT;