@wazo/sdk 0.43.4 → 0.43.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/wazo-sdk.js +2 -2
- package/esm/api/auth.js +1 -1
- package/esm/simple/Auth.js +4 -10
- package/esm/simple/__tests__/Auth.test.js +7 -63
- package/esm/types/simple/Auth.d.ts.map +1 -1
- package/esm/types/utils/api-requester.d.ts.map +1 -1
- package/esm/utils/__tests__/api-requester.test.js +17 -0
- package/esm/utils/api-requester.js +9 -1
- package/lib/api/auth.js +1 -1
- package/lib/simple/Auth.js +4 -10
- package/lib/simple/__tests__/Auth.test.js +10 -63
- package/lib/types/simple/Auth.d.ts.map +1 -1
- package/lib/types/utils/api-requester.d.ts.map +1 -1
- package/lib/utils/__tests__/api-requester.test.js +17 -0
- package/lib/utils/api-requester.js +9 -1
- package/package.json +1 -1
- package/src/api/auth.ts +1 -1
- package/src/simple/Auth.ts +4 -11
- package/src/simple/__tests__/Auth.test.ts +8 -86
- package/src/utils/__tests__/api-requester.test.ts +20 -0
- package/src/utils/api-requester.ts +9 -1
package/dist/wazo-sdk.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@wazo/sdk"]=e["@wazo/sdk"]||{})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}"undefined"==typeof window?global.window={navigator:{},removeEventListener:{},addEventListener:{}}:window.global=window.global||window;const i="function"==typeof Buffer,n=("function"==typeof TextDecoder&&new TextDecoder,"function"==typeof TextEncoder?new TextEncoder:void 0),r=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),s=(e=>{let t={};return e.forEach(((e,i)=>t[e]=i)),t})(r),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,o=String.fromCharCode.bind(String),c=("function"==typeof Uint8Array.from&&Uint8Array.from.bind(Uint8Array),e=>e.replace(/=/g,"").replace(/[+\/]/g,(e=>"+"==e?"-":"_"))),d=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),l=e=>{let t,i,n,s,a="";const o=e.length%3;for(let o=0;o<e.length;){if((i=e.charCodeAt(o++))>255||(n=e.charCodeAt(o++))>255||(s=e.charCodeAt(o++))>255)throw new TypeError("invalid character found");t=i<<16|n<<8|s,a+=r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}return o?a.slice(0,o-3)+"===".substring(o):a},h="function"==typeof btoa?e=>btoa(e):i?e=>Buffer.from(e,"binary").toString("base64"):l,u=i?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let i=0,n=e.length;i<n;i+=4096)t.push(o.apply(null,e.subarray(i,i+4096)));return h(t.join(""))},p=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?o(192|t>>>6)+o(128|63&t):o(224|t>>>12&15)+o(128|t>>>6&63)+o(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return o(240|t>>>18&7)+o(128|t>>>12&63)+o(128|t>>>6&63)+o(128|63&t)},g=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,f=e=>e.replace(g,p),m=i?e=>Buffer.from(e,"utf8").toString("base64"):n?e=>u(n.encode(e)):e=>h(f(e)),v=(e,t=!1)=>t?c(m(e)):m(e),y=e=>{if(e=e.replace(/\s+/g,""),!a.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,i,n,r="";for(let a=0;a<e.length;)t=s[e.charAt(a++)]<<18|s[e.charAt(a++)]<<12|(i=s[e.charAt(a++)])<<6|(n=s[e.charAt(a++)]),r+=64===i?o(t>>16&255):64===n?o(t>>16&255,t>>8&255):o(t>>16&255,t>>8&255,255&t);return r},S=v;class b extends Error{static fromResponse(e,t){return new b(e.message||JSON.stringify(e),t,e.timestamp,e.error_id,e.details,e)}static fromText(e,t){return new b(e,t)}status;timestamp;errorId;details;error;constructor(e,t,i=null,n=null,r=null,s=null){super(e),this.timestamp=i,this.status=t,this.errorId=n,this.details=r,this.error=s}}class w extends b{static fromResponse(e,t){return new w(e.message||JSON.stringify(e),t,e.timestamp,e.error_id,e.details)}static fromText(e,t){return new w(e,t)}}var E="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function C(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var T={exports:{}};!function(e,t){e.exports=function(){var t,i;function n(){return t.apply(null,arguments)}function r(e){t=e}function s(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function a(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function o(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(o(e,t))return!1;return!0}function d(e){return void 0===e}function l(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function h(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function u(e,t){var i,n=[],r=e.length;for(i=0;i<r;++i)n.push(t(e[i],i));return n}function p(e,t){for(var i in t)o(t,i)&&(e[i]=t[i]);return o(t,"toString")&&(e.toString=t.toString),o(t,"valueOf")&&(e.valueOf=t.valueOf),e}function g(e,t,i,n){return zi(e,t,i,n,!0).utc()}function f(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(e){return null==e._pf&&(e._pf=f()),e._pf}function v(e){var t=null,n=!1,r=e._d&&!isNaN(e._d.getTime());return r&&(t=m(e),n=i.call(t.parsedDateParts,(function(e){return null!=e})),r=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n),e._strict&&(r=r&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour)),null!=Object.isFrozen&&Object.isFrozen(e)?r:(e._isValid=r,e._isValid)}function y(e){var t=g(NaN);return null!=e?p(m(t),e):m(t).userInvalidated=!0,t}i=Array.prototype.some?Array.prototype.some:function(e){var t,i=Object(this),n=i.length>>>0;for(t=0;t<n;t++)if(t in i&&e.call(this,i[t],t,i))return!0;return!1};var S=n.momentProperties=[],b=!1;function w(e,t){var i,n,r,s=S.length;if(d(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),d(t._i)||(e._i=t._i),d(t._f)||(e._f=t._f),d(t._l)||(e._l=t._l),d(t._strict)||(e._strict=t._strict),d(t._tzm)||(e._tzm=t._tzm),d(t._isUTC)||(e._isUTC=t._isUTC),d(t._offset)||(e._offset=t._offset),d(t._pf)||(e._pf=m(t)),d(t._locale)||(e._locale=t._locale),s>0)for(i=0;i<s;i++)d(r=t[n=S[i]])||(e[n]=r);return e}function E(e){w(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===b&&(b=!0,n.updateOffset(this),b=!1)}function C(e){return e instanceof E||null!=e&&null!=e._isAMomentObject}function T(e){!1===n.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function _(e,t){var i=!0;return p((function(){if(null!=n.deprecationHandler&&n.deprecationHandler(null,e),i){var r,s,a,c=[],d=arguments.length;for(s=0;s<d;s++){if(r="","object"==typeof arguments[s]){for(a in r+="\n["+s+"] ",arguments[0])o(arguments[0],a)&&(r+=a+": "+arguments[0][a]+", ");r=r.slice(0,-2)}else r=arguments[s];c.push(r)}T(e+"\nArguments: "+Array.prototype.slice.call(c).join("")+"\n"+(new Error).stack),i=!1}return t.apply(this,arguments)}),t)}var x,I={};function R(e,t){null!=n.deprecationHandler&&n.deprecationHandler(e,t),I[e]||(T(t),I[e]=!0)}function A(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function P(e){var t,i;for(i in e)o(e,i)&&(A(t=e[i])?this[i]=t:this["_"+i]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function D(e,t){var i,n=p({},e);for(i in t)o(t,i)&&(a(e[i])&&a(t[i])?(n[i]={},p(n[i],e[i]),p(n[i],t[i])):null!=t[i]?n[i]=t[i]:delete n[i]);for(i in e)o(e,i)&&!o(t,i)&&a(e[i])&&(n[i]=p({},n[i]));return n}function N(e){null!=e&&this.set(e)}n.suppressDeprecationWarnings=!1,n.deprecationHandler=null,x=Object.keys?Object.keys:function(e){var t,i=[];for(t in e)o(e,t)&&i.push(t);return i};var k={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function O(e,t,i){var n=this._calendar[e]||this._calendar.sameElse;return A(n)?n.call(t,i):n}function F(e,t,i){var n=""+Math.abs(e),r=t-n.length;return(e>=0?i?"+":"":"-")+Math.pow(10,Math.max(0,r)).toString().substr(1)+n}var M=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,H=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,L={},j={};function B(e,t,i,n){var r=n;"string"==typeof n&&(r=function(){return this[n]()}),e&&(j[e]=r),t&&(j[t[0]]=function(){return F(r.apply(this,arguments),t[1],t[2])}),i&&(j[i]=function(){return this.localeData().ordinal(r.apply(this,arguments),e)})}function U(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function V(e){var t,i,n=e.match(M);for(t=0,i=n.length;t<i;t++)j[n[t]]?n[t]=j[n[t]]:n[t]=U(n[t]);return function(t){var r,s="";for(r=0;r<i;r++)s+=A(n[r])?n[r].call(t,e):n[r];return s}}function q(e,t){return e.isValid()?(t=G(t,e.localeData()),L[t]=L[t]||V(t),L[t](e)):e.localeData().invalidDate()}function G(e,t){var i=5;function n(e){return t.longDateFormat(e)||e}for(H.lastIndex=0;i>=0&&H.test(e);)e=e.replace(H,n),H.lastIndex=0,i-=1;return e}var K={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function W(e){var t=this._longDateFormat[e],i=this._longDateFormat[e.toUpperCase()];return t||!i?t:(this._longDateFormat[e]=i.match(M).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])}var z="Invalid date";function Y(){return this._invalidDate}var J="%d",Z=/\d{1,2}/;function X(e){return this._ordinal.replace("%d",e)}var Q={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function ee(e,t,i,n){var r=this._relativeTime[i];return A(r)?r(e,t,i,n):r.replace(/%d/i,e)}function te(e,t){var i=this._relativeTime[e>0?"future":"past"];return A(i)?i(t):i.replace(/%s/i,t)}var ie={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function ne(e){return"string"==typeof e?ie[e]||ie[e.toLowerCase()]:void 0}function re(e){var t,i,n={};for(i in e)o(e,i)&&(t=ne(i))&&(n[t]=e[i]);return n}var se={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};function ae(e){var t,i=[];for(t in e)o(e,t)&&i.push({unit:t,priority:se[t]});return i.sort((function(e,t){return e.priority-t.priority})),i}var oe,ce=/\d/,de=/\d\d/,le=/\d{3}/,he=/\d{4}/,ue=/[+-]?\d{6}/,pe=/\d\d?/,ge=/\d\d\d\d?/,fe=/\d\d\d\d\d\d?/,me=/\d{1,3}/,ve=/\d{1,4}/,ye=/[+-]?\d{1,6}/,Se=/\d+/,be=/[+-]?\d+/,we=/Z|[+-]\d\d:?\d\d/gi,Ee=/Z|[+-]\d\d(?::?\d\d)?/gi,Ce=/[+-]?\d+(\.\d{1,3})?/,$e=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,Te=/^[1-9]\d?/,_e=/^([1-9]\d|\d)/;function xe(e,t,i){oe[e]=A(t)?t:function(e,n){return e&&i?i:t}}function Ie(e,t){return o(oe,e)?oe[e](t._strict,t._locale):new RegExp(Re(e))}function Re(e){return Ae(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,i,n,r){return t||i||n||r})))}function Ae(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function Pe(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function De(e){var t=+e,i=0;return 0!==t&&isFinite(t)&&(i=Pe(t)),i}oe={};var Ne={};function ke(e,t){var i,n,r=t;for("string"==typeof e&&(e=[e]),l(t)&&(r=function(e,i){i[t]=De(e)}),n=e.length,i=0;i<n;i++)Ne[e[i]]=r}function Oe(e,t){ke(e,(function(e,i,n,r){n._w=n._w||{},t(e,n._w,n,r)}))}function Fe(e,t,i){null!=t&&o(Ne,e)&&Ne[e](t,i._a,i,e)}function Me(e){return e%4==0&&e%100!=0||e%400==0}var He=0,Le=1,je=2,Be=3,Ue=4,Ve=5,qe=6,Ge=7,Ke=8;function We(e){return Me(e)?366:365}B("Y",0,0,(function(){var e=this.year();return e<=9999?F(e,4):"+"+e})),B(0,["YY",2],0,(function(){return this.year()%100})),B(0,["YYYY",4],0,"year"),B(0,["YYYYY",5],0,"year"),B(0,["YYYYYY",6,!0],0,"year"),xe("Y",be),xe("YY",pe,de),xe("YYYY",ve,he),xe("YYYYY",ye,ue),xe("YYYYYY",ye,ue),ke(["YYYYY","YYYYYY"],He),ke("YYYY",(function(e,t){t[He]=2===e.length?n.parseTwoDigitYear(e):De(e)})),ke("YY",(function(e,t){t[He]=n.parseTwoDigitYear(e)})),ke("Y",(function(e,t){t[He]=parseInt(e,10)})),n.parseTwoDigitYear=function(e){return De(e)+(De(e)>68?1900:2e3)};var ze,Ye=Ze("FullYear",!0);function Je(){return Me(this.year())}function Ze(e,t){return function(i){return null!=i?(Qe(this,e,i),n.updateOffset(this,t),this):Xe(this,e)}}function Xe(e,t){if(!e.isValid())return NaN;var i=e._d,n=e._isUTC;switch(t){case"Milliseconds":return n?i.getUTCMilliseconds():i.getMilliseconds();case"Seconds":return n?i.getUTCSeconds():i.getSeconds();case"Minutes":return n?i.getUTCMinutes():i.getMinutes();case"Hours":return n?i.getUTCHours():i.getHours();case"Date":return n?i.getUTCDate():i.getDate();case"Day":return n?i.getUTCDay():i.getDay();case"Month":return n?i.getUTCMonth():i.getMonth();case"FullYear":return n?i.getUTCFullYear():i.getFullYear();default:return NaN}}function Qe(e,t,i){var n,r,s,a,o;if(e.isValid()&&!isNaN(i)){switch(n=e._d,r=e._isUTC,t){case"Milliseconds":return void(r?n.setUTCMilliseconds(i):n.setMilliseconds(i));case"Seconds":return void(r?n.setUTCSeconds(i):n.setSeconds(i));case"Minutes":return void(r?n.setUTCMinutes(i):n.setMinutes(i));case"Hours":return void(r?n.setUTCHours(i):n.setHours(i));case"Date":return void(r?n.setUTCDate(i):n.setDate(i));case"FullYear":break;default:return}s=i,a=e.month(),o=29!==(o=e.date())||1!==a||Me(s)?o:28,r?n.setUTCFullYear(s,a,o):n.setFullYear(s,a,o)}}function et(e){return A(this[e=ne(e)])?this[e]():this}function tt(e,t){if("object"==typeof e){var i,n=ae(e=re(e)),r=n.length;for(i=0;i<r;i++)this[n[i].unit](e[n[i].unit])}else if(A(this[e=ne(e)]))return this[e](t);return this}function it(e,t){return(e%t+t)%t}function nt(e,t){if(isNaN(e)||isNaN(t))return NaN;var i=it(t,12);return e+=(t-i)/12,1===i?Me(e)?29:28:31-i%7%2}ze=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},B("M",["MM",2],"Mo",(function(){return this.month()+1})),B("MMM",0,0,(function(e){return this.localeData().monthsShort(this,e)})),B("MMMM",0,0,(function(e){return this.localeData().months(this,e)})),xe("M",pe,Te),xe("MM",pe,de),xe("MMM",(function(e,t){return t.monthsShortRegex(e)})),xe("MMMM",(function(e,t){return t.monthsRegex(e)})),ke(["M","MM"],(function(e,t){t[Le]=De(e)-1})),ke(["MMM","MMMM"],(function(e,t,i,n){var r=i._locale.monthsParse(e,n,i._strict);null!=r?t[Le]=r:m(i).invalidMonth=e}));var rt="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),st="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),at=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,ot=$e,ct=$e;function dt(e,t){return e?s(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||at).test(t)?"format":"standalone"][e.month()]:s(this._months)?this._months:this._months.standalone}function lt(e,t){return e?s(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[at.test(t)?"format":"standalone"][e.month()]:s(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function ht(e,t,i){var n,r,s,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],n=0;n<12;++n)s=g([2e3,n]),this._shortMonthsParse[n]=this.monthsShort(s,"").toLocaleLowerCase(),this._longMonthsParse[n]=this.months(s,"").toLocaleLowerCase();return i?"MMM"===t?-1!==(r=ze.call(this._shortMonthsParse,a))?r:null:-1!==(r=ze.call(this._longMonthsParse,a))?r:null:"MMM"===t?-1!==(r=ze.call(this._shortMonthsParse,a))||-1!==(r=ze.call(this._longMonthsParse,a))?r:null:-1!==(r=ze.call(this._longMonthsParse,a))||-1!==(r=ze.call(this._shortMonthsParse,a))?r:null}function ut(e,t,i){var n,r,s;if(this._monthsParseExact)return ht.call(this,e,t,i);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),n=0;n<12;n++){if(r=g([2e3,n]),i&&!this._longMonthsParse[n]&&(this._longMonthsParse[n]=new RegExp("^"+this.months(r,"").replace(".","")+"$","i"),this._shortMonthsParse[n]=new RegExp("^"+this.monthsShort(r,"").replace(".","")+"$","i")),i||this._monthsParse[n]||(s="^"+this.months(r,"")+"|^"+this.monthsShort(r,""),this._monthsParse[n]=new RegExp(s.replace(".",""),"i")),i&&"MMMM"===t&&this._longMonthsParse[n].test(e))return n;if(i&&"MMM"===t&&this._shortMonthsParse[n].test(e))return n;if(!i&&this._monthsParse[n].test(e))return n}}function pt(e,t){if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=De(t);else if(!l(t=e.localeData().monthsParse(t)))return e;var i=t,n=e.date();return n=n<29?n:Math.min(n,nt(e.year(),i)),e._isUTC?e._d.setUTCMonth(i,n):e._d.setMonth(i,n),e}function gt(e){return null!=e?(pt(this,e),n.updateOffset(this,!0),this):Xe(this,"Month")}function ft(){return nt(this.year(),this.month())}function mt(e){return this._monthsParseExact?(o(this,"_monthsRegex")||yt.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(o(this,"_monthsShortRegex")||(this._monthsShortRegex=ot),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function vt(e){return this._monthsParseExact?(o(this,"_monthsRegex")||yt.call(this),e?this._monthsStrictRegex:this._monthsRegex):(o(this,"_monthsRegex")||(this._monthsRegex=ct),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function yt(){function e(e,t){return t.length-e.length}var t,i,n,r,s=[],a=[],o=[];for(t=0;t<12;t++)i=g([2e3,t]),n=Ae(this.monthsShort(i,"")),r=Ae(this.months(i,"")),s.push(n),a.push(r),o.push(r),o.push(n);s.sort(e),a.sort(e),o.sort(e),this._monthsRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function St(e,t,i,n,r,s,a){var o;return e<100&&e>=0?(o=new Date(e+400,t,i,n,r,s,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,i,n,r,s,a),o}function bt(e){var t,i;return e<100&&e>=0?((i=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,i)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function wt(e,t,i){var n=7+t-i;return-(7+bt(e,0,n).getUTCDay()-t)%7+n-1}function Et(e,t,i,n,r){var s,a,o=1+7*(t-1)+(7+i-n)%7+wt(e,n,r);return o<=0?a=We(s=e-1)+o:o>We(e)?(s=e+1,a=o-We(e)):(s=e,a=o),{year:s,dayOfYear:a}}function Ct(e,t,i){var n,r,s=wt(e.year(),t,i),a=Math.floor((e.dayOfYear()-s-1)/7)+1;return a<1?n=a+$t(r=e.year()-1,t,i):a>$t(e.year(),t,i)?(n=a-$t(e.year(),t,i),r=e.year()+1):(r=e.year(),n=a),{week:n,year:r}}function $t(e,t,i){var n=wt(e,t,i),r=wt(e+1,t,i);return(We(e)-n+r)/7}function Tt(e){return Ct(e,this._week.dow,this._week.doy).week}B("w",["ww",2],"wo","week"),B("W",["WW",2],"Wo","isoWeek"),xe("w",pe,Te),xe("ww",pe,de),xe("W",pe,Te),xe("WW",pe,de),Oe(["w","ww","W","WW"],(function(e,t,i,n){t[n.substr(0,1)]=De(e)}));var _t={dow:0,doy:6};function xt(){return this._week.dow}function It(){return this._week.doy}function Rt(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")}function At(e){var t=Ct(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")}function Pt(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}function Dt(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Nt(e,t){return e.slice(t,7).concat(e.slice(0,t))}B("d",0,"do","day"),B("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),B("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),B("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),B("e",0,0,"weekday"),B("E",0,0,"isoWeekday"),xe("d",pe),xe("e",pe),xe("E",pe),xe("dd",(function(e,t){return t.weekdaysMinRegex(e)})),xe("ddd",(function(e,t){return t.weekdaysShortRegex(e)})),xe("dddd",(function(e,t){return t.weekdaysRegex(e)})),Oe(["dd","ddd","dddd"],(function(e,t,i,n){var r=i._locale.weekdaysParse(e,n,i._strict);null!=r?t.d=r:m(i).invalidWeekday=e})),Oe(["d","e","E"],(function(e,t,i,n){t[n]=De(e)}));var kt="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Ot="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Ft="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Mt=$e,Ht=$e,Lt=$e;function jt(e,t){var i=s(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?Nt(i,this._week.dow):e?i[e.day()]:i}function Bt(e){return!0===e?Nt(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function Ut(e){return!0===e?Nt(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function Vt(e,t,i){var n,r,s,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],n=0;n<7;++n)s=g([2e3,1]).day(n),this._minWeekdaysParse[n]=this.weekdaysMin(s,"").toLocaleLowerCase(),this._shortWeekdaysParse[n]=this.weekdaysShort(s,"").toLocaleLowerCase(),this._weekdaysParse[n]=this.weekdays(s,"").toLocaleLowerCase();return i?"dddd"===t?-1!==(r=ze.call(this._weekdaysParse,a))?r:null:"ddd"===t?-1!==(r=ze.call(this._shortWeekdaysParse,a))?r:null:-1!==(r=ze.call(this._minWeekdaysParse,a))?r:null:"dddd"===t?-1!==(r=ze.call(this._weekdaysParse,a))||-1!==(r=ze.call(this._shortWeekdaysParse,a))||-1!==(r=ze.call(this._minWeekdaysParse,a))?r:null:"ddd"===t?-1!==(r=ze.call(this._shortWeekdaysParse,a))||-1!==(r=ze.call(this._weekdaysParse,a))||-1!==(r=ze.call(this._minWeekdaysParse,a))?r:null:-1!==(r=ze.call(this._minWeekdaysParse,a))||-1!==(r=ze.call(this._weekdaysParse,a))||-1!==(r=ze.call(this._shortWeekdaysParse,a))?r:null}function qt(e,t,i){var n,r,s;if(this._weekdaysParseExact)return Vt.call(this,e,t,i);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),n=0;n<7;n++){if(r=g([2e3,1]).day(n),i&&!this._fullWeekdaysParse[n]&&(this._fullWeekdaysParse[n]=new RegExp("^"+this.weekdays(r,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[n]=new RegExp("^"+this.weekdaysShort(r,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[n]=new RegExp("^"+this.weekdaysMin(r,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[n]||(s="^"+this.weekdays(r,"")+"|^"+this.weekdaysShort(r,"")+"|^"+this.weekdaysMin(r,""),this._weekdaysParse[n]=new RegExp(s.replace(".",""),"i")),i&&"dddd"===t&&this._fullWeekdaysParse[n].test(e))return n;if(i&&"ddd"===t&&this._shortWeekdaysParse[n].test(e))return n;if(i&&"dd"===t&&this._minWeekdaysParse[n].test(e))return n;if(!i&&this._weekdaysParse[n].test(e))return n}}function Gt(e){if(!this.isValid())return null!=e?this:NaN;var t=Xe(this,"Day");return null!=e?(e=Pt(e,this.localeData()),this.add(e-t,"d")):t}function Kt(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")}function Wt(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=Dt(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7}function zt(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||Zt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(o(this,"_weekdaysRegex")||(this._weekdaysRegex=Mt),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function Yt(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||Zt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(o(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Ht),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Jt(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||Zt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(o(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Lt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Zt(){function e(e,t){return t.length-e.length}var t,i,n,r,s,a=[],o=[],c=[],d=[];for(t=0;t<7;t++)i=g([2e3,1]).day(t),n=Ae(this.weekdaysMin(i,"")),r=Ae(this.weekdaysShort(i,"")),s=Ae(this.weekdays(i,"")),a.push(n),o.push(r),c.push(s),d.push(n),d.push(r),d.push(s);a.sort(e),o.sort(e),c.sort(e),d.sort(e),this._weekdaysRegex=new RegExp("^("+d.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Xt(){return this.hours()%12||12}function Qt(){return this.hours()||24}function ei(e,t){B(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function ti(e,t){return t._meridiemParse}function ii(e){return"p"===(e+"").toLowerCase().charAt(0)}B("H",["HH",2],0,"hour"),B("h",["hh",2],0,Xt),B("k",["kk",2],0,Qt),B("hmm",0,0,(function(){return""+Xt.apply(this)+F(this.minutes(),2)})),B("hmmss",0,0,(function(){return""+Xt.apply(this)+F(this.minutes(),2)+F(this.seconds(),2)})),B("Hmm",0,0,(function(){return""+this.hours()+F(this.minutes(),2)})),B("Hmmss",0,0,(function(){return""+this.hours()+F(this.minutes(),2)+F(this.seconds(),2)})),ei("a",!0),ei("A",!1),xe("a",ti),xe("A",ti),xe("H",pe,_e),xe("h",pe,Te),xe("k",pe,Te),xe("HH",pe,de),xe("hh",pe,de),xe("kk",pe,de),xe("hmm",ge),xe("hmmss",fe),xe("Hmm",ge),xe("Hmmss",fe),ke(["H","HH"],Be),ke(["k","kk"],(function(e,t,i){var n=De(e);t[Be]=24===n?0:n})),ke(["a","A"],(function(e,t,i){i._isPm=i._locale.isPM(e),i._meridiem=e})),ke(["h","hh"],(function(e,t,i){t[Be]=De(e),m(i).bigHour=!0})),ke("hmm",(function(e,t,i){var n=e.length-2;t[Be]=De(e.substr(0,n)),t[Ue]=De(e.substr(n)),m(i).bigHour=!0})),ke("hmmss",(function(e,t,i){var n=e.length-4,r=e.length-2;t[Be]=De(e.substr(0,n)),t[Ue]=De(e.substr(n,2)),t[Ve]=De(e.substr(r)),m(i).bigHour=!0})),ke("Hmm",(function(e,t,i){var n=e.length-2;t[Be]=De(e.substr(0,n)),t[Ue]=De(e.substr(n))})),ke("Hmmss",(function(e,t,i){var n=e.length-4,r=e.length-2;t[Be]=De(e.substr(0,n)),t[Ue]=De(e.substr(n,2)),t[Ve]=De(e.substr(r))}));var ni=/[ap]\.?m?\.?/i,ri=Ze("Hours",!0);function si(e,t,i){return e>11?i?"pm":"PM":i?"am":"AM"}var ai,oi={calendar:k,longDateFormat:K,invalidDate:z,ordinal:J,dayOfMonthOrdinalParse:Z,relativeTime:Q,months:rt,monthsShort:st,week:_t,weekdays:kt,weekdaysMin:Ft,weekdaysShort:Ot,meridiemParse:ni},ci={},di={};function li(e,t){var i,n=Math.min(e.length,t.length);for(i=0;i<n;i+=1)if(e[i]!==t[i])return i;return n}function hi(e){return e?e.toLowerCase().replace("_","-"):e}function ui(e){for(var t,i,n,r,s=0;s<e.length;){for(t=(r=hi(e[s]).split("-")).length,i=(i=hi(e[s+1]))?i.split("-"):null;t>0;){if(n=gi(r.slice(0,t).join("-")))return n;if(i&&i.length>=t&&li(r,i)>=t-1)break;t--}s++}return ai}function pi(e){return!(!e||!e.match("^[^/\\\\]*$"))}function gi(t){var i=null;if(void 0===ci[t]&&e&&e.exports&&pi(t))try{i=ai._abbr,$("./locale/"+t),fi(i)}catch(e){ci[t]=null}return ci[t]}function fi(e,t){var i;return e&&((i=d(t)?yi(e):mi(e,t))?ai=i:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ai._abbr}function mi(e,t){if(null!==t){var i,n=oi;if(t.abbr=e,null!=ci[e])R("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=ci[e]._config;else if(null!=t.parentLocale)if(null!=ci[t.parentLocale])n=ci[t.parentLocale]._config;else{if(null==(i=gi(t.parentLocale)))return di[t.parentLocale]||(di[t.parentLocale]=[]),di[t.parentLocale].push({name:e,config:t}),null;n=i._config}return ci[e]=new N(D(n,t)),di[e]&&di[e].forEach((function(e){mi(e.name,e.config)})),fi(e),ci[e]}return delete ci[e],null}function vi(e,t){if(null!=t){var i,n,r=oi;null!=ci[e]&&null!=ci[e].parentLocale?ci[e].set(D(ci[e]._config,t)):(null!=(n=gi(e))&&(r=n._config),t=D(r,t),null==n&&(t.abbr=e),(i=new N(t)).parentLocale=ci[e],ci[e]=i),fi(e)}else null!=ci[e]&&(null!=ci[e].parentLocale?(ci[e]=ci[e].parentLocale,e===fi()&&fi(e)):null!=ci[e]&&delete ci[e]);return ci[e]}function yi(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ai;if(!s(e)){if(t=gi(e))return t;e=[e]}return ui(e)}function Si(){return x(ci)}function bi(e){var t,i=e._a;return i&&-2===m(e).overflow&&(t=i[Le]<0||i[Le]>11?Le:i[je]<1||i[je]>nt(i[He],i[Le])?je:i[Be]<0||i[Be]>24||24===i[Be]&&(0!==i[Ue]||0!==i[Ve]||0!==i[qe])?Be:i[Ue]<0||i[Ue]>59?Ue:i[Ve]<0||i[Ve]>59?Ve:i[qe]<0||i[qe]>999?qe:-1,m(e)._overflowDayOfYear&&(t<He||t>je)&&(t=je),m(e)._overflowWeeks&&-1===t&&(t=Ge),m(e)._overflowWeekday&&-1===t&&(t=Ke),m(e).overflow=t),e}var wi=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Ei=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Ci=/Z|[+-]\d\d(?::?\d\d)?/,$i=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],Ti=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],_i=/^\/?Date\((-?\d+)/i,xi=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Ii={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Ri(e){var t,i,n,r,s,a,o=e._i,c=wi.exec(o)||Ei.exec(o),d=$i.length,l=Ti.length;if(c){for(m(e).iso=!0,t=0,i=d;t<i;t++)if($i[t][1].exec(c[1])){r=$i[t][0],n=!1!==$i[t][2];break}if(null==r)return void(e._isValid=!1);if(c[3]){for(t=0,i=l;t<i;t++)if(Ti[t][1].exec(c[3])){s=(c[2]||" ")+Ti[t][0];break}if(null==s)return void(e._isValid=!1)}if(!n&&null!=s)return void(e._isValid=!1);if(c[4]){if(!Ci.exec(c[4]))return void(e._isValid=!1);a="Z"}e._f=r+(s||"")+(a||""),Bi(e)}else e._isValid=!1}function Ai(e,t,i,n,r,s){var a=[Pi(e),st.indexOf(t),parseInt(i,10),parseInt(n,10),parseInt(r,10)];return s&&a.push(parseInt(s,10)),a}function Pi(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function Di(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function Ni(e,t,i){return!e||Ot.indexOf(e)===new Date(t[0],t[1],t[2]).getDay()||(m(i).weekdayMismatch=!0,i._isValid=!1,!1)}function ki(e,t,i){if(e)return Ii[e];if(t)return 0;var n=parseInt(i,10),r=n%100;return(n-r)/100*60+r}function Oi(e){var t,i=xi.exec(Di(e._i));if(i){if(t=Ai(i[4],i[3],i[2],i[5],i[6],i[7]),!Ni(i[1],t,e))return;e._a=t,e._tzm=ki(i[8],i[9],i[10]),e._d=bt.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),m(e).rfc2822=!0}else e._isValid=!1}function Fi(e){var t=_i.exec(e._i);null===t?(Ri(e),!1===e._isValid&&(delete e._isValid,Oi(e),!1===e._isValid&&(delete e._isValid,e._strict?e._isValid=!1:n.createFromInputFallback(e)))):e._d=new Date(+t[1])}function Mi(e,t,i){return null!=e?e:null!=t?t:i}function Hi(e){var t=new Date(n.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function Li(e){var t,i,n,r,s,a=[];if(!e._d){for(n=Hi(e),e._w&&null==e._a[je]&&null==e._a[Le]&&ji(e),null!=e._dayOfYear&&(s=Mi(e._a[He],n[He]),(e._dayOfYear>We(s)||0===e._dayOfYear)&&(m(e)._overflowDayOfYear=!0),i=bt(s,0,e._dayOfYear),e._a[Le]=i.getUTCMonth(),e._a[je]=i.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=a[t]=n[t];for(;t<7;t++)e._a[t]=a[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[Be]&&0===e._a[Ue]&&0===e._a[Ve]&&0===e._a[qe]&&(e._nextDay=!0,e._a[Be]=0),e._d=(e._useUTC?bt:St).apply(null,a),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Be]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(m(e).weekdayMismatch=!0)}}function ji(e){var t,i,n,r,s,a,o,c,d;null!=(t=e._w).GG||null!=t.W||null!=t.E?(s=1,a=4,i=Mi(t.GG,e._a[He],Ct(Yi(),1,4).year),n=Mi(t.W,1),((r=Mi(t.E,1))<1||r>7)&&(c=!0)):(s=e._locale._week.dow,a=e._locale._week.doy,d=Ct(Yi(),s,a),i=Mi(t.gg,e._a[He],d.year),n=Mi(t.w,d.week),null!=t.d?((r=t.d)<0||r>6)&&(c=!0):null!=t.e?(r=t.e+s,(t.e<0||t.e>6)&&(c=!0)):r=s),n<1||n>$t(i,s,a)?m(e)._overflowWeeks=!0:null!=c?m(e)._overflowWeekday=!0:(o=Et(i,n,r,s,a),e._a[He]=o.year,e._dayOfYear=o.dayOfYear)}function Bi(e){if(e._f!==n.ISO_8601)if(e._f!==n.RFC_2822){e._a=[],m(e).empty=!0;var t,i,r,s,a,o,c,d=""+e._i,l=d.length,h=0;for(c=(r=G(e._f,e._locale).match(M)||[]).length,t=0;t<c;t++)s=r[t],(i=(d.match(Ie(s,e))||[])[0])&&((a=d.substr(0,d.indexOf(i))).length>0&&m(e).unusedInput.push(a),d=d.slice(d.indexOf(i)+i.length),h+=i.length),j[s]?(i?m(e).empty=!1:m(e).unusedTokens.push(s),Fe(s,i,e)):e._strict&&!i&&m(e).unusedTokens.push(s);m(e).charsLeftOver=l-h,d.length>0&&m(e).unusedInput.push(d),e._a[Be]<=12&&!0===m(e).bigHour&&e._a[Be]>0&&(m(e).bigHour=void 0),m(e).parsedDateParts=e._a.slice(0),m(e).meridiem=e._meridiem,e._a[Be]=Ui(e._locale,e._a[Be],e._meridiem),null!==(o=m(e).era)&&(e._a[He]=e._locale.erasConvertYear(o,e._a[He])),Li(e),bi(e)}else Oi(e);else Ri(e)}function Ui(e,t,i){var n;return null==i?t:null!=e.meridiemHour?e.meridiemHour(t,i):null!=e.isPM?((n=e.isPM(i))&&t<12&&(t+=12),n||12!==t||(t=0),t):t}function Vi(e){var t,i,n,r,s,a,o=!1,c=e._f.length;if(0===c)return m(e).invalidFormat=!0,void(e._d=new Date(NaN));for(r=0;r<c;r++)s=0,a=!1,t=w({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[r],Bi(t),v(t)&&(a=!0),s+=m(t).charsLeftOver,s+=10*m(t).unusedTokens.length,m(t).score=s,o?s<n&&(n=s,i=t):(null==n||s<n||a)&&(n=s,i=t,a&&(o=!0));p(e,i||t)}function qi(e){if(!e._d){var t=re(e._i),i=void 0===t.day?t.date:t.day;e._a=u([t.year,t.month,i,t.hour,t.minute,t.second,t.millisecond],(function(e){return e&&parseInt(e,10)})),Li(e)}}function Gi(e){var t=new E(bi(Ki(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}function Ki(e){var t=e._i,i=e._f;return e._locale=e._locale||yi(e._l),null===t||void 0===i&&""===t?y({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),C(t)?new E(bi(t)):(h(t)?e._d=t:s(i)?Vi(e):i?Bi(e):Wi(e),v(e)||(e._d=null),e))}function Wi(e){var t=e._i;d(t)?e._d=new Date(n.now()):h(t)?e._d=new Date(t.valueOf()):"string"==typeof t?Fi(e):s(t)?(e._a=u(t.slice(0),(function(e){return parseInt(e,10)})),Li(e)):a(t)?qi(e):l(t)?e._d=new Date(t):n.createFromInputFallback(e)}function zi(e,t,i,n,r){var o={};return!0!==t&&!1!==t||(n=t,t=void 0),!0!==i&&!1!==i||(n=i,i=void 0),(a(e)&&c(e)||s(e)&&0===e.length)&&(e=void 0),o._isAMomentObject=!0,o._useUTC=o._isUTC=r,o._l=i,o._i=e,o._f=t,o._strict=n,Gi(o)}function Yi(e,t,i,n){return zi(e,t,i,n,!1)}n.createFromInputFallback=_("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",(function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))})),n.ISO_8601=function(){},n.RFC_2822=function(){};var Ji=_("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=Yi.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:y()})),Zi=_("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=Yi.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:y()}));function Xi(e,t){var i,n;if(1===t.length&&s(t[0])&&(t=t[0]),!t.length)return Yi();for(i=t[0],n=1;n<t.length;++n)t[n].isValid()&&!t[n][e](i)||(i=t[n]);return i}function Qi(){return Xi("isBefore",[].slice.call(arguments,0))}function en(){return Xi("isAfter",[].slice.call(arguments,0))}var tn=function(){return Date.now?Date.now():+new Date},nn=["year","quarter","month","week","day","hour","minute","second","millisecond"];function rn(e){var t,i,n=!1,r=nn.length;for(t in e)if(o(e,t)&&(-1===ze.call(nn,t)||null!=e[t]&&isNaN(e[t])))return!1;for(i=0;i<r;++i)if(e[nn[i]]){if(n)return!1;parseFloat(e[nn[i]])!==De(e[nn[i]])&&(n=!0)}return!0}function sn(){return this._isValid}function an(){return Rn(NaN)}function on(e){var t=re(e),i=t.year||0,n=t.quarter||0,r=t.month||0,s=t.week||t.isoWeek||0,a=t.day||0,o=t.hour||0,c=t.minute||0,d=t.second||0,l=t.millisecond||0;this._isValid=rn(t),this._milliseconds=+l+1e3*d+6e4*c+1e3*o*60*60,this._days=+a+7*s,this._months=+r+3*n+12*i,this._data={},this._locale=yi(),this._bubble()}function cn(e){return e instanceof on}function dn(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function ln(e,t,i){var n,r=Math.min(e.length,t.length),s=Math.abs(e.length-t.length),a=0;for(n=0;n<r;n++)(i&&e[n]!==t[n]||!i&&De(e[n])!==De(t[n]))&&a++;return a+s}function hn(e,t){B(e,0,0,(function(){var e=this.utcOffset(),i="+";return e<0&&(e=-e,i="-"),i+F(~~(e/60),2)+t+F(~~e%60,2)}))}hn("Z",":"),hn("ZZ",""),xe("Z",Ee),xe("ZZ",Ee),ke(["Z","ZZ"],(function(e,t,i){i._useUTC=!0,i._tzm=pn(Ee,e)}));var un=/([\+\-]|\d\d)/gi;function pn(e,t){var i,n,r=(t||"").match(e);return null===r?null:0===(n=60*(i=((r[r.length-1]||[])+"").match(un)||["-",0,0])[1]+De(i[2]))?0:"+"===i[0]?n:-n}function gn(e,t){var i,r;return t._isUTC?(i=t.clone(),r=(C(e)||h(e)?e.valueOf():Yi(e).valueOf())-i.valueOf(),i._d.setTime(i._d.valueOf()+r),n.updateOffset(i,!1),i):Yi(e).local()}function fn(e){return-Math.round(e._d.getTimezoneOffset())}function mn(e,t,i){var r,s=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=pn(Ee,e)))return this}else Math.abs(e)<16&&!i&&(e*=60);return!this._isUTC&&t&&(r=fn(this)),this._offset=e,this._isUTC=!0,null!=r&&this.add(r,"m"),s!==e&&(!t||this._changeInProgress?kn(this,Rn(e-s,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,n.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?s:fn(this)}function vn(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}function yn(e){return this.utcOffset(0,e)}function Sn(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(fn(this),"m")),this}function bn(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=pn(we,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this}function wn(e){return!!this.isValid()&&(e=e?Yi(e).utcOffset():0,(this.utcOffset()-e)%60==0)}function En(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Cn(){if(!d(this._isDSTShifted))return this._isDSTShifted;var e,t={};return w(t,this),(t=Ki(t))._a?(e=t._isUTC?g(t._a):Yi(t._a),this._isDSTShifted=this.isValid()&&ln(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function $n(){return!!this.isValid()&&!this._isUTC}function Tn(){return!!this.isValid()&&this._isUTC}function _n(){return!!this.isValid()&&this._isUTC&&0===this._offset}n.updateOffset=function(){};var xn=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,In=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Rn(e,t){var i,n,r,s=e,a=null;return cn(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:l(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(a=xn.exec(e))?(i="-"===a[1]?-1:1,s={y:0,d:De(a[je])*i,h:De(a[Be])*i,m:De(a[Ue])*i,s:De(a[Ve])*i,ms:De(dn(1e3*a[qe]))*i}):(a=In.exec(e))?(i="-"===a[1]?-1:1,s={y:An(a[2],i),M:An(a[3],i),w:An(a[4],i),d:An(a[5],i),h:An(a[6],i),m:An(a[7],i),s:An(a[8],i)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(r=Dn(Yi(s.from),Yi(s.to)),(s={}).ms=r.milliseconds,s.M=r.months),n=new on(s),cn(e)&&o(e,"_locale")&&(n._locale=e._locale),cn(e)&&o(e,"_isValid")&&(n._isValid=e._isValid),n}function An(e,t){var i=e&&parseFloat(e.replace(",","."));return(isNaN(i)?0:i)*t}function Pn(e,t){var i={};return i.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(i.months,"M").isAfter(t)&&--i.months,i.milliseconds=+t-+e.clone().add(i.months,"M"),i}function Dn(e,t){var i;return e.isValid()&&t.isValid()?(t=gn(t,e),e.isBefore(t)?i=Pn(e,t):((i=Pn(t,e)).milliseconds=-i.milliseconds,i.months=-i.months),i):{milliseconds:0,months:0}}function Nn(e,t){return function(i,n){var r;return null===n||isNaN(+n)||(R(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),r=i,i=n,n=r),kn(this,Rn(i,n),e),this}}function kn(e,t,i,r){var s=t._milliseconds,a=dn(t._days),o=dn(t._months);e.isValid()&&(r=null==r||r,o&&pt(e,Xe(e,"Month")+o*i),a&&Qe(e,"Date",Xe(e,"Date")+a*i),s&&e._d.setTime(e._d.valueOf()+s*i),r&&n.updateOffset(e,a||o))}Rn.fn=on.prototype,Rn.invalid=an;var On=Nn(1,"add"),Fn=Nn(-1,"subtract");function Mn(e){return"string"==typeof e||e instanceof String}function Hn(e){return C(e)||h(e)||Mn(e)||l(e)||jn(e)||Ln(e)||null==e}function Ln(e){var t,i,n=a(e)&&!c(e),r=!1,s=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],d=s.length;for(t=0;t<d;t+=1)i=s[t],r=r||o(e,i);return n&&r}function jn(e){var t=s(e),i=!1;return t&&(i=0===e.filter((function(t){return!l(t)&&Mn(e)})).length),t&&i}function Bn(e){var t,i,n=a(e)&&!c(e),r=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<s.length;t+=1)i=s[t],r=r||o(e,i);return n&&r}function Un(e,t){var i=e.diff(t,"days",!0);return i<-6?"sameElse":i<-1?"lastWeek":i<0?"lastDay":i<1?"sameDay":i<2?"nextDay":i<7?"nextWeek":"sameElse"}function Vn(e,t){1===arguments.length&&(arguments[0]?Hn(arguments[0])?(e=arguments[0],t=void 0):Bn(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var i=e||Yi(),r=gn(i,this).startOf("day"),s=n.calendarFormat(this,r)||"sameElse",a=t&&(A(t[s])?t[s].call(this,i):t[s]);return this.format(a||this.localeData().calendar(s,this,Yi(i)))}function qn(){return new E(this)}function Gn(e,t){var i=C(e)?e:Yi(e);return!(!this.isValid()||!i.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()>i.valueOf():i.valueOf()<this.clone().startOf(t).valueOf())}function Kn(e,t){var i=C(e)?e:Yi(e);return!(!this.isValid()||!i.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()<i.valueOf():this.clone().endOf(t).valueOf()<i.valueOf())}function Wn(e,t,i,n){var r=C(e)?e:Yi(e),s=C(t)?t:Yi(t);return!!(this.isValid()&&r.isValid()&&s.isValid())&&("("===(n=n||"()")[0]?this.isAfter(r,i):!this.isBefore(r,i))&&(")"===n[1]?this.isBefore(s,i):!this.isAfter(s,i))}function zn(e,t){var i,n=C(e)?e:Yi(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()===n.valueOf():(i=n.valueOf(),this.clone().startOf(t).valueOf()<=i&&i<=this.clone().endOf(t).valueOf()))}function Yn(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function Jn(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function Zn(e,t,i){var n,r,s;if(!this.isValid())return NaN;if(!(n=gn(e,this)).isValid())return NaN;switch(r=6e4*(n.utcOffset()-this.utcOffset()),t=ne(t)){case"year":s=Xn(this,n)/12;break;case"month":s=Xn(this,n);break;case"quarter":s=Xn(this,n)/3;break;case"second":s=(this-n)/1e3;break;case"minute":s=(this-n)/6e4;break;case"hour":s=(this-n)/36e5;break;case"day":s=(this-n-r)/864e5;break;case"week":s=(this-n-r)/6048e5;break;default:s=this-n}return i?s:Pe(s)}function Xn(e,t){if(e.date()<t.date())return-Xn(t,e);var i=12*(t.year()-e.year())+(t.month()-e.month()),n=e.clone().add(i,"months");return-(i+(t-n<0?(t-n)/(n-e.clone().add(i-1,"months")):(t-n)/(e.clone().add(i+1,"months")-n)))||0}function Qn(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function er(e){if(!this.isValid())return null;var t=!0!==e,i=t?this.clone().utc():this;return i.year()<0||i.year()>9999?q(i,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):A(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",q(i,"Z")):q(i,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function tr(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t,i,n,r="moment",s="";return this.isLocal()||(r=0===this.utcOffset()?"moment.utc":"moment.parseZone",s="Z"),e="["+r+'("]',t=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i="-MM-DD[T]HH:mm:ss.SSS",n=s+'[")]',this.format(e+t+i+n)}function ir(e){e||(e=this.isUtc()?n.defaultFormatUtc:n.defaultFormat);var t=q(this,e);return this.localeData().postformat(t)}function nr(e,t){return this.isValid()&&(C(e)&&e.isValid()||Yi(e).isValid())?Rn({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function rr(e){return this.from(Yi(),e)}function sr(e,t){return this.isValid()&&(C(e)&&e.isValid()||Yi(e).isValid())?Rn({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function ar(e){return this.to(Yi(),e)}function or(e){var t;return void 0===e?this._locale._abbr:(null!=(t=yi(e))&&(this._locale=t),this)}n.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",n.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var cr=_("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(e){return void 0===e?this.localeData():this.locale(e)}));function dr(){return this._locale}var lr=1e3,hr=60*lr,ur=60*hr,pr=3506328*ur;function gr(e,t){return(e%t+t)%t}function fr(e,t,i){return e<100&&e>=0?new Date(e+400,t,i)-pr:new Date(e,t,i).valueOf()}function mr(e,t,i){return e<100&&e>=0?Date.UTC(e+400,t,i)-pr:Date.UTC(e,t,i)}function vr(e){var t,i;if(void 0===(e=ne(e))||"millisecond"===e||!this.isValid())return this;switch(i=this._isUTC?mr:fr,e){case"year":t=i(this.year(),0,1);break;case"quarter":t=i(this.year(),this.month()-this.month()%3,1);break;case"month":t=i(this.year(),this.month(),1);break;case"week":t=i(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=i(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=i(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=gr(t+(this._isUTC?0:this.utcOffset()*hr),ur);break;case"minute":t=this._d.valueOf(),t-=gr(t,hr);break;case"second":t=this._d.valueOf(),t-=gr(t,lr)}return this._d.setTime(t),n.updateOffset(this,!0),this}function yr(e){var t,i;if(void 0===(e=ne(e))||"millisecond"===e||!this.isValid())return this;switch(i=this._isUTC?mr:fr,e){case"year":t=i(this.year()+1,0,1)-1;break;case"quarter":t=i(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=i(this.year(),this.month()+1,1)-1;break;case"week":t=i(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=i(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=i(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=ur-gr(t+(this._isUTC?0:this.utcOffset()*hr),ur)-1;break;case"minute":t=this._d.valueOf(),t+=hr-gr(t,hr)-1;break;case"second":t=this._d.valueOf(),t+=lr-gr(t,lr)-1}return this._d.setTime(t),n.updateOffset(this,!0),this}function Sr(){return this._d.valueOf()-6e4*(this._offset||0)}function br(){return Math.floor(this.valueOf()/1e3)}function wr(){return new Date(this.valueOf())}function Er(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function Cr(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function $r(){return this.isValid()?this.toISOString():null}function Tr(){return v(this)}function _r(){return p({},m(this))}function xr(){return m(this).overflow}function Ir(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function Rr(e,t){var i,r,s,a=this._eras||yi("en")._eras;for(i=0,r=a.length;i<r;++i)switch("string"==typeof a[i].since&&(s=n(a[i].since).startOf("day"),a[i].since=s.valueOf()),typeof a[i].until){case"undefined":a[i].until=1/0;break;case"string":s=n(a[i].until).startOf("day").valueOf(),a[i].until=s.valueOf()}return a}function Ar(e,t,i){var n,r,s,a,o,c=this.eras();for(e=e.toUpperCase(),n=0,r=c.length;n<r;++n)if(s=c[n].name.toUpperCase(),a=c[n].abbr.toUpperCase(),o=c[n].narrow.toUpperCase(),i)switch(t){case"N":case"NN":case"NNN":if(a===e)return c[n];break;case"NNNN":if(s===e)return c[n];break;case"NNNNN":if(o===e)return c[n]}else if([s,a,o].indexOf(e)>=0)return c[n]}function Pr(e,t){var i=e.since<=e.until?1:-1;return void 0===t?n(e.since).year():n(e.since).year()+(t-e.offset)*i}function Dr(){var e,t,i,n=this.localeData().eras();for(e=0,t=n.length;e<t;++e){if(i=this.clone().startOf("day").valueOf(),n[e].since<=i&&i<=n[e].until)return n[e].name;if(n[e].until<=i&&i<=n[e].since)return n[e].name}return""}function Nr(){var e,t,i,n=this.localeData().eras();for(e=0,t=n.length;e<t;++e){if(i=this.clone().startOf("day").valueOf(),n[e].since<=i&&i<=n[e].until)return n[e].narrow;if(n[e].until<=i&&i<=n[e].since)return n[e].narrow}return""}function kr(){var e,t,i,n=this.localeData().eras();for(e=0,t=n.length;e<t;++e){if(i=this.clone().startOf("day").valueOf(),n[e].since<=i&&i<=n[e].until)return n[e].abbr;if(n[e].until<=i&&i<=n[e].since)return n[e].abbr}return""}function Or(){var e,t,i,r,s=this.localeData().eras();for(e=0,t=s.length;e<t;++e)if(i=s[e].since<=s[e].until?1:-1,r=this.clone().startOf("day").valueOf(),s[e].since<=r&&r<=s[e].until||s[e].until<=r&&r<=s[e].since)return(this.year()-n(s[e].since).year())*i+s[e].offset;return this.year()}function Fr(e){return o(this,"_erasNameRegex")||Vr.call(this),e?this._erasNameRegex:this._erasRegex}function Mr(e){return o(this,"_erasAbbrRegex")||Vr.call(this),e?this._erasAbbrRegex:this._erasRegex}function Hr(e){return o(this,"_erasNarrowRegex")||Vr.call(this),e?this._erasNarrowRegex:this._erasRegex}function Lr(e,t){return t.erasAbbrRegex(e)}function jr(e,t){return t.erasNameRegex(e)}function Br(e,t){return t.erasNarrowRegex(e)}function Ur(e,t){return t._eraYearOrdinalRegex||Se}function Vr(){var e,t,i,n,r,s=[],a=[],o=[],c=[],d=this.eras();for(e=0,t=d.length;e<t;++e)i=Ae(d[e].name),n=Ae(d[e].abbr),r=Ae(d[e].narrow),a.push(i),s.push(n),o.push(r),c.push(i),c.push(n),c.push(r);this._erasRegex=new RegExp("^("+c.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+a.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+o.join("|")+")","i")}function qr(e,t){B(0,[e,e.length],0,t)}function Gr(e){return Zr.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function Kr(e){return Zr.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function Wr(){return $t(this.year(),1,4)}function zr(){return $t(this.isoWeekYear(),1,4)}function Yr(){var e=this.localeData()._week;return $t(this.year(),e.dow,e.doy)}function Jr(){var e=this.localeData()._week;return $t(this.weekYear(),e.dow,e.doy)}function Zr(e,t,i,n,r){var s;return null==e?Ct(this,n,r).year:(t>(s=$t(e,n,r))&&(t=s),Xr.call(this,e,t,i,n,r))}function Xr(e,t,i,n,r){var s=Et(e,t,i,n,r),a=bt(s.year,0,s.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}function Qr(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)}B("N",0,0,"eraAbbr"),B("NN",0,0,"eraAbbr"),B("NNN",0,0,"eraAbbr"),B("NNNN",0,0,"eraName"),B("NNNNN",0,0,"eraNarrow"),B("y",["y",1],"yo","eraYear"),B("y",["yy",2],0,"eraYear"),B("y",["yyy",3],0,"eraYear"),B("y",["yyyy",4],0,"eraYear"),xe("N",Lr),xe("NN",Lr),xe("NNN",Lr),xe("NNNN",jr),xe("NNNNN",Br),ke(["N","NN","NNN","NNNN","NNNNN"],(function(e,t,i,n){var r=i._locale.erasParse(e,n,i._strict);r?m(i).era=r:m(i).invalidEra=e})),xe("y",Se),xe("yy",Se),xe("yyy",Se),xe("yyyy",Se),xe("yo",Ur),ke(["y","yy","yyy","yyyy"],He),ke(["yo"],(function(e,t,i,n){var r;i._locale._eraYearOrdinalRegex&&(r=e.match(i._locale._eraYearOrdinalRegex)),i._locale.eraYearOrdinalParse?t[He]=i._locale.eraYearOrdinalParse(e,r):t[He]=parseInt(e,10)})),B(0,["gg",2],0,(function(){return this.weekYear()%100})),B(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),qr("gggg","weekYear"),qr("ggggg","weekYear"),qr("GGGG","isoWeekYear"),qr("GGGGG","isoWeekYear"),xe("G",be),xe("g",be),xe("GG",pe,de),xe("gg",pe,de),xe("GGGG",ve,he),xe("gggg",ve,he),xe("GGGGG",ye,ue),xe("ggggg",ye,ue),Oe(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,i,n){t[n.substr(0,2)]=De(e)})),Oe(["gg","GG"],(function(e,t,i,r){t[r]=n.parseTwoDigitYear(e)})),B("Q",0,"Qo","quarter"),xe("Q",ce),ke("Q",(function(e,t){t[Le]=3*(De(e)-1)})),B("D",["DD",2],"Do","date"),xe("D",pe,Te),xe("DD",pe,de),xe("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient})),ke(["D","DD"],je),ke("Do",(function(e,t){t[je]=De(e.match(pe)[0])}));var es=Ze("Date",!0);function ts(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")}B("DDD",["DDDD",3],"DDDo","dayOfYear"),xe("DDD",me),xe("DDDD",le),ke(["DDD","DDDD"],(function(e,t,i){i._dayOfYear=De(e)})),B("m",["mm",2],0,"minute"),xe("m",pe,_e),xe("mm",pe,de),ke(["m","mm"],Ue);var is=Ze("Minutes",!1);B("s",["ss",2],0,"second"),xe("s",pe,_e),xe("ss",pe,de),ke(["s","ss"],Ve);var ns,rs,ss=Ze("Seconds",!1);for(B("S",0,0,(function(){return~~(this.millisecond()/100)})),B(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),B(0,["SSS",3],0,"millisecond"),B(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),B(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),B(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),B(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),B(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),B(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),xe("S",me,ce),xe("SS",me,de),xe("SSS",me,le),ns="SSSS";ns.length<=9;ns+="S")xe(ns,Se);function as(e,t){t[qe]=De(1e3*("0."+e))}for(ns="S";ns.length<=9;ns+="S")ke(ns,as);function os(){return this._isUTC?"UTC":""}function cs(){return this._isUTC?"Coordinated Universal Time":""}rs=Ze("Milliseconds",!1),B("z",0,0,"zoneAbbr"),B("zz",0,0,"zoneName");var ds=E.prototype;function ls(e){return Yi(1e3*e)}function hs(){return Yi.apply(null,arguments).parseZone()}function us(e){return e}ds.add=On,ds.calendar=Vn,ds.clone=qn,ds.diff=Zn,ds.endOf=yr,ds.format=ir,ds.from=nr,ds.fromNow=rr,ds.to=sr,ds.toNow=ar,ds.get=et,ds.invalidAt=xr,ds.isAfter=Gn,ds.isBefore=Kn,ds.isBetween=Wn,ds.isSame=zn,ds.isSameOrAfter=Yn,ds.isSameOrBefore=Jn,ds.isValid=Tr,ds.lang=cr,ds.locale=or,ds.localeData=dr,ds.max=Zi,ds.min=Ji,ds.parsingFlags=_r,ds.set=tt,ds.startOf=vr,ds.subtract=Fn,ds.toArray=Er,ds.toObject=Cr,ds.toDate=wr,ds.toISOString=er,ds.inspect=tr,"undefined"!=typeof Symbol&&null!=Symbol.for&&(ds[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),ds.toJSON=$r,ds.toString=Qn,ds.unix=br,ds.valueOf=Sr,ds.creationData=Ir,ds.eraName=Dr,ds.eraNarrow=Nr,ds.eraAbbr=kr,ds.eraYear=Or,ds.year=Ye,ds.isLeapYear=Je,ds.weekYear=Gr,ds.isoWeekYear=Kr,ds.quarter=ds.quarters=Qr,ds.month=gt,ds.daysInMonth=ft,ds.week=ds.weeks=Rt,ds.isoWeek=ds.isoWeeks=At,ds.weeksInYear=Yr,ds.weeksInWeekYear=Jr,ds.isoWeeksInYear=Wr,ds.isoWeeksInISOWeekYear=zr,ds.date=es,ds.day=ds.days=Gt,ds.weekday=Kt,ds.isoWeekday=Wt,ds.dayOfYear=ts,ds.hour=ds.hours=ri,ds.minute=ds.minutes=is,ds.second=ds.seconds=ss,ds.millisecond=ds.milliseconds=rs,ds.utcOffset=mn,ds.utc=yn,ds.local=Sn,ds.parseZone=bn,ds.hasAlignedHourOffset=wn,ds.isDST=En,ds.isLocal=$n,ds.isUtcOffset=Tn,ds.isUtc=_n,ds.isUTC=_n,ds.zoneAbbr=os,ds.zoneName=cs,ds.dates=_("dates accessor is deprecated. Use date instead.",es),ds.months=_("months accessor is deprecated. Use month instead",gt),ds.years=_("years accessor is deprecated. Use year instead",Ye),ds.zone=_("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",vn),ds.isDSTShifted=_("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",Cn);var ps=N.prototype;function gs(e,t,i,n){var r=yi(),s=g().set(n,t);return r[i](s,e)}function fs(e,t,i){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return gs(e,t,i,"month");var n,r=[];for(n=0;n<12;n++)r[n]=gs(e,n,i,"month");return r}function ms(e,t,i,n){"boolean"==typeof e?(l(t)&&(i=t,t=void 0),t=t||""):(i=t=e,e=!1,l(t)&&(i=t,t=void 0),t=t||"");var r,s=yi(),a=e?s._week.dow:0,o=[];if(null!=i)return gs(t,(i+a)%7,n,"day");for(r=0;r<7;r++)o[r]=gs(t,(r+a)%7,n,"day");return o}function vs(e,t){return fs(e,t,"months")}function ys(e,t){return fs(e,t,"monthsShort")}function Ss(e,t,i){return ms(e,t,i,"weekdays")}function bs(e,t,i){return ms(e,t,i,"weekdaysShort")}function ws(e,t,i){return ms(e,t,i,"weekdaysMin")}ps.calendar=O,ps.longDateFormat=W,ps.invalidDate=Y,ps.ordinal=X,ps.preparse=us,ps.postformat=us,ps.relativeTime=ee,ps.pastFuture=te,ps.set=P,ps.eras=Rr,ps.erasParse=Ar,ps.erasConvertYear=Pr,ps.erasAbbrRegex=Mr,ps.erasNameRegex=Fr,ps.erasNarrowRegex=Hr,ps.months=dt,ps.monthsShort=lt,ps.monthsParse=ut,ps.monthsRegex=vt,ps.monthsShortRegex=mt,ps.week=Tt,ps.firstDayOfYear=It,ps.firstDayOfWeek=xt,ps.weekdays=jt,ps.weekdaysMin=Ut,ps.weekdaysShort=Bt,ps.weekdaysParse=qt,ps.weekdaysRegex=zt,ps.weekdaysShortRegex=Yt,ps.weekdaysMinRegex=Jt,ps.isPM=ii,ps.meridiem=si,fi("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===De(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),n.lang=_("moment.lang is deprecated. Use moment.locale instead.",fi),n.langData=_("moment.langData is deprecated. Use moment.localeData instead.",yi);var Es=Math.abs;function Cs(){var e=this._data;return this._milliseconds=Es(this._milliseconds),this._days=Es(this._days),this._months=Es(this._months),e.milliseconds=Es(e.milliseconds),e.seconds=Es(e.seconds),e.minutes=Es(e.minutes),e.hours=Es(e.hours),e.months=Es(e.months),e.years=Es(e.years),this}function $s(e,t,i,n){var r=Rn(t,i);return e._milliseconds+=n*r._milliseconds,e._days+=n*r._days,e._months+=n*r._months,e._bubble()}function Ts(e,t){return $s(this,e,t,1)}function _s(e,t){return $s(this,e,t,-1)}function xs(e){return e<0?Math.floor(e):Math.ceil(e)}function Is(){var e,t,i,n,r,s=this._milliseconds,a=this._days,o=this._months,c=this._data;return s>=0&&a>=0&&o>=0||s<=0&&a<=0&&o<=0||(s+=864e5*xs(As(o)+a),a=0,o=0),c.milliseconds=s%1e3,e=Pe(s/1e3),c.seconds=e%60,t=Pe(e/60),c.minutes=t%60,i=Pe(t/60),c.hours=i%24,a+=Pe(i/24),o+=r=Pe(Rs(a)),a-=xs(As(r)),n=Pe(o/12),o%=12,c.days=a,c.months=o,c.years=n,this}function Rs(e){return 4800*e/146097}function As(e){return 146097*e/4800}function Ps(e){if(!this.isValid())return NaN;var t,i,n=this._milliseconds;if("month"===(e=ne(e))||"quarter"===e||"year"===e)switch(t=this._days+n/864e5,i=this._months+Rs(t),e){case"month":return i;case"quarter":return i/3;case"year":return i/12}else switch(t=this._days+Math.round(As(this._months)),e){case"week":return t/7+n/6048e5;case"day":return t+n/864e5;case"hour":return 24*t+n/36e5;case"minute":return 1440*t+n/6e4;case"second":return 86400*t+n/1e3;case"millisecond":return Math.floor(864e5*t)+n;default:throw new Error("Unknown unit "+e)}}function Ds(e){return function(){return this.as(e)}}var Ns=Ds("ms"),ks=Ds("s"),Os=Ds("m"),Fs=Ds("h"),Ms=Ds("d"),Hs=Ds("w"),Ls=Ds("M"),js=Ds("Q"),Bs=Ds("y"),Us=Ns;function Vs(){return Rn(this)}function qs(e){return e=ne(e),this.isValid()?this[e+"s"]():NaN}function Gs(e){return function(){return this.isValid()?this._data[e]:NaN}}var Ks=Gs("milliseconds"),Ws=Gs("seconds"),zs=Gs("minutes"),Ys=Gs("hours"),Js=Gs("days"),Zs=Gs("months"),Xs=Gs("years");function Qs(){return Pe(this.days()/7)}var ea=Math.round,ta={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function ia(e,t,i,n,r){return r.relativeTime(t||1,!!i,e,n)}function na(e,t,i,n){var r=Rn(e).abs(),s=ea(r.as("s")),a=ea(r.as("m")),o=ea(r.as("h")),c=ea(r.as("d")),d=ea(r.as("M")),l=ea(r.as("w")),h=ea(r.as("y")),u=s<=i.ss&&["s",s]||s<i.s&&["ss",s]||a<=1&&["m"]||a<i.m&&["mm",a]||o<=1&&["h"]||o<i.h&&["hh",o]||c<=1&&["d"]||c<i.d&&["dd",c];return null!=i.w&&(u=u||l<=1&&["w"]||l<i.w&&["ww",l]),(u=u||d<=1&&["M"]||d<i.M&&["MM",d]||h<=1&&["y"]||["yy",h])[2]=t,u[3]=+e>0,u[4]=n,ia.apply(null,u)}function ra(e){return void 0===e?ea:"function"==typeof e&&(ea=e,!0)}function sa(e,t){return void 0!==ta[e]&&(void 0===t?ta[e]:(ta[e]=t,"s"===e&&(ta.ss=t-1),!0))}function aa(e,t){if(!this.isValid())return this.localeData().invalidDate();var i,n,r=!1,s=ta;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(r=e),"object"==typeof t&&(s=Object.assign({},ta,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),n=na(this,!r,s,i=this.localeData()),r&&(n=i.pastFuture(+this,n)),i.postformat(n)}var oa=Math.abs;function ca(e){return(e>0)-(e<0)||+e}function da(){if(!this.isValid())return this.localeData().invalidDate();var e,t,i,n,r,s,a,o,c=oa(this._milliseconds)/1e3,d=oa(this._days),l=oa(this._months),h=this.asSeconds();return h?(e=Pe(c/60),t=Pe(e/60),c%=60,e%=60,i=Pe(l/12),l%=12,n=c?c.toFixed(3).replace(/\.?0+$/,""):"",r=h<0?"-":"",s=ca(this._months)!==ca(h)?"-":"",a=ca(this._days)!==ca(h)?"-":"",o=ca(this._milliseconds)!==ca(h)?"-":"",r+"P"+(i?s+i+"Y":"")+(l?s+l+"M":"")+(d?a+d+"D":"")+(t||e||c?"T":"")+(t?o+t+"H":"")+(e?o+e+"M":"")+(c?o+n+"S":"")):"P0D"}var la=on.prototype;return la.isValid=sn,la.abs=Cs,la.add=Ts,la.subtract=_s,la.as=Ps,la.asMilliseconds=Ns,la.asSeconds=ks,la.asMinutes=Os,la.asHours=Fs,la.asDays=Ms,la.asWeeks=Hs,la.asMonths=Ls,la.asQuarters=js,la.asYears=Bs,la.valueOf=Us,la._bubble=Is,la.clone=Vs,la.get=qs,la.milliseconds=Ks,la.seconds=Ws,la.minutes=zs,la.hours=Ys,la.days=Js,la.weeks=Qs,la.months=Zs,la.years=Xs,la.humanize=aa,la.toISOString=da,la.toString=da,la.toJSON=da,la.locale=or,la.localeData=dr,la.toIsoString=_("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",da),la.lang=cr,B("X",0,0,"unix"),B("x",0,0,"valueOf"),xe("x",be),xe("X",Ce),ke("X",(function(e,t,i){i._d=new Date(1e3*parseFloat(e))})),ke("x",(function(e,t,i){i._d=new Date(De(e))})),
|
|
2
2
|
//! moment.js
|
|
3
|
-
n.version="2.30.1",r(Yi),n.fn=ds,n.min=Qi,n.max=en,n.now=tn,n.utc=g,n.unix=ls,n.months=vs,n.isDate=h,n.locale=fi,n.invalid=y,n.duration=Rn,n.isMoment=C,n.weekdays=Ss,n.parseZone=hs,n.localeData=yi,n.isDuration=cn,n.monthsShort=ys,n.weekdaysMin=ws,n.defineLocale=mi,n.updateLocale=vi,n.locales=Si,n.weekdaysShort=bs,n.normalizeUnits=ne,n.relativeTimeRounding=ra,n.relativeTimeThreshold=sa,n.calendarFormat=Un,n.prototype=ds,n.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},n}()}(T);var _=C(T.exports);const x=()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product,I=e=>{if("string"!=typeof e)throw new Error("Input is not a string");return e.charAt(0).toLowerCase()+e.substring(1).replace(/([A-Z])/g,"_$1").toLowerCase()},R=e=>e?e.split("-").map(((e,t)=>0===t?e:"xxxxxx")).join("-"):e,A="trace",P="debug",D="info",N="log",k="warn",O="error",F=[D,N,k,O],M=[A,P,D,N,k,O],H="logger-category=",L=(e,t=!1)=>(e.TRACE=A,e.DEBUG=P,e.INFO=D,e.LOG=N,e.WARN=k,e.ERROR=O,t&&(e.trace=(...t)=>e.apply(null,[A,...t]),e.debug=(...t)=>e.apply(null,[P,...t]),e.info=(...t)=>e.apply(null,[D,...t]),e.log=(...t)=>e.apply(null,[N,...t]),e.warn=(...t)=>e.apply(null,[k,...t]),e.error=(...t)=>e.apply(null,[O,...t])),e),j=e=>{try{return JSON.stringify(e)}catch(e){}return'{"message": "Not parsable JSON"}'};var B=new class{TRACE;INFO;LOG;WARN;ERROR;oldConsoleMethods;enabled;remoteClientConfiguration;buffer;bufferTimeout;_boundProcessBuffer;_boundParseLoggerBody;_callback;constructor(){L(this),this.oldConsoleMethods=null,this.enabled=!1,this.remoteClientConfiguration=null,this.buffer=[],this.bufferTimeout=null,this._boundProcessBuffer=this._processBuffer.bind(this),this._boundParseLoggerBody=this._parseLoggerBody.bind(this),this._callback=null}init(){this._catchConsole()}setCallback(e){this._callback=e}configureRemoteClient(e={tag:"wazo-sdk",host:null,port:null,level:null,extra:{}}){this.remoteClientConfiguration=e}enable(){this.oldConsoleMethods||this.init(),this.enabled=!0}disable(){this.enabled=!1}loggerFor(e){return L(((t,...i)=>{this.log.apply(this,[t,this._makeCategory(e),...i])}),!0)}removeSlashes(e){return e.replace(/"/g,"'").replace(/\\/g,"")}obfuscateHeaderToken(e){const t={...e};return"X-Auth-Token"in t&&(t["X-Auth-Token"]=R(t["X-Auth-Token"])),t}log(e,...t){if(!this.enabled)return;let i=null,n=!1,r={};0===t[0].indexOf(H)&&(i=t[0].split("=")[1],t.splice(0,1));const s=t[t.length-1];s&&("object"==typeof s&&Object.keys(s).length||s instanceof Error)&&(r=s instanceof Error?{errorMessage:s.message,errorStack:s.stack,errorType:s.constructor.name,skipSendToRemote:s.skipSendToRemote}:s,t.splice(1,1)),r.skipSendToRemote&&(n=!0,delete r.skipSendToRemote);const a=_().format("YYYY-MM-DD HH:mm:ss.SSS"),o=t.join(", ");let c=o;if(Object.keys(r).length){c=`${c} (${j(r)})`}i&&(c=`[${i}] ${c}`);const d=x()&&"error"===e?k:e,l=this.oldConsoleMethods?.[d]||this.oldConsoleMethods?.log;l.apply(l,[a,c]),this._callback&&this._callback(e,c),n||this._sendToRemoteLogger(e,{date:a,message:o,category:i,...r})}logRequest(e,t,i,n){if(!this.enabled)return;const{status:r}=i,s=+new Date-+n;let a=A;r>=400&&r<500?a=k:r>=500&&(a=O),this.log(a,this._makeCategory("http"),e,{status:r,body:this.removeSlashes(JSON.stringify(t.body)),method:t.method,headers:this.obfuscateHeaderToken(t.headers),duration:s})}getLogs(){return console.warn("IssueReporter's logs aren't stored anymore. Please use fluentd to store them"),[]}getParsedLogs(){return console.warn("IssueReporter's logs aren't stored anymore. Please use fluentd to store them"),[]}getReport(){return this.getParsedLogs().join("\r\n")}_catchConsole(){this.oldConsoleMethods={},F.forEach((e=>{this.oldConsoleMethods&&(this.oldConsoleMethods[e]=console[e]);("undefined"!=typeof window?window:global).console[e]=(...t)=>{try{this.log(e,t.join(" ")),this.oldConsoleMethods&&this.oldConsoleMethods[e].apply(null,t)}catch(e){}}}))}_sendToRemoteLogger(e,t={}){if(!this.remoteClientConfiguration)return;const{level:i,bufferSize:n}=this.remoteClientConfiguration;if(i&&!this._isLevelAbove(i,e)){if(t.level=e,n>0)return this._addToBuffer(t);this._sendDebugToGrafana(t)}}_parseLoggerBody(e){const{level:t}=e,{maxMessageSize:i,extra:n}=this.remoteClientConfiguration||{};return delete e.level,i&&"string"==typeof e.message&&e.message.length>i&&(e.message=`${e.message.substr(0,i)}...`),j({level:t,...e,...n})}_addToBuffer(e){this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null),this.buffer.push(e);const{bufferSize:t,bufferTimeout:i}=this.remoteClientConfiguration;if(this.buffer.length>t)return this._processBuffer();i>0&&(this.bufferTimeout=setTimeout(this._boundProcessBuffer,i))}_processBuffer(){this._sendDebugToGrafana(this.buffer),this.buffer=[],this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null)}_computeRetryDelay(e,t=1e3,i=5e4){const n=Math.min(t*1.5**e,i);return Math.max(t,Math.random()*n)}_sendDebugToGrafana(e,t=0){if(!this.remoteClientConfiguration||t>=10)return;const{tag:i,host:n,port:r}=this.remoteClientConfiguration,s=443==+r,a=`http${s?"s":""}://${n}${s?"":`:${r}`}/${i}`,o=Array.isArray(e)?`[${e.map(this._boundParseLoggerBody).join(",")}]`:this._parseLoggerBody(e);fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:o}).catch((i=>{i.skipSendToRemote=!0,this.log("error",this._makeCategory("grafana"),"Sending log to grafana, error",i);const n=this._computeRetryDelay(t,1e3,5e4);setTimeout((()=>{Array.isArray(e)?e=e.map((e=>this._writeRetryCount(e,t+1))):e&&"object"==typeof e&&(e=this._writeRetryCount(e,t+1)),this._sendDebugToGrafana(e,t+1)}),n)}))}_writeRetryCount(e,t){return e&&"object"==typeof e&&(e._retry=t),e}_isLevelAbove(e,t){const i=M.indexOf(e),n=M.indexOf(t);return-1!==i&&-1!==n&&i>n}_makeCategory(e){return`${H}${e}`}};const U=["head","get","post","put","delete","options"],V=B?B.loggerFor("api"):console,q=3e5;class G{server;agent;clientId;token;tenant;fetchOptions;refreshTokenCallback;refreshTokenPromise;shouldLogErrors;requestTimeout;head;get;post;put;delete;options;static successResponseParser(e){return 204===e.status||201===e.status||200===e.status}static defaultParser(e){return e.json().then((t=>({...t,_headers:e.headers})))}static getQueryString(e){return Object.keys(e).filter((t=>e[t])).map((t=>`${t}=${encodeURIComponent(e[t])}`)).join("&")}static base64Encode(e){return"undefined"!=typeof btoa?btoa(e):S(e)}constructor({server:e,refreshTokenCallback:t,clientId:i,agent:n=null,token:r=null,fetchOptions:s,requestTimeout:a=3e5}){this.server=e,this.agent=n,this.clientId=i,this.refreshTokenCallback=t,this.refreshTokenPromise=null,this.fetchOptions=s||{},this.requestTimeout=a||q,r&&(this.token=r),this.shouldLogErrors=!0,U.forEach((e=>{this[e]=function(...t){return t.splice(1,0,e),this.call.call(this,...t)}}))}setRequestTimeout(e){this.requestTimeout=e}setTenant(e){this.tenant=e}setToken(e){this.token=e}setFetchOptions(e){this.fetchOptions=e}disableErrorLogging(){this.shouldLogErrors=!1}enableErrorLogging(){this.shouldLogErrors=!0}async call(e,t="get",i=null,n=null,r=G.defaultParser,s=!0){const a=this.computeUrl(t,e,i),o=this.getHeaders(n);let c="get"===t?null:i;c&&"application/json"===o["Content-Type"]&&(c=JSON.stringify(c));const d="head"===t,l=("delete"===t||d)&&r===G.defaultParser?G.successResponseParser:r,h={...this.fetchOptions||{}},u=new AbortController,p=h.headers||{};delete h.headers;const g={method:t,body:c,signal:u?u.signal:null,headers:{...this.getHeaders(n),...p},agent:this.agent,...h};this.refreshTokenPromise&&(V.info("A token is already refreshing, waiting ...",{url:a}),await this.refreshTokenPromise);const f=new Date,m=fetch(a,g).then((o=>{const c=-1!==(o.headers.get("content-type")||"").indexOf("application/json");if(B.logRequest(a,g,o,f),d&&o.status>=500||!d&&o.status>=400){const a=c?o.json():o.text(),d=o.status>=500?w:b;return a.then((async a=>{if(s&&this._checkTokenExpired(o,a))return V.warn("token expired",{error:a.reason}),this._replayWithNewToken(a,e,t,i,n,r);const c="string"==typeof a?d.fromText(a,o.status):d.fromResponse(a,o.status);throw this.shouldLogErrors&&V.error("API error",c),c}))}return l(o,c)})).catch((e=>{throw this.shouldLogErrors&&V.error("Fetch failed",{url:a,options:g,message:e.message,stack:e.stack}),e})),v=new Promise(((e,t)=>{setTimeout((()=>{u.abort(),t(new Error(`Request timed out after ${this.requestTimeout} ms`))}),this.requestTimeout)}));return Promise.race([m,v])}_checkTokenExpired(e,t){const i=404===e.status&&this._isTokenNotFound(t);return 401===e.status||i}_isTokenNotFound(e){return e&&e.reason&&"No such token"===e.reason[0]}_replayWithNewToken(e,t,i,n=null,r=null,s=void 0){const a=this._isTokenNotFound(e);let o=t;return V.info("refreshing token",{inProgress:!!this.refreshTokenPromise}),this.refreshTokenPromise=this.refreshTokenPromise||this.refreshTokenCallback(),this.refreshTokenPromise?.then((()=>{if(this.refreshTokenPromise=null,V.info("token refreshed",{isTokenNotFound:a}),a){const e=t.split("/");e.pop(),e.push(this.token),o=e.join("/")}return this.call(o,i,n,r,s,!1)})).catch((e=>{throw this.refreshTokenPromise=null,e}))}getHeaders(e){return e instanceof Object?e:{"X-Auth-Token":this.token,...this.tenant?{"Wazo-Tenant":this.tenant}:null,Accept:"application/json","Content-Type":"application/json"}}computeUrl(e,t,i){const n=`${this.baseUrl}/${t}`;return"get"===e&&i&&Object.keys(i).length?`${n}?${G.getQueryString(i)}`:n}get baseUrl(){return`https://${this.server}/api`}}var K,W,z,Y,J,Z,X,Q,ee,te={userAgent:!1},ie={},ne=ne||function(e,t){var i={},n=i.lib={},r=n.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var i=new e;return t&&i.mixIn(t),i.hasOwnProperty("init")||(i.init=function(){i.$super.init.apply(this,arguments)}),i.init.prototype=i,i.$super=this,i},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,i=e.words,n=this.sigBytes,r=e.sigBytes;if(this.clamp(),n%4)for(var s=0;s<r;s++){var a=i[s>>>2]>>>24-s%4*8&255;t[n+s>>>2]|=a<<24-(n+s)%4*8}else for(s=0;s<r;s+=4)t[n+s>>>2]=i[s>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var i=[],n=0;n<t;n+=4)i.push(4294967296*e.random()|0);return new s.init(i,t)}}),a=i.enc={},o=a.Hex={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push((s>>>4).toString(16)),n.push((15&s).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n+=2)i[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(i,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n++)i[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(i,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i=this._data,n=i.words,r=i.sigBytes,a=this.blockSize,o=r/(4*a),c=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,d=e.min(4*c,r);if(c){for(var l=0;l<c;l+=a)this._doProcessBlock(n,l);var h=n.splice(0,c);i.sigBytes-=d}return new s.init(h,d)},clone:function(){var e=r.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});n.Hasher=l.extend({cfg:r.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,i){return new e.init(i).finalize(t)}},_createHmacHelper:function(e){return function(t,i){return new h.HMAC.init(e,i).finalize(t)}}});var h=i.algo={};return i}(Math);W=(K=ne).lib,z=W.Base,Y=W.WordArray,(K=K.x64={}).Word=z.extend({init:function(e,t){this.high=e,this.low=t}}),K.WordArray=z.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:8*e.length},toX32:function(){for(var e=this.words,t=e.length,i=[],n=0;n<t;n++){var r=e[n];i.push(r.high),i.push(r.low)}return Y.create(i,this.sigBytes)},clone:function(){for(var e=z.clone.call(this),t=e.words=this.words.slice(0),i=t.length,n=0;n<i;n++)t[n]=t[n].clone();return e}}),ne.lib.Cipher||function(e){var t=(p=ne).lib,i=t.Base,n=t.WordArray,r=t.BufferedBlockAlgorithm,s=p.enc.Base64,a=p.algo.EvpKDF,o=t.Cipher=r.extend({cfg:i.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,i){this.cfg=this.cfg.extend(i),this._xformMode=e,this._key=t,this.reset()},reset:function(){r.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(e){return{encrypt:function(t,i,n){return("string"==typeof i?g:u).encrypt(e,t,i,n)},decrypt:function(t,i,n){return("string"==typeof i?g:u).decrypt(e,t,i,n)}}}});t.StreamCipher=o.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var c=p.mode={},d=function(e,t,i){var n=this._iv;n?this._iv=undefined:n=this._prevBlock;for(var r=0;r<i;r++)e[t+r]^=n[r]},l=(t.BlockCipherMode=i.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}})).extend();l.Encryptor=l.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize;d.call(this,e,t,n),i.encryptBlock(e,t),this._prevBlock=e.slice(t,t+n)}}),l.Decryptor=l.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize,r=e.slice(t,t+n);i.decryptBlock(e,t),d.call(this,e,t,n),this._prevBlock=r}}),c=c.CBC=l,l=(p.pad={}).Pkcs7={pad:function(e,t){for(var i,r=(i=(i=4*t)-e.sigBytes%i)<<24|i<<16|i<<8|i,s=[],a=0;a<i;a+=4)s.push(r);i=n.create(s,i),e.concat(i)},unpad:function(e){e.sigBytes-=255&e.words[e.sigBytes-1>>>2]}},t.BlockCipher=o.extend({cfg:o.cfg.extend({mode:c,padding:l}),reset:function(){o.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var i=t.createEncryptor;else i=t.createDecryptor,this._minBufferSize=1;this._mode=i.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=i.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),u=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(s)},parse:function(e){var t=(e=s.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var i=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:i})}},t.SerializableCipher=i.extend({cfg:i.extend({format:c}),encrypt:function(e,t,i,n){n=this.cfg.extend(n);var r=e.createEncryptor(i,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:i,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,i,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(i,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,i,r){return r||(r=n.random(8)),e=a.create({keySize:t+i}).compute(e,r),i=n.create(e.words.slice(t),4*i),e.sigBytes=4*t,h.create({key:e,iv:i,salt:r})}},g=t.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:p}),encrypt:function(e,t,i,n){return i=(n=this.cfg.extend(n)).kdf.execute(i,e.keySize,e.ivSize),n.iv=i.iv,(e=u.encrypt.call(this,e,t,i.key,n)).mixIn(i),e},decrypt:function(e,t,i,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),i=n.kdf.execute(i,e.keySize,e.ivSize,t.salt),n.iv=i.iv,u.decrypt.call(this,e,t,i.key,n)}})}(),function(){for(var e=ne,t=e.lib.BlockCipher,i=e.algo,n=[],r=[],s=[],a=[],o=[],c=[],d=[],l=[],h=[],u=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var f=0,m=0;for(g=0;256>g;g++){var v=(v=m^m<<1^m<<2^m<<3^m<<4)>>>8^255&v^99;n[f]=v,r[v]=f;var y=p[f],S=p[y],b=p[S],w=257*p[v]^16843008*v;s[f]=w<<24|w>>>8,a[f]=w<<16|w>>>16,o[f]=w<<8|w>>>24,c[f]=w,w=16843009*b^65537*S^257*y^16843008*f,d[v]=w<<24|w>>>8,l[v]=w<<16|w>>>16,h[v]=w<<8|w>>>24,u[v]=w,f?(f=y^p[p[p[b^y]]],m^=p[p[m]]):f=m=1}var E=[0,1,2,4,8,16,32,64,128,27,54];i=i.AES=t.extend({_doReset:function(){for(var e=(i=this._key).words,t=i.sigBytes/4,i=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],s=0;s<i;s++)if(s<t)r[s]=e[s];else{var a=r[s-1];s%t?6<t&&4==s%t&&(a=n[a>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a]):(a=n[(a=a<<8|a>>>24)>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a],a^=E[s/t|0]<<24),r[s]=r[s-t]^a}for(e=this._invKeySchedule=[],t=0;t<i;t++)s=i-t,a=t%4?r[s]:r[s-4],e[t]=4>t||4>=s?a:d[n[a>>>24]]^l[n[a>>>16&255]]^h[n[a>>>8&255]]^u[n[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,o,c,n)},decryptBlock:function(e,t){var i=e[t+1];e[t+1]=e[t+3],e[t+3]=i,this._doCryptBlock(e,t,this._invKeySchedule,d,l,h,u,r),i=e[t+1],e[t+1]=e[t+3],e[t+3]=i},_doCryptBlock:function(e,t,i,n,r,s,a,o){for(var c=this._nRounds,d=e[t]^i[0],l=e[t+1]^i[1],h=e[t+2]^i[2],u=e[t+3]^i[3],p=4,g=1;g<c;g++){var f=n[d>>>24]^r[l>>>16&255]^s[h>>>8&255]^a[255&u]^i[p++],m=n[l>>>24]^r[h>>>16&255]^s[u>>>8&255]^a[255&d]^i[p++],v=n[h>>>24]^r[u>>>16&255]^s[d>>>8&255]^a[255&l]^i[p++];u=n[u>>>24]^r[d>>>16&255]^s[l>>>8&255]^a[255&h]^i[p++],d=f,l=m,h=v}f=(o[d>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&u])^i[p++],m=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[u>>>8&255]<<8|o[255&d])^i[p++],v=(o[h>>>24]<<24|o[u>>>16&255]<<16|o[d>>>8&255]<<8|o[255&l])^i[p++],u=(o[u>>>24]<<24|o[d>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^i[p++],e[t]=f,e[t+1]=m,e[t+2]=v,e[t+3]=u},keySize:8});e.AES=t._createHelper(i)}(),function(){function e(e,t){var i=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=i,this._lBlock^=i<<e}function t(e,t){var i=(this._rBlock>>>e^this._lBlock)&t;this._lBlock^=i,this._rBlock^=i<<e}var i=ne,n=(r=i.lib).WordArray,r=r.BlockCipher,s=i.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],l=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],h=s.DES=r.extend({_doReset:function(){for(var e=this._key.words,t=[],i=0;56>i;i++){var n=a[i]-1;t[i]=e[n>>>5]>>>31-n%32&1}for(e=this._subKeys=[],n=0;16>n;n++){var r=e[n]=[],s=c[n];for(i=0;24>i;i++)r[i/6|0]|=t[(o[i]-1+s)%28]<<31-i%6,r[4+(i/6|0)]|=t[28+(o[i+24]-1+s)%28]<<31-i%6;for(r[0]=r[0]<<1|r[0]>>>31,i=1;7>i;i++)r[i]>>>=4*(i-1)+3;r[7]=r[7]<<5|r[7]>>>27}for(t=this._invSubKeys=[],i=0;16>i;i++)t[i]=e[15-i]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(i,n,r){this._lBlock=i[n],this._rBlock=i[n+1],e.call(this,4,252645135),e.call(this,16,65535),t.call(this,2,858993459),t.call(this,8,16711935),e.call(this,1,1431655765);for(var s=0;16>s;s++){for(var a=r[s],o=this._lBlock,c=this._rBlock,h=0,u=0;8>u;u++)h|=d[u][((c^a[u])&l[u])>>>0];this._lBlock=c,this._rBlock=o^h}r=this._lBlock,this._lBlock=this._rBlock,this._rBlock=r,e.call(this,1,1431655765),t.call(this,8,16711935),t.call(this,2,858993459),e.call(this,16,65535),e.call(this,4,252645135),i[n]=this._lBlock,i[n+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});i.DES=r._createHelper(h),s=s.TripleDES=r.extend({_doReset:function(){var e=this._key.words;this._des1=h.createEncryptor(n.create(e.slice(0,2))),this._des2=h.createEncryptor(n.create(e.slice(2,4))),this._des3=h.createEncryptor(n.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2}),i.TripleDES=r._createHelper(s)}(),function(){var e=ne,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,n=this._map;e.clamp(),e=[];for(var r=0;r<i;r+=3)for(var s=(t[r>>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a<i;a++)e.push(n.charAt(s>>>6*(3-a)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var i=e.length,n=this._map;(r=n.charAt(64))&&(-1!=(r=e.indexOf(r))&&(i=r));for(var r=[],s=0,a=0;a<i;a++)if(a%4){var o=n.indexOf(e.charAt(a-1))<<a%4*2,c=n.indexOf(e.charAt(a))>>>6-a%4*2;r[s>>>2]|=(o|c)<<24-s%4*8,s++}return t.create(r,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,i,n,r,s,a){return((e=e+(t&i|~t&n)+r+a)<<s|e>>>32-s)+t}function i(e,t,i,n,r,s,a){return((e=e+(t&n|i&~n)+r+a)<<s|e>>>32-s)+t}function n(e,t,i,n,r,s,a){return((e=e+(t^i^n)+r+a)<<s|e>>>32-s)+t}function r(e,t,i,n,r,s,a){return((e=e+(i^(t|~n))+r+a)<<s|e>>>32-s)+t}for(var s=ne,a=(c=s.lib).WordArray,o=c.Hasher,c=s.algo,d=[],l=0;64>l;l++)d[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,s){for(var a=0;16>a;a++){var o=e[c=s+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[s+0],l=(o=e[s+1],e[s+2]),h=e[s+3],u=e[s+4],p=e[s+5],g=e[s+6],f=e[s+7],m=e[s+8],v=e[s+9],y=e[s+10],S=e[s+11],b=e[s+12],w=e[s+13],E=e[s+14],C=e[s+15],$=t($=a[0],x=a[1],_=a[2],T=a[3],c,7,d[0]),T=t(T,$,x,_,o,12,d[1]),_=t(_,T,$,x,l,17,d[2]),x=t(x,_,T,$,h,22,d[3]);$=t($,x,_,T,u,7,d[4]),T=t(T,$,x,_,p,12,d[5]),_=t(_,T,$,x,g,17,d[6]),x=t(x,_,T,$,f,22,d[7]),$=t($,x,_,T,m,7,d[8]),T=t(T,$,x,_,v,12,d[9]),_=t(_,T,$,x,y,17,d[10]),x=t(x,_,T,$,S,22,d[11]),$=t($,x,_,T,b,7,d[12]),T=t(T,$,x,_,w,12,d[13]),_=t(_,T,$,x,E,17,d[14]),$=i($,x=t(x,_,T,$,C,22,d[15]),_,T,o,5,d[16]),T=i(T,$,x,_,g,9,d[17]),_=i(_,T,$,x,S,14,d[18]),x=i(x,_,T,$,c,20,d[19]),$=i($,x,_,T,p,5,d[20]),T=i(T,$,x,_,y,9,d[21]),_=i(_,T,$,x,C,14,d[22]),x=i(x,_,T,$,u,20,d[23]),$=i($,x,_,T,v,5,d[24]),T=i(T,$,x,_,E,9,d[25]),_=i(_,T,$,x,h,14,d[26]),x=i(x,_,T,$,m,20,d[27]),$=i($,x,_,T,w,5,d[28]),T=i(T,$,x,_,l,9,d[29]),_=i(_,T,$,x,f,14,d[30]),$=n($,x=i(x,_,T,$,b,20,d[31]),_,T,p,4,d[32]),T=n(T,$,x,_,m,11,d[33]),_=n(_,T,$,x,S,16,d[34]),x=n(x,_,T,$,E,23,d[35]),$=n($,x,_,T,o,4,d[36]),T=n(T,$,x,_,u,11,d[37]),_=n(_,T,$,x,f,16,d[38]),x=n(x,_,T,$,y,23,d[39]),$=n($,x,_,T,w,4,d[40]),T=n(T,$,x,_,c,11,d[41]),_=n(_,T,$,x,h,16,d[42]),x=n(x,_,T,$,g,23,d[43]),$=n($,x,_,T,v,4,d[44]),T=n(T,$,x,_,b,11,d[45]),_=n(_,T,$,x,C,16,d[46]),$=r($,x=n(x,_,T,$,l,23,d[47]),_,T,c,6,d[48]),T=r(T,$,x,_,f,10,d[49]),_=r(_,T,$,x,E,15,d[50]),x=r(x,_,T,$,p,21,d[51]),$=r($,x,_,T,b,6,d[52]),T=r(T,$,x,_,h,10,d[53]),_=r(_,T,$,x,y,15,d[54]),x=r(x,_,T,$,o,21,d[55]),$=r($,x,_,T,m,6,d[56]),T=r(T,$,x,_,C,10,d[57]),_=r(_,T,$,x,g,15,d[58]),x=r(x,_,T,$,w,21,d[59]),$=r($,x,_,T,u,6,d[60]),T=r(T,$,x,_,S,10,d[61]),_=r(_,T,$,x,l,15,d[62]),x=r(x,_,T,$,v,21,d[63]);a[0]=a[0]+$|0,a[1]=a[1]+x|0,a[2]=a[2]+_|0,a[3]=a[3]+T|0},_doFinalize:function(){var t=this._data,i=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;i[r>>>5]|=128<<24-r%32;var s=e.floor(n/4294967296);for(i[15+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),i[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(i.length+1),this._process(),i=(t=this._hash).words,n=0;4>n;n++)r=i[n],i[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),s.MD5=o._createHelper(c),s.HmacMD5=o._createHmacHelper(c)}(Math),Z=(ee=(J=ne).lib).WordArray,X=ee.Hasher,Q=[],ee=J.algo.SHA1=X.extend({_doReset:function(){this._hash=new Z.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],a=i[3],o=i[4],c=0;80>c;c++){if(16>c)Q[c]=0|e[t+c];else{var d=Q[c-3]^Q[c-8]^Q[c-14]^Q[c-16];Q[c]=d<<1|d>>>31}d=(n<<5|n>>>27)+o+Q[c],d=20>c?d+(1518500249+(r&s|~r&a)):40>c?d+(1859775393+(r^s^a)):60>c?d+((r&s|r&a|s&a)-1894007588):d+((r^s^a)-899497514),o=a,a=s,s=r<<30|r>>>2,r=n,n=d}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+a|0,i[4]=i[4]+o|0},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(i/4294967296),t[15+(n+64>>>9<<4)]=i,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=X.clone.call(this);return e._hash=this._hash.clone(),e}}),J.SHA1=X._createHelper(ee),J.HmacSHA1=X._createHmacHelper(ee),function(e){for(var t=ne,i=(r=t.lib).WordArray,n=r.Hasher,r=t.algo,s=[],a=[],o=function(e){return 4294967296*(e-(0|e))|0},c=2,d=0;64>d;){var l;e:{l=c;for(var h=e.sqrt(l),u=2;u<=h;u++)if(!(l%u)){l=!1;break e}l=!0}l&&(8>d&&(s[d]=o(e.pow(c,.5))),a[d]=o(e.pow(c,1/3)),d++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new i.init(s.slice(0))},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],o=i[3],c=i[4],d=i[5],l=i[6],h=i[7],u=0;64>u;u++){if(16>u)p[u]=0|e[t+u];else{var g=p[u-15],f=p[u-2];p[u]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[u-7]+((f<<15|f>>>17)^(f<<13|f>>>19)^f>>>10)+p[u-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&d^~c&l)+a[u]+p[u],f=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&s^r&s),h=l,l=d,d=c,c=o+g|0,o=s,s=r,r=n,n=g+f|0}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+o|0,i[4]=i[4]+c|0,i[5]=i[5]+d|0,i[6]=i[6]+l|0,i[7]=i[7]+h|0},_doFinalize:function(){var t=this._data,i=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return i[r>>>5]|=128<<24-r%32,i[14+(r+64>>>9<<4)]=e.floor(n/4294967296),i[15+(r+64>>>9<<4)]=n,t.sigBytes=4*i.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),function(){var e=ne,t=e.lib.WordArray,i=(n=e.algo).SHA256,n=n.SHA224=i.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=i._doFinalize.call(this);return e.sigBytes-=4,e}});e.SHA224=i._createHelper(n),e.HmacSHA224=i._createHmacHelper(n)}(),function(){function e(){return n.create.apply(n,arguments)}for(var t=ne,i=t.lib.Hasher,n=(s=t.x64).Word,r=s.WordArray,s=t.algo,a=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],o=[],c=0;80>c;c++)o[c]=e();s=s.SHA512=i.extend({_doReset:function(){this._hash=new r.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var i=(h=this._hash.words)[0],n=h[1],r=h[2],s=h[3],c=h[4],d=h[5],l=h[6],h=h[7],u=i.high,p=i.low,g=n.high,f=n.low,m=r.high,v=r.low,y=s.high,S=s.low,b=c.high,w=c.low,E=d.high,C=d.low,$=l.high,T=l.low,_=h.high,x=h.low,I=u,R=p,A=g,P=f,D=m,N=v,k=y,O=S,F=b,M=w,H=E,L=C,j=$,B=T,U=_,V=x,q=0;80>q;q++){var G=o[q];if(16>q)var K=G.high=0|e[t+2*q],W=G.low=0|e[t+2*q+1];else{K=((W=(K=o[q-15]).high)>>>1|(z=K.low)<<31)^(W>>>8|z<<24)^W>>>7;var z=(z>>>1|W<<31)^(z>>>8|W<<24)^(z>>>7|W<<25),Y=((W=(Y=o[q-2]).high)>>>19|(J=Y.low)<<13)^(W<<3|J>>>29)^W>>>6,J=(J>>>19|W<<13)^(J<<3|W>>>29)^(J>>>6|W<<26),Z=(W=o[q-7]).high,X=(Q=o[q-16]).high,Q=Q.low;K=(K=(K=K+Z+((W=z+W.low)>>>0<z>>>0?1:0))+Y+((W=W+J)>>>0<J>>>0?1:0))+X+((W=W+Q)>>>0<Q>>>0?1:0);G.high=K,G.low=W}Z=F&H^~F&j,Q=M&L^~M&B,G=I&A^I&D^A&D;var ee=R&P^R&N^P&N,te=(z=(I>>>28|R<<4)^(I<<30|R>>>2)^(I<<25|R>>>7),Y=(R>>>28|I<<4)^(R<<30|I>>>2)^(R<<25|I>>>7),(J=a[q]).high),ie=J.low;X=U+((F>>>14|M<<18)^(F>>>18|M<<14)^(F<<23|M>>>9))+((J=V+((M>>>14|F<<18)^(M>>>18|F<<14)^(M<<23|F>>>9)))>>>0<V>>>0?1:0),U=j,V=B,j=H,B=L,H=F,L=M,F=k+(X=(X=(X=X+Z+((J=J+Q)>>>0<Q>>>0?1:0))+te+((J=J+ie)>>>0<ie>>>0?1:0))+K+((J=J+W)>>>0<W>>>0?1:0))+((M=O+J|0)>>>0<O>>>0?1:0)|0,k=D,O=N,D=A,N=P,A=I,P=R,I=X+(G=z+G+((W=Y+ee)>>>0<Y>>>0?1:0))+((R=J+W|0)>>>0<J>>>0?1:0)|0}p=i.low=p+R,i.high=u+I+(p>>>0<R>>>0?1:0),f=n.low=f+P,n.high=g+A+(f>>>0<P>>>0?1:0),v=r.low=v+N,r.high=m+D+(v>>>0<N>>>0?1:0),S=s.low=S+O,s.high=y+k+(S>>>0<O>>>0?1:0),w=c.low=w+M,c.high=b+F+(w>>>0<M>>>0?1:0),C=d.low=C+L,d.high=E+H+(C>>>0<L>>>0?1:0),T=l.low=T+B,l.high=$+j+(T>>>0<B>>>0?1:0),x=h.low=x+V,h.high=_+U+(x>>>0<V>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(i/4294967296),t[31+(n+128>>>10<<5)]=i,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=i._createHelper(s),t.HmacSHA512=i._createHmacHelper(s)}(),function(){var e=ne,t=(r=e.x64).Word,i=r.WordArray,n=(r=e.algo).SHA512,r=r.SHA384=n.extend({_doReset:function(){this._hash=new i.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(r),e.HmacSHA384=n._createHmacHelper(r)}(),function(){var e=ne,t=(n=e.lib).WordArray,i=n.Hasher,n=e.algo,r=t.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),s=t.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),a=t.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),o=t.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),c=t.create([0,1518500249,1859775393,2400959708,2840853838]),d=t.create([1352829926,1548603684,1836072691,2053994217,0]);n=n.RIPEMD160=i.extend({_doReset:function(){this._hash=t.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=0;16>i;i++){var n=e[b=t+i];e[b]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var l,h,u,p,g,f,m,v,y,S,b=this._hash.words,w=(n=c.words,d.words),E=r.words,C=s.words,$=a.words,T=o.words;f=l=b[0],m=h=b[1],v=u=b[2],y=p=b[3],S=g=b[4];var _;for(i=0;80>i;i+=1)_=l+e[t+E[i]]|0,_=16>i?_+((h^u^p)+n[0]):32>i?_+((h&u|~h&p)+n[1]):48>i?_+(((h|~u)^p)+n[2]):64>i?_+((h&p|u&~p)+n[3]):_+((h^(u|~p))+n[4]),_=(_=(_|=0)<<$[i]|_>>>32-$[i])+g|0,l=g,g=p,p=u<<10|u>>>22,u=h,h=_,_=f+e[t+C[i]]|0,_=16>i?_+((m^(v|~y))+w[0]):32>i?_+((m&y|v&~y)+w[1]):48>i?_+(((m|~v)^y)+w[2]):64>i?_+((m&v|~m&y)+w[3]):_+((m^v^y)+w[4]),_=(_=(_|=0)<<T[i]|_>>>32-T[i])+S|0,f=S,S=y,y=v<<10|v>>>22,v=m,m=_;_=b[1]+u+y|0,b[1]=b[2]+p+S|0,b[2]=b[3]+g+f|0,b[3]=b[4]+l+m|0,b[4]=b[0]+h+v|0,b[0]=_},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;for(t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),e.sigBytes=4*(t.length+1),this._process(),t=(e=this._hash).words,i=0;5>i;i++)n=t[i],t[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8);return e},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});e.RIPEMD160=i._createHelper(n),e.HmacRIPEMD160=i._createHmacHelper(n)}(),function(){var e=ne,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,i){e=this._hasher=new e.init,"string"==typeof i&&(i=t.parse(i));var n=e.blockSize,r=4*n;i.sigBytes>r&&(i=e.finalize(i)),i.clamp();for(var s=this._oKey=i.clone(),a=this._iKey=i.clone(),o=s.words,c=a.words,d=0;d<n;d++)o[d]^=1549556828,c[d]^=909522486;s.sigBytes=a.sigBytes=r,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}(),function(){var e,t=ne,i=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).HMAC,s=e.PBKDF2=i.extend({cfg:i.extend({keySize:4,hasher:e.SHA1,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){var i=this.cfg,s=r.create(i.hasher,e),a=n.create(),o=n.create([1]),c=a.words,d=o.words,l=i.keySize;for(i=i.iterations;c.length<l;){var h=s.update(t).finalize(o);s.reset();for(var u=h.words,p=u.length,g=h,f=1;f<i;f++){g=s.finalize(g),s.reset();for(var m=g.words,v=0;v<p;v++)u[v]^=m[v]}a.concat(h),d[0]++}return a.sigBytes=4*l,a}});t.PBKDF2=function(e,t,i){return s.create(i).compute(e,t)}}();
|
|
3
|
+
n.version="2.30.1",r(Yi),n.fn=ds,n.min=Qi,n.max=en,n.now=tn,n.utc=g,n.unix=ls,n.months=vs,n.isDate=h,n.locale=fi,n.invalid=y,n.duration=Rn,n.isMoment=C,n.weekdays=Ss,n.parseZone=hs,n.localeData=yi,n.isDuration=cn,n.monthsShort=ys,n.weekdaysMin=ws,n.defineLocale=mi,n.updateLocale=vi,n.locales=Si,n.weekdaysShort=bs,n.normalizeUnits=ne,n.relativeTimeRounding=ra,n.relativeTimeThreshold=sa,n.calendarFormat=Un,n.prototype=ds,n.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},n}()}(T);var _=C(T.exports);const x=()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product,I=e=>{if("string"!=typeof e)throw new Error("Input is not a string");return e.charAt(0).toLowerCase()+e.substring(1).replace(/([A-Z])/g,"_$1").toLowerCase()},R=e=>e?e.split("-").map(((e,t)=>0===t?e:"xxxxxx")).join("-"):e,A="trace",P="debug",D="info",N="log",k="warn",O="error",F=[D,N,k,O],M=[A,P,D,N,k,O],H="logger-category=",L=(e,t=!1)=>(e.TRACE=A,e.DEBUG=P,e.INFO=D,e.LOG=N,e.WARN=k,e.ERROR=O,t&&(e.trace=(...t)=>e.apply(null,[A,...t]),e.debug=(...t)=>e.apply(null,[P,...t]),e.info=(...t)=>e.apply(null,[D,...t]),e.log=(...t)=>e.apply(null,[N,...t]),e.warn=(...t)=>e.apply(null,[k,...t]),e.error=(...t)=>e.apply(null,[O,...t])),e),j=e=>{try{return JSON.stringify(e)}catch(e){}return'{"message": "Not parsable JSON"}'};var B=new class{TRACE;INFO;LOG;WARN;ERROR;oldConsoleMethods;enabled;remoteClientConfiguration;buffer;bufferTimeout;_boundProcessBuffer;_boundParseLoggerBody;_callback;constructor(){L(this),this.oldConsoleMethods=null,this.enabled=!1,this.remoteClientConfiguration=null,this.buffer=[],this.bufferTimeout=null,this._boundProcessBuffer=this._processBuffer.bind(this),this._boundParseLoggerBody=this._parseLoggerBody.bind(this),this._callback=null}init(){this._catchConsole()}setCallback(e){this._callback=e}configureRemoteClient(e={tag:"wazo-sdk",host:null,port:null,level:null,extra:{}}){this.remoteClientConfiguration=e}enable(){this.oldConsoleMethods||this.init(),this.enabled=!0}disable(){this.enabled=!1}loggerFor(e){return L(((t,...i)=>{this.log.apply(this,[t,this._makeCategory(e),...i])}),!0)}removeSlashes(e){return e.replace(/"/g,"'").replace(/\\/g,"")}obfuscateHeaderToken(e){const t={...e};return"X-Auth-Token"in t&&(t["X-Auth-Token"]=R(t["X-Auth-Token"])),t}log(e,...t){if(!this.enabled)return;let i=null,n=!1,r={};0===t[0].indexOf(H)&&(i=t[0].split("=")[1],t.splice(0,1));const s=t[t.length-1];s&&("object"==typeof s&&Object.keys(s).length||s instanceof Error)&&(r=s instanceof Error?{errorMessage:s.message,errorStack:s.stack,errorType:s.constructor.name,skipSendToRemote:s.skipSendToRemote}:s,t.splice(1,1)),r.skipSendToRemote&&(n=!0,delete r.skipSendToRemote);const a=_().format("YYYY-MM-DD HH:mm:ss.SSS"),o=t.join(", ");let c=o;if(Object.keys(r).length){c=`${c} (${j(r)})`}i&&(c=`[${i}] ${c}`);const d=x()&&"error"===e?k:e,l=this.oldConsoleMethods?.[d]||this.oldConsoleMethods?.log;l.apply(l,[a,c]),this._callback&&this._callback(e,c),n||this._sendToRemoteLogger(e,{date:a,message:o,category:i,...r})}logRequest(e,t,i,n){if(!this.enabled)return;const{status:r}=i,s=+new Date-+n;let a=A;r>=400&&r<500?a=k:r>=500&&(a=O),this.log(a,this._makeCategory("http"),e,{status:r,body:this.removeSlashes(JSON.stringify(t.body)),method:t.method,headers:this.obfuscateHeaderToken(t.headers),duration:s})}getLogs(){return console.warn("IssueReporter's logs aren't stored anymore. Please use fluentd to store them"),[]}getParsedLogs(){return console.warn("IssueReporter's logs aren't stored anymore. Please use fluentd to store them"),[]}getReport(){return this.getParsedLogs().join("\r\n")}_catchConsole(){this.oldConsoleMethods={},F.forEach((e=>{this.oldConsoleMethods&&(this.oldConsoleMethods[e]=console[e]);("undefined"!=typeof window?window:global).console[e]=(...t)=>{try{this.log(e,t.join(" ")),this.oldConsoleMethods&&this.oldConsoleMethods[e].apply(null,t)}catch(e){}}}))}_sendToRemoteLogger(e,t={}){if(!this.remoteClientConfiguration)return;const{level:i,bufferSize:n}=this.remoteClientConfiguration;if(i&&!this._isLevelAbove(i,e)){if(t.level=e,n>0)return this._addToBuffer(t);this._sendDebugToGrafana(t)}}_parseLoggerBody(e){const{level:t}=e,{maxMessageSize:i,extra:n}=this.remoteClientConfiguration||{};return delete e.level,i&&"string"==typeof e.message&&e.message.length>i&&(e.message=`${e.message.substr(0,i)}...`),j({level:t,...e,...n})}_addToBuffer(e){this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null),this.buffer.push(e);const{bufferSize:t,bufferTimeout:i}=this.remoteClientConfiguration;if(this.buffer.length>t)return this._processBuffer();i>0&&(this.bufferTimeout=setTimeout(this._boundProcessBuffer,i))}_processBuffer(){this._sendDebugToGrafana(this.buffer),this.buffer=[],this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null)}_computeRetryDelay(e,t=1e3,i=5e4){const n=Math.min(t*1.5**e,i);return Math.max(t,Math.random()*n)}_sendDebugToGrafana(e,t=0){if(!this.remoteClientConfiguration||t>=10)return;const{tag:i,host:n,port:r}=this.remoteClientConfiguration,s=443==+r,a=`http${s?"s":""}://${n}${s?"":`:${r}`}/${i}`,o=Array.isArray(e)?`[${e.map(this._boundParseLoggerBody).join(",")}]`:this._parseLoggerBody(e);fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:o}).catch((i=>{i.skipSendToRemote=!0,this.log("error",this._makeCategory("grafana"),"Sending log to grafana, error",i);const n=this._computeRetryDelay(t,1e3,5e4);setTimeout((()=>{Array.isArray(e)?e=e.map((e=>this._writeRetryCount(e,t+1))):e&&"object"==typeof e&&(e=this._writeRetryCount(e,t+1)),this._sendDebugToGrafana(e,t+1)}),n)}))}_writeRetryCount(e,t){return e&&"object"==typeof e&&(e._retry=t),e}_isLevelAbove(e,t){const i=M.indexOf(e),n=M.indexOf(t);return-1!==i&&-1!==n&&i>n}_makeCategory(e){return`${H}${e}`}};const U=["head","get","post","put","delete","options"],V=B?B.loggerFor("api"):console,q=3e5;class G{server;agent;clientId;token;tenant;fetchOptions;refreshTokenCallback;refreshTokenPromise;shouldLogErrors;requestTimeout;head;get;post;put;delete;options;static successResponseParser(e){return 204===e.status||201===e.status||200===e.status}static defaultParser(e){return e.json().then((t=>({...t,_headers:e.headers})))}static getQueryString(e){return Object.keys(e).filter((t=>e[t])).map((t=>`${t}=${encodeURIComponent(e[t])}`)).join("&")}static base64Encode(e){if("undefined"!=typeof btoa)try{return btoa(e)}catch(e){}return S(e)}constructor({server:e,refreshTokenCallback:t,clientId:i,agent:n=null,token:r=null,fetchOptions:s,requestTimeout:a=3e5}){this.server=e,this.agent=n,this.clientId=i,this.refreshTokenCallback=t,this.refreshTokenPromise=null,this.fetchOptions=s||{},this.requestTimeout=a||q,r&&(this.token=r),this.shouldLogErrors=!0,U.forEach((e=>{this[e]=function(...t){return t.splice(1,0,e),this.call.call(this,...t)}}))}setRequestTimeout(e){this.requestTimeout=e}setTenant(e){this.tenant=e}setToken(e){this.token=e}setFetchOptions(e){this.fetchOptions=e}disableErrorLogging(){this.shouldLogErrors=!1}enableErrorLogging(){this.shouldLogErrors=!0}async call(e,t="get",i=null,n=null,r=G.defaultParser,s=!0){const a=this.computeUrl(t,e,i),o=this.getHeaders(n);let c="get"===t?null:i;c&&"application/json"===o["Content-Type"]&&(c=JSON.stringify(c));const d="head"===t,l=("delete"===t||d)&&r===G.defaultParser?G.successResponseParser:r,h={...this.fetchOptions||{}},u=new AbortController,p=h.headers||{};delete h.headers;const g={method:t,body:c,signal:u?u.signal:null,headers:{...this.getHeaders(n),...p},agent:this.agent,...h};this.refreshTokenPromise&&(V.info("A token is already refreshing, waiting ...",{url:a}),await this.refreshTokenPromise);const f=new Date,m=fetch(a,g).then((o=>{const c=-1!==(o.headers.get("content-type")||"").indexOf("application/json");if(B.logRequest(a,g,o,f),d&&o.status>=500||!d&&o.status>=400){const a=c?o.json():o.text(),d=o.status>=500?w:b;return a.then((async a=>{if(s&&this._checkTokenExpired(o,a))return V.warn("token expired",{error:a.reason}),this._replayWithNewToken(a,e,t,i,n,r);const c="string"==typeof a?d.fromText(a,o.status):d.fromResponse(a,o.status);throw this.shouldLogErrors&&V.error("API error",c),c}))}return l(o,c)})).catch((e=>{throw this.shouldLogErrors&&V.error("Fetch failed",{url:a,options:g,message:e.message,stack:e.stack}),e})),v=new Promise(((e,t)=>{setTimeout((()=>{u.abort(),t(new Error(`Request timed out after ${this.requestTimeout} ms`))}),this.requestTimeout)}));return Promise.race([m,v])}_checkTokenExpired(e,t){const i=404===e.status&&this._isTokenNotFound(t);return 401===e.status||i}_isTokenNotFound(e){return e&&e.reason&&"No such token"===e.reason[0]}_replayWithNewToken(e,t,i,n=null,r=null,s=void 0){const a=this._isTokenNotFound(e);let o=t;return V.info("refreshing token",{inProgress:!!this.refreshTokenPromise}),this.refreshTokenPromise=this.refreshTokenPromise||this.refreshTokenCallback(),this.refreshTokenPromise?.then((()=>{if(this.refreshTokenPromise=null,V.info("token refreshed",{isTokenNotFound:a}),a){const e=t.split("/");e.pop(),e.push(this.token),o=e.join("/")}return this.call(o,i,n,r,s,!1)})).catch((e=>{throw this.refreshTokenPromise=null,e}))}getHeaders(e){return e instanceof Object?e:{"X-Auth-Token":this.token,...this.tenant?{"Wazo-Tenant":this.tenant}:null,Accept:"application/json","Content-Type":"application/json"}}computeUrl(e,t,i){const n=`${this.baseUrl}/${t}`;return"get"===e&&i&&Object.keys(i).length?`${n}?${G.getQueryString(i)}`:n}get baseUrl(){return`https://${this.server}/api`}}var K,W,z,Y,J,Z,X,Q,ee,te={userAgent:!1},ie={},ne=ne||function(e,t){var i={},n=i.lib={},r=n.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var i=new e;return t&&i.mixIn(t),i.hasOwnProperty("init")||(i.init=function(){i.$super.init.apply(this,arguments)}),i.init.prototype=i,i.$super=this,i},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,i=e.words,n=this.sigBytes,r=e.sigBytes;if(this.clamp(),n%4)for(var s=0;s<r;s++){var a=i[s>>>2]>>>24-s%4*8&255;t[n+s>>>2]|=a<<24-(n+s)%4*8}else for(s=0;s<r;s+=4)t[n+s>>>2]=i[s>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var i=[],n=0;n<t;n+=4)i.push(4294967296*e.random()|0);return new s.init(i,t)}}),a=i.enc={},o=a.Hex={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push((s>>>4).toString(16)),n.push((15&s).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n+=2)i[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(i,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n++)i[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(i,t)}},d=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i=this._data,n=i.words,r=i.sigBytes,a=this.blockSize,o=r/(4*a),c=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,d=e.min(4*c,r);if(c){for(var l=0;l<c;l+=a)this._doProcessBlock(n,l);var h=n.splice(0,c);i.sigBytes-=d}return new s.init(h,d)},clone:function(){var e=r.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});n.Hasher=l.extend({cfg:r.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,i){return new e.init(i).finalize(t)}},_createHmacHelper:function(e){return function(t,i){return new h.HMAC.init(e,i).finalize(t)}}});var h=i.algo={};return i}(Math);W=(K=ne).lib,z=W.Base,Y=W.WordArray,(K=K.x64={}).Word=z.extend({init:function(e,t){this.high=e,this.low=t}}),K.WordArray=z.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:8*e.length},toX32:function(){for(var e=this.words,t=e.length,i=[],n=0;n<t;n++){var r=e[n];i.push(r.high),i.push(r.low)}return Y.create(i,this.sigBytes)},clone:function(){for(var e=z.clone.call(this),t=e.words=this.words.slice(0),i=t.length,n=0;n<i;n++)t[n]=t[n].clone();return e}}),ne.lib.Cipher||function(e){var t=(p=ne).lib,i=t.Base,n=t.WordArray,r=t.BufferedBlockAlgorithm,s=p.enc.Base64,a=p.algo.EvpKDF,o=t.Cipher=r.extend({cfg:i.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,i){this.cfg=this.cfg.extend(i),this._xformMode=e,this._key=t,this.reset()},reset:function(){r.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(e){return{encrypt:function(t,i,n){return("string"==typeof i?g:u).encrypt(e,t,i,n)},decrypt:function(t,i,n){return("string"==typeof i?g:u).decrypt(e,t,i,n)}}}});t.StreamCipher=o.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var c=p.mode={},d=function(e,t,i){var n=this._iv;n?this._iv=undefined:n=this._prevBlock;for(var r=0;r<i;r++)e[t+r]^=n[r]},l=(t.BlockCipherMode=i.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}})).extend();l.Encryptor=l.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize;d.call(this,e,t,n),i.encryptBlock(e,t),this._prevBlock=e.slice(t,t+n)}}),l.Decryptor=l.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize,r=e.slice(t,t+n);i.decryptBlock(e,t),d.call(this,e,t,n),this._prevBlock=r}}),c=c.CBC=l,l=(p.pad={}).Pkcs7={pad:function(e,t){for(var i,r=(i=(i=4*t)-e.sigBytes%i)<<24|i<<16|i<<8|i,s=[],a=0;a<i;a+=4)s.push(r);i=n.create(s,i),e.concat(i)},unpad:function(e){e.sigBytes-=255&e.words[e.sigBytes-1>>>2]}},t.BlockCipher=o.extend({cfg:o.cfg.extend({mode:c,padding:l}),reset:function(){o.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var i=t.createEncryptor;else i=t.createDecryptor,this._minBufferSize=1;this._mode=i.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=i.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),u=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(s)},parse:function(e){var t=(e=s.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var i=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:i})}},t.SerializableCipher=i.extend({cfg:i.extend({format:c}),encrypt:function(e,t,i,n){n=this.cfg.extend(n);var r=e.createEncryptor(i,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:i,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,i,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(i,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,i,r){return r||(r=n.random(8)),e=a.create({keySize:t+i}).compute(e,r),i=n.create(e.words.slice(t),4*i),e.sigBytes=4*t,h.create({key:e,iv:i,salt:r})}},g=t.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:p}),encrypt:function(e,t,i,n){return i=(n=this.cfg.extend(n)).kdf.execute(i,e.keySize,e.ivSize),n.iv=i.iv,(e=u.encrypt.call(this,e,t,i.key,n)).mixIn(i),e},decrypt:function(e,t,i,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),i=n.kdf.execute(i,e.keySize,e.ivSize,t.salt),n.iv=i.iv,u.decrypt.call(this,e,t,i.key,n)}})}(),function(){for(var e=ne,t=e.lib.BlockCipher,i=e.algo,n=[],r=[],s=[],a=[],o=[],c=[],d=[],l=[],h=[],u=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var f=0,m=0;for(g=0;256>g;g++){var v=(v=m^m<<1^m<<2^m<<3^m<<4)>>>8^255&v^99;n[f]=v,r[v]=f;var y=p[f],S=p[y],b=p[S],w=257*p[v]^16843008*v;s[f]=w<<24|w>>>8,a[f]=w<<16|w>>>16,o[f]=w<<8|w>>>24,c[f]=w,w=16843009*b^65537*S^257*y^16843008*f,d[v]=w<<24|w>>>8,l[v]=w<<16|w>>>16,h[v]=w<<8|w>>>24,u[v]=w,f?(f=y^p[p[p[b^y]]],m^=p[p[m]]):f=m=1}var E=[0,1,2,4,8,16,32,64,128,27,54];i=i.AES=t.extend({_doReset:function(){for(var e=(i=this._key).words,t=i.sigBytes/4,i=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],s=0;s<i;s++)if(s<t)r[s]=e[s];else{var a=r[s-1];s%t?6<t&&4==s%t&&(a=n[a>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a]):(a=n[(a=a<<8|a>>>24)>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a],a^=E[s/t|0]<<24),r[s]=r[s-t]^a}for(e=this._invKeySchedule=[],t=0;t<i;t++)s=i-t,a=t%4?r[s]:r[s-4],e[t]=4>t||4>=s?a:d[n[a>>>24]]^l[n[a>>>16&255]]^h[n[a>>>8&255]]^u[n[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,o,c,n)},decryptBlock:function(e,t){var i=e[t+1];e[t+1]=e[t+3],e[t+3]=i,this._doCryptBlock(e,t,this._invKeySchedule,d,l,h,u,r),i=e[t+1],e[t+1]=e[t+3],e[t+3]=i},_doCryptBlock:function(e,t,i,n,r,s,a,o){for(var c=this._nRounds,d=e[t]^i[0],l=e[t+1]^i[1],h=e[t+2]^i[2],u=e[t+3]^i[3],p=4,g=1;g<c;g++){var f=n[d>>>24]^r[l>>>16&255]^s[h>>>8&255]^a[255&u]^i[p++],m=n[l>>>24]^r[h>>>16&255]^s[u>>>8&255]^a[255&d]^i[p++],v=n[h>>>24]^r[u>>>16&255]^s[d>>>8&255]^a[255&l]^i[p++];u=n[u>>>24]^r[d>>>16&255]^s[l>>>8&255]^a[255&h]^i[p++],d=f,l=m,h=v}f=(o[d>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&u])^i[p++],m=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[u>>>8&255]<<8|o[255&d])^i[p++],v=(o[h>>>24]<<24|o[u>>>16&255]<<16|o[d>>>8&255]<<8|o[255&l])^i[p++],u=(o[u>>>24]<<24|o[d>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^i[p++],e[t]=f,e[t+1]=m,e[t+2]=v,e[t+3]=u},keySize:8});e.AES=t._createHelper(i)}(),function(){function e(e,t){var i=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=i,this._lBlock^=i<<e}function t(e,t){var i=(this._rBlock>>>e^this._lBlock)&t;this._lBlock^=i,this._rBlock^=i<<e}var i=ne,n=(r=i.lib).WordArray,r=r.BlockCipher,s=i.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],l=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],h=s.DES=r.extend({_doReset:function(){for(var e=this._key.words,t=[],i=0;56>i;i++){var n=a[i]-1;t[i]=e[n>>>5]>>>31-n%32&1}for(e=this._subKeys=[],n=0;16>n;n++){var r=e[n]=[],s=c[n];for(i=0;24>i;i++)r[i/6|0]|=t[(o[i]-1+s)%28]<<31-i%6,r[4+(i/6|0)]|=t[28+(o[i+24]-1+s)%28]<<31-i%6;for(r[0]=r[0]<<1|r[0]>>>31,i=1;7>i;i++)r[i]>>>=4*(i-1)+3;r[7]=r[7]<<5|r[7]>>>27}for(t=this._invSubKeys=[],i=0;16>i;i++)t[i]=e[15-i]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(i,n,r){this._lBlock=i[n],this._rBlock=i[n+1],e.call(this,4,252645135),e.call(this,16,65535),t.call(this,2,858993459),t.call(this,8,16711935),e.call(this,1,1431655765);for(var s=0;16>s;s++){for(var a=r[s],o=this._lBlock,c=this._rBlock,h=0,u=0;8>u;u++)h|=d[u][((c^a[u])&l[u])>>>0];this._lBlock=c,this._rBlock=o^h}r=this._lBlock,this._lBlock=this._rBlock,this._rBlock=r,e.call(this,1,1431655765),t.call(this,8,16711935),t.call(this,2,858993459),e.call(this,16,65535),e.call(this,4,252645135),i[n]=this._lBlock,i[n+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});i.DES=r._createHelper(h),s=s.TripleDES=r.extend({_doReset:function(){var e=this._key.words;this._des1=h.createEncryptor(n.create(e.slice(0,2))),this._des2=h.createEncryptor(n.create(e.slice(2,4))),this._des3=h.createEncryptor(n.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2}),i.TripleDES=r._createHelper(s)}(),function(){var e=ne,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,n=this._map;e.clamp(),e=[];for(var r=0;r<i;r+=3)for(var s=(t[r>>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a<i;a++)e.push(n.charAt(s>>>6*(3-a)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var i=e.length,n=this._map;(r=n.charAt(64))&&(-1!=(r=e.indexOf(r))&&(i=r));for(var r=[],s=0,a=0;a<i;a++)if(a%4){var o=n.indexOf(e.charAt(a-1))<<a%4*2,c=n.indexOf(e.charAt(a))>>>6-a%4*2;r[s>>>2]|=(o|c)<<24-s%4*8,s++}return t.create(r,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,i,n,r,s,a){return((e=e+(t&i|~t&n)+r+a)<<s|e>>>32-s)+t}function i(e,t,i,n,r,s,a){return((e=e+(t&n|i&~n)+r+a)<<s|e>>>32-s)+t}function n(e,t,i,n,r,s,a){return((e=e+(t^i^n)+r+a)<<s|e>>>32-s)+t}function r(e,t,i,n,r,s,a){return((e=e+(i^(t|~n))+r+a)<<s|e>>>32-s)+t}for(var s=ne,a=(c=s.lib).WordArray,o=c.Hasher,c=s.algo,d=[],l=0;64>l;l++)d[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,s){for(var a=0;16>a;a++){var o=e[c=s+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[s+0],l=(o=e[s+1],e[s+2]),h=e[s+3],u=e[s+4],p=e[s+5],g=e[s+6],f=e[s+7],m=e[s+8],v=e[s+9],y=e[s+10],S=e[s+11],b=e[s+12],w=e[s+13],E=e[s+14],C=e[s+15],$=t($=a[0],x=a[1],_=a[2],T=a[3],c,7,d[0]),T=t(T,$,x,_,o,12,d[1]),_=t(_,T,$,x,l,17,d[2]),x=t(x,_,T,$,h,22,d[3]);$=t($,x,_,T,u,7,d[4]),T=t(T,$,x,_,p,12,d[5]),_=t(_,T,$,x,g,17,d[6]),x=t(x,_,T,$,f,22,d[7]),$=t($,x,_,T,m,7,d[8]),T=t(T,$,x,_,v,12,d[9]),_=t(_,T,$,x,y,17,d[10]),x=t(x,_,T,$,S,22,d[11]),$=t($,x,_,T,b,7,d[12]),T=t(T,$,x,_,w,12,d[13]),_=t(_,T,$,x,E,17,d[14]),$=i($,x=t(x,_,T,$,C,22,d[15]),_,T,o,5,d[16]),T=i(T,$,x,_,g,9,d[17]),_=i(_,T,$,x,S,14,d[18]),x=i(x,_,T,$,c,20,d[19]),$=i($,x,_,T,p,5,d[20]),T=i(T,$,x,_,y,9,d[21]),_=i(_,T,$,x,C,14,d[22]),x=i(x,_,T,$,u,20,d[23]),$=i($,x,_,T,v,5,d[24]),T=i(T,$,x,_,E,9,d[25]),_=i(_,T,$,x,h,14,d[26]),x=i(x,_,T,$,m,20,d[27]),$=i($,x,_,T,w,5,d[28]),T=i(T,$,x,_,l,9,d[29]),_=i(_,T,$,x,f,14,d[30]),$=n($,x=i(x,_,T,$,b,20,d[31]),_,T,p,4,d[32]),T=n(T,$,x,_,m,11,d[33]),_=n(_,T,$,x,S,16,d[34]),x=n(x,_,T,$,E,23,d[35]),$=n($,x,_,T,o,4,d[36]),T=n(T,$,x,_,u,11,d[37]),_=n(_,T,$,x,f,16,d[38]),x=n(x,_,T,$,y,23,d[39]),$=n($,x,_,T,w,4,d[40]),T=n(T,$,x,_,c,11,d[41]),_=n(_,T,$,x,h,16,d[42]),x=n(x,_,T,$,g,23,d[43]),$=n($,x,_,T,v,4,d[44]),T=n(T,$,x,_,b,11,d[45]),_=n(_,T,$,x,C,16,d[46]),$=r($,x=n(x,_,T,$,l,23,d[47]),_,T,c,6,d[48]),T=r(T,$,x,_,f,10,d[49]),_=r(_,T,$,x,E,15,d[50]),x=r(x,_,T,$,p,21,d[51]),$=r($,x,_,T,b,6,d[52]),T=r(T,$,x,_,h,10,d[53]),_=r(_,T,$,x,y,15,d[54]),x=r(x,_,T,$,o,21,d[55]),$=r($,x,_,T,m,6,d[56]),T=r(T,$,x,_,C,10,d[57]),_=r(_,T,$,x,g,15,d[58]),x=r(x,_,T,$,w,21,d[59]),$=r($,x,_,T,u,6,d[60]),T=r(T,$,x,_,S,10,d[61]),_=r(_,T,$,x,l,15,d[62]),x=r(x,_,T,$,v,21,d[63]);a[0]=a[0]+$|0,a[1]=a[1]+x|0,a[2]=a[2]+_|0,a[3]=a[3]+T|0},_doFinalize:function(){var t=this._data,i=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;i[r>>>5]|=128<<24-r%32;var s=e.floor(n/4294967296);for(i[15+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),i[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(i.length+1),this._process(),i=(t=this._hash).words,n=0;4>n;n++)r=i[n],i[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),s.MD5=o._createHelper(c),s.HmacMD5=o._createHmacHelper(c)}(Math),Z=(ee=(J=ne).lib).WordArray,X=ee.Hasher,Q=[],ee=J.algo.SHA1=X.extend({_doReset:function(){this._hash=new Z.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],a=i[3],o=i[4],c=0;80>c;c++){if(16>c)Q[c]=0|e[t+c];else{var d=Q[c-3]^Q[c-8]^Q[c-14]^Q[c-16];Q[c]=d<<1|d>>>31}d=(n<<5|n>>>27)+o+Q[c],d=20>c?d+(1518500249+(r&s|~r&a)):40>c?d+(1859775393+(r^s^a)):60>c?d+((r&s|r&a|s&a)-1894007588):d+((r^s^a)-899497514),o=a,a=s,s=r<<30|r>>>2,r=n,n=d}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+a|0,i[4]=i[4]+o|0},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(i/4294967296),t[15+(n+64>>>9<<4)]=i,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=X.clone.call(this);return e._hash=this._hash.clone(),e}}),J.SHA1=X._createHelper(ee),J.HmacSHA1=X._createHmacHelper(ee),function(e){for(var t=ne,i=(r=t.lib).WordArray,n=r.Hasher,r=t.algo,s=[],a=[],o=function(e){return 4294967296*(e-(0|e))|0},c=2,d=0;64>d;){var l;e:{l=c;for(var h=e.sqrt(l),u=2;u<=h;u++)if(!(l%u)){l=!1;break e}l=!0}l&&(8>d&&(s[d]=o(e.pow(c,.5))),a[d]=o(e.pow(c,1/3)),d++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new i.init(s.slice(0))},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],o=i[3],c=i[4],d=i[5],l=i[6],h=i[7],u=0;64>u;u++){if(16>u)p[u]=0|e[t+u];else{var g=p[u-15],f=p[u-2];p[u]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[u-7]+((f<<15|f>>>17)^(f<<13|f>>>19)^f>>>10)+p[u-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&d^~c&l)+a[u]+p[u],f=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&s^r&s),h=l,l=d,d=c,c=o+g|0,o=s,s=r,r=n,n=g+f|0}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+o|0,i[4]=i[4]+c|0,i[5]=i[5]+d|0,i[6]=i[6]+l|0,i[7]=i[7]+h|0},_doFinalize:function(){var t=this._data,i=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return i[r>>>5]|=128<<24-r%32,i[14+(r+64>>>9<<4)]=e.floor(n/4294967296),i[15+(r+64>>>9<<4)]=n,t.sigBytes=4*i.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),function(){var e=ne,t=e.lib.WordArray,i=(n=e.algo).SHA256,n=n.SHA224=i.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=i._doFinalize.call(this);return e.sigBytes-=4,e}});e.SHA224=i._createHelper(n),e.HmacSHA224=i._createHmacHelper(n)}(),function(){function e(){return n.create.apply(n,arguments)}for(var t=ne,i=t.lib.Hasher,n=(s=t.x64).Word,r=s.WordArray,s=t.algo,a=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],o=[],c=0;80>c;c++)o[c]=e();s=s.SHA512=i.extend({_doReset:function(){this._hash=new r.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var i=(h=this._hash.words)[0],n=h[1],r=h[2],s=h[3],c=h[4],d=h[5],l=h[6],h=h[7],u=i.high,p=i.low,g=n.high,f=n.low,m=r.high,v=r.low,y=s.high,S=s.low,b=c.high,w=c.low,E=d.high,C=d.low,$=l.high,T=l.low,_=h.high,x=h.low,I=u,R=p,A=g,P=f,D=m,N=v,k=y,O=S,F=b,M=w,H=E,L=C,j=$,B=T,U=_,V=x,q=0;80>q;q++){var G=o[q];if(16>q)var K=G.high=0|e[t+2*q],W=G.low=0|e[t+2*q+1];else{K=((W=(K=o[q-15]).high)>>>1|(z=K.low)<<31)^(W>>>8|z<<24)^W>>>7;var z=(z>>>1|W<<31)^(z>>>8|W<<24)^(z>>>7|W<<25),Y=((W=(Y=o[q-2]).high)>>>19|(J=Y.low)<<13)^(W<<3|J>>>29)^W>>>6,J=(J>>>19|W<<13)^(J<<3|W>>>29)^(J>>>6|W<<26),Z=(W=o[q-7]).high,X=(Q=o[q-16]).high,Q=Q.low;K=(K=(K=K+Z+((W=z+W.low)>>>0<z>>>0?1:0))+Y+((W=W+J)>>>0<J>>>0?1:0))+X+((W=W+Q)>>>0<Q>>>0?1:0);G.high=K,G.low=W}Z=F&H^~F&j,Q=M&L^~M&B,G=I&A^I&D^A&D;var ee=R&P^R&N^P&N,te=(z=(I>>>28|R<<4)^(I<<30|R>>>2)^(I<<25|R>>>7),Y=(R>>>28|I<<4)^(R<<30|I>>>2)^(R<<25|I>>>7),(J=a[q]).high),ie=J.low;X=U+((F>>>14|M<<18)^(F>>>18|M<<14)^(F<<23|M>>>9))+((J=V+((M>>>14|F<<18)^(M>>>18|F<<14)^(M<<23|F>>>9)))>>>0<V>>>0?1:0),U=j,V=B,j=H,B=L,H=F,L=M,F=k+(X=(X=(X=X+Z+((J=J+Q)>>>0<Q>>>0?1:0))+te+((J=J+ie)>>>0<ie>>>0?1:0))+K+((J=J+W)>>>0<W>>>0?1:0))+((M=O+J|0)>>>0<O>>>0?1:0)|0,k=D,O=N,D=A,N=P,A=I,P=R,I=X+(G=z+G+((W=Y+ee)>>>0<Y>>>0?1:0))+((R=J+W|0)>>>0<J>>>0?1:0)|0}p=i.low=p+R,i.high=u+I+(p>>>0<R>>>0?1:0),f=n.low=f+P,n.high=g+A+(f>>>0<P>>>0?1:0),v=r.low=v+N,r.high=m+D+(v>>>0<N>>>0?1:0),S=s.low=S+O,s.high=y+k+(S>>>0<O>>>0?1:0),w=c.low=w+M,c.high=b+F+(w>>>0<M>>>0?1:0),C=d.low=C+L,d.high=E+H+(C>>>0<L>>>0?1:0),T=l.low=T+B,l.high=$+j+(T>>>0<B>>>0?1:0),x=h.low=x+V,h.high=_+U+(x>>>0<V>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(i/4294967296),t[31+(n+128>>>10<<5)]=i,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=i._createHelper(s),t.HmacSHA512=i._createHmacHelper(s)}(),function(){var e=ne,t=(r=e.x64).Word,i=r.WordArray,n=(r=e.algo).SHA512,r=r.SHA384=n.extend({_doReset:function(){this._hash=new i.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(r),e.HmacSHA384=n._createHmacHelper(r)}(),function(){var e=ne,t=(n=e.lib).WordArray,i=n.Hasher,n=e.algo,r=t.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),s=t.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),a=t.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),o=t.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),c=t.create([0,1518500249,1859775393,2400959708,2840853838]),d=t.create([1352829926,1548603684,1836072691,2053994217,0]);n=n.RIPEMD160=i.extend({_doReset:function(){this._hash=t.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=0;16>i;i++){var n=e[b=t+i];e[b]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var l,h,u,p,g,f,m,v,y,S,b=this._hash.words,w=(n=c.words,d.words),E=r.words,C=s.words,$=a.words,T=o.words;f=l=b[0],m=h=b[1],v=u=b[2],y=p=b[3],S=g=b[4];var _;for(i=0;80>i;i+=1)_=l+e[t+E[i]]|0,_=16>i?_+((h^u^p)+n[0]):32>i?_+((h&u|~h&p)+n[1]):48>i?_+(((h|~u)^p)+n[2]):64>i?_+((h&p|u&~p)+n[3]):_+((h^(u|~p))+n[4]),_=(_=(_|=0)<<$[i]|_>>>32-$[i])+g|0,l=g,g=p,p=u<<10|u>>>22,u=h,h=_,_=f+e[t+C[i]]|0,_=16>i?_+((m^(v|~y))+w[0]):32>i?_+((m&y|v&~y)+w[1]):48>i?_+(((m|~v)^y)+w[2]):64>i?_+((m&v|~m&y)+w[3]):_+((m^v^y)+w[4]),_=(_=(_|=0)<<T[i]|_>>>32-T[i])+S|0,f=S,S=y,y=v<<10|v>>>22,v=m,m=_;_=b[1]+u+y|0,b[1]=b[2]+p+S|0,b[2]=b[3]+g+f|0,b[3]=b[4]+l+m|0,b[4]=b[0]+h+v|0,b[0]=_},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;for(t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),e.sigBytes=4*(t.length+1),this._process(),t=(e=this._hash).words,i=0;5>i;i++)n=t[i],t[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8);return e},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});e.RIPEMD160=i._createHelper(n),e.HmacRIPEMD160=i._createHmacHelper(n)}(),function(){var e=ne,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,i){e=this._hasher=new e.init,"string"==typeof i&&(i=t.parse(i));var n=e.blockSize,r=4*n;i.sigBytes>r&&(i=e.finalize(i)),i.clamp();for(var s=this._oKey=i.clone(),a=this._iKey=i.clone(),o=s.words,c=a.words,d=0;d<n;d++)o[d]^=1549556828,c[d]^=909522486;s.sigBytes=a.sigBytes=r,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher;return e=t.finalize(e),t.reset(),t.finalize(this._oKey.clone().concat(e))}})}(),function(){var e,t=ne,i=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).HMAC,s=e.PBKDF2=i.extend({cfg:i.extend({keySize:4,hasher:e.SHA1,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){var i=this.cfg,s=r.create(i.hasher,e),a=n.create(),o=n.create([1]),c=a.words,d=o.words,l=i.keySize;for(i=i.iterations;c.length<l;){var h=s.update(t).finalize(o);s.reset();for(var u=h.words,p=u.length,g=h,f=1;f<i;f++){g=s.finalize(g),s.reset();for(var m=g.words,v=0;v<p;v++)u[v]^=m[v]}a.concat(h),d[0]++}return a.sigBytes=4*l,a}});t.PBKDF2=function(e,t,i){return s.create(i).compute(e,t)}}();
|
|
4
4
|
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
|
|
5
5
|
*/
|
|
6
6
|
var re,se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ae="=";function oe(e){var t,i,n="";for(t=0;t+3<=e.length;t+=3)i=parseInt(e.substring(t,t+3),16),n+=se.charAt(i>>6)+se.charAt(63&i);for(t+1==e.length?(i=parseInt(e.substring(t,t+1),16),n+=se.charAt(i<<2)):t+2==e.length&&(i=parseInt(e.substring(t,t+2),16),n+=se.charAt(i>>2)+se.charAt((3&i)<<4));(3&n.length)>0;)n+=ae;return n}function ce(e){var t,i,n,r="",s=0;for(t=0;t<e.length&&e.charAt(t)!=ae;++t)(n=se.indexOf(e.charAt(t)))<0||(0==s?(r+=fe(n>>2),i=3&n,s=1):1==s?(r+=fe(i<<2|n>>4),i=15&n,s=2):2==s?(r+=fe(i),r+=fe(n>>2),i=3&n,s=3):(r+=fe(i<<2|n>>4),r+=fe(15&n),s=0));return 1==s&&(r+=fe(i<<2)),r}
|
|
@@ -25,7 +25,7 @@ function Ke(e,t){this.x=t,this.q=e}function We(e,t,i,n){this.curve=e,this.x=t,th
|
|
|
25
25
|
Ke.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},We.prototype.getEncoded=function(e){var t=function(e,t){var i=e.toByteArrayUnsigned();if(t<i.length)i=i.slice(i.length-t);else for(;t>i.length;)i.unshift(0);return i},i=this.getX().toBigInteger(),n=this.getY().toBigInteger(),r=t(i,32);return e?n.isEven()?r.unshift(2):r.unshift(3):(r.unshift(4),r=r.concat(t(n,32))),r},We.decodeFrom=function(e,t){t[0];var i=t.length-1,n=t.slice(1,1+i/2),r=t.slice(1+i/2,1+i);n.unshift(0),r.unshift(0);var s=new de(n),a=new de(r);return new We(e,e.fromBigInteger(s),e.fromBigInteger(a))},We.decodeFromHex=function(e,t){t.substr(0,2);var i=t.length-2,n=t.substr(2,i/2),r=t.substr(2+i/2,i/2),s=new de(n,16),a=new de(r,16);return new We(e,e.fromBigInteger(s),e.fromBigInteger(a))},We.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),i=e.y.subtract(this.y).divide(t),n=i.square().subtract(this.x).subtract(e.x),r=i.multiply(this.x.subtract(n)).subtract(this.y);return new We(this.curve,n,r)},We.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(de.valueOf(2)),t=this.curve.fromBigInteger(de.valueOf(3)),i=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=i.square().subtract(this.x.multiply(e)),r=i.multiply(this.x.subtract(n)).subtract(this.y);return new We(this.curve,n,r)},We.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,i=e,n=i.multiply(new de("3")),r=this.negate(),s=this;for(t=n.bitLength()-2;t>0;--t){s=s.twice();var a=n.testBit(t);a!=i.testBit(t)&&(s=s.add2D(a?this:r))}return s},We.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),i=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),r=this.curve.getQ(),s=t.multiply(t).mod(r),a=e.multiply(e).multiply(e).add(i.multiply(e)).add(n).mod(r);return s.equals(a)},We.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},We.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),i=this.getY().toBigInteger();if(t.compareTo(de.ONE)<0||t.compareTo(e.subtract(de.ONE))>0)throw new Error("x coordinate out of bounds");if(i.compareTo(de.ONE)<0||i.compareTo(e.subtract(de.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};
|
|
26
26
|
/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval
|
|
27
27
|
*/
|
|
28
|
-
var Ye=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),i={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?i[t]:String.fromCharCode(parseInt(n,16))}var r=new String(""),s=Object.hasOwnProperty;return function(i,a){var o,c,d=i.match(e),l=d[0],h=!1;"{"===l?o={}:"["===l?o=[]:(o=[],h=!0);for(var u=[o],p=1-h,g=d.length;p<g;++p){var f;switch((l=d[p]).charCodeAt(0)){default:(f=u[0])[c||f.length]=+l,c=void 0;break;case 34:if(-1!==(l=l.substring(1,l.length-1)).indexOf("\\")&&(l=l.replace(t,n)),f=u[0],!c){if(!(f instanceof Array)){c=l||r;break}c=f.length}f[c]=l,c=void 0;break;case 91:f=u[0],u.unshift(f[c||f.length]=[]),c=void 0;break;case 93:case 125:u.shift();break;case 102:(f=u[0])[c||f.length]=!1,c=void 0;break;case 110:(f=u[0])[c||f.length]=null,c=void 0;break;case 116:(f=u[0])[c||f.length]=!0,c=void 0;break;case 123:f=u[0],u.unshift(f[c||f.length]={}),c=void 0}}if(h){if(1!==u.length)throw new Error;o=o[0]}else if(u.length)throw new Error;if(a){var m=function(e,t){var i=e[t];if(i&&"object"==typeof i){var n=null;for(var r in i)if(s.call(i,r)&&i!==e){var o=m(i,r);void 0!==o?i[r]=o:(n||(n=[]),n.push(r))}if(n)for(var c=n.length;--c>=0;)delete i[n[c]]}return a.call(e,t,i)};o=m({"":o},"")}return o}}();void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),Je.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){return Rt(e)},this.getPEMStringFromHex=function(e,t){return ht(e,t)},this.newObject=function(e){var t=Je.asn1,i=t.ASN1Object,n=t.DERBoolean,r=t.DERInteger,s=t.DERBitString,a=t.DEROctetString,o=t.DERNull,c=t.DERObjectIdentifier,d=t.DEREnumerated,l=t.DERUTF8String,h=t.DERNumericString,u=t.DERPrintableString,p=t.DERTeletexString,g=t.DERIA5String,f=t.DERUTCTime,m=t.DERGeneralizedTime,v=t.DERVisibleString,y=t.DERBMPString,S=t.DERSequence,b=t.DERSet,w=t.DERTaggedObject,E=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var C=Object.keys(e);if(1!=C.length)throw new Error("key of param shall be only one.");var $=C[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+$+":"))throw new Error("undefined key: "+$);if("bool"==$)return new n(e[$]);if("int"==$)return new r(e[$]);if("bitstr"==$)return new s(e[$]);if("octstr"==$)return new a(e[$]);if("null"==$)return new o(e[$]);if("oid"==$)return new c(e[$]);if("enum"==$)return new d(e[$]);if("utf8str"==$)return new l(e[$]);if("numstr"==$)return new h(e[$]);if("prnstr"==$)return new u(e[$]);if("telstr"==$)return new p(e[$]);if("ia5str"==$)return new g(e[$]);if("utctime"==$)return new f(e[$]);if("gentime"==$)return new m(e[$]);if("visstr"==$)return new v(e[$]);if("bmpstr"==$)return new y(e[$]);if("asn1"==$)return new i(e[$]);if("seq"==$){for(var T=e[$],_=[],x=0;x<T.length;x++){var I=E(T[x]);_.push(I)}return new S({array:_})}if("set"==$){for(T=e[$],_=[],x=0;x<T.length;x++){I=E(T[x]);_.push(I)}return new b({array:_})}if("tag"==$){var R=e[$];if("[object Array]"===Object.prototype.toString.call(R)&&3==R.length){var A=E(R[2]);return new w({tag:R[0],explicit:R[1],obj:A})}return new w(R)}},this.jsonToASN1HEX=function(e){return this.newObject(e).tohex()}},Je.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",i=parseInt(e.substr(0,2),16),n=(t=Math.floor(i/40)+"."+i%40,""),r=2;r<e.length;r+=2){var s=("00000000"+parseInt(e.substr(r,2),16).toString(2)).slice(-8);if(n+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new de(n,2).toString(10),n=""}return t},Je.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},i=function(e){var i="",n=new de(e,10).toString(2),r=7-n.length%7;7==r&&(r=0);for(var s="",a=0;a<r;a++)s+="0";n=s+n;for(a=0;a<n.length-1;a+=7){var o=n.substr(a,7);a!=n.length-7&&(o="1"+o),i+=t(parseInt(o,2))}return i};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",r=e.split("."),s=40*parseInt(r[0])+parseInt(r[1]);n+=t(s),r.splice(0,2);for(var a=0;a<r.length;a++)n+=i(r[a]);return n},Je.asn1.ASN1Object=function(e){this.params=null,this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw new Error("this.hV is null or undefined");if(this.hV.length%2==1)throw new Error("value hex must be even length: n=0,v="+this.hV);var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var i=t.length/2;if(i>15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+i).toString(16)+t},this.tohex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.getValueHex=function(){return this.tohex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},Je.asn1.DERAbstractString=function(e){Je.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=at(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},Nt(Je.asn1.DERAbstractString,Je.asn1.ASN1Object),Je.asn1.DERAbstractTime=function(e){Je.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,i){var n=this.zeroPadding,r=this.localDateToUTC(e),s=String(r.getFullYear());"utc"==t&&(s=s.substr(2,2));var a=s+n(String(r.getMonth()+1),2)+n(String(r.getDate()),2)+n(String(r.getHours()),2)+n(String(r.getMinutes()),2)+n(String(r.getSeconds()),2);if(!0===i){var o=r.getMilliseconds();if(0!=o){var c=n(String(o),3);a=a+"."+(c=c.replace(/[0]+$/,""))}}return a+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.setByParam=function(e){this.hV=null,this.hTLV=null,this.params=e},this.getString=function(){},this.setString=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.str=e},this.setByDate=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.date=e},this.setByDateValue=function(e,t,i,n,r,s){var a=new Date(Date.UTC(e,t-1,i,n,r,s,0));this.setByDate(a)},this.getFreshValueHex=function(){return this.hV}},Nt(Je.asn1.DERAbstractTime,Je.asn1.ASN1Object),Je.asn1.DERAbstractStructured=function(e){Je.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},Nt(Je.asn1.DERAbstractStructured,Je.asn1.ASN1Object),Je.asn1.DERBoolean=function(e){Je.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},Nt(Je.asn1.DERBoolean,Je.asn1.ASN1Object),Je.asn1.DERInteger=function(e){Je.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=Rt;this.setByBigInteger=function(e){this.isModified=!0,this.params={bigint:e}},this.setByInteger=function(e){this.isModified=!0,this.params=e},this.setValueHex=function(e){this.isModified=!0,this.params={hex:e}},this.getFreshValueHex=function(){var e=this.params,i=null;if(null==e)throw new Error("value not set");if("object"==typeof e&&null!=e.hex)return this.hV=e.hex,this.hV;if("number"==typeof e)i=new de(String(e),10);else if(null!=e.int)i=new de(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");i=e.bigint}return this.hV=t(i),this.hV},null!=e&&(this.params=e)},Nt(Je.asn1.DERInteger,Je.asn1.ASN1Object),Je.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=Je.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}Je.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var i="0"+e;this.hTLV=null,this.isModified=!0,this.hV=i+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0),e+="0000000".substr(0,t);for(var i="",n=0;n<e.length-1;n+=8){var r=e.substr(n,8),s=parseInt(r,2).toString(16);1==s.length&&(s="0"+s),i+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+i},this.setByBooleanArray=function(e){for(var t="",i=0;i<e.length;i++)1==e[i]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),i=0;i<e;i++)t[i]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},Nt(Je.asn1.DERBitString,Je.asn1.ASN1Object),Je.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=Je.asn1.ASN1Util.newObject(e.obj);e.hex=t.tohex()}Je.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},Nt(Je.asn1.DEROctetString,Je.asn1.DERAbstractString),Je.asn1.DERNull=function(){Je.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},Nt(Je.asn1.DERNull,Je.asn1.ASN1Object),Je.asn1.DERObjectIdentifier=function(e){Je.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){var t=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},i=function(e){var i="",n=parseInt(e,10).toString(2),r=7-n.length%7;7==r&&(r=0);for(var s="",a=0;a<r;a++)s+="0";n=s+n;for(a=0;a<n.length-1;a+=7){var o=n.substr(a,7);a!=n.length-7&&(o="1"+o),i+=t(parseInt(o,2))}return i};try{if(!e.match(/^[0-9.]+$/))return null;var n="",r=e.split("."),s=40*parseInt(r[0],10)+parseInt(r[1],10);n+=t(s),r.splice(0,2);for(var a=0;a<r.length;a++)n+=i(r[a]);return n}catch(e){return null}}(e);if(null==t)throw new Error("malformed oid string: "+e);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.setValueName=function(e){var t=Je.asn1.x509.OID.name2oid(e);if(""===t)throw new Error("DERObjectIdentifier oidName undefined: "+e);this.setValueOidString(t)},this.setValueNameOrOid=function(e){e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){"string"==typeof e?this.setValueNameOrOid(e):void 0!==e.oid?this.setValueNameOrOid(e.oid):void 0!==e.name?this.setValueNameOrOid(e.name):void 0!==e.hex&&this.setValueHex(e.hex)},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.DERObjectIdentifier,Je.asn1.ASN1Object),Je.asn1.DEREnumerated=function(e){Je.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=Rt(e)},this.setByInteger=function(e){var t=new de(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},Nt(Je.asn1.DEREnumerated,Je.asn1.ASN1Object),Je.asn1.DERUTF8String=function(e){Je.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},Nt(Je.asn1.DERUTF8String,Je.asn1.DERAbstractString),Je.asn1.DERNumericString=function(e){Je.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},Nt(Je.asn1.DERNumericString,Je.asn1.DERAbstractString),Je.asn1.DERPrintableString=function(e){Je.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},Nt(Je.asn1.DERPrintableString,Je.asn1.DERAbstractString),Je.asn1.DERTeletexString=function(e){Je.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},Nt(Je.asn1.DERTeletexString,Je.asn1.DERAbstractString),Je.asn1.DERIA5String=function(e){Je.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},Nt(Je.asn1.DERIA5String,Je.asn1.DERAbstractString),Je.asn1.DERVisibleString=function(e){Je.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},Nt(Je.asn1.DERVisibleString,Je.asn1.DERAbstractString),Je.asn1.DERBMPString=function(e){Je.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},Nt(Je.asn1.DERBMPString,Je.asn1.DERAbstractString),Je.asn1.DERUTCTime=function(e){Je.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.params=void 0,this.getFreshValueHex=function(){var e=this.params;if(null==this.params&&(e={date:new Date}),"string"==typeof e){if(!e.match(/^[0-9]{12}Z$/)&&!e.match(/^[0-9]{12}\.[0-9]+Z$/))throw new Error("malformed string for UTCTime: "+e);this.hV=tt(e)}else if(null!=e.str)this.hV=tt(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=tt(this.formatDate(t,"utc",!0))}else if(null!=e.date&&e.date instanceof Date){var i=!0===e.millis;this.hV=tt(this.formatDate(e.date,"utc",i))}else e instanceof Date&&(this.hV=tt(this.formatDate(e,"utc")));if(null==this.hV)throw new Error("parameter not specified properly for UTCTime");return this.hV},null!=e&&this.setByParam(e)},Nt(Je.asn1.DERUTCTime,Je.asn1.DERAbstractTime),Je.asn1.DERGeneralizedTime=function(e){Je.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.params=e,this.getFreshValueHex=function(){var e=this.params;if(null==this.params&&(e={date:new Date}),"string"==typeof e){if(!e.match(/^[0-9]{14}Z$/)&&!e.match(/^[0-9]{14}\.[0-9]+Z$/))throw new Error("malformed string for GeneralizedTime: "+e);this.hV=tt(e)}else if(null!=e.str)this.hV=tt(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=tt(this.formatDate(t,"gen",!0))}else if(null!=e.date&&e.date instanceof Date){var i=!0===e.millis;this.hV=tt(this.formatDate(e.date,"gen",i))}else e instanceof Date&&(this.hV=tt(this.formatDate(e,"gen")));if(null==this.hV)throw new Error("parameter not specified properly for GeneralizedTime");return this.hV},null!=e&&this.setByParam(e)},Nt(Je.asn1.DERGeneralizedTime,Je.asn1.DERAbstractTime),Je.asn1.DERSequence=function(e){Je.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++){e+=this.asn1Array[t].tohex()}return this.hV=e,this.hV}},Nt(Je.asn1.DERSequence,Je.asn1.DERAbstractStructured),Je.asn1.DERSet=function(e){Je.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var i=this.asn1Array[t];e.push(i.tohex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},Nt(Je.asn1.DERSet,Je.asn1.DERAbstractStructured),Je.asn1.DERTaggedObject=function(e){Je.asn1.DERTaggedObject.superclass.constructor.call(this);var t=Je.asn1,i=Qe,n=i.getV;i.isASN1HEX;var r=t.ASN1Util.newObject;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.params={tag:"a0",explicit:!0},this.setASN1Object=function(e,t,i){this.params={tag:t,explicit:e,obj:i}},this.getFreshValueHex=function(){var e=this.params;if(null==e.explicit&&(e.explicit=!0),null!=e.tage&&(e.tag=e.tage,e.explicit=!0),null!=e.tagi&&(e.tag=e.tagi,e.explicit=!1),null!=e.str)this.hV=at(e.str);else if(null!=e.hex)this.hV=e.hex;else{if(null==e.obj)throw new Error("str, hex nor obj not specified");var i;e.obj instanceof t.ASN1Object?i=e.obj.tohex():"object"==typeof e.obj&&(i=r(e.obj).tohex()),e.explicit?this.hV=i:this.hV=n(i,0)}return null==e.tag&&(e.tag="a0"),this.hT=e.tag,this.hTLV=null,this.isModified=!0,this.hV},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.DERTaggedObject,Je.asn1.ASN1Object);var Je,Ze,Xe,Qe=new function(){};function et(e){for(var t="",i=0;i<e.length;i++){var n=e[i].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function tt(e){return et(function(e){for(var t=new Array,i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}(e))}function it(e){return e=(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function nt(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),e=(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function rt(e){return e.length%2==1&&(e="0"+e),it(oe(e))}function st(e){return ce(nt(e))}function at(e){return gt(Ct(e)).toLowerCase()}function ot(e){try{return decodeURIComponent(ft(e))}catch(e){return null}}function ct(e){return ot(function(e){for(var t=e.match(/.{1,2}/g),i=[],n=0;n<t.length;n++){var r=parseInt(t[n],16);161<=r&&r<=191?(i.push("c2"),i.push(t[n])):192<=r&&r<=255?(i.push("c3"),i.push((r-64).toString(16))):i.push(t[n])}return i.join("")}(e))}function dt(e){for(var t="",i=0;i<e.length-1;i+=2)t+=String.fromCharCode(parseInt(e.substr(i,2),16));return t}function lt(e){for(var t="",i=0;i<e.length;i++)t+=("0"+e.charCodeAt(i).toString(16)).slice(-2);return t}function ht(e,t){return"-----BEGIN "+t+"-----\r\n"+function(e,t){return(e=e.replace(new RegExp("(.{"+t+"})","g"),"$1\r\n")).replace(/\s+$/,"")}(function(e){return oe(e)}(e),64)+"\r\n-----END "+t+"-----\r\n"}function ut(e,t){if(-1==e.indexOf("-----BEGIN "))throw new Error("can't find PEM header");return function(e){return ce(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function pt(e){return Math.round(function(e){var t,i,n,r,s,a,o,c,d,l;if(e=function(e){return e.match(/^[0-9]{12}Z$/)||e.match(/^[0-9]{12}[.][0-9]*Z$/)?e.match(/^[0-4]/)?"20"+e:"19"+e:e}(e),l=e.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return t=parseInt(l[1]),i=parseInt(l[2])-1,n=parseInt(l[3]),r=parseInt(l[4]),s=parseInt(l[5]),a=parseInt(l[6]),o=0,""!==(c=l[7])&&(d=(c.substr(1)+"00").substr(0,3),o=parseInt(d)),Date.UTC(t,i,n,r,s,a,o);throw new Error("unsupported zulu format: "+e)}(e)/1e3)}function gt(e){return e.replace(/%/g,"")}function ft(e){return e.replace(/(..)/g,"%$1")}function mt(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var i=(e=e.toLowerCase()).split(":").length-1;if(i<2)throw t;var n=":".repeat(7-i+2),r=(e=e.replace("::",n)).split(":");if(8!=r.length)throw t;for(var s=0;s<8;s++)r[s]=("0000"+r[s]).slice(-4);return r.join("")}function vt(e){if(!e.match(/^[0-9A-Fa-f]{32}$/))throw new Error("malformed IPv6 address: "+e);var t=(e=e.toLowerCase()).match(/.{1,4}/g);t=t.map((function(e){return e.replace(/^0+/,"")})),t=t.map((function(e){return""==e?"0":e}));var i=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null==i)return e.slice(1,-1);var n=i.sort().slice(-1)[0];return"::"!=(e=e.replace(n.substr(0,n.length-1),":")).substr(0,2)&&(e=e.substr(1)),"::"!=e.substr(-2,2)&&(e=e.substr(0,e.length-1)),e}function yt(e){var t=new Error("malformed hex value");if(!e.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(8==e.length){try{return parseInt(e.substr(0,2),16)+"."+parseInt(e.substr(2,2),16)+"."+parseInt(e.substr(4,2),16)+"."+parseInt(e.substr(6,2),16)}catch(e){throw t}}else{if(16!=e.length){if(32==e.length)return vt(e);if(64==e.length){try{return vt(e.substr(0,32))+"/"+St(e.substr(32))}catch(e){throw t}return}return e}try{return yt(e.substr(0,8))+"/"+St(e.substr(8))}catch(e){throw t}}}function St(e){var t,i=new Error("malformed mask");try{t=new de(e,16).toString(2)}catch(e){throw i}if(!t.match(/^1*0*$/))throw i;return t.replace(/0+$/,"").length}function bt(e){var t=new Error("malformed IP address");if(!(e=e.toLowerCase(e)).match(/^[0-9a-f.:/]+$/))throw t;if(!e.match(/^[0-9.]+$/)){var i;if(e.match(/^[0-9.]+\/[0-9]+$/))return bt((i=e.split("/"))[0])+wt(parseInt(i[1]),32);if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return mt(e);if(e.match(/^[0-9a-f:]+\/[0-9]+$/)&&-1!==e.indexOf(":"))return mt((i=e.split("/"))[0])+wt(parseInt(i[1]),128);throw t}var n=e.split(".");if(4!==n.length)throw t;var r="";try{for(var s=0;s<4;s++){r+=("0"+parseInt(n[s]).toString(16)).slice(-2)}return r}catch(e){throw t}}function wt(e,t){return 32==t&&0==e?"00000000":128==t&&0==e?"00000000000000000000000000000000":new de(Array(e+1).join("1")+Array(t-e+1).join("0"),2).toString(16)}function Et(e){var t=e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),i=parseInt(e.substr(2),16);if(0==t&i<128)return String.fromCharCode(i);if(t<8){var n=128|63&i;return ot((192|(7&t)<<3|(192&i)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&i)>>6;var r=128|63&i;return ot((224|(240&t)>>4).toString(16)+n.toString(16)+r.toString(16))}));return t.join("")}function Ct(e){for(var t=encodeURIComponent(e),i="",n=0;n<t.length;n++)"%"==t[n]?(i+=t.substr(n,3),n+=2):i=i+"%"+tt(t[n]);return i}function $t(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function Tt(e){return!!e.match(/^[0-9A-Za-z-_.]+$/)}function _t(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}function xt(e){if(!$t(e))return null;try{var t=[],i=e.substr(0,2),n=parseInt(i,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var r=e.substr(2),s=[],a=0;a<r.length/2;a++)s.push(parseInt(r.substr(2*a,2),16));var o=[],c="";for(a=0;a<s.length;a++)128&s[a]?c+=At((127&s[a]).toString(2),7):(c+=At((127&s[a]).toString(2),7),o.push(new String(parseInt(c,2))),c="");var d=t.join(".");return o.length>0&&(d=d+"."+o.join(".")),d}catch(e){return null}}function It(e){return Rt(new de(String(e),10))}function Rt(e){var t=e.toString(16);if("-"!=t.substr(0,1))return t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t),t;var i=t.substr(1).length;i%2==1?i+=1:t.match(/^[0-7]/)||(i+=2);for(var n="",r=0;r<i;r++)n+="f";return t=new de(n,16).xor(e).add(de.ONE).toString(16).replace(/^-/,"")}Qe.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var i=parseInt(e.substr(t+3,1));return 0==i?-1:0<i&&i<10?i+1:-2},Qe.getL=function(e,t){var i=Qe.getLblen(e,t);return i<1?"":e.substr(t+2,2*i)},Qe.getVblen=function(e,t){var i;return""==(i=Qe.getL(e,t))?-1:("8"===i.substr(0,1)?new de(i.substr(2),16):new de(i,16)).intValue()},Qe.getVidx=function(e,t){var i=Qe.getLblen(e,t);return i<0?i:t+2*(i+1)},Qe.getV=function(e,t){var i=Qe.getVidx(e,t),n=Qe.getVblen(e,t);return e.substr(i,2*n)},Qe.getTLV=function(e,t){return e.substr(t,2)+Qe.getL(e,t)+Qe.getV(e,t)},Qe.getTLVblen=function(e,t){return 2+2*Qe.getLblen(e,t)+2*Qe.getVblen(e,t)},Qe.getNextSiblingIdx=function(e,t){return Qe.getVidx(e,t)+2*Qe.getVblen(e,t)},Qe.getChildIdx=function(e,t){var i,n,r,s=Qe,a=[];i=s.getVidx(e,t),n=2*s.getVblen(e,t),"03"==e.substr(t,2)&&(i+=2,n-=2),r=0;for(var o=i;r<=n;){var c=s.getTLVblen(e,o);if((r+=c)<=n&&a.push(o),o+=c,r>=n)break}return a},Qe.getNthChildIdx=function(e,t,i){return Qe.getChildIdx(e,t)[i]},Qe.getIdxbyList=function(e,t,i,n){var r,s,a=Qe;return 0==i.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(r=i.shift())>=(s=a.getChildIdx(e,t)).length?-1:a.getIdxbyList(e,s[r],i,n)},Qe.getIdxbyListEx=function(e,t,i,n){var r,s,a=Qe;if(0==i.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;r=i.shift(),s=a.getChildIdx(e,t);for(var o=0,c=0;c<s.length;c++){var d=e.substr(s[c],2);if("number"==typeof r&&!a.isContextTag(d)&&o==r||"string"==typeof r&&a.isContextTag(d,r))return a.getIdxbyListEx(e,s[c],i,n);a.isContextTag(d)||o++}return-1},Qe.getTLVbyList=function(e,t,i,n){var r=Qe,s=r.getIdxbyList(e,t,i,n);return-1==s||s>=e.length?null:r.getTLV(e,s)},Qe.getTLVbyListEx=function(e,t,i,n){var r=Qe,s=r.getIdxbyListEx(e,t,i,n);return-1==s?null:r.getTLV(e,s)},Qe.getVbyList=function(e,t,i,n,r){var s,a,o=Qe;return-1==(s=o.getIdxbyList(e,t,i,n))||s>=e.length?null:(a=o.getV(e,s),!0===r&&(a=a.substr(2)),a)},Qe.getVbyListEx=function(e,t,i,n,r){var s,a,o=Qe;return-1==(s=o.getIdxbyListEx(e,t,i,n))?null:(a=o.getV(e,s),"03"==e.substr(s,2)&&!1!==r&&(a=a.substr(2)),a)},Qe.getInt=function(e,t,i){null==i&&(i=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return i;var r=Qe.getV(e,t);return"02"==n?parseInt(r,16):function(e){if(e.length%2!=0)return-1;if(e=e.toLowerCase(),null==e.match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var i=parseInt(t,16);if(i>7)return-1;var n=e.substr(2),r=parseInt(n,16).toString(2);"0"==r&&(r="00000000"),r=r.slice(0,0-i);var s=parseInt(r,2);return NaN==s?-1:s}catch(e){return-1}}(r)}catch(e){return i}},Qe.getOID=function(e,t,i){null==i&&(i=null);try{return"06"!=e.substr(t,2)?i:xt(Qe.getV(e,t))}catch(e){return i}},Qe.getOIDName=function(e,t,i){null==i&&(i=null);try{var n=Qe.getOID(e,t,i);if(n==i)return i;var r=Je.asn1.x509.OID.oid2name(n);return""==r?n:r}catch(e){return i}},Qe.getString=function(e,t,i){null==i&&(i=null);try{return dt(Qe.getV(e,t))}catch(e){return i}},Qe.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},i=[],n=e.substr(0,2),r=parseInt(n,16);i[0]=new String(Math.floor(r/40)),i[1]=new String(r%40);for(var s=e.substr(2),a=[],o=0;o<s.length/2;o++)a.push(parseInt(s.substr(2*o,2),16));var c=[],d="";for(o=0;o<a.length;o++)128&a[o]?d+=t((127&a[o]).toString(2),7):(d+=t((127&a[o]).toString(2),7),c.push(new String(parseInt(d,2))),d="");var l=i.join(".");return c.length>0&&(l=l+"."+c.join(".")),l},Qe.dump=function(e,t,i,n){var r=Qe,s=r.getV,a=r.dump,o=r.getChildIdx,c=e;e instanceof Je.asn1.ASN1Object&&(c=e.tohex());var d=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===i&&(i=0),void 0===n&&(n="");var l,h=t.ommit_long_octet;if("01"==(l=c.substr(i,2)))return"00"==(u=s(c,i))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==l)return n+"INTEGER "+d(u=s(c,i),h)+"\n";if("03"==l){var u=s(c,i);if(r.isASN1HEX(u.substr(2))){var p=n+"BITSTRING, encapsulates\n";return p+=a(u.substr(2),t,0,n+" ")}return n+"BITSTRING "+d(u,h)+"\n"}if("04"==l){u=s(c,i);if(r.isASN1HEX(u)){p=n+"OCTETSTRING, encapsulates\n";return p+=a(u,t,0,n+" ")}return n+"OCTETSTRING "+d(u,h)+"\n"}if("05"==l)return n+"NULL\n";if("06"==l){var g=s(c,i),f=Je.asn1.ASN1Util.oidHexToInt(g),m=Je.asn1.x509.OID.oid2name(f),v=f.replace(/\./g," ");return""!=m?n+"ObjectIdentifier "+m+" ("+v+")\n":n+"ObjectIdentifier ("+v+")\n"}if("0a"==l)return n+"ENUMERATED "+parseInt(s(c,i))+"\n";if("0c"==l)return n+"UTF8String '"+ot(s(c,i))+"'\n";if("13"==l)return n+"PrintableString '"+ot(s(c,i))+"'\n";if("14"==l)return n+"TeletexString '"+ot(s(c,i))+"'\n";if("16"==l)return n+"IA5String '"+ot(s(c,i))+"'\n";if("17"==l)return n+"UTCTime "+ot(s(c,i))+"\n";if("18"==l)return n+"GeneralizedTime "+ot(s(c,i))+"\n";if("1a"==l)return n+"VisualString '"+ot(s(c,i))+"'\n";if("1e"==l)return n+"BMPString '"+Et(s(c,i))+"'\n";if("30"==l){if("3000"==c.substr(i,4))return n+"SEQUENCE {}\n";p=n+"SEQUENCE\n";var y=t;if((2==(w=o(c,i)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){m=r.oidname(s(c,w[0]));var S=JSON.parse(JSON.stringify(t));S.x509ExtName=m,y=S}for(var b=0;b<w.length;b++)p+=a(c,y,w[b],n+" ");return p}if("31"==l){p=n+"SET\n";var w=o(c,i);for(b=0;b<w.length;b++)p+=a(c,t,w[b],n+" ");return p}if(0!=(128&(l=parseInt(l,16)))){var E=31&l;if(0!=(32&l)){for(p=n+"["+E+"]\n",w=o(c,i),b=0;b<w.length;b++)p+=a(c,t,w[b],n+" ");return p}u=s(c,i);if(Qe.isASN1HEX(u)){var p=n+"["+E+"]\n";return p+=a(u,t,0,n+" ")}return("68747470"==u.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==E)&&(u=ot(u)),p=n+"["+E+"] "+u+"\n"}return n+"UNKNOWN("+l+") "+s(c,i)+"\n"},Qe.parse=function(e){var t=Qe,i=t.parse,n=t.isASN1HEX,r=t.getV,s=t.getTLV,a=t.getChildIdx,o=Je.asn1,c=o.ASN1Util.oidHexToInt,d=o.x509.OID.oid2name,l=ot,h=Et,u=ct,p={"0c":"utf8str",12:"numstr",13:"prnstr",14:"telstr",16:"ia5str",17:"utctime",18:"gentime","1a":"visstr","1e":"bmpstr",30:"seq",31:"set"},g=e.substr(0,2),f={},m=r(e,0);if("01"==g)return"0101ff"==e?{bool:!0}:{bool:!1};if("02"==g)return{int:{hex:m}};if("03"==g)try{if("00"!=m.substr(0,2))throw"not encap";var v=m.substr(2);if(!n(v))throw"not encap";return{bitstr:{obj:i(v)}}}catch(e){var y=null;return m.length<=10&&(y=function(e){if("string"!=typeof e)return null;if(e.length%2!=0)return null;if(!e.match(/^[0-9a-f]+$/))return null;try{var t=parseInt(e.substr(0,2),16);if(t<0||7<t)return null;for(var i=e.substr(2),n="",r=0;r<i.length;r+=2){var s=i.substr(r,2),a=parseInt(s,16).toString(2);n+=a=("0000000"+a).slice(-8)}return n.substr(0,n.length-t)}catch(e){return null}}(m)),null==y?{bitstr:{hex:m}}:{bitstr:{bin:y}}}else if("04"==g)try{if(!n(m))throw"not encap";return{octstr:{obj:i(m)}}}catch(e){return{octstr:{hex:m}}}else{if("05"==g)return{null:""};if("06"==g){var S=c(m),b=d(S);return""==b?{oid:S}:{oid:b}}if("0a"==g)return m.length>4?{enum:{hex:m}}:{enum:parseInt(m,16)};if("30"==g||"31"==g)return f[p[g]]=function(e){for(var t=[],n=a(e,0),r=0;r<n.length;r++){var o=n[r],c=s(e,o),d=i(c);t.push(d)}return t}(e),f;if("14"==g){var w=u(m);return f[p[g]]={str:w},f}if("1e"==g){w=h(m);return f[p[g]]={str:w},f}if(-1!=":0c:12:13:16:17:18:1a:".indexOf(g)){w=l(m);return f[p[g]]={str:w},f}if(g.match(/^8[0-9]$/))return null==(w=l(m))|""==w||null!=w.match(/[\x00-\x1F\x7F-\x9F]/)||null!=w.match(/[\u0000-\u001F\u0080–\u009F]/)?{tag:{tag:g,explicit:!1,hex:m}}:{tag:{tag:g,explicit:!1,str:w}};if(!g.match(/^a[0-9]$/)){var E=new Je.asn1.ASN1Object;return E.hV=m,{asn1:{tlv:g+E.getLengthHexFromValue()+m}}}try{if(!n(m))throw new Error("not encap");return{tag:{tag:g,explicit:!0,obj:i(m)}}}catch(e){return{tag:{tag:g,explicit:!0,hex:m}}}}},Qe.isContextTag=function(e,t){var i,n;e=e.toLowerCase();try{i=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&i);try{return null!=t.match(/^\[[0-9]+\]$/)&&(!((n=parseInt(t.substr(1,t.length-1),10))>31)&&(128==(192&i)&&(31&i)==n))}catch(e){return!1}},Qe.isASN1HEX=function(e){var t=Qe;if(e.length%2==1)return!1;var i=t.getVblen(e,0),n=e.substr(0,2),r=t.getL(e,0);return e.length-n.length-r.length==2*i},Qe.checkStrictDER=function(e,t,i,n,r){var s=Qe;if(void 0===i){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!Je.lang.String.isHex(e))throw new Error("not hex string");i=e.length,r=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(s.getL(e,t).length>2*r)throw new Error("L of TLV too long: idx="+t);var a=s.getVblen(e,t);if(a>n)throw new Error("value of L too long than hex: idx="+t);var o=s.getTLV(e,t),c=o.length-2-s.getL(e,t).length;if(c!==2*a)throw new Error("V string length and L's value not the same:"+c+"/"+2*a);if(0===t&&e.length!=o.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+o.length);var d=e.substr(t,2);if("02"===d){var l=s.getVidx(e,t);if("00"==e.substr(l,2)&&e.charCodeAt(l+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(d,16)){for(var h=s.getVblen(e,t),u=0,p=s.getChildIdx(e,t),g=0;g<p.length;g++){u+=s.getTLV(e,p[g]).length,s.checkStrictDER(e,p[g],i,n,r)}if(2*h!=u)throw new Error("sum of children's TLV length and L unmatch: "+2*h+"!="+u)}},Qe.oidname=function(e){var t=Je.asn1;Je.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var i=t.x509.OID.oid2name(e);return""===i&&(i=e),i},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.x509&&Je.asn1.x509||(Je.asn1.x509={}),Je.asn1.x509.Certificate=function(e){Je.asn1.x509.Certificate.superclass.constructor.call(this);var t=Je.asn1,i=t.DERBitString,n=t.DERSequence,r=t.x509,s=r.TBSCertificate,a=r.AlgorithmIdentifier;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.sigalg;null!=e.sigalg.name&&(t=e.sigalg.name);var i=e.tbsobj.tohex(),n=new Je.crypto.Signature({alg:t});n.init(e.cakey),n.updateHex(i),e.sighex=n.sign()},this.getPEM=function(){return ht(this.tohex(),"CERTIFICATE")},this.tohex=function(){var e=this.params;if(null!=e.tbsobj&&null!=e.tbsobj||(e.tbsobj=new s(e)),null==e.sighex&&null!=e.cakey&&this.sign(),null==e.sighex)throw new Error("sighex or cakey parameter not defined");var t=[];return t.push(e.tbsobj),t.push(new a({name:e.sigalg})),t.push(new i({hex:"00"+e.sighex})),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},Nt(Je.asn1.x509.Certificate,Je.asn1.ASN1Object),Je.asn1.x509.TBSCertificate=function(e){Je.asn1.x509.TBSCertificate.superclass.constructor.call(this);var t=Je.asn1,i=t.x509,n=t.DERTaggedObject,r=t.DERInteger,s=t.DERSequence,a=i.AlgorithmIdentifier,o=i.Time,c=i.X500Name,d=i.Extensions,l=i.SubjectPublicKeyInfo;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=[],t=this.params;if(null!=t.version||1!=t.version){var i=2;null!=t.version&&(i=t.version-1);var h=new n({obj:new r({int:i})});e.push(h)}return e.push(new r(t.serial)),e.push(new a({name:t.sigalg})),e.push(new c(t.issuer)),e.push(new s({array:[new o(t.notbefore),new o(t.notafter)]})),e.push(new c(t.subject)),e.push(new l(kt.getKey(t.sbjpubkey))),void 0!==t.ext&&t.ext.length>0&&e.push(new n({tag:"a3",obj:new d(t.ext)})),new Je.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.TBSCertificate,Je.asn1.ASN1Object),Je.asn1.x509.Extensions=function(e){Je.asn1.x509.Extensions.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.x509;this.aParam=[],this.setByParam=function(e){this.aParam=e},this.tohex=function(){for(var e=[],t=0;t<this.aParam.length;t++){var r=this.aParam[t],s=r.extname,a=null;if(null!=r.extn)a=new n.PrivateExtension(r);else if("subjectKeyIdentifier"==s)a=new n.SubjectKeyIdentifier(r);else if("keyUsage"==s)a=new n.KeyUsage(r);else if("subjectAltName"==s)a=new n.SubjectAltName(r);else if("issuerAltName"==s)a=new n.IssuerAltName(r);else if("basicConstraints"==s)a=new n.BasicConstraints(r);else if("nameConstraints"==s)a=new n.NameConstraints(r);else if("cRLDistributionPoints"==s)a=new n.CRLDistributionPoints(r);else if("certificatePolicies"==s)a=new n.CertificatePolicies(r);else if("policyMappings"==s)a=new n.PolicyMappings(r);else if("policyConstraints"==s)a=new n.PolicyConstraints(r);else if("inhibitAnyPolicy"==s)a=new n.InhibitAnyPolicy(r);else if("authorityKeyIdentifier"==s)a=new n.AuthorityKeyIdentifier(r);else if("extKeyUsage"==s)a=new n.ExtKeyUsage(r);else if("authorityInfoAccess"==s)a=new n.AuthorityInfoAccess(r);else if("cRLNumber"==s)a=new n.CRLNumber(r);else if("cRLReason"==s)a=new n.CRLReason(r);else if("ocspNonce"==s)a=new n.OCSPNonce(r);else if("ocspNoCheck"==s)a=new n.OCSPNoCheck(r);else if("adobeTimeStamp"==s)a=new n.AdobeTimeStamp(r);else{if("subjectDirectoryAttributes"!=s)throw new Error("extension not supported:"+JSON.stringify(r));a=new n.SubjectDirectoryAttributes(r)}null!=a&&e.push(a)}return new i({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.x509.Extensions,Je.asn1.ASN1Object),Je.asn1.x509.Extension=function(e){Je.asn1.x509.Extension.superclass.constructor.call(this);var t=Je.asn1,i=t.DERObjectIdentifier,n=t.DEROctetString;t.DERBitString;var r=t.DERBoolean,s=t.DERSequence;this.tohex=function(){var e=new i({oid:this.oid}),t=new n({hex:this.getExtnValueHex()}),a=new Array;return a.push(e),this.critical&&a.push(new r),a.push(t),new s({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.critical=!1,void 0!==e&&void 0!==e.critical&&(this.critical=e.critical)},Nt(Je.asn1.x509.Extension,Je.asn1.ASN1Object),Je.asn1.x509.KeyUsage=function(e){Je.asn1.x509.KeyUsage.superclass.constructor.call(this,e);var t=Error,i={digitalSignature:0,nonRepudiation:1,keyEncipherment:2,dataEncipherment:3,keyAgreement:4,keyCertSign:5,cRLSign:6,encipherOnly:7,decipherOnly:8};this.getExtnValueHex=function(){var e=this.getBinValue();return this.asn1ExtnValue=new Je.asn1.DERBitString({bin:e}),this.asn1ExtnValue.tohex()},this.getBinValue=function(){var e=this.params;if("object"!=typeof e||"object"!=typeof e.names&&"string"!=typeof e.bin)throw new t("parameter not yet set");if(null!=e.names)return Pt(e.names,i);if(null!=e.bin)return e.bin;throw new t("parameter not set properly")},this.oid="2.5.29.15",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.KeyUsage,Je.asn1.x509.Extension),Je.asn1.x509.BasicConstraints=function(e){Je.asn1.x509.BasicConstraints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERBoolean,n=t.DERInteger,r=t.DERSequence;this.getExtnValueHex=function(){var e=new Array;this.cA&&e.push(new i),this.pathLen>-1&&e.push(new n({int:this.pathLen}));var t=new r({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.oid="2.5.29.19",this.cA=!1,this.pathLen=-1,void 0!==e&&(void 0!==e.cA&&(this.cA=e.cA),void 0!==e.pathLen&&(this.pathLen=e.pathLen))},Nt(Je.asn1.x509.BasicConstraints,Je.asn1.x509.Extension),Je.asn1.x509.CRLDistributionPoints=function(e){Je.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],r=0;r<e.length;r++)if(e[r]instanceof Je.asn1.ASN1Object)n.push(e[r]);else{var s=new i.DistributionPoint(e[r]);n.push(s)}this.asn1ExtnValue=new t.DERSequence({array:n})},this.setByOneURI=function(e){var t=new i.DistributionPoint({fulluri:e});this.setByDPArray([t])},this.oid="2.5.29.31",void 0!==e&&(void 0!==e.array?this.setByDPArray(e.array):void 0!==e.uri&&this.setByOneURI(e.uri))},Nt(Je.asn1.x509.CRLDistributionPoints,Je.asn1.x509.Extension),Je.asn1.x509.DistributionPoint=function(e){Je.asn1.x509.DistributionPoint.superclass.constructor.call(this);var t=Je.asn1,i=t.x509.DistributionPointName;this.tohex=function(){var e=new t.DERSequence;if(null!=this.asn1DP){var i=new t.DERTaggedObject({explicit:!0,tag:"a0",obj:this.asn1DP});e.appendASN1Object(i)}return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.dpobj?this.asn1DP=e.dpobj:void 0!==e.dpname?this.asn1DP=new i(e.dpname):void 0!==e.fulluri&&(this.asn1DP=new i({full:[{uri:e.fulluri}]})))},Nt(Je.asn1.x509.DistributionPoint,Je.asn1.ASN1Object),Je.asn1.x509.DistributionPointName=function(e){Je.asn1.x509.DistributionPointName.superclass.constructor.call(this);var t=Je.asn1,i=t.DERTaggedObject;if(this.tohex=function(){if("full"!=this.type)throw new Error("currently type shall be 'full': "+this.type);return this.asn1Obj=new i({explicit:!1,tag:this.tag,obj:this.asn1V}),this.hTLV=this.asn1Obj.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e)if(t.x509.GeneralNames.prototype.isPrototypeOf(e))this.type="full",this.tag="a0",this.asn1V=e;else{if(void 0===e.full)throw new Error("This class supports GeneralNames only as argument");this.type="full",this.tag="a0",this.asn1V=new t.x509.GeneralNames(e.full)}},Nt(Je.asn1.x509.DistributionPointName,Je.asn1.ASN1Object),Je.asn1.x509.CertificatePolicies=function(e){Je.asn1.x509.CertificatePolicies.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509,n=t.DERSequence,r=i.PolicyInformation;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++)e.push(new r(this.params.array[t]));var i=new n({array:e});return this.asn1ExtnValue=i,this.asn1ExtnValue.tohex()},this.oid="2.5.29.32",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.CertificatePolicies,Je.asn1.x509.Extension),Je.asn1.x509.PolicyInformation=function(e){Je.asn1.x509.PolicyInformation.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier,r=t.x509.PolicyQualifierInfo;this.params=null,this.tohex=function(){if(void 0===this.params.policyoid&&void 0===this.params.array)throw new Error("parameter oid and array missing");var e=[new n(this.params.policyoid)];if(void 0!==this.params.array){for(var t=[],s=0;s<this.params.array.length;s++)t.push(new r(this.params.array[s]));t.length>0&&e.push(new i({array:t}))}return new i({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyInformation,Je.asn1.ASN1Object),Je.asn1.x509.PolicyQualifierInfo=function(e){Je.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.DERIA5String,r=t.DERObjectIdentifier,s=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new i({array:[new r({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new i({array:[new r({oid:"1.3.6.1.5.5.7.2.2"}),new s(this.params.unotice)]}).tohex():void 0},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyQualifierInfo,Je.asn1.ASN1Object),Je.asn1.x509.UserNotice=function(e){Je.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=Je.asn1.DERSequence;Je.asn1.DERInteger;var i=Je.asn1.x509.DisplayText,n=Je.asn1.x509.NoticeReference;this.params=null,this.tohex=function(){var e=[];return void 0!==this.params.noticeref&&e.push(new n(this.params.noticeref)),void 0!==this.params.exptext&&e.push(new i(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.UserNotice,Je.asn1.ASN1Object),Je.asn1.x509.NoticeReference=function(e){Je.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=Je.asn1.DERSequence,i=Je.asn1.DERInteger,n=Je.asn1.x509.DisplayText;this.params=null,this.tohex=function(){var e=[];if(void 0!==this.params.org&&e.push(new n(this.params.org)),void 0!==this.params.noticenum){for(var r=[],s=this.params.noticenum,a=0;a<s.length;a++)r.push(new i(s[a]));e.push(new t({array:r}))}if(0==e.length)throw new Error("parameter is empty");return new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.NoticeReference,Je.asn1.ASN1Object),Je.asn1.x509.DisplayText=function(e){Je.asn1.x509.DisplayText.superclass.constructor.call(this,e),this.hT="0c",void 0!==e&&("ia5"===e.type?this.hT="16":"vis"===e.type?this.hT="1a":"bmp"===e.type&&(this.hT="1e"))},Nt(Je.asn1.x509.DisplayText,Je.asn1.DERAbstractString),Je.asn1.x509.PolicyMappings=function(e){Je.asn1.x509.PolicyMappings.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){for(var e=this.params,t=[],n=0;n<e.array.length;n++){var r=e.array[n];t.push({seq:[{oid:r[0]},{oid:r[1]}]})}return this.asn1ExtnValue=i({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.33",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyMappings,Je.asn1.x509.Extension),Je.asn1.x509.PolicyConstraints=function(e){Je.asn1.x509.PolicyConstraints.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];return null!=e.reqexp&&t.push({tag:{tagi:"80",obj:{int:e.reqexp}}}),null!=e.inhibit&&t.push({tag:{tagi:"81",obj:{int:e.inhibit}}}),this.asn1ExtnValue=i({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.36",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyConstraints,Je.asn1.x509.Extension),Je.asn1.x509.InhibitAnyPolicy=function(e){Je.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=i({int:this.params.skip}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.54",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.InhibitAnyPolicy,Je.asn1.x509.Extension),Je.asn1.x509.NameConstraints=function(e){Je.asn1.x509.NameConstraints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509,n=t.ASN1Util.newObject,r=i.GeneralSubtree;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];if(null!=e.permit&&null!=e.permit.length){for(var i=[],s=0;s<e.permit.length;s++)i.push(new r(e.permit[s]));t.push({tag:{tagi:"a0",obj:{seq:i}}})}if(null!=e.exclude&&null!=e.exclude.length){var a=[];for(s=0;s<e.exclude.length;s++)a.push(new r(e.exclude[s]));t.push({tag:{tagi:"a1",obj:{seq:a}}})}return this.asn1ExtnValue=n({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.30",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.NameConstraints,Je.asn1.x509.Extension),Je.asn1.x509.GeneralSubtree=function(e){Je.asn1.x509.GeneralSubtree.superclass.constructor.call(this);var t=Je.asn1,i=t.x509.GeneralName,n=t.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params,t=[new i(e)];return null!=e.min&&t.push({tag:{tagi:"80",obj:{int:e.min}}}),null!=e.max&&t.push({tag:{tagi:"81",obj:{int:e.max}}}),n({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.GeneralSubtree,Je.asn1.ASN1Object),Je.asn1.x509.ExtKeyUsage=function(e){Je.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,e);var t=Je.asn1;this.setPurposeArray=function(e){this.asn1ExtnValue=new t.DERSequence;for(var i=0;i<e.length;i++){var n=new t.DERObjectIdentifier(e[i]);this.asn1ExtnValue.appendASN1Object(n)}},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.37",void 0!==e&&void 0!==e.array&&this.setPurposeArray(e.array)},Nt(Je.asn1.x509.ExtKeyUsage,Je.asn1.x509.Extension),Je.asn1.x509.AuthorityKeyIdentifier=function(e){Je.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,e);var t=Je,i=t.asn1,n=i.DERTaggedObject,r=i.x509.GeneralNames;t.crypto.Util.isKey,this.asn1KID=null,this.asn1CertIssuer=null,this.asn1CertSN=null,this.getExtnValueHex=function(){var e=new Array;this.asn1KID&&e.push(new n({explicit:!1,tag:"80",obj:this.asn1KID})),this.asn1CertIssuer&&e.push(new n({explicit:!1,tag:"a1",obj:new r([{dn:this.asn1CertIssuer}])})),this.asn1CertSN&&e.push(new n({explicit:!1,tag:"82",obj:this.asn1CertSN}));var t=new i.DERSequence({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.setKIDByParam=function(e){if(void 0!==e.str||void 0!==e.hex)this.asn1KID=new Je.asn1.DEROctetString(e);else if("object"==typeof e&&Je.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN ")){var t=e;"string"==typeof e&&(t=kt.getKey(e));var i=kt.getKeyID(t);this.asn1KID=new Je.asn1.DEROctetString({hex:i})}},this.setCertIssuerByParam=function(e){void 0!==e.str||void 0!==e.ldapstr||void 0!==e.hex||void 0!==e.certsubject||void 0!==e.certissuer?this.asn1CertIssuer=new Je.asn1.x509.X500Name(e):"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&-1!=e.indexOf("CERTIFICATE")&&(this.asn1CertIssuer=new Je.asn1.x509.X500Name({certissuer:e}))},this.setCertSNByParam=function(e){if(void 0!==e.str||void 0!==e.bigint||void 0!==e.hex)this.asn1CertSN=new Je.asn1.DERInteger(e);else if("string"==typeof e&&-1!=e.indexOf("BEGIN ")&&e.indexOf("CERTIFICATE")){var t=new Ht;t.readCertPEM(e);var i=t.getSerialNumberHex();this.asn1CertSN=new Je.asn1.DERInteger({hex:i})}},this.oid="2.5.29.35",void 0!==e&&(void 0!==e.kid&&this.setKIDByParam(e.kid),void 0!==e.issuer&&this.setCertIssuerByParam(e.issuer),void 0!==e.sn&&this.setCertSNByParam(e.sn),void 0!==e.issuersn&&"string"==typeof e.issuersn&&-1!=e.issuersn.indexOf("BEGIN ")&&e.issuersn.indexOf("CERTIFICATE")&&(this.setCertSNByParam(e.issuersn),this.setCertIssuerByParam(e.issuersn)))},Nt(Je.asn1.x509.AuthorityKeyIdentifier,Je.asn1.x509.Extension),Je.asn1.x509.SubjectKeyIdentifier=function(e){Je.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this,e);var t=Je.asn1.DEROctetString;this.asn1KID=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=this.asn1KID,this.asn1ExtnValue.tohex()},this.setKIDByParam=function(e){if(void 0!==e.str||void 0!==e.hex)this.asn1KID=new t(e);else if("object"==typeof e&&Je.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN")){var i=e;"string"==typeof e&&(i=kt.getKey(e));var n=kt.getKeyID(i);this.asn1KID=new Je.asn1.DEROctetString({hex:n})}},this.oid="2.5.29.14",void 0!==e&&void 0!==e.kid&&this.setKIDByParam(e.kid)},Nt(Je.asn1.x509.SubjectKeyIdentifier,Je.asn1.x509.Extension),Je.asn1.x509.AuthorityInfoAccess=function(e){Je.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,e),this.setAccessDescriptionArray=function(e){for(var t=new Array,i=Je.asn1,n=i.DERSequence,r=i.DERObjectIdentifier,s=i.x509.GeneralName,a=0;a<e.length;a++){var o,c=e[a];if(void 0!==c.ocsp)o=new n({array:[new r({oid:"1.3.6.1.5.5.7.48.1"}),new s({uri:c.ocsp})]});else{if(void 0===c.caissuer)throw new Error("unknown AccessMethod parameter: "+JSON.stringify(c));o=new n({array:[new r({oid:"1.3.6.1.5.5.7.48.2"}),new s({uri:c.caissuer})]})}t.push(o)}this.asn1ExtnValue=new n({array:t})},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.1.1",void 0!==e&&void 0!==e.array&&this.setAccessDescriptionArray(e.array)},Nt(Je.asn1.x509.AuthorityInfoAccess,Je.asn1.x509.Extension),Je.asn1.x509.SubjectAltName=function(e){Je.asn1.x509.SubjectAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new Je.asn1.x509.GeneralNames(e)},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.17",void 0!==e&&void 0!==e.array&&this.setNameArray(e.array)},Nt(Je.asn1.x509.SubjectAltName,Je.asn1.x509.Extension),Je.asn1.x509.IssuerAltName=function(e){Je.asn1.x509.IssuerAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new Je.asn1.x509.GeneralNames(e)},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.18",void 0!==e&&void 0!==e.array&&this.setNameArray(e.array)},Nt(Je.asn1.x509.IssuerAltName,Je.asn1.x509.Extension),Je.asn1.x509.SubjectDirectoryAttributes=function(e){Je.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.ASN1Util.newObject,r=t.x509.OID.name2oid;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++){var s=this.params.array[t];if(null==s.attr||null==s.array){var a={seq:[{oid:"1.2.3.4"},{set:[{utf8str:"DE"}]}]};if("dateOfBirth"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={gentime:s.str};else if("placeOfBirth"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={utf8str:s.str};else if("gender"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str};else if("countryOfCitizenship"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str};else{if("countryOfResidence"!=s.attr)throw new Error("unsupported attribute: "+s.attr);a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str}}e.push(new n(a))}else{var o={seq:[{oid:s.attr},{set:s.array}]};e.push(n(o))}}var c=new i({array:e});return this.asn1ExtnValue=c,this.asn1ExtnValue.tohex()},this.oid="2.5.29.9",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.SubjectDirectoryAttributes,Je.asn1.x509.Extension),Je.asn1.x509.PrivateExtension=function(e){Je.asn1.x509.PrivateExtension.superclass.constructor.call(this,e);var t=Je,i=t.lang.String.isHex,n=t.asn1,r=n.x509.OID.name2oid,s=n.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.oid=r(e.extname),this.params=e},this.getExtnValueHex=function(){if(null==this.params.extname||null==this.params.extn)throw new Error("extname or extnhex not specified");var e=this.params.extn;if("string"==typeof e&&i(e))return e;if("object"==typeof e)try{return s(e).tohex()}catch(e){}throw new Error("unsupported extn value")},null!=e&&this.setByParam(e)},Nt(Je.asn1.x509.PrivateExtension,Je.asn1.x509.Extension),Je.asn1.x509.CRL=function(e){Je.asn1.x509.CRL.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERBitString,r=t.x509,s=r.AlgorithmIdentifier,a=r.TBSCertList;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=new a(this.params).tohex(),t=new Je.crypto.Signature({alg:this.params.sigalg});t.init(this.params.cakey),t.updateHex(e);var i=t.sign();this.params.sighex=i},this.getPEM=function(){return ht(this.tohex(),"X509 CRL")},this.tohex=function(){var e=this.params;if(null==e.tbsobj&&(e.tbsobj=new a(e)),null==e.sighex&&null!=e.cakey&&this.sign(),null==e.sighex)throw new Error("sighex or cakey parameter not defined");var t=[];return t.push(e.tbsobj),t.push(new s({name:e.sigalg})),t.push(new n({hex:"00"+e.sighex})),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRL,Je.asn1.ASN1Object),Je.asn1.x509.TBSCertList=function(e){Je.asn1.x509.TBSCertList.superclass.constructor.call(this);var t=Je.asn1,i=t.DERInteger,n=t.DERSequence,r=t.DERTaggedObject;t.DERObjectIdentifier;var s=t.x509,a=s.AlgorithmIdentifier,o=s.Time,c=s.Extensions,d=s.X500Name;this.params=null,this.setByParam=function(e){this.params=e},this.getRevCertSequence=function(){for(var e=[],t=this.params.revcert,r=0;r<t.length;r++){var s=[new i(t[r].sn),new o(t[r].date)];null!=t[r].ext&&s.push(new c(t[r].ext)),e.push(new n({array:s}))}return new n({array:e})},this.tohex=function(){var e=[],t=this.params;if(null!=t.version){var s=t.version-1,l=new i({int:s});e.push(l)}if(e.push(new a({name:t.sigalg})),e.push(new d(t.issuer)),e.push(new o(t.thisupdate)),null!=t.nextupdate&&e.push(new o(t.nextupdate)),null!=t.revcert&&e.push(this.getRevCertSequence()),null!=t.ext){var h=new c(t.ext);e.push(new r({tag:"a0",explicit:!0,obj:h}))}return new n({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.TBSCertList,Je.asn1.ASN1Object),Je.asn1.x509.CRLEntry=function(e){Je.asn1.x509.CRLEntry.superclass.constructor.call(this);var t=Je.asn1;this.setCertSerial=function(e){this.sn=new t.DERInteger(e)},this.setRevocationDate=function(e){this.time=new t.x509.Time(e)},this.tohex=function(){var e=new t.DERSequence({array:[this.sn,this.time]});return this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.time&&this.setRevocationDate(e.time),void 0!==e.sn&&this.setCertSerial(e.sn))},Nt(Je.asn1.x509.CRLEntry,Je.asn1.ASN1Object),Je.asn1.x509.CRLNumber=function(e){Je.asn1.x509.CRLNumber.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DERInteger(this.params.num),this.asn1ExtnValue.tohex()},this.oid="2.5.29.20",null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRLNumber,Je.asn1.x509.Extension),Je.asn1.x509.CRLReason=function(e){Je.asn1.x509.CRLReason.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DEREnumerated(this.params.code),this.asn1ExtnValue.tohex()},this.oid="2.5.29.21",null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRLReason,Je.asn1.x509.Extension),Je.asn1.x509.OCSPNonce=function(e){Je.asn1.x509.OCSPNonce.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DEROctetString(this.params),this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.2",null!=e&&(this.params=e)},Nt(Je.asn1.x509.OCSPNonce,Je.asn1.x509.Extension),Je.asn1.x509.OCSPNoCheck=function(e){Je.asn1.x509.OCSPNoCheck.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DERNull,this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.5",null!=e&&(this.params=e)},Nt(Je.asn1.x509.OCSPNoCheck,Je.asn1.x509.Extension),Je.asn1.x509.AdobeTimeStamp=function(e){Je.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERInteger,n=t.DERBoolean,r=t.DERSequence,s=t.x509.GeneralName;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[new i(1)];return t.push(new s({uri:e.uri})),null!=e.reqauth&&t.push(new n(e.reqauth)),this.asn1ExtnValue=new r({array:t}),this.asn1ExtnValue.tohex()},this.oid="1.2.840.113583.1.1.9.1",void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.AdobeTimeStamp,Je.asn1.x509.Extension),Je.asn1.x509.X500Name=function(e){Je.asn1.x509.X500Name.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=Je.asn1,i=t.x509,n=i.RDN;this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var i=e.split("/");i.shift();for(var r=[],s=0;s<i.length;s++)if(i[s].match(/^[^=]+=.+$/))r.push(i[s]);else{var a=r.length-1;r[a]=r[a]+"/"+i[s]}for(s=0;s<r.length;s++)this.asn1Array.push(new n({str:r[s],rule:this.sRule}))},this.setByLdapString=function(e,t){void 0!==t&&(this.sRule=t);var n=i.X500Name.ldapToCompat(e);this.setByString(n,t)},this.setByObject=function(e,t){for(var i in void 0!==t&&(this.sRule=t),e)if(e.hasOwnProperty(i)){var r=new n({str:i+"="+e[i],rule:this.sRule});this.asn1Array?this.asn1Array.push(r):this.asn1Array=[r]}},this.setByParam=function(e){var t;(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.array)?this.paramArray=e.array:void 0!==e.str?this.setByString(e.str):void 0!==e.ldapstr?this.setByLdapString(e.ldapstr):void 0!==e.hex?this.hTLV=e.hex:void 0!==e.certissuer?((t=new Ht).readCertPEM(e.certissuer),this.hTLV=t.getIssuerHex()):void 0!==e.certsubject?((t=new Ht).readCertPEM(e.certsubject),this.hTLV=t.getSubjectHex()):"object"==typeof e&&void 0===e.certsubject&&void 0===e.certissuer&&this.setByObject(e)},this.tohex=function(){if("string"==typeof this.hTLV)return this.hTLV;if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var i={array:this.paramArray[e]};"utf8"!=this.sRule&&(i.rule=this.sRule);var r=new n(i);this.asn1Array.push(r)}var s=new t.DERSequence({array:this.asn1Array});return this.hTLV=s.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.X500Name,Je.asn1.ASN1Object),Je.asn1.x509.X500Name.compatToLDAP=function(e){if("/"!==e.substr(0,1))throw"malformed input";var t=(e=e.substr(1)).split("/");return t.reverse(),t=t.map((function(e){return e.replace(/,/,"\\,")})),t.join(",")},Je.asn1.x509.X500Name.onelineToLDAP=function(e){return Je.asn1.x509.X500Name.compatToLDAP(e)},Je.asn1.x509.X500Name.ldapToCompat=function(e){for(var t=e.split(","),i=!1,n=[],r=0;t.length>0;r++){var s=t.shift();if(!0===i){var a=(n.pop()+","+s).replace(/\\,/g,",");n.push(a),i=!1}else n.push(s);"\\"===s.substr(-1,1)&&(i=!0)}return n=n.map((function(e){return e.replace("/","\\/")})),n.reverse(),"/"+n.join("/")},Je.asn1.x509.X500Name.ldapToOneline=function(e){return Je.asn1.x509.X500Name.ldapToCompat(e)},Je.asn1.x509.RDN=function(e){Je.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=Je.asn1.x509.AttributeTypeAndValue;this.setByParam=function(e){void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.str&&this.addByMultiValuedString(e.str),void 0!==e.array&&(this.paramArray=e.array)},this.addByString=function(e){this.asn1Array.push(new Je.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=Je.asn1.x509.RDN.parseString(e),i=0;i<t.length;i++)this.addByString(t[i])},this.tohex=function(){if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var i=this.paramArray[e];void 0!==i.rule&&"utf8"!=this.sRule&&(i.rule=this.sRule);var n=new t(i);this.asn1Array.push(n)}var r=new Je.asn1.DERSet({array:this.asn1Array});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.RDN,Je.asn1.ASN1Object),Je.asn1.x509.RDN.parseString=function(e){for(var t=e.split(/\+/),i=!1,n=[],r=0;t.length>0;r++){var s=t.shift();if(!0===i){var a=(n.pop()+"+"+s).replace(/\\\+/g,"+");n.push(a),i=!1}else n.push(s);"\\"===s.substr(-1,1)&&(i=!0)}var o=!1,c=[];for(r=0;n.length>0;r++){s=n.shift();if(!0===o){var d=c.pop();if(s.match(/"$/)){a=(d+"+"+s).replace(/^([^=]+)="(.*)"$/,"$1=$2");c.push(a),o=!1}else c.push(d+"+"+s)}else c.push(s);s.match(/^[^=]+="/)&&(o=!0)}return c},Je.asn1.x509.AttributeTypeAndValue=function(e){Je.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=Je,i=t.asn1,n=i.DERSequence,r=i.DERUTF8String,s=i.DERPrintableString,a=i.DERTeletexString,o=i.DERIA5String,c=i.DERVisibleString,d=i.DERBMPString,l=t.lang.String.isMail,h=t.lang.String.isPrintable;this.setByParam=function(e){if(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.ds&&(this.dsType=e.ds),void 0===e.value&&void 0!==e.str){var t=e.str.match(/^([^=]+)=(.+)$/);if(!t)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.sType=t[1],this.sValue=t[2]}else this.sType=e.type,this.sValue=e.value},this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var i=e.match(/^([^=]+)=(.+)$/);if(!i)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(i[1],i[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,i=this.sRule;return"prn"===i?"CN"==e&&l(t)?"ia5":h(t)?"prn":"utf8":"utf8"===i?"CN"==e&&l(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,i){void 0!==i&&(this.sRule=i),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new r({str:t});if("prn"==e)return new s({str:t});if("tel"==e)return new a({str:t});if("ia5"==e)return new o({str:t});if("vis"==e)return new c({str:t});if("bmp"==e)return new d({str:t});throw new Error("unsupported directory string type: type="+e+" value="+t)},this.tohex=function(){null==this.dsType&&(this.dsType=this._getDsType());var e=Je.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),i=new n({array:[e,t]});return this.TLV=i.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.AttributeTypeAndValue,Je.asn1.ASN1Object),Je.asn1.x509.SubjectPublicKeyInfo=function(e){Je.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=Je,i=t.asn1,n=i.DERInteger,r=i.DERBitString,s=i.DERObjectIdentifier,a=i.DERSequence,o=i.ASN1Util.newObject,c=i.x509.AlgorithmIdentifier,d=t.crypto;d.ECDSA,d.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new a({array:[this.asn1AlgId,this.asn1SubjPKey]})},this.tohex=function(){var e=this.getASN1Object();return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.setPubKey=function(e){try{if(e instanceof Ge){var t=o({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new c({name:"rsaEncryption"}),this.asn1SubjPKey=new r({hex:"00"+t})}}catch(e){}try{if(e instanceof Je.crypto.ECDSA){var i=new s({name:e.curveName});this.asn1AlgId=new c({name:"ecPublicKey",asn1params:i}),this.asn1SubjPKey=new r({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof Je.crypto.DSA){i=new o({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new c({name:"dsa",asn1params:i});var a=new n({bigint:e.y});this.asn1SubjPKey=new r({hex:"00"+a.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},Nt(Je.asn1.x509.SubjectPublicKeyInfo,Je.asn1.ASN1Object),Je.asn1.x509.Time=function(e){Je.asn1.x509.Time.superclass.constructor.call(this);var t=Je.asn1,i=t.DERUTCTime,n=t.DERGeneralizedTime;this.params=null,this.type=null,this.setTimeParams=function(e){this.timeParams=e},this.setByParam=function(e){this.params=e},this.getType=function(e){return e.match(/^[0-9]{12}Z$/)?"utc":e.match(/^[0-9]{14}Z$/)?"gen":e.match(/^[0-9]{12}\.[0-9]+Z$/)?"utc":e.match(/^[0-9]{14}\.[0-9]+Z$/)?"gen":null},this.tohex=function(){var e=this.params,t=null;if("string"==typeof e&&(e={str:e}),null==e||!e.str||null!=e.type&&null!=e.type||(e.type=this.getType(e.str)),null!=e&&e.str?("utc"==e.type&&(t=new i(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new i,null==t)throw new Error("wrong setting for Time");return this.TLV=t.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Je.asn1.x509.Time_bak=function(e){Je.asn1.x509.Time_bak.superclass.constructor.call(this);var t=Je.asn1,i=t.DERUTCTime,n=t.DERGeneralizedTime;this.setTimeParams=function(e){this.timeParams=e},this.tohex=function(){var e=null;return e=null!=this.timeParams?"utc"==this.type?new i(this.timeParams):new n(this.timeParams):"utc"==this.type?new i:new n,this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},this.type="utc",void 0!==e&&(void 0!==e.type?this.type=e.type:void 0!==e.str&&(e.str.match(/^[0-9]{12}Z$/)&&(this.type="utc"),e.str.match(/^[0-9]{14}Z$/)&&(this.type="gen")),this.timeParams=e)},Nt(Je.asn1.x509.Time,Je.asn1.ASN1Object),Je.asn1.x509.AlgorithmIdentifier=function(e){Je.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=Je.asn1,i=t.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;if(this.tohex=function(){if(null===this.nameAlg&&null===this.asn1Alg)throw new Error("algorithm not specified");if(null!==this.nameAlg){var e=null;for(var n in i)n===this.nameAlg&&(e=i[n]);if(null!==e)return this.hTLV=e,this.hTLV}null!==this.nameAlg&&null===this.asn1Alg&&(this.asn1Alg=t.x509.OID.name2obj(this.nameAlg));var r=[this.asn1Alg];null!==this.asn1Params&&r.push(this.asn1Params);var s=new t.DERSequence({array:r});return this.hTLV=s.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.name&&(this.nameAlg=e.name),void 0!==e.asn1params&&(this.asn1Params=e.asn1params),void 0!==e.paramempty&&(this.paramEmpty=e.paramempty)),null===this.asn1Params&&!1===this.paramEmpty&&null!==this.nameAlg){void 0!==this.nameAlg.name&&(this.nameAlg=this.nameAlg.name);var n=this.nameAlg.toLowerCase();"withdsa"!==n.substr(-7,7)&&"withecdsa"!==n.substr(-9,9)&&(this.asn1Params=new t.DERNull)}},Nt(Je.asn1.x509.AlgorithmIdentifier,Je.asn1.ASN1Object),Je.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},Je.asn1.x509.GeneralName=function(e){Je.asn1.x509.GeneralName.superclass.constructor.call(this);var t=Je.asn1,i=t.x509,n=i.X500Name,r=i.OtherName,s=t.DERIA5String;t.DERPrintableString;var a=t.DEROctetString,o=t.DERTaggedObject,c=t.ASN1Object,d=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,i=this.params,l=!1;if(void 0!==i.other)e="a0",t=new r(i.other);else if(void 0!==i.rfc822)e="81",t=new s({str:i.rfc822});else if(void 0!==i.dns)e="82",t=new s({str:i.dns});else if(void 0!==i.dn)e="a4",l=!0,t="string"==typeof i.dn?new n({str:i.dn}):i.dn instanceof Je.asn1.x509.X500Name?i.dn:new n(i.dn);else if(void 0!==i.ldapdn)e="a4",l=!0,t=new n({ldapstr:i.ldapdn});else if(void 0!==i.certissuer||void 0!==i.certsubj){var h,u;e="a4",l=!0;var p=null;if(void 0!==i.certsubj?(h=!1,u=i.certsubj):(h=!0,u=i.certissuer),u.match(/^[0-9A-Fa-f]+$/),-1!=u.indexOf("-----BEGIN ")&&(p=ut(u)),null==p)throw new Error("certsubj/certissuer not cert");var g,f=new Ht;f.hex=p,g=h?f.getIssuerHex():f.getSubjectHex(),(t=new c).hTLV=g}else if(void 0!==i.uri)e="86",t=new s({str:i.uri});else{if(void 0===i.ip)throw new d("improper params");var m;e="87";var v=i.ip;try{if(v.match(/^[0-9a-f]+$/)){var y=v.length;if(8!=y&&16!=y&&32!=y&&64!=y)throw"err";m=v}else m=bt(v)}catch(e){throw new d("malformed IP address: "+i.ip+":"+e.message)}t=new a({hex:m})}return new o({tag:e,explicit:l,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.GeneralName,Je.asn1.ASN1Object),Je.asn1.x509.GeneralNames=function(e){Je.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=Je.asn1;this.setByParamArray=function(e){for(var i=0;i<e.length;i++){var n=new t.x509.GeneralName(e[i]);this.asn1Array.push(n)}},this.tohex=function(){return new t.DERSequence({array:this.asn1Array}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.asn1Array=new Array,void 0!==e&&this.setByParamArray(e)},Nt(Je.asn1.x509.GeneralNames,Je.asn1.ASN1Object),Je.asn1.x509.OtherName=function(e){Je.asn1.x509.OtherName.superclass.constructor.call(this);var t=Je.asn1,i=t.DERObjectIdentifier,n=t.DERSequence,r=t.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if(null==e.oid||null==e.value)throw new Error("oid or value not specified");var t=new i({oid:e.oid}),s=r({tag:{tag:"a0",explicit:!0,obj:e.value}});return new n({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.OtherName,Je.asn1.ASN1Object),Je.asn1.x509.OID=new function(){var e=Je.asn1.DERObjectIdentifier;this.name2oidList={"aes128-CBC":"2.16.840.1.101.3.4.1.2","aes256-CBC":"2.16.840.1.101.3.4.1.42",sha1:"1.3.14.3.2.26",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",sha224:"2.16.840.1.101.3.4.2.4",md5:"1.2.840.113549.2.5",md2:"1.3.14.7.2.2.1",ripemd160:"1.3.36.3.2.1",hmacWithSHA1:"1.2.840.113549.2.7",hmacWithSHA224:"1.2.840.113549.2.8",hmacWithSHA256:"1.2.840.113549.2.9",hmacWithSHA384:"1.2.840.113549.2.10",hmacWithSHA512:"1.2.840.113549.2.11",MD2withRSA:"1.2.840.113549.1.1.2",MD4withRSA:"1.2.840.113549.1.1.3",MD5withRSA:"1.2.840.113549.1.1.4",SHA1withRSA:"1.2.840.113549.1.1.5","pkcs1-MGF":"1.2.840.113549.1.1.8",rsaPSS:"1.2.840.113549.1.1.10",SHA224withRSA:"1.2.840.113549.1.1.14",SHA256withRSA:"1.2.840.113549.1.1.11",SHA384withRSA:"1.2.840.113549.1.1.12",SHA512withRSA:"1.2.840.113549.1.1.13",SHA1withECDSA:"1.2.840.10045.4.1",SHA224withECDSA:"1.2.840.10045.4.3.1",SHA256withECDSA:"1.2.840.10045.4.3.2",SHA384withECDSA:"1.2.840.10045.4.3.3",SHA512withECDSA:"1.2.840.10045.4.3.4",dsa:"1.2.840.10040.4.1",SHA1withDSA:"1.2.840.10040.4.3",SHA224withDSA:"2.16.840.1.101.3.4.3.1",SHA256withDSA:"2.16.840.1.101.3.4.3.2",rsaEncryption:"1.2.840.113549.1.1.1",commonName:"2.5.4.3",countryName:"2.5.4.6",localityName:"2.5.4.7",stateOrProvinceName:"2.5.4.8",streetAddress:"2.5.4.9",organizationName:"2.5.4.10",organizationalUnitName:"2.5.4.11",domainComponent:"0.9.2342.19200300.100.1.25",userId:"0.9.2342.19200300.100.1.1",surname:"2.5.4.4",givenName:"2.5.4.42",title:"2.5.4.12",distinguishedName:"2.5.4.49",emailAddress:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3",subjectDirectoryAttributes:"2.5.29.9",subjectKeyIdentifier:"2.5.29.14",keyUsage:"2.5.29.15",subjectAltName:"2.5.29.17",issuerAltName:"2.5.29.18",basicConstraints:"2.5.29.19",cRLNumber:"2.5.29.20",cRLReason:"2.5.29.21",nameConstraints:"2.5.29.30",cRLDistributionPoints:"2.5.29.31",certificatePolicies:"2.5.29.32",anyPolicy:"2.5.29.32.0",policyMappings:"2.5.29.33",authorityKeyIdentifier:"2.5.29.35",policyConstraints:"2.5.29.36",extKeyUsage:"2.5.29.37",inhibitAnyPolicy:"2.5.29.54",authorityInfoAccess:"1.3.6.1.5.5.7.1.1",ocsp:"1.3.6.1.5.5.7.48.1",ocspBasic:"1.3.6.1.5.5.7.48.1.1",ocspNonce:"1.3.6.1.5.5.7.48.1.2",ocspNoCheck:"1.3.6.1.5.5.7.48.1.5",caIssuers:"1.3.6.1.5.5.7.48.2",anyExtendedKeyUsage:"2.5.29.37.0",serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",emailProtection:"1.3.6.1.5.5.7.3.4",timeStamping:"1.3.6.1.5.5.7.3.8",ocspSigning:"1.3.6.1.5.5.7.3.9",smtpUTF8Mailbox:"1.3.6.1.5.5.7.8.9",dateOfBirth:"1.3.6.1.5.5.7.9.1",placeOfBirth:"1.3.6.1.5.5.7.9.2",gender:"1.3.6.1.5.5.7.9.3",countryOfCitizenship:"1.3.6.1.5.5.7.9.4",countryOfResidence:"1.3.6.1.5.5.7.9.5",ecPublicKey:"1.2.840.10045.2.1","P-256":"1.2.840.10045.3.1.7",secp256r1:"1.2.840.10045.3.1.7",secp256k1:"1.3.132.0.10",secp384r1:"1.3.132.0.34",secp521r1:"1.3.132.0.35",pkcs5PBES2:"1.2.840.113549.1.5.13",pkcs5PBKDF2:"1.2.840.113549.1.5.12","des-EDE3-CBC":"1.2.840.113549.3.7",data:"1.2.840.113549.1.7.1","signed-data":"1.2.840.113549.1.7.2","enveloped-data":"1.2.840.113549.1.7.3","digested-data":"1.2.840.113549.1.7.5","encrypted-data":"1.2.840.113549.1.7.6","authenticated-data":"1.2.840.113549.1.9.16.1.2",tstinfo:"1.2.840.113549.1.9.16.1.4",signingCertificate:"1.2.840.113549.1.9.16.2.12",timeStampToken:"1.2.840.113549.1.9.16.2.14",signaturePolicyIdentifier:"1.2.840.113549.1.9.16.2.15",etsArchiveTimeStamp:"1.2.840.113549.1.9.16.2.27",signingCertificateV2:"1.2.840.113549.1.9.16.2.47",etsArchiveTimeStampV2:"1.2.840.113549.1.9.16.2.48",extensionRequest:"1.2.840.113549.1.9.14",contentType:"1.2.840.113549.1.9.3",messageDigest:"1.2.840.113549.1.9.4",signingTime:"1.2.840.113549.1.9.5",counterSignature:"1.2.840.113549.1.9.6",archiveTimeStampV3:"0.4.0.1733.2.4",pdfRevocationInfoArchival:"1.2.840.113583.1.1.8",adobeTimeStamp:"1.2.840.113583.1.1.9.1",smimeMailboxLegacy:"2.23.140.1.5.1.1",smimeMailboxMulti:"2.23.140.1.5.1.2",smimeMailboxStrict:"2.23.140.1.5.1.3",smimeOrganizationLegacy:"2.23.140.1.5.2.1",smimeOrganizationMulti:"2.23.140.1.5.2.2",smimeOrganizationStrict:"2.23.140.1.5.2.3",smimeSponsorLegacy:"2.23.140.1.5.3.1",smimeSponsorMulti:"2.23.140.1.5.3.2",smimeSponsorStrict:"2.23.140.1.5.3.3",smimeIndividualLegacy:"2.23.140.1.5.4.1",smimeIndividualMulti:"2.23.140.1.5.4.2",smimeIndividualStrict:"2.23.140.1.5.4.3"},this.atype2oidList={CN:"2.5.4.3",L:"2.5.4.7",ST:"2.5.4.8",O:"2.5.4.10",OU:"2.5.4.11",C:"2.5.4.6",STREET:"2.5.4.9",DC:"0.9.2342.19200300.100.1.25",UID:"0.9.2342.19200300.100.1.1",SN:"2.5.4.4",T:"2.5.4.12",GN:"2.5.4.42",DN:"2.5.4.49",E:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3"},this.objCache={},this.name2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];if(void 0===this.name2oidList[t])throw"Name of ObjectIdentifier not defined: "+t;var i=this.name2oidList[t],n=new e({oid:i});return this.objCache[t]=n,n},this.atype2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];var i;if(t.match(/^\d+\.\d+\.[0-9.]+$/))i=t;else if(void 0!==this.atype2oidList[t])i=this.atype2oidList[t];else{if(void 0===this.name2oidList[t])throw new Error("AttributeType name undefined: "+t);i=this.name2oidList[t]}var n=new e({oid:i});return this.objCache[t]=n,n},this.registerOIDs=function(e){if(this.checkOIDs(e))for(var t in e)this.name2oidList[t]=e[t]},this.checkOIDs=function(e){try{var t=Object.keys(e);return 0!=t.length&&(t.map((function(e,t,i){if(!this[e].match(/^[0-2]\.[0-9.]+$/))throw new Error("value is not OID")}),e),!0)}catch(e){return!1}}},Je.asn1.x509.OID.oid2name=function(e){var t=Je.asn1.x509.OID.name2oidList;for(var i in t)if(t[i]==e)return i;return""},Je.asn1.x509.OID.oid2atype=function(e){var t=Je.asn1.x509.OID.atype2oidList;for(var i in t)if(t[i]==e)return i;return e},Je.asn1.x509.OID.name2oid=function(e){if(e.match(/^[0-9.]+$/))return e;var t=Je.asn1.x509.OID.name2oidList;return void 0===t[e]?"":t[e]},Je.asn1.x509.X509Util={},Je.asn1.x509.X509Util.newCertPEM=function(e){var t=Je.asn1.x509;return t.TBSCertificate,new(0,t.Certificate)(e).getPEM()},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.cms&&Je.asn1.cms||(Je.asn1.cms={}),Je.asn1.cms.Attribute=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERSet,s=i.DERObjectIdentifier;this.params=null,this.typeOid=null,this.setByParam=function(e){this.params=e},this.getValueArray=function(){throw new t("not yet implemented abstract")},this.tohex=function(){var e=new s({oid:this.typeOid}),t=new r({array:this.getValueArray()});return new n({array:[e,t]}).tohex()},this.getEncodedHex=function(){return this.tohex()}},Nt(Je.asn1.cms.Attribute,Je.asn1.ASN1Object),Je.asn1.cms.ContentType=function(e){var t=Je.asn1;t.cms.ContentType.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.3",this.getValueArray=function(){return[new t.DERObjectIdentifier(this.params.type)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ContentType,Je.asn1.cms.Attribute),Je.asn1.cms.MessageDigest=function(e){var t=Je.asn1,i=t.DEROctetString;t.cms.MessageDigest.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.4",this.getValueArray=function(){return[new i(this.params)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.MessageDigest,Je.asn1.cms.Attribute),Je.asn1.cms.SigningTime=function(e){var t=Je.asn1;t.cms.SigningTime.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.5",this.getValueArray=function(){return[new t.x509.Time(this.params)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningTime,Je.asn1.cms.Attribute),Je.asn1.cms.SigningCertificate=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence,s=n.cms,a=s.ESSCertID;i.crypto,s.SigningCertificate.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.12",this.getValueArray=function(){if(null==this.params||null==this.params||null==this.params.array)throw new t("parameter 'array' not specified");for(var i=this.params.array,n=[],s=0;s<i.length;s++){var o=i[s];0!=e.hasis||"string"!=typeof o||-1==o.indexOf("-----BEGIN")&&!Qe.isASN1HEX(o)||(o={cert:o}),0!=o.hasis&&0==e.hasis&&(o.hasis=!1),n.push(new a(o))}var c=new r({array:n});return[new r({array:[c]})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningCertificate,Je.asn1.cms.Attribute),Je.asn1.cms.ESSCertID=function(e){Je.asn1.cms.ESSCertID.superclass.constructor.call(this);var t=Error,i=Je,n=i.asn1,r=n.DEROctetString,s=n.DERSequence,a=n.cms.IssuerSerial;this.params=null,this.getCertHash=function(e,n){if(null!=e.hash)return e.hash;if("string"==typeof e&&-1==e.indexOf("-----BEGIN")&&!Qe.isASN1HEX(e))return e;var r,s,a;if("string"==typeof e)r=e;else{if(null==e.cert)throw new t("hash nor cert unspecified");r=e.cert}if(s=-1!=r.indexOf("-----BEGIN")?ut(r):r,"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?s=ut(e):Qe.isASN1HEX(e)&&(s=e)),null!=e.alg)a=e.alg;else{if(null==n)throw new t("hash alg unspecified");a=n}return i.crypto.Util.hashHex(s,a)},this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha1"),i=[];return i.push(new r({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&i.push(new a(e)),new s({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ESSCertID,Je.asn1.ASN1Object),Je.asn1.cms.SigningCertificateV2=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence;n.x509;var s=n.cms,a=s.ESSCertIDv2;i.crypto,s.SigningCertificateV2.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.47",this.getValueArray=function(){if(null==this.params||null==this.params||null==this.params.array)throw new t("parameter 'array' not specified");for(var i=this.params.array,n=[],s=0;s<i.length;s++){var o=i[s];null==e.alg&&0!=e.hasis||"string"!=typeof o||-1==o.indexOf("-----BEGIN")&&!Qe.isASN1HEX(o)||(o={cert:o}),null==o.alg&&null!=e.alg&&(o.alg=e.alg),0!=o.hasis&&0==e.hasis&&(o.hasis=!1),n.push(new a(o))}var c=new r({array:n});return[new r({array:[c]})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningCertificateV2,Je.asn1.cms.Attribute),Je.asn1.cms.ESSCertIDv2=function(e){Je.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);var t=Je.asn1,i=t.DEROctetString,n=t.DERSequence,r=t.cms.IssuerSerial,s=t.x509.AlgorithmIdentifier;this.params=null,this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha256"),a=[];return null!=e.alg&&"sha256"!=e.alg&&a.push(new s({name:e.alg})),a.push(new i({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&a.push(new r(e)),new n({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ESSCertIDv2,Je.asn1.cms.ESSCertID),Je.asn1.cms.IssuerSerial=function(e){var t=Error,i=Je.asn1,n=i.DERInteger,r=i.DERSequence,s=i.cms,a=i.x509.GeneralNames,o=Ht;s.IssuerSerial.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.tohex=function(){var e,i,s=this.params;if("string"==typeof s&&-1!=s.indexOf("-----BEGIN")||null!=s.cert){var c;c=null!=s.cert?s.cert:s;var d=new o;d.readCertPEM(c),e=d.getIssuer(),i={hex:d.getSerialNumberHex()}}else{if(null==s.issuer||!s.serial)throw new t("cert or issuer and serial parameter not specified");e=s.issuer,i=s.serial}var l=new a([{dn:e}]),h=new n(i);return new r({array:[l,h]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.IssuerSerial,Je.asn1.ASN1Object),Je.asn1.cms.SignerIdentifier=function(e){var t=Je.asn1;t.DERInteger,t.DERSequence;var i=t.cms,n=i.IssuerAndSerialNumber,r=i.SubjectKeyIdentifier;t.x509.X500Name,i.SignerIdentifier.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if("isssn"==e.type)return new n(e).tohex();if("skid"==e.type)return new r(e).tohex();throw new Error("wrong property for isssn or skid")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignerIdentifier,Je.asn1.ASN1Object),Je.asn1.cms.IssuerAndSerialNumber=function(e){var t=Je.asn1,i=t.DERInteger,n=t.DERSequence,r=t.cms,s=t.x509.X500Name,a=Ht,o=Error;r.IssuerAndSerialNumber.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e,t,r=this.params;if("string"==typeof r&&-1!=r.indexOf("-----BEGIN")||null!=r.cert){var c;c=null!=r.cert?r.cert:r;var d=new a;d.readCertPEM(c),e=d.getIssuer(),t={hex:d.getSerialNumberHex()}}else{if(null==r.issuer||!r.serial)throw new o("cert or issuer and serial parameter not specified");e=r.issuer,t=r.serial}var l=new s(e),h=new i(t);return new n({array:[l,h]}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.IssuerAndSerialNumber,Je.asn1.ASN1Object),Je.asn1.cms.SubjectKeyIdentifier=function(e){var t=Je.asn1;t.DERInteger,t.DERSequence;var i=t.ASN1Util.newObject,n=t.cms;n.IssuerAndSerialName,n.SubjectKeyIdentifier,t.x509.X500Name;var r=Ht,s=Error;n.SubjectKeyIdentifier.superclass.constructor.call(this),this.tohex=function(){var e,t=this.params;if(null==t.cert&&null==t.skid)throw new s("property cert nor skid undefined");null!=t.cert?e=new r(t.cert).getExtSubjectKeyIdentifier().kid.hex:null!=t.skid&&(e=t.skid);return i({tag:{tage:"a0",obj:{octstr:{hex:e}}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SubjectKeyIdentifier,Je.asn1.ASN1Object),Je.asn1.cms.AttributeList=function(e){var t=Error,i=Je.asn1,n=i.DERSet,r=i.cms;r.AttributeList.superclass.constructor.call(this),this.params=null,this.hTLV=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if(null!=this.hTLV)return this.hTLV;var i=!0;null!=e.sortflag&&(i=e.sortflag);for(var s=e.array,a=[],o=0;o<s.length;o++){var c=s[o],d=c.attr;if("contentType"==d)a.push(new r.ContentType(c));else if("messageDigest"==d)a.push(new r.MessageDigest(c));else if("signingTime"==d)a.push(new r.SigningTime(c));else if("signingCertificate"==d)a.push(new r.SigningCertificate(c));else if("signingCertificateV2"==d)a.push(new r.SigningCertificateV2(c));else if("signaturePolicyIdentifier"==d)a.push(new Je.asn1.cades.SignaturePolicyIdentifier(c));else{if("signatureTimeStamp"!=d&&"timeStampToken"!=d)throw new t("unknown attr: "+d);a.push(new Je.asn1.cades.SignatureTimeStamp(c))}}var l=new n({array:a,sortflag:i});return this.hTLV=l.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.AttributeList,Je.asn1.ASN1Object),Je.asn1.cms.SignerInfo=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERInteger,s=n.DEROctetString,a=n.DERSequence,o=n.DERTaggedObject,c=n.cms,d=c.SignerIdentifier,l=c.AttributeList;c.ContentType,c.EncapsulatedContentInfo,c.MessageDigest,c.SignedData;var h=n.x509.AlgorithmIdentifier,u=i.crypto,p=kt;c.SignerInfo.superclass.constructor.call(this),this.params=null,this.sign=function(){var e=this.params,t=e.sigalg,i=new l(e.sattrs).tohex(),n=p.getKey(e.signkey),r=new u.Signature({alg:t});r.init(n),r.updateHex(i);var s=r.sign();e.sighex=s},this.tohex=function(){var e=this.params,i=[];if(i.push(new r({int:e.version})),i.push(new d(e.id)),i.push(new h({name:e.hashalg})),null!=e.sattrs){var n=new l(e.sattrs);try{i.push(new o({tag:"a0",explicit:!1,obj:n}))}catch(e){throw new t("si sattr error: "+e)}}if(null!=e.sigalgfield?i.push(new h({name:e.sigalgfield})):i.push(new h({name:e.sigalg})),null==e.sighex&&null!=e.signkey&&this.sign(),i.push(new s({hex:e.sighex})),null!=e.uattrs){n=new l(e.uattrs);try{i.push(new o({tag:"a1",explicit:!1,obj:n}))}catch(e){throw new t("si uattr error: "+e)}}return new a({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignerInfo,Je.asn1.ASN1Object),Je.asn1.cms.EncapsulatedContentInfo=function(e){var t=Je.asn1,i=t.DERTaggedObject,n=t.DERSequence,r=t.DERObjectIdentifier,s=t.DEROctetString;t.cms.EncapsulatedContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];if(t.push(new r(e.type)),null!=e.content&&(null!=e.content.hex||null!=e.content.str)&&1!=e.isDetached){var a=new s(e.content),o=new i({tag:"a0",explicit:!0,obj:a});t.push(o)}return new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.EncapsulatedContentInfo,Je.asn1.ASN1Object),Je.asn1.cms.ContentInfo=function(e){var t=Je.asn1,i=t.DERTaggedObject,n=t.DERSequence,r=t.DERObjectIdentifier;t.x509.OID.name2obj,Je.asn1.cms.ContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];t.push(new r(e.type));var s=new i({tag:"a0",explicit:!0,obj:e.obj});return t.push(s),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ContentInfo,Je.asn1.ASN1Object),Je.asn1.cms.SignedData=function(e){var t=Je.asn1;t.ASN1Object;var i=t.DERInteger,n=t.DERSet,r=t.DERSequence;t.DERTaggedObject;var s=t.cms,a=s.EncapsulatedContentInfo,o=s.SignerInfo,c=s.ContentInfo,d=s.CertificateSet,l=s.RevocationInfoChoices,h=t.x509.AlgorithmIdentifier;Je.asn1.cms.SignedData.superclass.constructor.call(this),this.params=null,this.checkAndFixParam=function(){var e=this.params;this._setDigestAlgs(e),this._setContentTypeByEContent(e),this._setMessageDigestByEContent(e),this._setSignerInfoVersion(e),this._setSignedDataVersion(e)},this._setDigestAlgs=function(e){for(var t={},i=e.sinfos,n=0;n<i.length;n++){t[i[n].hashalg]=1}e.hashalgs=Object.keys(t).sort()},this._setContentTypeByEContent=function(e){for(var t=e.econtent.type,i=e.sinfos,n=0;n<i.length;n++){var r=i[n];this._getAttrParamByName(r,"contentType").type=t}},this._setMessageDigestByEContent=function(e){var t=e.econtent;e.econtent.type;var i=t.content.hex;null==i&&"data"==t.type&&null!=t.content.str&&(i=lt(t.content.str));for(var n=e.sinfos,r=0;r<n.length;r++){var s=n[r],a=s.hashalg,o=this._getAttrParamByName(s,"messageDigest"),c=Je.crypto.Util.hashHex(i,a);o.hex=c}},this._getAttrParamByName=function(e,t){for(var i=e.sattrs.array,n=0;n<i.length;n++)if(i[n].attr==t)return i[n]},this._setSignerInfoVersion=function(e){for(var t=e.sinfos,i=0;i<t.length;i++){var n=t[i],r=1;"skid"==n.id.type&&(r=3),n.version=r}},this._setSignedDataVersion=function(e){var t=this._getSignedDataVersion(e);e.version=t},this._getSignedDataVersion=function(e){if(null!=e.revinfos)for(var t=e.revinfos,i=0;i<t.length;i++){if(null!=t[i].ocsp)return 5}var n=e.sinfos;for(i=0;i<n.length;i++){if(3==e.sinfos[i].version)return 3}return"data"!=e.econtent.type?3:1},this.tohex=function(){var e=this.params;null!=this.getEncodedHexPrepare&&this.getEncodedHexPrepare(),1!=e.fixed&&this.checkAndFixParam();var t=[];t.push(new i({int:e.version}));for(var s=[],c=0;c<e.hashalgs.length;c++){var u=e.hashalgs[c];s.push(new h({name:u}))}t.push(new n({array:s})),t.push(new a(e.econtent)),null!=e.certs&&t.push(new d(e.certs)),null!=e.revinfos&&t.push(new l(e.revinfos));var p=[];for(c=0;c<e.sinfos.length;c++){var g=e.sinfos[c];p.push(new o(g))}return t.push(new n({array:p})),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.getContentInfo=function(){return new c({type:"signed-data",obj:this})},this.getContentInfoEncodedHex=function(){return this.getContentInfo().tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignedData,Je.asn1.ASN1Object),Je.asn1.cms.CertificateSet=function(e){Je.asn1.cms.CertificateSet.superclass.constructor.call(this);var t=Error,i=Je.asn1,n=i.DERTaggedObject,r=i.DERSet,s=i.ASN1Object;this.params=null,this.tohex=function(){var e,i=this.params,a=[];if(i instanceof Array)e=i;else{if(null==i.array)throw new t("cert array not specified");e=i.array}for(var o=0;o<e.length;o++){var c=ut(e[o]),d=new s;d.hTLV=c,a.push(d)}var l={array:a};0==i.sortflag&&(l.sortflag=!1);var h=new r(l);return new n({tag:"a0",explicit:!1,obj:h}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.CertificateSet,Je.asn1.ASN1Object),Je.asn1.cms.RevocationInfoChoices=function(e){Je.asn1.cms.RevocationInfoChoices.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(!e instanceof Array)throw new Error("params is not array");for(var t=[],i=0;i<e.length;i++)t.push(new Je.asn1.cms.RevocationInfoChoice(e[i]));return Je.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:{set:t}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.RevocationInfoChoices,Je.asn1.ASN1Object),Je.asn1.cms.RevocationInfoChoice=function(e){Je.asn1.cms.RevocationInfoChoice.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(null!=e.crl&&"string"==typeof e.crl){var t=e.crl;return-1!=e.crl.indexOf("-----BEGIN")&&(t=ut(e.crl)),t}if(null!=e.ocsp)return Je.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:new Je.asn1.cms.OtherRevocationFormat(e)}}).tohex();throw new Error("property crl or ocsp undefined")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.RevocationInfoChoice,Je.asn1.ASN1Object),Je.asn1.cms.OtherRevocationFormat=function(e){Je.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);var t=Error,i=Je,n=i.asn1.ASN1Util.newObject,r=i.lang.String.isHex;this.params=null,this.tohex=function(){var e=this.params;if(null==e.ocsp)throw new t("property ocsp not specified");if(!r(e.ocsp)||!Qe.isASN1HEX(e.ocsp))throw new t("ocsp value not ASN.1 hex string");return n({seq:[{oid:"1.3.6.1.5.5.7.16.2"},{asn1:{tlv:e.ocsp}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.OtherRevocationFormat,Je.asn1.ASN1Object),Je.asn1.cms.CMSUtil=new function(){},Je.asn1.cms.CMSUtil.newSignedData=function(e){return new Je.asn1.cms.SignedData(e)},Je.asn1.cms.CMSUtil.verifySignedData=function(e){var t=Je,i=t.asn1,n=i.cms;n.SignerInfo,n.SignedData,n.SigningTime,n.SigningCertificate,n.SigningCertificateV2,i.cades.SignaturePolicyIdentifier;var r=t.lang.String.isHex,s=Qe,a=s.getVbyList,o=s.getTLVbyList,c=s.getIdxbyList,d=s.getChildIdx,l=s.getTLV,h=s.oidname,u=t.crypto.Util.hashHex;void 0===e.cms&&r(e.cms);var p=e.cms,g=function(e,t){var i=t.idx;t.signerid_issuer1=o(e,i,[1,0],"30"),t.signerid_serial1=a(e,i,[1,1],"02"),t.hashalg=h(a(e,i,[2,0],"06"));var n=c(e,i,[3],"a0");t.idxSignedAttrs=n,f(e,t,n);var r=d(e,i).length;if(r<6)throw"malformed SignerInfo";t.sigalg=h(a(e,i,[r-2,0],"06")),t.sigval=a(e,i,[r-1],"04")},f=function(e,t,i){var n=d(e,i);t.signedAttrIdxList=n;for(var r=0;r<n.length;r++){var s,o=n[r],c=a(e,o,[0],"06");"2a864886f70d010905"===c?(s=ot(a(e,o,[1,0])),t.saSigningTime=s):"2a864886f70d010904"===c&&(s=a(e,o,[1,0],"04"),t.saMessageDigest=s)}},m=function(e,t,i,n){i.verifyDetail={};var r=i.verifyDetail,s=t.parse.econtent,a=i.hashalg,o=i.saMessageDigest;r.validMessageDigest=!1,u(s,a)===o&&(r.validMessageDigest=!0),function(e,t,i,n){var r,s=t.parse.certsIdx;if(void 0===t.certs){r=[],t.certkeys=[];for(var a=d(e,s),o=0;o<a.length;o++){var c=l(e,a[o]),h=new Ht;h.readCertHex(c),r[o]=h,t.certkeys[o]=h.getPublicKey()}t.certs=r}else r=t.certs;for(t.cccc=r.length,t.cccci=a.length,o=0;o<r.length;o++){var u=h.getIssuerHex(),p=h.getSerialNumberHex();i.signerid_issuer1===u&&i.signerid_serial1===p&&(i.certkey_idx=o)}}(e,t,i),r.validSignatureValue=!1;var c=i.sigalg,h="31"+l(e,i.idxSignedAttrs).substr(2);i.signedattrshex=h;var p=t.certs[i.certkey_idx].getPublicKey(),g=new Je.crypto.Signature({alg:c});g.init(p),g.updateHex(h);var f=g.verify(i.sigval);r.validSignatureValue_isValid=f,!0===f&&(r.validSignatureValue=!0),i.isValid=!1,r.validMessageDigest&&r.validSignatureValue&&(i.isValid=!0)},v={isValid:!1,parse:{}};return function(e,t){if("2a864886f70d010702"!==a(e,0,[0],"06"))return t;t.cmsType="signedData",t.econtent=a(e,0,[1,0,2,1,0]),function(e,t){for(var i,n=3;n<6;n++)if(void 0!==(i=c(e,0,[1,0,n]))){var r=e.substr(i,2);"a0"===r&&(t.certsIdx=i),"a1"===r&&(t.revinfosIdx=i),"31"===r&&(t.signerinfosIdx=i)}}(e,t),t.signerInfos=[],function(e,t){var i=t.signerinfosIdx;if(void 0!==i){var n=d(e,i);t.signerInfoIdxList=n;for(var r=0;r<n.length;r++){var s={idx:n[r]};g(e,s),t.signerInfos.push(s)}}}(e,t)}(p,v.parse),function(e,t){for(var i=t.parse.signerInfos,n=i.length,r=!0,s=0;s<n;s++){var a=i[s];m(e,t,a),a.isValid||(r=!1)}t.isValid=r}(p,v),v},Je.asn1.cms.CMSParser=function(){var e=Error,t=Ht,i=new t,n=Qe,r=n.getV,s=n.getTLV;n.getIdxbyList;var a=n.getTLVbyList,o=n.getTLVbyListEx,c=n.getVbyList,d=n.getVbyListEx,l=n.getChildIdx;this.getCMSSignedData=function(e){var t=a(e,0,[1,0]);return this.getSignedData(t)},this.getSignedData=function(e){var t=l(e,0),i={},n=r(e,t[0]),a=parseInt(n,16);i.version=a;var c=s(e,t[1]);i.hashalgs=this.getHashAlgArray(c);var d=s(e,t[2]);i.econtent=this.getEContent(d);var h=o(e,0,["[0]"]);null!=h&&(i.certs=this.getCertificateSet(h)),o(e,0,["[1]"]);var u=o(e,0,[3]);return i.sinfos=this.getSignerInfos(u),i},this.getHashAlgArray=function(e){for(var i=l(e,0),n=new t,r=[],a=0;a<i.length;a++){var o=s(e,i[a]),c=n.getAlgorithmIdentifierName(o);r.push(c)}return r},this.getEContent=function(e){var t={},i=c(e,0,[0]),n=c(e,0,[1,0]);return t.type=Je.asn1.x509.OID.oid2name(Qe.hextooidstr(i)),t.content={hex:n},t},this.getSignerInfos=function(e){for(var t=[],i=l(e,0),n=0;n<i.length;n++){var r=s(e,i[n]),a=this.getSignerInfo(r);t.push(a)}return t},this.getSignerInfo=function(e){var t={},r=l(e,0),a=n.getInt(e,r[0],-1);-1!=a&&(t.version=a);var c=s(e,r[1]),h=this.getIssuerAndSerialNumber(c);t.id=h;var u=s(e,r[2]),p=i.getAlgorithmIdentifierName(u);t.hashalg=p;var g=o(e,0,["[0]"]);if(null!=g){var f=this.getAttributeList(g);t.sattrs=f}var m=o(e,0,[3]),v=i.getAlgorithmIdentifierName(m);t.sigalg=v;var y=d(e,0,[4]);t.sighex=y;var S=o(e,0,["[1]"]);if(null!=S){var b=this.getAttributeList(S);t.uattrs=b}return t},this.getSignerIdentifier=function(e){if("30"==e.substr(0,2))return this.getIssuerAndSerialNumber(e);throw new Error("SKID of signerIdentifier not supported")},this.getIssuerAndSerialNumber=function(e){var t={type:"isssn"},n=l(e,0),a=s(e,n[0]);t.issuer=i.getX500Name(a);var o=r(e,n[1]);return t.serial={hex:o},t},this.getAttributeList=function(e){for(var t=[],i=l(e,0),n=0;n<i.length;n++){var r=s(e,i[n]),a=this.getAttribute(r);t.push(a)}return{array:t}},this.getAttribute=function(e){var t={},i=l(e,0),r=n.getOID(e,i[0]),a=Je.asn1.x509.OID.oid2name(r);t.attr=a;var o=s(e,i[1]),c=l(o,0);if(1==c.length)t.valhex=s(o,c[0]);else{for(var d=[],h=0;h<c.length;h++)d.push(s(o,c[h]));t.valhex=d}return"contentType"==a?this.setContentType(t):"messageDigest"==a?this.setMessageDigest(t):"signingTime"==a?this.setSigningTime(t):"signingCertificate"==a?this.setSigningCertificate(t):"signingCertificateV2"==a?this.setSigningCertificateV2(t):"signaturePolicyIdentifier"==a&&this.setSignaturePolicyIdentifier(t),t},this.setContentType=function(e){var t=n.getOIDName(e.valhex,0,null);null!=t&&(e.type=t,delete e.valhex)},this.setSigningTime=function(e){var t=ot(r(e.valhex,0));e.str=t,delete e.valhex},this.setMessageDigest=function(e){var t=r(e.valhex,0);e.hex=t,delete e.valhex},this.setSigningCertificate=function(e){var t=l(e.valhex,0);if(t.length>0){for(var i=s(e.valhex,t[0]),n=l(i,0),r=[],a=0;a<n.length;a++){var o=s(i,n[a]),c=this.getESSCertID(o);r.push(c)}e.array=r}if(t.length>1){var d=s(e.valhex,t[1]);e.polhex=d}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var i=l(e.valhex,0);if(i.length>0){var a=n.getOID(e.valhex,i[0]);e.oid=a}if(i.length>1){var o=new t,c=l(e.valhex,i[1]),d=s(e.valhex,c[0]),h=o.getAlgorithmIdentifierName(d);e.alg=h;var u=r(e.valhex,c[1]);e.hash=u}delete e.valhex},this.setSigningCertificateV2=function(e){var t=l(e.valhex,0);if(t.length>0){for(var i=s(e.valhex,t[0]),n=l(i,0),r=[],a=0;a<n.length;a++){var o=s(i,n[a]),c=this.getESSCertIDv2(o);r.push(c)}e.array=r}if(t.length>1){var d=s(e.valhex,t[1]);e.polhex=d}delete e.valhex},this.getESSCertID=function(e){var t={},i=l(e,0);if(i.length>0){var n=r(e,i[0]);t.hash=n}if(i.length>1){var a=s(e,i[1]),o=this.getIssuerSerial(a);null!=o.serial&&(t.serial=o.serial),null!=o.issuer&&(t.issuer=o.issuer)}return t},this.getESSCertIDv2=function(t){var n={},a=l(t,0);if(a.length<1||3<a.length)throw new e("wrong number of elements");var o=0;if("30"==t.substr(a[0],2)){var c=s(t,a[0]);n.alg=i.getAlgorithmIdentifierName(c),o++}else n.alg="sha256";var d=r(t,a[o]);if(n.hash=d,a.length>o+1){var h=s(t,a[o+1]),u=this.getIssuerSerial(h);n.issuer=u.issuer,n.serial=u.serial}return n},this.getIssuerSerial=function(e){var t={},n=l(e,0),a=s(e,n[0]),o=i.getGeneralNames(a)[0].dn;t.issuer=o;var c=r(e,n[1]);return t.serial={hex:c},t},this.getCertificateSet=function(e){for(var t=l(e,0),i=[],n=0;n<t.length;n++){var r=s(e,t[n]);if("30"==r.substr(0,2)){var a=ht(r,"CERTIFICATE");i.push(a)}}return{array:i,sortflag:!1}}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.tsp&&Je.asn1.tsp||(Je.asn1.tsp={}),Je.asn1.tsp.TimeStampToken=function(e){var t=Je.asn1.tsp;t.TimeStampToken.superclass.constructor.call(this),this.params=null,this.getEncodedHexPrepare=function(){var e=new t.TSTInfo(this.params.econtent.content);this.params.econtent.content.hex=e.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampToken,Je.asn1.cms.SignedData),Je.asn1.tsp.TSTInfo=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERInteger,r=t.DERBoolean,s=t.DERGeneralizedTime,a=t.DERObjectIdentifier,o=t.DERTaggedObject,c=t.tsp,d=c.MessageImprint,l=c.Accuracy;t.x509.X500Name;var h=t.x509.GeneralName;if(c.TSTInfo.superclass.constructor.call(this),this.dVersion=new n({int:1}),this.dPolicy=null,this.dMessageImprint=null,this.dSerial=null,this.dGenTime=null,this.dAccuracy=null,this.dOrdering=null,this.dNonce=null,this.dTsa=null,this.tohex=function(){var e=[this.dVersion];if(null==this.dPolicy)throw new Error("policy shall be specified.");if(e.push(this.dPolicy),null==this.dMessageImprint)throw new Error("messageImprint shall be specified.");if(e.push(this.dMessageImprint),null==this.dSerial)throw new Error("serialNumber shall be specified.");if(e.push(this.dSerial),null==this.dGenTime)throw new Error("genTime shall be specified.");e.push(this.dGenTime),null!=this.dAccuracy&&e.push(this.dAccuracy),null!=this.dOrdering&&e.push(this.dOrdering),null!=this.dNonce&&e.push(this.dNonce),null!=this.dTsa&&e.push(this.dTsa);var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){if("string"==typeof e.policy){if(!e.policy.match(/^[0-9.]+$/))throw"policy shall be oid like 0.1.4.134";this.dPolicy=new a({oid:e.policy})}void 0!==e.messageImprint&&(this.dMessageImprint=new d(e.messageImprint)),void 0!==e.serial&&(this.dSerial=new n(e.serial)),void 0!==e.genTime&&(this.dGenTime=new s(e.genTime)),void 0!==e.accuracy&&(this.dAccuracy=new l(e.accuracy)),void 0!==e.ordering&&1==e.ordering&&(this.dOrdering=new r),void 0!==e.nonce&&(this.dNonce=new n(e.nonce)),void 0!==e.tsa&&(this.dTsa=new o({tag:"a0",explicit:!0,obj:new h({dn:e.tsa})}))}},Nt(Je.asn1.tsp.TSTInfo,Je.asn1.ASN1Object),Je.asn1.tsp.Accuracy=function(e){var t=Je.asn1,i=t.ASN1Util.newObject;t.tsp.Accuracy.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return null!=e.seconds&&"number"==typeof e.seconds&&t.push({int:e.seconds}),null!=e.millis&&"number"==typeof e.millis&&t.push({tag:{tagi:"80",obj:{int:e.millis}}}),null!=e.micros&&"number"==typeof e.micros&&t.push({tag:{tagi:"81",obj:{int:e.micros}}}),i({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.Accuracy,Je.asn1.ASN1Object),Je.asn1.tsp.MessageImprint=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DEROctetString,r=t.x509.AlgorithmIdentifier;t.tsp.MessageImprint.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=new r({name:e.alg}),s=new n({hex:e.hash});return new i({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.tsp.MessageImprint,Je.asn1.ASN1Object),Je.asn1.tsp.TimeStampReq=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERInteger,r=t.DERBoolean;t.ASN1Object;var s=t.DERObjectIdentifier,a=t.tsp,o=a.MessageImprint;a.TimeStampReq.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return t.push(new n({int:1})),e.messageImprint instanceof Je.asn1.ASN1Object?t.push(e.messageImprint):t.push(new o(e.messageImprint)),null!=e.policy&&t.push(new s(e.policy)),null!=e.nonce&&t.push(new n(e.nonce)),1==e.certreq&&t.push(new r),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampReq,Je.asn1.ASN1Object),Je.asn1.tsp.TimeStampResp=function(e){var t=Je.asn1,i=t.DERSequence;t.ASN1Object;var n=t.tsp,r=n.PKIStatusInfo;n.TimeStampResp.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,s=[];if(null!=e.econtent||null!=e.tst)if(null!=e.statusinfo?s.push(new r(e.statusinfo)):s.push(new r("granted")),null!=e.econtent)s.push(new n.TimeStampToken(e).getContentInfo());else{if(!(e.tst instanceof t.ASN1Object))throw new Error("improper member tst value");s.push(e.tst)}else{if(null==e.statusinfo)throw new Error("parameter for token nor statusinfo not specified");s.push(new r(e.statusinfo))}return new i({array:s}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampResp,Je.asn1.ASN1Object),Je.asn1.tsp.PKIStatusInfo=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.tsp,s=r.PKIStatus,a=r.PKIFreeText,o=r.PKIFailureInfo;r.PKIStatusInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,i=[];if("string"==typeof e)i.push(new s(e));else{if(null==e.status)throw new t("property 'status' unspecified");i.push(new s(e.status)),null!=e.statusstr&&i.push(new a(e.statusstr)),null!=e.failinfo&&i.push(new o(e.failinfo))}return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIStatusInfo,Je.asn1.ASN1Object),Je.asn1.tsp.PKIStatus=function(e){var t=Error,i=Je.asn1,n=i.DERInteger;i.tsp.PKIStatus.superclass.constructor.call(this);var r={granted:0,grantedWithMods:1,rejection:2,waiting:3,revocationWarning:4,revocationNotification:5};this.params=null,this.tohex=function(){var e,i=this.params;if("string"==typeof i)try{e=r[i]}catch(e){throw new t("undefined name: "+i)}else{if("number"!=typeof i)throw new t("unsupported params");e=i}return new n({int:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIStatus,Je.asn1.ASN1Object),Je.asn1.tsp.PKIFreeText=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERUTF8String;i.tsp.PKIFreeText.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(!e instanceof Array)throw new t("wrong params: not array");for(var i=[],s=0;s<e.length;s++)i.push(new r({str:e[s]}));return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIFreeText,Je.asn1.ASN1Object),Je.asn1.tsp.PKIFailureInfo=function(e){var t=Error,i=Je.asn1,n=i.DERBitString,r=i.tsp.PKIFailureInfo,s={badAlg:0,badRequest:2,badDataFormat:5,timeNotAvailable:14,unacceptedPolicy:15,unacceptedExtension:16,addInfoNotAvailable:17,systemFailure:25};r.superclass.constructor.call(this),this.params=null,this.getBinValue=function(){var e=this.params,i=0;if("number"==typeof e&&0<=e&&e<=25){for(var n=(i|=1<<e).toString(2),r="",a=n.length-1;a>=0;a--)r+=n[a];return r}if("string"==typeof e&&null!=s[e])return Pt([e],s);if("object"==typeof e&&null!=e.length)return Pt(e,s);throw new t("wrong params")},this.tohex=function(){this.params;var e=this.getBinValue();return new n({bin:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIFailureInfo,Je.asn1.ASN1Object),Je.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},Je.asn1.tsp.SimpleTSAAdapter=function(e){var t=Je,i=t.asn1.tsp,n=t.crypto.Util.hashHex;i.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var r=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:r},this.params.econtent.content.serial={int:this.serial++};var s=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:s},new i.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.tsp.SimpleTSAAdapter,Je.asn1.tsp.AbstractTSAAdapter),Je.asn1.tsp.FixedTSAAdapter=function(e){var t=Je,i=t.asn1.tsp,n=t.crypto.Util.hashHex;i.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var r=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:r},new i.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.tsp.FixedTSAAdapter,Je.asn1.tsp.AbstractTSAAdapter),Je.asn1.tsp.TSPUtil=new function(){},Je.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new Je.asn1.tsp.TimeStampToken(e)},Je.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new Je.asn1.tsp.TSPParser).getTimeStampReq(e)},Je.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new Je.asn1.tsp.TSPParser).getMessageImprint(e)},Je.asn1.tsp.TSPParser=function(){var e=new Ht,t=Qe,i=t.getV,n=t.getTLV,r=t.getIdxbyList;t.getTLVbyListEx;var s=t.getChildIdx,a=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],o={0:"badAlg",2:"badRequest",5:"badDataFormat",14:"timeNotAvailable",15:"unacceptedPolicy",16:"unacceptedExtension",17:"addInfoNotAvailable",25:"systemFailure"};this.getResponse=function(e){var t=s(e,0);if(1==t.length)return this.getPKIStatusInfo(n(e,t[0]));if(t.length>1){var i=this.getPKIStatusInfo(n(e,t[0])),r=n(e,t[1]),a=this.getToken(r);return a.statusinfo=i,a}},this.getToken=function(e){var t=(new Je.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var i=t.content.hex,n=this.getTSTInfo(i);t.content=n}},this.getTSTInfo=function(t){var r={},a=s(t,0),o=i(t,a[1]);r.policy=xt(o);var c=n(t,a[2]);r.messageImprint=this.getMessageImprint(c);var d=i(t,a[3]);r.serial={hex:d};var l=i(t,a[4]);r.genTime={str:ot(l)};var h=0;if(a.length>5&&"30"==t.substr(a[5],2)){var u=n(t,a[5]);r.accuracy=this.getAccuracy(u),h++}a.length>5+h&&"01"==t.substr(a[5+h],2)&&("ff"==i(t,a[5+h])&&(r.ordering=!0),h++);if(a.length>5+h&&"02"==t.substr(a[5+h],2)){var p=i(t,a[5+h]);r.nonce={hex:p},h++}if(a.length>5+h&&"a0"==t.substr(a[5+h],2)){var g=n(t,a[5+h]);g="30"+g.substr(2),pGeneralNames=e.getGeneralNames(g);var f=pGeneralNames[0].dn;r.tsa=f,h++}if(a.length>5+h&&"a1"==t.substr(a[5+h],2)){var m=n(t,a[5+h]);m="30"+m.substr(2);var v=e.getExtParamArray(m);r.ext=v,h++}return r},this.getAccuracy=function(e){for(var t={},n=s(e,0),r=0;r<n.length;r++){var a=e.substr(n[r],2),o=i(e,n[r]),c=parseInt(o,16);"02"==a?t.seconds=c:"80"==a?t.millis=c:"81"==a&&(t.micros=c)}return t},this.getMessageImprint=function(e){if("30"!=e.substr(0,2))throw new Error("head of messageImprint hex shall be x30");var n={};s(e,0);var a=r(e,0,[0,0]),o=i(e,a),c=t.hextooidstr(o),d=Je.asn1.x509.OID.oid2name(c);if(""==d)throw new Error("hashAlg name undefined: "+c);var l=d,h=r(e,0,[1]);return n.alg=l,n.hash=i(e,h),n},this.getPKIStatusInfo=function(e){var t={},r=s(e,0),o=0;try{var c=i(e,r[0]),d=parseInt(c,16);t.status=a[d]}catch(e){}if(r.length>1&&"30"==e.substr(r[1],2)){var l=n(e,r[1]);t.statusstr=this.getPKIFreeText(l),o++}if(r.length>o&&"03"==e.substr(r[1+o],2)){var h=n(e,r[1+o]);t.failinfo=this.getPKIFailureInfo(h)}return t},this.getPKIFreeText=function(e){for(var i=[],n=s(e,0),r=0;r<n.length;r++)i.push(t.getString(e,n[r]));return i},this.getPKIFailureInfo=function(e){var i=t.getInt(e,0);return null!=o[i]?o[i]:i},this.getTimeStampReq=function(e){var r={certreq:!1},a=s(e,0);if(a.length<2)throw new Error("TimeStampReq must have at least 2 items");var o=n(e,a[1]);r.messageImprint=Je.asn1.tsp.TSPUtil.parseMessageImprint(o);for(var c=2;c<a.length;c++){var d=a[c],l=e.substr(d,2);if("06"==l){var h=i(e,d);r.policy=t.hextooidstr(h)}"02"==l&&(r.nonce=i(e,d)),"01"==l&&(r.certreq=!0)}return r}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.cades&&Je.asn1.cades||(Je.asn1.cades={}),Je.asn1.cades.SignaturePolicyIdentifier=function(e){var t=Je.asn1.cades,i=t.SignaturePolicyId;t.SignaturePolicyIdentifier.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.15",this.params=null,this.getValueArray=function(){return[new i(this.params)]},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignaturePolicyIdentifier,Je.asn1.cms.Attribute),Je.asn1.cades.SignaturePolicyId=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier;t.x509.AlgorithmIdentifier;var r=t.cades,s=r.SignaturePolicyId,a=r.OtherHashAlgAndValue;s.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return t.push(new n(e.oid)),t.push(new a(e)),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignaturePolicyId,Je.asn1.ASN1Object),Je.asn1.cades.OtherHashAlgAndValue=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DEROctetString,s=i.x509.AlgorithmIdentifier;i.cades.OtherHashAlgAndValue.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(null==e.alg)throw new t("property 'alg' not specified");if(null==e.hash&&null==e.cert)throw new t("property 'hash' nor 'cert' not specified");var i=null;if(null!=e.hash)i=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var a=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(a=ut(e.cert)),i=Je.crypto.Util.hashHex(a,e.alg)}var o=[];return o.push(new s({name:e.alg})),o.push(new r({hex:i})),new n({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHashAlgAndValue,Je.asn1.ASN1Object),Je.asn1.cades.OtherHashValue=function(e){Je.asn1.cades.OtherHashValue.superclass.constructor.call(this);var t=Error,i=Je;i.lang.String.isHex;var n=i.asn1.DEROctetString;i.crypto.Util.hashHex,this.params=null,this.tohex=function(){var e=this.params;if(null==e.hash&&null==e.cert)throw new t("hash or cert not specified");var i=null;if(null!=e.hash)i=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var r=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(r=ut(e.cert)),i=Je.crypto.Util.hashHex(r,"sha1")}return new n({hex:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHashValue,Je.asn1.ASN1Object),Je.asn1.cades.SignatureTimeStamp=function(e){var t=Error,i=Je,n=i.lang.String.isHex,r=i.asn1,s=r.ASN1Object;r.x509,r.cades.SignatureTimeStamp.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.14",this.params=null,this.getValueArray=function(){var e=this.params;if(null!=e.tst){if(n(e.tst))return(i=new s).hTLV=e.tst,[i];if(e.tst instanceof s)return[e.tst];throw new t("params.tst has wrong value")}if(null!=e.res){var i,r=e.res;if(r instanceof s&&(r=r.tohex()),"string"!=typeof r||!n(r))throw new t("params.res has wrong value");return Qe.getTLVbyList(r,0,[1]),(i=new s).hTLV=e.tst,[i]}},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignatureTimeStamp,Je.asn1.cms.Attribute),Je.asn1.cades.CompleteCertificateRefs=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence,s=n.cades,a=s.OtherCertID,o=i.lang.String.isHex;s.CompleteCertificateRefs.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.21",this.params=null,this.getValueArray=function(){for(var e=this.params,i=[],n=0;n<e.array.length;n++){var s=e.array[n];if("string"==typeof s)if(-1!=s.indexOf("-----BEGIN"))s={cert:s};else{if(!o(s))throw new t("unsupported value: "+s);s={hash:s}}null!=e.alg&&null==s.alg&&(s.alg=e.alg),null!=e.hasis&&null==s.hasis&&(s.hasis=e.hasis);var c=new a(s);i.push(c)}return[new r({array:i})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.CompleteCertificateRefs,Je.asn1.cms.Attribute),Je.asn1.cades.OtherCertID=function(e){var t=Je.asn1,i=t.DERSequence,n=t.cms.IssuerSerial,r=t.cades,s=r.OtherHashValue,a=r.OtherHashAlgAndValue;r.OtherCertID.superclass.constructor.call(this),this.params=e,this.tohex=function(){var e=this.params;"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?e={cert:e}:_isHex(e)&&(e={hash:e}));var t=[],r=null;if(r=null!=e.alg?new a(e):new s(e),t.push(r),null!=e.cert&&1==e.hasis||null!=e.issuer&&null!=e.serial){var o=new n(e);t.push(o)}return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherCertID,Je.asn1.ASN1Object),Je.asn1.cades.OtherHash=function(e){var t=Je,i=t.asn1;i.cms;var n=i.cades,r=n.OtherHashAlgAndValue,s=n.OtherHashValue;t.crypto.Util.hashHex;var a=t.lang.String.isHex;n.OtherHash.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?e={cert:e}:a(e)&&(e={hash:e}));return(null!=e.alg?new r(e):new s(e)).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHash,Je.asn1.ASN1Object),Je.asn1.cades.CAdESUtil=new function(){},Je.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned=function(e){return(new Je.asn1.cms.CMSParser).getCMSSignedData(e)},Je.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned=function(e,t,i){var n=Qe,r=n.getChildIdx,s=n.getTLV,a=n.getV,o=Je.asn1,c=o.ASN1Object,d=o.cms,l=d.AttributeList,h=d.SignerInfo,u={},p=r(e,t);if(6!=p.length)throw"not supported items for SignerInfo (!=6)";var g=p.shift();u.version=s(e,g);var f=p.shift();u.si=s(e,f);var m=p.shift();u.digalg=s(e,m);var v=p.shift();u.sattrs=s(e,v);var y=p.shift();u.sigalg=s(e,y);var S=p.shift();u.sig=s(e,S),u.sigval=a(e,S);var b=null;return u.obj=new h,(b=new c).hTLV=u.version,u.obj.dCMSVersion=b,(b=new c).hTLV=u.si,u.obj.dSignerIdentifier=b,(b=new c).hTLV=u.digalg,u.obj.dDigestAlgorithm=b,(b=new c).hTLV=u.sattrs,u.obj.dSignedAttrs=b,(b=new c).hTLV=u.sigalg,u.obj.dSigAlg=b,(b=new c).hTLV=u.sig,u.obj.dSig=b,u.obj.dUnsignedAttrs=new l,u},void 0!==Je.asn1.csr&&Je.asn1.csr||(Je.asn1.csr={}),Je.asn1.csr.CertificationRequest=function(e){var t=Je.asn1,i=t.DERBitString,n=t.DERSequence,r=t.csr;t.x509;var s=r.CertificationRequestInfo;r.CertificationRequest.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.sign=function(){var e=new s(this.params).tohex(),t=new Je.crypto.Signature({alg:this.params.sigalg});t.init(this.params.sbjprvkey),t.updateHex(e);var i=t.sign();this.params.sighex=i},this.getPEM=function(){return ht(this.tohex(),"CERTIFICATE REQUEST")},this.tohex=function(){var e=this.params,t=new Je.asn1.csr.CertificationRequestInfo(this.params),r=new Je.asn1.x509.AlgorithmIdentifier({name:e.sigalg});if(null==e.sighex&&null!=e.sbjprvkey&&this.sign(),null==e.sighex)throw new Error("sighex or sbjprvkey parameter not defined");var s=new i({hex:"00"+e.sighex});return new n({array:[t,r,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.csr.CertificationRequest,Je.asn1.ASN1Object),Je.asn1.csr.CertificationRequestInfo=function(e){var t=Je.asn1;t.DERBitString;var i=t.DERSequence,n=t.DERInteger,r=t.DERUTF8String,s=t.DERTaggedObject,a=t.ASN1Util.newObject,o=t.csr,c=t.x509,d=c.X500Name,l=c.Extensions,h=c.SubjectPublicKeyInfo;o.AttributeList,o.CertificationRequestInfo.superclass.constructor.call(this),this.params=null,this.setByParam=function(e){null!=e&&(this.params=e)},this.tohex=function(){var e=this.params,t=[];if(t.push(new n({int:0})),t.push(new d(e.subject)),t.push(new h(kt.getKey(e.sbjpubkey))),null!=e.attrs){var o=function(e){for(var t=Error,i=Je.asn1.x509.Extensions,n=[],r=0;r<e.length;r++){var s=e[r],a=s.attr;if("extensionRequest"==a){var o={seq:[{oid:"1.2.840.113549.1.9.14"},{set:[new i(s.ext)]}]};n.push(o)}else if("unstructuredName"==a){o={seq:[{oid:"1.2.840.113549.1.9.2"},{set:s.names}]};n.push(o)}else{if("challengePassword"!=a)throw new t("unknown CSR attribute");o={seq:[{oid:"1.2.840.113549.1.9.7"},{set:[{utf8str:s.password}]}]};n.push(o)}}return{set:n}}(e.attrs),c=a({tag:{tage:"a0",obj:o}});t.push(c)}else if(null!=e.extreq){var u=new l(e.extreq);c=a({tag:{tage:"a0",obj:{seq:[{oid:"1.2.840.113549.1.9.14"},{set:[u]}]}}});t.push(c)}else t.push(new s({tag:"a0",explicit:!1,obj:new r({str:""})}));return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.csr.CertificationRequestInfo,Je.asn1.ASN1Object),Je.asn1.csr.AttributeList=function(e){},Nt(Je.asn1.csr.AttributeList,Je.asn1.ASN1Object),Je.asn1.csr.CSRUtil=new function(){},Je.asn1.csr.CSRUtil.newCSRPEM=function(e){return new Je.asn1.csr.CertificationRequest(e).getPEM()},Je.asn1.csr.CSRUtil.getParam=function(e,t){var i=Qe,n=i.getV,r=i.getIdxbyList,s=i.getTLVbyList,a=i.getTLVbyListEx,o=i.getVbyListEx,c={};if(-1==e.indexOf("-----BEGIN CERTIFICATE REQUEST"))throw new Error("argument is not PEM file");var d=ut(e,"CERTIFICATE REQUEST");t&&(c.tbs=s(d,0,[0]));try{var l=a(d,0,[0,1]);if("3000"==l)c.subject={};else{var h=new Ht;c.subject=h.getX500Name(l)}}catch(e){}var u=a(d,0,[0,2]),p=kt.getKey(u,null,"pkcs8pub");c.sbjpubkey=kt.getPEM(p,"PKCS8PUB");var g=function(e){var t=r(e,0,[0,3,0,0],"06");return"2a864886f70d01090e"!=n(e,t)?null:s(e,0,[0,3,0,1,0],"30")}(d);h=new Ht;null!=g&&(c.extreq=h.getExtParamArray(g));try{var f=a(d,0,[1],"30");h=new Ht;c.sigalg=h.getAlgorithmIdentifierName(f)}catch(e){}try{var m=o(d,0,[2]);c.sighex=m}catch(e){}return c},Je.asn1.csr.CSRUtil.verifySignature=function(e){try{var t=null;if("string"==typeof e&&-1!=e.indexOf("-----BEGIN CERTIFICATE REQUEST")?t=Je.asn1.csr.CSRUtil.getParam(e,!0):"object"==typeof e&&null!=e.sbjpubkey&&null!=e.sigalg&&null!=e.sighex&&null!=e.tbs&&(t=e),null==t)return!1;var i=new Je.crypto.Signature({alg:t.sigalg});return i.init(t.sbjpubkey),i.updateHex(t.tbs),i.verify(t.sighex)}catch(e){return alert(e),!1}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.ocsp&&Je.asn1.ocsp||(Je.asn1.ocsp={}),Je.asn1.ocsp.DEFAULT_HASH="sha1",Je.asn1.ocsp.OCSPResponse=function(e){Je.asn1.ocsp.OCSPResponse.superclass.constructor.call(this),Je.asn1.DEREnumerated;var t=Je.asn1.ASN1Util.newObject,i=Je.asn1.ocsp.ResponseBytes,n=["successful","malformedRequest","internalError","tryLater","_not_used_","sigRequired","unauthorized"];this.params=null,this._getStatusCode=function(){var e=this.params.resstatus;return"number"==typeof e?e:"string"!=typeof e?-1:n.indexOf(e)},this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params,n=this._getStatusCode();if(-1==n)throw new Error("responseStatus not supported: "+e.resstatus);if(0!=n)return t({seq:[{enum:{int:n}}]}).tohex();var r=new i(e);return t({seq:[{enum:{int:0}},{tag:{tag:"a0",explicit:!0,obj:r}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.OCSPResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponseBytes=function(e){Je.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier,r=t.DEROctetString,s=t.ocsp.BasicOCSPResponse;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if("ocspBasic"!=e.restype)throw new Error("not supported responseType: "+e.restype);var t=new s(e),a=[];return a.push(new n({name:"ocspBasic"})),a.push(new r({hex:t.tohex()})),new i({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponseBytes,Je.asn1.ASN1Object),Je.asn1.ocsp.BasicOCSPResponse=function(e){Je.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);var t=Error,i=Je.asn1,n=i.ASN1Object,r=i.DERSequence;i.DERGeneralizedTime;var s=i.DERTaggedObject,a=i.DERBitString;i.x509.Extensions;var o=i.x509.AlgorithmIdentifier,c=i.ocsp;c.ResponderID,_SingleResponseList=c.SingleResponseList,_ResponseData=c.ResponseData,this.params=null,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.tbsresp.tohex(),i=new Je.crypto.Signature({alg:e.sigalg});i.init(e.reskey),i.updateHex(t),e.sighex=i.sign()},this.tohex=function(){var e=this.params;null==e.tbsresp&&(e.tbsresp=new _ResponseData(e)),null==e.sighex&&null!=e.reskey&&this.sign();var i=[];if(i.push(e.tbsresp),i.push(new o({name:e.sigalg})),i.push(new a({hex:"00"+e.sighex})),null!=e.certs&&null!=e.certs.length){for(var c=[],d=0;d<e.certs.length;d++){var l=e.certs[d],h=null;if(Qe.isASN1HEX(l))h=l;else{if(!l.match(/-----BEGIN/))throw new t("certs["+d+"] not hex or PEM");h=ut(l)}c.push(new n({tlv:h}))}var u=new r({array:c});i.push(new s({tag:"a0",explicit:!0,obj:u}))}return new r({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.BasicOCSPResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponseData=function(e){Je.asn1.ocsp.ResponseData.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERGeneralizedTime,r=t.DERTaggedObject,s=t.x509.Extensions,a=t.ocsp,o=a.ResponderID;_SingleResponseList=a.SingleResponseList,this.params=null,this.tohex=function(){var e=this.params;e.respid,e.prodat,e.array;var t=[];if(t.push(new o(e.respid)),t.push(new n(e.prodat)),t.push(new _SingleResponseList(e.array)),null!=e.ext){var a=new s(e.ext);t.push(new r({tag:"a1",explicit:!0,obj:a}))}return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponseData,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponderID=function(e){Je.asn1.ocsp.ResponderID.superclass.constructor.call(this);var t=Je,i=t.asn1,n=i.ASN1Util.newObject,r=i.x509.X500Name,s=t.lang.String.isHex,a=Error;this.params=null,this.tohex=function(){var e=this.params;if(null!=e.key){var t,i=null;if("string"==typeof e.key){if(s(e.key)&&(i=e.key),e.key.match(/-----BEGIN CERTIFICATE/))null!=(t=new Ht(e.key).getExtSubjectKeyIdentifier())&&(i=t.kid.hex)}else if(e.key instanceof Ht)null!=(t=e.key.getExtSubjectKeyIdentifier())&&(i=t.kid.hex);if(null==i)throw new a("wrong key member value");return n({tag:{tag:"a2",explicit:!0,obj:{octstr:{hex:i}}}}).tohex()}if(null!=e.name){var o=null;if("string"==typeof e.name&&e.name.match(/-----BEGIN CERTIFICATE/))o=new Ht(e.name).getSubject();else e.name instanceof Ht?o=e.name.getSubject():"object"!=typeof e.name||null==e.name.array&&null==e.name.str||(o=e.name);if(null==o)throw new a("wrong name member value");return n({tag:{tag:"a1",explicit:!0,obj:new r(o)}}).tohex()}throw new a("key or name not specified")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponderID,Je.asn1.ASN1Object),Je.asn1.ocsp.SingleResponseList=function(e){Je.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.ocsp.SingleResponse;this.params=null,this.tohex=function(){var e=this.params;if("object"!=typeof e||null==e.length)throw new Error("params not specified properly");for(var t=[],r=0;r<e.length;r++)t.push(new n(e[r]));return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.SingleResponseList,Je.asn1.ASN1Object),Je.asn1.ocsp.SingleResponse=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERGeneralizedTime,s=i.DERTaggedObject,a=i.ocsp,o=a.CertID,c=a.CertStatus,d=i.x509.Extensions;a.SingleResponse.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,i=[];if(null==e.certid)throw new t("certid unspecified");if(null==e.status)throw new t("status unspecified");if(null==e.thisupdate)throw new t("thisupdate unspecified");if(i.push(new o(e.certid)),i.push(new c(e.status)),i.push(new r(e.thisupdate)),null!=e.nextupdate){var a=new r(e.nextupdate);i.push(new s({tag:"a0",explicit:!0,obj:a}))}if(null!=e.ext){var l=new d(e.ext);i.push(new s({tag:"a1",explicit:!0,obj:l}))}return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.SingleResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.CertID=function(e){var t=Je,i=t.asn1,n=i.DEROctetString,r=i.DERInteger,s=i.DERSequence,a=i.x509.AlgorithmIdentifier,o=i.ocsp;o.DEFAULT_HASH;var c=t.crypto.Util.hashHex,d=Ht,l=Qe.getVbyList;o.CertID.superclass.constructor.call(this),this.DEFAULT_HASH="sha1",this.params=null,this.setByValue=function(e,t,i,n){null==n&&(n=this.DEFAULT_HASH),this.params={alg:n,issname:e,isskey:t,sbjsn:i}},this.setByCert=function(e,t,i){null==i&&(i=this.DEFAULT_HASH),this.params={alg:i,issuerCert:e,subjectCert:t}},this.getParamByCerts=function(e,t,i){null==i&&(i=this.DEFAULT_HASH);var n=new d(e),r=new d(t),s=c(n.getSubjectHex(),i),a=n.getPublicKeyHex();return{alg:i,issname:s,isskey:c(l(a,0,[1],"03",!0),i),sbjsn:r.getSerialNumberHex()}},this.tohex=function(){if("object"!=typeof this.params)throw new Error("params not set");var e,t,i,o,c=this.params;if(o=null==c.alg?this.DEFAULT_HASH:c.alg,null!=c.issuerCert&&null!=c.subjectCert){var d=this.getParamByCerts(c.issuerCert,c.subjectCert,o);e=d.issname,t=d.isskey,i=d.sbjsn}else{if(null==c.issname||null==c.isskey||null==c.sbjsn)throw new Error("required param members not defined");e=c.issname,t=c.isskey,i=c.sbjsn}var l=new a({name:o}),h=new n({hex:e}),u=new n({hex:t}),p=new r({hex:i}),g=new s({array:[l,h,u,p]});return this.hTLV=g.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.CertID,Je.asn1.ASN1Object),Je.asn1.ocsp.CertStatus=function(e){Je.asn1.ocsp.CertStatus.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if("good"==e.status)return"8000";if("unknown"==e.status)return"8200";if("revoked"==e.status){var t=[{gentime:{str:e.time}}];null!=e.reason&&t.push({tag:{tag:"a0",explicit:!0,obj:{enum:{int:e.reason}}}});var i={tag:"a1",explicit:!1,obj:{seq:t}};return Je.asn1.ASN1Util.newObject({tag:i}).tohex()}throw new Error("bad status")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.CertStatus,Je.asn1.ASN1Object),Je.asn1.ocsp.Request=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;if(n.Request.superclass.constructor.call(this),this.dReqCert=null,this.dExt=null,this.tohex=function(){var e=[];if(null===this.dReqCert)throw"reqCert not set";e.push(this.dReqCert);var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){var r=new n.CertID(e);this.dReqCert=r}},Nt(Je.asn1.ocsp.Request,Je.asn1.ASN1Object),Je.asn1.ocsp.TBSRequest=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;n.TBSRequest.superclass.constructor.call(this),this.version=0,this.dRequestorName=null,this.dRequestList=[],this.dRequestExt=null,this.setRequestListByParam=function(e){for(var t=[],i=0;i<e.length;i++){var r=new n.Request(e[0]);t.push(r)}this.dRequestList=t},this.tohex=function(){var e=[];if(0!==this.version)throw"not supported version: "+this.version;if(null!==this.dRequestorName)throw"requestorName not supported";var t=new i({array:this.dRequestList});if(e.push(t),null!==this.dRequestExt)throw"requestExtensions not supported";var n=new i({array:e});return this.hTLV=n.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList&&this.setRequestListByParam(e.reqList)},Nt(Je.asn1.ocsp.TBSRequest,Je.asn1.ASN1Object),Je.asn1.ocsp.OCSPRequest=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;if(n.OCSPRequest.superclass.constructor.call(this),this.dTbsRequest=null,this.dOptionalSignature=null,this.tohex=function(){var e=[];if(null===this.dTbsRequest)throw"tbsRequest not set";if(e.push(this.dTbsRequest),null!==this.dOptionalSignature)throw"optionalSignature not supported";var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList){var r=new n.TBSRequest(e);this.dTbsRequest=r}},Nt(Je.asn1.ocsp.OCSPRequest,Je.asn1.ASN1Object),Je.asn1.ocsp.OCSPUtil={},Je.asn1.ocsp.OCSPUtil.getRequestHex=function(e,t,i){var n=Je.asn1.ocsp;void 0===i&&(i=n.DEFAULT_HASH);var r={alg:i,issuerCert:e,subjectCert:t};return new n.OCSPRequest({reqList:[r]}).tohex()},Je.asn1.ocsp.OCSPUtil.getOCSPResponseInfo=function(e){var t=Qe,i=t.getVbyList,n=t.getVbyListEx,r=t.getIdxbyList;t.getIdxbyListEx;var s=t.getV,a={};try{var o=n(e,0,[0],"0a");a.responseStatus=parseInt(o,16)}catch(e){}if(0!==a.responseStatus)return a;try{var c=r(e,0,[1,0,1,0,0,2,0,1]);"80"===e.substr(c,2)?a.certStatus="good":"a1"===e.substr(c,2)?(a.certStatus="revoked",a.revocationTime=ot(i(e,c,[0]))):"82"===e.substr(c,2)&&(a.certStatus="unknown")}catch(e){}try{var d=r(e,0,[1,0,1,0,0,2,0,2]);a.thisUpdate=ot(s(e,d))}catch(e){}try{var l=r(e,0,[1,0,1,0,0,2,0,3]);"a0"===e.substr(l,2)&&(a.nextUpdate=ot(i(e,l,[0])))}catch(e){}return a},Je.asn1.ocsp.OCSPParser=function(){var e=Error,t=Ht,i=new t,n=Qe,r=n.getV,s=n.getTLV,a=n.getIdxbyList,o=n.getVbyList,c=n.getTLVbyList,d=n.getVbyListEx,l=n.getTLVbyListEx,h=n.getChildIdx;this.getOCSPRequest=function(t){var i=h(t,0);if(1!=i.length&&2!=i.length)throw new e("wrong number elements: "+i.length);return this.getTBSRequest(s(t,i[0]))},this.getTBSRequest=function(e){var t={},n=l(e,0,[0],"30");t.array=this.getRequestList(n);var r=l(e,0,["[2]",0],"30");return null!=r&&(t.ext=i.getExtParamArray(r)),t},this.getRequestList=function(e){for(var t=[],i=h(e,0),n=0;n<i.length;n++){e=s(e,i[n]);t.push(this.getRequest(e))}return t},this.getRequest=function(t){var n=h(t,0);if(1!=n.length&&2!=n.length)throw new e("wrong number elements: "+n.length);var r=this.getCertID(s(t,n[0]));if(2==n.length){var o=a(t,0,[1,0]);r.ext=i.getExtParamArray(s(t,o))}return r},this.getCertID=function(i){var n=h(i,0);if(4!=n.length)throw new e("wrong number elements: "+n.length);var a=new t,o={};return o.alg=a.getAlgorithmIdentifierName(s(i,n[0])),o.issname=r(i,n[1]),o.isskey=r(i,n[2]),o.sbjsn=r(i,n[3]),o},this.getOCSPResponse=function(e){var t,i=h(e,0),n=r(e,i[0]),s=parseInt(n);if(1==i.length)return{resstatus:s};var a=c(e,0,[1,0]);return(t=this.getResponseBytes(a)).resstatus=s,t},this.getResponseBytes=function(e){var t,i=h(e,0),n=c(e,0,[1,0]);t=this.getBasicOCSPResponse(n);var s=r(e,i[0]);return t.restype=Je.asn1.x509.OID.oid2name(xt(s)),t},this.getBasicOCSPResponse=function(e){var t,i=h(e,0);t=this.getResponseData(s(e,i[0]));var n=new Ht;t.alg=n.getAlgorithmIdentifierName(s(e,i[1]));var a=r(e,i[2]);t.sighex=a.substr(2);var o=d(e,0,["[0]"]);if(null!=o){for(var c=h(o,0),l=[],u=0;u<c.length;u++){var p=s(o,c[u]);l.push(p)}t.certs=l}return t},this.getResponseData=function(e){var t=h(e,0),i=t.length,n={},a=0;"a0"==e.substr(t[0],2)&&a++,n.respid=this.getResponderID(s(e,t[a++]));var o=r(e,t[a++]);if(n.prodat=ot(o),n.array=this.getSingleResponseList(s(e,t[a++])),"a1"==e.substr(t[i-1],2)){var d=c(e,t[i-1],[0]),l=new Ht;n.ext=l.getExtParamArray(d)}return n},this.getResponderID=function(e){var t={};if("a2"==e.substr(0,2)){var i=o(e,0,[0]);t.key=i}if("a1"==e.substr(0,2)){var n=c(e,0,[0]),r=new Ht;t.name=r.getX500Name(n)}return t},this.getSingleResponseList=function(e){for(var t=h(e,0),i=[],n=0;n<t.length;n++){var r=this.getSingleResponse(s(e,t[n]));i.push(r)}return i},this.getSingleResponse=function(e){var t=h(e,0),i={},n=this.getCertID(s(e,t[0]));i.certid=n;var a=this.getCertStatus(s(e,t[1]));if(i.status=a,"18"==e.substr(t[2],2)){var d=r(e,t[2]);i.thisupdate=ot(d)}for(var l=3;l<t.length;l++){if("a0"==e.substr(t[l],2)){var u=o(e,t[l],[0],"18");i.nextupdate=ot(u)}if("a1"==e.substr(t[l],2)){var p=new Ht,g=c(e,0,[l,0]);i.ext=p.getExtParamArray(g)}}return i},this.getCertStatus=function(e){var t={};if("8000"==e)return{status:"good"};if("8200"==e)return{status:"unknown"};if("a1"==e.substr(0,2)){t.status="revoked";var i=ot(o(e,0,[0]));t.time=i}return t}},void 0!==Je&&Je||(Je={}),void 0!==Je.lang&&Je.lang||(Je.lang={}),Je.lang.String=function(){},"function"==typeof Buffer?(Ze=function(e){return it(Buffer.from(e,"utf8").toString("base64"))},Xe=function(e){return Buffer.from(nt(e),"base64").toString("utf8")}):(Ze=function(e){return rt(gt(Ct(e)))},Xe=function(e){return decodeURIComponent(ft(st(e)))}),Je.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},Je.lang.String.isHex=function(e){return $t(e)},Je.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},Je.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=nt(e),Je.lang.String.isBase64(e))},Je.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},Je.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},Je.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},Je.lang.String.isMail=function(e){return null!==e.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/)};var At=function(e,t,i){return null==i&&(i="0"),e.length>=t?e:new Array(t-e.length+1).join(i)+e};function Pt(e,t){for(var i=0,n=0;n<e.length;n++)i|=1<<t[e[n]];var r=i.toString(2),s="";for(n=r.length-1;n>=0;n--)s+=r[n];return s}function Dt(e,t,i){if("object"==typeof e){t=String(t).split(".");for(var n=0;n<t.length&&e;n++){var r=t[n];r.match(/^[0-9]+$/)&&(r=parseInt(r)),e=e[r]}return e||!1===e?e:i}}function Nt(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:ne.algo.MD5,sha1:ne.algo.SHA1,sha224:ne.algo.SHA224,sha256:ne.algo.SHA256,sha384:ne.algo.SHA384,sha512:ne.algo.SHA512,ripemd160:ne.algo.RIPEMD160},this.getDigestInfoHex=function(e,t){if(void 0===this.DIGESTINFOHEAD[t])throw"alg not supported in Util.DIGESTINFOHEAD: "+t;return this.DIGESTINFOHEAD[t]+e},this.getPaddedDigestInfoHex=function(e,t,i){var n=this.getDigestInfoHex(e,t),r=i/4;if(n.length+22>r)throw"key is too short for SigAlg: keylen="+i+","+t;for(var s="0001",a="00"+n,o="",c=r-4-a.length,d=0;d<c;d+=2)o+="ff";return s+o+a},this.hashString=function(e,t){return new Je.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new Je.crypto.MessageDigest({alg:t}).digestHex(e)},this.sha1=function(e){return this.hashString(e,"sha1")},this.sha256=function(e){return this.hashString(e,"sha256")},this.sha256Hex=function(e){return this.hashHex(e,"sha256")},this.sha512=function(e){return this.hashString(e,"sha512")},this.sha512Hex=function(e){return this.hashHex(e,"sha512")},this.isKey=function(e){return e instanceof Ge||e instanceof Je.crypto.DSA||e instanceof Je.crypto.ECDSA}},Je.crypto.Util.md5=function(e){return new Je.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},Je.crypto.Util.ripemd160=function(e){return new Je.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},Je.crypto.Util.SECURERANDOMGEN=new Ve,Je.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return Je.crypto.Util.SECURERANDOMGEN.nextBytes(t),et(t)},Je.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new de(Je.crypto.Util.getRandomHexOfNbytes(e),16)},Je.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,i=new Array((e-t)/8+1);return Je.crypto.Util.SECURERANDOMGEN.nextBytes(i),i[0]=(255<<t&255^255)&i[0],et(i)},Je.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new de(Je.crypto.Util.getRandomHexOfNbits(e),16)},Je.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var i=Je.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(i))return i}},Je.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var i=e.compareTo(t);if(1==i)throw"biMin is greater than biMax";if(0==i)return e;var n=t.subtract(e);return Je.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},Je.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=Je.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=Je.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=Je.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[e].create()}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=ne.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(ne.enc.Hex)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}if(-1!=":sha256:".indexOf(e)&&"sjcl"==t){try{this.md=new sjcl.hash.sha256}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=sjcl.codec.hex.toBits(e);this.md.update(t)},this.digest=function(){var e=this.md.finalize();return sjcl.codec.hex.fromBits(e)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==e&&void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},Je.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},Je.crypto.MessageDigest.getHashLength=function(e){var t=Je.crypto.MessageDigest,i=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[i])throw"not supported algorithm: "+e;return t.HASHLENGTH[i]},Je.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},Je.crypto.Mac=function(e){this.setAlgAndProvider=function(e,t){if(null==(e=e.toLowerCase())&&(e="hmacsha1"),"hmac"!=(e=e.toLowerCase()).substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+e;void 0===t&&(t=Je.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var i=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(i)&&"cryptojs"==t){try{var n=Je.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[i];this.mac=ne.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+i+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=ne.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(ne.enc.Hex)},this.doFinalString=function(e){return this.updateString(e),this.doFinal()},this.doFinalHex=function(e){return this.updateHex(e),this.doFinal()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(e){if("string"==typeof e){var t=e;return e.length%2!=1&&e.match(/^[0-9A-Fa-f]+$/)||(t=lt(e)),void(this.pass=ne.enc.Hex.parse(t))}if("object"!=typeof e)throw"KJUR.crypto.Mac unsupported password type: "+e;t=null;if(void 0!==e.hex){if(e.hex.length%2!=0||!e.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+e.hex;t=e.hex}if(void 0!==e.utf8&&(t=at(e.utf8)),void 0!==e.rstr&&(t=lt(e.rstr)),void 0!==e.b64&&(t=ce(e.b64)),void 0!==e.b64u&&(t=st(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=ne.enc.Hex.parse(t)},void 0!==e&&(void 0!==e.pass&&this.setPassword(e.pass),void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},Je.crypto.Signature=function(e){var t=null;if(this._setAlgNames=function(){var e=this.algName.match(/^(.+)with(.+)$/);e&&(this.mdAlgName=e[1].toLowerCase(),this.pubkeyAlgName=e[2].toLowerCase(),"rsaandmgf1"==this.pubkeyAlgName&&"sha"==this.mdAlgName&&(this.mdAlgName="sha1"))},this._zeroPaddingOfSignature=function(e,t){for(var i="",n=t/4-e.length,r=0;r<n;r++)i+="0";return i+e},this.setAlgAndProvider=function(e,t){if(this._setAlgNames(),"cryptojs/jsrsa"!=t)throw new Error("provider not supported: "+t);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=new Je.crypto.MessageDigest({alg:this.mdAlgName})}catch(e){throw new Error("setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+e)}this.init=function(e,t){var i=null;try{i=void 0===t?kt.getKey(e):kt.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===i.isPrivate)this.prvKey=i,this.state="SIGN";else{if(!0!==i.isPublic)throw"init failed.:"+i;this.pubKey=i,this.state="VERIFY"}},this.updateString=function(e){this.md.updateString(e)},this.updateHex=function(e){this.md.updateHex(e)},this.sign=function(){if(this.sHashHex=this.md.digest(),void 0===this.prvKey&&void 0!==this.ecprvhex&&void 0!==this.eccurvename&&void 0!==Je.crypto.ECDSA&&(this.prvKey=new Je.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof Ge&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof Ge&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof Je.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof Je.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(e){return this.updateString(e),this.sign()},this.signHex=function(e){return this.updateHex(e),this.sign()},this.verify=function(e){if(this.sHashHex=this.md.digest(),void 0===this.pubKey&&void 0!==this.ecpubhex&&void 0!==this.eccurvename&&void 0!==Je.crypto.ECDSA&&(this.pubKey=new Je.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof Ge&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof Ge&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==Je.crypto.ECDSA&&this.pubKey instanceof Je.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==Je.crypto.DSA&&this.pubKey instanceof Je.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(e,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(e){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(e){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(e){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(e){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=e,void 0!==e&&(void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov?this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=e.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==e.psssaltlen&&(this.pssSaltLen=e.psssaltlen),void 0!==e.prvkeypem)){if(void 0!==e.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{t=kt.getKey(e.prvkeypem);this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},Je.crypto.Cipher=function(e){},Je.crypto.Cipher.encrypt=function(e,t,i,n){if(null!=Dt(n,"enclag")&&(i=n.encalg),"string"==typeof i&&"-CBC"==i.substr(-4)){var r=t,s=e;null!=Dt(n,"key")&&(r=n.key),null!=Dt(n,"enc")&&(hEnc=n.enc);var a,o=ne.enc.Hex.parse(r),c=ne.enc.Hex.parse(s),d=ne.enc.Hex.parse(n.iv);if("des-EDE3-CBC"==i)a=ne.TripleDES.encrypt(c,o,{iv:d});else{if("aes128-CBC"!=i&&"aes256-CBC"!=i)throw new Error("unsupported algorithm: "+i);a=ne.AES.encrypt(c,o,{iv:d})}return a+""}throw new Error("Cipher.encrypt: unsupported key or algorithm")},Je.crypto.Cipher.decrypt=function(e,t,i,n){if(null!=Dt(n,"enclag")&&(i=n.encalg),"string"==typeof i&&"-CBC"==i.substr(-4)){var r=t,s=e;null!=Dt(n,"key")&&(r=n.key),null!=Dt(n,"enc")&&(s=n.enc);var a,o=ne.enc.Hex.parse(r),c=ne.enc.Hex.parse(s),d=ne.enc.Hex.parse(n.iv);if("des-EDE3-CBC"==i)a=ne.TripleDES.decrypt({ciphertext:c},o,{iv:d});else{if("aes128-CBC"!=i&&"aes256-CBC"!=i)throw new Error("unsupported algorithm: "+i);a=ne.AES.decrypt({ciphertext:c},o,{iv:d})}return ne.enc.Hex.stringify(a)}throw new Error("Cipher.decrypt: unsupported key or algorithm")},Je.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040022":"secp384r1","2b81040023":"secp521r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.ECDSA=function(e){var t=Error,i=de,n=We,r=Je.crypto.ECDSA,s=Je.crypto.ECParameterDB,a=r.getName,o=Qe,c=o.getVbyListEx,d=o.isASN1HEX,l=new Ve;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new i(e.bitLength(),l).mod(e.subtract(i.ONE)).add(i.ONE)},this.setNamedCurve=function(e){this.ecparams=s.getByName(e),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=e},this.setPrivateKeyHex=function(e){this.isPrivate=!0,this.prvKeyHex=e},this.setPublicKeyHex=function(e){this.isPublic=!0,this.pubKeyHex=e},this.getPublicKeyXYHex=function(){var e=this.pubKeyHex;if("04"!==e.substr(0,2))throw"this method supports uncompressed format(04) only";var t=this.ecparams.keycharlen;if(e.length!==2+2*t)throw"malformed public key hex length";var i={};return i.x=e.substr(2,t),i.y=e.substr(2+t),i},this.getShortNISTPCurveName=function(){var e=this.curveName;return"secp256r1"===e||"NIST P-256"===e||"P-256"===e||"prime256v1"===e?"P-256":"secp384r1"===e||"NIST P-384"===e||"P-384"===e?"P-384":"secp521r1"===e||"NIST P-521"===e||"P-521"===e?"P-521":null},this.generateKeyPairHex=function(){var e=this.ecparams.n,t=this.getBigRandom(e),i=this.ecparams.keycharlen,n=("0000000000"+t.toString(16)).slice(-i);return this.setPrivateKeyHex(n),{ecprvhex:n,ecpubhex:this.generatePublicKeyHex()}},this.generatePublicKeyHex=function(){var e=new i(this.prvKeyHex,16),t=this.ecparams.G.multiply(e),n=t.getX().toBigInteger(),r=t.getY().toBigInteger(),s=this.ecparams.keycharlen,a="04"+("0000000000"+n.toString(16)).slice(-s)+("0000000000"+r.toString(16)).slice(-s);return this.setPublicKeyHex(a),a},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new i(t,16),s=this.ecparams.n,a=new i(e.substring(0,this.ecparams.keycharlen),16);do{var o=this.getBigRandom(s),c=this.ecparams.G.multiply(o).getX().toBigInteger().mod(s)}while(c.compareTo(i.ZERO)<=0);var d=o.modInverse(s).multiply(a.add(n.multiply(c))).mod(s);return r.biRSSigToASN1Sig(c,d)},this.sign=function(e,t){var n=t,r=this.ecparams.n,s=i.fromByteArrayUnsigned(e);do{var a=this.getBigRandom(r),o=this.ecparams.G.multiply(a).getX().toBigInteger().mod(r)}while(o.compareTo(de.ZERO)<=0);var c=a.modInverse(r).multiply(s.add(n.multiply(o))).mod(r);return this.serializeSig(o,c)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,s){try{var a,o,c=r.parseSigHex(t);a=c.r,o=c.s;var d=n.decodeFromHex(this.ecparams.curve,s),l=new i(e.substring(0,this.ecparams.keycharlen),16);return this.verifyRaw(l,a,o,d)}catch(e){return!1}},this.verify=function(e,t,r){var s,a,o;if(Bitcoin.Util.isArray(t)){var c=this.parseSig(t);s=c.r,a=c.s}else{if("object"!=typeof t||!t.r||!t.s)throw"Invalid value for signature";s=t.r,a=t.s}if(r instanceof We)o=r;else{if(!Bitcoin.Util.isArray(r))throw"Invalid format for pubkey value, must be byte array or ECPointFp";o=n.decodeFrom(this.ecparams.curve,r)}var d=i.fromByteArrayUnsigned(e);return this.verifyRaw(d,s,a,o)},this.verifyRaw=function(e,t,n,r){var s=this.ecparams.n,a=this.ecparams.G;if(t.compareTo(i.ONE)<0||t.compareTo(s)>=0)return!1;if(n.compareTo(i.ONE)<0||n.compareTo(s)>=0)return!1;var o=n.modInverse(s),c=e.multiply(o).mod(s),d=t.multiply(o).mod(s);return a.multiply(c).add(r.multiply(d)).getX().toBigInteger().mod(s).equals(t)},this.serializeSig=function(e,t){var i=e.toByteArraySigned(),n=t.toByteArraySigned(),r=[];return r.push(2),r.push(i.length),(r=r.concat(i)).push(2),r.push(n.length),(r=r.concat(n)).unshift(r.length),r.unshift(48),r},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var r=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:i.fromByteArrayUnsigned(n),s:i.fromByteArrayUnsigned(r)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:i.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:i.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===d(e))throw new Error("not ASN.1 hex string");var t,i,n;try{t=c(e,0,["[0]",0],"06"),i=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=a(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(i),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===d(e))throw new t("not ASN.1 hex string");var i,n,r;try{c(e,0,[1,0],"06"),i=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{r=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=a(i),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(r),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===d(e))throw new t("not ASN.1 hex string");var i,n;try{c(e,0,[0,0],"06"),i=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=a(i),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,i){if(!1===d(e))throw new t("not ASN.1 hex string");var n,r;try{n=c(e,0,[0,5,0,1],"06"),r=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=a(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(r)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},Je.crypto.ECDSA.parseSigHex=function(e){var t=Je.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new de(t.r,16),s:new de(t.s,16)}},Je.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=Qe,i=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var r=i(e,0);if(2!=r.length)throw new Error("signature shall have two elements");var s=r[0],a=r[1];if("02"!=e.substr(s,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(a,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,s),s:n(e,a)}},Je.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=Je.crypto.ECDSA.parseSigHexInHexRS(e),i=t.r,n=t.s;if(i.length>=130&&i.length<=134){if(i.length%2!=0)throw Error("unknown ECDSA sig r length error");if(n.length%2!=0)throw Error("unknown ECDSA sig s length error");"00"==i.substr(0,2)&&(i=i.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var r=Math.max(i.length,n.length);return(i=("000000"+i).slice(-r))+(n=("000000"+n).slice(-r))}if("00"==i.substr(0,2)&&i.length%32==2&&(i=i.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),i.length%32==30&&(i="00"+i),n.length%32==30&&(n="00"+n),i.length%32!=0)throw Error("unknown ECDSA sig r length error");if(n.length%32!=0)throw Error("unknown ECDSA sig s length error");return i+n},Je.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length%4!=0)throw Error("unknown ECDSA concatinated r-s sig length error");var t=e.substr(0,e.length/2),i=e.substr(e.length/2);return Je.crypto.ECDSA.hexRSSigToASN1Sig(t,i)},Je.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var i=new de(e,16),n=new de(t,16);return Je.crypto.ECDSA.biRSSigToASN1Sig(i,n)},Je.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var i=Je.asn1,n=new i.DERInteger({bigint:e}),r=new i.DERInteger({bigint:t});return new i.DERSequence({array:[n,r]}).tohex()},Je.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":"2b81040023"===e?"secp521r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":-1!=="|secp521r1|NIST P-521|P-521|".indexOf(e)?"secp521r1":null},void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.ECParameterDB=new function(){var e={},t={};function i(e){return new de(e,16)}this.getByName=function(i){var n=i;if(void 0!==t[n]&&(n=t[i]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,r,s,a,o,c,d,l,h,u,p,g){e[n]={};var f=i(s),m=i(a),v=i(o),y=i(c),S=i(d),b=new ze(f,m,v),w=b.decodePointHex("04"+l+h);e[n].name=n,e[n].keylen=r,e[n].keycharlen=2*Math.ceil(r/8),e[n].curve=b,e[n].G=w,e[n].n=y,e[n].h=S,e[n].oid=p,e[n].info=g;for(var E=0;E<u.length;E++)t[u[E]]=n}},Je.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),Je.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),Je.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),Je.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),Je.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),Je.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),Je.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),Je.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),Je.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),Je.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]),void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.DSA=function(){var e=Qe;e.getVbyList;var t=e.getVbyListEx,i=e.isASN1HEX,n=de;this.p=null,this.q=null,this.g=null,this.y=null,this.x=null,this.type="DSA",this.isPrivate=!1,this.isPublic=!1,this.setPrivate=function(e,t,i,n,r){this.isPrivate=!0,this.p=e,this.q=t,this.g=i,this.y=n,this.x=r},this.setPrivateHex=function(e,t,i,n,r){var s,a,o,c,d;s=new de(e,16),a=new de(t,16),o=new de(i,16),c="string"==typeof n&&n.length>1?new de(n,16):null,d=new de(r,16),this.setPrivate(s,a,o,c,d)},this.setPublic=function(e,t,i,n){this.isPublic=!0,this.p=e,this.q=t,this.g=i,this.y=n,this.x=null},this.setPublicHex=function(e,t,i,n){var r,s,a,o;r=new de(e,16),s=new de(t,16),a=new de(i,16),o=new de(n,16),this.setPublic(r,s,a,o)},this.signWithMessageHash=function(e){var t=this.p,i=this.q,n=this.g;this.y;var r=this.x,s=Je.crypto.Util.getRandomBigIntegerMinToMax(de.ONE.add(de.ONE),i.subtract(de.ONE)),a=new de(e.substr(0,i.bitLength()/4),16),o=n.modPow(s,t).mod(i),c=s.modInverse(i).multiply(a.add(r.multiply(o))).mod(i);return Je.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:o}},{int:{bigint:c}}]})},this.verifyWithMessageHash=function(e,t){var i=this.p,n=this.q,r=this.g,s=this.y,a=this.parseASN1Signature(t),o=a[0],c=a[1],d=new de(e.substr(0,n.bitLength()/4),16);if(de.ZERO.compareTo(o)>0||o.compareTo(n)>0)throw"invalid DSA signature";if(de.ZERO.compareTo(c)>=0||c.compareTo(n)>0)throw"invalid DSA signature";var l=c.modInverse(n),h=d.multiply(l).mod(n),u=o.multiply(l).mod(n);return 0==r.modPow(h,i).multiply(s.modPow(u,i)).mod(i).mod(n).compareTo(o)},this.parseASN1Signature=function(e){try{return[new n(t(e,0,[0],"02"),16),new n(t(e,0,[1],"02"),16)]}catch(e){throw new Error("malformed ASN.1 DSA signature")}},this.readPKCS5PrvKeyHex=function(e){var n,r,s,a,o;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),r=t(e,0,[2],"02"),s=t(e,0,[3],"02"),a=t(e,0,[4],"02"),o=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,r,s,a,o)},this.readPKCS8PrvKeyHex=function(e){var n,r,s,a;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),r=t(e,0,[1,1,1],"02"),s=t(e,0,[1,1,2],"02"),a=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,r,s,null,a)},this.readPKCS8PubKeyHex=function(e){var n,r,s,a;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),r=t(e,0,[0,1,1],"02"),s=t(e,0,[0,1,2],"02"),a=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,r,s,a)},this.readCertPubKeyHex=function(e,n){var r,s,a,o;if(!1===i(e))throw new Error("not ASN.1 hex string");try{r=t(e,0,[0,5,0,1,0],"02"),s=t(e,0,[0,5,0,1,1],"02"),a=t(e,0,[0,5,0,1,2],"02"),o=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(r,s,a,o)}};var kt=function(){var e=function(e,i,n){return t(ne.AES,e,i,n)},t=function(e,t,i,n){var r=ne.enc.Hex.parse(t),s=ne.enc.Hex.parse(i),a=ne.enc.Hex.parse(n),o={};o.key=s,o.iv=a,o.ciphertext=r;var c=e.decrypt(o,s,{iv:a});return ne.enc.Hex.stringify(c)},i=function(e,t,i){return n(ne.AES,e,t,i)},n=function(e,t,i,n){var r=ne.enc.Hex.parse(t),s=ne.enc.Hex.parse(i),a=ne.enc.Hex.parse(n),o=e.encrypt(r,s,{iv:a}),c=ne.enc.Hex.parse(o.toString());return ne.enc.Base64.stringify(c)},r={"AES-256-CBC":{proc:e,eproc:i,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:i,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:i,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,i,n){return t(ne.TripleDES,e,i,n)},eproc:function(e,t,i){return n(ne.TripleDES,e,t,i)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,i,n){return t(ne.DES,e,i,n)},eproc:function(e,t,i){return n(ne.DES,e,t,i)},keylen:8,ivlen:8}},s=function(e){var t={},i=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));i&&(t.cipher=i[1],t.ivsalt=i[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var r=-1,s=0;-1!=e.indexOf("\r\n\r\n")&&(r=e.indexOf("\r\n\r\n"),s=2),-1!=e.indexOf("\n\n")&&(r=e.indexOf("\n\n"),s=1);var a=e.indexOf("-----END");if(-1!=r&&-1!=a){var o=e.substring(r+2*s,a-s);o=o.replace(/\s+/g,""),t.data=o}return t},a=function(e,t,i){for(var n=i.substring(0,16),s=ne.enc.Hex.parse(n),a=ne.enc.Utf8.parse(t),o=r[e].keylen+r[e].ivlen,c="",d=null;;){var l=ne.algo.MD5.create();if(null!=d&&l.update(d),l.update(a),l.update(s),d=l.finalize(),(c+=ne.enc.Hex.stringify(d)).length>=2*o)break}var h={};return h.keyhex=c.substr(0,2*r[e].keylen),h.ivhex=c.substr(2*r[e].keylen,2*r[e].ivlen),h},o=function(e,t,i,n){var s=ne.enc.Base64.parse(e),a=ne.enc.Hex.stringify(s);return(0,r[t].proc)(a,i,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return s(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,i){return a(e,t,i)},decryptKeyB64:function(e,t,i,n){return o(e,t,i,n)},getDecryptedKeyHex:function(e,t){var i=s(e),n=i.cipher,r=i.ivsalt,c=i.data,d=a(n,t,r).keyhex;return o(c,n,d,r)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,i,n,s){var o="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===r[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===s||null==s){var c=function(e){var t=ne.lib.WordArray.random(e);return ne.enc.Hex.stringify(t)}(r[n].ivlen);s=c.toUpperCase()}var d=function(e,t,i,n){return(0,r[t].eproc)(e,i,n)}(t,n,a(n,i,s).keyhex,s);o="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return o+="Proc-Type: 4,ENCRYPTED\r\n",o+="DEK-Info: "+n+","+s+"\r\n",o+="\r\n",o+=d.replace(/(.{64})/g,"$1\r\n"),o+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},getEncryptedPKCS8PEM:function(e,t,i){return ht(this.getEncryptedPKCS8Hex(e,t,i),"ENCRYPTED PRIVATE KEY")},getEncryptedPKCS8Hex:function(e,t,i){var n;(n=null==i||null==i?{}:JSON.parse(JSON.stringify(i))).plain=e,this.initPBES2Param(n),this.encryptPBES2Param(n,t);var r=this.generatePBES2ASN1Param(n);return Je.asn1.ASN1Util.newObject(r).tohex()},initPBES2Param:function(e){var t;(null==Dt(e,"encalg")&&(e.encalg="aes256-CBC"),null==Dt(e,"iter")&&(e.iter=2048),null==Dt(e,"prf")&&(e.prf="hmacWithSHA256"),null==Dt(e,"salt")&&(e.salt=ne.enc.Hex.stringify(ne.lib.WordArray.random(8))),null==Dt(e,"enciv"))&&("des-EDE3-CBC"==e.encalg&&(t=8),"aes128-CBC"==e.encalg&&(t=16),"aes256-CBC"==e.encalg&&(t=16),e.enciv=ne.enc.Hex.stringify(ne.lib.WordArray.random(t)))},encryptPBES2Param:function(e,t){var i=kt.getDKFromPBES2Param(e,t);try{var n=Je.crypto.Cipher.encrypt(e.plain,i,e.encalg,{iv:e.enciv})}catch(t){throw new Error("encrypt error: "+e.plain+" "+i+" "+e.encalg+" "+e.enciv)}e.enc=n},generatePBES2ASN1Param:function(e){var t={seq:[{seq:[{oid:"pkcs5PBES2"},{seq:[{seq:[{oid:"pkcs5PBKDF2"},{seq:[{octstr:{hex:e.salt}},{int:{hex:It(e.iter)}}]}]},{seq:[{oid:e.encalg},{octstr:{hex:e.enciv}}]}]}]},{octstr:{hex:e.enc}}]};return"hmacWithSHA1"!=e.prf&&t.seq[0].seq[1].seq[0].seq[1].seq.push({seq:[{oid:e.prf},{null:""}]}),t},parseHexOfEncryptedPKCS8:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={},s=i(e,0);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+s.length);r.ciphertext=n(e,s[1]);var a=i(e,s[0]);if(2!=a.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+a.length);if("2a864886f70d01050d"!=n(e,a[0]))throw new Error("this only supports pkcs5PBES2");var o=i(e,a[1]);if(2!=a.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+o.length);var c=i(e,o[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";r.encryptionSchemeAlg="TripleDES",r.encryptionSchemeIV=n(e,c[1]);var d=i(e,o[0]);if(2!=d.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+d.length);if("2a864886f70d01050c"!=n(e,d[0]))throw new Error("this only supports pkcs5PBKDF2");var l=i(e,d[1]);if(l.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+l.length);r.pbkdf2Salt=n(e,l[0]);var h=n(e,l[1]);try{r.pbkdf2Iter=parseInt(h,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+h)}return r},getPBKDF2KeyHexFromParam:function(e,t){var i=ne.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,r=ne.PBKDF2(t,i,{keySize:6,iterations:n});return ne.enc.Hex.stringify(r)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var i=ut(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(i),r=kt.getPBKDF2KeyHexFromParam(n,t),s={};s.ciphertext=ne.enc.Hex.parse(n.ciphertext);var a=ne.enc.Hex.parse(r),o=ne.enc.Hex.parse(n.encryptionSchemeIV),c=ne.TripleDES.decrypt(s,a,{iv:o});return ne.enc.Hex.stringify(c)},parsePBES2:function(e){var t=Qe.parse(e);if("pkcs5PBES2"!=Dt(t,"seq.0.seq.0.oid")||"pkcs5PBKDF2"!=Dt(t,"seq.0.seq.1.seq.0.seq.0.oid"))throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");var i=Dt(t,"seq.0.seq.1.seq.0.seq.1.seq");if(null==i)throw new Error("PBKDF2 parameter not found");var n=Dt(i,"0.octstr.hex"),r=Dt(i,"1.int.hex"),s=Dt(i,"2.seq.0.oid","hmacWithSHA1"),a=-1;try{a=parseInt(r,16)}catch(e){throw new Error("iter not proper value")}var o=Dt(t,"seq.0.seq.1.seq.1.seq.0.oid"),c=Dt(t,"seq.0.seq.1.seq.1.seq.1.octstr.hex"),d=Dt(t,"seq.1.octstr.hex");if(null==o||null==c||null==d)throw new Error("encalg, enciv or enc is undefined");return{salt:n,iter:a,prf:s,encalg:o,enciv:c,enc:d}},getDKFromPBES2Param:function(e,t){var i={hmacWithSHA1:ne.algo.SHA1,hmacWithSHA224:ne.algo.SHA224,hmacWithSHA256:ne.algo.SHA256,hmacWithSHA384:ne.algo.SHA384,hmacWithSHA512:ne.algo.SHA512}[e.prf];if(null==i)throw new Error("unsupported prf");var n={"des-EDE3-CBC":6,"aes128-CBC":4,"aes256-CBC":8}[e.encalg];if(null==n)throw new Error("unsupported encalg");var r=ne.enc.Hex.parse(e.salt),s=e.iter;try{var a=ne.PBKDF2(t,r,{keySize:n,iterations:s,hasher:i});return ne.enc.Hex.stringify(a)}catch(i){throw new Error("PBKDF2 error: "+i+" "+JSON.stringify(e)+" "+t)}},getPlainHexFromEncryptedPKCS8PEM:function(e,t){if(-1==e.indexOf("BEGIN ENCRYPTED PRIVATE KEY"))throw new Error("not Encrypted PKCS#8 PEM string");var i,n=ut(e);try{i=kt.parsePBES2(n)}catch(e){throw new Error("malformed PBES2 format: "+e.message)}var r=kt.getDKFromPBES2Param(i,t);return Je.crypto.Cipher.decrypt(i.enc,r,i.encalg,{iv:i.enciv})},getKeyFromEncryptedPKCS8PEM:function(e,t){var i=this.getPlainHexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(i)},parsePlainPrivatePKCS8Hex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var s=i(e,0);if(s.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(s[1],2))throw new Error("malformed PKCS8 private key(code:003)");var a=i(e,s[1]);if(2!=a.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(r.algoid=n(e,a[0]),"06"==e.substr(a[1],2)&&(r.algparam=n(e,a[1])),"04"!=e.substr(s[2],2))throw new Error("malformed PKCS8 private key(code:006)");return r.keyidx=t.getVidx(e,s[2]),r},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=ut(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,i=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==i.algoid)t=new Ge;else if("2a8648ce380401"==i.algoid)t=new Je.crypto.DSA;else{if("2a8648ce3d0201"!=i.algoid)throw new Error("unsupported private key algorithm");t=new Je.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,i=Qe.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===i)t=new Ge;else if("2a8648ce380401"===i)t=new Je.crypto.DSA;else{if("2a8648ce3d0201"!==i)throw new Error("unsupported PKCS#8 public key hex");t=new Je.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var s=i(e,0);if(2!=s.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(s[0],2))throw new Error("malformed RSA key(code:003)");if(r.n=n(e,s[0]),"02"!=e.substr(s[1],2))throw new Error("malformed RSA key(code:004)");return r.e=n(e,s[1]),r},parsePublicPKCS8Hex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={algparam:null},s=i(e,0);if(2!=s.length)throw new Error("outer DERSequence shall have 2 elements: "+s.length);var a=s[0];if("30"!=e.substr(a,2))throw new Error("malformed PKCS8 public key(code:001)");var o=i(e,a);if(2!=o.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(o[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(r.algoid=n(e,o[0]),"06"==e.substr(o[1],2)?r.algparam=n(e,o[1]):"30"==e.substr(o[1],2)&&(r.algparam={},r.algparam.p=t.getVbyList(e,o[1],[0],"02"),r.algparam.q=t.getVbyList(e,o[1],[1],"02"),r.algparam.g=t.getVbyList(e,o[1],[2],"02")),"03"!=e.substr(s[1],2))throw new Error("malformed PKCS8 public key(code:004)");return r.key=n(e,s[1]).substr(2),r}}}();function Ot(e,t){for(var i="",n=t/4-e.length,r=0;r<n;r++)i+="0";return i+e}function Ft(e,t,i){for(var n="",r=0;n.length<t;)n+=dt(i(lt(e+String.fromCharCode.apply(String,[(4278190080&r)>>24,(16711680&r)>>16,(65280&r)>>8,255&r])))),r+=1;return n}function Mt(e){for(var t in Je.crypto.Util.DIGESTINFOHEAD){var i=Je.crypto.Util.DIGESTINFOHEAD[t],n=i.length;if(e.substring(0,n)==i)return[t,e.substring(n)]}return[]}function Ht(e){var t=Qe,i=t.getChildIdx,n=t.getV;t.dump;var r,s=t.parse,a=t.getTLV,o=t.getVbyList,c=t.getVbyListEx,d=t.getTLVbyList,l=t.getTLVbyListEx,h=t.getIdxbyList,u=t.getIdxbyListEx,p=t.getVidx,g=t.getInt,f=t.oidname,m=t.hextooidstr,v=ut,y=Error;try{r=Je.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=d(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=d(e,0,[0]),i=g(t,0);if(i<0||2<i)throw new Error("malformed version field");return this.version=i+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return c(this.hex,0,[0,0],"02")},this.getSignatureAlgorithmField=function(){var e=l(this.hex,0,[0,1]);return this.getAlgorithmIdentifierName(e)},this.getAlgorithmIdentifierName=function(e){for(var t in r)if(e===r[t])return t;return f(c(e,0,[0],"06"))},this.getIssuer=function(e,t){return this.getX500Name(this.getIssuerHex(),e,t)},this.getIssuerHex=function(){return d(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return this.getIssuer().str},this.getSubject=function(e,t){return this.getX500Name(this.getSubjectHex(),e,t)},this.getSubjectHex=function(){return d(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=o(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getNotAfter=function(){var e=o(this.hex,0,[0,4+this.foffset,1]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getPublicKeyHex=function(){return this.getSPKI()},this.getSPKI=function(){return d(this.hex,0,[0,6+this.foffset],"30")},this.getSPKIValue=function(){var e=this.getSPKI();return null==e?null:o(e,0,[1],"03",!0)},this.getPublicKeyIdx=function(){return h(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return h(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return kt.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=d(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return o(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),i=this.getSignatureValueHex(),n=d(this.hex,0,[0],"30"),r=new Je.crypto.Signature({alg:t});return r.init(e),r.updateHex(n),r.verify(i)},this.parseExt=function(e){var r,s,a;if(void 0===e){if(a=this.hex,3!==this.version)return-1;r=h(a,0,[0,7,0],"30"),s=i(a,r)}else{a=ut(e);var c=h(a,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=n(a,c))return void(this.aExtInfo=new Array);r=h(a,0,[0,3,0,1,0],"30"),s=i(a,r),this.hex=a}this.aExtInfo=new Array;for(var d=0;d<s.length;d++){var l={critical:!1},u=0;3===i(a,s[d]).length&&(l.critical=!0,u=1),l.oid=t.hextooidstr(o(a,s[d],[0],"06"));var g=h(a,s[d],[1+u]);l.vidx=p(a,g),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,i=e;if(e.match(/^[0-9.]+$/)||(i=Je.asn1.x509.OID.name2oid(e)),""!==i)for(var n=0;n<t.length;n++)if(t[n].oid===i)return t[n]},this.getCriticalExtV=function(e,t,i){if(null!=t)return[t,i];var n=this.getExtInfo(e);return null==n?[null,null]:[a(this.hex,n.vidx),n.critical]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("basicConstraints");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var r={extname:"basicConstraints"};if(t&&(r.critical=!0),"3000"===e)return r;if("30030101ff"===e)return r.cA=!0,r;if("30060101ff02"===e.substr(0,12)){var s=n(e,10),o=parseInt(s,16);return r.cA=!0,r.pathLen=o,r}throw new Error("hExtV parse error: "+e)},this.getExtNameConstraints=function(e,t){var n=this.getCriticalExtV("nameConstraints",e,t);if(e=n[0],t=n[1],null!=e){var r={extname:"nameConstraints"};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){for(var c=[],d=i(e,s[o]),l=0;l<d.length;l++){var h=a(e,d[l]),u=this.getGeneralSubtree(h);c.push(u)}var p=e.substr(s[o],2);"a0"==p?r.permit=c:"a1"==p&&(r.exclude=c)}return r}},this.getGeneralSubtree=function(e){var t=i(e,0),r=t.length;if(r<1||2<r)throw new Error("wrong num elements");for(var s=this.getGeneralName(a(e,t[0])),o=1;o<r;o++){var c=e.substr(t[o],2),d=n(e,t[o]),l=parseInt(d,16);"80"==c&&(s.min=l),"81"==c&&(s.max=l)}return s},this.getExtKeyUsage=function(e,t){var i=this.getCriticalExtV("keyUsage",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"keyUsage"};return t&&(n.critical=!0),n.names=this.getExtKeyUsageString(e).split(","),n}},this.getExtKeyUsageBin=function(e){if(void 0===e){var t=this.getExtInfo("keyUsage");if(void 0===t)return"";e=a(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var i="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(i=i.slice(-8)),10==e.length&&(i=i.slice(-16)),""==(i=i.replace(/0+$/,""))&&(i="0"),i},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),i=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&i.push(Ht.KEYUSAGE_NAME[n]);return i.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectKeyIdentifier");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var r={extname:"subjectKeyIdentifier"};t&&(r.critical=!0);var s=n(e,0);return r.kid={hex:s},r},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityKeyIdentifier");if(void 0===r)return;e=a(this.hex,r.vidx),t=r.critical}var s={extname:"authorityKeyIdentifier"};t&&(s.critical=!0);for(var o=i(e,0),c=0;c<o.length;c++){var d=e.substr(o[c],2);if("80"===d&&(s.kid={hex:n(e,o[c])}),"a1"===d){var l=a(e,o[c]),h=this.getGeneralNames(l);s.issuer=h[0].dn}"82"===d&&(s.sn={hex:n(e,o[c])})}return s},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("extKeyUsage");if(void 0===r)return;e=a(this.hex,r.vidx),t=r.critical}var s={extname:"extKeyUsage",array:[]};t&&(s.critical=!0);for(var o=i(e,0),c=0;c<o.length;c++)s.array.push(f(n(e,o[c])));return s},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,r=a(this.hex,e.vidx);if(""===r)return t;for(var s=i(r,0),o=0;o<s.length;o++)t.push(f(n(r,s[o])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectAltName");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"subjectAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getExtIssuerAltName=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("issuerAltName");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=i(e,0),n=[],r=0;r<t.length;r++){var s=this.getGeneralName(a(e,t[r]));void 0!==s&&n.push(s)}return n},this.getGeneralName=function(e){var t=e.substr(0,2),i=n(e,0),r=dt(i);return"81"==t?{rfc822:r}:"82"==t?{dns:r}:"86"==t?{uri:r}:"87"==t?{ip:yt(i)}:"a4"==t?{dn:this.getX500Name(i)}:"a0"==t?{other:this.getOtherName(e)}:void 0},this.getExtSubjectAltName2=function(){var e,t,r,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var o=new Array,c=a(this.hex,s.vidx),d=i(c,0),l=0;l<d.length;l++)r=c.substr(d[l],2),e=n(c,d[l]),"81"===r&&(t=ot(e),o.push(["MAIL",t])),"82"===r&&(t=ot(e),o.push(["DNS",t])),"84"===r&&(t=Ht.hex2dn(e,0),o.push(["DN",t])),"86"===r&&(t=ot(e),o.push(["URI",t])),"87"===r&&(t=yt(e),o.push(["IP",t]));return o},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("cRLDistributionPoints");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"cRLDistributionPoints",array:[]};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){var c=a(e,s[o]);r.array.push(this.getDistributionPoint(c))}return r},this.getDistributionPoint=function(e){for(var t={},n=i(e,0),r=0;r<n.length;r++){var s=e.substr(n[r],2),o=a(e,n[r]);"a0"==s&&(t.dpname=this.getDistributionPointName(o))}return t},this.getDistributionPointName=function(e){for(var t={},n=i(e,0),r=0;r<n.length;r++){var s=e.substr(n[r],2),o=a(e,n[r]);"a0"==s&&(t.full=this.getGeneralNames(o))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtCRLDistributionPoints();if(null==e)return e;for(var t=e.array,i=[],n=0;n<t.length;n++)try{null!=t[n].dpname.full[0].uri&&i.push(t[n].dpname.full[0].uri)}catch(e){}return i},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},n=i(this.hex,e.vidx),r=0;r<n.length;r++){var s=o(this.hex,n[r],[0],"06"),a=o(this.hex,n[r],[1],"86");"2b06010505073001"===s&&t.ocsp.push(ot(a)),"2b06010505073002"===s&&t.caissuer.push(ot(a))}return t},this.getExtAuthorityInfoAccess=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("authorityInfoAccess");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"authorityInfoAccess",array:[]};t&&(r.critical=!0);for(var s=i(e,0),d=0;d<s.length;d++){var l=c(e,s[d],[0],"06"),h=ot(o(e,s[d],[1],"86"));if("2b06010505073001"==l)r.array.push({ocsp:h});else{if("2b06010505073002"!=l)throw new Error("unknown method: "+l);r.array.push({caissuer:h})}}return r},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("certificatePolicies");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"certificatePolicies",array:[]};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){var c=a(e,s[o]),d=this.getPolicyInformation(c);r.array.push(d)}return r},this.getPolicyInformation=function(e){var t={},n=o(e,0,[0],"06");t.policyoid=f(n);var r=u(e,0,[1],"30");if(-1!=r){t.array=[];for(var s=i(e,r),c=0;c<s.length;c++){var d=a(e,s[c]),l=this.getPolicyQualifierInfo(d);t.array.push(l)}}return t},this.getOtherName=function(e){var t={},n=i(e,0),r=o(e,n[0],[],"06"),a=o(e,n[1],[]);return t.oid=f(r),t.value=s(a),t},this.getPolicyQualifierInfo=function(e){var t={},i=o(e,0,[0],"06");if("2b06010505070201"===i){var n=c(e,0,[1],"16");t.cps=dt(n)}else if("2b06010505070202"===i){var r=d(e,0,[1],"30");t.unotice=this.getUserNotice(r)}return t},this.getUserNotice=function(e){var i=null;try{return i=t.parse(e),this._asn1ToUnotice(i)}catch(e){return}},this._asn1ToUnotice=function(e){try{for(var t={},i=Dt(e,"seq"),n=0;n<i.length;n++){var r=this._asn1ToNoticeRef(i[n]);null!=r&&(t.noticeref=r);var s=this.asn1ToDisplayText(i[n]);null!=s&&(t.exptext=s)}return Object.keys(t).length>0?t:void 0}catch(e){return}},this._asn1ToNoticeRef=function(e){try{for(var t={},i=Dt(e,"seq"),n=0;n<i.length;n++){var r=this._asn1ToNoticeNum(i[n]);null!=r&&(t.noticenum=r);var s=this.asn1ToDisplayText(i[n]);null!=s&&(t.org=s)}return Object.keys(t).length>0?t:void 0}catch(e){return}},this._asn1ToNoticeNum=function(e){try{for(var t=Dt(e,"seq"),i=[],n=0;n<t.length;n++){var r=t[n];i.push(parseInt(Dt(r,"int.hex"),16))}return i}catch(e){return}},this.getDisplayText=function(e){var t={};return t.type={"0c":"utf8",16:"ia5","1a":"vis","1e":"bmp"}[e.substr(0,2)],t.str=dt(n(e,0)),t},this.asn1ToDisplayText=function(e){return null!=e.utf8str?{type:"utf8",str:e.utf8str.str}:null!=e.ia5str?{type:"ia5",str:e.ia5str.str}:null!=e.visstr?{type:"vis",str:e.visstr.str}:null!=e.bmpstr?{type:"bmp",str:e.bmpstr.str}:null!=e.prnstr?{type:"prn",str:e.prnstr.str}:void 0},this.getExtPolicyMappings=function(e,t){var i=this.getCriticalExtV("policyMappings",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"policyMappings"};t&&(n.critical=!0);try{for(var r=s(e).seq,a=[],o=0;o<r.length;o++){var c=r[o].seq;a.push([c[0].oid,c[1].oid])}n.array=a}catch(e){throw new y("malformed policyMappings")}return n}},this.getExtPolicyConstraints=function(e,t){var i=this.getCriticalExtV("policyConstraints",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"policyConstraints"};t&&(n.critical=!0);var r=s(e);try{for(var a=r.seq,o=0;o<a.length;o++){var c=a[o].tag;0==c.explicit&&("80"==c.tag&&(n.reqexp=parseInt(c.hex,16)),"81"==c.tag&&(n.inhibit=parseInt(c.hex,16)))}}catch(e){return new y("malformed policyConstraints value")}return n}},this.getExtInhibitAnyPolicy=function(e,t){var i=this.getCriticalExtV("inhibitAnyPolicy",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"inhibitAnyPolicy"};t&&(n.critical=!0);var r=g(e,0);return-1==r?new y("wrong value"):(n.skip=r,n)}},this.getExtCRLNumber=function(e,t){var i={extname:"cRLNumber"};if(t&&(i.critical=!0),"02"==e.substr(0,2))return i.num={hex:n(e,0)},i;throw new y("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var i={extname:"cRLReason"};if(t&&(i.critical=!0),"0a"==e.substr(0,2))return i.code=parseInt(n(e,0),16),i;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var i={extname:"ocspNonce"};t&&(i.critical=!0);var r=n(e,0);return i.hex=r,i},this.getExtOcspNoCheck=function(e,t){var i={extname:"ocspNoCheck"};return t&&(i.critical=!0),i},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("adobeTimeStamp");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"adobeTimeStamp"};t&&(r.critical=!0);var s=i(e,0);if(s.length>1){var o=a(e,s[1]),c=this.getGeneralName(o);null!=c.uri&&(r.uri=c.uri)}if(s.length>2){var d=a(e,s[2]);"0101ff"==d&&(r.reqauth=!0),"010100"==d&&(r.reqauth=!1)}return r},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectDirectoryAttributes");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var r=s(e),o=[],c=0;c<r.seq.length;c++){var d=r.seq[c],l=Dt(d,"seq.0.oid"),h=Dt(d,"seq.1.set");if(null==l||null==h)throw"error";o.push({attr:l,array:h})}return n.array=o,n}catch(e){throw new Error("malformed subjectDirectoryAttributes extension value")}};var S=function(e){var t={};try{var i=e.seq[0].oid,n=Je.asn1.x509.OID.name2oid(i);t.type=Je.asn1.x509.OID.oid2atype(n);var r=e.seq[1];if(null!=r.utf8str)t.ds="utf8",t.value=r.utf8str.str;else if(null!=r.numstr)t.ds="num",t.value=r.numstr.str;else if(null!=r.telstr)t.ds="tel",t.value=r.telstr.str;else if(null!=r.prnstr)t.ds="prn",t.value=r.prnstr.str;else if(null!=r.ia5str)t.ds="ia5",t.value=r.ia5str.str;else if(null!=r.visstr)t.ds="vis",t.value=r.visstr.str;else{if(null==r.bmpstr)throw"error";t.ds="bmp",t.value=r.bmpstr.str}return t}catch(e){throw new Erorr("improper ASN.1 parsed AttrTypeAndValue")}},b=function(e){try{return e.set.map((function(e){return S(e)}))}catch(e){throw new Error("improper ASN.1 parsed RDN: "+e)}};this.getX500NameRule=function(e){for(var t=null,i=[],n=0;n<e.length;n++)for(var r=e[n],s=0;s<r.length;s++)i.push(r[s]);for(n=0;n<i.length;n++){var a=i[n],o=a.ds,c=a.value,d=a.type;if("prn"!=o&&"utf8"!=o&&"ia5"!=o)return"mixed";if("ia5"==o){if("CN"!=d)return"mixed";if(Je.lang.String.isMail(c))continue;return"mixed"}if("C"==d){if("prn"==o)continue;return"mixed"}if(null==t)t=o;else if(t!==o)return"mixed"}return null==t?"prn":t},this.getAttrTypeAndValue=function(e){var t=s(e);return S(t)},this.getRDN=function(e){var t=s(e);return b(t)},this.getX500NameArray=function(e){return function(e){try{return e.seq.map((function(e){return b(e)}))}catch(e){throw new Error("improper ASN.1 parsed X500Name: "+e)}}(s(e))},this.getX500Name=function(e,t,i){var n=this.getX500NameArray(e),r={str:this.dnarraytostr(n)};return r.array=n,1==i&&(r.hex=e),1==t&&(r.canon=this.c14nRDNArray(n)),r},this.readCertPEM=function(e){this.readCertHex(v(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{h(this.hex,0,[0,7],"a3"),this.parseExt()}catch(e){}},this.getParam=function(e){var t={};return null==e&&(e={}),t.version=this.getVersion(),t.serial={hex:this.getSerialNumberHex()},t.sigalg=this.getSignatureAlgorithmField(),t.issuer=this.getIssuer(e.dncanon,e.dnhex),t.notbefore=this.getNotBefore(),t.notafter=this.getNotAfter(),t.subject=this.getSubject(e.dncanon,e.dnhex),t.sbjpubkey=ht(this.getPublicKeyHex(),"PUBLIC KEY"),null!=this.aExtInfo&&this.aExtInfo.length>0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=d(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=u(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=i(e,0),r=0;r<n.length;r++){var s=a(e,n[r]),o=this.getExtParam(s);null!=o&&t.push(o)}return t},this.getExtParam=function(e){var t=i(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var n=m(o(e,0,[0],"06")),r=!1;3==t&&"0101ff"==d(e,0,[1])&&(r=!0);var a=d(e,0,[t-1,0]),c=void 0;if("2.5.29.14"==n?c=this.getExtSubjectKeyIdentifier(a,r):"2.5.29.15"==n?c=this.getExtKeyUsage(a,r):"2.5.29.17"==n?c=this.getExtSubjectAltName(a,r):"2.5.29.18"==n?c=this.getExtIssuerAltName(a,r):"2.5.29.19"==n?c=this.getExtBasicConstraints(a,r):"2.5.29.30"==n?c=this.getExtNameConstraints(a,r):"2.5.29.31"==n?c=this.getExtCRLDistributionPoints(a,r):"2.5.29.32"==n?c=this.getExtCertificatePolicies(a,r):"2.5.29.33"==n?c=this.getExtPolicyMappings(a,r):"2.5.29.35"==n?c=this.getExtAuthorityKeyIdentifier(a,r):"2.5.29.36"==n?c=this.getExtPolicyConstraints(a,r):"2.5.29.37"==n?c=this.getExtExtKeyUsage(a,r):"2.5.29.54"==n?c=this.getExtInhibitAnyPolicy(a,r):"1.3.6.1.5.5.7.1.1"==n?c=this.getExtAuthorityInfoAccess(a,r):"2.5.29.20"==n?c=this.getExtCRLNumber(a,r):"2.5.29.21"==n?c=this.getExtCRLReason(a,r):"2.5.29.9"==n?c=this.getExtSubjectDirectoryAttributes(a,r):"1.3.6.1.5.5.7.48.1.2"==n?c=this.getExtOcspNonce(a,r):"1.3.6.1.5.5.7.48.1.5"==n?c=this.getExtOcspNoCheck(a,r):"1.2.840.113583.1.1.9.1"==n?c=this.getExtAdobeTimeStamp(a,r):null!=Ht.EXT_PARSER[n]&&(c=Ht.EXT_PARSER[n](n,r,a)),null!=c)return c;var l={extname:n,extn:a};try{l.extn=s(a)}catch(e){}return r&&(l.critical=!0),l},this.findExt=function(e,t){for(var i=0;i<e.length;i++)if(e[i].extname==t)return e[i];return null},this.updateExtCDPFullURI=function(e,t){var i=this.findExt(e,"cRLDistributionPoints");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)if(null!=n[r].dpname&&null!=n[r].dpname.full)for(var s=n[r].dpname.full,a=0;a<s.length;a++){var o=s[r];null!=o.uri&&(o.uri=t)}},this.updateExtAIAOCSP=function(e,t){var i=this.findExt(e,"authorityInfoAccess");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)null!=n[r].ocsp&&(n[r].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var i=this.findExt(e,"authorityInfoAccess");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)null!=n[r].caissuer&&(n[r].caissuer=t)},this.dnarraytostr=function(e){return"/"+e.map((function(e){return function(e){return e.map((function(e){return function(e){return e.type+"="+e.value}(e).replace(/\+/,"\\+")})).join("+")}(e).replace(/\//,"\\/")})).join("/")},this.setCanonicalizedDN=function(e){var t;if(null!=e.str&&null==e.array){var i=new Je.asn1.x509.X500Name({str:e.str}).tohex();t=this.getX500NameArray(i)}else t=e.array;null==e.canon&&(e.canon=this.c14nRDNArray(t))},this.c14nRDNArray=function(e){for(var t=[],i=0;i<e.length;i++){for(var n=e[i],r=[],s=0;s<n.length;s++){var a=n[s],o=a.value;o=(o=(o=(o=o.replace(/^\s*/,"")).replace(/\s*$/,"")).replace(/\s+/g," ")).toLowerCase(),r.push(a.type.toLowerCase()+"="+o)}t.push(r.join("+"))}return"/"+t.join("/")},this.getInfo=function(){var e,t,i,n=function(e){for(var t="",i=" ",n="\n",r=e.array,s=0;s<r.length;s++){var a=r[s];if(null!=a.dn&&(t+=i+"dn: "+a.dn.str+n),null!=a.ip&&(t+=i+"ip: "+a.ip+n),null!=a.rfc822&&(t+=i+"rfc822: "+a.rfc822+n),null!=a.dns&&(t+=i+"dns: "+a.dns+n),null!=a.uri&&(t+=i+"uri: "+a.uri+n),null!=a.other)t+=i+"other: "+a.other.oid+"="+JSON.stringify(a.other.value).replace(/\"/g,"")+n}return t=t.replace(/\n$/,"")},r=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];if(t+=" policy oid: "+r.policyoid+"\n",void 0!==r.array)for(var s=0;s<r.array.length;s++){var a=r.array[s];void 0!==a.cps&&(t+=" cps: "+a.cps+"\n")}}return t},s=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];try{void 0!==r.dpname.full[0].uri&&(t+=" "+r.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==r.dname.full[0].dn.hex&&(t+=" "+Ht.hex2dn(r.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},a=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];void 0!==r.caissuer&&(t+=" caissuer: "+r.caissuer+"\n"),void 0!==r.ocsp&&(t+=" ocsp: "+r.ocsp+"\n")}return t};if(e="Basic Fields\n",e+=" serial number: "+this.getSerialNumberHex()+"\n",e+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n",e+=" issuer: "+this.getIssuerString()+"\n",e+=" notBefore: "+this.getNotBefore()+"\n",e+=" notAfter: "+this.getNotAfter()+"\n",e+=" subject: "+this.getSubjectString()+"\n",e+=" subject public key info: \n",e+=" key algorithm: "+(t=this.getPublicKey()).type+"\n","RSA"===t.type&&(e+=" n="+_t(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+_t(t.e.toString(16))+"\n"),null!=(i=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var o=0;o<i.length;o++){var c=i[o],d=Je.asn1.x509.OID.oid2name(c.oid);""===d&&(d=c.oid);var l="";if(!0===c.critical&&(l="CRITICAL"),e+=" "+d+" "+l+":\n","basicConstraints"===d){var h=this.getExtBasicConstraints();void 0===h.cA?e+=" {}\n":(e+=" cA=true",void 0!==h.pathLen&&(e+=", pathLen="+h.pathLen),e+="\n")}else{var u;if("policyMappings"==d)e+=" "+this.getExtPolicyMappings().array.map((function(e){var t=e;return t[0]+":"+t[1]})).join(", ")+"\n";else if("policyConstraints"==d)e+=" ",null!=(u=this.getExtPolicyConstraints()).reqexp&&(e+=" reqexp="+u.reqexp),null!=u.inhibit&&(e+=" inhibit="+u.inhibit),e+="\n";else if("inhibitAnyPolicy"==d)e+=" skip="+(u=this.getExtInhibitAnyPolicy()).skip+"\n";else if("keyUsage"==d)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"==d)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"==d){var p=this.getExtAuthorityKeyIdentifier();void 0!==p.kid&&(e+=" kid="+p.kid.hex+"\n")}else{if("extKeyUsage"==d)e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n";else if("subjectAltName"==d)e+=n(this.getExtSubjectAltName())+"\n";else if("cRLDistributionPoints"==d)e+=s(this.getExtCRLDistributionPoints());else if("authorityInfoAccess"==d)e+=a(this.getExtAuthorityInfoAccess());else"certificatePolicies"==d&&(e+=r(this.getExtCertificatePolicies()))}}}}return e+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n",e+="signature: "+this.getSignatureValueHex().substr(0,16)+"...\n"},"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?this.readCertPEM(e):Je.lang.String.isHex(e)&&this.readCertHex(e))}kt.getKey=function(e,t,i){var n=(m=Qe).getChildIdx;m.getV;var r=m.getVbyList,s=Je.crypto,a=s.ECDSA,o=s.DSA,c=Ge,d=ut,l=kt;if(void 0!==c&&e instanceof c)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==o&&e instanceof o)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new a({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new a({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(x=new c).setPublic(e.n,e.e),x;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.co&&void 0===e.qi)return(x=new c).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),x;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(x=new c).setPrivate(e.n,e.e,e.d),x;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(x=new o).setPublic(e.p,e.q,e.g,e.y),x;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(x=new o).setPrivate(e.p,e.q,e.g,e.y,e.x),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(x=new c).setPublic(st(e.n),st(e.e)),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.qi)return(x=new c).setPrivateEx(st(e.n),st(e.e),st(e.d),st(e.p),st(e.q),st(e.dp),st(e.dq),st(e.qi)),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(x=new c).setPrivate(st(e.n),st(e.e),st(e.d)),x;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var h=(_=new a({curve:e.crv})).ecparams.keycharlen,u="04"+("0000000000"+st(e.x)).slice(-h)+("0000000000"+st(e.y)).slice(-h);return _.setPublicKeyHex(u),_}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){h=(_=new a({curve:e.crv})).ecparams.keycharlen,u="04"+("0000000000"+st(e.x)).slice(-h)+("0000000000"+st(e.y)).slice(-h);var p=("0000000000"+st(e.d)).slice(-h);return _.setPublicKeyHex(u),_.setPrivateKeyHex(p),_}if("pkcs5prv"===i){var g,f=e,m=Qe;if(9===(g=n(f,0)).length)(x=new c).readPKCS5PrvKeyHex(f);else if(6===g.length)(x=new o).readPKCS5PrvKeyHex(f);else{if(!(g.length>2&&"04"===f.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(x=new a).readPKCS5PrvKeyHex(f)}return x}if("pkcs8prv"===i)return x=l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===i)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===i)return Ht.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return Ht.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var v=ut(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(v)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var y=d(e,"RSA PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var S=r(A=d(e,"DSA PRIVATE KEY"),0,[1],"02"),b=r(A,0,[2],"02"),w=r(A,0,[3],"02"),E=r(A,0,[4],"02"),C=r(A,0,[5],"02");return(x=new o).setPrivate(new de(S,16),new de(b,16),new de(w,16),new de(E,16),new de(C,16)),x}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){y=d(e,"EC PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END PRIVATE KEY-"))return l.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var $=l.getDecryptedKeyHex(e,t),T=new Ge;return T.readPKCS5PrvKeyHex($),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var _,x=r(A=l.getDecryptedKeyHex(e,t),0,[1],"04"),I=r(A,0,[2,0],"06"),R=r(A,0,[3,0],"03").substr(2);if(void 0===Je.crypto.OID.oidhex2name[I])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+I);return(_=new a({curve:Je.crypto.OID.oidhex2name[I]})).setPublicKeyHex(R),_.setPrivateKeyHex(x),_.isPublic=!1,_}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var A;S=r(A=l.getDecryptedKeyHex(e,t),0,[1],"02"),b=r(A,0,[2],"02"),w=r(A,0,[3],"02"),E=r(A,0,[4],"02"),C=r(A,0,[5],"02");return(x=new o).setPrivate(new de(S,16),new de(b,16),new de(w,16),new de(E,16),new de(C,16)),x}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},kt.generateKeypair=function(e,t){if("RSA"==e){var i=t;(a=new Ge).generate(i,"10001"),a.isPrivate=!0,a.isPublic=!0;var n=new Ge,r=a.n.toString(16),s=a.e.toString(16);return n.setPublic(r,s),n.isPrivate=!1,n.isPublic=!0,(o={}).prvKeyObj=a,o.pubKeyObj=n,o}if("EC"==e){var a,o,c=t,d=new Je.crypto.ECDSA({curve:c}).generateKeyPairHex();return(a=new Je.crypto.ECDSA({curve:c})).setPublicKeyHex(d.ecpubhex),a.setPrivateKeyHex(d.ecprvhex),a.isPrivate=!0,a.isPublic=!1,(n=new Je.crypto.ECDSA({curve:c})).setPublicKeyHex(d.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(o={}).prvKeyObj=a,o.pubKeyObj=n,o}throw new Error("unknown algorithm: "+e)},kt.getPEM=function(e,t,i,n,r,s){var a=Je,o=a.asn1,c=o.DERObjectIdentifier,d=o.DERInteger,l=o.ASN1Util.newObject,h=o.x509.SubjectPublicKeyInfo,u=a.crypto,p=u.DSA,g=u.ECDSA,f=Ge;function m(e){return l({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function v(e){return l({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function y(e){return l({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==f&&e instanceof f||void 0!==p&&e instanceof p||void 0!==g&&e instanceof g)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return ht(E=new h(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===i||null==i)&&1==e.isPrivate)return ht(E=m(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===i||null==i)&&1==e.isPrivate){var S=new c({name:e.curveName}).tohex(),b=v(e).tohex(),w="";return w+=ht(S,"EC PARAMETERS"),w+=ht(b,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===i||null==i)&&1==e.isPrivate)return ht(E=y(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==i&&null!=i&&1==e.isPrivate){var E=m(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,i,n,s)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==i&&null!=i&&1==e.isPrivate){E=v(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,i,n,s)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==i&&null!=i&&1==e.isPrivate){E=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,i,n,s)}var C=function(e,t){if("string"==typeof t)return kt.getEncryptedPKCS8PEM(e,t);if("object"==typeof t&&null!=Dt(t,"passcode")){var i=JSON.parse(JSON.stringify(t)),n=i.passcode;return delete i.passcode,kt.getEncryptedPKCS8PEM(e,n,i)}};if("PKCS8PRV"==t&&null!=f&&e instanceof f&&1==e.isPrivate){var $=m(e).tohex();E=l({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){var T={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&T.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});$=new l(T).tohex(),E=l({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){$=new d({bigint:e.x}).tohex(),E=l({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}throw new Error("unsupported object nor format")},kt.getKeyFromCSRPEM=function(e){var t=ut(e,"CERTIFICATE REQUEST");return kt.getKeyFromCSRHex(t)},kt.getKeyFromCSRHex=function(e){var t=kt.parseCSRHex(e);return kt.getKey(t.p8pubkeyhex,null,"pkcs8pub")},kt.parseCSRHex=function(e){var t=Qe,i=t.getChildIdx,n=t.getTLV,r={},s=e;if("30"!=s.substr(0,2))throw new Error("malformed CSR(code:001)");var a=i(s,0);if(a.length<1)throw new Error("malformed CSR(code:002)");if("30"!=s.substr(a[0],2))throw new Error("malformed CSR(code:003)");var o=i(s,a[0]);if(o.length<3)throw new Error("malformed CSR(code:004)");return r.p8pubkeyhex=n(s,o[2]),r},kt.getKeyID=function(e){var t=kt,i=Qe;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=ut(t.getPEM(e)),r=i.getIdxbyList(n,0,[1]),s=i.getV(n,r).substring(2);return Je.crypto.Util.hashHex(s,"sha1")},kt.getJWK=function(e,t,i,n,r){var s,a,o={},c=Je.crypto.Util.hashHex;if("string"==typeof e)s=kt.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(a=ut(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof Ht?(s=e.getPublicKey(),a=e.hex):s=e}if(s instanceof Ge&&s.isPrivate)o.kty="RSA",o.n=rt(s.n.toString(16)),o.e=rt(s.e.toString(16)),o.d=rt(s.d.toString(16)),o.p=rt(s.p.toString(16)),o.q=rt(s.q.toString(16)),o.dp=rt(s.dmp1.toString(16)),o.dq=rt(s.dmq1.toString(16)),o.qi=rt(s.coeff.toString(16));else if(s instanceof Ge&&s.isPublic)o.kty="RSA",o.n=rt(s.n.toString(16)),o.e=rt(s.e.toString(16));else if(s instanceof Je.crypto.ECDSA&&s.isPrivate){if("P-256"!==(l=s.getShortNISTPCurveName())&&"P-384"!==l&&"P-521"!==l)throw new Error("unsupported curve name for JWT: "+l);var d=s.getPublicKeyXYHex();o.kty="EC",o.crv=l,o.x=rt(d.x),o.y=rt(d.y),o.d=rt(s.prvKeyHex)}else if(s instanceof Je.crypto.ECDSA&&s.isPublic){var l;if("P-256"!==(l=s.getShortNISTPCurveName())&&"P-384"!==l&&"P-521"!==l)throw new Error("unsupported curve name for JWT: "+l);d=s.getPublicKeyXYHex();o.kty="EC",o.crv=l,o.x=rt(d.x),o.y=rt(d.y)}if(null==o.kty)throw new Error("unsupported keyinfo");return s.isPrivate||1==t||(o.kid=Je.jws.JWS.getJWKthumbprint(o)),null!=a&&1!=i&&(o.x5c=[oe(a)]),null!=a&&1!=n&&(o.x5t=it(oe(c(a,"sha1")))),null!=a&&1!=r&&(o["x5t#S256"]=it(oe(c(a,"sha256")))),o},kt.getJWKFromKey=function(e){return kt.getJWK(e,!0,!0,!0,!0)},Ge.getPosArrayOfChildrenFromHex=function(e){return Qe.getChildIdx(e,0)},Ge.getHexValueArrayOfChildrenFromHex=function(e){var t,i=Qe.getV,n=i(e,(t=Ge.getPosArrayOfChildrenFromHex(e))[0]),r=i(e,t[1]),s=i(e,t[2]),a=i(e,t[3]),o=i(e,t[4]),c=i(e,t[5]),d=i(e,t[6]),l=i(e,t[7]),h=i(e,t[8]);return(t=new Array).push(n,r,s,a,o,c,d,l,h),t},Ge.prototype.readPrivateKeyFromPEMString=function(e){var t=ut(e),i=Ge.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8])},Ge.prototype.readPKCS5PrvKeyHex=function(e){var t=Ge.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},Ge.prototype.readPKCS8PrvKeyHex=function(e){var t,i,n,r,s,a,o,c,d=Qe,l=d.getVbyListEx;if(!1===d.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=l(e,0,[2,0,1],"02"),i=l(e,0,[2,0,2],"02"),n=l(e,0,[2,0,3],"02"),r=l(e,0,[2,0,4],"02"),s=l(e,0,[2,0,5],"02"),a=l(e,0,[2,0,6],"02"),o=l(e,0,[2,0,7],"02"),c=l(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,i,n,r,s,a,o,c)},Ge.prototype.readPKCS5PubKeyHex=function(e){var t=Qe,i=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var r=i(e,n[0]),s=i(e,n[1]);this.setPublic(r,s)},Ge.prototype.readPKCS8PubKeyHex=function(e){var t=Qe;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var i=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(i)},Ge.prototype.readCertPubKeyHex=function(e,t){var i,n;(i=new Ht).readCertHex(e),n=i.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},Ge.prototype.sign=function(e,t){var i=function(e){return Je.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(i,t)},Ge.prototype.signWithMessageHash=function(e,t){var i=qe(Je.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return Ot(this.doPrivate(i).toString(16),this.n.bitLength())},Ge.prototype.signPSS=function(e,t,i){var n=function(e){return Je.crypto.Util.hashHex(e,t)}(lt(e));return void 0===i&&(i=-1),this.signWithMessageHashPSS(n,t,i)},Ge.prototype.signWithMessageHashPSS=function(e,t,i){var n,r=dt(e),s=r.length,a=this.n.bitLength()-1,o=Math.ceil(a/8),c=function(e){return Je.crypto.Util.hashHex(e,t)};if(-1===i||void 0===i)i=s;else if(-2===i)i=o-s-2;else if(i<-2)throw new Error("invalid salt length");if(o<s+i+2)throw new Error("data too long");var d="";i>0&&(d=new Array(i),(new Ve).nextBytes(d),d=String.fromCharCode.apply(String,d));var l=dt(c(lt("\0\0\0\0\0\0\0\0"+r+d))),h=[];for(n=0;n<o-i-s-2;n+=1)h[n]=0;var u=String.fromCharCode.apply(String,h)+""+d,p=Ft(l,u.length,c),g=[];for(n=0;n<u.length;n+=1)g[n]=u.charCodeAt(n)^p.charCodeAt(n);var f=65280>>8*o-a&255;for(g[0]&=~f,n=0;n<s;n++)g.push(l.charCodeAt(n));return g.push(188),Ot(this.doPrivate(new de(g)).toString(16),this.n.bitLength())},Ge.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var i=qe(t,16),n=this.n.bitLength();if(i.bitLength()>n)return!1;var r=this.doPublic(i).toString(16);if(r.length+3!=n/4)return!1;var s=Mt(r.replace(/^1f+00/,""));if(0==s.length)return!1;var a=s[0],o=s[1],c=function(e){return Je.crypto.Util.hashString(e,a)}(e);return o==c},Ge.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i=qe(t,16);if(i.bitLength()>this.n.bitLength())return 0;var n=Mt(this.doPublic(i).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},Ge.prototype.verifyPSS=function(e,t,i,n){var r,s=(r=lt(e),Je.crypto.Util.hashHex(r,i));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(s,t,i,n)},Ge.prototype.verifyWithMessageHashPSS=function(e,t,i,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r,s=new de(t,16),a=function(e){return Je.crypto.Util.hashHex(e,i)},o=dt(e),c=o.length,d=this.n.bitLength()-1,l=Math.ceil(d/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=l-c-2;else if(n<-2)throw new Error("invalid salt length");if(l<c+n+2)throw new Error("data too long");var h=this.doPublic(s).toByteArray();for(r=0;r<h.length;r+=1)h[r]&=255;for(;h.length<l;)h.unshift(0);if(188!==h[l-1])throw new Error("encoded message does not end in 0xbc");var u=(h=String.fromCharCode.apply(String,h)).substr(0,l-c-1),p=h.substr(u.length,c),g=65280>>8*l-d&255;if(0!=(u.charCodeAt(0)&g))throw new Error("bits beyond keysize not zero");var f=Ft(p,u.length,a),m=[];for(r=0;r<u.length;r+=1)m[r]=u.charCodeAt(r)^f.charCodeAt(r);m[0]&=~g;var v=l-c-n-2;for(r=0;r<v;r+=1)if(0!==m[r])throw new Error("leftmost octets not zero");if(1!==m[v])throw new Error("0x01 marker not found");return p===dt(a(lt("\0\0\0\0\0\0\0\0"+o+String.fromCharCode.apply(String,m.slice(-n)))))},Ge.SALT_LEN_HLEN=-1,Ge.SALT_LEN_MAX=-2,Ge.SALT_LEN_RECOVER=-2,Ht.EXT_PARSER={},Ht.registExtParser=function(e,t){Ht.EXT_PARSER[e]=t},Ht.hex2dn=function(e,t){void 0===t&&(t=0);var i=new Ht;return Qe.getTLV(e,t),i.getX500Name(e).str},Ht.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var i=new Array,n=Qe.getChildIdx(e,t),r=0;r<n.length;r++)i.push(Ht.hex2attrTypeValue(e,n[r]));return i=i.map((function(e){return e.replace("+","\\+")})),i.join("+")},Ht.hex2attrTypeValue=function(e,t){var i=Qe,n=i.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var r=i.getChildIdx(e,t);2!==r.length||e.substr(r[0],2);var s=n(e,r[0]),a=Je.asn1.ASN1Util.oidHexToInt(s);return Je.asn1.x509.OID.oid2atype(a)+"="+dt(n(e,r[1]))},Ht.getPublicKeyFromCertHex=function(e){var t=new Ht;return t.readCertHex(e),t.getPublicKey()},Ht.getPublicKeyFromCertPEM=function(e){var t=new Ht;return t.readCertPEM(e),t.getPublicKey()},Ht.getPublicKeyInfoPropOfCertPEM=function(e){var t,i,n=Qe.getVbyList,r={};return r.algparam=null,(t=new Ht).readCertPEM(e),i=t.getPublicKeyHex(),r.keyhex=n(i,0,[1],"03").substr(2),r.algoid=n(i,0,[0,0],"06"),"2a8648ce3d0201"===r.algoid&&(r.algparam=n(i,0,[0,1],"06")),r},Ht.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==Je&&Je||(Je={}),void 0!==Je.jws&&Je.jws||(Je.jws={}),Je.jws.JWS=function(){var e=Je.jws.JWS.isSafeJSONString;this.parseJWS=function(t,i){if(void 0===this.parsedJWS||!i&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var r=n[1],s=n[2],a=n[3],o=r+"."+s;if(this.parsedJWS={},this.parsedJWS.headB64U=r,this.parsedJWS.payloadB64U=s,this.parsedJWS.sigvalB64U=a,this.parsedJWS.si=o,!i){var c=st(a),d=qe(c,16);this.parsedJWS.sigvalH=c,this.parsedJWS.sigvalBI=d}var l=Xe(r),h=Xe(s);if(this.parsedJWS.headS=l,this.parsedJWS.payloadS=h,!e(l,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+l}}},Je.jws.JWS.sign=function(e,t,i,n,r){var s=Je,a=s.jws.JWS,o=a.readSafeJSONString,c=a.isSafeJSONString,d=s.crypto;d.ECDSA;var l,h,u,p=d.Mac,g=d.Signature,f=JSON;if("string"!=typeof t&&"object"!=typeof t)throw"spHeader must be JSON string or object: "+t;if("object"==typeof t&&(h=t,l=f.stringify(h)),"string"==typeof t){if(!c(l=t))throw"JWS Head is not safe JSON string: "+l;h=o(l)}if(u=i,"object"==typeof i&&(u=f.stringify(i)),""!=e&&null!=e||void 0===h.alg||(e=h.alg),""!=e&&null!=e&&void 0===h.alg&&(h.alg=e,l=f.stringify(h)),e!==h.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+h.alg;var m=null;if(void 0===a.jwsalg2sigalg[e])throw"unsupported alg name: "+e;m=a.jwsalg2sigalg[e];var v=Ze(l)+"."+Ze(u),y="";if("Hmac"==m.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var S=new p({alg:m,prov:"cryptojs",pass:n});S.updateString(v),y=S.doFinal()}else if(-1!=m.indexOf("withECDSA")){(w=new g({alg:m})).init(n,r),w.updateString(v);var b=w.sign();y=Je.crypto.ECDSA.asn1SigToConcatSig(b)}else{var w;if("none"!=m)(w=new g({alg:m})).init(n,r),w.updateString(v),y=w.sign()}return v+"."+rt(y)},Je.jws.JWS.verify=function(e,t,i){var n,r=Je,s=r.jws.JWS,a=s.readSafeJSONString,o=r.crypto,c=o.ECDSA,d=o.Mac,l=o.Signature;if(n=Ge,!Tt(e))return!1;var h=e.split(".");if(3!==h.length)return!1;var u=h[0]+"."+h[1],p=st(h[2]),g=a(Xe(h[0])),f=null,m=null;if(void 0===g.alg)throw"algorithm not specified in header";if((m=(f=g.alg).substr(0,2),null!=i&&"[object Array]"===Object.prototype.toString.call(i)&&i.length>0)&&-1==(":"+i.join(":")+":").indexOf(":"+f+":"))throw"algorithm '"+f+"' not accepted in the list";if("none"!=f&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=kt.getKey(t)),!("RS"!=m&&"PS"!=m||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==m&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var v=null;if(void 0===s.jwsalg2sigalg[g.alg])throw"unsupported alg name: "+f;if("none"==(v=s.jwsalg2sigalg[f]))throw"not supported";if("Hmac"==v.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var y=new d({alg:v,pass:t});return y.updateString(u),p==y.doFinal()}if(-1!=v.indexOf("withECDSA")){var S,b=null;try{b=c.concatSigToASN1Sig(p)}catch(e){return!1}return(S=new l({alg:v})).init(t),S.updateString(u),S.verify(b)}return(S=new l({alg:v})).init(t),S.updateString(u),S.verify(p)},Je.jws.JWS.parse=function(e){var t,i,n,r=e.split("."),s={};if(2!=r.length&&3!=r.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=r[0],i=r[1],3==r.length&&(n=r[2]),s.headerObj=Je.jws.JWS.readSafeJSONString(Xe(t)),s.payloadObj=Je.jws.JWS.readSafeJSONString(Xe(i)),s.headerPP=JSON.stringify(s.headerObj,null," "),null==s.payloadObj?s.payloadPP=Xe(i):s.payloadPP=JSON.stringify(s.payloadObj,null," "),void 0!==n&&(s.sigHex=st(n)),s},Je.jws.JWS.verifyJWT=function(e,t,i){var n=Je.jws,r=n.JWS,s=r.readSafeJSONString,a=r.inArray,o=r.includedArray;if(!Tt(e))return!1;var c=e.split(".");if(3!=c.length)return!1;var d=c[0],l=c[1];st(c[2]);var h=s(Xe(d)),u=s(Xe(l));if(void 0===h.alg)return!1;if(void 0===i.alg)throw"acceptField.alg shall be specified";if(!a(h.alg,i.alg))return!1;if(void 0!==u.iss&&"object"==typeof i.iss&&!a(u.iss,i.iss))return!1;if(void 0!==u.sub&&"object"==typeof i.sub&&!a(u.sub,i.sub))return!1;if(void 0!==u.aud&&"object"==typeof i.aud)if("string"==typeof u.aud){if(!a(u.aud,i.aud))return!1}else if("object"==typeof u.aud&&!o(u.aud,i.aud))return!1;var p=n.IntDate.getNow();return void 0!==i.verifyAt&&"number"==typeof i.verifyAt&&(p=i.verifyAt),void 0!==i.gracePeriod&&"number"==typeof i.gracePeriod||(i.gracePeriod=0),!(void 0!==u.exp&&"number"==typeof u.exp&&u.exp+i.gracePeriod<p)&&(!(void 0!==u.nbf&&"number"==typeof u.nbf&&p<u.nbf-i.gracePeriod)&&(!(void 0!==u.iat&&"number"==typeof u.iat&&p<u.iat-i.gracePeriod)&&((void 0===u.jti||void 0===i.jti||u.jti===i.jti)&&!!r.verify(e,t,i.alg))))},Je.jws.JWS.includedArray=function(e,t){var i=Je.jws.JWS.inArray;if(null===e)return!1;if("object"!=typeof e)return!1;if("number"!=typeof e.length)return!1;for(var n=0;n<e.length;n++)if(!i(e[n],t))return!1;return!0},Je.jws.JWS.inArray=function(e,t){if(null===t)return!1;if("object"!=typeof t)return!1;if("number"!=typeof t.length)return!1;for(var i=0;i<t.length;i++)if(t[i]==e)return!0;return!1},Je.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",ES512:"SHA512withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},Je.jws.JWS.isSafeJSONString=function(e,t,i){var n=null;try{return"object"!=typeof(n=Ye(e))||n.constructor===Array?0:(t&&(t[i]=n),1)}catch(e){return 0}},Je.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=typeof(t=Ye(e))||t.constructor===Array?null:t}catch(e){return null}},Je.jws.JWS.getEncodedSignatureValueFromJWS=function(e){var t=e.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(null==t)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return t[1]},Je.jws.JWS.getJWKthumbprint=function(e){if("RSA"!==e.kty&&"EC"!==e.kty&&"oct"!==e.kty)throw"unsupported algorithm for JWK Thumprint";var t="{";if("RSA"===e.kty){if("string"!=typeof e.n||"string"!=typeof e.e)throw"wrong n and e value for RSA key";t+='"e":"'+e.e+'",',t+='"kty":"'+e.kty+'",',t+='"n":"'+e.n+'"}'}else if("EC"===e.kty){if("string"!=typeof e.crv||"string"!=typeof e.x||"string"!=typeof e.y)throw"wrong crv, x and y value for EC key";t+='"crv":"'+e.crv+'",',t+='"kty":"'+e.kty+'",',t+='"x":"'+e.x+'",',t+='"y":"'+e.y+'"}'}else if("oct"===e.kty){if("string"!=typeof e.k)throw"wrong k value for oct(symmetric) key";t+='"kty":"'+e.kty+'",',t+='"k":"'+e.k+'"}'}var i=lt(t);return rt(Je.crypto.Util.hashHex(i,"sha256"))},Je.jws.IntDate={},Je.jws.IntDate.get=function(e){var t=Je.jws.IntDate,i=t.getNow,n=t.getZulu;if("now"==e)return i();if("now + 1hour"==e)return i()+3600;if("now + 1day"==e)return i()+86400;if("now + 1month"==e)return i()+2592e3;if("now + 1year"==e)return i()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},Je.jws.IntDate.getZulu=function(e){return pt(e)},Je.jws.IntDate.getNow=function(){return~~(new Date/1e3)},Je.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},Je.jws.IntDate.intDate2Zulu=function(e){var t=new Date(1e3*e);return("0000"+t.getUTCFullYear()).slice(-4)+("00"+(t.getUTCMonth()+1)).slice(-2)+("00"+t.getUTCDate()).slice(-2)+("00"+t.getUTCHours()).slice(-2)+("00"+t.getUTCMinutes()).slice(-2)+("00"+t.getUTCSeconds()).slice(-2)+"Z"},void 0!==Je&&Je||(Je={}),void 0!==Je.jws&&Je.jws||(Je.jws={}),Je.jws.JWSJS=function(){var e=Je.jws.JWS,t=e.readSafeJSONString;this.aHeader=[],this.sPayload="",this.aSignature=[],this.init=function(){this.aHeader=[],this.sPayload=void 0,this.aSignature=[]},this.initWithJWS=function(e){this.init();var t=e.split(".");if(3!=t.length)throw"malformed input JWS";this.aHeader.push(t[0]),this.sPayload=t[1],this.aSignature.push(t[2])},this.addSignature=function(e,t,i,n){if(void 0===this.sPayload||null===this.sPayload)throw"there's no JSON-JS signature to add.";var r=this.aHeader.length;if(this.aHeader.length!=this.aSignature.length)throw"aHeader.length != aSignature.length";try{var s=Je.jws.JWS.sign(e,t,this.sPayload,i,n).split(".");s[0],s[2];this.aHeader.push(s[0]),this.aSignature.push(s[2])}catch(e){throw this.aHeader.length>r&&this.aHeader.pop(),this.aSignature.length>r&&this.aSignature.pop(),"addSignature failed: "+e}},this.verifyAll=function(e){if(this.aHeader.length!==e.length||this.aSignature.length!==e.length)return!1;for(var t=0;t<e.length;t++){var i=e[t];if(2!==i.length)return!1;if(!1===this.verifyNth(t,i[0],i[1]))return!1}return!0},this.verifyNth=function(t,i,n){if(this.aHeader.length<=t||this.aSignature.length<=t)return!1;var r=this.aHeader[t],s=this.aSignature[t],a=r+"."+this.sPayload+"."+s,o=!1;try{o=e.verify(a,i,n)}catch(e){return!1}return o},this.readJWSJS=function(e){if("string"==typeof e){var i=t(e);if(null==i)throw"argument is not safe JSON object string";this.aHeader=i.headers,this.sPayload=i.payload,this.aSignature=i.signatures}else try{if(!(e.headers.length>0))throw"malformed header";if(this.aHeader=e.headers,"string"!=typeof e.payload)throw"malformed signatures";if(this.sPayload=e.payload,!(e.signatures.length>0))throw"malformed signatures";this.aSignature=e.signatures}catch(e){throw"malformed JWS-JS JSON object: "+e}},this.getJSON=function(){return{headers:this.aHeader,payload:this.sPayload,signatures:this.aSignature}},this.isEmpty=function(){return 0==this.aHeader.length?1:0}},Je.crypto.ECDSA,Je.crypto.DSA,Je.crypto.Signature,Je.crypto.MessageDigest,Je.crypto.Mac;var Lt=kt,jt=Xe,Bt=Je;Je.crypto,Je.asn1,Je.jws,Je.lang;var Ut=(e,t)=>{const i={};return Object.getOwnPropertyNames(e).forEach((t=>{i[t]=e[t]})),new t(i)};class Vt{type;id;extensions;endpointCustom;endpointSccp;endpointSip;static parse(e){return new Vt({id:e.id,extensions:e.extensions,endpointCustom:e.endpoint_custom||null,endpointSccp:e.endpoint_sccp||null,endpointSip:e.endpoint_sip||null})}static newFrom(e){return Ut(e,Vt)}is(e){return!!e&&this.id===e.id}hasExtension(e){return!!this.extensions&&this.extensions.some((t=>t.exten===e))}constructor({id:e,extensions:t,endpointCustom:i,endpointSccp:n,endpointSip:r}={}){this.id=e,this.extensions=t,this.endpointCustom=i||null,this.endpointSccp=n||null,this.endpointSip=r||null,this.type="Line"}}const qt={BUSY:"busy",NO_ANSWER:"noanswer",UNCONDITIONAL:"unconditional"};class Gt{destination;enabled;key;static parse(e,t){return new Gt({destination:e.destination||"",enabled:e.enabled,key:t})}static newFrom(e){return Ut(e,Gt)}constructor({destination:e,enabled:t,key:i}={}){this.destination=e,this.enabled=t,this.key=i}setDestination(e){return this.destination=e,this}setEnabled(e){return this.enabled=e,this}is(e){return this.key===e.key}}class Kt{id;extensions;extension;type="Incall";constructor({id:e,extensions:t}={}){this.id=e,this.extensions=t,this.extension=t?.[0]?.exten}static parse(e){return new Kt({id:e.id,extensions:e.extensions})}static newFrom(e){return Ut(e,Kt)}hasExtension(e){return!!this.extensions&&this.extensions.some((t=>t.exten===e))}}const Wt={AVAILABLE:"available",UNAVAILABLE:"unavailable",INVISIBLE:"invisible",DISCONNECTED:"disconnected",AWAY:"away"},zt={AVAILABLE:"available",HOLDING:"holding",RINGING:"ringing",TALKING:"talking",UNAVAILABLE:"unavailable",PROGRESSING:"progressing"};class Yt{id;firstName;lastName;email;lines;sipLines;incalls;username;mobileNumber;forwards;doNotDisturb;onlineCallRecordEnabled;state;ringSeconds;voicemail;status;subscriptionType;agent;switchboards;callPickupTargetUsers;static parse(e){return new Yt({id:e.uuid,firstName:e.firstName||e.firstname||"",lastName:e.lastName||e.lastname||"",email:e.email,lines:e.lines.map((e=>Vt.parse(e))),incalls:e.incalls,username:e.username,mobileNumber:e.mobile_phone_number||"",ringSeconds:e.ring_seconds,forwards:[Gt.parse(e.forwards.unconditional,qt.UNCONDITIONAL),Gt.parse(e.forwards.noanswer,qt.NO_ANSWER),Gt.parse(e.forwards.busy,qt.BUSY)],doNotDisturb:e.services.dnd.enabled,subscriptionType:e.subscription_type,voicemail:e.voicemail,switchboards:e.switchboards||[],agent:e.agent,status:"",callPickupTargetUsers:e.call_pickup_target_users||[],onlineCallRecordEnabled:e.online_call_record_enabled})}static newFrom(e){return Ut(e,Yt)}constructor({id:e,firstName:t,lastName:i,email:n,lines:r,username:s,mobileNumber:a,forwards:o,doNotDisturb:c,state:d,subscriptionType:l,voicemail:h,switchboards:u,agent:p,status:g,ringSeconds:f,sipLines:m,callPickupTargetUsers:v,onlineCallRecordEnabled:y,incalls:S}){this.id=e,this.firstName=t,this.lastName=i,this.email=n,this.lines=r,this.username=s,this.mobileNumber=a,this.forwards=o,this.doNotDisturb=c,this.state=d,this.voicemail=h,this.subscriptionType=l,this.switchboards=u,this.agent=p,this.status=g,this.callPickupTargetUsers=v,this.onlineCallRecordEnabled=y,this.ringSeconds=f,this.sipLines=m||[],this.incalls=S?.map(Kt.parse)||[]}static getLinesState(e){let t=zt.UNAVAILABLE;for(const i of e){if(i.state===zt.RINGING){t=zt.RINGING;break}if(i.state===zt.TALKING){t=zt.TALKING;break}i.state===zt.AVAILABLE&&(t=zt.AVAILABLE)}return t}hasId(e){return e===this.id}setMobileNumber(e){return this.mobileNumber=e,this}setForwardOption(e){const t=this.forwards.slice(),i=t.findIndex((t=>t.is(e)));return t.splice(i,1,e),this.forwards=t,this}setDoNotDisturb(e){return this.doNotDisturb=e,this}setState(e){return this.state=e,this}}const Jt={OFFICE365:"office365",PERSONAL:"personal",GOOGLE:"google",WAZO:"wazo",CONFERENCE:"conference",PHONEBOOK:"phonebook"},Zt="mobile";class Xt{static BACKEND=Jt;type;id;uuid;name;number;numbers;favorited;email;emails;entreprise;birthday;address;note;endpointId;personal;state;lineState;previousPresential;lastActivity;mobile;source;sourceId;status;backend;personalStatus;sessions;connected;doNotDisturb;ringing;lines;static merge(e,t){return t.map((t=>{const i=e.find((e=>e&&e.is(t)));return i?t.merge(i):t}))}static sortContacts(e,t){const i=e.separateName(),n=t.separateName(),r=i.lastName,s=n.lastName;return r===s?i.firstName.localeCompare(n.firstName):r.localeCompare(s)}static parseMany(e,t=0,i=null){if(!e||!e.results||0===i)return[];return(null!==i&&i>0?e.results.slice(t,i):t>0?e.results.slice(t):e.results).map((t=>Xt.parse(t,e.column_types)))}static manyGraphQlWithNumbersParser(e){return t=>t.data&&t.data.me&&t.data.me.contacts?t.data.me.contacts.edges.map(((t,i)=>{if(!t.node)return null;const{email:n}=t.node,r=t.node.firstname&&t.node.lastname?`${t.node.firstname||""} ${t.node.lastname||""}`:t.node.wazoReverse;return new Xt({name:r,number:e[i],numbers:[{label:"primary",number:e[i]}],backend:t.node.wazoBackend,source:t.node.wazoSourceName,sourceId:t.node.wazoSourceEntryId||"",email:n||"",emails:n?[{label:"primary",email:n}]:[],uuid:t.node.userUuid})})).filter((e=>!!e)):[]}static fetchNumbers(e,t){const i=t.map(((e,t)=>({index:t,columnName:e}))).filter((e=>"number"===e.columnName||"callable"===e.columnName)).map((e=>e.index));return e.column_values.filter(((e,t)=>i.some((e=>e===t))&&null!==e))}static parse(e,t){const i=Xt.fetchNumbers(e,t),n=e.column_values[t.indexOf("email")];return new Xt({name:e.column_values[t.indexOf("name")],number:i.length?i[0]:"",numbers:i.map(((e,t)=>({label:0===t?"primary":"secondary",number:e}))),favorited:e.column_values[t.indexOf("favorite")],email:n||"",emails:n?[{label:"primary",email:n}]:[],entreprise:e.column_values[t.indexOf("entreprise")]||"",birthday:e.column_values[t.indexOf("birthday")]||"",address:e.column_values[t.indexOf("address")]||"",note:e.column_values[t.indexOf("note")]||"",endpointId:e.relations.endpoint_id,personal:e.column_values[t.indexOf("personal")],source:e.source,sourceId:e.relations.source_entry_id||"",uuid:e.relations.user_uuid,backend:e.backend||""})}static parseManyPersonal(e){return e.map((e=>Xt.parsePersonal(e)))}static parsePersonal(e){return new Xt({name:`${e.firstName||e.firstname||""} ${e.lastName||e.lastname||""}`,number:e.number||"",numbers:e.number?[{label:"primary",number:e.number}]:[],email:e.email||"",emails:e.email?[{label:"primary",email:e.email}]:[],source:"personal",sourceId:e.id||"",entreprise:e.entreprise||"",birthday:e.birthday||"",address:e.address||"",note:e.note||"",favorited:e.favorited,personal:!0,backend:e.backend||Jt.PERSONAL})}static parseMobile(e){let t="";if(e.postalAddresses.length){const i=e.postalAddresses[0];t=`${i.street} ${i.city} ${i.postCode} ${i.country}`}const i=e.givenName||"",n=e.familyName||"",r=e.company||"";return new Xt({name:!i&&!n?r:`${i} ${n}`,number:e.phoneNumbers.length?e.phoneNumbers[0].number:"",numbers:[...new Map(e.phoneNumbers.map((e=>[e.number,e]))).values()].map(((e,t)=>({label:0===t?"primary":"secondary",number:e.number}))),email:e.emailAddresses.length?e.emailAddresses[0].email:"",emails:e.emailAddresses.length?[{label:"primary",email:e.emailAddresses[0].email}]:[],source:Zt,sourceId:e.recordID||"",birthday:e.birthday?`${e.birthday.year}-${e.birthday.month}-${e.birthday.day}`:"",address:t,note:e.note||"",favorited:!1,personal:!0})}static parseManyOffice365(e,t){return e.map((e=>Xt.parseOffice365(e,t)))}static parseOffice365(e,t){const i=[],n=[];return e.emailAddresses&&e.emailAddresses.map((e=>i.push({email:e.address}))),e.businessPhones&&e.businessPhones.map((e=>n.push({label:"business",number:e}))),e.mobilePhone&&n.push({label:"mobile",number:e.mobilePhone}),e.homePhones&&e.homePhones.map((e=>n.push({label:"home",number:e}))),new Xt({sourceId:e.id||"",name:e.displayName||"",number:n.length?n[0].number:"",numbers:n,emails:i,source:t.name,backend:Jt.OFFICE365})}static parseManyGoogle(e,t){return e.map((e=>Xt.parseGoogle(e,t)))}static parseGoogle(e,t){const i=[];return e.emails&&e.emails.forEach((e=>"object"==typeof e?{email:e.address,label:e.label}:{email:e})),e.numbers_by_label?Object.keys(e.numbers_by_label).forEach((t=>i.push({label:t,number:e.numbers_by_label[t]}))):e.numbers&&e.numbers.forEach((e=>i.push({number:e}))),new Xt({sourceId:e.id||"",name:e.name||"",number:i.length?i[0].number:"",numbers:i,emails:[],source:t.name,backend:Jt.GOOGLE})}static parseManyWazo(e,t){return e.map((e=>Xt.parseWazo(e,t)))}static parseWazo(e,t){const i=[],n=[];return e.email&&i.push({label:"email",email:e.email}),e.exten&&n.push({label:"exten",number:e.exten}),e.mobile_phone_number&&n.push({label:"mobile",number:e.mobile_phone_number}),new Xt({uuid:e.uuid,sourceId:String(e.id)||"",name:`${e.firstname}${e.lastname?` ${e.lastname}`:""}`,number:n.length?n[0].number:"",numbers:n,emails:i,source:t.name,backend:Jt.WAZO})}static parseManyConference(e,t){return e.map((e=>Xt.parseConference(e,t)))}static parseConference(e,t){const i=[];let n="";return e&&e.extensions&&e.extensions.length>0&&e.extensions[0].exten&&(n=e.extensions[0].exten,i.push({label:"exten",number:n})),new Xt({sourceId:String(e.id),name:e.name,number:n,numbers:i,source:t.name,backend:Jt.CONFERENCE})}static newFrom(e){return Ut(e,Xt)}constructor({id:e,uuid:t,name:i,number:n,numbers:r,email:s,emails:a,source:o,sourceId:c,entreprise:d,birthday:l,address:h,note:u,state:p,lineState:g,lastActivity:f,mobile:m,status:v,endpointId:y,personal:S,favorited:b,backend:w,personalStatus:E,sessions:C,connected:$,doNotDisturb:T,ringing:_,previousPresential:x,lines:I}={}){this.id=e,this.uuid=t,this.name=i||"",this.number=n,this.numbers=r,this.email=s,this.emails=a,this.source=o,this.sourceId=c,this.entreprise=d,this.birthday=l,this.address=h,this.note=u,this.state=p,this.lineState=g,this.lastActivity=f,this.mobile=m,this.status=v,this.endpointId=y,this.personal=S,this.favorited=b,this.backend=w,this.personalStatus=E||"",this.sessions=C||[],this.connected=$,this.doNotDisturb=T,this.ringing=_,this.previousPresential=x,this.lines=I||[],this.type="Contact"}setFavorite(e){return this.favorited=e,this}is(e){const t=null!==this.sourceId&&null!==e.sourceId&&this.sourceId===e.sourceId,i=!!this.uuid&&!!e.uuid&&this.uuid===e.uuid,n=t||i,r=!!this.backend&&!!e.backend&&this.backend===e.backend,s=!!this.source&&!!e.source&&this.source===e.source;return!!e&&n&&r&&s}hasId(e){return this.uuid===e}hasNumber(e){return this.number===e}hasEndpointId(e){return this.endpointId===e}isAvailable(){return this.state===Wt.AVAILABLE}isAway(){return this.state===Wt.AWAY}isUnavailable(){return this.state===Wt.UNAVAILABLE}isInvisible(){return this.state===Wt.INVISIBLE}isInCall(){return this.lineState===zt.TALKING||this.lineState===zt.HOLDING}isRinging(){return this.ringing}isInUseOrRinging(){return this.lineState===zt.TALKING||this.lineState===zt.RINGING}isProgressing(){return this.lineState===zt.PROGRESSING}merge(e){return Object.keys(e).filter((e=>"lineState"!==e)).forEach((t=>{this[t]=e[t]||this[t]})),e.lineState&&(this.lineState=e.lineState),this}isIntern(){return!!this.uuid}hasSourceId(){return!!this.sourceId}isCallable(e){return!!this.number&&!!e&&!e.is(this)}isFromMobile(){return this.source===Zt}isFavorite(){return this.favorited}separateName(){if(!this.name)return{firstName:"",lastName:""};const e=this.name.split(/\s+/);return{firstName:e[0],lastName:e.slice(1).join(" ")}}}const{jws:Qt}=Bt,ei=Lt.getKey("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmkXOuNfY8u5xoTiIhkb8\ndjnbIwG/Wrz3vpo8BZir8L5e1a1nSy740qBjP7ZINBQoALDhFfmdOfJnCyEGiHuz\nZW6jbG6C3PryE3Bu6GKwqSmD6k3q4Zk27fpwYAnNl+rWhYYM563rJZBda/INyHNN\npK7M1mixWi7gNdjjXwoEXSSBx+VpYMkY6LiAB2mvHXTY9M1qI14dvgGoQISZQoKi\nNMTRCg5UP2ic0Dd9nSz/XpcOxGfa+0fwIl1F7RC1tJXOqvkGGPTOV4LLfg/Yta3h\nnUPX9EZZDIX6vO/0IBV1LzjSl2A1bYFYAjJfowv3i1CpvONBOClHjSY5t9Y8MH6p\nBwIDAQAB\n-----END PUBLIC KEY-----");let ti=class e{acl;contact;token;refreshToken;uuid;tenantUuid;stackUuid;sessionUuid;engineVersion;_stackHostFromHeader;profile;expiresAt;authorizations;static parse(t){const i=t.data.metadata?t.data.metadata.jwt:null;let n=[];if(i){if(Qt.JWS.verifyJWT(i,ei,{alg:["RS256"],verifyAt:new Date})){const e=Qt.JWS.readSafeJSONString(jt(i.split(".")[1]));n=e?e.authorizations:[]}}return new e({token:t.data.token,refreshToken:t.data.refresh_token||null,uuid:t.data.metadata?t.data.metadata.uuid:null,sessionUuid:t.data.session_uuid,authorizations:n,acl:t.data.acls?t.data.acls:t.data.acl?t.data.acl:[],tenantUuid:t.data.metadata?t.data.metadata.tenant_uuid:void 0,expiresAt:_.utc(t.data.utc_expires_at).toDate(),stackUuid:t.data.xivo_uuid,stackHostFromHeader:t._headers?.get?.("wazo-stack-host")})}static newFrom(t){return Ut(t,e)}constructor({token:e,uuid:t,tenantUuid:i,profile:n,expiresAt:r,authorizations:s,acl:a,engineVersion:o,refreshToken:c,sessionUuid:d,stackUuid:l,stackHostFromHeader:h}){this.token=e,this.uuid=t,this.tenantUuid=i||null,this.profile=n,this.expiresAt=r,this.authorizations=s||[],this.acl=a||[],this.engineVersion=o,this.refreshToken=c,this.sessionUuid=d,this.stackUuid=l,this._stackHostFromHeader=h}hasExpired(e=new Date){return e>=this.expiresAt}is(e){return Boolean(e)&&this.uuid===e.uuid}using(e){return this.profile=e,this}hasAuthorizations(){return this.authorizations&&!!this.authorizations.length}displayName(){return this.profile?`${this.profile.firstName} ${this.profile.lastName}`:""}hasAccessToVoicemail(){return!!this.profile&&!!this.profile.voicemail}primaryLine(){return this.profile&&this.profile.lines.length>0?this.profile.lines[0]:null}primarySipLine(){return this.profile&&this.profile.sipLines.length>0?this.profile.sipLines[0]:null}primaryWebRtcLine(){return this.profile&&(this.profile.sipLines||[]).find((e=>e&&e.isWebRtc()))}primaryCtiLine(){return this.profile&&(this.profile.sipLines||[]).find((e=>e&&!e.isWebRtc()))}getContact(){if(this.contact)return this.contact;const{email:e,firstName:t,lastName:i,mobileNumber:n,state:r,status:s}=this.profile||{},a=this.primaryNumber()||"",o=[{label:"primary",number:a}];return n&&o.push({label:"mobile",number:n}),new Xt({uuid:this.uuid||"",email:e,name:`${t} ${i}`,number:a,numbers:o,state:r||"",status:s,backend:"wazo",source:"default"})}primaryContext(){if(this.engineVersion&&this.hasEngineVersionGte("19.08"))return"default";const e=this.primaryLine();return e&&Array.isArray(e.extensions)&&e.extensions.length>0?e.extensions[0].context:"default"}hasEngineVersionGte(e){return!!this.engineVersion&&((e,t)=>{let i,n;const r=/(\.0+)+$/,s=e.replace(r,"").split("."),a=t.replace(r,"").split("."),o=Math.min(s.length,a.length);for(i=0;i<o;i++)if(n=parseInt(s[i],10)-parseInt(a[i],10),n)return n;return s.length-a.length})(String(this.engineVersion),String(e))>=0}primaryNumber(){const e=this.primaryLine();return e&&Array.isArray(e.extensions)&&e.extensions.length?e.extensions[0].exten:null}allLines(){return this.profile&&this.profile.lines||[]}allNumbers(){const e=this.allLines().map((e=>e.extensions?.map((e=>e.exten))||[]));return e.length?e.reduce(((e,t)=>e.concat(t))):[]}hasExtension(e){return this.allNumbers().some((t=>t===e))}getHostFromHeader(){return this._stackHostFromHeader}get acls(){return console.warn("`acls` property of Session has been removed in Wazo's SDK, please use `acl` instead."),this.acl}get engineUuid(){return console.warn("`engineUuid` property of Session has been removed in Wazo's SDK, please use `stackUuid` instead."),this.stackUuid}toJSON(){return{...this,engineUuid:this.engineUuid}}};const ii="wazo_user",ni=3600;class ri{number;idType;type;static parse(e){return new ri({number:e.number,type:e.type})}static parseMany(e){return e.items.map((e=>ri.parse(e)))}static newFrom(e){return Ut(e,ri)}constructor({type:e,number:t}){this.idType=e,this.number=t,this.type="CallerID"}}const si=["vp8","vp9","h264"];class ai{id;uuid;tenantUuid;username;secret;type;host;options;endpointSectionOptions;links;trunk;line;static parse(e){let{username:t,secret:i,host:n}=e;if(e.auth_section_options){const r=(e,t)=>e.find((e=>e[0]===t)),s=r(e.auth_section_options,"username"),a=r(e.auth_section_options,"password"),o=r(e.endpoint_section_options,"media_address");t=s?s[1]:"",i=a?a[1]:"",n=o?o[1]:""}return new ai({id:e.id,uuid:e.uuid,tenantUuid:e.tenant_uuid,username:t,secret:i,type:e.type,host:n,options:e.options,endpointSectionOptions:e.endpoint_section_options,links:e.links,trunk:e.trunk,line:e.line})}static newFrom(e){return Ut(e,ai)}is(e){return e.uuid?this.uuid===e.uuid:this.id===e.id}getOptions(){return this.endpointSectionOptions||this.options||[]}isWebRtc(){return this.getOptions().some((e=>"webrtc"===e[0]&&"yes"===e[1]))}hasVideo(){const e=this.getOptions().find((e=>"allow"===e[0]));return Array.isArray(e)&&e[1].split(",").some((e=>si.some((t=>t===e))))}hasVideoConference(){return this.getOptions().some((e=>"max_audio_streams"===e[0]&&parseInt(e[1],10)>0))&&this.getOptions().some((e=>"max_video_streams"===e[0]&&parseInt(e[1],10)>1))}constructor({id:e,uuid:t,tenantUuid:i,username:n,secret:r,type:s,host:a,options:o,endpointSectionOptions:c,links:d,trunk:l,line:h}){this.id=e,this.uuid=t,this.tenantUuid=i,this.username=n,this.secret=r,this.type=s,this.host=a,this.options=o,this.endpointSectionOptions=c,this.links=d,this.trunk=l,this.line=h,this.type="SipLine"}}class oi{name;type;configuration;static parse(e){return new oi({name:e.name,configuration:e.configuration})}static parseMany(e){return e.items.map((e=>oi.parse(e)))}static newFrom(e){return Ut(e,oi)}constructor({name:e,configuration:t}={}){this.name=e,this.configuration=t,this.type="ExternalApp"}}class ci{type;guestSipAuthorization;uri;uuid;name;port;extension;persistent;ownerUuids;creationTime;pendingAuthorizations;requireAuthorization;static parse(e){return new ci({guestSipAuthorization:e.guest_sip_authorization,uri:e.ingress_http_uri,name:e.name,ownerUuids:e.owner_uuids,port:e.port,uuid:e.uuid,extension:e.exten,persistent:e.persistent,creationTime:_(e.creation_time).toDate(),requireAuthorization:e.require_authorization})}static parseMany(e){return e?e.map((e=>ci.parse(e))):[]}static newFrom(e){return Ut(e,ci)}constructor({uuid:e,name:t,guestSipAuthorization:i,ownerUuids:n,port:r,uri:s,extension:a,persistent:o,creationTime:c,requireAuthorization:d}={}){this.guestSipAuthorization=i,this.uri=s,this.name=t,this.ownerUuids=n,this.port=r,this.uuid=e,this.extension=a,this.persistent=o,this.creationTime=c,this.requireAuthorization=d,this.type="Meeting"}getGuestSipCredentials(){const[e,t]=Buffer.from(this.guestSipAuthorization,"base64").toString("ascii").split(":");return{username:e,secret:t}}}class di{static PENDING="pending";static ACCEPTED="accepted";static REJECTED="rejected";static POST_PROCESSING="post_processing";static POST_PROCESSED_SUCCESS="post_processed_success";static POST_PROCESSED_ERROR="post_processed_error";meetingUuid;uuid;userUuid;userName;status;constructor({meetingUuid:e,uuid:t,userUuid:i,userName:n}={}){this.meetingUuid=e,this.uuid=t,this.userUuid=i,this.userName=n}setStatus(e){this.status=e}getStatus(){return this.status}static parse(e){const{meeting_uuid:t,uuid:i,guest_uuid:n,guest_name:r}=e;return new di({meetingUuid:t,uuid:i,userUuid:n,userName:r})}static parseMany(e){return e?e.map(di.parse):[]}}const li=e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Input is not an object");return Object.keys(e).reduce(((t,i)=>(t[I(i)]="object"!=typeof e[i]||Array.isArray(e[i])?e[i]:li(e[i]),t)),{})};var hi=(e,t)=>({listUsers:()=>e.get(`${t}/users`,null),getUser:i=>e.get(`${t}/users/${i}`,null).then(Yt.parse),updateUser:(i,n)=>{const r={firstname:n.firstName,lastname:n.lastName,email:n.email,mobile_phone_number:n.mobileNumber};return e.put(`${t}/users/${i}`,r,null,G.successResponseParser)},updateForwardOption:(i,n,r,s)=>{const a=`${t}/users/${i}/forwards/${n}`;return e.put(a,{destination:r,enabled:s},null,G.successResponseParser)},updateDoNotDisturb:(i,n)=>e.put(`${t}/users/${i}/services/dnd`,{enabled:n},null,G.successResponseParser),getUserLineSip:(i,n)=>e.get(`${t}/users/${i}/lines/${n}/associated/endpoints/sip?view=merged`).then(ai.parse),getUserLinesSip(e,t){return Promise.all(t.map((t=>this.getUserLineSip(e,t).catch((()=>null)))))},getUserLineSipFromToken(e){return this.getUser(e).then((t=>{if(!t.lines.length)return console.warn(`No sip line for user: ${e}`),null;const i=t.lines[0];return this.getUserLineSip(e,i.uuid||i.id)}))},listApplications:()=>e.get(`${t}/applications`,null),getInfos:()=>e.get(`${t}/infos`,null),getExternalApps:i=>e.get(`${t}/users/${i}/external/apps`).then(oi.parseMany),getExternalApp:async(i,n)=>{const r=`${t}/users/${i}/external/apps/${n}?view=fallback`;try{return await e.get(r).then(oi.parse)}catch(e){return null}},getMyMeetings:()=>e.get(`${t}/users/me/meetings`).then((e=>ci.parseMany(e.items))),createMyMeeting:i=>e.post(`${t}/users/me/meetings`,li(i)).then(ci.parse),updateMyMeeting:(i,n)=>e.put(`${t}/users/me/meetings/${i}`,li(n),null,G.successResponseParser),deleteMyMeeting:i=>e.delete(`${t}/users/me/meetings/${i}`,null),getMeeting:i=>e.get(`${t}/meetings/${i}`,null).then(ci.parse),meetingAuthorizations:i=>e.get(`${t}/users/me/meetings/${i}/authorizations`,null).then((e=>di.parseMany(e.items))),meetingAuthorizationReject:(i,n)=>e.put(`${t}/users/me/meetings/${i}/authorizations/${n}/reject`,{},null,G.successResponseParser),meetingAuthorizationAccept:(i,n)=>e.put(`${t}/users/me/meetings/${i}/authorizations/${n}/accept`,{},null,G.successResponseParser),guestGetMeeting:i=>e.get(`${t}/guests/me/meetings/${i}`,null).then(ci.parse),guestAuthorizationRequest:(i,n,r)=>e.post(`${t}/guests/${i}/meetings/${n}/authorizations`,{guest_name:r}).then(di.parse),guestAuthorizationCheck:(i,n,r)=>e.get(`${t}/guests/${i}/meetings/${n}/authorizations/${r}`,null),getOutgoingCallerIDs:i=>e.get(`${t}/users/${i}/callerids/outgoing`,null).then(ri.parseMany)});class ui{static MIN_ENGINE_VERSION_REQUIRED;relocatedCall;initiatorCall;recipientCall;static parse(e){return new ui({initiatorCall:e.initiator_call,recipientCall:e.recipient_call,relocatedCall:e.relocated_call})}constructor({relocatedCall:e,initiatorCall:t,recipientCall:i}){this.initiatorCall=t||"",this.relocatedCall=e||"",this.recipientCall=i||""}}ui.MIN_ENGINE_VERSION_REQUIRED="19.09";class pi{type;uuid;content;date;alias;userUuid;roomUuid;read;static parseMany(e){return e&&e.items?e.items.map((e=>pi.parse(e))):[]}static parse(e){return new pi({uuid:e.uuid,date:_(e.created_at).toDate(),content:e.content,alias:e.alias,userUuid:e.user_uuid,read:!0,roomUuid:e.room?e.room.uuid:null})}static newFrom(e){return Ut(e,pi)}constructor({uuid:e,date:t,content:i,userUuid:n,alias:r,roomUuid:s,read:a}={}){this.uuid=e,this.date=t,this.content=i,this.userUuid=n,this.alias=r,this.roomUuid=s,this.read=a,this.type="ChatMessage"}is(e){return this.uuid===e.uuid}isIncoming(e){return this.userUuid!==e}acknowledge(){return this.read=!0,this}}class gi{type;id;date;duration;unread;caller;static parse(e){return new gi({id:e.id,date:_(1e3*e.timestamp).toDate(),duration:1e3*e.duration,caller:{name:e.caller_id_name,number:e.caller_id_num},unread:e.folder?"new"===e.folder.type:null})}static parseMany(e){if(!e)return[];const t=e.folders.filter((e=>"new"===e.type))[0].messages,i=e.folders.filter((e=>"old"===e.type))[0].messages;return[...t.map((e=>gi.parse(e))).map((e=>e.makeAsUnRead())),...i.map((e=>gi.parse(e))).map((e=>e.acknowledge()))]}static newFrom(e){return Ut(e,gi)}constructor({id:e,date:t,duration:i,caller:n,unread:r}){this.id=e,this.date=t,this.duration=i,this.caller=n,this.unread=r,this.type="Voicemail"}is(e){return e&&this.id===e.id}acknowledge(){return this.unread=!1,this}makeAsUnRead(){return this.unread=!0,this}contains(e){return!e||(this.caller.name.toUpperCase().includes(e.toUpperCase())||this.caller.number.includes(e))}}class fi{type;id;sipCallId;callerName;callerNumber;calleeName;calleeNumber;dialedExtension;lineId;isCaller;isVideo;onHold;muted;status;startingTime;talkingToIds;recording;static parseMany(e){return e?e.map((e=>fi.parse(e))):[]}static parse(e){return new fi({id:e.call_id,sipCallId:e.sip_call_id,callerName:e.caller_id_name,callerNumber:e.caller_id_number,calleeName:e.peer_caller_id_name,calleeNumber:e.peer_caller_id_number,dialedExtension:e.dialed_extension,isCaller:e.is_caller,isVideo:e.is_video,muted:e.muted,onHold:e.on_hold,status:e.status,lineId:e.line_id,startingTime:_(e.creation_time).toDate(),talkingToIds:Object.keys(e.talking_to||{}),recording:"active"===e.record_state})}static newFrom(e){return Ut(e,fi)}constructor({id:e,sipCallId:t,callerName:i,callerNumber:n,calleeName:r,calleeNumber:s,dialedExtension:a,isCaller:o,isVideo:c,lineId:d,muted:l,onHold:h,status:u,startingTime:p,talkingToIds:g,recording:f}){this.id=e,this.sipCallId=t,this.callerName=i,this.callerNumber=n,this.calleeName=r,this.calleeNumber=s,this.dialedExtension=a,this.muted=l,this.onHold=h,this.isCaller=o,this.lineId=d,this.status=u,this.startingTime=p,this.talkingToIds=g||[],this.recording=f,this.isVideo=!!c,this.type="Call"}getElapsedTimeInSeconds(){return(Date.now()-+this.startingTime)/1e3}separateCalleeName(){const e=this.calleeName.split(" ");return{firstName:e[0],lastName:e.slice(1).join(" ")}}is(e){return!!e&&this.id===e.id}hasACalleeName(){return this.calleeName.length>0}hasNumber(e){return this.calleeNumber===e}isUp(){return"Up"===this.status}isDown(){return"Down"===this.status}isRinging(){return this.isRingingIncoming()||this.isRingingOutgoing()}isRingingIncoming(){return"Ringing"===this.status}isRingingOutgoing(){return"Ring"===this.status}isFromTransfer(){return"Down"===this.status||"Ringing"===this.status}isOnHold(){return this.onHold}putOnHold(){this.onHold=!0}resume(){this.onHold=!1}isRecording(){return this.recording}}var mi;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(mi=mi||(mi={}));var vi=(e,t)=>{Object.keys(t).forEach((i=>{(!e[i]&&t[i]||void 0!==e[i]&&void 0!==t[i]&&e[i]!==t[i])&&(e[i]=t[i])}))};class yi{call;callId;displayName;realDisplayName;updatedNumber;number;callerNumber;creationTime;startTime;answerTime;endTime;isCaller;answeredBySystem;dialedExtension;ringing;paused;sipCallId;sipStatus;muted;videoMuted;videoRemotelyDowngraded;cameraEnabled;autoAnswer;ignored;screensharing;type;recording;recordingPaused;sipSession;conference;constructor({answered:e,answeredBySystem:t,isCaller:i,displayName:n,callId:r,muted:s,videoMuted:a,number:o,paused:c,ringing:d,startTime:l,creationTime:h,endTime:u,cameraEnabled:p,dialedExtension:g,sipCallId:f,sipStatus:m,callerNumber:v,call:y,autoAnswer:S,ignored:b,screensharing:w,recording:E,recordingPaused:C,videoRemotelyDowngraded:$,sipSession:T,answerTime:_,conference:x}){this.callId=r,this.sipCallId=f,this.displayName=n,this.number=o,this.creationTime=h,this.startTime=l,this.endTime=u,this.isCaller=i,this.answered=e,this.answeredBySystem=t,this.ringing=d,this.paused=c,this.muted=s,this.videoMuted=a,this.callerNumber=v,this.cameraEnabled=p,this.dialedExtension=g||"",this.call=y,this.sipStatus=m,this.autoAnswer=S||!1,this.ignored=b||!1,this.screensharing=w||!1,this.recording=E||!1,this.recordingPaused=C||!1,this.videoRemotelyDowngraded=$,this.sipSession=T,this.answerTime=_||this.answerTime,this.conference=x,this.type="CallSession"}resume(){this.paused=!1}hold(){this.paused=!0}mute(){this.muted=!0}unmute(){this.muted=!1}muteVideo(){this.videoMuted=!0}unmuteVideo(){this.videoMuted=!1}answer(){this.answerTime=new Date}systemAnswer(){this.answeredBySystem=!0}enableCamera(){this.cameraEnabled=!0}disableCamera(){this.cameraEnabled=!1}ignore(){this.ignored=!0}startScreenSharing(){this.screensharing=!0}stopScreenSharing(){this.screensharing=!1}setIsConference(e){this.conference=e}isIncoming(){return!this.isCaller&&!this.answered}isOutgoing(){return this.isCaller&&!this.answered}isActive(){return this.answered||this.isOutgoing()}isAnswered(){return this.answered}isAnsweredBySystem(){return this.answeredBySystem}isRinging(){return this.ringing}isOnHold(){return this.paused}isMuted(){return this.muted}isVideoMuted(){return this.videoMuted}isCameraEnabled(){return this.cameraEnabled}isIgnored(){return this.ignored}isScreenSharing(){return this.screensharing}isRecording(){return this.recording}recordingIsPaused(){return this.recordingPaused}hasAnInitialInterceptionNumber(){return this.number.startsWith("*8")}isAnInterception(){return this.dialedExtension.startsWith("*8")}isEstablished(){return this.sipStatus===mi.Established}isTerminating(){return this.sipStatus===mi.Terminating}isTerminated(){return this.sipStatus===mi.Terminated}isConference(){return this.conference}getElapsedTimeInSeconds(){return this.startTime?(Date.now()-this.startTime)/1e3:0}getId(){return this.sipCallId||this.callId}is(e){return!!e&&(this.isId(e.sipCallId)||this.isId(e.callId))}isId(e){return this.getId()===e||!!this.sipCallId&&this.sipCallId===e||!!this.callId&&this.callId===e}updateFrom(e){vi(this,e)}separateDisplayName(){const e=this.displayName.split(" ");return{firstName:e[0],lastName:e.slice(1).join(" ")}}getTalkingToIds(){return this.call?this.call.talkingToIds:[]}setVideoRemotelyDowngraded(e){this.videoRemotelyDowngraded=e}isVideoRemotelyDowngraded(){return this.videoRemotelyDowngraded}static newFrom(e){return Ut(e,yi)}set answered(e){this.answerTime=e?this.answerTime||new Date:null}get answered(){return!!this.answerTime}toJSON(){const e={...this};return e.answered=this.answered,e}static parseCall(e){return new yi({callId:e.id,sipCallId:e.sipCallId,displayName:e.calleeName||e.calleeNumber,number:e.calleeNumber,callerNumber:e.callerNumber,startTime:+e.startingTime,paused:e.isOnHold(),isCaller:e.isCaller,muted:e.muted,videoMuted:!1,screensharing:!1,recording:e.isRecording(),recordingPaused:!1,ringing:e.isRinging(),answered:e.isUp(),answeredBySystem:e.isUp()&&0===e.talkingToIds.length,cameraEnabled:e.isVideo,dialedExtension:e.dialedExtension,call:e,conference:!1})}}var Si,bi={exports:{}},wi="object"==typeof Reflect?Reflect:null,Ei=wi&&"function"==typeof wi.apply?wi.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};Si=wi&&"function"==typeof wi.ownKeys?wi.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Ci=Number.isNaN||function(e){return e!=e};function $i(){$i.init.call(this)}bi.exports=$i,bi.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}ki(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&ki(e,"error",t,i)}(e,r,{once:!0})}))},$i.EventEmitter=$i,$i.prototype._events=void 0,$i.prototype._eventsCount=0,$i.prototype._maxListeners=void 0;var Ti=10;function _i(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function xi(e){return void 0===e._maxListeners?$i.defaultMaxListeners:e._maxListeners}function Ii(e,t,i,n){var r,s,a,o;if(_i(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=xi(e))>0&&a.length>r&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.length,o=c,console&&console.warn&&console.warn(o)}return e}function Ri(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Ai(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=Ri.bind(n);return r.listener=i,n.wrapFn=r,r}function Pi(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):Ni(r,r.length)}function Di(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function Ni(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function ki(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}Object.defineProperty($i,"defaultMaxListeners",{enumerable:!0,get:function(){return Ti},set:function(e){if("number"!=typeof e||e<0||Ci(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Ti=e}}),$i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},$i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Ci(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},$i.prototype.getMaxListeners=function(){return xi(this)},$i.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var o=r[e];if(void 0===o)return!1;if("function"==typeof o)Ei(o,this,t);else{var c=o.length,d=Ni(o,c);for(i=0;i<c;++i)Ei(d[i],this,t)}return!0},$i.prototype.addListener=function(e,t){return Ii(this,e,t,!1)},$i.prototype.on=$i.prototype.addListener,$i.prototype.prependListener=function(e,t){return Ii(this,e,t,!0)},$i.prototype.once=function(e,t){return _i(t),this.on(e,Ai(this,e,t)),this},$i.prototype.prependOnceListener=function(e,t){return _i(t),this.prependListener(e,Ai(this,e,t)),this},$i.prototype.removeListener=function(e,t){var i,n,r,s,a;if(_i(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},$i.prototype.off=$i.prototype.removeListener,$i.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},$i.prototype.listeners=function(e){return Pi(this,e,!0)},$i.prototype.rawListeners=function(e){return Pi(this,e,!1)},$i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Di.call(e,t)},$i.prototype.listenerCount=Di,$i.prototype.eventNames=function(){return this._eventsCount>0?Si(this._events):[]};var Oi=C(bi.exports);class Fi{eventEmitter;constructor(){this.eventEmitter=new Oi}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.removeListener(e,t)}unbind(){this.eventEmitter.removeAllListeners()}}class Mi{static async fetchCallLogs(e,t){return pn().callLogd.listCallLogs(e,t)}static async fetchDistinctCallLogs(e,t,i="peer_exten"){return pn().callLogd.listDistinctCallLogs(e,t,i)}static async fetchActiveCalls(){return pn().calld.listCalls()}static async fetchCallLogsFromDate(e,t){return pn().callLogd.listCallLogsFromDate(e,t)}static async search(e,t){return pn().callLogd.search(e,t)}static async searchBy(e,t,i){return pn().callLogd.searchBy(e,t,i)}static async fetchSIP(e,t){const i=t||e.primaryLine();return pn().confd.getUserLineSip(e.uuid,i?i.id:"")}static async cancelCall(e){return pn().calld.cancelCall(e.callId)}static async makeCall(e,t,i=!1,n=!1){const r=e?e.id:null,s=await pn().calld.makeCall(t,i,r,n);return fi.parse(s)}static async relocateCall(e,t,i){return pn().calld.relocateCall(e,"line",t,i)}static async hold(e){return pn().calld.hold(e)}static async resume(e){return pn().calld.resume(e)}static async mute(e){return pn().calld.mute(e)}static async sendDTMF(e,t){return pn().calld.sendDTMF(e,t)}static async unmute(e){return pn().calld.unmute(e)}static async transferCall(e,t,i){return pn().calld.transferCall(e,t,i)}static async cancelCallTransfer(e){return pn().calld.cancelCallTransfer(e)}static async confirmCallTransfer(e){return pn().calld.confirmCallTransfer(e)}}const Hi="blind",Li=B?B.loggerFor("cti-phone"):console;class ji extends Fi{session;isMobile;callbackAllLines;currentCall;client=null;constructor(e,t=!1,i=!1){super(),Li.info("CTI Phone created"),this.session=e,this.isMobile=t,this.callbackAllLines=i}getOptions(){return{accept:!1,decline:!0,mute:!0,hold:!1,transfer:!0,sendKey:!0,addParticipant:!1,record:!0,merge:!1}}hasAnActiveCall(){return!!this.currentCall}callCount(){return this.currentCall?1:0}isWebRTC(){return!1}getUserAgent(){return"cti-phone"}startHeartbeat(){}setOnHeartbeatTimeout(){}setOnHeartbeatCallback(){}stopHeartbeat(){}bindClientEvents(){}onConnect(){return Promise.resolve()}onDisconnect(){}async makeCall(e,t){if(Li.info("make CTI call",{number:e}),!e)return null;try{this.currentCall=await Mi.makeCall(t,e,this.isMobile,this.callbackAllLines)}catch(e){}if(!this.currentCall)return null;const i=yi.parseCall(this.currentCall);return this.eventEmitter.emit("onCallOutgoing",i),i}accept(e){return e?(Li.info("accept CTI call",{callId:e.getId(),number:e.number}),this.currentCall||(this.currentCall=e.call),Promise.resolve(e.getId())):Promise.resolve(null)}endCurrentCall(e){e&&(Li.info("end current CTI call",{callId:e.getId(),number:e.number}),this.currentCall=void 0,this.eventEmitter.emit("onCallEnded",e))}async hangup(e){if(!e)return Promise.resolve(!1);Li.info("hangup CTI call",{callId:e.getId(),number:e.number});try{return await Mi.cancelCall(e),this.currentCall&&e.callId===this.currentCall.id&&this.endCurrentCall(e),this.eventEmitter.emit("onCallEnded",e),!0}catch(t){return Li.error("hangup CTI call, error",t),this.eventEmitter.emit("onCallFailed",e),!1}}ignore(){}async reject(e){e&&(Li.info("reject CTI call",{callId:e.getId(),number:e.number}),await Mi.cancelCall(e),this.eventEmitter.emit("onCallEnded",e))}async transfer(e,t){e&&(Li.info("transfer CTI call",{callId:e.getId(),number:e.number,to:t}),await Mi.transferCall(e.callId,t,Hi))}indirectTransfer(){return Promise.resolve(!1)}async initiateCTIIndirectTransfer(e,t){return e?(Li.info("indirect CTI transfer",{callId:e.getId(),number:e.number,to:t}),Mi.transferCall(e.callId,t,"attended")):Promise.resolve(null)}async cancelCTIIndirectTransfer(e){return Li.info("cancel CTI transfer",{transferId:e}),Mi.cancelCallTransfer(e)}async confirmCTIIndirectTransfer(e){return Li.info("confirm CTI transfer",{transferId:e}),Mi.confirmCallTransfer(e)}sendKey(e,t){e&&(Li.info("send CTI key",{callId:e.getId(),number:e.number,digits:t}),Mi.sendDTMF(e.callId,t))}onConnectionMade(){Li.info("on CTI connection made"),this.eventEmitter.emit("onCallAccepted")}async close(){return Li.info("CTI close"),Promise.resolve()}async hold(e){return!!e&&(Li.info("CTI hold",{callId:e.getId(),number:e.number}),Mi.hold(e.callId))}async resume(e){return!!e&&(Li.info("CTI resume",{callId:e.getId(),number:e.number}),Mi.resume(e.callId))}async mute(e){e&&(Li.info("CTI mute",{callId:e.getId(),number:e.number}),await Mi.mute(e.callId))}async unmute(e){e&&(Li.info("CTI unmute",{callId:e.getId(),number:e.number}),await Mi.unmute(e.callId))}putOnSpeaker(){}putOffSpeaker(){}turnCameraOff(){}turnCameraOn(){}changeAudioInputDevice(){return Promise.resolve(null)}changeVideoInputDevice(){return Promise.resolve(null)}changeAudioDevice(){return Promise.resolve()}changeRingDevice(){}changeAudioVolume(){}changeRingVolume(){}hasVideo(){return!1}hasAVideoTrack(){return!1}getLocalStreamForCall(){return null}getRemoteStreamForCall(){return null}getLocalVideoStream(){return null}setActiveSipSession(){}isRegistered(){return!0}hasIncomingCallSession(){return!0}hasActiveRemoteVideoStream(){return!1}getCurrentCallSession(){return this.currentCall?yi.parseCall(this.currentCall):null}enableRinging(){}sendMessage(){}disableRinging(){}getLocalStream(){return null}getRemoteStream(){return null}getRemoteVideoStream(){return null}getRemoteAudioStream(){return null}hasLocalVideo(){return!1}useLocalVideoElement(){}setMediaConstraints(){}register(){return Promise.resolve(null)}}var Bi={},Ui={};Object.defineProperty(Ui,"__esModule",{value:!0}),Ui.EnumType=void 0;var Vi=function(e){this.value=e};Ui.EnumType=Vi;var qi={};Object.defineProperty(qi,"__esModule",{value:!0}),qi.VariableType=void 0;var Gi=function(){function e(e){this.value=e}return e.prototype.toJSON=function(){return"$".concat(this.value)},e}();qi.VariableType=Gi,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.jsonToGraphQLQuery=e.configFields=void 0;var t=Ui,i=qi;function n(e){if(e instanceof t.EnumType)return e.value;if(e instanceof i.VariableType)return"$".concat(e.value);if("object"!=typeof e||null===e)return JSON.stringify(e);if(Array.isArray(e))return"[".concat(e.map((function(e){return n(e)})).join(", "),"]");var r=Object.keys(e).map((function(t){return"".concat(t,": ").concat(n(e[t]))})).join(", ");return"{".concat(r,"}")}function r(t,i){return-1==e.configFields.indexOf(t)&&-1==i.indexOf(t)}function s(e,t,i,a){Object.keys(e).filter((function(e){return r(e,a.ignoreFields)})).forEach((function(o){var c=e[o];if("object"==typeof c){if(Array.isArray(c)&&!(c=c.find((function(e){return e&&"object"==typeof e}))))return void i.push(["".concat(o),t]);if(c&&0===Object.keys(c).filter((function(e){return!1!==c[e]||a.includeFalsyKeys})).length)return;var d=Object.keys(c).filter((function(e){return r(e,a.ignoreFields)})).length>0,l="object"==typeof c.__args&&Object.keys(c.__args).length>0,h="object"==typeof c.__directives,u=c.__all_on instanceof Array,p="object"==typeof c.__on,g="".concat(o);if("string"==typeof c.__name&&(g="".concat(g," ").concat(c.__name)),"string"==typeof c.__aliasFor&&(g="".concat(g,": ").concat(c.__aliasFor)),"object"==typeof c.__variables&&Object.keys(c.__variables).length>0)g="".concat(g," (").concat(function(e){var t=[];for(var i in e)t.push("$".concat(i,": ").concat(e[i]));return t.join(", ")}(c.__variables),")");else if(l||h){var f="",m="";h&&(m=Object.entries(c.__directives).map((function(e){var t;return"@".concat(function(e){var t=Object.keys(e)[0],i=e[t];if("boolean"==typeof i||"object"==typeof i&&0===Object.keys(i).length)return t;if("object"==typeof i){var r=[];for(var s in i){var a=n(i[s]).replace(/"/g,"");r.push("".concat(s,": ").concat(a))}return"".concat(t,"(").concat(r.join(", "),")")}throw new Error("Unsupported type for directive: ".concat(typeof i,". Types allowed: object, boolean.\n")+"Offending object: ".concat(JSON.stringify(e)))}(((t={})[e[0]]=e[1],t)))})).join(" ")),l&&(f="(".concat(function(e){var t=[];for(var i in e)t.push("".concat(i,": ").concat(n(e[i])));return t.join(", ")}(c.__args),")"));var v=h&&l?" ":"";g="".concat(g," ").concat(f).concat(v).concat(m)}if(i.push([g+(d||p||u?" {":""),t]),s(c,t+1,i,a),u&&c.__all_on.forEach((function(e){i.push(["...".concat(e),t+1])})),p)(c.__on instanceof Array?c.__on:[c.__on]).forEach((function(e){var n=e.__typeName;i.push(["... on ".concat(n," {"),t+1]),s(e,t+2,i,a),i.push(["}",t+1])}));(d||p||u)&&i.push(["}",t])}else(!0===a.includeFalsyKeys||c)&&i.push(["".concat(o),t])}))}e.configFields=["__args","__alias","__aliasFor","__variables","__directives","__on","__all_on","__typeName","__name"],e.jsonToGraphQLQuery=function(e,t){if(void 0===t&&(t={}),!e||"object"!=typeof e)throw new Error("query object not specified");if(0==Object.keys(e).length)throw new Error("query object has no data");t.ignoreFields instanceof Array||(t.ignoreFields=[]);var i=[];s(e,0,i,t);var n="";return i.forEach((function(e){var i=e[0],r=e[1];t.pretty?(n&&(n+="\n"),n+=function(e){return Array(4*e+1).join(" ")}(r)+i):(n&&(n+=" "),n+=i)})),n}}(Bi);const Ki=e=>({email:e.email,firstname:e.firstName?e.firstName:"",lastname:e.lastName?e.lastName:"",number:e.phoneNumber?e.phoneNumber:"",entreprise:e.entreprise?e.entreprise:"",birthday:e.birthday?e.birthday:"",address:e.address?e.address:"",note:e.note?e.note:""});class Wi{deleted;end;fileName;start;uuid;static parseMany(e=[]){return e?e.map((e=>Wi.parse(e))):[]}static parse(e){return new Wi({deleted:e.deleted,fileName:e.filename,end:e.end_time?_(e.end_time).toDate():null,start:_(e.start_time).toDate(),uuid:e.uuid})}constructor({deleted:e,end:t,fileName:i,start:n,uuid:r}){this.deleted=e,this.end=t,this.fileName=i,this.start=n,this.uuid=r}}class zi{type;answer;answered;newMissedCall;callDirection;destination;recordings;source;id;duration;start;end;static merge(e,t){const i=e.concat(t);return i.map((e=>e.id)).filter(((e,t,i)=>i.indexOf(e)===t)).map((e=>i.find((t=>t&&t.id===e))))}static parseMany(e){return e&&e.items?e.items.map((e=>zi.parse(e))):[]}static parse(e){return new zi({answer:e.answer?_(e.answer).toDate():null,answered:e.answered,callDirection:e.call_direction,destination:{extension:e.requested_extension||e.destination_extension||`meeting-${e.requested_name||e.destination_name||""}`,name:e.requested_name||e.destination_name||"",uuid:e.destination_user_uuid},source:{extension:e.source_extension,name:e.source_name,uuid:e.source_user_uuid},id:e.id,duration:1e3*(e.duration||0),start:_(e.start).toDate(),end:e.end?_(e.end).toDate():null,recordings:Wi.parseMany(e.recordings||[])})}static parseNew(e,t){const i=zi.parse(e);return i.newMissedCall=t&&t.hasExtension(e.requested_extension||e.destination_extension)&&!e.answered,i}static newFrom(e){return Ut(e,zi)}constructor({answer:e,answered:t,callDirection:i,destination:n,source:r,id:s,duration:a,start:o,end:c,recordings:d}){this.answer=e,this.answered=t,this.callDirection=i,this.destination=n,this.source=r,this.id=s,this.duration=a,this.start=o,this.end=c,this.recordings=d||[],this.type="CallLog"}isFromSameParty(e,t){return this.theOtherParty(t).extension===e.theOtherParty(t).extension}theOtherParty(e){return"inbound"===this.callDirection?this.source:"outbound"===this.callDirection||e&&e.hasExtension(this.source.extension)?this.destination:this.source}isNewMissedCall(){return this.newMissedCall}acknowledgeCall(){return this.newMissedCall=!1,this}isAcknowledged(){return this.newMissedCall}isAnswered(){return this.answered}isOutgoing(e){return"internal"===this.callDirection?e.hasExtension(this.source.extension):"outbound"===this.callDirection}isIncoming(e){return"internal"===this.callDirection?e.hasExtension(this.destination.extension):"inbound"===this.callDirection}isAnOutgoingCall(e){return console.warn("@wazo/sdk \n CallLog.isAnOutgoingcall(session) method is obsolete.\n Please use CallLog.isOutgoing(session).\n "),e.hasExtension(this.source.extension)&&this.answered}isAMissedOutgoingCall(e){return e.hasExtension(this.source.extension)&&!this.answered}isAnIncomingCall(e){return console.warn("@wazo/sdk\n CallLog.isAnIncomingCall(session) method is obsolete.\n Please use CallLog.isIncoming(session).\n "),e.hasExtension(this.destination.extension)&&this.answered}isADeclinedCall(e){return!this.answered&&e.hasExtension(this.destination.extension)}getRecordings(){return this.recordings}}class Yi{type;uuid;name;users;static parseMany(e){return e&&e.items?e.items.map((e=>Yi.parse(e))):[]}static parse(e){return new Yi({uuid:e.uuid,name:e.name,users:e.users})}static newFrom(e){return Ut(e,Yi)}constructor({uuid:e,name:t,users:i}={}){this.uuid=e,this.name=t,this.users=i,this.type="ChatRoom"}}var Ji=(e,t)=>({updateState:(i,n)=>e.put(`${t}/users/${i}/presences`,{state:n},null,G.successResponseParser),updateStatus:(i,n,r)=>{const s={state:n,status:r};return e.put(`${t}/users/${i}/presences`,s,null,G.successResponseParser)},getState:async i=>e.get(`${t}/users/${i}/presences`).then((e=>e.state)),getContactStatusInfo:async i=>e.get(`${t}/users/${i}/presences`).then((e=>e)),getLineState:async i=>e.get(`${t}/users/${i}/presences`).then((e=>Yt.getLinesState(e.lines))),async getMultipleLineState(i){const n={},r=i||[];if(r.length>30){const e=r.reduce(((e,t,i)=>(i%30==0&&e.push(this.getMultipleLineState(r.slice(i,i+30))),e)),[]);return(await Promise.all(e)).flat()}return r.length&&(n.user_uuid=r.join(",")),e.get(`${t}/users/presences`,n).then((e=>e.items))},getUserRooms:async()=>e.get(`${t}/users/me/rooms`).then(Yi.parseMany),createRoom:async(i,n)=>e.post(`${t}/users/me/rooms`,{name:i,users:n}).then(Yi.parse),getRoomMessages:async(i,n)=>{const r=G.getQueryString(n||{});return e.get(`${t}/users/me/rooms/${i}/messages${r.length?`?${r}`:""}`).then((e=>pi.parseMany(e)))},sendRoomMessage:async(i,n)=>e.post(`${t}/users/me/rooms/${i}/messages`,n).then(pi.parse),getMessages:async i=>e.get(`${t}/users/me/rooms/messages`,i)});class Zi{status;id;sourceId;destinationId;constructor({sourceId:e,destinationId:t,status:i,id:n}){this.sourceId=e,this.destinationId=t,this.status=i,this.id=n}static parseFromCallSession(e,t){return new Zi({sourceId:e.getId(),destinationId:t.getId()})}static parseFromApi(e){return new Zi({id:e.id,status:e.status,sourceId:e.initiator_call,destinationId:e.recipient_call})}destinationIs(e){return e.isId(this.destinationId)}sourceIs(e){return e.isId(this.sourceId)}updateFrom(e){vi(this,e)}static newFrom(e){return Ut(e,Zi)}}class Xi{type;full;constructor({full:e}={}){this.full=e,this.type="MeetingStatus"}static parse(e){return new Xi({full:e.full})}}class Qi{context;extension;id;logged;number;paused;pausedReason;static parse(e){return new Qi({context:e.context,extension:e.extension,id:e.id,logged:e.logged,number:e.number,paused:e.paused,pausedReason:e.paused_reason})}constructor({context:e,extension:t,id:i,logged:n,number:r,paused:s,pausedReason:a}){this.context=e,this.extension=t,this.id=i,this.logged=n,this.number=r,this.paused=s,this.pausedReason=a}}class en{name;events;config;uuid;service;eventsUserUuid;eventsWazoUuid;metadata;ownerTenantUuid;ownerUserUuid;static parse(e){return new en({name:e.name,events:e.events,config:e.config,uuid:e.uuid,service:e.service,eventsUserUuid:e.events_user_uuid,eventsWazoUuid:e.events_wazo_uuid,metadata:e.metadata,ownerTenantUuid:e.owner_tenant_uuid,ownerUserUuid:e.owner_user_uuid})}static parseMany(e){return e.items.map((e=>en.parse(e)))}constructor({name:e,events:t,config:i,uuid:n,service:r,eventsUserUuid:s,eventsWazoUuid:a,metadata:o,ownerTenantUuid:c,ownerUserUuid:d}){this.name=e,this.events=t,this.config=i,this.uuid=n,this.service=r,this.eventsUserUuid=s,this.eventsWazoUuid=a,this.metadata=o,this.ownerTenantUuid=c,this.ownerUserUuid=d}}const tn=B?B.loggerFor("api"):console;class nn{client;auth;application;confd;ctidNg;dird;callLogd;chatd;calld;agentd;webhookd;amid;refreshToken;onRefreshToken;onRefreshTokenError;refreshExpiration;refreshBackend;refreshTenantId;refreshDomainName;isMobile;fetchOptions;constructor({server:e,agent:t=null,refreshToken:i,clientId:n,isMobile:r=!1,fetchOptions:s}){this.updateParameters({server:e,agent:t,clientId:n,fetchOptions:s}),this.refreshToken=i,this.isMobile=r||!1}initializeEndpoints(){var e,t;this.auth=(e=this.client,t="auth/0.1",{checkToken:i=>e.head(`${t}/token/${i}`,null,{}),authenticate:i=>e.get(`${t}/token/${i}`,null,{}).then((e=>ti.parse(e))),logIn(i){const n={backend:i.backend||ii,expiration:i.expiration||ni},r={Authorization:`Basic ${G.base64Encode(`${i.username}:${i.password}`)}`,"Content-Type":"application/json"};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),i.mobile&&(r["Wazo-Session-Type"]="mobile"),i.tenantId&&(console.warn("Use of `tenantId` is deprecated when calling logIn() method, use `domainName` instead."),n.tenant_id=i.tenantId),i.domainName&&(n.domain_name=i.domainName),e.post(`${t}/token`,n,r).then((e=>ti.parse(e)))},logOut:i=>e.delete(`${t}/token/${i}`,null,{},G.successResponseParser),samlLogIn:async i=>{const n={saml_session_id:i};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),e.post(`${t}/token`,n).then(ti.parse)},initiateIdpAuthentication:async(i,n)=>{const r={domain:i,redirect_url:n};return e.post(`${t}/saml/sso`,r,{Accept:"application/json","Content-Type":"application/json"},(e=>e))},refreshToken:(i,n,r,s,a,o)=>{const c={backend:n||ii,expiration:r||ni,refresh_token:i,client_id:e.clientId};a&&(console.warn("Use of `tenantId` is deprecated when calling refreshToken() method, use `domainName` instead."),c.tenant_id=a),o&&(c.domain_name=o);const d={"Content-Type":"application/json",...s?{"Wazo-Session-Type":"mobile"}:{}};return e.post(`${t}/token`,c,d,G.defaultParser,!1).then(ti.parse)},deleteRefreshToken:i=>e.delete(`${t}/users/me/tokens/${i}`,null,null,G.successResponseParser),updatePassword:(i,n,r)=>{const s={new_password:r,old_password:n};return e.put(`${t}/users/${i}/password`,s,null,G.successResponseParser)},sendDeviceToken:(i,n,r,s)=>{const a={token:n};return r&&(a.apns_token=r,a.apns_voip_token=r),s&&(a.apns_notification_token=s),e.post(`${t}/users/${i}/external/mobile`,a)},getPushNotificationSenderId:i=>e.get(`${t}/users/${i}/external/mobile/sender_id`,null).then((e=>e.sender_id)),sendResetPasswordEmail:({username:i,email:n})=>{const r={};return i&&(r.username=i),n&&(r.email=n),e.get(`${t}/users/password/reset`,r,{},G.successResponseParser)},resetPassword:(i,n)=>{const r={password:n};return e.post(`${t}/users/password/reset?user_uuid=${i}`,r,null,G.successResponseParser)},removeDeviceToken:i=>e.delete(`${t}/users/${i}/external/mobile`),createUser:(i,n,r,s)=>{const a={username:i,password:n,firstname:r,lastname:s};return e.post(`${t}/users`,a)},addUserEmail:(i,n,r)=>{const s={emails:[{address:n,main:r}]};return e.put(`${t}/users/${i}/emails`,s)},addUserPolicy:(i,n)=>e.put(`${t}/users/${i}/policies/${n}`),getRestrictionPolicies:i=>e.post(`${t}/token/${e.token}/scopes/check`,{scopes:i}),deleteUserPolicy:(i,n)=>e.delete(`${t}/users/${i}/policies/${n}`),addUserGroup:(i,n)=>e.put(`${t}/groups/${n}/users/${i}`),listUsersGroup:i=>e.get(`${t}/groups/${i}/users`),deleteUserGroup:(i,n)=>e.delete(`${t}/groups/${n}/users/${i}`),getUser:i=>e.get(`${t}/users/${i}`),getUserSession:i=>e.get(`${t}/users/${i}/sessions`),deleteUserSession:(i,n)=>e.delete(`${t}/users/${i}/sessions/${n}`),listUsers:()=>e.get(`${t}/users`),deleteUser:i=>e.delete(`${t}/users/${i}`),listTenants:()=>e.get(`${t}/tenants`),getTenant:i=>e.get(`${t}/tenants/${i}`),createTenant:i=>e.post(`${t}/tenants`,{name:i}),updateTenant:(i,n,r,s,a)=>{const o={name:n,contact:r,phone:s,address:a};return e.put(`${t}/tenants/${i}`,o)},deleteTenant:i=>e.delete(`${t}/tenants/${i}`),createGroup:i=>e.post(`${t}/groups`,{name:i}),listGroups:()=>e.get(`${t}/groups`),deleteGroup:i=>e.delete(`${t}/groups/${i}`),createPolicy:(i,n,r)=>{const s={name:i,description:n,acl_templates:r,acl:r};return e.post(`${t}/policies`,s)},listPolicies:()=>e.get(`${t}/policies`),deletePolicy:i=>e.delete(`${t}/policies/${i}`),getProviders:i=>e.get(`${t}/users/${i}/external`),getProviderToken:(i,n)=>e.get(`${t}/users/${i}/external/${n}`),getProviderAuthUrl:(i,n)=>e.post(`${t}/users/${i}/external/${n}`,{}),deleteProviderToken:(i,n)=>e.delete(`${t}/users/${i}/external/${n}`)}),this.application=((e,t)=>({bridgeCall(i,n,r,s,a,o){const c=`${t}/${i}/nodes`,d={calls:[{id:n}]};return e.post(c,d,null,(e=>e.json().then((e=>e.uuid)))).then((t=>e.post(`${c}/${t}/calls`,{context:r,exten:s,autoanswer:a,displayed_caller_id_number:o}).then((e=>({nodeUuid:t,data:e})))))},answerCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/answer`,{},null,G.successResponseParser),calls:i=>e.get(`${t}/${i}/calls`),hangupCall:(i,n)=>e.delete(`${t}/${i}/calls/${n}`),startPlaybackCall:(i,n,r,s)=>e.post(`${t}/${i}/calls/${n}/playbacks`,{language:r,uri:s}),stopPlaybackCall:(i,n)=>e.delete(`${t}/${i}/playbacks/${n}`),startProgressCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/progress/start`,{},null,G.successResponseParser),stopProgressCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/progress/stop`,{},null,G.successResponseParser),startMohCall:(i,n,r)=>e.put(`${t}/${i}/calls/${n}/moh/${r}/start`,{},null,G.successResponseParser),stopMohCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/moh/stop`,{},null,G.successResponseParser),startHoldCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/hold/start`,{},null,G.successResponseParser),stopHoldCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/hold/stop`,{},null,G.successResponseParser),startMuteCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/mute/start`,{},null,G.successResponseParser),stopMuteCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/mute/stop`,{},null,G.successResponseParser),sendDTMFCall:(i,n,r)=>e.put(`${t}/${i}/calls/${n}/dtmf`,{digits:r},null,G.successResponseParser),addCallNodes:(i,n,r)=>e.put(`${t}/${i}/nodes/${n}/calls/${r}`,{},null,G.successResponseParser),createNewNodeWithCall:(i,n)=>e.post(`${t}/${i}/nodes`,{calls:n}),addNewCallNodes:(i,n,r,s,a)=>e.post(`${t}/${i}/nodes/${n}/calls`,{context:r,exten:s,autoanswer:a}),listCallsNodes:(i,n)=>e.get(`${t}/${i}/nodes/${n}`),listNodes:i=>e.get(`${t}/${i}/nodes`),removeNode:(i,n)=>e.delete(`${t}/${i}/nodes/${n}`),removeCallNodes:(i,n,r)=>e.delete(`${t}/${i}/nodes/${n}/calls/${r}`),listSnoop:i=>e.get(`${t}/${i}/snoops`),removeSnoop:(i,n)=>e.delete(`${t}/${i}/snoops/${n}`),viewSnoop:(i,n)=>e.get(`${t}/${i}/snoops/${n}`),createSnoop:(i,n,r,s)=>e.post(`${t}/${i}/calls/${n}/snoops`,{snooping_call_id:r,whisper_mode:s}),updateSnoop:(i,n,r)=>e.put(`${t}/${i}/snoops/${n}`,{whisper_mode:r},null,G.successResponseParser)}))(this.client,"calld/1.0/applications"),this.confd=hi(this.client,"confd/1.1"),this.ctidNg=((e,t)=>({updatePresence:i=>e.put(`${t}/users/me/presences`,{presence:i},null,G.successResponseParser),listMessages:(i,n)=>{const r={};return i&&(r.participant_user_uuid=i),n&&(r.limit=n),e.get(`${t}/users/me/chats`,r).then(pi.parseMany)},sendMessage:(i,n,r)=>{const s={alias:i,msg:n,to:r};return e.post(`${t}/users/me/chats`,s,null,G.successResponseParser)},makeCall:(i,n,r,s=!1)=>{const a={from_mobile:n,extension:i};return r&&(a.line_id=r),s&&(a.all_lines=!0),e.post(`${t}/users/me/calls`,a)},cancelCall:i=>e.delete(`${t}/users/me/calls/${i}`),listCalls:()=>e.get(`${t}/users/me/calls`).then((e=>fi.parseMany(e.items))),relocateCall(i,n,r,s){const a={completions:["answer"],destination:n,initiator_call:i,auto_answer:!0};return(r||s)&&(a.location={}),r&&(a.location.line_id=r),s&&(a.location.contact=s),e.post(`${t}/users/me/relocates`,a).then(ui.parse)},transferCall(i,n,r=Hi){const s={exten:n,flow:r,initiator_call:i};return e.post(`${t}/users/me/transfers`,s)},cancelCallTransfer:i=>e.delete(`${t}/users/me/transfers/${i}`),confirmCallTransfer:i=>e.put(`${t}/users/me/transfers/${i}/complete`),listVoicemails:()=>e.get(`${t}/users/me/voicemails`,null).then((e=>gi.parseMany(e))),deleteVoicemail:i=>e.delete(`${t}/users/me/voicemails/messages/${i}`,null),getPresence:i=>e.get(`${t}/users/${i}/presences`,null),getStatus:i=>e.get(`${t}/lines/${i}/presences`,null),fetchSwitchboardHeldCalls:i=>e.get(`${t}/switchboards/${i}/calls/held`,null),holdSwitchboardCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}`,null,null,G.successResponseParser),answerSwitchboardHeldCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}/answer`,null),fetchSwitchboardQueuedCalls:i=>e.get(`${t}/switchboards/${i}/calls/queued`,null),answerSwitchboardQueuedCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/queued/${n}/answer`,null),sendFax:(i,n,r=null)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},a=G.getQueryString({extension:i,caller_id:r});return e.post(`${t}/users/me/faxes?${a}`,n,s)}}))(this.client,"ctid-ng/1.0"),this.dird=((e,t)=>({search:(i,n,r=0,s=null)=>e.get(`${t}/directories/lookup/${i}`,{term:n}).then((e=>Xt.parseMany(e,r,s))),listPersonalContacts:i=>e.get(`${t}/personal`,i).then((e=>Xt.parseManyPersonal(e.items))),fetchPersonalContact:i=>e.get(`${t}/personal/${i}`).then(Xt.parsePersonal),addContact:i=>e.post(`${t}/personal`,Ki(i)).then(Xt.parsePersonal),editContact:i=>e.put(`${t}/personal/${i.sourceId||i.id||""}`,Ki(i)).then(Xt.parsePersonal),importContacts:async i=>{const n={"Content-Type":"text/csv; charset=utf-8","X-Auth-Token":e.token};return e.post(`${t}/personal/import`,i,n).then((e=>Xt.parseManyPersonal(e.created)))},deleteContact:i=>e.delete(`${t}/personal/${i}`),listFavorites:i=>e.get(`${t}/directories/favorites/${i}`).then(Xt.parseMany),markAsFavorite:(i,n)=>{const r=`${t}/directories/favorites/${i}/${n}`;return e.put(r,null,null,G.successResponseParser)},removeFavorite:(i,n)=>e.delete(`${t}/directories/favorites/${i}/${n}`),fetchOffice365Source:i=>e.get(`${t}/directories/${i}/sources`,{backend:"office365"}),fetchOffice365Contacts:async(i,n)=>i?e.get(`${t}/backends/office365/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyOffice365(e.items,i))):Promise.resolve([]),fetchWazoSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"wazo"}),fetchWazoContacts:async(i,n)=>i?e.get(`${t}/backends/wazo/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyWazo(e.items,i))):Promise.resolve([]),fetchGoogleSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"google"}),fetchGoogleContacts:async(i,n)=>i?e.get(`${t}/backends/google/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyGoogle(e.items,i))):Promise.resolve([]),fetchConferenceSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"conference"}),fetchSourcesFor:(i,n)=>e.get(`${t}/directories/${i}/sources`,{backend:n}),fetchPhonebookContacts:async(i,n)=>i?e.get(`${t}/backends/phonebook/sources/${i.uuid}/contacts`,n):Promise.resolve({items:[],total:0}),fetchConferenceContacts:async(i,n)=>i?e.get(`${t}/backends/conference/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyConference(e.items,i))):Promise.resolve([]),findMultipleContactsByNumber:(i,n)=>{const r=Bi.jsonToGraphQLQuery({me:{contacts:{__args:{profile:"default",extens:i},edges:{node:n||{firstname:!0,lastname:!0,wazoReverse:!0,wazoBackend:!0,email:!0,wazoSourceEntryId:!0,wazoSourceName:!0,"... on WazoContact":{userUuid:!0}}}}}});return e.post(`${t}/graphql`,{query:`{${r}}`}).then(Xt.manyGraphQlWithNumbersParser(i))}}))(this.client,"dird/0.1"),this.callLogd=((e,t)=>({search:(i,n=5)=>e.get(`${t}/users/me/cdr`,{search:i,limit:n}).then(zi.parseMany),searchBy:(i,n,r=5)=>e.get(`${t}/users/me/cdr`,{[i]:n,limit:r}).then(zi.parseMany),listCallLogs:(i,n=5)=>e.get(`${t}/users/me/cdr`,{offset:i,limit:n}).then(zi.parseMany),listDistinctCallLogs:(i,n=5,r=void 0)=>e.get(`${t}/users/me/cdr`,{offset:i,limit:n,distinct:r}).then(zi.parseMany),listCallLogsFromDate:(i,n)=>e.get(`${t}/users/me/cdr`,{from:i.toISOString(),number:n}).then(zi.parseMany)}))(this.client,"call-logd/1.0"),this.chatd=Ji(this.client,"chatd/1.0"),this.calld=((e,t)=>({updatePresence:i=>e.put(`${t}/users/me/presences`,{presence:i},null,G.successResponseParser),listMessages:(i,n)=>{const r={};return i&&(r.participant_user_uuid=i),n&&(r.limit=n),e.get(`${t}/users/me/chats`,r).then((e=>pi.parseMany(e)))},sendMessage:(i,n,r)=>{const s={alias:i,msg:n,to:r};return e.post(`${t}/users/me/chats`,s,null,G.successResponseParser)},makeCall:(i,n,r,s=!1)=>{const a={from_mobile:n,extension:i};return r&&(a.line_id=r),s&&(a.all_lines=!0),e.post(`${t}/users/me/calls`,a)},cancelCall:i=>e.delete(`${t}/users/me/calls/${i}`,null),listCalls:()=>e.get(`${t}/users/me/calls`,null).then((e=>fi.parseMany(e.items))),relocateCall(i,n,r,s){const a={completions:["answer"],destination:n,initiator_call:i,auto_answer:!0};return(r||s)&&(a.location={}),r&&(a.location.line_id=r),s&&(a.location.contact=s),e.post(`${t}/users/me/relocates`,a).then((e=>ui.parse(e)))},listVoicemails:()=>e.get(`${t}/users/me/voicemails`).then((e=>gi.parseMany(e))),deleteVoicemail:i=>e.delete(`${t}/users/me/voicemails/messages/${i}`),getVoicemailUrl:i=>{const n={token:e.token};return e.computeUrl("get",`${t}/users/me/voicemails/messages/${i.id}/recording`,n)},fetchSwitchboardHeldCalls:i=>e.get(`${t}/switchboards/${i}/calls/held`),holdSwitchboardCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}`,null,null,G.successResponseParser),answerSwitchboardHeldCall:(i,n,r=null)=>e.put(`${t}/switchboards/${i}/calls/held/${n}/answer${r?`?line_id=${r}`:""}`),fetchSwitchboardQueuedCalls:i=>e.get(`${t}/switchboards/${i}/calls/queued`),answerSwitchboardQueuedCall:(i,n,r=null)=>e.put(`${t}/switchboards/${i}/calls/queued/${n}/answer${r?`?line_id=${r}`:""}`),sendFax:(i,n,r)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},a=G.getQueryString({extension:i,caller_id:r});return e.post(`${t}/users/me/faxes?${a}`,n,s)},getConferenceParticipantsAsUser:async i=>e.get(`${t}/users/me/conferences/${i}/participants`),getMeetingParticipantsAsUser:async i=>e.get(`${t}/users/me/meetings/${i}/participants`),banMeetingParticipant:(i,n)=>e.delete(`${t}/users/me/meetings/${i}/participants/${n}`,null,null,G.successResponseParser),listTrunks:()=>e.get(`${t}/trunks`),mute:i=>e.put(`${t}/users/me/calls/${i}/mute/start`,null,null,G.successResponseParser),unmute:i=>e.put(`${t}/users/me/calls/${i}/mute/stop`,null,null,G.successResponseParser),hold:i=>e.put(`${t}/users/me/calls/${i}/hold/start`,null,null,G.successResponseParser),resume:i=>e.put(`${t}/users/me/calls/${i}/hold/stop`,null,null,G.successResponseParser),transferCall:(i,n,r)=>e.post(`${t}/users/me/transfers`,{initiator_call:i,exten:n,flow:r}).then(Zi.parseFromApi),confirmCallTransfer:i=>e.put(`${t}/users/me/transfers/${i}/complete`,null,null,G.successResponseParser),cancelCallTransfer:i=>e.delete(`${t}/users/me/transfers/${i}`,null,null,G.successResponseParser),sendDTMF:(i,n)=>e.put(`${t}/users/me/calls/${i}/dtmf?digits=${encodeURIComponent(n)}`,null,null,G.successResponseParser),isAhHocConferenceAPIEnabled:()=>e.head(`${t}/users/me/conferences/adhoc`,null,null,G.successResponseParser),createAdHocConference:(i,n)=>e.post(`${t}/users/me/conferences/adhoc`,{host_call_id:i,participant_call_ids:n}),addAdHocConferenceParticipant:(i,n)=>e.put(`${t}/users/me/conferences/adhoc/${i}/participants/${n}`,null,null,G.successResponseParser),removeAdHocConferenceParticipant:(i,n)=>e.delete(`${t}/users/me/conferences/adhoc/${i}/participants/${n}`,null,null,G.successResponseParser),deleteAdHocConference:i=>e.delete(`${t}/users/me/conferences/adhoc/${i}`,null,null,G.successResponseParser),startRecording:i=>e.put(`${t}/users/me/calls/${i}/record/start`,null,null,G.successResponseParser),stopRecording:i=>e.put(`${t}/users/me/calls/${i}/record/stop`,null,null,G.successResponseParser),pauseRecording:i=>e.put(`${t}/users/me/calls/${i}/record/pause`,null,null,G.successResponseParser),resumeRecording:i=>e.put(`${t}/users/me/calls/${i}/record/resume`,null,null,G.successResponseParser),guestGetMeetingStatus:i=>e.get(`${t}/guests/me/meetings/${i}/status`).then(Xi.parse)}))(this.client,"calld/1.0"),this.agentd=((e,t)=>({getAgent:i=>e.get(`${t}/agents/by-id/${i}`,null).then(Qi.parse),login:(i,n,r)=>e.post(`${t}/agents/by-number/${i}/login`,{context:n,extension:r},null,G.successResponseParser),loginWithLineId:i=>e.post(`${t}/users/me/agents/login`,{line_id:i},null,G.successResponseParser),logout:i=>e.post(`${t}/agents/by-number/${i}/logoff`,null,null,G.successResponseParser),pause:i=>e.post(`${t}/agents/by-number/${i}/pause`,{reason:"songbird_reason"},null,G.successResponseParser),resume:i=>e.post(`${t}/agents/by-number/${i}/unpause`,null,null,G.successResponseParser),getStatus:()=>e.get(`${t}/users/me/agents`,null).then(Qi.parse),staticLogout:()=>e.post(`${t}/users/me/agents/logoff`,null,null,G.successResponseParser),staticPause:()=>e.post(`${t}/users/me/agents/pause`,{reason:"songbird_reason"},null,G.successResponseParser),staticResume:()=>e.post(`${t}/users/me/agents/unpause`,null,null,G.successResponseParser)}))(this.client,"agentd/1.0"),this.webhookd=((e,t)=>({getSubscriptions:()=>e.get(`${t}/users/me/subscriptions`).then(en.parseMany),getSubscription:i=>e.get(`${t}/users/me/subscriptions/${i}`).then(en.parse),createSubscription:i=>e.post(`${t}/users/me/subscriptions`,i),removeSubscription:i=>e.delete(`${t}/users/me/subscriptions/${i}`)}))(this.client,"webhookd/1.0"),this.amid=((e,t)=>({action:(i,n={})=>e.post(`${t}/action/${i}`,n),getAors:async i=>{try{const n=await e.post(`${t}/action/PJSIPShowEndpoint`,{Endpoint:i})||[];return n?n.filter((e=>"ContactStatusDetail"===e.Event)):[]}catch{return[]}}}))(this.client,"amid/1.0")}updateParameters({server:e,agent:t,clientId:i,fetchOptions:n}){const r=this.refreshTokenCallback.bind(this);this.client=new G({server:e,agent:t,refreshTokenCallback:r,clientId:i,fetchOptions:n}),this.initializeEndpoints()}async forceRefreshToken(){return tn.info("forcing refresh token, calling callback"),this.refreshTokenCallback()}async refreshTokenCallback(){if(tn.info("refresh token callback called",{refreshToken:R(this.refreshToken),refreshBackend:this.refreshBackend,refreshTenantId:this.refreshTenantId,refreshDomainName:this.refreshDomainName,refreshExpiration:this.refreshExpiration,isMobile:this.isMobile}),!this.refreshToken)return null;try{const e=await this.auth.refreshToken(this.refreshToken,this.refreshBackend,this.refreshExpiration,this.isMobile,this.refreshTenantId,this.refreshDomainName);return e?(tn.info("token refreshed",{token:R(e.token)}),this.onRefreshToken&&this.onRefreshToken(e.token,e),this.setToken(e.token),e.token):null}catch(e){tn.error("token refresh, error",e),this.onRefreshTokenError&&this.onRefreshTokenError(e)}return null}setToken(e){this.client.setToken(e)}setTenant(e){this.client.setTenant(e)}setRefreshToken(e){this.refreshToken=e}setRequestTimeout(e){this.client.setRequestTimeout(e)}setClientId(e){this.client.clientId=e}setOnRefreshToken(e){this.onRefreshToken=e}setOnRefreshTokenError(e){this.onRefreshTokenError=e}setRefreshExpiration(e){this.refreshExpiration=e}setRefreshBackend(e){this.refreshBackend=e}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead"),this.refreshTenantId=e}setRefreshDomainName(e){this.refreshDomainName=e}setIsMobile(e){this.isMobile=e}setFetchOptions(e){this.fetchOptions=e,this.client.setFetchOptions(e)}disableErrorLogging(){this.client.disableErrorLogging()}}global.wazoClients=global.wazoClients||{},global.wazoClientId=global.wazoClientId||{},global.wazoClientToken=global.wazoClientToken||{},global.wazoRefreshToken=global.wazoRefreshToken||{},global.wazoRefreshTenantId=global.wazoRefreshTenantId||{},global.wazoRefreshDomainName=global.wazoRefreshDomainName||{},global.wazoOnRefreshToken=global.wazoOnRefreshToken||{},global.wazoOnRefreshTokenError=global.wazoOnRefreshTokenError||{},global.wazoRefreshExpiration=global.wazoRefreshExpiration||{},global.wazoRefreshBackend=global.wazoRefreshBackend||{},global.wazoIsMobile=global.wazoIsMobile||{},global.wazoRequestApiTimeout=global.wazoRequestApiTimeout||{},global.wazoFetchOptions=global.wazoFetchOptions||{};const rn=(e,t=null)=>{global.wazoClientId[String(t)]=e},sn=e=>{global.wazoCurrentServer=e},an=(e,t=null)=>{global.wazoClientToken[String(t)]=e},on=(e,t=null)=>{global.wazoRefreshToken[String(t)]=e},cn=(e,t=null)=>{global.wazoOnRefreshToken[String(t)]=e},dn=(e,t=null)=>{global.wazoOnRefreshTokenError[String(t)]=e},ln=(e,t=null)=>{global.wazoFetchOptions[String(t)]=e},hn=(e=null)=>(e?global.wazoFetchOptions[e]:global.wazoFetchOptions.null)||global.wazoFetchOptions.null,un=e=>{const{server:t,token:i,clientId:n}=e.client,r=global.wazoRefreshTenantId[t]||global.wazoRefreshTenantId.null||e.refreshTenantId,s=global.wazoRequestApiTimeout[t]||global.wazoRequestApiTimeout.null;return e.setToken(global.wazoClientToken[t]||global.wazoClientToken.null||i),e.setClientId(global.wazoClientId[t]||global.wazoClientId.null||n),e.setRefreshToken(global.wazoRefreshToken[t]||global.wazoRefreshToken.null||e.refreshToken),r&&e.setRefreshTenantId(r),e.setRefreshDomainName(global.wazoRefreshDomainName[t]||global.wazoRefreshDomainName.null||e.refreshDomainName),e.setFetchOptions(global.wazoFetchOptions[t]||global.wazoFetchOptions.null||e.fetchOptions),e.setOnRefreshToken(global.wazoOnRefreshToken[t]||global.wazoOnRefreshToken.null||e.onRefreshToken),e.setOnRefreshTokenError(global.wazoOnRefreshTokenError[t]||global.wazoOnRefreshTokenError.null||e.onRefreshTokenError),e.setRefreshExpiration(global.wazoRefreshExpiration[t]||global.wazoRefreshExpiration.null||e.refreshExpiration),e.setRefreshBackend(global.wazoRefreshBackend[t]||global.wazoRefreshBackend.null||e.refreshBackend),e.setIsMobile(global.wazoIsMobile[t]||global.wazoIsMobile.null||e.isMobile),s&&e.setRequestTimeout(s),e};var pn=(e=null)=>{const t=e||global.wazoCurrentServer||"";return t in global.wazoClients||(global.wazoClients[t]=new nn({server:t})),un(global.wazoClients[t])};class gn extends Error{}class fn extends Error{}class mn extends Error{}class vn extends Error{}class yn extends Error{}class Sn extends Error{}const bn=B.loggerFor("simple-auth");class wn{clientId;expiration;minSubscriptionType;authorizationName;host;session;onRefreshTokenCallback;onRefreshTokenCallbackError;onHostFromHeadersCallback;authenticated;mobile;BACKEND_WAZO;BACKEND_LDAP;usingEdgeServer;onSetUsingEdgeServer;constructor(){this.expiration=ni,this.authenticated=!1,this.minSubscriptionType=null,this.BACKEND_WAZO=ii,this.BACKEND_LDAP="ldap_user"}init(e,t,i,n,r){this.clientId=e,this.expiration=t,this.minSubscriptionType=void 0===i?null:i,this.authorizationName=n,this.host=null,this.session=null,this.mobile=r||!1,rn(this.clientId),((e,t=null)=>{global.wazoRefreshExpiration[String(t)]=e})(this.expiration),cn(((e,t)=>{bn.info("on refresh token done",{token:R(e)}),an(e),Ol.Websocket.updateToken(e),this.onRefreshTokenCallback&&this.onRefreshTokenCallback(e,t)})),dn((e=>{bn.error("on refresh token error",e),this.onRefreshTokenCallbackError&&this.onRefreshTokenCallbackError(e)}))}setFetchOptions(e){ln(e)}async logIn(e,t,i,n){let r=null,s=null;if("string"==typeof n&&(r=n),n&&"object"==typeof n&&(s=n.domainName),i&&i!==this.BACKEND_WAZO&&!r&&!s){if(!r)throw new mn("No tenant id");if(!s)throw new vn("No domain name")}this.authenticated=!1,this.session=null;const a=await pn().auth.logIn({username:e,password:t,backend:i,tenantId:r,domainName:s,expiration:this.expiration,mobile:this.mobile});if(a){const e=a.getHostFromHeader();e&&(this.setHost(e),this.onHostFromHeadersCallback&&this.onHostFromHeadersCallback(e))}return i&&pn().setRefreshBackend(i),r&&pn().setRefreshTenantId(r),s&&pn().setRefreshDomainName(s),this._onAuthenticated(a)}async samlLogIn(e){const t=await pn().auth.samlLogIn(e);return this._onAuthenticated(t)}async initiateIdpAuthentication(e,t){let i;try{i=await pn().auth.initiateIdpAuthentication(e,t)}catch(e){throw bn.error("Error during IdP authentication initialization:",e.message),e}if(!i.ok){if(404===i.status)throw new yn("No route found for SAML SSO");if(500===i.status)throw new Sn("SAML/server configuration error");const e=await i.json();throw new Error(e.message||e.reason)}return i.json()}async logInViaRefreshToken(e){const t=await pn().auth.refreshToken(e,"",this.expiration,this.mobile);return this._onAuthenticated(t)}async validateToken(e,t,i){if(e){this.usingEdgeServer&&"string"==typeof i&&(bn.info("using edge server, setting user UUID header",{headerUserUuid:i}),this.setHttpUserUuidHeader(i)),t&&on(t);try{const t=await pn().auth.authenticate(e);return this._onAuthenticated(t)}catch(e){bn.error("on validate token error",e),console.warn(e)}}}async generateNewToken(e){return pn().auth.refreshToken(e,"",this.expiration)}async logout(e=!0){try{Ol.Websocket.close(!0),this.clientId&&e&&await pn().auth.deleteRefreshToken(this.clientId)}catch(e){}try{this.session?.token&&await pn().auth.logOut(this.session.token)}catch(e){}an(null),on(null),this.session=null,this.authenticated=!1,this.usingEdgeServer=void 0,ln({})}setOnHostFromHeaders(e){this.onHostFromHeadersCallback=e}setOnSetUsingEdgeServer(e){bn.info("setting onSetUsingEdgeServer callback",{callback:"function"==typeof e}),this.onSetUsingEdgeServer=e}setOnRefreshToken(e){this.onRefreshTokenCallback=e}setOnRefreshTokenError(e){this.onRefreshTokenCallbackError=e}checkAuthorizations(e,t){if(!t)return;const{authorizations:i}=e;if(!i.find((e=>e.rules.find((e=>e.name===t)))))throw new fn(`No authorization '${t||""}' found for your account.`)}checkSubscription(e,t){const i=e.profile?.subscriptionType||null;if(null===i||i<=t){throw new gn(`Invalid subscription ${i||"n/a"}, required at least ${t}`)}}setHost(e){this.host=e,sn(e)}setApiToken(e){an(e)}setRefreshToken(e){on(e)}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead."),((e,t=null)=>{console.warn("Use of `setRefreshTenantId` is deprecated, please use `setRefreshDomainName` instead"),global.wazoRefreshTenantId[String(t)]=e})(e),pn().setRefreshTenantId(e)}setRefreshDomainName(e){((e,t=null)=>{global.wazoRefreshDomainName[String(t)]=e})(e),pn().setRefreshDomainName(e)}setRequestTimeout(e){((e,t=null)=>{global.wazoRequestApiTimeout[String(t)]=e})(e),pn().setRequestTimeout(e)}forceRefreshToken(){return pn().forceRefreshToken()}setIsMobile(e){this.mobile=e}getHost(){return this.host||void 0}getSession(){return this.session||void 0}getFirstName(){return this.session&&this.session.profile?this.session.profile.firstName:""}getLastName(){return this.session&&this.session.profile?this.session.profile.lastName:""}setClientId(e){this.clientId=e,rn(this.clientId)}getName(){return`${this.getFirstName()} ${this.getLastName()}`}_getHttpUserUuidHeaders(e){return{...hn()?.headers||{},"X-User-UUID":e}}setHttpUserUuidHeader(e){if(bn.info("Setting http header user uuid",{uuid:e}),!e)return void bn.warn("attempting to set a null value to user uuid header");const t=this._getHttpUserUuidHeaders(e);ln({...hn(),headers:t})}async checkHttpUserUuidHeader(e){if(bn.info("Checking user uuid http header",{uuid:e}),!e)return;const t=this._getHttpUserUuidHeaders(e);try{const i=await pn().client.head("auth/0.1/status",null,t,(e=>e)),n=i.headers.get("access-control-allow-headers")?.includes("X-User-UUID");if(this.mobile&&!n)throw new Error("Server does not allow user UUID header on mobile");this.setHttpUserUuidHeader(e),this.usingEdgeServer=!0,bn.info("Setting usingEdgeServer value to TRUE",{requestHeaders:t,responseHeaders:i.headers,allowsUserUuidHeader:n})}catch(e){this.usingEdgeServer=!1,bn.info("Setting usingEdgeServer to FALSE",{justification:e})}"function"==typeof this.onSetUsingEdgeServer&&(bn.info("calling onSetUsingEdgeServer",{usingEdgeServer:this.usingEdgeServer}),this.onSetUsingEdgeServer(this.usingEdgeServer))}async _onAuthenticated(e){if(this.authenticated&&this.session)return this.session;const t=e;if(!t)return null;this.usingEdgeServer?this.setHttpUserUuidHeader(t.uuid):void 0===this.usingEdgeServer&&await this.checkHttpUserUuidHeader(t.uuid),an(t.token),t.refreshToken&&on(t.refreshToken);try{const[e,{wazo_version:i}]=await Promise.all([pn().confd.getUser(t.uuid),pn().confd.getInfos()]);t.engineVersion=i,t.profile=e,this.checkAuthorizations(t,this.authorizationName),null!==this.minSubscriptionType&&this.checkSubscription(t,+this.minSubscriptionType)}catch(e){throw bn.error("on authenticated error",e),this.clientId&&await pn().auth.deleteRefreshToken(this.clientId),t&&await pn().auth.logOut(t.token),e}try{const e=t.profile?.lines.filter((e=>!e.endpointSccp)).map((e=>String(e.id))),i=await pn().confd.getUserLinesSip(t.uuid,e);t.profile.sipLines=i.filter((e=>e instanceof ai))}catch(e){}return this.authenticated=!0,Ol.Websocket.open(this.host,t),this.session=t,t}}global.wazoAuthInstance||(global.wazoAuthInstance=new wn);var En=global.wazoAuthInstance;class Cn{phone;host;participants;started;finished;conferenceId;answerTime;muted;paused;constructor({phone:e,host:t,participants:i,started:n,finished:r,answerTime:s,conferenceId:a,muted:o,paused:c}){this.phone=e,this.host=t,this.participants=i||{},this.started=n||!1,this.finished=r||!1,this.answerTime=s,this.conferenceId=a||"",this.muted=o||!1,this.paused=c||!1,this.host&&this.host.setIsConference(!0)}async start(){this.started=!0,this.answerTime=Object.values(this.participants).length?Object.values(this.participants)[0].answerTime:null;const e=Object.keys(this.participants),t=await pn().calld.createAdHocConference(this.host.callId,e);return this.conferenceId=t.conference_id,this}getParticipants(){return Object.values(this.participants)}async addParticipant(e){const t=e.getTalkingToIds()[0],i={...this.participants,[t]:e};return await pn().calld.addAdHocConferenceParticipant(this.conferenceId,t),new Cn({...this,participants:i})}participantHasLeft(e){return delete this.participants[e.getId()],new Cn({...this,participants:this.participants})}hasParticipants(){return Object.keys(this.participants).length>0}mute(){return this.muted=!0,this.phone.mute(this.host),new Cn({...this})}unmute(){return this.muted=!1,this.phone.unmute(this.host),new Cn({...this})}hold(){return this.paused=!0,this.phone.hold(this.host),new Cn({...this})}resume(){return this.paused=!1,this.phone.resume(this.host),new Cn({...this})}isOnHold(){return this.paused}isMuted(){return this.muted}async hangup(){return await pn().calld.deleteAdHocConference(this.conferenceId),new Cn({...this,finished:!0,participant:[]})}async removeParticipant(e){const t=e.getTalkingToIds()[0];return delete this.participants[t],await pn().calld.removeAdHocConferenceParticipant(this.conferenceId,t),new Cn({...this,participants:this.participants})}}class $n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class Tn extends $n{constructor(e){super(e||"Unsupported content type.")}}class _n extends $n{constructor(e){super(e||"Request pending.")}}class xn extends $n{constructor(e){super(e||"Unspecified session description handler error.")}}class In extends $n{constructor(){super("The session has terminated.")}}class Rn extends $n{constructor(e){super(e||"An error occurred during state transition.")}}class An{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Pn{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class Dn{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class Nn{constructor(){this.listeners=new Array}addListener(e,t){const i=t=>{this.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}emit(e){this.listeners.slice().forEach((t=>t(e)))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class kn{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class On{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class Fn extends On{constructor(e,t,i){super(i),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new Fn(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class Mn extends On{constructor(e="sip",t,i,n,r,s){if(super(r||{}),this.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(const e in s)s.hasOwnProperty(e)&&this.setHeader(e,s[e]);this.raw={scheme:e,user:t,host:i,port:n},this.normal={scheme:e.toLowerCase(),user:t,host:i.toLowerCase(),port:n}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new Mn(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const i=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&i.push(e+"="+this.headers[e][t]);return i.length>0&&(t+="?"+i.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),n=i.length;let r="";for(let e=0;e<n;e++)0!==e&&(r+="-"),r+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[r]&&(r=t[r]),r}}function Hn(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){const i=Object.keys(e.parameters),n=Object.keys(t.parameters);return!!i.filter((e=>n.includes(e))).every((i=>e.parameters[i]===t.parameters[i]))&&(!!["user","ttl","method","transport"].every((i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i)))&&!!["maddr"].every((i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i))))}(e,t))return!1;const i=Object.keys(e.headers),n=Object.keys(t.headers);if(0!==i.length||0!==n.length){if(i.length!==n.length)return!1;const r=i.filter((e=>n.includes(e)));if(r.length!==n.length)return!1;if(!r.every((i=>e.headers[i].length&&t.headers[i].length&&e.headers[i][0]===t.headers[i][0])))return!1}return!0}function Ln(e,t,i){return i=i||" ",e.length>t?e:(t-=e.length,e+(i+=i.repeat(t)).slice(0,t))}class jn extends Error{constructor(e,t,i,n){super(),this.message=e,this.expected=t,this.found=i,this.location=n,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,jn.prototype):this.__proto__=jn.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,jn)}static buildMessage(e,t){function i(e){return e.charCodeAt(0).toString(16).toUpperCase()}function n(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(e=>"\\x0"+i(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+i(e)))}function r(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(e=>"\\x0"+i(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+i(e)))}function s(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":const t=e.parts.map((e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(e)));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(s);let i,n;if(t.sort(),t.length>0){for(i=1,n=1;i<t.length;i++)t[i-1]!==t[i]&&(t[n]=t[i],n++);t.length=n}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((a=t)?'"'+n(a)+'"':"end of input")+" found.");var a}format(e){let t="Error: "+this.message;if(this.location){let i,n=null;for(i=0;i<e.length;i++)if(e[i].source===this.location.source){n=e[i].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,s=this.location.source+":"+r.line+":"+r.column;if(n){let e=this.location.end,i=Ln("",r.line.toString().length," "),a=n[r.line-1],o=r.line===e.line?e.column:a.length+1;t+="\n --\x3e "+s+"\n"+i+" |\n"+r.line+" | "+a+"\n"+i+" | "+Ln("",r.column-1," ")+Ln("",o-r.column,"^")}else t+="\n at "+s}return t}}const Bn=function(e,t){const i={},n=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let s=119;const a=["\r\n",v("\r\n",!1),/^[0-9]/,y([["0","9"]],!1,!1),/^[a-zA-Z]/,y([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,y([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,y([["\0","ÿ"]],!1,!1),/^["]/,y(['"'],!1,!1)," ",v(" ",!1),"\t",v("\t",!1),/^[a-zA-Z0-9]/,y([["a","z"],["A","Z"],["0","9"]],!1,!1),";",v(";",!1),"/",v("/",!1),"?",v("?",!1),":",v(":",!1),"@",v("@",!1),"&",v("&",!1),"=",v("=",!1),"+",v("+",!1),"$",v("$",!1),",",v(",",!1),"-",v("-",!1),"_",v("_",!1),".",v(".",!1),"!",v("!",!1),"~",v("~",!1),"*",v("*",!1),"'",v("'",!1),"(",v("(",!1),")",v(")",!1),"%",v("%",!1),function(){return" "},function(){return":"},/^[!-~]/,y([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,y([["",""]],!1,!1),/^[\x80-\xBF]/,y([["","¿"]],!1,!1),/^[a-f]/,y([["a","f"]],!1,!1),"`",v("`",!1),"<",v("<",!1),">",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\v-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(f().slice(0,-1))},function(){(t=t||{data:{}}).data.password=f()},function(){return(t=t||{data:{}}).data.host=f(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",f()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},function(){return(t=t||{data:{}}).data.host_type="IPv4",f()},"25",v("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,i){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),i=null===i?void 0:i[1],t.data.uri_params[e.toLowerCase()]=i},function(e,i){e=e.join("").toLowerCase(),i=i.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(i):t.data.uri_headers[e]=[i]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=f()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=f()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=f(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=f()},function(){(t=t||{data:{}}).data=f()},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Fn(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(e){'"'===(e=f().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",v("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",v("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",v("0",!1),function(){return parseFloat(f())},function(e,i){(t=t||{data:{}}).data.params||(t.data.params={}),i=null===i?void 0:i[1],t.data.params[e.toLowerCase()]=i},"render",v("render",!0),"session",v("session",!0),"icon",v("icon",!0),"alert",v("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=f().toLowerCase())},"handling",v("handling",!0),"optional",v("optional",!0),"required",v("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=f()},"text",v("text",!0),"image",v("image",!0),"audio",v("audio",!0),"video",v("video",!0),"application",v("application",!0),"message",v("message",!0),"multipart",v("multipart",!0),"x-",v("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Fn(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",v("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new Fn(t.data.uri,t.data.displayName,t.data.params)},"digest",v("Digest",!0),"realm",v("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",v("domain",!0),"nonce",v("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",v("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",v("stale",!0),"true",v("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",v("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",v("algorithm",!0),"md5",v("MD5",!0),"md5-sess",v("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",v("qop",!0),"auth-int",v("auth-int",!0),"auth",v("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Fn(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new Fn(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",v("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",v("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",v("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",v("active",!0),"pending",v("pending",!0),"terminated",v("terminated",!0),function(){(t=t||{data:{}}).data.state=f()},"reason",v("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",v("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",v("deactivated",!0),"probation",v("probation",!0),"rejected",v("rejected",!0),"timeout",v("timeout",!0),"giveup",v("giveup",!0),"noresource",v("noresource",!0),"invariant",v("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Fn(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",v("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",v("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",v("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",v("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",v("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},v("UDP",!0),v("TCP",!0),v("TLS",!0),v("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=f()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",v("refresher",!1),"uas",v("uas",!1),"uac",v("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",v("stuns",!0),"stun",v("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",v("?transport=",!1),"turns",v("turns",!0),"turn",v("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=f()},"Referred-By",v("Referred-By",!1),"b",v("b",!1),"cid",v("cid",!1)],o=[E('2 ""6 7!'),E('4"""5!7#'),E('4$""5!7%'),E('4&""5!7\''),E(";'.# &;("),E('4(""5!7)'),E('4*""5!7+'),E('2,""6,7-'),E('2.""6.7/'),E('40""5!71'),E('22""6273. &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E(";).# &;,"),E('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),E('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),E('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),E(';.." &"'),E("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),E('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E('4\\""5!7].# &;3'),E('4^""5!7_'),E('4`""5!7a'),E(';!.) &4b""5!7c'),E('%$;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('%$;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273. &28""6879. &2j""6j7k. &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),E('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),E("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),E("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),E("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),E("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),E("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),E('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),E('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),E("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),E("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),E("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),E("%;//0#;&/'$8\":~\" )(\"'#&'#"),E("%;&/0#;//'$8\":~\" )(\"'#&'#"),E("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),E('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),E("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),E("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),E(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),E('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),E("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),E("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),E('%3""5$7.) &3""5#7/\' 8!:!! )'),E('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),E("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),E('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),E('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:! )'),E('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:! )"),E('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),E('$4""5!7/,#0)*4""5!7&&&#'),E('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),E('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),E('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),E('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),E("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),E('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),E('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),E(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),E('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),E('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),E('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),E('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),E('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),E('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),E('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),E('%$;j/�#*;j&&&#/"!&,)'),E('%$;j/�#*;j&&&#/"!&,)'),E(";k.) &;+.# &;-"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),E('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),E('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),E("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),E("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),E(";.# &;r"),E("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E(";M.# &;t"),E("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),E('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),E('%24""6475/,#;{/#$+")("\'#&\'#'),E("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),E(";*.) &;+.# &;-"),E(';+. &;-. &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E("$;~0#*;~&"),E(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),E(";.# &;"),E('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),E('$;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/#0*;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),E("$;y0#*;y&"),E('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),E('2Õ""6Õ7Ö'),E('2×""6×7Ø'),E('2Ù""6Ù7Ú'),E('2Û""6Û7Ü'),E('2Ý""6Ý7Þ'),E('2ß""6ß7à'),E('2á""6á7â'),E('2ã""6ã7ä'),E('2å""6å7æ'),E('2ç""6ç7è'),E('2é""6é7ê'),E("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),E("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%;/' 8!:ì!! )"),E("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),E("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),E("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),E("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),E("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),E("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),E("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),E(";.) &;.# &; "),E("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),E("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ø!! )"),E('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),E('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),E(";6.) &;T.# &;H"),E("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),E(";¥.# &; "),E('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:Č!! )"),E("%;©/& 8!:č! )"),E("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";«.# &;¬"),E('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),E('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),E(";6.# &;®"),E('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),E(";.# &;6"),E("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),E(";6.# &;H"),E("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),E("%;/' 8!:ğ!! )"),E('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),E('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),E(";¹.# &; "),E("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),E("%;/' 8!:Ħ!! )"),E("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),E(";¾"),E("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),E("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),E(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),E("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:Ĭ!! )"),E("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),E(";t.# &;w"),E("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:ı!! )"),E("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),E('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),E('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),E('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),E('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),E("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),E("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),E('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),E("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),E("%;/& 8!:Ő! )"),E('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),E("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),E("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),E("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),E('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),E(';1." &"'),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),E("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),E(";¹.# &; "),E("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),E("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),E("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),E("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),E("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),E("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),E("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),E('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),E('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),E('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),E('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),E(";¾"),E('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),E(";ô.# &; "),E('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),E('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),E("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),E("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),E("$;%0#*;%&"),E("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),E('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),E('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),E(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),E('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),E('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),E('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),E("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),E("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),E("%;ă/,#;ă/#$+\")(\"'#&'#"),E("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),E("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),E('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),E(";.# &;L"),E("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),E("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,d=0;const l=[{line:1,column:1}];let h,u=0,p=[],g=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');s=r[t.startRule]}function f(){return e.substring(d,c)}function m(){return b(d,c)}function v(e,t){return{type:"literal",text:e,ignoreCase:t}}function y(e,t,i){return{type:"class",parts:e,inverted:t,ignoreCase:i}}function S(t){let i,n=l[t];if(n)return n;for(i=t-1;!l[i];)i--;for(n=l[i],n={line:n.line,column:n.column};i<t;)10===e.charCodeAt(i)?(n.line++,n.column=1):n.column++,i++;return l[t]=n,n}function b(e,t){const i=S(e),r=S(t);return{source:n,start:{offset:e,line:i.line,column:i.column},end:{offset:t,line:r.line,column:r.column}}}function w(e){c<u||(c>u&&(u=c,p=[]),p.push(e))}function E(e){return e.split("").map((e=>e.charCodeAt(0)-32))}if(t.data={},h=function t(n){const r=o[n];let s=0;const l=[];let h=r.length;const u=[],p=[];let f;for(;;){for(;s<h;)switch(r[s]){case 0:p.push(a[r[s+1]]),s+=2;break;case 1:p.push(void 0),s++;break;case 2:p.push(null),s++;break;case 3:p.push(i),s++;break;case 4:p.push([]),s++;break;case 5:p.push(c),s++;break;case 6:p.pop(),s++;break;case 7:c=p.pop(),s++;break;case 8:p.length-=r[s+1],s+=2;break;case 9:p.splice(-2,1),s++;break;case 10:p[p.length-2].push(p.pop()),s++;break;case 11:p.push(p.splice(p.length-r[s+1],r[s+1])),s+=2;break;case 12:p.push(e.substring(p.pop(),c)),s++;break;case 13:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 14:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]===i?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 15:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]!==i?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 16:p[p.length-1]!==i?(u.push(h),l.push(s),h=s+2+r[s+1],s+=2):s+=2+r[s+1];break;case 17:u.push(h),l.push(s+3+r[s+1]+r[s+2]),e.length>c?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 18:u.push(h),l.push(s+4+r[s+2]+r[s+3]),e.substr(c,a[r[s+1]].length)===a[r[s+1]]?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 19:u.push(h),l.push(s+4+r[s+2]+r[s+3]),e.substr(c,a[r[s+1]].length).toLowerCase()===a[r[s+1]]?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 20:u.push(h),l.push(s+4+r[s+2]+r[s+3]),a[r[s+1]].test(e.charAt(c))?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 21:p.push(e.substr(c,r[s+1])),c+=r[s+1],s+=2;break;case 22:p.push(a[r[s+1]]),c+=a[r[s+1]].length,s+=2;break;case 23:p.push(i),0===g&&w(a[r[s+1]]),s+=2;break;case 24:d=p[p.length-1-r[s+1]],s+=2;break;case 25:d=c,s++;break;case 26:f=r.slice(s+4,s+4+r[s+3]).map((function(e){return p[p.length-1-e]})),p.splice(p.length-r[s+2],r[s+2],a[r[s+1]].apply(null,f)),s+=4+r[s+3];break;case 27:p.push(t(r[s+1])),s+=2;break;case 28:g++,s++;break;case 29:g--,s++;break;default:throw new Error("Invalid opcode: "+r[s]+".")}if(!(u.length>0))break;h=u.pop(),s=l.pop()}return p[0]}(s),h!==i&&c===e.length)return h;throw h!==i&&c<e.length&&w({type:"end"}),C=p,$=u<e.length?e.charAt(u):null,T=u<e.length?b(u,u+1):b(u,u),new jn(jn.buildMessage(C,$),C,$,T);var C,$,T};var Un;!function(e){e.parse=function(e,t){const i={startRule:t};try{Bn(e,i)}catch(e){i.data=-1}return i.data},e.nameAddrHeaderParse=function(t){const i=e.parse(t,"Name_Addr_Header");return-1!==i?i:void 0},e.URIParse=function(t){const i=e.parse(t,"SIP_URI");return-1!==i?i:void 0}}(Un=Un||(Un={}));const Vn={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function qn(e,t=32){let i="";for(let n=0;n<e;n++){i+=Math.floor(Math.random()*t).toString(t)}return i}function Gn(e){return Vn[e]||""}function Kn(){return qn(10)}function Wn(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),n=i.length;let r="";for(let e=0;e<n;e++)0!==e&&(r+="-"),r+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[r]&&(r=t[r]),r}function zn(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Yn{constructor(){this.headers={}}addHeader(e,t){const i={raw:t};e=Wn(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[Wn(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Wn(e)],i=[];if(!t)return[];for(const e of t)i.push(e.raw);return i}hasHeader(e){return!!this.headers[Wn(e)]}parseHeader(e,t=0){if(e=Wn(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const i=this.headers[e][t],n=i.raw;if(i.parsed)return i.parsed;const r=Un.parse(n,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(i.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Wn(e)]=[{raw:t}]}toString(){return this.data}}class Jn extends Yn{constructor(){super()}}class Zn extends Yn{constructor(){super()}}class Xn{constructor(e,t,i,n,r,s,a){this.headers={},this.extraHeaders=[],this.options=Xn.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),s&&s.length&&(this.extraHeaders=s.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Kn(),this.from=Xn.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=n.clone(),this.toTag=this.options.toTag,this.to=Xn.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+qn(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,i){const n={};return i&&(n.tag=i),new Fn(e,t,n)}getHeader(e){const t=this.headers[Wn(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[Wn(e)];if(i)for(const e of i)t.push(e);else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)i.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[Wn(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[Wn(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const i of this.headers[t])e+=t+": "+i+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+zn(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+zn(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Qn(e){return"application/sdp"===e?"session":"render"}function er(e){const t="string"==typeof e?e:e.body,i="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Qn(i),contentType:i,content:t}}function tr(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function ir(e){let t,i,n;if(e instanceof Jn&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,i=e.parseHeader("Content-Type"),n=e.body}if(e instanceof Zn&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,i=e.parseHeader("Content-Type"),n=e.body}if(e instanceof Xn&&e.body)if(t=e.getHeader("Content-Disposition"),i=e.getHeader("Content-Type"),"string"==typeof e.body){if(!i)throw new Error("Header content type header does not equal body content type.");n=e.body}else{if(i&&i!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");i=e.body.contentType,n=e.body.body}if(tr(e)&&(t=e.contentDisposition,i=e.contentType,n=e.content),n){if(i&&!t&&(t=Qn(i)),!t)throw new Error("Content disposition undefined.");if(!i)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:i,content:n}}}var nr,rr;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(nr=nr||(nr={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(rr=rr||(rr={}));const sr=500,ar=5e3,or={T1:sr,T2:4e3,T4:ar,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class cr extends $n{constructor(e){super(e||"Transaction state error.")}}var dr;!function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(dr=dr||(dr={}));const lr=[dr.ACK,dr.BYE,dr.CANCEL,dr.INFO,dr.INVITE,dr.MESSAGE,dr.NOTIFY,dr.OPTIONS,dr.PRACK,dr.REFER,dr.REGISTER,dr.SUBSCRIBE];class hr{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class ur{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class pr{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Fn))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const i=((e=e||{}).extraHeaders||[]).slice(),n=this.replaces;n&&i.push("Replaces: "+decodeURIComponent(n));const r=this.referredBy;return r&&i.push("Referred-By: "+r),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}class gr{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=mi.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Nn,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case mi.Initial:case mi.Establishing:break;case mi.Established:return new Promise((e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})}));case mi.Terminating:case mi.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case mi.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case mi.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case mi.Established:{const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._bye(t,i)}case mi.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case mi.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==mi.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._info(t,i)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==mi.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new _n("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const i=ir(t.message);if(!i)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(mi.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(i,n).then((e=>{t.ack({body:e})})).catch((e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===mi.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(mi.Terminated))})).then((()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))}else{const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(i,n).then((()=>{t.ack()})).catch((e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==mi.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(mi.Terminated)):t.ack()})).then((()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch((e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==mi.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated)}})).then((()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)}))},onTrying:e=>{}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+lr.toString()),i.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,i))}const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(n).then((e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=e,this.dialog.invite(t,i)})).catch((e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e}))}message(e={}){if(this.state!==mi.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._message(t,i)}refer(e,t={}){if(this.state!==mi.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof gr&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,n=this.copyRequestOptions(t.requestOptions);return n.extraHeaders=n.extraHeaders?n.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,i,n)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const i=this.dialog;switch(i.sessionState){case nr.Initial:case nr.Early:throw new Error(`Invalid dialog state ${i.sessionState}`);case nr.AckWait:return this.stateTransition(mi.Terminating),new Promise((n=>{i.delegate={onAck:()=>{const r=i.bye(e,t);return this.stateTransition(mi.Terminated),n(r),Promise.resolve()},onAckTimeout:()=>{const r=i.bye(e,t);this.stateTransition(mi.Terminated),n(r)}}}));case nr.Confirmed:{const n=i.bye(e,t);return this.stateTransition(mi.Terminated),Promise.resolve(n)}case nr.Terminated:throw new Error(`Invalid dialog state ${i.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const n=[];t&&n.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:n})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==mi.Established&&this.state!==mi.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new An(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case rr.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.Stable:{const n=ir(e.message);return n?"render"===n.contentDisposition?(this._renderbody=n.content,this._rendertype=n.contentType,Promise.resolve()):"session"!==n.contentDisposition?Promise.resolve():this.setAnswer(n,i).catch((e=>{this.logger.error(e.message);const i=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:i}),this.stateTransition(mi.Terminated)})):Promise.resolve()}case rr.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===mi.Established){if(this.delegate&&this.delegate.onBye){const t=new Pn(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(mi.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===mi.Established)if(this.delegate&&this.delegate.onInfo){const t=new kn(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==mi.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=Un.nameAddrHeaderParse(t)}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then((i=>{const n=e.accept({statusCode:200,extraHeaders:t,body:i});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,200)})).catch((t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==rr.Stable)this.rollbackOffer().then((()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)})).catch((t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const i=e.reject({statusCode:488});if(this.state!==mi.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,488)}));else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}}))}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===mi.Established)if(this.delegate&&this.delegate.onMessage){const t=new hr(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===mi.Established)if(this.onNotify){const t=new ur(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new ur(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===mi.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==mi.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new pr(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then((()=>t.makeInviter(this._referralInviterOptions).invite())).catch((e=>{this.logger.error(e.message)})))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const i=ir(e.message);return i&&"session"===i.contentDisposition?this.setOfferAndGetAnswer(i,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case rr.Initial:return this.getOffer(e);case rr.HaveLocalOffer:return Promise.resolve(void 0);case rr.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case rr.Stable:return this.state!==mi.Established?Promise.resolve(void 0):this.getOffer(e);case rr.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(i,n).then((e=>er(e))).catch((e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch((e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const i=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Tn)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,n,r).catch((e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const i=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Tn)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,n,r).then((()=>i.getDescription(n,r))).then((e=>er(e))).catch((e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case mi.Initial:e!==mi.Establishing&&e!==mi.Established&&e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Establishing:e!==mi.Established&&e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Established:e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Terminating:e!==mi.Terminated&&t();break;case mi.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===mi.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const i=e;let n=Gn(e);return!n&&t&&(n=t),"SIP;cause="+i+';text="'+n+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof Mn)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,n=e.dialog.remoteTarget.toString(),r=e.dialog.callId,s=e.dialog.remoteTag,a=e.dialog.localTag;t=`"${i}" <${n}?Replaces=${encodeURIComponent(`${r};to-tag=${s};from-tag=${a}`)}>`}return t}}var fr;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(fr=fr||(fr={}));const mr={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class vr extends gr{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const i=this.incomingInviteRequest.message,n=i.getHeader("require");n&&n.toLowerCase().includes("100rel")&&(this.rel100="required");const r=i.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),i.toTag=t.toTag,"string"!=typeof i.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout((()=>{t.reject({statusCode:480}),this.stateTransition(mi.Terminated)}),this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),i.hasHeader("expires")){const e=1e3*Number(i.getHeader("expires")||0);this.expiresTimer=setTimeout((()=>{this.state===mi.Initial&&(t.reject({statusCode:487}),this.stateTransition(mi.Terminated))}),e)}const s=this.request.getHeader("P-Asserted-Identity");s&&(this._assertedIdentity=Un.nameAddrHeaderParse(s)),this._contact=this.userAgent.contact.toString();const a=i.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=i.body,this._rendertype=i.getHeader("Content-Type")),this._id=i.callId+i.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case mi.Initial:case mi.Establishing:return this.reject().then((()=>super.dispose()));case mi.Established:case mi.Terminating:case mi.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==mi.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(mi.Establishing),this.sendAccept(e).then((({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(mi.Established),this._replacee&&this._replacee._bye()})).catch((e=>this.handleResponseError(e)))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==mi.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then((()=>{})).catch((e=>this.handleResponseError(e))):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===fr.Required?this.sendProgressReliableWaitForPrack(e).then((()=>{})).catch((e=>this.handleResponseError(e))):this.sendProgress(e).then((()=>{})).catch((e=>this.handleResponseError(e)))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==mi.Initial&&this.state!==mi.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:Gn(t),n=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?er(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:i,extraHeaders:n,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:i,extraHeaders:n,body:r}),this.stateTransition(mi.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===mi.Initial||this.state===mi.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new Dn(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(mi.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=ir(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case rr.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case rr.Stable:return this.setAnswer(t,i).then((()=>{}));case rr.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case rr.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case rr.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof Tn?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof xn?this.logger.error("A session description handler occurred while sending response"):e instanceof In?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof cr&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===mi.Initial||this.state===mi.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(mi.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(mi.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then((()=>clearTimeout(this.userNoAnswerTimer))).then((()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t))).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i}))):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i}))))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),r=e.body?er(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:n,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:e}))).then((e=>(this._dialog=e.session,e)))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let s;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise(((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>(s=e,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:s})))).then((t=>{let o,c;this._dialog=t.session,t.session.delegate={onPrack:i=>{o=i,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(o).then((i=>{try{c=o.accept({statusCode:200,body:i}),this.prackArrived(),e({prackRequest:o,prackResponse:c,progressResponse:t})}catch(e){a(e)}})).catch((e=>a(e))))}};const d=setTimeout((()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then((()=>a(new In))).catch((e=>a(e))))}),64*or.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:s})}catch(e){return this.waitingForPrack=!1,void a(e)}u=setTimeout(l,h*=2)};let h=or.T1,u=setTimeout(l,h)})).catch((e=>{this.waitingForPrack=!1,a(e)}))}))}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t})),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new In),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class yr extends gr{constructor(e,t,i={}){super(e,i),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:this.earlyMedia,this.fromTag=Kn(),this.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},i);n.params=Object.assign({},i.params);const r=i.anonymous||!1,s=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let a=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(a="string"==typeof n.params.fromUri?Un.URIParse(n.params.fromUri):n.params.fromUri),!a)throw new TypeError("Invalid from URI: "+n.params.fromUri);let o=t;if(n.params.toUri&&(o="string"==typeof n.params.toUri?Un.URIParse(n.params.toUri):n.params.toUri),!o)throw new TypeError("Invalid to URI: "+n.params.toUri);const c=Object.assign({},n.params);c.fromTag=this.fromTag;const d=(n.extraHeaders||[]).slice();r&&e.configuration.uri&&(d.push("P-Preferred-Identity: "+e.configuration.uri.toString()),d.push("Privacy: id")),d.push("Contact: "+s),d.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===fr.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===fr.Required&&d.push("Require: replaces"),n.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(dr.INVITE,t,a,o,c,d,undefined),this._contact=s,this._referralInviterOptions=n,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case mi.Initial:case mi.Establishing:return this.cancel().then((()=>super.dispose()));case mi.Established:case mi.Terminating:case mi.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==mi.Initial&&this.state!==mi.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(mi.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Gn(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(mi.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==mi.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(mi.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then((t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(mi.Establishing),this.sendInvite(e)))).catch((e=>{throw this.logger.log(e.message),this.state!==mi.Terminated&&this.stateTransition(mi.Terminated),e}))}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(mi.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then((()=>{this.disposeEarlyMedia()})).catch((()=>{this.disposeEarlyMedia()})).then((()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch((()=>{this.disposeEarlyMedia()})).then((()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)})))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach((e=>{e.close()})),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof gr))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==mi.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,i=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Un.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),i.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=i,i.signalingState){case rr.Initial:case rr.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(mi.Terminated),Promise.reject(new Error("Bad Media Description"));case rr.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then((t=>{e.ack({body:t}),this.stateTransition(mi.Established)})).catch((t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(mi.Terminated),t}))}case rr.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(mi.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(mi.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(mi.Established),Promise.resolve()}const t=i.answer;if(!t)throw new Error("Answer is undefined.");const n={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,n).then((()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(mi.Established)})).catch((t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(mi.Terminated),t}))}case rr.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==mi.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const i=e.message,n=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Un.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));const r=i.getHeader("require"),s=i.getHeader("rseq"),a=!!(r&&r.includes("100rel")&&s?Number(s):void 0),o=[];switch(a&&o.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),n.signalingState){case rr.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:o})),Promise.resolve();case rr.HaveLocalOffer:return a&&e.prack({extraHeaders:o}),Promise.resolve();case rr.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(n.id,r),r.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then((()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers))).then((t=>{const i={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:o,body:i})})).catch((e=>{throw this.stateTransition(mi.Terminated),e}))}case rr.Stable:if(a&&e.prack({extraHeaders:o}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=n;const e=n.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch((e=>{throw this.stateTransition(mi.Terminated),e}))}return Promise.resolve();case rr.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===mi.Establishing||this.state===mi.Terminating?this.stateTransition(mi.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===mi.Establishing||this.state===mi.Terminating?this.stateTransition(mi.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===mi.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class Sr{constructor(e,t,i,n="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let s=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(s="string"==typeof r.params.fromUri?Un.URIParse(r.params.fromUri):r.params.fromUri),!s)throw new TypeError("Invalid from URI: "+r.params.fromUri);let a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?Un.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);const o=r.params?Object.assign({},r.params):{},c=(r.extraHeaders||[]).slice(),d={contentDisposition:"render",contentType:n,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(dr.MESSAGE,t,s,a,o,c,d),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var br,wr,Er,Cr,$r,Tr,_r;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(br=br||(br={}));class xr{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=br.Initial,this._waiting=!1,this._stateEventEmitter=new Nn,this._waitingEventEmitter=new Nn,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},xr.defaultOptions()),{registrar:i}),xr.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===Un.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const n=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,s=this.options.params&&this.options.params.toUri||e.configuration.uri,a=this.options.params||{},o=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(dr.REGISTER,n,r,s,a,o,void 0),this.expires=this.options.expires||xr.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||xr.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))}))),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:xr.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Mn("sip","anonymous","anonymous.invalid"),refreshFrequency:xr.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t)),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise((e=>{const t=()=>{if(!this.waiting&&this._state===br.Registered)return this.stateChange.addListener((()=>{this.terminated(),e()}),{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener((()=>{t()}),{once:!0}):t()})))}register(e={}){if(this.state===br.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new _n("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let i;t.message.hasHeader("expires")&&(i=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let n,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(n=t.message.parseHeader("contact",r),!n)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Hn(n.uri,this.userAgent.contact.pubGruu)){i=Number(n.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(n.uri.user===this.userAgent.contact.uri.user){i=Number(n.getParam("expires"));break}}else if(Hn(n.uri,this.userAgent.contact.uri)){i=Number(n.getParam("expires"));break}n=void 0}if(void 0===n)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===i)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(n.hasParam("temp-gruu")){const e=n.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=Un.URIParse(e.replace(/"/g,"")))}if(n.hasParam("pub-gruu")){const e=n.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Un.URIParse(e.replace(/"/g,"")))}this.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let i=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(i=Number.parseInt(e,void 0))}this._retryAfter=isNaN(i)?void 0:i,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}unregister(e={}){if(this.state===br.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==br.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new _n("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===br.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((e=>{t+=";"+e})),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout((()=>{this.registrationTimer=void 0,this.register()}),this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout((()=>{this.logger.warn("Registration expired"),this.unregistered()}),1e3*e),this._state!==br.Registered&&this.stateTransition(br.Registered)}unregistered(){this.clearTimers(),this._state!==br.Unregistered&&this.stateTransition(br.Unregistered)}terminated(){this.clearTimers(),this._state!==br.Terminated&&this.stateTransition(br.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case br.Initial:e!==br.Registered&&e!==br.Unregistered&&e!==br.Terminated&&t();break;case br.Registered:e!==br.Unregistered&&e!==br.Terminated&&t();break;case br.Unregistered:e!==br.Registered&&e!==br.Terminated&&t();break;case br.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===br.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===br.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}xr.defaultExpires=600,xr.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(wr=wr||(wr={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(Er=Er||(Er={})),function(e){e.Started="Started",e.Stopped="Stopped"}(Cr=Cr||(Cr={}));class Ir{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=Ir.hexChars,i=Ir.hexOut;let n,r,s,a;for(a=0;a<4;a+=1)for(r=8*a,n=e[a],s=0;s<8;s+=2)i[r+1+s]=t.charAt(15&n),n>>>=4,i[r+0+s]=t.charAt(15&n),n>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],n=e[1],r=e[2],s=e[3];i+=(n&r|~n&s)+t[0]-680876936|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[1]-389564586|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[2]+606105819|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[3]-1044525330|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[4]-176418897|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[5]+1200080426|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[6]-1473231341|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[7]-45705983|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[8]+1770035416|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[9]-1958414417|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[10]-42063|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[11]-1990404162|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[12]+1804603682|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[13]-40341101|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[14]-1502002290|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[15]+1236535329|0,n=(n<<22|n>>>10)+r|0,i+=(n&s|r&~s)+t[1]-165796510|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[6]-1069501632|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[11]+643717713|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[0]-373897302|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[5]-701558691|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[10]+38016083|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[15]-660478335|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[4]-405537848|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[9]+568446438|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[14]-1019803690|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[3]-187363961|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[8]+1163531501|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[13]-1444681467|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[2]-51403784|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[7]+1735328473|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[12]-1926607734|0,n=(n<<20|n>>>12)+r|0,i+=(n^r^s)+t[5]-378558|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[8]-2022574463|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[11]+1839030562|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[14]-35309556|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[1]-1530992060|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[4]+1272893353|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[7]-155497632|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[10]-1094730640|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[13]+681279174|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[0]-358537222|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[3]-722521979|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[6]+76029189|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[9]-640364487|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[12]-421815835|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[15]+530742520|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[2]-995338651|0,n=(n<<23|n>>>9)+r|0,i+=(r^(n|~s))+t[0]-198630844|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[7]+1126891415|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[14]-1416354905|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[5]-57434055|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[12]+1700485571|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[3]-1894986606|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[10]-1051523|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[1]-2054922799|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[8]+1873313359|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[15]-30611744|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[6]-1560198380|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[13]+1309151649|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[4]-145523070|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[11]-1120210379|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[2]+718787259|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[9]-343485551|0,n=(n<<21|n>>>11)+r|0,e[0]=i+e[0]|0,e[1]=n+e[1]|0,e[2]=r+e[2]|0,e[3]=s+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Ir.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let n,r,s=this._bufferLength;for(r=0;r<e.length;r+=1){if(n=e.charCodeAt(r),n<128)t[s++]=n;else if(n<2048)t[s++]=192+(n>>>6),t[s++]=63&n|128;else if(n<55296||n>56319)t[s++]=224+(n>>>12),t[s++]=n>>>6&63|128,t[s++]=63&n|128;else{if(n=1024*(n-55296)+(e.charCodeAt(++r)-56320)+65536,n>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[s++]=240+(n>>>18),t[s++]=n>>>12&63|128,t[s++]=n>>>6&63|128,t[s++]=63&n|128}s>=64&&(this._dataLength+=64,Ir._md5cycle(this._state,i),s-=64,i[0]=i[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let n,r=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-r);n--;)t[r++]=e.charCodeAt(s++);if(r<64)break;this._dataLength+=64,Ir._md5cycle(this._state,i),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let n,r=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-r);n--;)t[r++]=e[s++];if(r<64)break;this._dataLength+=64,Ir._md5cycle(this._state,i),r=0}return this._bufferLength=r,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,i=e.state,n=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,i=this._buffer8,n=this._buffer32,r=1+(t>>2);let s;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,n.set(Ir.buffer32Identity.subarray(r),r),t>55&&(Ir._md5cycle(this._state,n),n.set(Ir.buffer32Identity)),s=8*this._dataLength,s<=4294967295)n[14]=s;else{const e=s.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),i=parseInt(e[1],16)||0;n[14]=t,n[15]=i}return Ir._md5cycle(this._state,n),e?this._state:Ir._hex(this._state)}}function Rr(e){return Ir.hashStr(e)}Ir.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Ir.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ir.hexChars="0123456789abcdef",Ir.hexOut=[],Ir.onePassHasher=new Ir,"5d41402abc4b2a76b9719d911017c592"!==Ir.hashStr("hello")&&console.error("Md5 self test failed.");class Ar{constructor(e,t,i,n){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=n,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=qn(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,i;t=this.ha1,""!==t&&void 0!==t||(t=Rr(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(i=Rr(this.method+":"+this.uri),this.response=Rr(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):"auth-int"===this.qop?(i=Rr(this.method+":"+this.uri+":"+Rr(e||"")),this.response=Rr(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):void 0===this.qop&&(i=Rr(this.method+":"+this.uri),this.response=Rr(t+":"+this.nonce+":"+i))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}($r=$r||($r={}));class Pr{constructor(e,t,i){this.logger=e,this.category=t,this.label=i}error(e){this.genericLog($r.error,e)}warn(e){this.genericLog($r.warn,e)}log(e){this.genericLog($r.log,e)}debug(e){this.genericLog($r.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class Dr{constructor(){this.builtinEnabled=!0,this._level=$r.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:$r.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new Pr(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Pr(this,e);return this.loggers[e]=t,t}}genericLog(e,t,i,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,n),this.connector&&this.connector($r[e],t,i,n)}print(e,t,i,n){if("string"==typeof n){const e=[new Date,t];i&&e.push(i),n=e.concat(n).join(" | ")}switch(e){case $r.error:console.error(n);break;case $r.warn:console.warn(n);break;case $r.log:console.log(n);break;case $r.debug:console.debug(n)}}}function Nr(e,t){const i="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const n=t.reasonPhrase?t.reasonPhrase:Gn(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+n+i;t.statusCode>=100&&t.statusCode,t.statusCode;const s="From: "+e.getHeader("From")+i,a="Call-ID: "+e.callId+i,o="CSeq: "+e.cseq+" "+e.method+i,c=e.getHeaders("via").reduce(((e,t)=>e+"Via: "+t+i),"");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Kn()),d+=";tag="+e}d+=i;let l="";t.supported&&(l="Supported: "+t.supported.join(", ")+i);let h="";t.userAgent&&(h="User-Agent: "+t.userAgent+i);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce(((e,t)=>e+t.trim()+i),"")),r+=c,r+=s,r+=d,r+=o,r+=a,r+=l,r+=h,r+=u,t.body?(r+="Content-Type: "+t.body.contentType+i,r+="Content-Length: "+zn(t.body.content)+i+i,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let i=t,n=0,r=0;if(e.substring(i,i+2).match(/(^\r\n)/))return-2;for(;0===n;){if(r=e.indexOf("\r\n",i),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?i=r+2:n=r}return n}function i(e,t,i,n){const r=t.indexOf(":",i),s=t.substring(i,r).trim(),a=t.substring(r+1,n).trim();let o;switch(s.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(o=e.parseHeader("Via"),o&&(e.via=o,e.viaBranch=o.branch)):o=0;break;case"from":case"f":e.setHeader("from",a),o=e.parseHeader("from"),o&&(e.from=o,e.fromTag=o.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),o=e.parseHeader("to"),o&&(e.to=o,e.toTag=o.getParam("tag"));break;case"record-route":if(o=Un.parse(a,"Record_Route"),-1===o){o=void 0;break}if(!(o instanceof Array)){o=void 0;break}o.forEach((t=>{e.addHeader("record-route",a.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed}));break;case"call-id":case"i":e.setHeader("call-id",a),o=e.parseHeader("call-id"),o&&(e.callId=a);break;case"contact":case"m":if(o=Un.parse(a,"Contact"),-1===o){o=void 0;break}if(!(o instanceof Array)){o=void 0;break}o.forEach((t=>{e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed}));break;case"content-length":case"l":e.setHeader("content-length",a),o=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),o=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),o=e.parseHeader("cseq"),o&&(e.cseq=o.value),e instanceof Zn&&(e.method=o.method);break;case"max-forwards":e.setHeader("max-forwards",a),o=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),o=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),o=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),o=e.parseHeader("refer-to"),o&&(e.referTo=o);break;default:e.addHeader(s.toLowerCase(),a),o=0}return void 0!==o||{error:"error parsing header '"+s+"'"}}e.getHeader=t,e.parseHeader=i,e.parseMessage=function(e,n){let r=0,s=e.indexOf("\r\n");if(-1===s)return void n.warn("no CRLF found, not a SIP message, discarded");const a=e.substring(0,s),o=Un.parse(a,"Request_Response");let c,d;if(-1!==o){for(o.status_code?(c=new Zn,c.statusCode=o.status_code,c.reasonPhrase=o.reason_phrase):(c=new Jn,c.method=o.method,c.ruri=o.uri),c.data=e,r=s+2;;){if(s=t(e,r),-2===s){d=r+2;break}if(-1===s)return void n.error("malformed message");const a=i(c,e,r,s);if(a&&!0!==a)return void n.error(a.error);r=s+2}return c.hasHeader("content-length")?c.body=e.substr(d,Number(c.getHeader("content-length"))):c.body=e.substring(d),c}n.warn('error parsing first line of SIP message: "'+a+'"')}}(Tr=Tr||(Tr={}));class kr extends $n{constructor(e){super(e||"Unspecified transport error.")}}class Or{constructor(e,t,i,n,r){this._transport=e,this._user=t,this._id=i,this._state=n,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,i),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const i=()=>{this.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach((e=>e()))}removeStateChangeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch((e=>{if(e instanceof kr)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new kr(e.message):new kr,this.onTransportError(t),t}))}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Fr extends Or{constructor(e,t,i,n,r){super(t,i,e.viaBranch,n,r),this._request=e,this.user=i}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(_r=_r||(_r={}));class Mr extends Fr{constructor(e,t,i){super(e,t,i,_r.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case _r.Proceeding:if(e.method===dr.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case _r.Accepted:if(e.method===dr.INVITE)return;break;case _r.Completed:if(e.method===dr.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===dr.ACK)return void this.stateTransition(_r.Confirmed);break;case _r.Confirmed:case _r.Terminated:if(e.method===dr.INVITE||e.method===dr.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case _r.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(_r.Accepted),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send non-2xx final response.")}));break;case _r.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));break;case _r.Completed:case _r.Confirmed:case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}retransmitAcceptedResponse(){this.state===_r.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}))}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Proceeding:t();break;case _r.Accepted:case _r.Completed:this.state!==_r.Proceeding&&t();break;case _r.Confirmed:this.state!==_r.Completed&&t();break;case _r.Terminated:this.state!==_r.Accepted&&this.state!==_r.Completed&&this.state!==_r.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===_r.Accepted&&(this.L=setTimeout((()=>this.timerL()),or.TIMER_L)),e===_r.Completed&&(this.H=setTimeout((()=>this.timerH()),or.TIMER_H)),e===_r.Confirmed&&(this.I=setTimeout((()=>this.timerI()),or.TIMER_I)),e===_r.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}))}),or.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===_r.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(_r.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(_r.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===_r.Accepted&&this.stateTransition(_r.Terminated)}}class Hr extends Or{constructor(e,t,i,n,r){super(t,i,Hr.makeId(e),n,r),this._request=e,this.user=i,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class Lr extends Hr{constructor(e,t,i){super(e,t,i,_r.Trying,"sip.transaction.nict"),this.F=setTimeout((()=>this.timerF()),or.TIMER_F),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send initial outgoing request.")}))}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case _r.Trying:if(t>=100&&t<=199)return this.stateTransition(_r.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(_r.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(_r.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Completed:case _r.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Trying:i();break;case _r.Proceeding:this.state!==_r.Trying&&i();break;case _r.Completed:this.state!==_r.Trying&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Trying&&this.state!==_r.Proceeding&&this.state!==_r.Completed&&(t||i());break;default:i()}e===_r.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((()=>this.timerK()),or.TIMER_K)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==_r.Trying&&this.state!==_r.Proceeding||(this.onRequestTimeout(),this.stateTransition(_r.Terminated))}timerK(){this.state===_r.Completed&&this.stateTransition(_r.Terminated)}}class jr{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const i=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const r=n.uri,s=e.cseq,a=e.callId,o=e.fromTag,c=t.toTag;if(!a)throw new Error("Call id undefined.");if(!o)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const d=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+o+c,early:t.statusCode<200,callId:a,localTag:o,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:d,remoteURI:l,remoteTarget:r,routeSet:i,secure:!1}}static initialDialogStateForUserAgentServer(e,t,i=!1){const n=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,a=e.cseq,o=e.callId,c=t,d=e.fromTag,l=e.from.uri;return{id:o+c+d,early:i,callId:o,localTag:c,remoteTag:d,localSequenceNumber:undefined,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:n,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==dr.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const i=this.remoteURI,n=this.remoteTag,r=this.localURI,s=this.localTag,a=this.callId;let o;o=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,l=t&&t.extraHeaders,h=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,i,{callId:a,cseq:o,fromTag:s,toTag:n,routeSet:d},l,h)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===dr.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Br extends Hr{constructor(e,t,i){super(e,t,i,_r.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout((()=>this.timerB()),or.TIMER_B),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send initial outgoing request.")}))}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")}))}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case _r.Calling:if(t>=100&&t<=199)return this.stateTransition(_r.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(_r.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(_r.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(_r.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(_r.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch((e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case _r.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,i=this.request.callId,n=this.request.cseq,r=this.request.getHeader("from"),s=e.getHeader("to"),a=this.request.getHeader("via"),o=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;o&&(c+=`Route: ${o}\r\n`),c+=`Via: ${a}\r\n`,c+=`To: ${s}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${i}\r\n`,c+=`CSeq: ${n} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch((e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")}))}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Calling:i();break;case _r.Proceeding:this.state!==_r.Calling&&i();break;case _r.Accepted:case _r.Completed:this.state!==_r.Calling&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Calling&&this.state!==_r.Accepted&&this.state!==_r.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),_r.Proceeding,e===_r.Completed&&(this.D=setTimeout((()=>this.timerD()),or.TIMER_D)),e===_r.Accepted&&(this.M=setTimeout((()=>this.timerM()),or.TIMER_M)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===_r.Calling&&(this.onRequestTimeout(),this.stateTransition(_r.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===_r.Completed&&this.stateTransition(_r.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===_r.Accepted&&this.stateTransition(_r.Terminated)}}class Ur{constructor(e,t,i,n){this.transactionConstructor=e,this.core=t,this.message=i,this.delegate=n,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const i=this.core.makeOutgoingRequestMessage(dr.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),e&&i.setHeader("Reason",e),this.transaction.state===_r.Proceeding?new Ur(Lr,this.core,i):this.transaction.addStateChangeListener((()=>{this.transaction&&this.transaction.state===_r.Proceeding&&new Ur(Lr,this.core,i)}),{once:!0}),i}authenticationGuard(e,t){const i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;let n,r;if(401===i?(n=e.parseHeader("www-authenticate"),r="authorization"):(n=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);let s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new Zn;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new Zn;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===_r.Terminated&&(this.core.userAgentClients.delete(i),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id+t.request.method;this.core.userAgentClients.set(i,this)}}class Vr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.BYE,i);super(Lr,e.userAgentCore,n,t),e.dispose()}}class qr extends Fr{constructor(e,t,i){super(e,t,i,_r.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case _r.Trying:break;case _r.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case _r.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of final response.")}));break;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case _r.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(_r.Proceeding),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case _r.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case _r.Completed:return;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Trying:i();break;case _r.Proceeding:this.state!==_r.Trying&&i();break;case _r.Completed:this.state!==_r.Trying&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Proceeding&&this.state!==_r.Completed&&(t||i());break;default:i()}e===_r.Completed&&(this.J=setTimeout((()=>this.timerJ()),or.TIMER_J)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===_r.Completed&&this.stateTransition(_r.Terminated)}}class Gr{constructor(e,t,i,n){this.transactionConstructor=e,this.core=t,this.message=i,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=i.toTag?i.toTag:Kn(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new cr(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new cr(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new cr(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const i=t.statusCode;if(i<300||i>399)throw new TypeError(`Invalid statusCode: ${i}`);const n=new Array;e.forEach((e=>n.push(`Contact: ${e.toString()}`))),t.extraHeaders=(t.extraHeaders||[]).concat(n);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new cr(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new cr(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding||this.transaction.state===_r.Accepted;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=Nr(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===_r.Terminated&&(this.core.userAgentServers.delete(i),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id;this.core.userAgentServers.set(t.id,this)}}class Kr extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i)}}class Wr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.INFO,i);super(Lr,e.userAgentCore,n,t)}}class zr extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i)}}class Yr extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class Jr extends Gr{constructor(e,t,i){super(qr,e,t,i)}}class Zr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.NOTIFY,i);super(Lr,e.userAgentCore,n,t)}}class Xr extends Gr{constructor(e,t,i){const n=void 0!==e.userAgentCore?e.userAgentCore:e;super(qr,n,t,i)}}class Qr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.PRACK,i);super(Lr,e.userAgentCore,n,t),e.signalingStateTransition(n)}}class es extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class ts extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.INVITE,i);super(Br,e.userAgentCore,n,t),this.delegate=t,e.signalingStateTransition(n),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class is extends Gr{constructor(e,t,i){super(Mr,e.userAgentCore,t,i),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map((e=>`Record-Route: ${e}`)));const t=super.accept(e),i=this.dialog,n=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),n}progress(e={statusCode:180}){const t=super.progress(e),i=this.dialog,n=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class ns extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.REFER,i);super(Lr,e.userAgentCore,n,t)}}class rs extends Gr{constructor(e,t,i){const n=void 0!==e.userAgentCore?e.userAgentCore:e;super(qr,n,t,i)}}class ss extends jr{constructor(e,t,i,n){super(t,i),this.initialTransaction=e,this._signalingState=rr.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=n,e instanceof Mr&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=rr.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?nr.Early:this.ackWait?nr.AckWait:this._signalingState===rr.Closed?nr.Terminated:nr.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Br))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const i=this.createOutgoingRequestMessage(dr.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(i),this.signalingStateTransition(i),{message:i}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Mr){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==_r.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new Vr(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Wr(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new ts(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const i=this.createOutgoingRequestMessage(dr.MESSAGE,t);return new Yr(this.core,i,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Zr(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Qr(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new ns(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==dr.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===dr.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},i=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.ackWait&&this.signalingState!==rr.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:i});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===dr.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case dr.BYE:{const t=new Kr(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case dr.INFO:{const t=new zr(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case dr.INVITE:{const t=new is(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case dr.MESSAGE:{const t=new Jr(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case dr.NOTIFY:{const t=new Xr(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case dr.PRACK:{const t=new es(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case dr.REFER:{const t=new rs(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Br)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then((()=>this.ackProcessing=!1)).catch((()=>this.ackProcessing=!1)))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),i=e.getHeader("rseq"),n=t&&t.includes("100rel")&&i?Number(i):void 0;if(n){if(this.rseq&&this.rseq+1!==n)return!1;this.rseq=this.rseq?this.rseq+1:n}}return!0}signalingStateRollback(){this._signalingState!==rr.HaveLocalOffer&&this.signalingState!==rr.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=rr.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=ir(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===rr.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Jn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.HaveRemoteOffer:case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Zn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.HaveRemoteOffer:case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Xn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:break;case rr.HaveRemoteOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(tr(e))switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:break;case rr.HaveRemoteOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Mr){const e=this.initialTransaction;let t=or.T1;const i=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,or.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const n=()=>{e.state===_r.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(n)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Mr){const e=this.reinviteUserAgentServer.transaction;let t=or.T1;const i=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,or.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const n=()=>{e.state===_r.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(n)}}}class as extends Ur{constructor(e,t,i){super(Br,e,t,i),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=i}dispose(){this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===_r.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=jr.initialDialogStateForUserAgentClient(this.message,e);let i=this.earlyDialogs.get(t.id);if(!i){const e=this.transaction;if(!(e instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");i=new ss(e,this.core,t),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");i.signalingState!==rr.Initial&&i.signalingState!==rr.HaveLocalOffer||i.signalingStateTransition(e);const n=i;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:n,prack:e=>n.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=jr.initialDialogStateForUserAgentClient(this.message,e);let i=this.confirmedDialogs.get(t.id);if(i){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Br))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(i=this.earlyDialogs.get(t.id),i)i.confirm(),i.recomputeRouteSet(e),this.earlyDialogs.delete(i.id),this.confirmedDialogs.set(i.id,i);else{const e=this.transaction;if(!(e instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");i=new ss(e,this.core,t),this.confirmedDialogs.set(i.id,i)}i.signalingState!==rr.Initial&&i.signalingState!==rr.HaveLocalOffer||i.signalingStateTransition(e);const n=i;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:n,ack:e=>{const t=n.ack(e);return this.confirmedDialogAcks.set(n.id,t),t}});else{const e=n.ack();this.confirmedDialogAcks.set(n.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class os extends Gr{constructor(e,t,i){super(Mr,e,t,i),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new cr(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Mr))throw new Error("Transaction not instance of InviteClientTransaction.");const t=jr.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new ss(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),i=`Contact: ${this.core.configuration.contact.toString()}`,n="Allow: "+lr.toString();if(!e.body)if(this.confirmedDialog.signalingState===rr.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===rr.Initial||this.confirmedDialog.signalingState===rr.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(n),e.extraHeaders.push(i);const r=super.accept(e),s=this.confirmedDialog,a=Object.assign(Object.assign({},r),{session:s});return e.body&&this.confirmedDialog.signalingState!==rr.Stable&&this.confirmedDialog.signalingStateTransition(e.body),a}progress(e={statusCode:180}){if(!this.progressable)throw new cr(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Mr))throw new Error("Transaction not instance of InviteClientTransaction.");const t=jr.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new ss(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),i=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i);const n=super.progress(e),r=this.earlyDialog,s=Object.assign(Object.assign({},n),{session:r});return e.body&&this.earlyDialog.signalingState!==rr.Stable&&this.earlyDialog.signalingStateTransition(e.body),s}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class cs extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class ds extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class ls extends Gr{constructor(e,t,i){super(qr,e,t,i),this.core=e}}class hs extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.SUBSCRIBE,i);super(Lr,e.userAgentCore,n,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class us extends jr{constructor(e,t,i,n,r,s){super(n,r),this.delegate=s,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=i,this.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const i=t.getHeaders("record-route"),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const r=n.uri,s=e.cseq,a=e.callId,o=e.fromTag,c=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!o)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+o+c,early:!1,callId:a,localTag:o,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:i,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===dr.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+lr.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var i;if(this.subscriptionState!==wr.Pending&&this.subscriptionState!==wr.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const n=new hs(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(i=t.extraHeaders)||void 0===i?void 0:i.includes("Expires: 0"))||(this.N=setTimeout((()=>this.timerN()),or.TIMER_N)),n}terminate(){this.stateTransition(wr.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+lr.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const i=e.parseHeader("Subscription-State");if(!i||!i.state)return void this.core.replyStateless(e,{statusCode:489});const n=i.state,r=i.expires?Math.max(i.expires,0):void 0;switch(n){case"pending":this.stateTransition(wr.Pending,r);break;case"active":this.stateTransition(wr.Active,r);break;case"terminated":this.stateTransition(wr.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const s=new Xr(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())}),e)}}stateTransition(e,t){const i=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case wr.Initial:case wr.NotifyWait:return void i();case wr.Pending:if(this.subscriptionState!==wr.NotifyWait&&this.subscriptionState!==wr.Pending)return void i();break;case wr.Active:case wr.Terminated:if(this.subscriptionState!==wr.NotifyWait&&this.subscriptionState!==wr.Pending&&this.subscriptionState!==wr.Active)return void i();break;default:return void i()}e===wr.Pending&&t&&(this.subscriptionExpires=t),e===wr.Active&&t&&(this.subscriptionExpires=t),e===wr.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==wr.Terminated&&(this.stateTransition(wr.Terminated),this.onTerminated())}}class ps extends Ur{constructor(e,t,i){const n=t.getHeader("Event");if(!n)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(Lr,e,t,i),this.delegate=i,this.subscriberId=t.callId+t.fromTag+n,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=n,this.subscriptionState=wr.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const i=e.message.parseHeader("Subscription-State");if(!i||!i.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=i.state;switch(n){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${n}`),void e.reject({statusCode:489})}if("terminated"!==n){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=i.expires?Math.min(this.subscriptionExpires,Math.max(i.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=wr.Pending;break;case"active":this.subscriptionState=wr.Active;break;case"terminated":this.subscriptionState=wr.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==wr.Terminated){const t=us.initialDialogStateForSubscription(this.message,e.message);this.dialog=new us(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,i=this.dialog;this.delegate.onNotify({request:t,subscription:i})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((()=>this.timerN()),or.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class gs extends Gr{constructor(e,t,i){super(qr,e,t,i),this.core=e}}const fs=["application/sdp","application/dtmf-relay"];class ms{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach((e=>e.dispose())),this.dialogs.clear(),this.subscribers.forEach((e=>e.dispose())),this.subscribers.clear(),this.userAgentClients.forEach((e=>e.dispose())),this.userAgentClients.clear(),this.userAgentServers.forEach((e=>e.dispose())),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new as(this,e,t)}message(e,t){return new Yr(this,e,t)}publish(e,t){return new cs(this,e,t)}register(e,t){return new ds(this,e,t)}subscribe(e,t){return new ps(this,e,t)}request(e,t){return new Ur(Lr,this,e,t)}makeOutgoingRequestMessage(e,t,i,n,r,s,a){const o=this.configuration.sipjsId,c=this.configuration.displayName,d=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===dr.REGISTER&&h.push("path","gruu"),e===dr.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");const u={callIdPrefix:o,forceRport:d,fromDisplayName:c,hackViaTcp:l,optionTags:h,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},p=Object.assign(Object.assign({},u),r);return new Xn(e,t,i,n,p,s,a)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const i=this.configuration.userAgentHeaderFieldValue,n=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:i,supported:n});const r=Nr(e,t);return this.transport.send(r.message).catch((t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)})),r}receiveRequestFromTransport(e){const t=e.viaBranch,i=this.userAgentServers.get(t);e.method===dr.ACK&&i&&i.transaction.state===_r.Accepted&&i instanceof os?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==dr.CANCEL?i?i.transaction.receiveRequest(e):this.receiveRequest(e):i?(this.replyStateless(e,{statusCode:200}),i.transaction instanceof Mr&&i.transaction.state===_r.Proceeding&&i instanceof os&&i.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!lr.includes(e.method)){const t="Allow: "+lr.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,i=e=>!!e&&e.user===t.user;if(!i(this.configuration.aor)&&!(i(this.configuration.contact.uri)||i(this.configuration.contact.pubGruu)||i(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==dr.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==dr.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some((t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq)))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===dr.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const i=e.callId+e.toTag+t.event,n=this.subscribers.get(i);if(n){const t=new Xr(this,e);return void n.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,i=this.dialogs.get(t);if(i){if(e.method===dr.OPTIONS){const t="Allow: "+lr.toString(),i="Accept: "+fs.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}i.receiveRequest(e)}else e.method!==dr.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case dr.ACK:break;case dr.BYE:this.replyStateless(e,{statusCode:481});break;case dr.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case dr.INFO:this.replyStateless(e,{statusCode:405});break;case dr.INVITE:{const t=new os(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case dr.MESSAGE:{const t=new Jr(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case dr.NOTIFY:{const t=new Xr(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case dr.OPTIONS:{const t="Allow: "+lr.toString(),i="Accept: "+fs.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}break;case dr.REFER:{const t=new rs(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case dr.REGISTER:{const t=new ls(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case dr.SUBSCRIBE:{const t=new gs(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,i=this.userAgentClients.get(t);i?i.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class vs{constructor(e,t,i){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=i,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==i?void 0:i.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach((e=>{e.track&&e.track.stop()})),this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.stop()})),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach((t=>{t.track&&(t.track.enabled=e)}))}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach((t=>{t.track&&(t.track.enabled=e)}))}getDescription(e,t){var i,n;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(i=null==e?void 0:e.offerOptions)||void 0===i?void 0:i.iceRestart,s=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(n=this.sessionDescriptionHandlerConfiguration)||void 0===n?void 0:n.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then((()=>this.updateDirection(e))).then((()=>this.createDataChannel(e))).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.applyModifiers(e,t))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(r,s))).then((()=>this.getLocalSessionDescription())).then((e=>({body:e.sdp,contentType:"application/sdp"}))).catch((e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e}))}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const i=this._peerConnection.getSenders();if(0===i.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const n=i[0].dtmf;if(!n)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{n.insertDTMF(e,r,s)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,i){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const n="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then((()=>this.applyModifiers({sdp:e,type:n},i))).then((e=>this.setRemoteSessionDescription(e))).catch((e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e}))}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)).then((e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}})):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then((e=>this.setLocalMediaStream(e)))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,i=this._localMediaStream,n=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const s=t.getSenders().find((e=>e.track&&e.track.kind===r));s?n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()})).then((()=>s.replaceTrack(e).then((()=>{const t=i.getTracks().find((e=>e.kind===r));t&&(t.stop(),i.removeTrack(t),vs.dispatchRemoveTrackEvent(i,t)),i.addTrack(e),vs.dispatchAddTrackEvent(i,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))))):n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()})).then((()=>{try{t.addTrack(e,i)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}i.addTrack(e),vs.dispatchAddTrackEvent(i,e)})))},s=e.getAudioTracks();s.length&&r(s[0]);const a=e.getVideoTracks();return a.length&&r(a[0]),n.reduce(((e,t)=>e.then((()=>t))),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let i;switch(this._peerConnection.signalingState){case"stable":i="offer";break;case"have-local-offer":i="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:i}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach((e=>{e.stop(),t.removeTrack(e),vs.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),vs.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach((e=>{e.stop(),t.removeTrack(e),vs.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),vs.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach((e=>{if(e.direction){const i=t(e.direction);e.direction!==i&&(e.direction=i)}}))}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),i=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach((e=>{e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)}))}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise(((e,i)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=i,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout((()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()}),t))})),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var i;const n=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var i;const n=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var i;const n=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${n}`),"complete"===n&&this.iceGatheringComplete(),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var i;const n=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const i=e.track.kind,n=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${i} ${n}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function ys(e){return(t,i)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const n={iceGatheringTimeout:void 0!==(null==i?void 0:i.iceGatheringTimeout)?null==i?void 0:i.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==i?void 0:i.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new vs(r,e,n)}}class Ss{constructor(e,t){if(this._state=Er.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new Nn,this.logger=e,t){const e=t,i=null==e?void 0:e.wsServers,n=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==i){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==n){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}i&&!t.server&&("string"==typeof i&&(t.server=i),i instanceof Array&&(t.server=i[0]))}this.configuration=Object.assign(Object.assign({},Ss.defaultOptions),t);const i=this.configuration.server,n=Un.parse(i,"absoluteURI");if(-1===n)throw this.logger.error(`Invalid WebSocket Server URL "${i}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(n.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${i}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=n.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===Er.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case Er.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case Er.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case Er.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Er.Connecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Er.Connecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",(t=>this.onWebSocketClose(t,e))),e.addEventListener("error",(t=>this.onWebSocketError(t,e))),e.addEventListener("open",(t=>this.onWebSocketOpen(t,e))),e.addEventListener("message",(t=>this.onWebSocketMessage(t,e))),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise(((t,i)=>{this.connectResolve=t,this.connectReject=i,this.transitionState(Er.Disconnected,e)}))}return this.connectPromise=new Promise(((t,i)=>{this.connectResolve=t,this.connectReject=i,this.connectTimeout=setTimeout((()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)}),1e3*this.configuration.connectionTimeout)})),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case Er.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Er.Disconnecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Er.Disconnecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case Er.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise(((t,i)=>{this.disconnectResolve=t,this.disconnectReject=i;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}})),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==Er.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const i=`WebSocket closed ${this.server} (code: ${e.code})`,n=this.disconnectPromise?void 0:new Error(i);n&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(i),this._ws=void 0,this.transitionState(Er.Disconnected,n)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const i=e.data;let n;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{n=(new TextDecoder).decode(new Uint8Array(i))}catch(e){return this.logger.error(e.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+n+"\n")}else n=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===Er.Connected){if(this.onMessage)try{this.onMessage(n)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===Er.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(Er.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new Rn("Loop detected.")}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case Er.Connecting:e!==Er.Connected&&e!==Er.Disconnecting&&e!==Er.Disconnected&&i();break;case Er.Connected:e!==Er.Disconnecting&&e!==Er.Disconnected&&i();break;case Er.Disconnecting:e!==Er.Connecting&&e!==Er.Disconnected&&i();break;case Er.Disconnected:e!==Er.Connecting&&i();break;default:throw new Error("Unknown state.")}const n=this._state;this._state=e;const r=this.connectResolve,s=this.connectReject;n===Er.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,o=this.disconnectReject;if(n===Er.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${n} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===Er.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(n===Er.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(n===Er.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!s)throw new Error("Connect reject undefined.");e===Er.Connected?r():s(t||new Error("Connect aborted."))}if(n===Er.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!o)throw new Error("Disconnect reject undefined.");e===Er.Disconnected?a():o(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout((()=>{this.clearKeepAliveTimeout()}),1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval((()=>{this.sendKeepAlive(),this.startSendingKeepAlives()}),(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Ss.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class bs{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=Cr.Stopped,this._stateEventEmitter=new Nn,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},bs.defaultOptions()),{sipjsId:qn(5)}),{uri:new Mn("sip","anonymous."+qn(6),"anonymous.invalid")}),{viaHost:qn(12)+".invalid"}),bs.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,i=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Dr,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=$r.error;break;case"warn":this.loggerFactory.level=$r.warn;break;case"log":this.loggerFactory.level=$r.log;break;case"debug":this.loggerFactory.level=$r.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}}))),this.options.transportOptions){const t=this.options.transportOptions,i=t.maxReconnectionAttempts,n=t.reconnectionTimeout;if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==n){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==n&&(this.options.reconnectionDelay=n),void 0===e.reconnectionAttempts&&void 0!==i&&(this.options.reconnectionAttempts=i)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:bs.newUUID(),-1===Un.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Un.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:ys(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:fr.Unsupported,sipExtensionReplaces:fr.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Ss,transportOptions:{},uri:new Mn("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)}))}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t)),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===Cr.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then((()=>this.transport.connect()))}start(){return this.state===Cr.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(Cr.Started),this.transport.connect())}async stop(){if(this.state===Cr.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(Cr.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),i=Object.assign({},this._sessions),n=Object.assign({},this._subscriptions),r=this.transport,s=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._registerers[e],t}));this.logger.log("Dispose of sessions");for(const e in i)i[e]&&await i[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._sessions[e],t}));this.logger.log("Dispose of subscriptions");for(const e in n)n[e]&&await n[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t}));this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch((e=>{throw this.logger.error(e.message),delete this._publishers[t],e}));this.logger.log("Dispose of transport"),await r.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),s.dispose(),this.transitionState(Cr.Stopped)}_makeInviter(e,t){return new yr(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout((()=>{this.reconnect().then((()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)})).catch((i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)}))}),1===e?0:1e3*i))}initContact(){const e=""!==this.options.contactName?this.options.contactName:qn(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Mn("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const i=e.anonymous||!1,n=e.outbound||!1,r=e.register||!1;let s="<";return s+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,n&&(s+=";ob"),s+=">",this.options.instanceIdAlwaysAdded&&(s+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),s}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===fr.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===fr.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter((e=>mr[e]))),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,i=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new Ar(this.getLoggerFactory(),i,e,t)},transportAccessor:()=>this.transport};return new ms(i,{onInvite:e=>{var t;const i=new vr(this,e);if(e.delegate={onCancel:e=>{i._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==fr.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const n=t.replaces_to_tag;if("string"!=typeof n)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const s=e+n+r,a=this.userAgentCore.dialogs.get(s);if(!a)return void i.reject({statusCode:481});if(!a.early&&!0===t.early_only)return void i.reject({statusCode:486});const o=this._sessions[e+r]||this._sessions[e+n]||void 0;if(!o)throw new Error("Session does not exist.");i._replacee=o}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then((()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(i)})):void this.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new hr(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new ur(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==Cr.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==Cr.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=Tr.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===Cr.Stopped&&t instanceof Jn)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const i=()=>{const e=["from","to","call_id","cseq","via"];for(const i of e)if(!t.hasHeader(i))return this.logger.warn(`Missing mandatory header field : ${i}.`),!1;return!0};if(t instanceof Jn){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=zn(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof Zn){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=zn(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof Jn)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof Zn))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Cr.Started:e!==Cr.Stopped&&i();break;case Cr.Stopped:e!==Cr.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}const ws="onUserAgent",Es="onRegistered",Cs="onUnRegistered",$s="onProgress",Ts="onCallAccepted",_s="onCallAnswered",xs="onCallIncoming",Is="onCallOutgoing",Rs="onCallMuted",As="onCallUnmuted",Ps="onCallResumed",Ds="onCallHeld",Ns="onCallUnHeld",ks="onCameraDisabled",Os="onCameraResumed",Fs="onCallCanceled",Ms="onCallFailed",Hs="onCallRejected",Ls="onCallEnded",js="onCallEnding",Bs="onMessage",Us="reinvite",Vs="onTrack",qs="onAudioStream",Gs="onVideoStream",Ks="onRemoveStream",Ws="onScreenShareStarted",zs="onScreenShareEnding",Ys="onScreenShareEnded",Js="terminateSound",Zs="playRingingSound",Xs="playInboundCallSignalSound",Qs="playHangupSound",ea="playProgressSound",ta="videoInputChange",ia="onCallError",na="onTrackUpdated",ra="onNetworkStats",sa="phone/ON_CHAT",aa="phone/ON_SIGNAL",oa="onDisconnected",ca="onEarlyMedia",da="message/TYPE_CHAT",la="message/TYPE_SIGNAL",ha=[ws,Es,Cs,$s,Ts,_s,xs,Is,Rs,As,Ps,Ds,Ns,ks,Ms,Ls,Hs,Bs,Us,Vs,qs,Gs,Ks,Ys,Js,Zs,Xs,Qs,ea,ta,Ws,ia,sa,aa,ra,oa,ca],ua=B.loggerFor("webrtc-phone");class pa extends Fi{client;allowVideo;callSessions;incomingSessions;currentSipSession;currentCallSession;audioOutputDeviceId;audioRingDeviceId;audioOutputVolume;audioRingVolume;ringingEnabled;acceptedSessions;rejectedSessions;ignoredSessions;currentScreenShare;lastScreenShare;shouldSendReinvite;constructor(e,t,i=!1,n){super(),this.client=e,this.allowVideo=i,this.callSessions={},this.audioOutputDeviceId=t,this.audioRingDeviceId=n||t,this.audioOutputVolume=1,this.audioRingVolume=1,this.incomingSessions=[],this.ringingEnabled=!0,this.shouldSendReinvite=!1,this.bindClientEvents(),this.acceptedSessions={},this.rejectedSessions={},this.ignoredSessions={}}register(){return ua.info("WebRTC register",{client:!!this.client}),this.client?this.client.register().then((()=>(ua.info("WebRTC register, registered"),this.bindClientEvents()))).catch((e=>{console.error("register error",e,e.message,e.stack),ua.error("WebRTC register error",{message:e.message,stack:e.stack})})):Promise.resolve()}unregister(){return this.client&&this.client.isRegistered()?this.client.unregister():null}stop(){this.client&&(ua.info("WebRTC phone stop"),this.client.stop())}removeIncomingSessions(e){this.incomingSessions=this.incomingSessions.filter((t=>t!==e))}isWebRTC(){return!0}async sendReinvite(e,t=null,i=!1,n=!1,r=!1){const s=this.findSipSession(e);if(ua.info("WebRTC phone - send reinvite",{sessionId:s?s.id:null,constraints:t,audioOnly:n,conference:i,iceRestart:r}),!s)return;const a=t?.screen,o=a||t?.video;if(!t||o){if(o){if(!await this._upgradeToVideo(e,t,i))return}return this.client.reinvite(s,t,i,n,r)}this._downgradeToAudio(e)}getUserAgent(){return this.client?.config?.userAgentString||"webrtc-phone"}startHeartbeat(){ua.info("WebRTC phone - start heartbeat",{client:!!this.client,hasHeartbeat:this.client.hasHeartbeat()}),this.client&&!this.client.hasHeartbeat()&&this.client.startHeartbeat()}stopHeartbeat(){ua.info("WebRTC phone - stopHeartbeat",{client:!!this.client}),this.client&&this.client.stopHeartbeat()}setOnHeartbeatTimeout(e){this.client.setOnHeartbeatTimeout(e)}setOnHeartbeatCallback(e){this.client.setOnHeartbeatCallback(e)}reconnect(){ua.info("WebRTC phone - reconnect",{client:!!this.client}),this.client&&this.client.attemptReconnection()}getOptions(){return{accept:!0,decline:!0,mute:!0,hold:!0,transfer:!0,sendKey:!0,addParticipant:!1,record:!0,merge:!0}}onConnect(){return this.client?this.client.onConnect():Promise.reject(new Error("No webrtc client"))}onDisconnect(){return this.client?this.client.onDisconnect():Promise.reject(new Error("No webrtc client"))}_downgradeToAudio(e,t=!0){const i=this.findSipSession(e);return!!i&&(ua.info("Downgrade to audio",{id:e?e.getId():null,withMessage:t}),this.client.downgradeToAudio(i),e&&(e.cameraEnabled=!1,this._updateCallSession(e)),t&&this._sendReinviteMessage(e,!1),!0)}async _upgradeToVideo(e,t,i){const n=this.findSipSession(e);if(!n)return Promise.resolve(!1);ua.info("Upgrade to video",{id:e?e.getId():null,constraints:t,isConference:i});const r=t&&!!t.screen,s=t&&t.desktop,a=n.sessionDescriptionHandlerOptionsReInvite,o=a?.audioOnly,c=await this.client.upgradeToVideo(n,t,i);return e&&(e.cameraEnabled=!0,this._updateCallSession(e)),!c||(this._sendReinviteMessage(e,!0),r&&this._onScreenSharing(c,n,e,!1,s),!(!i||!o))}_sendReinviteMessage(e,t){const i=this.findSipSession(e);ua.info("Sending reinvite message",{id:e?e.getId():null,isUpgrade:t}),setTimeout((()=>{this.sendMessage(i,JSON.stringify({type:la,content:{type:na,update:t?"upgrade":"downgrade",sipCallId:i&&this.getSipSessionId(i),callId:e?e.callId:null,number:e?e.number:null,callerNumber:e?e.callerNumber:null}}))}),2500)}_bindEvents(e){const t=this.getSipSessionId(e);if(e instanceof vr){const i=e._onCancel.bind(e);e._onCancel=n=>{ua.trace("on sip session canceled",{callId:n.callId,sipSessionId:t}),i(n);const r=-1!==n.data.indexOf("cause=26")&&-1!==n.data.indexOf("completed elsewhere"),s=this._createCallSession(e);delete this.callSessions[t],this.eventEmitter.emit(Fs,s,r)}}if(e.stateChange.addListener((t=>{switch(t){case mi.Terminating:ua.info("WebRTC phone - call terminating",{sipId:e.id}),this.eventEmitter.emit(js,this._createCallSession(e));break;case mi.Terminated:{ua.info("WebRTC phone - call terminated",{sipId:e.id});const t=this._createCallSession(e);t.endTime=new Date;const i=this._onCallTerminated(e);return this.eventEmitter.emit(Ls,t,i)}}})),!e.sessionDescriptionHandler)return;const i=e.sessionDescriptionHandler.peerConnection;i?(i.ontrack=t=>{const i=t,[n]=i.streams,r=i&&i.track&&i.track.kind;return ua.info("on track stream called on the peer connection",{callId:this.getSipSessionId(e),streamId:n?n.id:null,tracks:n?n.getTracks():null,kind:r}),"audio"===r?this.eventEmitter.emit(qs,n):this.eventEmitter.emit(Gs,n,i.track.id,i,e)},i.onremovestream=e=>{ua.info("on remove stream called on the peer connection",{id:e.stream.id,tracks:e.stream.getTracks()}),this.eventEmitter.emit(Ks,e.stream)}):ua.info("null peer connection")}async startScreenSharing(e,t){ua.info("WebRTC - start screen sharing",{constraints:e,id:t?t.getId():null});const i=await this.client.getStreamFromConstraints(e);if(!i)throw new Error(`Can't create media stream for screensharing with: ${JSON.stringify(e)}`);const n=i.getVideoTracks()[0],r=this.currentSipSession,s=r&&this.client.getPeerConnection(this.getSipSessionId(r)),a=s&&s.getSenders&&s.getSenders().find((e=>e&&e.track&&"video"===e.track.kind)),o=r&&this.client.getLocalStream(this.getSipSessionId(r)),c=o?o.getTracks().find((e=>"video"===e.kind)):null,d=!!c;return c&&o&&(c.enabled=!1,c.stop(),o.removeTrack(c)),o&&o.addTrack(n),a&&a.replaceTrack(n),this._onScreenSharing(i,r,t,d,e.desktop),i}async stopScreenSharing(e=!0,t){if(!this.currentScreenShare)return;ua.info("WebRTC phone - stop screen sharing",{restoreLocalStream:e});let i=null;try{if(this.currentScreenShare.stream&&this.currentScreenShare.stream.getTracks().filter((e=>e.enabled&&"video"===e.kind)).forEach((e=>e.stop())),e){const e=t||this.currentCallSession,n=this.isConference(e),r={audio:!1,video:this.currentScreenShare.hadVideo};this._downgradeToAudio(e,!1),await new Promise((e=>setTimeout(e,500))),i=await this.sendReinvite(e,r,n)}}catch(e){console.warn(e)}const n=this.currentSipSession;return this.eventEmitter.emit(Ys,t&&n?this._createCallSession(n,t,{screensharing:!1}):null),this.currentScreenShare=null,i}_onScreenSharing(e,t,i,n,r){const s=e.getVideoTracks()[0],a=this.getSipSessionId(t),o=this.client.getPeerConnection(a),c=o&&o.getSenders&&o.getSenders().find((e=>e&&e.track&&"video"===e.track.kind));ua.info("WebRTC phone - on screensharing",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),s&&(s.onended=()=>{ua.info("WebRTC phone - on screenshare ended",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),this.eventEmitter.emit(zs,this._createCallSession(t,i))}),this.currentScreenShare={stream:e,hadVideo:n,sender:c,sipSessionId:a,desktop:r},this.client.setLocalMediaStream(this.getSipSessionId(t),e),this.eventEmitter.emit(Ws,this._createCallSession(t,i,{screensharing:!0}),e)}_onCallAccepted(e,t){ua.info("WebRTC phone - on call accepted",{sipId:e.id,cameraEnabled:t});const i=this._createAcceptedCallSession(e,t);this.currentSipSession&&!this.isCurrentCallSipSession(i)&&(ua.info("WebRTC phone - on call accepted with another ongoing call, holding it",{sipId:e.id,cameraEnabled:t}),this.holdSipSession(this.currentSipSession,this.currentCallSession,!0)),this.currentSipSession=e,this.currentCallSession=i,this.eventEmitter.emit(Js,i,"call accepted");const n=this.getSipSessionId(e);return n&&this.removeIncomingSessions(n),i.answerTime=new Date,this._updateCallSession(i),this.eventEmitter.emit(Ts,i,t),i}async changeAudioDevice(e){return ua.info("WebRTC phone - change audio device",{deviceId:e}),this.audioOutputDeviceId=e,this.client.changeAudioOutputDevice(e)}createAudioElementFor(e){return this.client.createAudioElementFor(e)}changeRingDevice(e){ua.info("WebRTC phone - changing ring device",{id:e}),this.audioRingDeviceId=e}changeAudioVolume(e){ua.info("WebRTC phone - changing audio volume",{volume:e}),this.audioOutputVolume=e,this.client.changeAudioOutputVolume(e)}changeRingVolume(e){ua.info("WebRTC phone - changing ring volume",{volume:e}),this.audioRingVolume=e}changeAudioInputDevice(e,t){return ua.info("WebRTC phone - changeAudio input device",{deviceId:e}),this.client.changeAudioInputDevice(e,this.currentSipSession,t)}async changeVideoInputDevice(e){return ua.info("WebRTC phone - change video input device",{deviceId:e}),this.client.changeVideoInputDevice(e,this.currentSipSession)}changeSessionVideoInputDevice(e){return ua.info("WebRTC phone - change session video input device",{deviceId:e}),this.currentSipSession&&this.client.changeSessionVideoInputDevice(e,this.currentSipSession)}_onCallTerminated(e){const t=this.getSipSessionId(e);ua.info("WebRTC phone - on call terminated",{sipId:e.id,sipSessionId:t,ids:Object.keys(this.callSessions)});const i=this._createCallSession(e),n=this.isCurrentCallSipSession(i),r=i.is(this.getIncomingCallSession()),s=n?this.incomingSessions.length:r;r&&setTimeout((()=>{this.eventEmitter.emit(Js,i,"call terminated")}),5),t&&this.removeIncomingSessions(t),delete this.callSessions[t],n&&(this.currentSipSession=void 0,this.currentCallSession=void 0);const a=this.hasIncomingCallSession();if(ua.info("WebRTC phone - check to re-trigger incoming call",{sipId:e.id,shouldRetrigger:s,hasIncomingCallSession:a}),this.client.onCallEnded(e),a&&s){const e=this.getIncomingCallSession();setTimeout((()=>{this.ringingEnabled&&(this.currentCallSession?this.eventEmitter.emit(Xs,this.audioOutputDeviceId,this.audioOutputVolume,e):this.eventEmitter.emit(Zs,this.audioRingDeviceId,this.audioRingVolume,e)),this.eventEmitter.emit(xs,e,e?.cameraEnabled)}),100)}return!(i.getId()in this.ignoredSessions)&&(e.isCanceled||setTimeout((()=>{this.eventEmitter.emit(Qs,this.audioOutputDeviceId,this.audioOutputVolume,i)}),10),n)}setActiveSipSession(e){const t=this.findSipSession(e);t&&(this.currentSipSession=t,this.currentCallSession=e)}hasAnActiveCall(){return!!this.currentSipSession}hasActiveRemoteVideoStream(){const e=this.currentSipSession;if(!e)return!1;const t=e.sessionDescriptionHandler.peerConnection.getRemoteStreams().find((e=>!!e.getVideoTracks().length));return t&&t.getVideoTracks().some((e=>!e.muted))}callCount(){return Object.keys(this.callSessions).length}isCurrentCallSipSession(e){return!!this.currentSipSession&&(this.currentSipSession&&this.getSipSessionId(this.currentSipSession)===e.getId())}hasVideo(e){return this.client.hasVideo(e.getId())}hasAVideoTrack(e){return this.client.hasAVideoTrack(e.getId())}getLocalStreamForCall(e){return ua.warn("WebRTCPhone.getLocalStreamForCall is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}getRemoteStreamForCall(e){return ua.warn("WebRTCPhone.getRemoteStreamForCall is deprecated, use WebRTCPhone.getRemoteStream instead"),this.getRemoteVideoStream(e)}getRemoteStreamsForCall(e){return ua.warn("WebRTCPhone.getRemoteStreamsForCall is deprecated, use WebRTCPhone.getRemoteStreams instead"),this.getRemoteStream(e)}accept(e,t){if(ua.info("WebRTC phone - accept call",{id:e?e.getId():"n/a",cameraEnabled:t}),this.currentSipSession&&!this.isCurrentCallSipSession(e)&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0),!e)return ua.warn("no CallSession to accept."),Promise.resolve(null);const i=this.getSipSessionIdFromCallSession(e);if(i&&!(i in this.callSessions))return ua.warn("Call session already ended or not found, can't accept it.",{sipSessionId:i}),Promise.resolve(null);if(e.getId()in this.acceptedSessions)return ua.warn("CallSession already accepted.",{id:e?e.getId():"n/a"}),Promise.resolve(e.sipCallId);this.shouldSendReinvite=!1,e.answerTime=new Date,this._updateCallSession(e),this.acceptedSessions[e.getId()]=!0,this.eventEmitter.emit(_s,e);const n=this.client.getSipSession(e.getId());if(n)return ua.info("accept call, session found",{sipId:n.id}),this.client.answer(n,!!this.allowVideo&&t).then((()=>e.sipCallId)).catch((t=>{throw ua.error(t),this.endCurrentCall(e),t}));const r="No CallSession found to accept.";return ua.warn(r,{id:e?e.getId():"n/a",ids:this.client.getSipSessionIds()}),e&&this.eventEmitter.emit(ia,new Error(r),e),Promise.resolve(null)}isAccepted(e){return e&&e.getId()in this.acceptedSessions}async reject(e){if(ua.info("reject WebRTC called",{id:e.getId()}),this.eventEmitter.emit(Js,e,"call rejected locally"),!e||e.getId()in this.rejectedSessions)return;this.shouldSendReinvite=!1,this.rejectedSessions[e.getId()]=!0;const t=this.findSipSession(e);t&&(ua.info("WebRTC rejecting",{sipId:t.id}),this.client.hangup(t))}async ignore(e){ua.info("WebRTC ignore",{id:e.getId()}),this.eventEmitter.emit(Js,e,"ignoring call"),this.ignoredSessions[e.getId()]=!0,e.ignore()}atxfer(e){const t=this.findSipSession(e);if(t)return ua.info("WebRTC atxfer",{sipId:t.id}),this.client.atxfer(t)}hold(e,t=!0){ua.info("WebRTC hold",{id:e.getId()});const i=this.findSipSession(e);return i?this.holdSipSession(i,e,t):null}unhold(e,t=!0){return console.warn("Please note that `phone.unhold()` is being deprecated; `phone.resume()` is the preferred method"),this.resume(e,t)}resume(e,t=!0){ua.info("WebRTC resume called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return new Promise(((e,t)=>t(new Error("No session to resume"))));ua.info("WebRTC resuming",{sipId:i.id}),this.currentSipSession&&this.currentSipSession.id!==i.id&&(ua.info("WebRTC hold call after resume",{id:this.currentSipSession.id}),this.holdSipSession(this.currentSipSession,this.currentCallSession,t));const n=this.unholdSipSession(i,e,t);return this.currentSipSession=i,e&&(this.currentCallSession=e),n}async holdSipSession(e,t,i=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to hold"))));const n=this.getSipSessionId(e),r=this.client.hasLocalVideo(n);ua.info("WebRTC hold sip session",{sipId:e.id,hasVideo:r}),this.currentScreenShare&&this.currentScreenShare.sipSessionId===n&&(this.lastScreenShare=this.currentScreenShare,await this.stopScreenSharing(!1,t)),r&&await this.client.downgradeToAudio(e);const s=!!t&&t.isConference(),a=this.client.hold(e,s,r);return i&&this.eventEmitter.emit(Ds,this._createCallSession(e,t)),a}async unholdSipSession(e,t,i=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to unhold"))));const n=!!t&&t.isConference(),r=this.getSipSessionId(e);ua.info("WebRTC unhold sip session",{sessionId:r,isConference:n});const{hasVideo:s}=this.client.getHeldSession(r)||{},a=this.lastScreenShare&&this.lastScreenShare.sipSessionId===r,o=this.lastScreenShare&&this.lastScreenShare.desktop,c=this.client.unhold(e,n);if(s){const t={audio:!1,video:!0,screen:a,desktop:o};await this.client.upgradeToVideo(e,t,n)}const d=i=>{const n=this.lastScreenShare&&this.lastScreenShare.hadVideo;i&&this._onScreenSharing(i,e,t,n),this.lastScreenShare=null};if(i){t&&(t.muted=!1);const i=this._createCallSession(e,t);this.eventEmitter.emit(Ns,i),this.eventEmitter.emit(Ps,i)}return c.then((()=>{const e=t?this.getLocalVideoStream(t):null;return a&&d(e),e}))}mute(e,t=!0){ua.info("WebRTC mute called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return;ua.info("WebRTC muting",{sipId:i.id}),this.client.mute(i);const n=this._createCallSession(i,e,{muted:!0});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(Rs,n)}unmute(e,t=!0){ua.info("WebRTC unmute called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return;ua.info("WebRTC unmuting",{sipId:i.id}),this.client.unmute(i);const n=this._createCallSession(i,e,{muted:!1});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(As,n)}isAudioMuted(e){const t=this.findSipSession(e);return!t||this.client.isAudioMuted(t)}turnCameraOn(e){const t=this.findSipSession(e);t&&(ua.info("WebRTC turn camera on",{sipId:t.id}),this.client.toggleCameraOn(t),this.eventEmitter.emit(Os,this._createCameraResumedCallSession(t,e)))}turnCameraOff(e){const t=this.findSipSession(e);t&&(ua.info("WebRTC turn camera off",{sipId:t.id}),this.client.toggleCameraOff(t),this.eventEmitter.emit(ks,this._createCameraDisabledCallSession(t,e)))}sendKey(e,t){const i=this.findSipSession(e);i&&(ua.info("WebRTC send key",{sipId:i.id,tone:t}),this.client.sendDTMF(i,t))}async makeCall(e,t,i,n=!1,r=!1,s={}){if(ua.info("make WebRTC call",{number:e,lineId:t?t.id:null,cameraEnabled:i,audioOnly:n,conference:r,options:s}),!e)return Promise.resolve(null);let a;this.client.isRegistered()||await this.client.register(),this.currentSipSession&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0).catch((e=>{ua.warn("Unable to hold current session when making another call",e)}));try{a=this.client.call(e,!!this.allowVideo&&i,n,r,s),this._bindEvents(a)}catch(e){return ua.warn("make WebRTC call, error",{message:e.message,stack:e.stack}),Promise.resolve(null)}const o=this._createOutgoingCallSession(a,i||!1);return o.setIsConference(r),o.creationTime=new Date,this._updateCallSession(o),this.eventEmitter.emit(ea,this.audioOutputDeviceId,this.audioOutputVolume),this.currentSipSession=a,this.currentCallSession=o,this.eventEmitter.emit(Is,o),a.invitePromise&&a.invitePromise.catch((e=>{this.eventEmitter.emit(ia,e,o)})),Promise.resolve(o)}transfer(e,t){const i=this.findSipSession(e);i&&(ua.info("WebRTC transfer",{sipId:i.id,target:t}),this.client.transfer(i,t))}async indirectTransfer(e,t){const i=this.client.getSipSession(e.sipCallId),n=this.client.getSipSession(t.sipCallId);return ua.info("WebRTC indirect transfer",{sipId:i?i.id:null,target:n?n.id:null}),n?new Promise((e=>{const r={requestDelegate:{onAccept:()=>{setTimeout((()=>{this.hangup(t).then(e)}),200)}}};return n.refer(i,r)})):Promise.reject()}initiateCTIIndirectTransfer(){return Promise.resolve(null)}cancelCTIIndirectTransfer(){}confirmCTIIndirectTransfer(){}async hangup(e){const t=this.findSipSession(e);if(!t)return console.error("Call is unknown to the WebRTC phone",e?e.sipCallId:null,e?e.callId:null),!1;const i=this.getSipSessionId(t);return ua.info("WebRTC hangup",{sipId:t.id,sipSessionId:i}),await this.client.hangup(t),e?this.endCurrentCall(e):i&&delete this.callSessions[i],this.shouldSendReinvite=!1,!0}async getStats(e){const t=this.findSipSession(e);return t?this.client.getStats(t):null}startNetworkMonitoring(e,t=1e3){const i=this.findSipSession(e);return i?this.client.startNetworkMonitoring(i,t):null}stopNetworkMonitoring(e){const t=this.findSipSession(e);return t?this.client.stopNetworkMonitoring(t):null}forceCancel(e){if(e&&e.outgoingInviteRequest)try{e.outgoingInviteRequest.cancel()}catch(e){ua.info("force cancel, error",e)}}endCurrentCall(e){const t=this.isCurrentCallSipSession(e);ua.info("Ending current call",{id:e?e.getId():null,isCurrent:t}),t&&(this.currentSipSession=void 0,this.currentCallSession=void 0),this.eventEmitter.emit(Js,e,"locally ended")}onConnectionMade(){}isConference(e){return!!e&&(this.client&&this.client.isConference(e.sipCallId))}async close(e=!1){ua.info("WebRTC close");try{await Promise.race([this.unregister(),new Promise(((e,t)=>setTimeout((()=>t(new Error("Unregister, timed out"))),3e3)))])}catch(e){ua.error("WebRTC close, unregister error",e)}await this.client.close(e),this.unbind(),this.incomingSessions=[],this.currentSipSession=void 0,this.currentCallSession=void 0,this.shouldSendReinvite=!1,this.rejectedSessions={}}isRegistered(){return this.client&&this.client.isRegistered()}enableRinging(){ua.info("WebRTC enable ringing"),this.ringingEnabled=!0}disableRinging(){ua.info("WebRTC disable ringing"),this.ringingEnabled=!1}getCurrentCallSession(){return this.currentSipSession?this._createCallSession(this.currentSipSession,this.currentCallSession):null}hasIncomingCallSession(){return this.incomingSessions.length>0}getIncomingCallSession(){if(!this.hasIncomingCallSession())return null;const e=this.incomingSessions[0],t=this.client.getSipSession(e);return t?this._createCallSession(t):null}sendMessage(e=null,t,i="text/plain"){return this.client.sendMessage(e,t,i)}getLocalStream(e){return e?this.client.getLocalStream(e.sipCallId):null}getLocalVideoStream(e){return e?this.client.getLocalVideoStream(e.sipCallId):null}getLocalMediaStream(e){return ua.warn("WebRTCPhone.getLocalMediaStream is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}hasLocalVideo(e){return!!e&&this.client.hasLocalVideo(e.sipCallId)}hasALocalVideoTrack(e){return!!e&&this.client.hasALocalVideoTrack(e.sipCallId)}getRemoteStream(e){return e?this.client.getRemoteStream(e.sipCallId):null}getRemoteVideoStream(e){return e?this.client.getRemoteVideoStream(e.sipCallId):null}getRemoteVideoStreamFromPc(e){return e?this.client.getRemoteVideoStreamFromPc(e.sipCallId):null}hasRemoteVideo(e){return!!e&&this.client.hasRemoteVideo(e.sipCallId)}setMediaConstraints(e){this.client.setMediaConstraints(e)}isVideoRemotelyHeld(e){return!!e&&this.client.isVideoRemotelyHeld(e.sipCallId)}bindClientEvents(){this.client.unbind(),this.client.on(this.client.INVITE,((e,t)=>{const i="Auto"===e.request.getHeader("Answer-Mode"),n=!!this.allowVideo&&t;ua.info("WebRTC invite received",{sipId:e.id,withVideo:n,autoAnswer:i});const r=this._createIncomingCallSession(e,n,null,i);this.incomingSessions.push(r.getId()),this._bindEvents(e),this.client.storeSipSession(e),r.creationTime=new Date,this._updateCallSession(r),this.eventEmitter.emit(xs,r,t),this.currentSipSession?this.eventEmitter.emit(Xs,this.audioOutputDeviceId,this.audioOutputVolume,r):this.ringingEnabled&&this.eventEmitter.emit(Zs,this.audioRingDeviceId,this.audioRingVolume,r)})),this.client.on(this.client.ON_REINVITE,((...e)=>{ua.info("WebRTC on reinvite",{sessionId:e[0].id,inviteId:e[1].id,updatedCalleeName:e[2],updatedNumber:e[3]});const t=e[0];setTimeout((()=>{this._createCallSession(t,this.callSessions[this.getSipSessionId(t)]),this.eventEmitter.emit.apply(this.eventEmitter,[this.client.ON_REINVITE,...e])}),2e3)})),this.client.on(this.client.ACCEPTED,(async e=>{const t=this.getSipSessionId(e),i=t in this.callSessions;ua.info("WebRTC call accepted",{sipId:t,hasSession:i}),i?(this._onCallAccepted(e,this.client.hasVideo(t)),this.audioOutputDeviceId&&await this.client.changeAudioOutputDevice(this.audioOutputDeviceId)):ua.warn("Call accepted ignored, session is no longer present in the WebRtcPhone",{sessionId:t})})),this.client.on("ended",(()=>{})),this.client.on(this.client.ON_ERROR,(e=>{ua.error("WebRTC error",e),this.eventEmitter.emit(ia,e)})),this.client.on(this.client.REJECTED,(e=>{ua.info("WebRTC call rejected",e.id);const t=this._createCallSession(e);delete this.callSessions[this.getSipSessionId(e)],t.endTime=new Date,this.eventEmitter.emit(Hs,t)})),this.client.on(this.client.UNREGISTERED,(()=>{ua.info("WebRTC unregistered"),this.eventEmitter.emit(Cs)})),this.client.on(this.client.ON_DISCONNECTED,(()=>{ua.info("WebRTC disconnected"),this.eventEmitter.emit(oa)})),this.client.on(this.client.ON_PROGRESS,(e=>{ua.info("WebRTC progress (180)");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit($s,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.ON_EARLY_MEDIA,(e=>{ua.info("WebRTC early media");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit(ca,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.REGISTERED,(()=>{if(ua.info("WebRTC registered",{shouldSendReinvite:this.shouldSendReinvite,state:this.currentSipSession?this.currentSipSession.state:null,currentSipSession:!!this.currentSipSession}),this.stopHeartbeat(),this.eventEmitter.emit(Es),this.shouldSendReinvite&&this.currentSipSession&&this.currentSipSession.state===mi.Established){this.shouldSendReinvite=!1;const e=this.currentSipSession?.sessionDescriptionHandler?.peerConnection,t=!!e&&e.sfu,i=this.currentCallSession&&this.currentCallSession.cameraEnabled;try{this.sendReinvite(this.currentCallSession,null,t,!i,!0)}catch(e){ua.error("WebRTC reinvite after register, error",{message:e.message,stack:e.stack})}}})),this.client.on(this.client.CONNECTED,(()=>{ua.info("WebRTC client connected"),this.stopHeartbeat()})),this.client.on(this.client.DISCONNECTED,(()=>{ua.info("WebRTC client disconnected"),this.eventEmitter.emit(Cs),this.client.hasHeartbeat()||this.startHeartbeat(),this.shouldSendReinvite=!0})),this.client.on(this.client.ON_TRACK,((e,t)=>{this.eventEmitter.emit(Vs,e,t)})),this.client.on("onVideoInputChange",(e=>{this.eventEmitter.emit(ta,e)})),this.client.on(this.client.MESSAGE,(e=>{this._onMessage(e),this.eventEmitter.emit(Bs,e)})),this.client.on(this.client.ON_NETWORK_STATS,((e,t,i)=>{const n=this.getCallSession(this.getSipSessionId(e));this.eventEmitter.emit(ra,n,t,i)})),this.client.on(this.client.ON_SCREEN_SHARING_REINVITE,((e,t,i)=>{const n=this.getSipSessionId(e),r=this.client.getLocalStream(n),s=this.callSessions[n];ua.info("Updrading directly in screensharing mode",{sipSessionId:n,tracks:r?.getTracks()||null}),this._onScreenSharing(r,e,s,!1,i)}))}findSipSession(e){const t=this.client.getSipSessionIds(),i=t.findIndex((t=>e&&e.isId(t)));if(-1===i){const e=this.currentSipSession?this.getSipSessionId(this.currentSipSession):this.client.getSipSessionIds()[0];return e?this.client.getSipSession(e):null}return this.client.getSipSession(t[i])}getCallSession(e){return this.callSessions[e]}getSipSessionId(e){return this.client.getSipSessionId(e)}getSipSessionIdFromCallSession(e){const t=this.findSipSession(e);return t?this.getSipSessionId(t):null}_updateCallSession(e){const t=this.getSipSessionIdFromCallSession(e);t&&(this.callSessions[t]=e)}_onMessage(e){if(!e||"MESSAGE"!==e.method)return;let t;try{t=JSON.parse(e.body||"")}catch(e){return}const{type:i,content:n}=t;switch(i){case da:this.eventEmitter.emit(sa,n);break;case la:this.eventEmitter.emit(aa,n)}}_createIncomingCallSession(e,t,i,n=!1){return this._createCallSession(e,i,{incoming:!0,ringing:!0,cameraEnabled:t,autoAnswer:n})}_createOutgoingCallSession(e,t,i){return this._createCallSession(e,i,{incoming:!1,ringing:!0,cameraEnabled:t})}_createAcceptedCallSession(e,t,i){return this._createCallSession(e,i,{cameraEnabled:void 0!==t&&t})}_createMutedCallSession(e,t){return this._createCallSession(e,t,{muted:!0})}_createUnmutedCallSession(e,t){return this._createCallSession(e,t,{muted:!1})}_createCameraResumedCallSession(e,t){return this._createCallSession(e,t,{videoMuted:!1})}_createCameraDisabledCallSession(e,t){return this._createCallSession(e,t,{videoMuted:!0})}_createCallSession(e,t,i={}){const n=e?e.remoteIdentity||e.assertedIdentity:null,r=n?n.uri._normal.user:null,{state:s}=e||{},a=this.getSipSessionId(e);t=t||this.callSessions[a];const o=new yi({callId:t&&t.callId,sipCallId:a,sipStatus:s,displayName:n&&n.displayName||r,startTime:t?t.startTime:new Date,creationTime:t?t.creationTime:null,answerTime:t?t.answerTime:null,endTime:t?t.endTime:null,answered:s===mi.Established,paused:this.client.isCallHeld(e),isCaller:t?t.isCaller:"incoming"in i&&!i.incoming,cameraEnabled:t?t.isCameraEnabled():this.client.hasVideo(a),number:r,ringing:!1,muted:t?t.isMuted():this.client.isAudioMuted(e),videoMuted:!!t&&t.isVideoMuted(),recording:!!t&&t.isRecording(),recordingPaused:!1,sipSession:e,conference:!!t&&t.isConference(),...i});return this.callSessions[a]=o,o}}var ga=Object.freeze({__proto__:null,MESSAGE_TYPE_CHAT:da,MESSAGE_TYPE_SIGNAL:la,ON_AUDIO_STREAM:qs,ON_CALL_ACCEPTED:Ts,ON_CALL_ANSWERED:_s,ON_CALL_CANCELED:Fs,ON_CALL_ENDED:Ls,ON_CALL_ENDING:js,ON_CALL_ERROR:ia,ON_CALL_FAILED:Ms,ON_CALL_HELD:Ds,ON_CALL_INCOMING:xs,ON_CALL_MUTED:Rs,ON_CALL_OUTGOING:Is,ON_CALL_REJECTED:Hs,ON_CALL_RESUMED:Ps,ON_CALL_UNHELD:Ns,ON_CALL_UNMUTED:As,ON_CAMERA_DISABLED:ks,ON_CAMERA_RESUMED:Os,ON_CHAT:sa,ON_DISCONNECTED:oa,ON_EARLY_MEDIA:ca,ON_MESSAGE:Bs,ON_MESSAGE_TRACK_UPDATED:na,ON_NETWORK_STATS:ra,ON_PLAY_HANGUP_SOUND:Qs,ON_PLAY_INBOUND_CALL_SIGNAL_SOUND:Xs,ON_PLAY_PROGRESS_SOUND:ea,ON_PLAY_RING_SOUND:Zs,ON_PROGRESS:$s,ON_REGISTERED:Es,ON_REINVITE:Us,ON_REMOVE_STREAM:Ks,ON_SHARE_SCREEN_ENDED:Ys,ON_SHARE_SCREEN_ENDING:zs,ON_SHARE_SCREEN_STARTED:Ws,ON_SIGNAL:aa,ON_TERMINATE_SOUND:Js,ON_TRACK:Vs,ON_UNREGISTERED:Cs,ON_USER_AGENT:ws,ON_VIDEO_INPUT_CHANGE:ta,ON_VIDEO_STREAM:Gs,default:pa,events:ha});let fa=!0,ma=!0;function va(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function ya(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Sa(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(fa=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ba(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ma=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function wa(){if("object"==typeof window){if(fa)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ea(e,t){ma&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ca(e){return"[object Object]"===Object.prototype.toString.call(e)}function $a(e){return Ca(e)?Object.keys(e).reduce((function(t,i){const n=Ca(e[i]),r=n?$a(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Ta(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Ta(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Ta(e,e.get(t),i)}))})))}function _a(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Ta(e,i,r)}))})),r}const xa=wa;function Ia(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let a=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),xa("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return xa("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Ra(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Aa(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ya(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Pa(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Da(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function Na(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>_a(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ya(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>_a(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ka(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Oa(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ka(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Fa(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Ma(e,t){ya(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Ha=Object.freeze({__proto__:null,fixNegotiationNeeded:Ma,shimAddTrackRemoveTrack:Oa,shimAddTrackRemoveTrackWithNative:ka,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:Pa,shimGetStats:Da,shimGetUserMedia:Ia,shimMediaStream:Ra,shimOnTrack:Aa,shimPeerConnection:Fa,shimSenderReceiverGetStats:Na});function La(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Ea("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function ja(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ba(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function Ua(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Va(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ya(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function qa(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ea("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Ga(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ka(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Wa(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function za(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ya(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ja=Object.freeze({__proto__:null,shimAddTransceiver:Ka,shimCreateAnswer:Ya,shimCreateOffer:za,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Wa,shimGetUserMedia:La,shimOnTrack:ja,shimPeerConnection:Ba,shimRTCDataChannel:Ga,shimReceiverGetStats:Va,shimRemoveStream:qa,shimSenderGetStats:Ua});function Za(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Xa(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Qa(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function eo(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(to(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function to(e){return e&&void 0!==e.video?Object.assign({},e,{video:$a(e.video)}):e}function io(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Ea("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function no(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ro(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function so(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ao=Object.freeze({__proto__:null,shimAudioContext:so,shimCallbacksAPI:Qa,shimConstraints:to,shimCreateOfferLegacy:ro,shimGetUserMedia:eo,shimLocalStreamsAPI:Za,shimRTCIceServerUrls:io,shimRemoteStreamsAPI:Xa,shimTrackEventTransceiver:no}),oo={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(oo);var co=oo.exports,lo=C(co),ho=t({__proto__:null,default:lo},[co]);function uo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=lo.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ya(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function po(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ya(e,"icecandidate",(e=>{if(e.candidate){const t=lo.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function go(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=lo.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=lo.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=lo.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function fo(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},ya(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function mo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function vo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function yo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function So(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var bo=Object.freeze({__proto__:null,removeExtmapAllowMixed:vo,shimAddIceCandidateNullOrEmpty:yo,shimConnectionState:mo,shimMaxMessageSize:go,shimParameterlessSetLocalDescription:So,shimRTCIceCandidate:uo,shimRTCIceCandidateRelayProtocol:po,shimSendThrowTypeError:fo});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=wa,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=va(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=va(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=va(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:bo,extractVersion:va,disableLog:Sa,disableWarnings:ba,sdp:ho};switch(n.browser){case"chrome":if(!Ha||!Fa||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Ha,yo(e,n),So(e),Ia(e,n),Ra(e),Fa(e,n),Aa(e),Oa(e,n),Pa(e),Da(e),Na(e),Ma(e,n),uo(e),po(e),mo(e),go(e,n),fo(e),vo(e,n);break;case"firefox":if(!Ja||!Ba||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Ja,yo(e,n),So(e),La(e,n),Ba(e,n),ja(e),qa(e),Ua(e),Va(e),Ga(e),Ka(e),Wa(e),za(e),Ya(e),uo(e),mo(e),go(e,n),fo(e);break;case"safari":if(!ao||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=ao,yo(e,n),So(e),io(e),ro(e),Qa(e),Za(e),Xa(e),no(e),eo(e),so(e),uo(e),po(e),go(e,n),fo(e),vo(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});function wo(e){return e.sdp=((e,t)=>{const i=new RegExp("m="+t+".*$","gm"),n=new RegExp("^a=group:.*$","gm");if(i.test(e)){let i;const r=(e=e.split(/^m=/gm).filter((e=>{if(e.substr(0,t.length)===t){if(i=e.match(/^a=mid:.*$/gm),i){const e=i[0].match(/:.+$/g);e&&(i=e[0].substr(1))}return!1}return!0})).join("m=")).match(n);if(r&&1===r.length){let t=r[0];const s=new RegExp(" *"+i+"[^ ]*","g");t=t.replace(s,""),e=e.split(n).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function Eo(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const i=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:i})}var Co={exports:{}};!function(e){e.exports=function(e,t,i){var n;(n=void 0!==E?E:null)&&"undefined"==typeof window&&void 0!==E&&(E.navigator={userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45",getUserMedia:function(){}},E.console||(E.console={}),void 0!==E.console.log&&void 0!==E.console.error||(E.console.error=E.console.log=E.console.log||function(){console.log(arguments)}),"undefined"==typeof document&&(n.document={documentElement:{appendChild:function(){return""}}},document.createElement=document.captureStream=document.mozCaptureStream=function(){var e={getContext:function(){return e},play:function(){},pause:function(){},drawImage:function(){},toDataURL:function(){return""}};return e},n.HTMLVideoElement=function(){}),"undefined"==typeof location&&(n.location={protocol:"file:",href:"",hash:""}),"undefined"==typeof screen&&(n.screen={width:0,height:0}),"undefined"==typeof URL&&(n.URL={createObjectURL:function(){return""},revokeObjectURL:function(){return""}}),"undefined"==typeof MediaStreamTrack&&(n.MediaStreamTrack=function(){}),void 0===r&&(n.RTCPeerConnection=function(){}),n.window=E);var r=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;"undefined"==typeof MediaStreamTrack&&(MediaStreamTrack={});var s={encryption:"sha-256",audio:{send:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},recv:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},bytesSent:0,bytesReceived:0,latency:0,packetsLost:0},video:{send:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},recv:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},bytesSent:0,bytesReceived:0,latency:0,packetsLost:0},bandwidth:{systemBandwidth:0,sentPerSecond:0,encodedPerSecond:0,helper:{audioBytesSent:0,videoBytestSent:0},speed:0},results:{},connectionType:{systemNetworkType:((navigator.connection||{}).type||"unknown").toString().toLowerCase(),systemIpAddress:"192.168.1.2",local:{candidateType:[],transport:[],ipAddress:[],networkType:[]},remote:{candidateType:[],transport:[],ipAddress:[],networkType:[]}},resolutions:{send:{width:0,height:0},recv:{width:0,height:0}},internal:{audio:{send:{},recv:{}},video:{send:{},recv:{}},candidates:{},getSendrecvType:function(e){var t=e.id.split("_").pop();if("isRemote"in e)!0===e.isRemote&&(t="recv"),!1===e.isRemote&&(t="send");else{var i=e.type.split("-")[0];t="outbound"===i?"send":"inbound"===i?"recv":null}return t}},nomore:function(){d=!0}},a={checkIfOfferer:function(e){"googLibjingleSession"===e.type&&(s.isOfferer=e.googInitiator)}},o=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),c=this;if(!(arguments[0]instanceof r))throw"1st argument is not instance of RTCPeerConnection.";c=arguments[0],arguments[1]instanceof MediaStreamTrack&&(e=arguments[1],t=arguments[2],i=arguments[3]);var d=!1;a.datachannel=function(e){"datachannel"===e.type&&(s.datachannel={state:e.state})},a.googCertificate=function(e){"googCertificate"==e.type&&(s.encryption=e.googFingerprintAlgorithm),"certificate"==e.type&&(s.encryption=e.fingerprintAlgorithm)},a.checkAudioTracks=function(e){if("audio"===e.mediaType){var t=s.internal.getSendrecvType(e);if(t){if(-1===s.audio[t].codecs.indexOf(e.googCodecName||"opus")&&s.audio[t].codecs.push(e.googCodecName||"opus"),e.bytesSent){var i=0;s.internal.audio[t].prevBytesSent||(s.internal.audio[t].prevBytesSent=e.bytesSent);var n=e.bytesSent-s.internal.audio[t].prevBytesSent;s.internal.audio[t].prevBytesSent=e.bytesSent,i=n/1024,s.audio[t].availableBandwidth=i.toFixed(1),s.audio.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.audio[t].prevBytesReceived||(s.internal.audio[t].prevBytesReceived=e.bytesReceived),n=e.bytesReceived-s.internal.audio[t].prevBytesReceived,s.internal.audio[t].prevBytesReceived=e.bytesReceived,i=n/1024,s.audio.bytesReceived=i.toFixed(1)),e.googTrackId&&-1===s.audio[t].tracks.indexOf(e.googTrackId)&&s.audio[t].tracks.push(e.googTrackId),e.googCurrentDelayMs&&(i=0,s.internal.audio.prevGoogCurrentDelayMs||(s.internal.audio.prevGoogCurrentDelayMs=e.googCurrentDelayMs),n=e.googCurrentDelayMs-s.internal.audio.prevGoogCurrentDelayMs,s.internal.audio.prevGoogCurrentDelayMs=e.googCurrentDelayMs,s.audio.latency=n.toFixed(1),s.audio.latency<0&&(s.audio.latency=0)),e.packetsLost&&(i=0,s.internal.audio.prevPacketsLost||(s.internal.audio.prevPacketsLost=e.packetsLost),n=e.packetsLost-s.internal.audio.prevPacketsLost,s.internal.audio.prevPacketsLost=e.packetsLost,s.audio.packetsLost=n.toFixed(1),s.audio.packetsLost<0&&(s.audio.packetsLost=0))}}},a.checkVideoTracks=function(e){if("video"===e.mediaType){var t=s.internal.getSendrecvType(e);if(t){if(-1===s.video[t].codecs.indexOf(e.googCodecName||"VP8")&&s.video[t].codecs.push(e.googCodecName||"VP8"),e.bytesSent){var i=0;s.internal.video[t].prevBytesSent||(s.internal.video[t].prevBytesSent=e.bytesSent);var n=e.bytesSent-s.internal.video[t].prevBytesSent;s.internal.video[t].prevBytesSent=e.bytesSent,i=n/1024,s.video[t].availableBandwidth=i.toFixed(1),s.video.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.video[t].prevBytesReceived||(s.internal.video[t].prevBytesReceived=e.bytesReceived),n=e.bytesReceived-s.internal.video[t].prevBytesReceived,s.internal.video[t].prevBytesReceived=e.bytesReceived,i=n/1024,s.video.bytesReceived=i.toFixed(1)),e.googFrameHeightReceived&&e.googFrameWidthReceived&&(s.resolutions[t].width=e.googFrameWidthReceived,s.resolutions[t].height=e.googFrameHeightReceived),e.googFrameHeightSent&&e.googFrameWidthSent&&(s.resolutions[t].width=e.googFrameWidthSent,s.resolutions[t].height=e.googFrameHeightSent),e.googTrackId&&-1===s.video[t].tracks.indexOf(e.googTrackId)&&s.video[t].tracks.push(e.googTrackId),e.framerateMean&&(s.bandwidth.framerateMean=e.framerateMean,i=0,s.internal.video[t].prevFramerateMean||(s.internal.video[t].prevFramerateMean=e.bitrateMean),n=e.bytesSent-s.internal.video[t].prevFramerateMean,s.internal.video[t].prevFramerateMean=e.framerateMean,i=n/1024,s.video[t].framerateMean=n.toFixed(1)),e.bitrateMean&&(s.bandwidth.bitrateMean=e.bitrateMean,i=0,s.internal.video[t].prevBitrateMean||(s.internal.video[t].prevBitrateMean=e.bitrateMean),n=e.bytesSent-s.internal.video[t].prevBitrateMean,s.internal.video[t].prevBitrateMean=e.bitrateMean,i=n/1024,s.video[t].bitrateMean=n.toFixed(1)),e.googCurrentDelayMs&&(i=0,s.internal.video.prevGoogCurrentDelayMs||(s.internal.video.prevGoogCurrentDelayMs=e.googCurrentDelayMs),n=e.googCurrentDelayMs-s.internal.video.prevGoogCurrentDelayMs,s.internal.video.prevGoogCurrentDelayMs=e.googCurrentDelayMs,s.video.latency=n.toFixed(1),s.video.latency<0&&(s.video.latency=0)),e.packetsLost&&(i=0,s.internal.video.prevPacketsLost||(s.internal.video.prevPacketsLost=e.packetsLost),n=e.packetsLost-s.internal.video.prevPacketsLost,s.internal.video.prevPacketsLost=e.packetsLost,s.video.packetsLost=n.toFixed(1),s.video.packetsLost<0&&(s.video.packetsLost=0))}}},a.bweforvideo=function(e){"VideoBwe"===e.type&&(s.bandwidth.availableSendBandwidth=e.googAvailableSendBandwidth,s.bandwidth.googActualEncBitrate=e.googActualEncBitrate,s.bandwidth.googAvailableSendBandwidth=e.googAvailableSendBandwidth,s.bandwidth.googAvailableReceiveBandwidth=e.googAvailableReceiveBandwidth,s.bandwidth.googRetransmitBitrate=e.googRetransmitBitrate,s.bandwidth.googTargetEncBitrate=e.googTargetEncBitrate,s.bandwidth.googBucketDelay=e.googBucketDelay,s.bandwidth.googTransmitBitrate=e.googTransmitBitrate)},a.candidatePair=function(e){if("googCandidatePair"===e.type||"candidate-pair"===e.type||"local-candidate"===e.type||"remote-candidate"===e.type){if("true"==e.googActiveConnection&&(Object.keys(s.internal.candidates).forEach((function(t){var i=s.internal.candidates[t];-1!==i.ipAddress.indexOf(e.googLocalAddress)&&(s.connectionType.local.candidateType=i.candidateType,s.connectionType.local.ipAddress=i.ipAddress,s.connectionType.local.networkType=i.networkType,s.connectionType.local.transport=i.transport),-1!==i.ipAddress.indexOf(e.googRemoteAddress)&&(s.connectionType.remote.candidateType=i.candidateType,s.connectionType.remote.ipAddress=i.ipAddress,s.connectionType.remote.networkType=i.networkType,s.connectionType.remote.transport=i.transport)})),s.connectionType.transport=e.googTransportType,(t=s.internal.candidates[e.localCandidateId])&&t.ipAddress&&(s.connectionType.systemIpAddress=t.ipAddress),(i=s.internal.candidates[e.remoteCandidateId])&&i.ipAddress&&(s.connectionType.systemIpAddress=i.ipAddress)),"candidate-pair"===e.type&&!0===e.selected&&!0===e.nominated&&"succeeded"===e.state)var t=s.internal.candidates[e.remoteCandidateId],i=s.internal.candidates[e.remoteCandidateId];if("local-candidate"===e.type&&(s.connectionType.local.candidateType=e.candidateType,s.connectionType.local.ipAddress=e.ipAddress,s.connectionType.local.networkType=e.networkType,s.connectionType.local.transport=e.mozLocalTransport||e.transport),"remote-candidate"===e.type&&(s.connectionType.remote.candidateType=e.candidateType,s.connectionType.remote.ipAddress=e.ipAddress,s.connectionType.remote.networkType=e.networkType,s.connectionType.remote.transport=e.mozRemoteTransport||e.transport),o){var n=e.localCandidateId?"send":"recv";if(!n)return;if(e.bytesSent){var r=0;s.internal.video[n].prevBytesSent||(s.internal.video[n].prevBytesSent=e.bytesSent);var a=e.bytesSent-s.internal.video[n].prevBytesSent;s.internal.video[n].prevBytesSent=e.bytesSent,r=a/1024,s.video[n].availableBandwidth=r.toFixed(1),s.video.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=0,s.internal.video[n].prevBytesReceived||(s.internal.video[n].prevBytesReceived=e.bytesReceived),a=e.bytesReceived-s.internal.video[n].prevBytesReceived,s.internal.video[n].prevBytesReceived=e.bytesReceived,r=a/1024,s.video.bytesReceived=r.toFixed(1)),e.availableOutgoingBitrate&&(r=0,s.internal.video[n].prevAvailableOutgoingBitrate||(s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate),a=e.availableOutgoingBitrate-s.internal.video[n].prevAvailableOutgoingBitrate,s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate,r=a/1024,s.video.availableOutgoingBitrate=r.toFixed(1)),e.availableIncomingBitrate&&(r=0,s.internal.video[n].prevAvailableIncomingBitrate||(s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate),a=e.availableIncomingBitrate-s.internal.video[n].prevAvailableIncomingBitrate,s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate,r=a/1024,s.video.availableIncomingBitrate=r.toFixed(1))}}};var l={},h={},u={},p={};a.localcandidate=function(e){"localcandidate"!==e.type&&"local-candidate"!==e.type||e.id&&(l[e.id]||(l[e.id]=[]),h[e.id]||(h[e.id]=[]),u[e.id]||(u[e.id]=[]),p[e.id]||(p[e.id]=[]),e.candidateType&&-1===l[e.id].indexOf(e.candidateType)&&l[e.id].push(e.candidateType),e.transport&&-1===h[e.id].indexOf(e.transport)&&h[e.id].push(e.transport),e.ipAddress&&-1===u[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&u[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===p[e.id].indexOf(e.networkType)&&p[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:l[e.id],ipAddress:u[e.id],portNumber:e.portNumber,networkType:p[e.id],priority:e.priority,transport:h[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.local.candidateType=l[e.id],s.connectionType.local.ipAddress=u[e.id],s.connectionType.local.networkType=p[e.id],s.connectionType.local.transport=h[e.id])};var g={},f={},m={},v={};a.remotecandidate=function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||e.id&&(g[e.id]||(g[e.id]=[]),f[e.id]||(f[e.id]=[]),m[e.id]||(m[e.id]=[]),v[e.id]||(v[e.id]=[]),e.candidateType&&-1===g[e.id].indexOf(e.candidateType)&&g[e.id].push(e.candidateType),e.transport&&-1===f[e.id].indexOf(e.transport)&&f[e.id].push(e.transport),e.ipAddress&&-1===m[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&m[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===v[e.id].indexOf(e.networkType)&&v[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:g[e.id],ipAddress:m[e.id],portNumber:e.portNumber,networkType:v[e.id],priority:e.priority,transport:f[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.remote.candidateType=g[e.id],s.connectionType.remote.ipAddress=m[e.id],s.connectionType.remote.networkType=v[e.id],s.connectionType.remote.transport=f[e.id])},a.dataSentReceived=function(e){!e.googCodecName||"video"!==e.mediaType&&"audio"!==e.mediaType||(e.bytesSent&&(s[e.mediaType].bytesSent=parseInt(e.bytesSent)),e.bytesReceived&&(s[e.mediaType].bytesReceived=parseInt(e.bytesReceived)))},a.inboundrtp=function(e){if(o&&"inbound-rtp"===e.type){var t=e.mediaType||"audio",i=e.isRemote?"recv":"send";if(i){if(e.bytesSent){var n=0;s.internal[t][i].prevBytesSent||(s.internal[t][i].prevBytesSent=e.bytesSent);var r=e.bytesSent-s.internal[t][i].prevBytesSent;s.internal[t][i].prevBytesSent=e.bytesSent,n=r/1024,s[t][i].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][i].prevBytesReceived||(s.internal[t][i].prevBytesReceived=e.bytesReceived),r=e.bytesReceived-s.internal[t][i].prevBytesReceived,s.internal[t][i].prevBytesReceived=e.bytesReceived,n=r/1024,s[t].bytesReceived=n.toFixed(1))}}},a.outboundrtp=function(e){if(o&&"outbound-rtp"===e.type){var t=e.mediaType||"audio",i=e.isRemote?"recv":"send";if(i){if(e.bytesSent){var n=0;s.internal[t][i].prevBytesSent||(s.internal[t][i].prevBytesSent=e.bytesSent);var r=e.bytesSent-s.internal[t][i].prevBytesSent;s.internal[t][i].prevBytesSent=e.bytesSent,n=r/1024,s[t][i].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][i].prevBytesReceived||(s.internal[t][i].prevBytesReceived=e.bytesReceived),r=e.bytesReceived-s.internal[t][i].prevBytesReceived,s.internal[t][i].prevBytesReceived=e.bytesReceived,n=r/1024,s[t].bytesReceived=n.toFixed(1))}}},a.track=function(e){if(o&&"track"===e.type){var t=!0===e.remoteSource?"send":"recv";e.frameWidth&&e.frameHeight&&(s.resolutions[t].width=e.frameWidth,s.resolutions[t].height=e.frameHeight)}};var y={audio:{send:[],recv:[]},video:{send:[],recv:[]}};a.ssrc=function(e){if(e.googCodecName&&("video"===e.mediaType||"audio"===e.mediaType)&&"ssrc"===e.type){var t=e.id.split("_").pop();-1===y[e.mediaType][t].indexOf(e.ssrc)&&y[e.mediaType][t].push(e.ssrc),s[e.mediaType][t].streams=y[e.mediaType][t].length}},function e(){var n;n=function(n){if(n&&n.forEach){n.forEach((function(e){Object.keys(a).forEach((function(t){if("function"==typeof a[t])try{a[t](e)}catch(e){console.error(e.message,e.stack,e)}}))}));try{-1!==c.iceConnectionState.search(/failed|closed|disconnected/gi)&&(d=!0)}catch(e){d=!0}!0===d&&(s.datachannel&&(s.datachannel.state="close"),s.ended=!0),s.results=n,s.audio&&s.video&&(s.bandwidth.speed=s.audio.bytesSent-s.bandwidth.helper.audioBytesSent+(s.video.bytesSent-s.bandwidth.helper.videoBytesSent),s.bandwidth.helper.audioBytesSent=s.audio.bytesSent,s.bandwidth.helper.videoBytesSent=s.video.bytesSent),t(s),d||null!=typeof i&&i&&setTimeout(e,i||1e3)}},c.getStats(window.mediaStreamTrack||null).then((function(e){var t=[];e.forEach((function(e){t.push(e)})),n(t)})).catch(n)}()}}(Co);var $o=C(Co.exports),To={},_o={},xo={exports:{}},Io=xo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Io).forEach((function(e){Io[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ro=xo.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=Ro,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(_o);var Ao=Ro,Po=/%[sdv%]/g,Do=function(e){var t=1,i=arguments,n=i.length;return e.replace(Po,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},No=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return Do.apply(null,n)},ko=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Oo=["i","c","b","a"],Fo=_o,Mo=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||ko,n=t.innerOrder||Oo,r=[];return i.forEach((function(t){Ao[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(No(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(No(t,i,e))}))}))})),e.media.forEach((function(e){r.push(No("m",Ao.m[0],e)),n.forEach((function(t){Ao[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(No(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(No(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"};To.write=Mo,To.parse=Fo.parse,To.parseParams=Fo.parseParams,To.parseFmtpConfig=Fo.parseFmtpConfig,To.parsePayloads=Fo.parsePayloads,To.parseRemoteCandidates=Fo.parseRemoteCandidates,To.parseImageAttributes=Fo.parseImageAttributes,To.parseSimulcastStreamList=Fo.parseSimulcastStreamList;const Ho=(e,t,i=!0)=>{const n=To.parse(e),r=(e=>e.filter((e=>e&&("srflx"===e.type||"relay"===e.type))))(t)[0],s=r?r.ip:null;s&&(n.origin.address=s),n.media=n.media.map((e=>{const n=i&&r?r.port:e.port;return{...e,port:n,candidates:(e.candidates||[]).concat(t),direction:n<10?"inactive":e.direction}}));let a=To.write(n);return s&&(a=a.replace(/IN IP4 0.0.0.0/g,`IN IP4 ${s}`)),a},Lo=e=>{const t=To.parse(e),i=t.media.find((e=>!!e.candidates));if(!i)return e;const{candidates:n}=i;return t.media=t.media.map((e=>({...e,candidates:e.candidates||n}))),To.write(t)},jo=B?B.loggerFor("webrtc-sdh"):console,Bo=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):e.screen&&!e.desktop?navigator.mediaDevices.getDisplayMedia.call(navigator.mediaDevices,e):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream);class Uo extends vs{gatheredCandidates;eventEmitter;isWeb;session;constructor(e,t,i,n,r){super(e,t,i),this.eventEmitter=new Oi,this.isWeb=n,this.session=r}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.removeListener(e,t)}setRemoteSessionDescription(e){try{const t=super.setRemoteSessionDescription(e);return this.eventEmitter.emit("setDescription",e),t}catch(e){throw this.logger.error(`SessionDescriptionHandler.setRemoteSessionDescription: ${e}`),e}}getDescription(e={},t){if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=e.onDataChannel;const i=!!e.offerOptions&&e.offerOptions.iceRestart,n=!!e&&!!e.conference,r=!!e&&!!e.audioOnly,s=!this.session.pendingReinviteAck&&(i||"constraints"in e),a=void 0===e.iceGatheringTimeout?this.sessionDescriptionHandlerConfiguration?.iceGatheringTimeout:e.iceGatheringTimeout;return jo.trace("getting SDP description",{iceRestart:i,shouldWaitForIce:s,iceTimeout:a}),this.gatheredCandidates=[],this.peerConnectionDelegate||(this.peerConnectionDelegate={}),this.peerConnectionDelegate.onicecandidate=e=>{jo.trace("onicecandidate",e.candidate?e.candidate.candidate:{done:!0}),e.candidate&&(this.gatheredCandidates.push((e=>{if(!e)return null;const t=To.parse(0===e.indexOf("a=")?e:`a=${e}`);return t.candidates?t.candidates[0]:null})(e.candidate.candidate)),-1===e.candidate.candidate.indexOf("srflx")&&-1===e.candidate.candidate.indexOf("relay")||(jo.info("A valid ice was found, triggering ice gathering complete callback.",{ice:e.candidate.candidate}),this.iceGatheringComplete()))},this.getLocalMediaStream(e).then((()=>this.updateDirection(e,n,r))).then((()=>this.createDataChannel(e))).then((()=>{!n||!e.constraints||e.constraints.video||"hold"in e||r||this.peerConnection?.addTransceiver&&this.peerConnection.addTransceiver("video",{streams:[this._localMediaStream],direction:"sendrecv"})})).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(i,a))).then((()=>this.getLocalSessionDescription())).then((t=>{const{sdp:i}=t;return-1!==i.indexOf("a=candidate")?{type:t.type,sdp:Lo(i)}:(jo.info("No ICE candidates found in SDP, fixing it with gathered ices",this.gatheredCandidates),{type:t.type,sdp:Ho(i,this.gatheredCandidates,!(!e||!e.constraints)&&e.constraints.video)})})).then((e=>this.applyModifiers(e,t))).then((e=>({body:e.sdp,contentType:"application/sdp"}))).catch((e=>{throw jo.error("error when creating media",e),this.logger.error(`SessionDescriptionHandler.getDescription failed - ${e}`),e}))}sendDtmf(e,t={duration:0,interToneGap:0}){if(this.isWeb)return super.sendDtmf(e,t);this.logger.debug(`DTMF sent via INFO: ${e.toString()}`);const i={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=${t.duration||1e3}`}};return this.session.info({requestOptions:i})}close(){if(jo.info("closing sdh"),this.isWeb)return super.close();this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this.peerConnection?.getLocalStreams&&(this.peerConnection?.getLocalStreams().forEach((e=>{e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))})),this.peerConnection?.getRemoteStreams().forEach((e=>{e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))}))),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}updateDirection(e,t=!1,i=!1){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!this.isWeb)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":{this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");const n=(n,r)=>{if(t)return i&&r.receiver.track&&"video"===r.receiver.track.kind||e&&e.hold?"sendonly":"sendrecv";switch(n){case"inactive":return e&&e.hold?"inactive":t&&!i?"sendrecv":"recvonly";case"recvonly":return e&&e.hold?"inactive":"recvonly";case"sendonly":case"sendrecv":return e&&e.hold?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach((e=>{if(e.direction){const t=n(e.direction,e);e.direction!==t&&(e.direction=t)}}))}break;case"have-remote-offer":{this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");const n=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),r=(()=>{switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return e&&e.hold?"inactive":"recvonly";case"sendrecv":return e&&e.hold?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach((e=>{if(!e.stopped&&e.direction){const{receiver:n}=e;if(t&&i&&n.track&&"video"===n.track.kind)return void(e.direction="inactive");"stopped"!==e.direction&&e.direction!==r&&(e.direction=r)}}))}break;default:return Promise.reject(new Error(`Invalid signaling state ${this._peerConnection.signalingState}`))}return Promise.resolve()}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,{sfu:i}=t,n=this._localMediaStream,r=[],s=e=>{const{kind:s}=e;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const a=t.getSenders&&t.getSenders().find((e=>e.track&&e.track.kind===s));!a||i&&"audio"!==e.kind?r.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${s} track`),e(null)})).then((()=>{try{t.addTrack?t.addTrack(e,n):t.addStream(n)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${s} track`),e}n.addTrack(e),vs.dispatchAddTrackEvent(n,e)}))):(a.track&&(e.enabled=a.track.enabled),r.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e(null)})).then((()=>a.replaceTrack(e).then((()=>{const t=n.getTracks().find((e=>e.kind===s));t&&(t.stop(),n.removeTrack(t),vs.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),vs.dispatchAddTrackEvent(n,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))))))},a=e.getAudioTracks();a.length&&s(a[0]);const o=e.getVideoTracks();return o.length&&s(o[0]),r.reduce(((e,t)=>e.then((()=>t))),Promise.resolve())}getLocalMediaStream(e){if(this.logger.debug("WazoSessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=e.constraints?{...e.constraints}:{};if(this.localMediaStreamConstraints){if(JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then((e=>(this.setLocalMediaStream(e),e)))}}class Vo{heartbeatDelay;heartbeatTimeout;maxHeartbeats;hasHeartbeat;_heartbeatDelayTimeout;_heartbeatNotReceivedTimeout;_heartbeatTries;_sendHeartbeatCallback;_onTimeoutCallback;constructor(e=2e3,t=5e3,i=3){this.heartbeatDelay=e,this.heartbeatTimeout=t,this.maxHeartbeats=i,this.hasHeartbeat=!1,this._heartbeatTries=0}setSendHeartbeat(e){this._sendHeartbeatCallback=e}setOnHeartbeatTimeout(e){this._onTimeoutCallback=e}stop(){this.hasHeartbeat=!1,this._heartbeatNotReceivedTimeout&&clearTimeout(this._heartbeatNotReceivedTimeout),this._heartbeatDelayTimeout&&clearTimeout(this._heartbeatDelayTimeout)}start(){this.stop(),this.hasHeartbeat=!0,this._heartbeatTries=0,this._sendHeartbeat()}onHeartbeat(){this._clearTimeouts(),this.hasHeartbeat&&this._sendHeartbeat()}_sendHeartbeat(){this._heartbeatTries>=this.maxHeartbeats||(this._clearTimeouts(),this._heartbeatDelayTimeout=setTimeout((()=>{this._heartbeatTries++,this._sendHeartbeatCallback&&this._sendHeartbeatCallback()}),this.heartbeatDelay),this._onTimeoutCallback&&(this._heartbeatNotReceivedTimeout=setTimeout(this._onTimeoutCallback,this.heartbeatTimeout)))}_clearTimeouts(){this._heartbeatNotReceivedTimeout&&clearTimeout(this._heartbeatNotReceivedTimeout),this._heartbeatDelayTimeout&&clearTimeout(this._heartbeatDelayTimeout)}}const qo=e=>Promise.resolve({...JSON.parse(JSON.stringify(e)),sdp:e.sdp.replace("c=IN IP4 0.0.0.0","c=IN IP4 127.0.0.1")}),Go=["STATUS_NULL","STATUS_NEW","STATUS_CONNECTING","STATUS_CONNECTED","STATUS_COMPLETED"],Ko=B?B.loggerFor("webrtc-client"):console,Wo=B?B.loggerFor("webrtc-stats"):console,zo="registered",Yo="unregistered",Jo="registrationFailed",Zo="invite",Xo="connected",Qo="disconnected",ec="transportError",tc="message",ic="accepted",nc="rejected",rc="onTrack",sc="onProgress",ac="onEarlyMedia",oc="reinvite",cc="onError",dc="onScreenSharingReinvite",lc="onNetworkStats",hc="onDisconnected",uc=[zo,Yo,Jo,Zo],pc=[Xo,Qo,ec,tc];class gc extends Error{}class fc extends Fi{clientId;config;uaConfigOverrides;userAgent;registerer;hasAudio;audio;audioElements;video;audioStreams;audioOutputDeviceId;audioOutputVolume;heldSessions;connectionPromise;_boundOnHeartbeat;heartbeat;heartbeatTimeoutCb;heartbeatCb;statsIntervals;sipSessions;conferences;skipRegister;networkMonitoringInterval;sessionNetworkStats;forceClosed;ON_USER_AGENT;REGISTERED;UNREGISTERED;REGISTRATION_FAILED;INVITE;CONNECTED;DISCONNECTED;TRANSPORT_ERROR;MESSAGE;ACCEPTED;REJECTED;ON_TRACK;ON_REINVITE;ON_ERROR;ON_SCREEN_SHARING_REINVITE;ON_NETWORK_STATS;ON_EARLY_MEDIA;ON_PROGRESS;ON_DISCONNECTED;static isAPrivateIp(e){return null==/^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*/.exec(e)}static getIceServers(e){return fc.isAPrivateIp(e)?[{urls:["stun:stun.l.google.com:19302","stun:stun4.l.google.com:19302"]}]:[]}constructor(e,t,i){super(),this.clientId=Math.ceil(1e3*Math.random()),Ko.info("sdk webrtc constructor",{clientId:this.clientId}),this.uaConfigOverrides=i,this.config=e,this.skipRegister=e.skipRegister,this._buildConfig(e,t).then((e=>{this.config=e,this.userAgent=this.createUserAgent(i)})),this.audioOutputDeviceId=e.audioDeviceOutput,this.audioOutputVolume=e.audioOutputVolume||1,e.media&&(this.configureMedia(e.media),this.setMediaConstraints({audio:e.media.audio,video:e.media.video})),this.heldSessions={},this.statsIntervals={},this.connectionPromise=null,this.sipSessions={},this.conferences={},this.networkMonitoringInterval={},this.sessionNetworkStats={},this.forceClosed=!1,this._boundOnHeartbeat=this._onHeartbeat.bind(this),this.heartbeat=new Vo(e.heartbeatDelay,e.heartbeatTimeout,e.maxHeartbeats),this.heartbeat.setSendHeartbeat(this.pingServer.bind(this)),this.heartbeat.setOnHeartbeatTimeout(this._onHeartbeatTimeout.bind(this)),this.REGISTERED=zo,this.UNREGISTERED=Yo,this.REGISTRATION_FAILED=Jo,this.INVITE=Zo,this.CONNECTED=Xo,this.DISCONNECTED=Qo,this.TRANSPORT_ERROR=ec,this.MESSAGE=tc,this.ACCEPTED=ic,this.REJECTED=nc,this.ON_TRACK=rc,this.ON_REINVITE=oc,this.ON_ERROR=cc,this.ON_SCREEN_SHARING_REINVITE=dc,this.ON_NETWORK_STATS=lc,this.ON_DISCONNECTED=hc,this.ON_EARLY_MEDIA=ac,this.ON_PROGRESS=sc}configureMedia(e){this.hasAudio=!!e.audio,this.audioStreams={},this.audioElements={}}setMediaConstraints(e){this.video=e.video,this.audio=e.audio}createUserAgent(e){const t=this._createUaOptions(e);Ko.info("sdk webrtc, creating UA",{uaOptions:{...t,authorizationPassword:`${t?.authorizationPassword?.slice(0,5)}xxxx`},clientId:this.clientId}),t.delegate={onConnect:this.onConnect.bind(this),onDisconnect:this.onDisconnect.bind(this),onInvite:e=>{Ko.info("sdk webrtc on invite",{method:"delegate.onInvite",clientId:this.clientId,id:e.id,remoteURI:e.remoteURI}),this._setupSession(e);const t=!!e.request.getHeader("alert-info");this.eventEmitter.emit(Zo,e,this.sessionWantsToDoVideo(e),t)}};const i=new bs(t);return i.start(),i.transport&&i.transport.connectPromise&&i.transport.connectPromise.catch((e=>{Ko.warn("Transport connect error",e)})),i.transport.onMessage=e=>{const t=Tr.parseMessage(e,i.transport.logger);i.onTransportMessage(e),this.eventEmitter.emit(tc,t),t&&t.method===dr.MESSAGE&&i.userAgentCore.replyStateless(t,{statusCode:200})},i}isConnected(){return Boolean(this.userAgent?.isConnected())}isConnecting(){return this.userAgent?.transport?.state===Er.Connecting}isRegistered(){return Boolean(this.registerer&&this.registerer.state===br.Registered)}onConnect(){return Ko.info("sdk webrtc connected",{method:"delegate.onConnect",clientId:this.clientId}),this.eventEmitter.emit(Xo),!this.isRegistered()&&this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.register()}async onDisconnect(e){Ko.info("sdk webrtc disconnected",{method:"delegate.onConnect",clientId:this.clientId,error:e}),this.connectionPromise=null,this.eventEmitter.emit(Qo,e),this.isRegistered()&&(await this.unregister(),this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.eventEmitter.emit(Yo))}async register(e=0){const t={clientId:this.clientId,userAgent:!!this.userAgent,registered:this.isRegistered(),connectionPromise:!!this.connectionPromise,registerer:!!this.registerer,waiting:this.registerer&&this.registerer.waiting,tries:e,skipRegister:this.skipRegister};if(this.forceClosed=!1,this.skipRegister)return Ko.info("sdk webrtc skip register...",t),Promise.resolve();if(Ko.info("sdk webrtc registering...",t),this.userAgent||(Ko.info("sdk webrtc recreating User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),!this.userAgent||this.isRegistered())return Ko.info("sdk webrtc registering aborted, already registered or no UA can be created"),Promise.resolve();if(this.connectionPromise||this.registerer?.waiting)return Ko.info("sdk webrtc registering aborted due to a registration in progress.",{clientId:this.clientId}),Promise.resolve();const i=this._isWeb()?{}:{extraContactHeaderParams:["mobility=mobile"]},n=()=>{Ko.info("sdk webrtc registering failed",{tries:e,clientId:this.clientId,registerer:!!this.registerer,forceClosed:this.forceClosed}),this.forceClosed||(this.connectionPromise=null,this.registerer&&this.registerer.waiting&&this.registerer.waitingToggle(!1),e<=5&&(Ko.info("sdk webrtc registering, retrying...",{clientId:this.clientId,tries:e}),setTimeout((()=>this.register(e+1)),300)))};return this._connectIfNeeded().then((()=>{this.userAgent||(Ko.info("sdk webrtc recreating User Agent after connection"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),Ko.info("sdk webrtc registering, transport connected",{registerOptions:i,ua:!!this.userAgent,clientId:this.clientId}),this.registerer=new xr(this.userAgent,i),this.connectionPromise=null,this._monkeyPatchRegisterer(this.registerer),this.registerer.stateChange.addListener((e=>{Ko.info("sdk webrtc registering, state changed",{newState:e,clientId:this.clientId}),e===br.Registered&&this.registerer&&this.registerer.state===br.Registered?this.eventEmitter.emit(zo):e===br.Unregistered&&this.eventEmitter.emit(Yo)}));const e={requestDelegate:{onReject:e=>{Ko.error("sdk webrtc registering, rejected",{clientId:this.clientId,response:e}),n()}}};return this.registerer.register(e).catch((e=>(Ko.error("sdk webrtc registering, error",e),this.eventEmitter.emit(Jo),e)))})).catch((e=>{Ko.error("sdk webrtc registering, transport error",e),n()}))}_monkeyPatchRegisterer(e){if(!e)return;const t=e.waitingToggle.bind(e),i=e.unregistered.bind(e);e.waitingToggle=i=>{e&&e.waiting!==i&&t(i)},e.unregistered=()=>{e&&e.state!==br.Terminated&&i()}}async unregister(){Ko.info("sdk webrtc unregistering..",{clientId:this.clientId,userAgent:!!this.userAgent,registerer:!!this.registerer});try{return new Promise(((e,t)=>{if(!this.registerer)return e();const i=t=>{t===br.Unregistered&&(Ko.info("sdk webrtc unregistered",{clientId:this.clientId}),this.registerer&&this.registerer.stateChange.addListener(i),this._cleanupRegister(),e())};this.registerer.stateChange.addListener(i),this.registerer.unregister().then().catch((e=>{Ko.error("sdk webrtc unregistering, promise error",e),this._cleanupRegister(),t()}))}))}catch(e){Ko.error("sdk webrtc unregistering, error",e),this._cleanupRegister()}}stop(){return Ko.info("sdk webrtc stop",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent?this.userAgent.stop().then((()=>this._cleanupRegister())).catch((e=>{Ko.warn("sdk webrtc stop, error",{message:e.message,stack:e.stack})})):Promise.resolve()}call(e,t,i=!1,n=!1,r={}){Ko.info("sdk webrtc creating call",{clientId:this.clientId,number:e,enableVideo:t,audioOnly:i,conference:n,options:r});const s={sessionDescriptionHandlerOptionsReInvite:{conference:n,audioOnly:i},earlyMedia:!0,...r};i&&(s.sessionDescriptionHandlerModifiersReInvite=[wo]);const a=this._makeURI(e);let o=null;a?o=this.userAgent?new yr(this.userAgent,a,s):null:Ko.error("Null URI"),o&&(this.storeSipSession(o),this._setupSession(o)),n&&(this.conferences[this.getSipSessionId(o)]=!0);const c={requestDelegate:{onAccept:e=>{o?.sessionDescriptionHandler?.peerConnection&&((o?.sessionDescriptionHandler).peerConnection.sfu=n),this._onAccepted(o,e.session,!0)},onProgress:e=>{this._onProgress(e.session,183===e.message.statusCode)},onReject:e=>{Ko.info("on call rejected",{id:o?.id,fromTag:o?.fromTag}),this._stopSendingStats(o),this.stopNetworkMonitoring(o),this.eventEmitter.emit(nc,o,e)}},sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1,n)};return c.sessionDescriptionHandlerOptions&&(c.sessionDescriptionHandlerOptions.audioOnly=i),c.sessionDescriptionHandlerModifiers=[qo],i&&c.sessionDescriptionHandlerModifiers.push(wo),o&&(o.invitePromise=o.invite(c).catch((e=>{Ko.warn("sdk webrtc creating call, error",e)}))),o}answer(e,t){if(Ko.info("sdk webrtc answer call",{clientId:this.clientId,id:e.id,enableVideo:t}),!e||!e.accept){const e="No session to answer, or not an invitation";return Ko.warn(e),Promise.reject(new Error(e))}const i={sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1)};return this._accept(e,i).then((()=>{if(e.isCanceled){const t="accepted a canceled session (or was canceled during the accept phase).";throw Ko.error(t,{id:e.id}),this.onCallEnded(e),new gc(t)}Ko.info("sdk webrtc answer, accepted."),this._onAccepted(e)})).catch((t=>{throw Ko.error(`answer call error for ${e?e.id:"n/a"}`,t),t}))}async hangup(e){const{state:t,id:i}=e;Ko.info("sdk webrtc hangup call",{clientId:this.clientId,id:i,state:t});try{this._stopSendingStats(e),this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)];const i=e instanceof yr,n={[mi.Initial]:i?this._cancel.bind(this,e):this._reject.bind(this,e),[mi.Establishing]:i?this._cancel.bind(this,e):this._reject.bind(this,e),[mi.Established]:this._bye.bind(this,e)};return n[t]?await n[t]():await this._bye(e)}catch(e){Ko.warn("sdk webrtc hangup, error",e)}return Promise.resolve(null)}async getStats(e){const t=e.sessionDescriptionHandler?.peerConnection;return t?t.getStats(null):null}startNetworkMonitoring(e,t=1e3){const i=this.getSipSessionId(e);Ko.info("starting network inspection",{id:i,clientId:this.clientId}),this.sessionNetworkStats[i]=[],this.networkMonitoringInterval[i]=setInterval((()=>this._fetchNetworkStats(i)),t)}stopNetworkMonitoring(e){const t=this.getSipSessionId(e),i=t in this.networkMonitoringInterval;Ko.info("stopping network inspection",{clientId:this.clientId,id:t,exists:i}),i&&(clearInterval(this.networkMonitoringInterval[t]),delete this.networkMonitoringInterval[t],delete this.sessionNetworkStats[t])}async reject(e){Ko.info("sdk webrtc reject call",{clientId:this.clientId,id:e.id});try{if(e instanceof vr)return this._reject(e);if(e instanceof yr)return this._cancel(e)}catch(e){Ko.warn("Error when rejecting call",e.message,e.stack)}}async close(e=!1){if(Ko.info("sdk webrtc closing client",{clientId:this.clientId,userAgent:!!this.userAgent,force:e}),this.forceClosed=e,this._cleanupMedia(),this.connectionPromise=null,Object.values(this.audioElements).forEach((e=>{e.srcObject=null,e.pause()})),this.audioElements={},this.userAgent){this.stopHeartbeat(),this.userAgent&&(this.userAgent.delegate=void 0),this.userAgent.stateChange.removeAllListeners(),await this._disconnectTransport(e),this._cleanupRegister();try{this.userAgent.transport.connectReject=()=>{},this.userAgent.stop().catch(console.error)}catch(e){}this.userAgent=null,Ko.info("sdk webrtc client closed",{clientId:this.clientId})}}getNumber(e){return e?e.remoteIdentity.uri._normal.user:null}mute(e){Ko.info("sdk webrtc mute",{id:e.id}),this._toggleAudio(e,!0)}unmute(e){Ko.info("sdk webrtc unmute",{id:e.id}),this._toggleAudio(e,!1)}isAudioMuted(e){if(!e||!e.sessionDescriptionHandler)return!1;let t=!0;const i=e.sessionDescriptionHandler.peerConnection;if(!i)return!1;if(i.getSenders){if(!i.getSenders().length)return!1;i.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(t=t&&!e.track.enabled)}))}else{if(!i.getLocalStreams().length)return!1;i.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{t=t&&!e.enabled}))}))}return t}toggleCameraOn(e){Ko.info("sdk webrtc toggle camera on",{id:e.id}),this._toggleVideo(e,!1)}toggleCameraOff(e){Ko.info("sdk webrtc toggle camera off",{id:e.id}),this._toggleVideo(e,!0)}hold(e,t=!1,i=!1){const n=this.getSipSessionId(e),r=i||this.hasLocalVideo(n);if(Ko.info("sdk webrtc hold",{sessionId:n,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:r}),n in this.heldSessions)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();this.heldSessions[n]={hasVideo:r,isConference:t},this.mute(e),e.sessionDescriptionHandlerOptionsReInvite={hold:!0,conference:t};const s=this.getMediaConfiguration(!1,t);return this._isWeb()||(s.sessionDescriptionHandlerModifiers=[Eo]),s.sessionDescriptionHandlerOptions={constraints:s.constraints,hold:!0,conference:t},e.sessionDescriptionHandler&&(e.sessionDescriptionHandler.localMediaStreamConstraints=s.constraints),e.invite(s).catch((e=>{Ko.warn("sdk webrtc re-invite during hold, error",e)}))}unhold(e,t=!1){const i=this.getSipSessionId(e),n=i in this.heldSessions&&this.heldSessions[i].hasVideo;if(Ko.info("sdk webrtc unhold",{sessionId:i,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:n}),e.pendingReinvite)return Promise.resolve();this.unmute(e),delete this.heldSessions[this.getSipSessionId(e)],e.sessionDescriptionHandlerOptionsReInvite={hold:!1,conference:t};const r=this.getMediaConfiguration(!1,t);return this._isWeb()||(r.sessionDescriptionHandlerModifiers=[]),r.sessionDescriptionHandlerOptions={constraints:r.constraints,hold:!1,conference:t},e.invite(r).catch((e=>{Ko.warn("sdk webrtc re-invite during resume, error",e)}))}async upgradeToVideo(e,t,i){const n=e.sessionDescriptionHandler?.peerConnection;let r;if(i){const e=n?.getTransceivers()||[],t=((e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1})(e,(e=>null===e.sender.track&&e.mid&&-1===e.mid.indexOf("video")));r=-1!==t?e[t].sender:null}else r=n&&n.getSenders&&n.getSenders().find((e=>null===e.track));if(!r)return;const s=await this.getStreamFromConstraints(t);if(!s)return void console.warn(`Can't create media stream with: ${JSON.stringify(t||{})}`);if(t&&!t.audio){const t=e.sessionDescriptionHandler?.localMediaStream,i=t.getTracks().find((e=>"audio"===e.kind));i&&s.addTrack(i)}const a=s.getVideoTracks()[0];return a&&r.replaceTrack(a),this.setLocalMediaStream(this.getSipSessionId(e),s),s}downgradeToAudio(e){const t=e.sessionDescriptionHandler,i=t?.localMediaStream,n=t?.peerConnection,r=i.getVideoTracks();n?.getSenders&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).forEach((e=>{e.replaceTrack(null)})),r.forEach((e=>{e.enabled=!1,e.stop(),i.removeTrack(e)}))}async getStreamFromConstraints(e,t=!1){const i=e&&e.video,{constraints:n}=this.getMediaConfiguration(i,t,e);let r=null;try{r=await Bo(n)}catch(e){}return r?(r.local=!0,r):null}getHeldSession(e){return this.heldSessions[e]}isCallHeld(e){return this.getSipSessionId(e)in this.heldSessions}isVideoRemotelyHeld(e){const t=this.getPeerConnection(e),i=t&&t.remoteDescription?t.remoteDescription.sdp:null;if(!i)return!1;const n=(e=>{const t=To.parse(e).media.find((e=>"video"===e.type));return t?t.direction:null})(i);return"sendonly"===n}sendDTMF(e,t){return!!e.sessionDescriptionHandler&&(Ko.info("Sending DTMF",{id:this.getSipSessionId(e),tone:t}),e.sessionDescriptionHandler.sendDtmf(t))}message(e,t){const i=this._makeURI(e);if(!this.userAgent||!i)return void Ko.warn("Null value on message",{uri:i,userAgent:this.userAgent});new Sr(this.userAgent,i,t).message()}transfer(e,t){this.hold(e),Ko.info("Transfering a session",{id:this.getSipSessionId(e),target:t});const i={requestDelegate:{onAccept:()=>{this.hangup(e)}}};setTimeout((()=>{const n=this._makeURI(t);n?e.refer(n,i):Ko.warn("transfer timeout: null URI")}),50)}atxfer(e){this.hold(e),Ko.info("webrtc transfer started",{id:this.getSipSessionId(e)});const t={newSession:null,init:async i=>{Ko.info("webrtc transfer initialized",{id:this.getSipSessionId(e),target:i}),t.newSession=await this.call(i)},complete:()=>{Ko.info("webrtc transfer completed",{id:this.getSipSessionId(e),referId:this.getSipSessionId(t.newSession)}),e.refer(t.newSession)},cancel:()=>{this.hangup(t.newSession),this.unhold(e)}};return t}sendMessage(e=null,t,i="text/plain"){if(e){Ko.info("send WebRTC message",{sipId:e.id,contentType:i});try{e.message({requestOptions:{body:{content:t,contentType:i,contentDisposition:""}}})}catch(e){console.warn(e)}}}pingServer(){if(!this.isConnected())return;const e=this.userAgent?.userAgentCore,t=this._makeURI(this.config.authorizationUser||""),i=new Mn("sip","",this.config.host);if(t){const n=e?.makeOutgoingRequestMessage("OPTIONS",i,t,i,{});if(n)return e?.request(n);Ko.warn("pingServer: null message")}Ko.warn("pingServer: null fromURI")}getState(){return this.userAgent?Go[this.userAgent.state]:Cr.Stopped}getContactIdentifier(){return this.userAgent?`${this.userAgent.configuration.contactName}/${this.userAgent.contact.uri}`:null}isFirefox(){return this._isWeb()&&navigator.userAgent.toLowerCase().indexOf("firefox")>-1}changeAudioOutputVolume(e){Ko.info("Changing audio output volume",{volume:e}),Object.values(this.audioElements).forEach((t=>{t instanceof HTMLAudioElement&&(t.volume=e)})),this.audioOutputVolume=e}async changeAudioOutputDevice(e){Ko.info("Changing audio output device",{id:e}),this.audioOutputDeviceId=e;const t=[];Object.values(this.audioElements).forEach((i=>t.push(i.setSinkId(e)))),await Promise.allSettled(t)}async changeAudioInputDevice(e,t,i){const n=this.getAudioDeviceId();if(Ko.info("setting audio input device",{id:e,currentId:n,session:!!t}),!i&&e===n)return null;let r=e;if("default"===e&&navigator.mediaDevices){const e=await navigator.mediaDevices.enumerateDevices(),t=e.find((e=>"default"===e.deviceId));if(t){const s=t.label.replace("Default - ",""),a=e.find((e=>e.label===s));if(a&&(r=a.deviceId,!i&&r===n))return null}}if(this.audio&&(this.audio={deviceId:{exact:r}}),t&&navigator.mediaDevices){const e=t.sessionDescriptionHandler,i=e?.peerConnection,n={audio:{deviceId:{exact:r}}},s=await navigator.mediaDevices.getUserMedia(n),a=s.getAudioTracks()[0],o=i&&i.getSenders&&i.getSenders().find((e=>a&&e&&e.track&&e.track.kind===a.kind));return o&&(o.track&&(a.enabled=o.track.enabled),o.replaceTrack(a)),s}return null}async changeVideoInputDevice(e,t){if(this.setVideoInputDevice(e),t)return this.changeSessionVideoInputDevice(e,t)}setVideoInputDevice(e){const t=this.getVideoDeviceId();if(Ko.info("setting video input device",{id:e,currentId:t}),e===t)return null;const i="object"==typeof this.video?this.video:{};this.video={...i,deviceId:{exact:e}}}changeSessionVideoInputDevice(e,t){if(!this.sessionWantsToDoVideo(t))return Promise.resolve();const i=t.sessionDescriptionHandler.peerConnection,n=this.getSipSessionId(t),r=this.getLocalStream(n);Ko.info("changing video input device",{id:e,sessionId:n}),r&&r.getVideoTracks().filter((e=>e.enabled)).forEach((e=>e.stop()));const s={video:!e||{deviceId:{exact:e}}};return navigator.mediaDevices.getUserMedia(s).then((async e=>{const t=e.getVideoTracks()[0];let r=i&&i.getSenders&&i.getSenders().find((e=>t&&e&&e.track&&e.track.kind===t.kind)),s=!1;return r||(r=i&&i.getSenders&&i.getSenders().find((e=>!e.track))),r&&(s=!!r.track&&r.track.enabled,t.enabled=s,s||t.stop(),r.replaceTrack(s?t:null)),this.eventEmitter.emit("onVideoInputChange",e),this.setLocalMediaStream(n,e),e}))}getAudioDeviceId(){return this.audio&&"object"==typeof this.audio&&"deviceId"in this.audio?this.audio.deviceId?.exact:void 0}getVideoDeviceId(){return this.video&&"object"==typeof this.video&&"deviceId"in this.video?this.video.deviceId?.exact:void 0}reinvite(e,t=null,i=!1,n=!1,r=!1){if(!e)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();const s=this.isAudioMuted(e),a=t?t.video:this.sessionWantsToDoVideo(e),o=t&&t.screen,c=t&&t.desktop;if(Ko.info("Sending reinvite",{clientId:this.clientId,id:this.getSipSessionId(e),newConstraints:t,conference:i,audioOnly:n,wasMuted:s,shouldDoVideo:a,shouldDoScreenSharing:o,desktop:c}),t&&t.video){const t=e.sessionDescriptionHandlerModifiersReInvite;e.sessionDescriptionHandlerModifiersReInvite=t.filter((e=>e!==wo))}e.sessionDescriptionHandlerOptionsReInvite={...e.sessionDescriptionHandlerOptionsReInvite,conference:i,audioOnly:n};const{constraints:d}=this.getMediaConfiguration(a,i,t);return e.invite({requestDelegate:{onAccept:t=>(e instanceof yr&&e.outgoingRequestMessage.body?e.outgoingRequestMessage.body.body=t.message.body:e instanceof vr&&(e.incomingInviteRequest.message.body=t.message.body),Ko.info("on re-INVITE accepted",{id:this.getSipSessionId(e),wasMuted:s,shouldDoScreenSharing:o}),this.updateRemoteStream(this.getSipSessionId(e),!1),s&&this.mute(e),this._onAccepted(e,t.session,!1,!1),o&&this.eventEmitter.emit(dc,e,t,c),this.eventEmitter.emit(oc,e,t))},sessionDescriptionHandlerModifiers:[qo],requestOptions:{extraHeaders:["Subject: "+(o?"screenshare":"upgrade-video")]},sessionDescriptionHandlerOptions:{constraints:d,conference:i,audioOnly:n,offerOptions:{iceRestart:r}}})}async getUserMedia(e){const t={audio:this._getAudioConstraints(),video:this._getVideoConstraints(e.video)};return navigator.mediaDevices.getUserMedia(t)}getPeerConnection(e){const t=this.sipSessions[e];return t&&t.sessionDescriptionHandler?t.sessionDescriptionHandler.peerConnection:null}getLocalStream(e){const t=this.sipSessions[e];return t?.sessionDescriptionHandler?.localMediaStream||null}getLocalTracks(e){const t=this.getLocalStream(e);return t?t.getTracks():[]}hasLocalVideo(e){return this.getLocalTracks(e).some(this._isVideoTrack)}hasALocalVideoTrack(e){return this.getLocalTracks(e).some((e=>"video"===e.kind))}getLocalVideoStream(e){return this.hasLocalVideo(e)?this.getLocalStream(e):null}getRemoteStream(e){const t=this.sipSessions[e];return t?.sessionDescriptionHandler?.remoteMediaStream||null}getRemoteTracks(e){const t=this.getRemoteStream(e);return t?t.getTracks():[]}hasRemoteVideo(e){return this.getRemoteTracks(e).some(this._isVideoTrack)}hasARemoteVideoTrack(e){return this.getRemoteTracks(e).some((e=>"video"===e.kind))}getRemoteVideoStream(e){return this.isVideoRemotelyHeld(e)?null:this.hasRemoteVideo(e)?this.getRemoteStream(e):null}getRemoteVideoStreamFromPc(e){const t=this.getPeerConnection(e);return t?t.getRemoteStreams().find((e=>!!e.getVideoTracks().length)):null}hasVideo(e){return this.hasLocalVideo(e)||this.hasRemoteVideo(e)}hasAVideoTrack(e){return this.hasALocalVideoTrack(e)||this.hasARemoteVideoTrack(e)}getSipSessionId(e){if(!e)return"";const t=e.message;return t?.callId?t.callId.substring(0,36):e instanceof yr&&e.outgoingRequestMessage?e.outgoingRequestMessage.callId.substring(0,36):(e.id||"").substring(0,36)}async waitForRegister(){return new Promise((e=>this.on(zo,e)))}sessionWantsToDoVideo(e){if(!e)return!1;const{body:t}=e.request||e;return(e=>!!e&&!!To.parse(e).media.find((e=>"video"===e.type&&e.port>10&&(!e.direction||"inactive"!==e.direction))))("object"==typeof t&&t?t.body:t)}hasHeartbeat(){return this.heartbeat.hasHeartbeat}startHeartbeat(){Ko.info("sdk webrtc start heartbeat",{userAgent:!!this.userAgent,clientId:this.clientId}),this.userAgent?(this.eventEmitter.off(tc,this._boundOnHeartbeat),this.eventEmitter.on(tc,this._boundOnHeartbeat),this.heartbeat.start()):this.heartbeat.stop()}stopHeartbeat(){Ko.info("sdk webrtc stop heartbeat",{clientId:this.clientId}),this.heartbeat.stop()}setOnHeartbeatTimeout(e){this.heartbeatTimeoutCb=e}setOnHeartbeatCallback(e){this.heartbeatCb=e}onCallEnded(e){this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)],this._stopSendingStats(e),this.stopNetworkMonitoring(e)}attemptReconnection(){Ko.info("attempt reconnection",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent&&this.userAgent.attemptReconnection()}storeSipSession(e){const t=this.getSipSessionId(e);Ko.info("storing sip session",{id:t,clientId:this.clientId}),this.sipSessions[t]=e}getSipSession(e){return e in this.sipSessions?this.sipSessions[e.substring(0,36)]:null}getSipSessionIds(){return Object.keys(this.sipSessions)}setLocalMediaStream(e,t){const i=this.sipSessions[e];i&&(Ko.info("setting local media stream",{sipSessionId:e,tracks:t?t.getTracks():null}),i.sessionDescriptionHandler&&(i.sessionDescriptionHandler._localMediaStream=t))}async updateLocalStream(e,t){const i=this.sipSessions[e];if(!i)return;const n=this.getLocalStream(e);Ko.info("updating local stream",{sipSessionId:e,oldStream:!!n,tracks:t.getTracks()}),n&&this._cleanupStream(n),this.setLocalMediaStream(e,t),await this._setupMedias(i,t)}updateRemoteStream(e,t=!0){const i=this.getRemoteStream(e),n=this.getPeerConnection(e);Ko.info("Updating remote stream",{sessionId:e,tracks:i?i.getTracks():null,receiverTracks:n&&n.getReceivers?n.getReceivers().map((e=>e.track)):null}),n&&i&&(i.getTracks().forEach((e=>{(t||"video"===e.kind)&&i.removeTrack(e)})),n.getReceivers&&n.getReceivers().forEach((e=>{(t||"video"===e.track.kind)&&i.addTrack(e.track)})))}getMediaConfiguration(e,t=!1,i=null){const n=!(!i||!("screen"in i))&&i.screen,r=!(!i||!("desktop"in i))&&i.desktop,s=!i||!("audio"in i)||i.audio,a=i&&"object"==typeof i.video?i.video.mandatory:{};return Ko.info("Retrieving media a configuration",{enableVideo:e,screenSharing:n,isDesktop:r,withAudio:s,constraints:i}),{constraints:{audio:n?!r:!!s&&this._getAudioConstraints(),video:n?r?{mandatory:{chromeMediaSource:"desktop",...a||{}}}:{cursor:"always"}:this._getVideoConstraints(e),screen:n,desktop:r,conference:t},enableVideo:e,conference:t,offerOptions:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:e,mandatory:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:e}}}}isConference(e){return e in this.conferences}async createAudioElementFor(e){const t=document.createElement("audio");return t.setAttribute("id",`audio-${e}`),Ko.info("creating audio element",{sessionId:e,audioOutputDeviceId:this.audioOutputDeviceId}),this.audioOutputDeviceId&&await t.setSinkId(this.audioOutputDeviceId),document.body&&document.body.appendChild(t),this.audioElements[e]=t,t.volume=this.audioOutputVolume,t.autoplay=!0,t}_onTransportError(){Ko.error("on transport error"),this.eventEmitter.emit(ec),this.attemptReconnection()}enableLogger(e){this.userAgent&&(this.userAgent?.transport&&(this.userAgent.transport.configuration.traceSip=!0),this.userAgent.loggerFactory.builtinEnabled=!0,this.userAgent.loggerFactory.level=3,this.userAgent.loggerFactory.connector=e)}_onHeartbeat(e){const t=e&&"object"==typeof e?e.data:e;t&&-1!==t.indexOf("200 OK")&&this.hasHeartbeat()&&(Ko.info("on heartbeat received from Asterisk",{hasHeartbeat:this.hasHeartbeat()}),this.heartbeat.onHeartbeat(),this.heartbeatCb&&this.heartbeatCb())}async _onHeartbeatTimeout(){if(Ko.warn("sdk webrtc heartbeat timed out",{userAgent:!!this.userAgent,cb:!!this.heartbeatTimeoutCb}),this.heartbeatTimeoutCb&&this.heartbeatTimeoutCb(),this.userAgent&&this.userAgent.transport){const e=this.userAgent.transport;if(!e.transitioningState&&!e.disconnectPromise)try{await this.userAgent.transport.disconnect()}catch(e){Ko.error("Transport disconnection after heartbeat timeout, error",e)}this._onTransportError()}}_isWeb(){return"object"==typeof window&&"object"==typeof document}_isVideoTrack(e){return"video"===e.kind&&"live"===e.readyState}_hasAudio(){return this.hasAudio}_getAudioConstraints(){return!this.audio?.deviceId?.exact||this.audio}_getVideoConstraints(e=!1){return!!e&&(!this.video?.deviceId?.exact||this.video)}_connectIfNeeded(){return Ko.info("connect if needed, checking",{connected:this.isConnected(),clientId:this.clientId}),this.userAgent||(Ko.info("need to recreate User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),this.isConnected()?(Ko.info("webrtc sdk, already connected"),Promise.resolve()):this.isConnecting()?(Ko.info("webrtc sdk, already connecting..."),this.connectionPromise=this.userAgent.transport.connectPromise,Promise.resolve(this.connectionPromise)):this.connectionPromise?(Ko.info("webrtc sdk, connection promise connecting..."),this.connectionPromise):(Ko.info("WebRTC UA needs to connect"),this.userAgent&&this.userAgent.state!==Cr.Stopped&&this.userAgent.transitionState(Cr.Stopped),this.userAgent.transport&&this.userAgent.transport.state!==Er.Disconnected&&this.userAgent.transport.transitionState(Er.Disconnected),this.connectionPromise=this.userAgent.start().catch(console.error),this.connectionPromise)}_buildConfig(e,t){if(!t)return new Promise((t=>t(e)));const i=new nn({server:`${e.host}:${String(e.port||443)}`});return i.setToken(t.token),i.setRefreshToken(t.refreshToken),i.confd.getUserLineSipFromToken(t.uuid).then((t=>({authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e.host}`,...e})))}_createUaOptions(e={}){let{host:t}=this.config,i=this.config.port||443;if(this.config.websocketSip){const e=this.config.websocketSip.split(":");[t]=e,i=Number(e[1])}const{userUuid:n}=this.config,r={noAnswerTimeout:86400,authorizationUsername:this.config.authorizationUser,authorizationPassword:this.config.password,displayName:this.config.displayName,hackIpInContact:!0,contactParams:{transport:"wss"},logBuiltinEnabled:this.config.log?this.config.log.builtinEnabled:null,logLevel:this.config.log?this.config.log.logLevel:null,logConnector:this.config.log?this.config.log.connector:null,uri:this._makeURI(this.config.authorizationUser||""),userAgentString:this.config.userAgentString||"wazo-sdk",reconnectionAttempts:1e4,reconnectionDelay:5,sessionDescriptionHandlerFactory:(e,t={})=>{const i=e.userAgent.getLogger("sip.WazoSessionDescriptionHandler"),n=this._isWeb(),r="peerConnectionOptions"in t&&t.peerConnectionOptions.iceGatheringTimeout||3e3,s={...t,iceGatheringTimeout:r,peerConnectionConfiguration:{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require",...t.peerConnectionConfiguration||{}}};return new Uo(i,Bo,s,n,e)},transportOptions:{traceSip:e?.traceSip||!1,wsServers:`wss://${t}:${i}/api/asterisk/ws${n?`?userUuid=${n}`:""}`},sessionDescriptionHandlerFactoryOptions:{modifiers:[qo],alwaysAcquireMediaFirst:this.isFirefox(),constraints:{audio:this._getAudioConstraints(),video:this._getVideoConstraints()},peerConnectionOptions:{iceCheckingTimeout:this.config.iceCheckingTimeout||1e3,iceGatheringTimeout:this.config.iceCheckingTimeout||1e3,rtcConfiguration:{rtcpMuxPolicy:"require",iceServers:fc.getIceServers(this.config.host),...this._getRtcOptions(),...e?.peerConnectionOptions||{}}},peerConnectionConfiguration:{rtcpMuxPolicy:"require",iceServers:fc.getIceServers(this.config.host),...e?.peerConnectionOptions||{}}}};return delete e?.traceSip,{...r,...e}}_getRtcOptions(){return{mandatory:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:!1}}}_setupSession(e){const t=this.getSipSessionId(e);e.delegate||(e.delegate={}),e.delegate.onSessionDescriptionHandler=e=>{e.on("error",(e=>{this.eventEmitter.emit(cc,e)})),e.peerConnectionDelegate={onicecandidateerror:e=>{Ko.error("on icecandidate error",{address:e.address,port:e.port,errorCode:e.errorCode,errorText:e.errorText,url:e.url})}}};const i=e.onInviteRequest.bind(e);let n=!1;e.onInviteRequest=e=>{n=this.hasARemoteVideoTrack(t),i(e)},e.delegate.onInvite=async i=>{let r=null,s=null;return e.assertedIdentity&&(s=e.assertedIdentity.uri.normal.user,r=e.assertedIdentity.displayName||s),Ko.info("re-invite received",{updatedCalleeName:r,updatedNumber:s,hadRemoteVideo:n}),e instanceof vr?e.incomingInviteRequest.message.body=i.body:e instanceof yr&&e.outgoingInviteRequest.message.body&&(e.outgoingInviteRequest.message.body.body=i.body),this.updateRemoteStream(t,!1),await this._setupMedias(e),this.eventEmitter.emit(oc,e,i,r,s,n)}}async _onProgress(e,t=!1){await this._setupMedias(e);const i=this.getSipSessionId(e).substr(0,20);this.updateRemoteStream(i),Ko.info("progress received",{sessionId:i,early:t}),this.eventEmitter.emit(t?ac:sc,e)}async _onAccepted(e,t,i=!0,n=!0){Ko.info("on call accepted",{id:e.id,clientId:this.clientId,remoteTag:e.remoteTag}),this.storeSipSession(e),await this._setupMedias(e),this.updateRemoteStream(this.getSipSessionId(e),n);const r=e.sessionDescriptionHandler?.peerConnection,s=t=>{const i=this._isAudioOnly(e),{kind:n,label:r,readyState:s,id:a,muted:o}=t.track;Ko.info("on track event",{isAudioOnly:i,kind:n,label:r,readyState:s,id:a,muted:o}),i&&"video"===n&&t.track.stop(),this.eventEmitter.emit(rc,e,t)},a=e.sessionDescriptionHandler;a?.peerConnection&&a.peerConnection.addEventListener("track",s),a.remoteMediaStream.onaddtrack=s,r&&(r.oniceconnectionstatechange=()=>{Ko.info("on ice connection state changed",{state:r.iceConnectionState}),"disconnected"===r.iceConnectionState&&this.eventEmitter.emit(hc)}),i&&this.eventEmitter.emit(ic,e,t),this._startSendingStats(e)}_isAudioOnly(e){return Boolean(e.sessionDescriptionHandlerModifiersReInvite.find((e=>e===wo)))}async _setupMedias(e,t=null){if(!this._isWeb())return void Ko.info("Setup media on mobile, no need to setup html element, bailing");const i=this.getSipSessionId(e),n=this.isConference(i);if(i in this.audioElements)return void Ko.info("html element already exists for session",{sessionId:i});this._hasAudio()&&this._isWeb()&&!(i in this.audioElements)&&await this.createAudioElementFor(i);const r=this.audioElements[i],s=this.sipSessions[e.callId],a=this.getRemoteStream(i),o=s?.sessionDescriptionHandler,c=o?o.remoteMediaStream:null,d=t||a||c;if(!d)return void Ko.info("Setup media no stream to attach, bailing");const l=r.currentTime>0&&!r.paused&&!r.ended&&r.readyState>2;Ko.info("setting up media",{sessionId:i,streams:{new:!!t,remove:!!a,early:!!c},hasAudio:this._hasAudio(),isConference:n,shouldPause:l}),n||(l&&r.pause(),r.srcObject=d,r.volume=this.audioOutputVolume,r.play().catch((()=>{})))}_cleanupMedia(e){const t=this.getSipSessionId(e),i=this.getLocalStream(t);i&&this._cleanupStream(i);const n=e=>{const t=this.audioElements[e];t&&(t.pause(),t.parentNode&&t.parentNode.removeChild(t),t.srcObject=null,delete this.audioElements[e])};this._hasAudio()&&this._isWeb()&&(e?n(this.getSipSessionId(e)):Object.keys(this.audioElements).forEach((e=>n(e))))}_cleanupStream(e){e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))}_toggleAudio(e,t){const i=e.sessionDescriptionHandler,n=i?.peerConnection||null;n&&(n.getSenders?n.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(e.track.enabled=!t)})):n.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{e.enabled=!t}))})))}_toggleVideo(e,t){const i=e.sessionDescriptionHandler,n=i?.peerConnection;n?.getSenders?n.getSenders().forEach((e=>{e&&e.track&&"video"===e.track.kind&&(e.track.enabled=!t)})):n.getLocalStreams().forEach((e=>{e.getVideoTracks().forEach((e=>{e.enabled=!t}))}))}_getRemoteStream(e){let t=null;return e&&e.getReceivers?(t="undefined"!=typeof global&&global.window&&global.window.MediaStream?new global.window.MediaStream:new window.MediaStream,e.getReceivers().forEach((e=>{const{track:i}=e;i&&t&&t.addTrack(i)}))):e&&([t]=e.getRemoteStreams()),t}_cleanupRegister(){this.registerer&&(this.registerer.stateChange.removeAllListeners(),this.registerer=null)}_startSendingStats(e){const t=e.sessionDescriptionHandler.peerConnection;if(!t)return;const i=this.getSipSessionId(e);$o(t,(e=>{const{results:t,internal:n,nomore:r,...s}=e;this.statsIntervals[i]=r,Wo.trace("stats",{sessionId:i,...s})}),5e3)}_stopSendingStats(e){const t=this.getSipSessionId(e);Ko.trace("Check for stopping stats",{sessionId:t,ids:Object.keys(this.statsIntervals)}),t in this.statsIntervals&&(Ko.trace("Stop sending stats for call",{sessionId:t}),this.statsIntervals[t](),delete this.statsIntervals[t])}_makeURI(e){return bs.makeURI(`sip:${e}@${this.config.host}`)}async _disconnectTransport(e=!1){const t=this.userAgent?.transport;if(e&&t)return t.disconnectResolve=()=>{},void(t._ws&&t._ws.close(1e3));if(t&&!t.disconnectPromise)try{await t.disconnect()}catch(e){Ko.error("WebRTC transport disconnect, error",e)}}async _fetchNetworkStats(e){const t=this.getSipSession(e),i=t?await this.getStats(t):null;if(!i||!(e in this.sessionNetworkStats))return Promise.resolve(null);const n={audioBytesSent:0,videoBytesSent:0,videoBytesReceived:0,audioBytesReceived:0},r=this.sessionNetworkStats[e].length,s=this.sessionNetworkStats[e][r-1],a=s?s.audioBytesSent:0,o=s?s.audioContentSent:0,c=s?s.videoBytesSent:0,d=s?s.audioBytesReceived:0,l=s?s.audioContentReceived:0,h=s?s.videoBytesReceived:0,u=s?s.transportSent:0,p=s?s.transportReceived:0;let g=0,f=0,m=0,v=0,y=0,S=0,b=0,w=0,E=0;i.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.kind&&(g+=Number(e.bytesSent)+Number(e.headerBytesSent),m+=Number(e.bytesSent)),"remote-outbound-rtp"===e.type&&"audio"===e.kind&&(g+=Number(e.bytesSent)),"outbound-rtp"===e.type&&"video"===e.kind&&(y+=Number(e.bytesSent)+Number(e.headerBytesSent)),"inbound-rtp"===e.type&&"audio"===e.kind&&(E+=Number(e.packetsLost),n.packetsReceived=Number(e.packetsReceived),f+=Number(e.bytesReceived)+Number(e.headerBytesReceived),v+=Number(e.bytesReceived)),"inbound-rtp"===e.type&&"video"===e.kind&&(S+=Number(e.bytesReceived)+Number(e.headerBytesReceived)),"outbound-rtp"===e.type&&"video"===e.kind&&("framesPerSecond"in e&&(n.framesPerSecond=Number(e.framesPerSecond)),"framerateMean"in e&&(n.framesPerSecond=Math.round(e.framerateMean))),"remote-inbound-rtp"===e.type&&"audio"===e.kind&&(E+=Number(e.packetsLost),n.roundTripTime=Number(e.roundTripTime),n.jitter=Number(e.jitter)),"remote-inbound-rtp"===e.type&&"video"===e.kind&&(E+=Number(e.packetsLost)),"transport"===e.type&&(b+=Number(e.bytesSent),w+=Number(e.bytesReceived))})),n.packetsLost=E,n.totalAudioBytesSent=g,n.audioBytesSent=g-a,n.totalAudioBytesReceived=f-d,n.audioBytesReceived=f,n.totalAudioContentSent=m,n.audioContentSent=m-o,n.totalAudioBytesReceived=v-l,n.audioContentReceived=v,n.totalVideoBytesSent=y,n.videoBytesSent=y-c,n.totalVideoBytesReceived=S,n.videoBytesReceived=S-h,n.totalTransportSent=b-u,n.transportSent=b,n.totalTransportReceived=w,n.transportReceived=w-p,n.bandwidth=n.audioBytesSent+n.audioBytesReceived+n.videoBytesSent+n.videoBytesReceived+n.transportReceived+n.transportSent,this.sessionNetworkStats[e]&&(this.eventEmitter.emit(lc,t,n,this.sessionNetworkStats[e]),e in this.sessionNetworkStats&&this.sessionNetworkStats[e].push(n))}async _accept(e,t={}){if(e.state===mi.Terminated||e.state===mi.Terminating){const t="Trying to accept a terminated sipSession.";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(e.state!==mi.Initial){const t="Trying to accept a non Initial sipSession.";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(!e.incomingInviteRequest.acceptable){const t="Trying to reject a non `acceptable` session";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}try{return await e.accept(t)}catch(e){Ko.warn("Session accept, error",e)}}async _reject(e,t={}){if(e.state===mi.Initial||e.state===mi.Establishing)if(e.incomingInviteRequest.rejectable)try{return await e.reject(t)}catch(e){Ko.warn("Session reject, error",e)}else Ko.warn("Trying to reject a non `rejectable` session",{state:e.state,sessionId:e.id});else Ko.warn("Trying to reject a session in a wrong state",{state:e.state,sessionId:e.id})}async _cancel(e,t={}){if(e.state===mi.Initial||e.state===mi.Establishing)try{return await e.cancel(t)}catch(e){Ko.warn("Session cancel, error",e)}else Ko.warn("Trying to cancel a session in a wrong state",{state:e.state,sessionId:e.id})}async _bye(e,t={}){if(e.state!==mi.Established)return Ko.warn("Trying to end a session in a wrong state",{state:e.state,sessionId:e.id}),null;try{return await e.bye(t)}catch(e){Ko.warn("Session bye, error",e)}return null}}class mc extends Error{constructor(e="Sorry your user is not configured to support video conference"){super(e),this.name="SFUNotAvailableError"}}const vc=B.loggerFor("simple-phone"),yc=B.loggerFor("sip.js"),Sc=B.loggerFor("sip"),bc=["Received WebSocket text message:","Sending WebSocket message:"];class wc extends Fi{client;phone;session;sipLine;SessionState;ON_USER_AGENT;ON_REGISTERED;ON_UNREGISTERED;ON_PROGRESS;ON_CALL_ACCEPTED;ON_CALL_ANSWERED;ON_CALL_INCOMING;ON_CALL_OUTGOING;ON_CALL_MUTED;ON_CALL_UNMUTED;ON_CALL_RESUMED;ON_CALL_HELD;ON_CALL_UNHELD;ON_CAMERA_DISABLED;ON_CAMERA_RESUMED;ON_CALL_CANCELED;ON_CALL_FAILED;ON_CALL_REJECTED;ON_CALL_ENDED;ON_CALL_ENDING;ON_MESSAGE;ON_REINVITE;ON_TRACK;ON_AUDIO_STREAM;ON_VIDEO_STREAM;ON_REMOVE_STREAM;ON_SHARE_SCREEN_STARTED;ON_SHARE_SCREEN_ENDING;ON_SHARE_SCREEN_ENDED;ON_TERMINATE_SOUND;ON_PLAY_RING_SOUND;ON_PLAY_INBOUND_CALL_SIGNAL_SOUND;ON_PLAY_HANGUP_SOUND;ON_PLAY_PROGRESS_SOUND;ON_VIDEO_INPUT_CHANGE;ON_CALL_ERROR;ON_MESSAGE_TRACK_UPDATED;ON_NETWORK_STATS;ON_CHAT;ON_SIGNAL;ON_DISCONNECTED;ON_EARLY_MEDIA;MESSAGE_TYPE_CHAT;MESSAGE_TYPE_SIGNAL;constructor(){super(),Object.keys(ga).forEach((e=>{this[e]=ga[e]})),this.SessionState=mi}async connect(e={},t=null){const i=e;if(this.phone)return void(i.media&&this.phone.setMediaConstraints(i.media));const n=Ol.Auth.getHost(),r=Ol.Auth.getSession();if(!n||!r)throw new Error("Please connect to the server using `Wazo.Auth.logIn` or `Wazo.Auth.authenticate` before using Room.connect().");if(this.session=r,this.sipLine=t||this.getPrimaryWebRtcLine(),!this.sipLine)throw new Error("Sorry, no sip lines found for this user");i.userUuid=r.uuid||"",this.connectWithCredentials(n,this.sipLine,r.displayName(),i)}connectWithCredentials(e,t,i,n={}){if(this.phone)return;const[r,s=443]=e.split(":"),a=n;a.media=a.media||{audio:!0,video:!1},a.uaConfigOverrides=a.uaConfigOverrides||{},B.enabled&&(a.uaConfigOverrides.traceSip=!0,a.log=a.log||{},a.log.builtinEnabled=!1,a.log.logLevel="debug",a.log.connector=this._logConnector),this.client=new fc({host:r,port:"string"==typeof s?parseInt(s,10):s,displayName:i,authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e}`,...a},void 0,a.uaConfigOverrides),this.phone=new pa(this.client,a.audioDeviceOutput,!0,a.audioDeviceRing),this._transferEvents()}async disconnect(){this.phone&&(this.phone.hasAnActiveCall()&&(vc.info("hangup call on disconnect"),await this.phone.hangup()),await this.phone.close()),this.phone=null}async call(e,t=!1,i=null,n=!1,r=!1){if(!this.phone)return;const s=i||this.getPrimaryWebRtcLine();return this.phone.makeCall(e,s,t,n,r)}async hangup(e){return vc.info("hangup via simple phone",{callId:e.getId()}),!!this.phone&&this.phone.hangup(e)}async accept(e,t){return vc.info("accept via simple phone",{callId:e.getId(),cameraEnabled:t}),this.phone?this.phone.accept(e,t):null}async startConference(e,t){const i=[e,...t].reduce(((e,t)=>(e[t.getTalkingToIds()[0]]=t,e)),{});if(!this.phone)return Promise.reject();return new Cn({phone:this.phone,host:e,participants:i}).start()}mute(e,t=!0){t&&this.muteViaAPI(e),this.phone?.mute(e)}unmute(e,t=!0){t&&this.unmuteViaAPI(e),this.phone?.unmute(e)}muteViaAPI(e){e&&e.callId&&Ol.getApiClient().calld.mute(e.callId).catch((e=>{vc.error("Mute via API, error",e)}))}unmuteViaAPI(e){e&&e.callId&&Ol.getApiClient().calld.unmute(e.callId).catch((e=>{vc.error("Unmute via API, error",e)}))}hold(e){return this.phone?.hold(e,!0)}async unhold(e){return this.phone?.unhold(e,!0)}async resume(e){return this.phone?.resume(e)||null}reject(e){return this.phone?.reject(e)}transfer(e,t){this.phone?.transfer(e,t)}atxfer(e){return this.phone?.atxfer(e)||null}async reinvite(e,t=null,i=!1){return this.phone?this.phone.sendReinvite(e,t,i):null}async getStats(e){return this.phone?this.phone.getStats(e):null}startNetworkMonitoring(e,t=1e3){return this.phone?this.phone.startNetworkMonitoring(e,t):null}stopNetworkMonitoring(e){return this.phone?this.phone.stopNetworkMonitoring(e):null}getSipSessionId(e){return e&&this.phone?this.phone.getSipSessionId(e):null}sendMessage(e,t,i="text/plain"){const n=t||this.getCurrentSipSession();n&&this.phone&&this.phone.sendMessage(n,e,i)}sendChat(e,t){this.sendMessage(JSON.stringify({type:da,content:e}),t,"application/json")}sendSignal(e,t){this.sendMessage(JSON.stringify({type:la,content:e}),t,"application/json")}turnCameraOff(e){this.phone?.turnCameraOff(e)}turnCameraOn(e){this.phone?.turnCameraOn(e)}async startScreenSharing(e,t){return this.phone?.startScreenSharing(e,t)||null}stopScreenSharing(e,t=!0){return this.phone?this.phone.stopScreenSharing(t,e):Promise.resolve()}sendDTMF(e,t){this.phone?.sendKey(t,e)}getLocalStream(e){return this.phone?.getLocalStream(e)}hasLocalVideo(e){return this.phone?.hasLocalVideo(e)||!1}hasALocalVideoTrack(e){return this.phone?.hasALocalVideoTrack(e)||!1}getLocalMediaStream(e){return vc.warn("Phone.getLocalMediaStream is deprecated, use Phone.getLocalStream instead"),this.phone?.getLocalStream(e)}getLocalVideoStream(e){return this.phone?.getLocalVideoStream(e)||null}getRemoteStream(e){return this.phone?.getRemoteStream(e)||null}getRemoteVideoStream(e){return this.phone?.getRemoteVideoStream(e)||null}isVideoRemotelyHeld(e){return this.phone?.isVideoRemotelyHeld(e)||!1}getRemoteStreamForCall(e){return vc.warn("Phone.getRemoteStreamForCall is deprecated, use Phone.getRemoteStream instead"),this.getRemoteStream(e)||null}getRemoteStreamsForCall(e){return vc.warn("Phone.getRemoteStreamsForCall is deprecated, use Phone.getLocalStream instead"),this.getLocalStream(e)||null}getRemoteVideoStreamForCall(e){return vc.warn("Phone.getRemoteVideoStreamForCall is deprecated, use Phone.getRemoteVideoStream instead"),this.getRemoteVideoStream(e)}getRemoteVideoStreamFromPc(e){return this.phone?.getRemoteVideoStreamFromPc(e)||null}hasVideo(e){return!!this.phone&&this.phone.hasVideo(e)}hasAVideoTrack(e){return!!this.phone&&this.phone.hasAVideoTrack(e)}getCurrentSipSession(){return this.phone?.currentSipSession||null}getPrimaryWebRtcLine(){const e=Ol.Auth.getSession();return e?.primaryWebRtcLine()||null}getOutputDevice(){return this.phone?.audioOutputDeviceId||null}getPrimaryLine(){const e=Ol.Auth.getSession();return e?.primarySipLine()||null}getLineById(e){return this.getSipLines().find((t=>t&&t.id===e))||null}getSipLines(){const e=Ol.Auth.getSession();return e&&e.profile?.sipLines||[]}hasSfu(){return this.sipLine?.hasVideoConference()||!1}checkSfu(){if(!this.hasSfu())throw new mc}enableLogger(){this.client.enableLogger(this._logConnector)}_transferEvents(){this.unbind(),[...uc,...pc].forEach((e=>{this.client.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter.emit,[`client-${e}`,...t])))})),Object.values(ga).forEach((e=>{"string"==typeof e&&this.phone&&this.phone.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter,[e,...t])))}))}_logConnector(e,t,i,n){const r=n&&n.indexOf?bc.findIndex((e=>-1!==n.indexOf(e))):-1;if("sip.Transport"===t&&-1!==r){const e=0===r?"receiving":"sending",i=n.replace(`${bc[r]}\n\n`,"").replace("\r\n","\n");Sc.trace(i,{className:t,direction:e})}else yc.trace(n,{className:t})}}global.wazoTelephonyInstance||(global.wazoTelephonyInstance=new wc);var Ec=global.wazoTelephonyInstance,Cc=function(e,t){return Cc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},Cc(e,t)};
|
|
28
|
+
var Ye=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),i={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?i[t]:String.fromCharCode(parseInt(n,16))}var r=new String(""),s=Object.hasOwnProperty;return function(i,a){var o,c,d=i.match(e),l=d[0],h=!1;"{"===l?o={}:"["===l?o=[]:(o=[],h=!0);for(var u=[o],p=1-h,g=d.length;p<g;++p){var f;switch((l=d[p]).charCodeAt(0)){default:(f=u[0])[c||f.length]=+l,c=void 0;break;case 34:if(-1!==(l=l.substring(1,l.length-1)).indexOf("\\")&&(l=l.replace(t,n)),f=u[0],!c){if(!(f instanceof Array)){c=l||r;break}c=f.length}f[c]=l,c=void 0;break;case 91:f=u[0],u.unshift(f[c||f.length]=[]),c=void 0;break;case 93:case 125:u.shift();break;case 102:(f=u[0])[c||f.length]=!1,c=void 0;break;case 110:(f=u[0])[c||f.length]=null,c=void 0;break;case 116:(f=u[0])[c||f.length]=!0,c=void 0;break;case 123:f=u[0],u.unshift(f[c||f.length]={}),c=void 0}}if(h){if(1!==u.length)throw new Error;o=o[0]}else if(u.length)throw new Error;if(a){var m=function(e,t){var i=e[t];if(i&&"object"==typeof i){var n=null;for(var r in i)if(s.call(i,r)&&i!==e){var o=m(i,r);void 0!==o?i[r]=o:(n||(n=[]),n.push(r))}if(n)for(var c=n.length;--c>=0;)delete i[n[c]]}return a.call(e,t,i)};o=m({"":o},"")}return o}}();void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),Je.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){return Rt(e)},this.getPEMStringFromHex=function(e,t){return ht(e,t)},this.newObject=function(e){var t=Je.asn1,i=t.ASN1Object,n=t.DERBoolean,r=t.DERInteger,s=t.DERBitString,a=t.DEROctetString,o=t.DERNull,c=t.DERObjectIdentifier,d=t.DEREnumerated,l=t.DERUTF8String,h=t.DERNumericString,u=t.DERPrintableString,p=t.DERTeletexString,g=t.DERIA5String,f=t.DERUTCTime,m=t.DERGeneralizedTime,v=t.DERVisibleString,y=t.DERBMPString,S=t.DERSequence,b=t.DERSet,w=t.DERTaggedObject,E=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var C=Object.keys(e);if(1!=C.length)throw new Error("key of param shall be only one.");var $=C[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+$+":"))throw new Error("undefined key: "+$);if("bool"==$)return new n(e[$]);if("int"==$)return new r(e[$]);if("bitstr"==$)return new s(e[$]);if("octstr"==$)return new a(e[$]);if("null"==$)return new o(e[$]);if("oid"==$)return new c(e[$]);if("enum"==$)return new d(e[$]);if("utf8str"==$)return new l(e[$]);if("numstr"==$)return new h(e[$]);if("prnstr"==$)return new u(e[$]);if("telstr"==$)return new p(e[$]);if("ia5str"==$)return new g(e[$]);if("utctime"==$)return new f(e[$]);if("gentime"==$)return new m(e[$]);if("visstr"==$)return new v(e[$]);if("bmpstr"==$)return new y(e[$]);if("asn1"==$)return new i(e[$]);if("seq"==$){for(var T=e[$],_=[],x=0;x<T.length;x++){var I=E(T[x]);_.push(I)}return new S({array:_})}if("set"==$){for(T=e[$],_=[],x=0;x<T.length;x++){I=E(T[x]);_.push(I)}return new b({array:_})}if("tag"==$){var R=e[$];if("[object Array]"===Object.prototype.toString.call(R)&&3==R.length){var A=E(R[2]);return new w({tag:R[0],explicit:R[1],obj:A})}return new w(R)}},this.jsonToASN1HEX=function(e){return this.newObject(e).tohex()}},Je.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",i=parseInt(e.substr(0,2),16),n=(t=Math.floor(i/40)+"."+i%40,""),r=2;r<e.length;r+=2){var s=("00000000"+parseInt(e.substr(r,2),16).toString(2)).slice(-8);if(n+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new de(n,2).toString(10),n=""}return t},Je.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},i=function(e){var i="",n=new de(e,10).toString(2),r=7-n.length%7;7==r&&(r=0);for(var s="",a=0;a<r;a++)s+="0";n=s+n;for(a=0;a<n.length-1;a+=7){var o=n.substr(a,7);a!=n.length-7&&(o="1"+o),i+=t(parseInt(o,2))}return i};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",r=e.split("."),s=40*parseInt(r[0])+parseInt(r[1]);n+=t(s),r.splice(0,2);for(var a=0;a<r.length;a++)n+=i(r[a]);return n},Je.asn1.ASN1Object=function(e){this.params=null,this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw new Error("this.hV is null or undefined");if(this.hV.length%2==1)throw new Error("value hex must be even length: n=0,v="+this.hV);var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var i=t.length/2;if(i>15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+i).toString(16)+t},this.tohex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.getValueHex=function(){return this.tohex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},Je.asn1.DERAbstractString=function(e){Je.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=at(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},Nt(Je.asn1.DERAbstractString,Je.asn1.ASN1Object),Je.asn1.DERAbstractTime=function(e){Je.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,i){var n=this.zeroPadding,r=this.localDateToUTC(e),s=String(r.getFullYear());"utc"==t&&(s=s.substr(2,2));var a=s+n(String(r.getMonth()+1),2)+n(String(r.getDate()),2)+n(String(r.getHours()),2)+n(String(r.getMinutes()),2)+n(String(r.getSeconds()),2);if(!0===i){var o=r.getMilliseconds();if(0!=o){var c=n(String(o),3);a=a+"."+(c=c.replace(/[0]+$/,""))}}return a+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.setByParam=function(e){this.hV=null,this.hTLV=null,this.params=e},this.getString=function(){},this.setString=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.str=e},this.setByDate=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.date=e},this.setByDateValue=function(e,t,i,n,r,s){var a=new Date(Date.UTC(e,t-1,i,n,r,s,0));this.setByDate(a)},this.getFreshValueHex=function(){return this.hV}},Nt(Je.asn1.DERAbstractTime,Je.asn1.ASN1Object),Je.asn1.DERAbstractStructured=function(e){Je.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},Nt(Je.asn1.DERAbstractStructured,Je.asn1.ASN1Object),Je.asn1.DERBoolean=function(e){Je.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},Nt(Je.asn1.DERBoolean,Je.asn1.ASN1Object),Je.asn1.DERInteger=function(e){Je.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=Rt;this.setByBigInteger=function(e){this.isModified=!0,this.params={bigint:e}},this.setByInteger=function(e){this.isModified=!0,this.params=e},this.setValueHex=function(e){this.isModified=!0,this.params={hex:e}},this.getFreshValueHex=function(){var e=this.params,i=null;if(null==e)throw new Error("value not set");if("object"==typeof e&&null!=e.hex)return this.hV=e.hex,this.hV;if("number"==typeof e)i=new de(String(e),10);else if(null!=e.int)i=new de(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");i=e.bigint}return this.hV=t(i),this.hV},null!=e&&(this.params=e)},Nt(Je.asn1.DERInteger,Je.asn1.ASN1Object),Je.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=Je.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}Je.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var i="0"+e;this.hTLV=null,this.isModified=!0,this.hV=i+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0),e+="0000000".substr(0,t);for(var i="",n=0;n<e.length-1;n+=8){var r=e.substr(n,8),s=parseInt(r,2).toString(16);1==s.length&&(s="0"+s),i+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+i},this.setByBooleanArray=function(e){for(var t="",i=0;i<e.length;i++)1==e[i]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),i=0;i<e;i++)t[i]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},Nt(Je.asn1.DERBitString,Je.asn1.ASN1Object),Je.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=Je.asn1.ASN1Util.newObject(e.obj);e.hex=t.tohex()}Je.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},Nt(Je.asn1.DEROctetString,Je.asn1.DERAbstractString),Je.asn1.DERNull=function(){Je.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},Nt(Je.asn1.DERNull,Je.asn1.ASN1Object),Je.asn1.DERObjectIdentifier=function(e){Je.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){var t=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},i=function(e){var i="",n=parseInt(e,10).toString(2),r=7-n.length%7;7==r&&(r=0);for(var s="",a=0;a<r;a++)s+="0";n=s+n;for(a=0;a<n.length-1;a+=7){var o=n.substr(a,7);a!=n.length-7&&(o="1"+o),i+=t(parseInt(o,2))}return i};try{if(!e.match(/^[0-9.]+$/))return null;var n="",r=e.split("."),s=40*parseInt(r[0],10)+parseInt(r[1],10);n+=t(s),r.splice(0,2);for(var a=0;a<r.length;a++)n+=i(r[a]);return n}catch(e){return null}}(e);if(null==t)throw new Error("malformed oid string: "+e);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.setValueName=function(e){var t=Je.asn1.x509.OID.name2oid(e);if(""===t)throw new Error("DERObjectIdentifier oidName undefined: "+e);this.setValueOidString(t)},this.setValueNameOrOid=function(e){e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(e){"string"==typeof e?this.setValueNameOrOid(e):void 0!==e.oid?this.setValueNameOrOid(e.oid):void 0!==e.name?this.setValueNameOrOid(e.name):void 0!==e.hex&&this.setValueHex(e.hex)},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.DERObjectIdentifier,Je.asn1.ASN1Object),Je.asn1.DEREnumerated=function(e){Je.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=Rt(e)},this.setByInteger=function(e){var t=new de(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},Nt(Je.asn1.DEREnumerated,Je.asn1.ASN1Object),Je.asn1.DERUTF8String=function(e){Je.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},Nt(Je.asn1.DERUTF8String,Je.asn1.DERAbstractString),Je.asn1.DERNumericString=function(e){Je.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},Nt(Je.asn1.DERNumericString,Je.asn1.DERAbstractString),Je.asn1.DERPrintableString=function(e){Je.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},Nt(Je.asn1.DERPrintableString,Je.asn1.DERAbstractString),Je.asn1.DERTeletexString=function(e){Je.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},Nt(Je.asn1.DERTeletexString,Je.asn1.DERAbstractString),Je.asn1.DERIA5String=function(e){Je.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},Nt(Je.asn1.DERIA5String,Je.asn1.DERAbstractString),Je.asn1.DERVisibleString=function(e){Je.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},Nt(Je.asn1.DERVisibleString,Je.asn1.DERAbstractString),Je.asn1.DERBMPString=function(e){Je.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},Nt(Je.asn1.DERBMPString,Je.asn1.DERAbstractString),Je.asn1.DERUTCTime=function(e){Je.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.params=void 0,this.getFreshValueHex=function(){var e=this.params;if(null==this.params&&(e={date:new Date}),"string"==typeof e){if(!e.match(/^[0-9]{12}Z$/)&&!e.match(/^[0-9]{12}\.[0-9]+Z$/))throw new Error("malformed string for UTCTime: "+e);this.hV=tt(e)}else if(null!=e.str)this.hV=tt(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=tt(this.formatDate(t,"utc",!0))}else if(null!=e.date&&e.date instanceof Date){var i=!0===e.millis;this.hV=tt(this.formatDate(e.date,"utc",i))}else e instanceof Date&&(this.hV=tt(this.formatDate(e,"utc")));if(null==this.hV)throw new Error("parameter not specified properly for UTCTime");return this.hV},null!=e&&this.setByParam(e)},Nt(Je.asn1.DERUTCTime,Je.asn1.DERAbstractTime),Je.asn1.DERGeneralizedTime=function(e){Je.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.params=e,this.getFreshValueHex=function(){var e=this.params;if(null==this.params&&(e={date:new Date}),"string"==typeof e){if(!e.match(/^[0-9]{14}Z$/)&&!e.match(/^[0-9]{14}\.[0-9]+Z$/))throw new Error("malformed string for GeneralizedTime: "+e);this.hV=tt(e)}else if(null!=e.str)this.hV=tt(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=tt(this.formatDate(t,"gen",!0))}else if(null!=e.date&&e.date instanceof Date){var i=!0===e.millis;this.hV=tt(this.formatDate(e.date,"gen",i))}else e instanceof Date&&(this.hV=tt(this.formatDate(e,"gen")));if(null==this.hV)throw new Error("parameter not specified properly for GeneralizedTime");return this.hV},null!=e&&this.setByParam(e)},Nt(Je.asn1.DERGeneralizedTime,Je.asn1.DERAbstractTime),Je.asn1.DERSequence=function(e){Je.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++){e+=this.asn1Array[t].tohex()}return this.hV=e,this.hV}},Nt(Je.asn1.DERSequence,Je.asn1.DERAbstractStructured),Je.asn1.DERSet=function(e){Je.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var i=this.asn1Array[t];e.push(i.tohex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},Nt(Je.asn1.DERSet,Je.asn1.DERAbstractStructured),Je.asn1.DERTaggedObject=function(e){Je.asn1.DERTaggedObject.superclass.constructor.call(this);var t=Je.asn1,i=Qe,n=i.getV;i.isASN1HEX;var r=t.ASN1Util.newObject;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.params={tag:"a0",explicit:!0},this.setASN1Object=function(e,t,i){this.params={tag:t,explicit:e,obj:i}},this.getFreshValueHex=function(){var e=this.params;if(null==e.explicit&&(e.explicit=!0),null!=e.tage&&(e.tag=e.tage,e.explicit=!0),null!=e.tagi&&(e.tag=e.tagi,e.explicit=!1),null!=e.str)this.hV=at(e.str);else if(null!=e.hex)this.hV=e.hex;else{if(null==e.obj)throw new Error("str, hex nor obj not specified");var i;e.obj instanceof t.ASN1Object?i=e.obj.tohex():"object"==typeof e.obj&&(i=r(e.obj).tohex()),e.explicit?this.hV=i:this.hV=n(i,0)}return null==e.tag&&(e.tag="a0"),this.hT=e.tag,this.hTLV=null,this.isModified=!0,this.hV},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.DERTaggedObject,Je.asn1.ASN1Object);var Je,Ze,Xe,Qe=new function(){};function et(e){for(var t="",i=0;i<e.length;i++){var n=e[i].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function tt(e){return et(function(e){for(var t=new Array,i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}(e))}function it(e){return e=(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function nt(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),e=(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function rt(e){return e.length%2==1&&(e="0"+e),it(oe(e))}function st(e){return ce(nt(e))}function at(e){return gt(Ct(e)).toLowerCase()}function ot(e){try{return decodeURIComponent(ft(e))}catch(e){return null}}function ct(e){return ot(function(e){for(var t=e.match(/.{1,2}/g),i=[],n=0;n<t.length;n++){var r=parseInt(t[n],16);161<=r&&r<=191?(i.push("c2"),i.push(t[n])):192<=r&&r<=255?(i.push("c3"),i.push((r-64).toString(16))):i.push(t[n])}return i.join("")}(e))}function dt(e){for(var t="",i=0;i<e.length-1;i+=2)t+=String.fromCharCode(parseInt(e.substr(i,2),16));return t}function lt(e){for(var t="",i=0;i<e.length;i++)t+=("0"+e.charCodeAt(i).toString(16)).slice(-2);return t}function ht(e,t){return"-----BEGIN "+t+"-----\r\n"+function(e,t){return(e=e.replace(new RegExp("(.{"+t+"})","g"),"$1\r\n")).replace(/\s+$/,"")}(function(e){return oe(e)}(e),64)+"\r\n-----END "+t+"-----\r\n"}function ut(e,t){if(-1==e.indexOf("-----BEGIN "))throw new Error("can't find PEM header");return function(e){return ce(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function pt(e){return Math.round(function(e){var t,i,n,r,s,a,o,c,d,l;if(e=function(e){return e.match(/^[0-9]{12}Z$/)||e.match(/^[0-9]{12}[.][0-9]*Z$/)?e.match(/^[0-4]/)?"20"+e:"19"+e:e}(e),l=e.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return t=parseInt(l[1]),i=parseInt(l[2])-1,n=parseInt(l[3]),r=parseInt(l[4]),s=parseInt(l[5]),a=parseInt(l[6]),o=0,""!==(c=l[7])&&(d=(c.substr(1)+"00").substr(0,3),o=parseInt(d)),Date.UTC(t,i,n,r,s,a,o);throw new Error("unsupported zulu format: "+e)}(e)/1e3)}function gt(e){return e.replace(/%/g,"")}function ft(e){return e.replace(/(..)/g,"%$1")}function mt(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var i=(e=e.toLowerCase()).split(":").length-1;if(i<2)throw t;var n=":".repeat(7-i+2),r=(e=e.replace("::",n)).split(":");if(8!=r.length)throw t;for(var s=0;s<8;s++)r[s]=("0000"+r[s]).slice(-4);return r.join("")}function vt(e){if(!e.match(/^[0-9A-Fa-f]{32}$/))throw new Error("malformed IPv6 address: "+e);var t=(e=e.toLowerCase()).match(/.{1,4}/g);t=t.map((function(e){return e.replace(/^0+/,"")})),t=t.map((function(e){return""==e?"0":e}));var i=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null==i)return e.slice(1,-1);var n=i.sort().slice(-1)[0];return"::"!=(e=e.replace(n.substr(0,n.length-1),":")).substr(0,2)&&(e=e.substr(1)),"::"!=e.substr(-2,2)&&(e=e.substr(0,e.length-1)),e}function yt(e){var t=new Error("malformed hex value");if(!e.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(8==e.length){try{return parseInt(e.substr(0,2),16)+"."+parseInt(e.substr(2,2),16)+"."+parseInt(e.substr(4,2),16)+"."+parseInt(e.substr(6,2),16)}catch(e){throw t}}else{if(16!=e.length){if(32==e.length)return vt(e);if(64==e.length){try{return vt(e.substr(0,32))+"/"+St(e.substr(32))}catch(e){throw t}return}return e}try{return yt(e.substr(0,8))+"/"+St(e.substr(8))}catch(e){throw t}}}function St(e){var t,i=new Error("malformed mask");try{t=new de(e,16).toString(2)}catch(e){throw i}if(!t.match(/^1*0*$/))throw i;return t.replace(/0+$/,"").length}function bt(e){var t=new Error("malformed IP address");if(!(e=e.toLowerCase(e)).match(/^[0-9a-f.:/]+$/))throw t;if(!e.match(/^[0-9.]+$/)){var i;if(e.match(/^[0-9.]+\/[0-9]+$/))return bt((i=e.split("/"))[0])+wt(parseInt(i[1]),32);if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return mt(e);if(e.match(/^[0-9a-f:]+\/[0-9]+$/)&&-1!==e.indexOf(":"))return mt((i=e.split("/"))[0])+wt(parseInt(i[1]),128);throw t}var n=e.split(".");if(4!==n.length)throw t;var r="";try{for(var s=0;s<4;s++){r+=("0"+parseInt(n[s]).toString(16)).slice(-2)}return r}catch(e){throw t}}function wt(e,t){return 32==t&&0==e?"00000000":128==t&&0==e?"00000000000000000000000000000000":new de(Array(e+1).join("1")+Array(t-e+1).join("0"),2).toString(16)}function Et(e){var t=e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),i=parseInt(e.substr(2),16);if(0==t&i<128)return String.fromCharCode(i);if(t<8){var n=128|63&i;return ot((192|(7&t)<<3|(192&i)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&i)>>6;var r=128|63&i;return ot((224|(240&t)>>4).toString(16)+n.toString(16)+r.toString(16))}));return t.join("")}function Ct(e){for(var t=encodeURIComponent(e),i="",n=0;n<t.length;n++)"%"==t[n]?(i+=t.substr(n,3),n+=2):i=i+"%"+tt(t[n]);return i}function $t(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function Tt(e){return!!e.match(/^[0-9A-Za-z-_.]+$/)}function _t(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}function xt(e){if(!$t(e))return null;try{var t=[],i=e.substr(0,2),n=parseInt(i,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var r=e.substr(2),s=[],a=0;a<r.length/2;a++)s.push(parseInt(r.substr(2*a,2),16));var o=[],c="";for(a=0;a<s.length;a++)128&s[a]?c+=At((127&s[a]).toString(2),7):(c+=At((127&s[a]).toString(2),7),o.push(new String(parseInt(c,2))),c="");var d=t.join(".");return o.length>0&&(d=d+"."+o.join(".")),d}catch(e){return null}}function It(e){return Rt(new de(String(e),10))}function Rt(e){var t=e.toString(16);if("-"!=t.substr(0,1))return t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t),t;var i=t.substr(1).length;i%2==1?i+=1:t.match(/^[0-7]/)||(i+=2);for(var n="",r=0;r<i;r++)n+="f";return t=new de(n,16).xor(e).add(de.ONE).toString(16).replace(/^-/,"")}Qe.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var i=parseInt(e.substr(t+3,1));return 0==i?-1:0<i&&i<10?i+1:-2},Qe.getL=function(e,t){var i=Qe.getLblen(e,t);return i<1?"":e.substr(t+2,2*i)},Qe.getVblen=function(e,t){var i;return""==(i=Qe.getL(e,t))?-1:("8"===i.substr(0,1)?new de(i.substr(2),16):new de(i,16)).intValue()},Qe.getVidx=function(e,t){var i=Qe.getLblen(e,t);return i<0?i:t+2*(i+1)},Qe.getV=function(e,t){var i=Qe.getVidx(e,t),n=Qe.getVblen(e,t);return e.substr(i,2*n)},Qe.getTLV=function(e,t){return e.substr(t,2)+Qe.getL(e,t)+Qe.getV(e,t)},Qe.getTLVblen=function(e,t){return 2+2*Qe.getLblen(e,t)+2*Qe.getVblen(e,t)},Qe.getNextSiblingIdx=function(e,t){return Qe.getVidx(e,t)+2*Qe.getVblen(e,t)},Qe.getChildIdx=function(e,t){var i,n,r,s=Qe,a=[];i=s.getVidx(e,t),n=2*s.getVblen(e,t),"03"==e.substr(t,2)&&(i+=2,n-=2),r=0;for(var o=i;r<=n;){var c=s.getTLVblen(e,o);if((r+=c)<=n&&a.push(o),o+=c,r>=n)break}return a},Qe.getNthChildIdx=function(e,t,i){return Qe.getChildIdx(e,t)[i]},Qe.getIdxbyList=function(e,t,i,n){var r,s,a=Qe;return 0==i.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(r=i.shift())>=(s=a.getChildIdx(e,t)).length?-1:a.getIdxbyList(e,s[r],i,n)},Qe.getIdxbyListEx=function(e,t,i,n){var r,s,a=Qe;if(0==i.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;r=i.shift(),s=a.getChildIdx(e,t);for(var o=0,c=0;c<s.length;c++){var d=e.substr(s[c],2);if("number"==typeof r&&!a.isContextTag(d)&&o==r||"string"==typeof r&&a.isContextTag(d,r))return a.getIdxbyListEx(e,s[c],i,n);a.isContextTag(d)||o++}return-1},Qe.getTLVbyList=function(e,t,i,n){var r=Qe,s=r.getIdxbyList(e,t,i,n);return-1==s||s>=e.length?null:r.getTLV(e,s)},Qe.getTLVbyListEx=function(e,t,i,n){var r=Qe,s=r.getIdxbyListEx(e,t,i,n);return-1==s?null:r.getTLV(e,s)},Qe.getVbyList=function(e,t,i,n,r){var s,a,o=Qe;return-1==(s=o.getIdxbyList(e,t,i,n))||s>=e.length?null:(a=o.getV(e,s),!0===r&&(a=a.substr(2)),a)},Qe.getVbyListEx=function(e,t,i,n,r){var s,a,o=Qe;return-1==(s=o.getIdxbyListEx(e,t,i,n))?null:(a=o.getV(e,s),"03"==e.substr(s,2)&&!1!==r&&(a=a.substr(2)),a)},Qe.getInt=function(e,t,i){null==i&&(i=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return i;var r=Qe.getV(e,t);return"02"==n?parseInt(r,16):function(e){if(e.length%2!=0)return-1;if(e=e.toLowerCase(),null==e.match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var i=parseInt(t,16);if(i>7)return-1;var n=e.substr(2),r=parseInt(n,16).toString(2);"0"==r&&(r="00000000"),r=r.slice(0,0-i);var s=parseInt(r,2);return NaN==s?-1:s}catch(e){return-1}}(r)}catch(e){return i}},Qe.getOID=function(e,t,i){null==i&&(i=null);try{return"06"!=e.substr(t,2)?i:xt(Qe.getV(e,t))}catch(e){return i}},Qe.getOIDName=function(e,t,i){null==i&&(i=null);try{var n=Qe.getOID(e,t,i);if(n==i)return i;var r=Je.asn1.x509.OID.oid2name(n);return""==r?n:r}catch(e){return i}},Qe.getString=function(e,t,i){null==i&&(i=null);try{return dt(Qe.getV(e,t))}catch(e){return i}},Qe.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},i=[],n=e.substr(0,2),r=parseInt(n,16);i[0]=new String(Math.floor(r/40)),i[1]=new String(r%40);for(var s=e.substr(2),a=[],o=0;o<s.length/2;o++)a.push(parseInt(s.substr(2*o,2),16));var c=[],d="";for(o=0;o<a.length;o++)128&a[o]?d+=t((127&a[o]).toString(2),7):(d+=t((127&a[o]).toString(2),7),c.push(new String(parseInt(d,2))),d="");var l=i.join(".");return c.length>0&&(l=l+"."+c.join(".")),l},Qe.dump=function(e,t,i,n){var r=Qe,s=r.getV,a=r.dump,o=r.getChildIdx,c=e;e instanceof Je.asn1.ASN1Object&&(c=e.tohex());var d=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===i&&(i=0),void 0===n&&(n="");var l,h=t.ommit_long_octet;if("01"==(l=c.substr(i,2)))return"00"==(u=s(c,i))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==l)return n+"INTEGER "+d(u=s(c,i),h)+"\n";if("03"==l){var u=s(c,i);if(r.isASN1HEX(u.substr(2))){var p=n+"BITSTRING, encapsulates\n";return p+=a(u.substr(2),t,0,n+" ")}return n+"BITSTRING "+d(u,h)+"\n"}if("04"==l){u=s(c,i);if(r.isASN1HEX(u)){p=n+"OCTETSTRING, encapsulates\n";return p+=a(u,t,0,n+" ")}return n+"OCTETSTRING "+d(u,h)+"\n"}if("05"==l)return n+"NULL\n";if("06"==l){var g=s(c,i),f=Je.asn1.ASN1Util.oidHexToInt(g),m=Je.asn1.x509.OID.oid2name(f),v=f.replace(/\./g," ");return""!=m?n+"ObjectIdentifier "+m+" ("+v+")\n":n+"ObjectIdentifier ("+v+")\n"}if("0a"==l)return n+"ENUMERATED "+parseInt(s(c,i))+"\n";if("0c"==l)return n+"UTF8String '"+ot(s(c,i))+"'\n";if("13"==l)return n+"PrintableString '"+ot(s(c,i))+"'\n";if("14"==l)return n+"TeletexString '"+ot(s(c,i))+"'\n";if("16"==l)return n+"IA5String '"+ot(s(c,i))+"'\n";if("17"==l)return n+"UTCTime "+ot(s(c,i))+"\n";if("18"==l)return n+"GeneralizedTime "+ot(s(c,i))+"\n";if("1a"==l)return n+"VisualString '"+ot(s(c,i))+"'\n";if("1e"==l)return n+"BMPString '"+Et(s(c,i))+"'\n";if("30"==l){if("3000"==c.substr(i,4))return n+"SEQUENCE {}\n";p=n+"SEQUENCE\n";var y=t;if((2==(w=o(c,i)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){m=r.oidname(s(c,w[0]));var S=JSON.parse(JSON.stringify(t));S.x509ExtName=m,y=S}for(var b=0;b<w.length;b++)p+=a(c,y,w[b],n+" ");return p}if("31"==l){p=n+"SET\n";var w=o(c,i);for(b=0;b<w.length;b++)p+=a(c,t,w[b],n+" ");return p}if(0!=(128&(l=parseInt(l,16)))){var E=31&l;if(0!=(32&l)){for(p=n+"["+E+"]\n",w=o(c,i),b=0;b<w.length;b++)p+=a(c,t,w[b],n+" ");return p}u=s(c,i);if(Qe.isASN1HEX(u)){var p=n+"["+E+"]\n";return p+=a(u,t,0,n+" ")}return("68747470"==u.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==E)&&(u=ot(u)),p=n+"["+E+"] "+u+"\n"}return n+"UNKNOWN("+l+") "+s(c,i)+"\n"},Qe.parse=function(e){var t=Qe,i=t.parse,n=t.isASN1HEX,r=t.getV,s=t.getTLV,a=t.getChildIdx,o=Je.asn1,c=o.ASN1Util.oidHexToInt,d=o.x509.OID.oid2name,l=ot,h=Et,u=ct,p={"0c":"utf8str",12:"numstr",13:"prnstr",14:"telstr",16:"ia5str",17:"utctime",18:"gentime","1a":"visstr","1e":"bmpstr",30:"seq",31:"set"},g=e.substr(0,2),f={},m=r(e,0);if("01"==g)return"0101ff"==e?{bool:!0}:{bool:!1};if("02"==g)return{int:{hex:m}};if("03"==g)try{if("00"!=m.substr(0,2))throw"not encap";var v=m.substr(2);if(!n(v))throw"not encap";return{bitstr:{obj:i(v)}}}catch(e){var y=null;return m.length<=10&&(y=function(e){if("string"!=typeof e)return null;if(e.length%2!=0)return null;if(!e.match(/^[0-9a-f]+$/))return null;try{var t=parseInt(e.substr(0,2),16);if(t<0||7<t)return null;for(var i=e.substr(2),n="",r=0;r<i.length;r+=2){var s=i.substr(r,2),a=parseInt(s,16).toString(2);n+=a=("0000000"+a).slice(-8)}return n.substr(0,n.length-t)}catch(e){return null}}(m)),null==y?{bitstr:{hex:m}}:{bitstr:{bin:y}}}else if("04"==g)try{if(!n(m))throw"not encap";return{octstr:{obj:i(m)}}}catch(e){return{octstr:{hex:m}}}else{if("05"==g)return{null:""};if("06"==g){var S=c(m),b=d(S);return""==b?{oid:S}:{oid:b}}if("0a"==g)return m.length>4?{enum:{hex:m}}:{enum:parseInt(m,16)};if("30"==g||"31"==g)return f[p[g]]=function(e){for(var t=[],n=a(e,0),r=0;r<n.length;r++){var o=n[r],c=s(e,o),d=i(c);t.push(d)}return t}(e),f;if("14"==g){var w=u(m);return f[p[g]]={str:w},f}if("1e"==g){w=h(m);return f[p[g]]={str:w},f}if(-1!=":0c:12:13:16:17:18:1a:".indexOf(g)){w=l(m);return f[p[g]]={str:w},f}if(g.match(/^8[0-9]$/))return null==(w=l(m))|""==w||null!=w.match(/[\x00-\x1F\x7F-\x9F]/)||null!=w.match(/[\u0000-\u001F\u0080–\u009F]/)?{tag:{tag:g,explicit:!1,hex:m}}:{tag:{tag:g,explicit:!1,str:w}};if(!g.match(/^a[0-9]$/)){var E=new Je.asn1.ASN1Object;return E.hV=m,{asn1:{tlv:g+E.getLengthHexFromValue()+m}}}try{if(!n(m))throw new Error("not encap");return{tag:{tag:g,explicit:!0,obj:i(m)}}}catch(e){return{tag:{tag:g,explicit:!0,hex:m}}}}},Qe.isContextTag=function(e,t){var i,n;e=e.toLowerCase();try{i=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&i);try{return null!=t.match(/^\[[0-9]+\]$/)&&(!((n=parseInt(t.substr(1,t.length-1),10))>31)&&(128==(192&i)&&(31&i)==n))}catch(e){return!1}},Qe.isASN1HEX=function(e){var t=Qe;if(e.length%2==1)return!1;var i=t.getVblen(e,0),n=e.substr(0,2),r=t.getL(e,0);return e.length-n.length-r.length==2*i},Qe.checkStrictDER=function(e,t,i,n,r){var s=Qe;if(void 0===i){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!Je.lang.String.isHex(e))throw new Error("not hex string");i=e.length,r=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(s.getL(e,t).length>2*r)throw new Error("L of TLV too long: idx="+t);var a=s.getVblen(e,t);if(a>n)throw new Error("value of L too long than hex: idx="+t);var o=s.getTLV(e,t),c=o.length-2-s.getL(e,t).length;if(c!==2*a)throw new Error("V string length and L's value not the same:"+c+"/"+2*a);if(0===t&&e.length!=o.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+o.length);var d=e.substr(t,2);if("02"===d){var l=s.getVidx(e,t);if("00"==e.substr(l,2)&&e.charCodeAt(l+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(d,16)){for(var h=s.getVblen(e,t),u=0,p=s.getChildIdx(e,t),g=0;g<p.length;g++){u+=s.getTLV(e,p[g]).length,s.checkStrictDER(e,p[g],i,n,r)}if(2*h!=u)throw new Error("sum of children's TLV length and L unmatch: "+2*h+"!="+u)}},Qe.oidname=function(e){var t=Je.asn1;Je.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var i=t.x509.OID.oid2name(e);return""===i&&(i=e),i},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.x509&&Je.asn1.x509||(Je.asn1.x509={}),Je.asn1.x509.Certificate=function(e){Je.asn1.x509.Certificate.superclass.constructor.call(this);var t=Je.asn1,i=t.DERBitString,n=t.DERSequence,r=t.x509,s=r.TBSCertificate,a=r.AlgorithmIdentifier;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.sigalg;null!=e.sigalg.name&&(t=e.sigalg.name);var i=e.tbsobj.tohex(),n=new Je.crypto.Signature({alg:t});n.init(e.cakey),n.updateHex(i),e.sighex=n.sign()},this.getPEM=function(){return ht(this.tohex(),"CERTIFICATE")},this.tohex=function(){var e=this.params;if(null!=e.tbsobj&&null!=e.tbsobj||(e.tbsobj=new s(e)),null==e.sighex&&null!=e.cakey&&this.sign(),null==e.sighex)throw new Error("sighex or cakey parameter not defined");var t=[];return t.push(e.tbsobj),t.push(new a({name:e.sigalg})),t.push(new i({hex:"00"+e.sighex})),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},Nt(Je.asn1.x509.Certificate,Je.asn1.ASN1Object),Je.asn1.x509.TBSCertificate=function(e){Je.asn1.x509.TBSCertificate.superclass.constructor.call(this);var t=Je.asn1,i=t.x509,n=t.DERTaggedObject,r=t.DERInteger,s=t.DERSequence,a=i.AlgorithmIdentifier,o=i.Time,c=i.X500Name,d=i.Extensions,l=i.SubjectPublicKeyInfo;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=[],t=this.params;if(null!=t.version||1!=t.version){var i=2;null!=t.version&&(i=t.version-1);var h=new n({obj:new r({int:i})});e.push(h)}return e.push(new r(t.serial)),e.push(new a({name:t.sigalg})),e.push(new c(t.issuer)),e.push(new s({array:[new o(t.notbefore),new o(t.notafter)]})),e.push(new c(t.subject)),e.push(new l(kt.getKey(t.sbjpubkey))),void 0!==t.ext&&t.ext.length>0&&e.push(new n({tag:"a3",obj:new d(t.ext)})),new Je.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.TBSCertificate,Je.asn1.ASN1Object),Je.asn1.x509.Extensions=function(e){Je.asn1.x509.Extensions.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.x509;this.aParam=[],this.setByParam=function(e){this.aParam=e},this.tohex=function(){for(var e=[],t=0;t<this.aParam.length;t++){var r=this.aParam[t],s=r.extname,a=null;if(null!=r.extn)a=new n.PrivateExtension(r);else if("subjectKeyIdentifier"==s)a=new n.SubjectKeyIdentifier(r);else if("keyUsage"==s)a=new n.KeyUsage(r);else if("subjectAltName"==s)a=new n.SubjectAltName(r);else if("issuerAltName"==s)a=new n.IssuerAltName(r);else if("basicConstraints"==s)a=new n.BasicConstraints(r);else if("nameConstraints"==s)a=new n.NameConstraints(r);else if("cRLDistributionPoints"==s)a=new n.CRLDistributionPoints(r);else if("certificatePolicies"==s)a=new n.CertificatePolicies(r);else if("policyMappings"==s)a=new n.PolicyMappings(r);else if("policyConstraints"==s)a=new n.PolicyConstraints(r);else if("inhibitAnyPolicy"==s)a=new n.InhibitAnyPolicy(r);else if("authorityKeyIdentifier"==s)a=new n.AuthorityKeyIdentifier(r);else if("extKeyUsage"==s)a=new n.ExtKeyUsage(r);else if("authorityInfoAccess"==s)a=new n.AuthorityInfoAccess(r);else if("cRLNumber"==s)a=new n.CRLNumber(r);else if("cRLReason"==s)a=new n.CRLReason(r);else if("ocspNonce"==s)a=new n.OCSPNonce(r);else if("ocspNoCheck"==s)a=new n.OCSPNoCheck(r);else if("adobeTimeStamp"==s)a=new n.AdobeTimeStamp(r);else{if("subjectDirectoryAttributes"!=s)throw new Error("extension not supported:"+JSON.stringify(r));a=new n.SubjectDirectoryAttributes(r)}null!=a&&e.push(a)}return new i({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.x509.Extensions,Je.asn1.ASN1Object),Je.asn1.x509.Extension=function(e){Je.asn1.x509.Extension.superclass.constructor.call(this);var t=Je.asn1,i=t.DERObjectIdentifier,n=t.DEROctetString;t.DERBitString;var r=t.DERBoolean,s=t.DERSequence;this.tohex=function(){var e=new i({oid:this.oid}),t=new n({hex:this.getExtnValueHex()}),a=new Array;return a.push(e),this.critical&&a.push(new r),a.push(t),new s({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.critical=!1,void 0!==e&&void 0!==e.critical&&(this.critical=e.critical)},Nt(Je.asn1.x509.Extension,Je.asn1.ASN1Object),Je.asn1.x509.KeyUsage=function(e){Je.asn1.x509.KeyUsage.superclass.constructor.call(this,e);var t=Error,i={digitalSignature:0,nonRepudiation:1,keyEncipherment:2,dataEncipherment:3,keyAgreement:4,keyCertSign:5,cRLSign:6,encipherOnly:7,decipherOnly:8};this.getExtnValueHex=function(){var e=this.getBinValue();return this.asn1ExtnValue=new Je.asn1.DERBitString({bin:e}),this.asn1ExtnValue.tohex()},this.getBinValue=function(){var e=this.params;if("object"!=typeof e||"object"!=typeof e.names&&"string"!=typeof e.bin)throw new t("parameter not yet set");if(null!=e.names)return Pt(e.names,i);if(null!=e.bin)return e.bin;throw new t("parameter not set properly")},this.oid="2.5.29.15",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.KeyUsage,Je.asn1.x509.Extension),Je.asn1.x509.BasicConstraints=function(e){Je.asn1.x509.BasicConstraints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERBoolean,n=t.DERInteger,r=t.DERSequence;this.getExtnValueHex=function(){var e=new Array;this.cA&&e.push(new i),this.pathLen>-1&&e.push(new n({int:this.pathLen}));var t=new r({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.oid="2.5.29.19",this.cA=!1,this.pathLen=-1,void 0!==e&&(void 0!==e.cA&&(this.cA=e.cA),void 0!==e.pathLen&&(this.pathLen=e.pathLen))},Nt(Je.asn1.x509.BasicConstraints,Je.asn1.x509.Extension),Je.asn1.x509.CRLDistributionPoints=function(e){Je.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],r=0;r<e.length;r++)if(e[r]instanceof Je.asn1.ASN1Object)n.push(e[r]);else{var s=new i.DistributionPoint(e[r]);n.push(s)}this.asn1ExtnValue=new t.DERSequence({array:n})},this.setByOneURI=function(e){var t=new i.DistributionPoint({fulluri:e});this.setByDPArray([t])},this.oid="2.5.29.31",void 0!==e&&(void 0!==e.array?this.setByDPArray(e.array):void 0!==e.uri&&this.setByOneURI(e.uri))},Nt(Je.asn1.x509.CRLDistributionPoints,Je.asn1.x509.Extension),Je.asn1.x509.DistributionPoint=function(e){Je.asn1.x509.DistributionPoint.superclass.constructor.call(this);var t=Je.asn1,i=t.x509.DistributionPointName;this.tohex=function(){var e=new t.DERSequence;if(null!=this.asn1DP){var i=new t.DERTaggedObject({explicit:!0,tag:"a0",obj:this.asn1DP});e.appendASN1Object(i)}return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.dpobj?this.asn1DP=e.dpobj:void 0!==e.dpname?this.asn1DP=new i(e.dpname):void 0!==e.fulluri&&(this.asn1DP=new i({full:[{uri:e.fulluri}]})))},Nt(Je.asn1.x509.DistributionPoint,Je.asn1.ASN1Object),Je.asn1.x509.DistributionPointName=function(e){Je.asn1.x509.DistributionPointName.superclass.constructor.call(this);var t=Je.asn1,i=t.DERTaggedObject;if(this.tohex=function(){if("full"!=this.type)throw new Error("currently type shall be 'full': "+this.type);return this.asn1Obj=new i({explicit:!1,tag:this.tag,obj:this.asn1V}),this.hTLV=this.asn1Obj.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e)if(t.x509.GeneralNames.prototype.isPrototypeOf(e))this.type="full",this.tag="a0",this.asn1V=e;else{if(void 0===e.full)throw new Error("This class supports GeneralNames only as argument");this.type="full",this.tag="a0",this.asn1V=new t.x509.GeneralNames(e.full)}},Nt(Je.asn1.x509.DistributionPointName,Je.asn1.ASN1Object),Je.asn1.x509.CertificatePolicies=function(e){Je.asn1.x509.CertificatePolicies.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509,n=t.DERSequence,r=i.PolicyInformation;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++)e.push(new r(this.params.array[t]));var i=new n({array:e});return this.asn1ExtnValue=i,this.asn1ExtnValue.tohex()},this.oid="2.5.29.32",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.CertificatePolicies,Je.asn1.x509.Extension),Je.asn1.x509.PolicyInformation=function(e){Je.asn1.x509.PolicyInformation.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier,r=t.x509.PolicyQualifierInfo;this.params=null,this.tohex=function(){if(void 0===this.params.policyoid&&void 0===this.params.array)throw new Error("parameter oid and array missing");var e=[new n(this.params.policyoid)];if(void 0!==this.params.array){for(var t=[],s=0;s<this.params.array.length;s++)t.push(new r(this.params.array[s]));t.length>0&&e.push(new i({array:t}))}return new i({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyInformation,Je.asn1.ASN1Object),Je.asn1.x509.PolicyQualifierInfo=function(e){Je.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.DERIA5String,r=t.DERObjectIdentifier,s=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new i({array:[new r({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new i({array:[new r({oid:"1.3.6.1.5.5.7.2.2"}),new s(this.params.unotice)]}).tohex():void 0},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyQualifierInfo,Je.asn1.ASN1Object),Je.asn1.x509.UserNotice=function(e){Je.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=Je.asn1.DERSequence;Je.asn1.DERInteger;var i=Je.asn1.x509.DisplayText,n=Je.asn1.x509.NoticeReference;this.params=null,this.tohex=function(){var e=[];return void 0!==this.params.noticeref&&e.push(new n(this.params.noticeref)),void 0!==this.params.exptext&&e.push(new i(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.UserNotice,Je.asn1.ASN1Object),Je.asn1.x509.NoticeReference=function(e){Je.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=Je.asn1.DERSequence,i=Je.asn1.DERInteger,n=Je.asn1.x509.DisplayText;this.params=null,this.tohex=function(){var e=[];if(void 0!==this.params.org&&e.push(new n(this.params.org)),void 0!==this.params.noticenum){for(var r=[],s=this.params.noticenum,a=0;a<s.length;a++)r.push(new i(s[a]));e.push(new t({array:r}))}if(0==e.length)throw new Error("parameter is empty");return new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.NoticeReference,Je.asn1.ASN1Object),Je.asn1.x509.DisplayText=function(e){Je.asn1.x509.DisplayText.superclass.constructor.call(this,e),this.hT="0c",void 0!==e&&("ia5"===e.type?this.hT="16":"vis"===e.type?this.hT="1a":"bmp"===e.type&&(this.hT="1e"))},Nt(Je.asn1.x509.DisplayText,Je.asn1.DERAbstractString),Je.asn1.x509.PolicyMappings=function(e){Je.asn1.x509.PolicyMappings.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){for(var e=this.params,t=[],n=0;n<e.array.length;n++){var r=e.array[n];t.push({seq:[{oid:r[0]},{oid:r[1]}]})}return this.asn1ExtnValue=i({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.33",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyMappings,Je.asn1.x509.Extension),Je.asn1.x509.PolicyConstraints=function(e){Je.asn1.x509.PolicyConstraints.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];return null!=e.reqexp&&t.push({tag:{tagi:"80",obj:{int:e.reqexp}}}),null!=e.inhibit&&t.push({tag:{tagi:"81",obj:{int:e.inhibit}}}),this.asn1ExtnValue=i({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.36",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.PolicyConstraints,Je.asn1.x509.Extension),Je.asn1.x509.InhibitAnyPolicy=function(e){Je.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this,e);var t=Je.asn1;t.x509;var i=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=i({int:this.params.skip}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.54",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.InhibitAnyPolicy,Je.asn1.x509.Extension),Je.asn1.x509.NameConstraints=function(e){Je.asn1.x509.NameConstraints.superclass.constructor.call(this,e);var t=Je.asn1,i=t.x509,n=t.ASN1Util.newObject,r=i.GeneralSubtree;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];if(null!=e.permit&&null!=e.permit.length){for(var i=[],s=0;s<e.permit.length;s++)i.push(new r(e.permit[s]));t.push({tag:{tagi:"a0",obj:{seq:i}}})}if(null!=e.exclude&&null!=e.exclude.length){var a=[];for(s=0;s<e.exclude.length;s++)a.push(new r(e.exclude[s]));t.push({tag:{tagi:"a1",obj:{seq:a}}})}return this.asn1ExtnValue=n({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.30",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.NameConstraints,Je.asn1.x509.Extension),Je.asn1.x509.GeneralSubtree=function(e){Je.asn1.x509.GeneralSubtree.superclass.constructor.call(this);var t=Je.asn1,i=t.x509.GeneralName,n=t.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params,t=[new i(e)];return null!=e.min&&t.push({tag:{tagi:"80",obj:{int:e.min}}}),null!=e.max&&t.push({tag:{tagi:"81",obj:{int:e.max}}}),n({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.GeneralSubtree,Je.asn1.ASN1Object),Je.asn1.x509.ExtKeyUsage=function(e){Je.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,e);var t=Je.asn1;this.setPurposeArray=function(e){this.asn1ExtnValue=new t.DERSequence;for(var i=0;i<e.length;i++){var n=new t.DERObjectIdentifier(e[i]);this.asn1ExtnValue.appendASN1Object(n)}},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.37",void 0!==e&&void 0!==e.array&&this.setPurposeArray(e.array)},Nt(Je.asn1.x509.ExtKeyUsage,Je.asn1.x509.Extension),Je.asn1.x509.AuthorityKeyIdentifier=function(e){Je.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,e);var t=Je,i=t.asn1,n=i.DERTaggedObject,r=i.x509.GeneralNames;t.crypto.Util.isKey,this.asn1KID=null,this.asn1CertIssuer=null,this.asn1CertSN=null,this.getExtnValueHex=function(){var e=new Array;this.asn1KID&&e.push(new n({explicit:!1,tag:"80",obj:this.asn1KID})),this.asn1CertIssuer&&e.push(new n({explicit:!1,tag:"a1",obj:new r([{dn:this.asn1CertIssuer}])})),this.asn1CertSN&&e.push(new n({explicit:!1,tag:"82",obj:this.asn1CertSN}));var t=new i.DERSequence({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.setKIDByParam=function(e){if(void 0!==e.str||void 0!==e.hex)this.asn1KID=new Je.asn1.DEROctetString(e);else if("object"==typeof e&&Je.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN ")){var t=e;"string"==typeof e&&(t=kt.getKey(e));var i=kt.getKeyID(t);this.asn1KID=new Je.asn1.DEROctetString({hex:i})}},this.setCertIssuerByParam=function(e){void 0!==e.str||void 0!==e.ldapstr||void 0!==e.hex||void 0!==e.certsubject||void 0!==e.certissuer?this.asn1CertIssuer=new Je.asn1.x509.X500Name(e):"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&-1!=e.indexOf("CERTIFICATE")&&(this.asn1CertIssuer=new Je.asn1.x509.X500Name({certissuer:e}))},this.setCertSNByParam=function(e){if(void 0!==e.str||void 0!==e.bigint||void 0!==e.hex)this.asn1CertSN=new Je.asn1.DERInteger(e);else if("string"==typeof e&&-1!=e.indexOf("BEGIN ")&&e.indexOf("CERTIFICATE")){var t=new Ht;t.readCertPEM(e);var i=t.getSerialNumberHex();this.asn1CertSN=new Je.asn1.DERInteger({hex:i})}},this.oid="2.5.29.35",void 0!==e&&(void 0!==e.kid&&this.setKIDByParam(e.kid),void 0!==e.issuer&&this.setCertIssuerByParam(e.issuer),void 0!==e.sn&&this.setCertSNByParam(e.sn),void 0!==e.issuersn&&"string"==typeof e.issuersn&&-1!=e.issuersn.indexOf("BEGIN ")&&e.issuersn.indexOf("CERTIFICATE")&&(this.setCertSNByParam(e.issuersn),this.setCertIssuerByParam(e.issuersn)))},Nt(Je.asn1.x509.AuthorityKeyIdentifier,Je.asn1.x509.Extension),Je.asn1.x509.SubjectKeyIdentifier=function(e){Je.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this,e);var t=Je.asn1.DEROctetString;this.asn1KID=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=this.asn1KID,this.asn1ExtnValue.tohex()},this.setKIDByParam=function(e){if(void 0!==e.str||void 0!==e.hex)this.asn1KID=new t(e);else if("object"==typeof e&&Je.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN")){var i=e;"string"==typeof e&&(i=kt.getKey(e));var n=kt.getKeyID(i);this.asn1KID=new Je.asn1.DEROctetString({hex:n})}},this.oid="2.5.29.14",void 0!==e&&void 0!==e.kid&&this.setKIDByParam(e.kid)},Nt(Je.asn1.x509.SubjectKeyIdentifier,Je.asn1.x509.Extension),Je.asn1.x509.AuthorityInfoAccess=function(e){Je.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,e),this.setAccessDescriptionArray=function(e){for(var t=new Array,i=Je.asn1,n=i.DERSequence,r=i.DERObjectIdentifier,s=i.x509.GeneralName,a=0;a<e.length;a++){var o,c=e[a];if(void 0!==c.ocsp)o=new n({array:[new r({oid:"1.3.6.1.5.5.7.48.1"}),new s({uri:c.ocsp})]});else{if(void 0===c.caissuer)throw new Error("unknown AccessMethod parameter: "+JSON.stringify(c));o=new n({array:[new r({oid:"1.3.6.1.5.5.7.48.2"}),new s({uri:c.caissuer})]})}t.push(o)}this.asn1ExtnValue=new n({array:t})},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.1.1",void 0!==e&&void 0!==e.array&&this.setAccessDescriptionArray(e.array)},Nt(Je.asn1.x509.AuthorityInfoAccess,Je.asn1.x509.Extension),Je.asn1.x509.SubjectAltName=function(e){Je.asn1.x509.SubjectAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new Je.asn1.x509.GeneralNames(e)},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.17",void 0!==e&&void 0!==e.array&&this.setNameArray(e.array)},Nt(Je.asn1.x509.SubjectAltName,Je.asn1.x509.Extension),Je.asn1.x509.IssuerAltName=function(e){Je.asn1.x509.IssuerAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new Je.asn1.x509.GeneralNames(e)},this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.oid="2.5.29.18",void 0!==e&&void 0!==e.array&&this.setNameArray(e.array)},Nt(Je.asn1.x509.IssuerAltName,Je.asn1.x509.Extension),Je.asn1.x509.SubjectDirectoryAttributes=function(e){Je.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERSequence,n=t.ASN1Util.newObject,r=t.x509.OID.name2oid;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++){var s=this.params.array[t];if(null==s.attr||null==s.array){var a={seq:[{oid:"1.2.3.4"},{set:[{utf8str:"DE"}]}]};if("dateOfBirth"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={gentime:s.str};else if("placeOfBirth"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={utf8str:s.str};else if("gender"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str};else if("countryOfCitizenship"==s.attr)a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str};else{if("countryOfResidence"!=s.attr)throw new Error("unsupported attribute: "+s.attr);a.seq[0].oid=r(s.attr),a.seq[1].set[0]={prnstr:s.str}}e.push(new n(a))}else{var o={seq:[{oid:s.attr},{set:s.array}]};e.push(n(o))}}var c=new i({array:e});return this.asn1ExtnValue=c,this.asn1ExtnValue.tohex()},this.oid="2.5.29.9",void 0!==e&&(this.params=e)},Nt(Je.asn1.x509.SubjectDirectoryAttributes,Je.asn1.x509.Extension),Je.asn1.x509.PrivateExtension=function(e){Je.asn1.x509.PrivateExtension.superclass.constructor.call(this,e);var t=Je,i=t.lang.String.isHex,n=t.asn1,r=n.x509.OID.name2oid,s=n.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.oid=r(e.extname),this.params=e},this.getExtnValueHex=function(){if(null==this.params.extname||null==this.params.extn)throw new Error("extname or extnhex not specified");var e=this.params.extn;if("string"==typeof e&&i(e))return e;if("object"==typeof e)try{return s(e).tohex()}catch(e){}throw new Error("unsupported extn value")},null!=e&&this.setByParam(e)},Nt(Je.asn1.x509.PrivateExtension,Je.asn1.x509.Extension),Je.asn1.x509.CRL=function(e){Je.asn1.x509.CRL.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERBitString,r=t.x509,s=r.AlgorithmIdentifier,a=r.TBSCertList;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=new a(this.params).tohex(),t=new Je.crypto.Signature({alg:this.params.sigalg});t.init(this.params.cakey),t.updateHex(e);var i=t.sign();this.params.sighex=i},this.getPEM=function(){return ht(this.tohex(),"X509 CRL")},this.tohex=function(){var e=this.params;if(null==e.tbsobj&&(e.tbsobj=new a(e)),null==e.sighex&&null!=e.cakey&&this.sign(),null==e.sighex)throw new Error("sighex or cakey parameter not defined");var t=[];return t.push(e.tbsobj),t.push(new s({name:e.sigalg})),t.push(new n({hex:"00"+e.sighex})),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRL,Je.asn1.ASN1Object),Je.asn1.x509.TBSCertList=function(e){Je.asn1.x509.TBSCertList.superclass.constructor.call(this);var t=Je.asn1,i=t.DERInteger,n=t.DERSequence,r=t.DERTaggedObject;t.DERObjectIdentifier;var s=t.x509,a=s.AlgorithmIdentifier,o=s.Time,c=s.Extensions,d=s.X500Name;this.params=null,this.setByParam=function(e){this.params=e},this.getRevCertSequence=function(){for(var e=[],t=this.params.revcert,r=0;r<t.length;r++){var s=[new i(t[r].sn),new o(t[r].date)];null!=t[r].ext&&s.push(new c(t[r].ext)),e.push(new n({array:s}))}return new n({array:e})},this.tohex=function(){var e=[],t=this.params;if(null!=t.version){var s=t.version-1,l=new i({int:s});e.push(l)}if(e.push(new a({name:t.sigalg})),e.push(new d(t.issuer)),e.push(new o(t.thisupdate)),null!=t.nextupdate&&e.push(new o(t.nextupdate)),null!=t.revcert&&e.push(this.getRevCertSequence()),null!=t.ext){var h=new c(t.ext);e.push(new r({tag:"a0",explicit:!0,obj:h}))}return new n({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.TBSCertList,Je.asn1.ASN1Object),Je.asn1.x509.CRLEntry=function(e){Je.asn1.x509.CRLEntry.superclass.constructor.call(this);var t=Je.asn1;this.setCertSerial=function(e){this.sn=new t.DERInteger(e)},this.setRevocationDate=function(e){this.time=new t.x509.Time(e)},this.tohex=function(){var e=new t.DERSequence({array:[this.sn,this.time]});return this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.time&&this.setRevocationDate(e.time),void 0!==e.sn&&this.setCertSerial(e.sn))},Nt(Je.asn1.x509.CRLEntry,Je.asn1.ASN1Object),Je.asn1.x509.CRLNumber=function(e){Je.asn1.x509.CRLNumber.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DERInteger(this.params.num),this.asn1ExtnValue.tohex()},this.oid="2.5.29.20",null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRLNumber,Je.asn1.x509.Extension),Je.asn1.x509.CRLReason=function(e){Je.asn1.x509.CRLReason.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DEREnumerated(this.params.code),this.asn1ExtnValue.tohex()},this.oid="2.5.29.21",null!=e&&(this.params=e)},Nt(Je.asn1.x509.CRLReason,Je.asn1.x509.Extension),Je.asn1.x509.OCSPNonce=function(e){Je.asn1.x509.OCSPNonce.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DEROctetString(this.params),this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.2",null!=e&&(this.params=e)},Nt(Je.asn1.x509.OCSPNonce,Je.asn1.x509.Extension),Je.asn1.x509.OCSPNoCheck=function(e){Je.asn1.x509.OCSPNoCheck.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new Je.asn1.DERNull,this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.5",null!=e&&(this.params=e)},Nt(Je.asn1.x509.OCSPNoCheck,Je.asn1.x509.Extension),Je.asn1.x509.AdobeTimeStamp=function(e){Je.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this,e);var t=Je.asn1,i=t.DERInteger,n=t.DERBoolean,r=t.DERSequence,s=t.x509.GeneralName;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[new i(1)];return t.push(new s({uri:e.uri})),null!=e.reqauth&&t.push(new n(e.reqauth)),this.asn1ExtnValue=new r({array:t}),this.asn1ExtnValue.tohex()},this.oid="1.2.840.113583.1.1.9.1",void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.AdobeTimeStamp,Je.asn1.x509.Extension),Je.asn1.x509.X500Name=function(e){Je.asn1.x509.X500Name.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=Je.asn1,i=t.x509,n=i.RDN;this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var i=e.split("/");i.shift();for(var r=[],s=0;s<i.length;s++)if(i[s].match(/^[^=]+=.+$/))r.push(i[s]);else{var a=r.length-1;r[a]=r[a]+"/"+i[s]}for(s=0;s<r.length;s++)this.asn1Array.push(new n({str:r[s],rule:this.sRule}))},this.setByLdapString=function(e,t){void 0!==t&&(this.sRule=t);var n=i.X500Name.ldapToCompat(e);this.setByString(n,t)},this.setByObject=function(e,t){for(var i in void 0!==t&&(this.sRule=t),e)if(e.hasOwnProperty(i)){var r=new n({str:i+"="+e[i],rule:this.sRule});this.asn1Array?this.asn1Array.push(r):this.asn1Array=[r]}},this.setByParam=function(e){var t;(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.array)?this.paramArray=e.array:void 0!==e.str?this.setByString(e.str):void 0!==e.ldapstr?this.setByLdapString(e.ldapstr):void 0!==e.hex?this.hTLV=e.hex:void 0!==e.certissuer?((t=new Ht).readCertPEM(e.certissuer),this.hTLV=t.getIssuerHex()):void 0!==e.certsubject?((t=new Ht).readCertPEM(e.certsubject),this.hTLV=t.getSubjectHex()):"object"==typeof e&&void 0===e.certsubject&&void 0===e.certissuer&&this.setByObject(e)},this.tohex=function(){if("string"==typeof this.hTLV)return this.hTLV;if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var i={array:this.paramArray[e]};"utf8"!=this.sRule&&(i.rule=this.sRule);var r=new n(i);this.asn1Array.push(r)}var s=new t.DERSequence({array:this.asn1Array});return this.hTLV=s.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.X500Name,Je.asn1.ASN1Object),Je.asn1.x509.X500Name.compatToLDAP=function(e){if("/"!==e.substr(0,1))throw"malformed input";var t=(e=e.substr(1)).split("/");return t.reverse(),t=t.map((function(e){return e.replace(/,/,"\\,")})),t.join(",")},Je.asn1.x509.X500Name.onelineToLDAP=function(e){return Je.asn1.x509.X500Name.compatToLDAP(e)},Je.asn1.x509.X500Name.ldapToCompat=function(e){for(var t=e.split(","),i=!1,n=[],r=0;t.length>0;r++){var s=t.shift();if(!0===i){var a=(n.pop()+","+s).replace(/\\,/g,",");n.push(a),i=!1}else n.push(s);"\\"===s.substr(-1,1)&&(i=!0)}return n=n.map((function(e){return e.replace("/","\\/")})),n.reverse(),"/"+n.join("/")},Je.asn1.x509.X500Name.ldapToOneline=function(e){return Je.asn1.x509.X500Name.ldapToCompat(e)},Je.asn1.x509.RDN=function(e){Je.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=Je.asn1.x509.AttributeTypeAndValue;this.setByParam=function(e){void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.str&&this.addByMultiValuedString(e.str),void 0!==e.array&&(this.paramArray=e.array)},this.addByString=function(e){this.asn1Array.push(new Je.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=Je.asn1.x509.RDN.parseString(e),i=0;i<t.length;i++)this.addByString(t[i])},this.tohex=function(){if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var i=this.paramArray[e];void 0!==i.rule&&"utf8"!=this.sRule&&(i.rule=this.sRule);var n=new t(i);this.asn1Array.push(n)}var r=new Je.asn1.DERSet({array:this.asn1Array});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.RDN,Je.asn1.ASN1Object),Je.asn1.x509.RDN.parseString=function(e){for(var t=e.split(/\+/),i=!1,n=[],r=0;t.length>0;r++){var s=t.shift();if(!0===i){var a=(n.pop()+"+"+s).replace(/\\\+/g,"+");n.push(a),i=!1}else n.push(s);"\\"===s.substr(-1,1)&&(i=!0)}var o=!1,c=[];for(r=0;n.length>0;r++){s=n.shift();if(!0===o){var d=c.pop();if(s.match(/"$/)){a=(d+"+"+s).replace(/^([^=]+)="(.*)"$/,"$1=$2");c.push(a),o=!1}else c.push(d+"+"+s)}else c.push(s);s.match(/^[^=]+="/)&&(o=!0)}return c},Je.asn1.x509.AttributeTypeAndValue=function(e){Je.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=Je,i=t.asn1,n=i.DERSequence,r=i.DERUTF8String,s=i.DERPrintableString,a=i.DERTeletexString,o=i.DERIA5String,c=i.DERVisibleString,d=i.DERBMPString,l=t.lang.String.isMail,h=t.lang.String.isPrintable;this.setByParam=function(e){if(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.ds&&(this.dsType=e.ds),void 0===e.value&&void 0!==e.str){var t=e.str.match(/^([^=]+)=(.+)$/);if(!t)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.sType=t[1],this.sValue=t[2]}else this.sType=e.type,this.sValue=e.value},this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var i=e.match(/^([^=]+)=(.+)$/);if(!i)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(i[1],i[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,i=this.sRule;return"prn"===i?"CN"==e&&l(t)?"ia5":h(t)?"prn":"utf8":"utf8"===i?"CN"==e&&l(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,i){void 0!==i&&(this.sRule=i),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new r({str:t});if("prn"==e)return new s({str:t});if("tel"==e)return new a({str:t});if("ia5"==e)return new o({str:t});if("vis"==e)return new c({str:t});if("bmp"==e)return new d({str:t});throw new Error("unsupported directory string type: type="+e+" value="+t)},this.tohex=function(){null==this.dsType&&(this.dsType=this._getDsType());var e=Je.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),i=new n({array:[e,t]});return this.TLV=i.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.AttributeTypeAndValue,Je.asn1.ASN1Object),Je.asn1.x509.SubjectPublicKeyInfo=function(e){Je.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=Je,i=t.asn1,n=i.DERInteger,r=i.DERBitString,s=i.DERObjectIdentifier,a=i.DERSequence,o=i.ASN1Util.newObject,c=i.x509.AlgorithmIdentifier,d=t.crypto;d.ECDSA,d.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new a({array:[this.asn1AlgId,this.asn1SubjPKey]})},this.tohex=function(){var e=this.getASN1Object();return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.setPubKey=function(e){try{if(e instanceof Ge){var t=o({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new c({name:"rsaEncryption"}),this.asn1SubjPKey=new r({hex:"00"+t})}}catch(e){}try{if(e instanceof Je.crypto.ECDSA){var i=new s({name:e.curveName});this.asn1AlgId=new c({name:"ecPublicKey",asn1params:i}),this.asn1SubjPKey=new r({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof Je.crypto.DSA){i=new o({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new c({name:"dsa",asn1params:i});var a=new n({bigint:e.y});this.asn1SubjPKey=new r({hex:"00"+a.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},Nt(Je.asn1.x509.SubjectPublicKeyInfo,Je.asn1.ASN1Object),Je.asn1.x509.Time=function(e){Je.asn1.x509.Time.superclass.constructor.call(this);var t=Je.asn1,i=t.DERUTCTime,n=t.DERGeneralizedTime;this.params=null,this.type=null,this.setTimeParams=function(e){this.timeParams=e},this.setByParam=function(e){this.params=e},this.getType=function(e){return e.match(/^[0-9]{12}Z$/)?"utc":e.match(/^[0-9]{14}Z$/)?"gen":e.match(/^[0-9]{12}\.[0-9]+Z$/)?"utc":e.match(/^[0-9]{14}\.[0-9]+Z$/)?"gen":null},this.tohex=function(){var e=this.params,t=null;if("string"==typeof e&&(e={str:e}),null==e||!e.str||null!=e.type&&null!=e.type||(e.type=this.getType(e.str)),null!=e&&e.str?("utc"==e.type&&(t=new i(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new i,null==t)throw new Error("wrong setting for Time");return this.TLV=t.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Je.asn1.x509.Time_bak=function(e){Je.asn1.x509.Time_bak.superclass.constructor.call(this);var t=Je.asn1,i=t.DERUTCTime,n=t.DERGeneralizedTime;this.setTimeParams=function(e){this.timeParams=e},this.tohex=function(){var e=null;return e=null!=this.timeParams?"utc"==this.type?new i(this.timeParams):new n(this.timeParams):"utc"==this.type?new i:new n,this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},this.type="utc",void 0!==e&&(void 0!==e.type?this.type=e.type:void 0!==e.str&&(e.str.match(/^[0-9]{12}Z$/)&&(this.type="utc"),e.str.match(/^[0-9]{14}Z$/)&&(this.type="gen")),this.timeParams=e)},Nt(Je.asn1.x509.Time,Je.asn1.ASN1Object),Je.asn1.x509.AlgorithmIdentifier=function(e){Je.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=Je.asn1,i=t.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;if(this.tohex=function(){if(null===this.nameAlg&&null===this.asn1Alg)throw new Error("algorithm not specified");if(null!==this.nameAlg){var e=null;for(var n in i)n===this.nameAlg&&(e=i[n]);if(null!==e)return this.hTLV=e,this.hTLV}null!==this.nameAlg&&null===this.asn1Alg&&(this.asn1Alg=t.x509.OID.name2obj(this.nameAlg));var r=[this.asn1Alg];null!==this.asn1Params&&r.push(this.asn1Params);var s=new t.DERSequence({array:r});return this.hTLV=s.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.name&&(this.nameAlg=e.name),void 0!==e.asn1params&&(this.asn1Params=e.asn1params),void 0!==e.paramempty&&(this.paramEmpty=e.paramempty)),null===this.asn1Params&&!1===this.paramEmpty&&null!==this.nameAlg){void 0!==this.nameAlg.name&&(this.nameAlg=this.nameAlg.name);var n=this.nameAlg.toLowerCase();"withdsa"!==n.substr(-7,7)&&"withecdsa"!==n.substr(-9,9)&&(this.asn1Params=new t.DERNull)}},Nt(Je.asn1.x509.AlgorithmIdentifier,Je.asn1.ASN1Object),Je.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},Je.asn1.x509.GeneralName=function(e){Je.asn1.x509.GeneralName.superclass.constructor.call(this);var t=Je.asn1,i=t.x509,n=i.X500Name,r=i.OtherName,s=t.DERIA5String;t.DERPrintableString;var a=t.DEROctetString,o=t.DERTaggedObject,c=t.ASN1Object,d=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,i=this.params,l=!1;if(void 0!==i.other)e="a0",t=new r(i.other);else if(void 0!==i.rfc822)e="81",t=new s({str:i.rfc822});else if(void 0!==i.dns)e="82",t=new s({str:i.dns});else if(void 0!==i.dn)e="a4",l=!0,t="string"==typeof i.dn?new n({str:i.dn}):i.dn instanceof Je.asn1.x509.X500Name?i.dn:new n(i.dn);else if(void 0!==i.ldapdn)e="a4",l=!0,t=new n({ldapstr:i.ldapdn});else if(void 0!==i.certissuer||void 0!==i.certsubj){var h,u;e="a4",l=!0;var p=null;if(void 0!==i.certsubj?(h=!1,u=i.certsubj):(h=!0,u=i.certissuer),u.match(/^[0-9A-Fa-f]+$/),-1!=u.indexOf("-----BEGIN ")&&(p=ut(u)),null==p)throw new Error("certsubj/certissuer not cert");var g,f=new Ht;f.hex=p,g=h?f.getIssuerHex():f.getSubjectHex(),(t=new c).hTLV=g}else if(void 0!==i.uri)e="86",t=new s({str:i.uri});else{if(void 0===i.ip)throw new d("improper params");var m;e="87";var v=i.ip;try{if(v.match(/^[0-9a-f]+$/)){var y=v.length;if(8!=y&&16!=y&&32!=y&&64!=y)throw"err";m=v}else m=bt(v)}catch(e){throw new d("malformed IP address: "+i.ip+":"+e.message)}t=new a({hex:m})}return new o({tag:e,explicit:l,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.GeneralName,Je.asn1.ASN1Object),Je.asn1.x509.GeneralNames=function(e){Je.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=Je.asn1;this.setByParamArray=function(e){for(var i=0;i<e.length;i++){var n=new t.x509.GeneralName(e[i]);this.asn1Array.push(n)}},this.tohex=function(){return new t.DERSequence({array:this.asn1Array}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.asn1Array=new Array,void 0!==e&&this.setByParamArray(e)},Nt(Je.asn1.x509.GeneralNames,Je.asn1.ASN1Object),Je.asn1.x509.OtherName=function(e){Je.asn1.x509.OtherName.superclass.constructor.call(this);var t=Je.asn1,i=t.DERObjectIdentifier,n=t.DERSequence,r=t.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if(null==e.oid||null==e.value)throw new Error("oid or value not specified");var t=new i({oid:e.oid}),s=r({tag:{tag:"a0",explicit:!0,obj:e.value}});return new n({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.x509.OtherName,Je.asn1.ASN1Object),Je.asn1.x509.OID=new function(){var e=Je.asn1.DERObjectIdentifier;this.name2oidList={"aes128-CBC":"2.16.840.1.101.3.4.1.2","aes256-CBC":"2.16.840.1.101.3.4.1.42",sha1:"1.3.14.3.2.26",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",sha224:"2.16.840.1.101.3.4.2.4",md5:"1.2.840.113549.2.5",md2:"1.3.14.7.2.2.1",ripemd160:"1.3.36.3.2.1",hmacWithSHA1:"1.2.840.113549.2.7",hmacWithSHA224:"1.2.840.113549.2.8",hmacWithSHA256:"1.2.840.113549.2.9",hmacWithSHA384:"1.2.840.113549.2.10",hmacWithSHA512:"1.2.840.113549.2.11",MD2withRSA:"1.2.840.113549.1.1.2",MD4withRSA:"1.2.840.113549.1.1.3",MD5withRSA:"1.2.840.113549.1.1.4",SHA1withRSA:"1.2.840.113549.1.1.5","pkcs1-MGF":"1.2.840.113549.1.1.8",rsaPSS:"1.2.840.113549.1.1.10",SHA224withRSA:"1.2.840.113549.1.1.14",SHA256withRSA:"1.2.840.113549.1.1.11",SHA384withRSA:"1.2.840.113549.1.1.12",SHA512withRSA:"1.2.840.113549.1.1.13",SHA1withECDSA:"1.2.840.10045.4.1",SHA224withECDSA:"1.2.840.10045.4.3.1",SHA256withECDSA:"1.2.840.10045.4.3.2",SHA384withECDSA:"1.2.840.10045.4.3.3",SHA512withECDSA:"1.2.840.10045.4.3.4",dsa:"1.2.840.10040.4.1",SHA1withDSA:"1.2.840.10040.4.3",SHA224withDSA:"2.16.840.1.101.3.4.3.1",SHA256withDSA:"2.16.840.1.101.3.4.3.2",rsaEncryption:"1.2.840.113549.1.1.1",commonName:"2.5.4.3",countryName:"2.5.4.6",localityName:"2.5.4.7",stateOrProvinceName:"2.5.4.8",streetAddress:"2.5.4.9",organizationName:"2.5.4.10",organizationalUnitName:"2.5.4.11",domainComponent:"0.9.2342.19200300.100.1.25",userId:"0.9.2342.19200300.100.1.1",surname:"2.5.4.4",givenName:"2.5.4.42",title:"2.5.4.12",distinguishedName:"2.5.4.49",emailAddress:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3",subjectDirectoryAttributes:"2.5.29.9",subjectKeyIdentifier:"2.5.29.14",keyUsage:"2.5.29.15",subjectAltName:"2.5.29.17",issuerAltName:"2.5.29.18",basicConstraints:"2.5.29.19",cRLNumber:"2.5.29.20",cRLReason:"2.5.29.21",nameConstraints:"2.5.29.30",cRLDistributionPoints:"2.5.29.31",certificatePolicies:"2.5.29.32",anyPolicy:"2.5.29.32.0",policyMappings:"2.5.29.33",authorityKeyIdentifier:"2.5.29.35",policyConstraints:"2.5.29.36",extKeyUsage:"2.5.29.37",inhibitAnyPolicy:"2.5.29.54",authorityInfoAccess:"1.3.6.1.5.5.7.1.1",ocsp:"1.3.6.1.5.5.7.48.1",ocspBasic:"1.3.6.1.5.5.7.48.1.1",ocspNonce:"1.3.6.1.5.5.7.48.1.2",ocspNoCheck:"1.3.6.1.5.5.7.48.1.5",caIssuers:"1.3.6.1.5.5.7.48.2",anyExtendedKeyUsage:"2.5.29.37.0",serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",emailProtection:"1.3.6.1.5.5.7.3.4",timeStamping:"1.3.6.1.5.5.7.3.8",ocspSigning:"1.3.6.1.5.5.7.3.9",smtpUTF8Mailbox:"1.3.6.1.5.5.7.8.9",dateOfBirth:"1.3.6.1.5.5.7.9.1",placeOfBirth:"1.3.6.1.5.5.7.9.2",gender:"1.3.6.1.5.5.7.9.3",countryOfCitizenship:"1.3.6.1.5.5.7.9.4",countryOfResidence:"1.3.6.1.5.5.7.9.5",ecPublicKey:"1.2.840.10045.2.1","P-256":"1.2.840.10045.3.1.7",secp256r1:"1.2.840.10045.3.1.7",secp256k1:"1.3.132.0.10",secp384r1:"1.3.132.0.34",secp521r1:"1.3.132.0.35",pkcs5PBES2:"1.2.840.113549.1.5.13",pkcs5PBKDF2:"1.2.840.113549.1.5.12","des-EDE3-CBC":"1.2.840.113549.3.7",data:"1.2.840.113549.1.7.1","signed-data":"1.2.840.113549.1.7.2","enveloped-data":"1.2.840.113549.1.7.3","digested-data":"1.2.840.113549.1.7.5","encrypted-data":"1.2.840.113549.1.7.6","authenticated-data":"1.2.840.113549.1.9.16.1.2",tstinfo:"1.2.840.113549.1.9.16.1.4",signingCertificate:"1.2.840.113549.1.9.16.2.12",timeStampToken:"1.2.840.113549.1.9.16.2.14",signaturePolicyIdentifier:"1.2.840.113549.1.9.16.2.15",etsArchiveTimeStamp:"1.2.840.113549.1.9.16.2.27",signingCertificateV2:"1.2.840.113549.1.9.16.2.47",etsArchiveTimeStampV2:"1.2.840.113549.1.9.16.2.48",extensionRequest:"1.2.840.113549.1.9.14",contentType:"1.2.840.113549.1.9.3",messageDigest:"1.2.840.113549.1.9.4",signingTime:"1.2.840.113549.1.9.5",counterSignature:"1.2.840.113549.1.9.6",archiveTimeStampV3:"0.4.0.1733.2.4",pdfRevocationInfoArchival:"1.2.840.113583.1.1.8",adobeTimeStamp:"1.2.840.113583.1.1.9.1",smimeMailboxLegacy:"2.23.140.1.5.1.1",smimeMailboxMulti:"2.23.140.1.5.1.2",smimeMailboxStrict:"2.23.140.1.5.1.3",smimeOrganizationLegacy:"2.23.140.1.5.2.1",smimeOrganizationMulti:"2.23.140.1.5.2.2",smimeOrganizationStrict:"2.23.140.1.5.2.3",smimeSponsorLegacy:"2.23.140.1.5.3.1",smimeSponsorMulti:"2.23.140.1.5.3.2",smimeSponsorStrict:"2.23.140.1.5.3.3",smimeIndividualLegacy:"2.23.140.1.5.4.1",smimeIndividualMulti:"2.23.140.1.5.4.2",smimeIndividualStrict:"2.23.140.1.5.4.3"},this.atype2oidList={CN:"2.5.4.3",L:"2.5.4.7",ST:"2.5.4.8",O:"2.5.4.10",OU:"2.5.4.11",C:"2.5.4.6",STREET:"2.5.4.9",DC:"0.9.2342.19200300.100.1.25",UID:"0.9.2342.19200300.100.1.1",SN:"2.5.4.4",T:"2.5.4.12",GN:"2.5.4.42",DN:"2.5.4.49",E:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3"},this.objCache={},this.name2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];if(void 0===this.name2oidList[t])throw"Name of ObjectIdentifier not defined: "+t;var i=this.name2oidList[t],n=new e({oid:i});return this.objCache[t]=n,n},this.atype2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];var i;if(t.match(/^\d+\.\d+\.[0-9.]+$/))i=t;else if(void 0!==this.atype2oidList[t])i=this.atype2oidList[t];else{if(void 0===this.name2oidList[t])throw new Error("AttributeType name undefined: "+t);i=this.name2oidList[t]}var n=new e({oid:i});return this.objCache[t]=n,n},this.registerOIDs=function(e){if(this.checkOIDs(e))for(var t in e)this.name2oidList[t]=e[t]},this.checkOIDs=function(e){try{var t=Object.keys(e);return 0!=t.length&&(t.map((function(e,t,i){if(!this[e].match(/^[0-2]\.[0-9.]+$/))throw new Error("value is not OID")}),e),!0)}catch(e){return!1}}},Je.asn1.x509.OID.oid2name=function(e){var t=Je.asn1.x509.OID.name2oidList;for(var i in t)if(t[i]==e)return i;return""},Je.asn1.x509.OID.oid2atype=function(e){var t=Je.asn1.x509.OID.atype2oidList;for(var i in t)if(t[i]==e)return i;return e},Je.asn1.x509.OID.name2oid=function(e){if(e.match(/^[0-9.]+$/))return e;var t=Je.asn1.x509.OID.name2oidList;return void 0===t[e]?"":t[e]},Je.asn1.x509.X509Util={},Je.asn1.x509.X509Util.newCertPEM=function(e){var t=Je.asn1.x509;return t.TBSCertificate,new(0,t.Certificate)(e).getPEM()},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.cms&&Je.asn1.cms||(Je.asn1.cms={}),Je.asn1.cms.Attribute=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERSet,s=i.DERObjectIdentifier;this.params=null,this.typeOid=null,this.setByParam=function(e){this.params=e},this.getValueArray=function(){throw new t("not yet implemented abstract")},this.tohex=function(){var e=new s({oid:this.typeOid}),t=new r({array:this.getValueArray()});return new n({array:[e,t]}).tohex()},this.getEncodedHex=function(){return this.tohex()}},Nt(Je.asn1.cms.Attribute,Je.asn1.ASN1Object),Je.asn1.cms.ContentType=function(e){var t=Je.asn1;t.cms.ContentType.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.3",this.getValueArray=function(){return[new t.DERObjectIdentifier(this.params.type)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ContentType,Je.asn1.cms.Attribute),Je.asn1.cms.MessageDigest=function(e){var t=Je.asn1,i=t.DEROctetString;t.cms.MessageDigest.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.4",this.getValueArray=function(){return[new i(this.params)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.MessageDigest,Je.asn1.cms.Attribute),Je.asn1.cms.SigningTime=function(e){var t=Je.asn1;t.cms.SigningTime.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.5",this.getValueArray=function(){return[new t.x509.Time(this.params)]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningTime,Je.asn1.cms.Attribute),Je.asn1.cms.SigningCertificate=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence,s=n.cms,a=s.ESSCertID;i.crypto,s.SigningCertificate.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.12",this.getValueArray=function(){if(null==this.params||null==this.params||null==this.params.array)throw new t("parameter 'array' not specified");for(var i=this.params.array,n=[],s=0;s<i.length;s++){var o=i[s];0!=e.hasis||"string"!=typeof o||-1==o.indexOf("-----BEGIN")&&!Qe.isASN1HEX(o)||(o={cert:o}),0!=o.hasis&&0==e.hasis&&(o.hasis=!1),n.push(new a(o))}var c=new r({array:n});return[new r({array:[c]})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningCertificate,Je.asn1.cms.Attribute),Je.asn1.cms.ESSCertID=function(e){Je.asn1.cms.ESSCertID.superclass.constructor.call(this);var t=Error,i=Je,n=i.asn1,r=n.DEROctetString,s=n.DERSequence,a=n.cms.IssuerSerial;this.params=null,this.getCertHash=function(e,n){if(null!=e.hash)return e.hash;if("string"==typeof e&&-1==e.indexOf("-----BEGIN")&&!Qe.isASN1HEX(e))return e;var r,s,a;if("string"==typeof e)r=e;else{if(null==e.cert)throw new t("hash nor cert unspecified");r=e.cert}if(s=-1!=r.indexOf("-----BEGIN")?ut(r):r,"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?s=ut(e):Qe.isASN1HEX(e)&&(s=e)),null!=e.alg)a=e.alg;else{if(null==n)throw new t("hash alg unspecified");a=n}return i.crypto.Util.hashHex(s,a)},this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha1"),i=[];return i.push(new r({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&i.push(new a(e)),new s({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ESSCertID,Je.asn1.ASN1Object),Je.asn1.cms.SigningCertificateV2=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence;n.x509;var s=n.cms,a=s.ESSCertIDv2;i.crypto,s.SigningCertificateV2.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.47",this.getValueArray=function(){if(null==this.params||null==this.params||null==this.params.array)throw new t("parameter 'array' not specified");for(var i=this.params.array,n=[],s=0;s<i.length;s++){var o=i[s];null==e.alg&&0!=e.hasis||"string"!=typeof o||-1==o.indexOf("-----BEGIN")&&!Qe.isASN1HEX(o)||(o={cert:o}),null==o.alg&&null!=e.alg&&(o.alg=e.alg),0!=o.hasis&&0==e.hasis&&(o.hasis=!1),n.push(new a(o))}var c=new r({array:n});return[new r({array:[c]})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SigningCertificateV2,Je.asn1.cms.Attribute),Je.asn1.cms.ESSCertIDv2=function(e){Je.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);var t=Je.asn1,i=t.DEROctetString,n=t.DERSequence,r=t.cms.IssuerSerial,s=t.x509.AlgorithmIdentifier;this.params=null,this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha256"),a=[];return null!=e.alg&&"sha256"!=e.alg&&a.push(new s({name:e.alg})),a.push(new i({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&a.push(new r(e)),new n({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ESSCertIDv2,Je.asn1.cms.ESSCertID),Je.asn1.cms.IssuerSerial=function(e){var t=Error,i=Je.asn1,n=i.DERInteger,r=i.DERSequence,s=i.cms,a=i.x509.GeneralNames,o=Ht;s.IssuerSerial.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.tohex=function(){var e,i,s=this.params;if("string"==typeof s&&-1!=s.indexOf("-----BEGIN")||null!=s.cert){var c;c=null!=s.cert?s.cert:s;var d=new o;d.readCertPEM(c),e=d.getIssuer(),i={hex:d.getSerialNumberHex()}}else{if(null==s.issuer||!s.serial)throw new t("cert or issuer and serial parameter not specified");e=s.issuer,i=s.serial}var l=new a([{dn:e}]),h=new n(i);return new r({array:[l,h]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.IssuerSerial,Je.asn1.ASN1Object),Je.asn1.cms.SignerIdentifier=function(e){var t=Je.asn1;t.DERInteger,t.DERSequence;var i=t.cms,n=i.IssuerAndSerialNumber,r=i.SubjectKeyIdentifier;t.x509.X500Name,i.SignerIdentifier.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if("isssn"==e.type)return new n(e).tohex();if("skid"==e.type)return new r(e).tohex();throw new Error("wrong property for isssn or skid")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignerIdentifier,Je.asn1.ASN1Object),Je.asn1.cms.IssuerAndSerialNumber=function(e){var t=Je.asn1,i=t.DERInteger,n=t.DERSequence,r=t.cms,s=t.x509.X500Name,a=Ht,o=Error;r.IssuerAndSerialNumber.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e,t,r=this.params;if("string"==typeof r&&-1!=r.indexOf("-----BEGIN")||null!=r.cert){var c;c=null!=r.cert?r.cert:r;var d=new a;d.readCertPEM(c),e=d.getIssuer(),t={hex:d.getSerialNumberHex()}}else{if(null==r.issuer||!r.serial)throw new o("cert or issuer and serial parameter not specified");e=r.issuer,t=r.serial}var l=new s(e),h=new i(t);return new n({array:[l,h]}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.IssuerAndSerialNumber,Je.asn1.ASN1Object),Je.asn1.cms.SubjectKeyIdentifier=function(e){var t=Je.asn1;t.DERInteger,t.DERSequence;var i=t.ASN1Util.newObject,n=t.cms;n.IssuerAndSerialName,n.SubjectKeyIdentifier,t.x509.X500Name;var r=Ht,s=Error;n.SubjectKeyIdentifier.superclass.constructor.call(this),this.tohex=function(){var e,t=this.params;if(null==t.cert&&null==t.skid)throw new s("property cert nor skid undefined");null!=t.cert?e=new r(t.cert).getExtSubjectKeyIdentifier().kid.hex:null!=t.skid&&(e=t.skid);return i({tag:{tage:"a0",obj:{octstr:{hex:e}}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SubjectKeyIdentifier,Je.asn1.ASN1Object),Je.asn1.cms.AttributeList=function(e){var t=Error,i=Je.asn1,n=i.DERSet,r=i.cms;r.AttributeList.superclass.constructor.call(this),this.params=null,this.hTLV=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if(null!=this.hTLV)return this.hTLV;var i=!0;null!=e.sortflag&&(i=e.sortflag);for(var s=e.array,a=[],o=0;o<s.length;o++){var c=s[o],d=c.attr;if("contentType"==d)a.push(new r.ContentType(c));else if("messageDigest"==d)a.push(new r.MessageDigest(c));else if("signingTime"==d)a.push(new r.SigningTime(c));else if("signingCertificate"==d)a.push(new r.SigningCertificate(c));else if("signingCertificateV2"==d)a.push(new r.SigningCertificateV2(c));else if("signaturePolicyIdentifier"==d)a.push(new Je.asn1.cades.SignaturePolicyIdentifier(c));else{if("signatureTimeStamp"!=d&&"timeStampToken"!=d)throw new t("unknown attr: "+d);a.push(new Je.asn1.cades.SignatureTimeStamp(c))}}var l=new n({array:a,sortflag:i});return this.hTLV=l.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.AttributeList,Je.asn1.ASN1Object),Je.asn1.cms.SignerInfo=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERInteger,s=n.DEROctetString,a=n.DERSequence,o=n.DERTaggedObject,c=n.cms,d=c.SignerIdentifier,l=c.AttributeList;c.ContentType,c.EncapsulatedContentInfo,c.MessageDigest,c.SignedData;var h=n.x509.AlgorithmIdentifier,u=i.crypto,p=kt;c.SignerInfo.superclass.constructor.call(this),this.params=null,this.sign=function(){var e=this.params,t=e.sigalg,i=new l(e.sattrs).tohex(),n=p.getKey(e.signkey),r=new u.Signature({alg:t});r.init(n),r.updateHex(i);var s=r.sign();e.sighex=s},this.tohex=function(){var e=this.params,i=[];if(i.push(new r({int:e.version})),i.push(new d(e.id)),i.push(new h({name:e.hashalg})),null!=e.sattrs){var n=new l(e.sattrs);try{i.push(new o({tag:"a0",explicit:!1,obj:n}))}catch(e){throw new t("si sattr error: "+e)}}if(null!=e.sigalgfield?i.push(new h({name:e.sigalgfield})):i.push(new h({name:e.sigalg})),null==e.sighex&&null!=e.signkey&&this.sign(),i.push(new s({hex:e.sighex})),null!=e.uattrs){n=new l(e.uattrs);try{i.push(new o({tag:"a1",explicit:!1,obj:n}))}catch(e){throw new t("si uattr error: "+e)}}return new a({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignerInfo,Je.asn1.ASN1Object),Je.asn1.cms.EncapsulatedContentInfo=function(e){var t=Je.asn1,i=t.DERTaggedObject,n=t.DERSequence,r=t.DERObjectIdentifier,s=t.DEROctetString;t.cms.EncapsulatedContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];if(t.push(new r(e.type)),null!=e.content&&(null!=e.content.hex||null!=e.content.str)&&1!=e.isDetached){var a=new s(e.content),o=new i({tag:"a0",explicit:!0,obj:a});t.push(o)}return new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.EncapsulatedContentInfo,Je.asn1.ASN1Object),Je.asn1.cms.ContentInfo=function(e){var t=Je.asn1,i=t.DERTaggedObject,n=t.DERSequence,r=t.DERObjectIdentifier;t.x509.OID.name2obj,Je.asn1.cms.ContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];t.push(new r(e.type));var s=new i({tag:"a0",explicit:!0,obj:e.obj});return t.push(s),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.ContentInfo,Je.asn1.ASN1Object),Je.asn1.cms.SignedData=function(e){var t=Je.asn1;t.ASN1Object;var i=t.DERInteger,n=t.DERSet,r=t.DERSequence;t.DERTaggedObject;var s=t.cms,a=s.EncapsulatedContentInfo,o=s.SignerInfo,c=s.ContentInfo,d=s.CertificateSet,l=s.RevocationInfoChoices,h=t.x509.AlgorithmIdentifier;Je.asn1.cms.SignedData.superclass.constructor.call(this),this.params=null,this.checkAndFixParam=function(){var e=this.params;this._setDigestAlgs(e),this._setContentTypeByEContent(e),this._setMessageDigestByEContent(e),this._setSignerInfoVersion(e),this._setSignedDataVersion(e)},this._setDigestAlgs=function(e){for(var t={},i=e.sinfos,n=0;n<i.length;n++){t[i[n].hashalg]=1}e.hashalgs=Object.keys(t).sort()},this._setContentTypeByEContent=function(e){for(var t=e.econtent.type,i=e.sinfos,n=0;n<i.length;n++){var r=i[n];this._getAttrParamByName(r,"contentType").type=t}},this._setMessageDigestByEContent=function(e){var t=e.econtent;e.econtent.type;var i=t.content.hex;null==i&&"data"==t.type&&null!=t.content.str&&(i=lt(t.content.str));for(var n=e.sinfos,r=0;r<n.length;r++){var s=n[r],a=s.hashalg,o=this._getAttrParamByName(s,"messageDigest"),c=Je.crypto.Util.hashHex(i,a);o.hex=c}},this._getAttrParamByName=function(e,t){for(var i=e.sattrs.array,n=0;n<i.length;n++)if(i[n].attr==t)return i[n]},this._setSignerInfoVersion=function(e){for(var t=e.sinfos,i=0;i<t.length;i++){var n=t[i],r=1;"skid"==n.id.type&&(r=3),n.version=r}},this._setSignedDataVersion=function(e){var t=this._getSignedDataVersion(e);e.version=t},this._getSignedDataVersion=function(e){if(null!=e.revinfos)for(var t=e.revinfos,i=0;i<t.length;i++){if(null!=t[i].ocsp)return 5}var n=e.sinfos;for(i=0;i<n.length;i++){if(3==e.sinfos[i].version)return 3}return"data"!=e.econtent.type?3:1},this.tohex=function(){var e=this.params;null!=this.getEncodedHexPrepare&&this.getEncodedHexPrepare(),1!=e.fixed&&this.checkAndFixParam();var t=[];t.push(new i({int:e.version}));for(var s=[],c=0;c<e.hashalgs.length;c++){var u=e.hashalgs[c];s.push(new h({name:u}))}t.push(new n({array:s})),t.push(new a(e.econtent)),null!=e.certs&&t.push(new d(e.certs)),null!=e.revinfos&&t.push(new l(e.revinfos));var p=[];for(c=0;c<e.sinfos.length;c++){var g=e.sinfos[c];p.push(new o(g))}return t.push(new n({array:p})),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.getContentInfo=function(){return new c({type:"signed-data",obj:this})},this.getContentInfoEncodedHex=function(){return this.getContentInfo().tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.SignedData,Je.asn1.ASN1Object),Je.asn1.cms.CertificateSet=function(e){Je.asn1.cms.CertificateSet.superclass.constructor.call(this);var t=Error,i=Je.asn1,n=i.DERTaggedObject,r=i.DERSet,s=i.ASN1Object;this.params=null,this.tohex=function(){var e,i=this.params,a=[];if(i instanceof Array)e=i;else{if(null==i.array)throw new t("cert array not specified");e=i.array}for(var o=0;o<e.length;o++){var c=ut(e[o]),d=new s;d.hTLV=c,a.push(d)}var l={array:a};0==i.sortflag&&(l.sortflag=!1);var h=new r(l);return new n({tag:"a0",explicit:!1,obj:h}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.CertificateSet,Je.asn1.ASN1Object),Je.asn1.cms.RevocationInfoChoices=function(e){Je.asn1.cms.RevocationInfoChoices.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(!e instanceof Array)throw new Error("params is not array");for(var t=[],i=0;i<e.length;i++)t.push(new Je.asn1.cms.RevocationInfoChoice(e[i]));return Je.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:{set:t}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.RevocationInfoChoices,Je.asn1.ASN1Object),Je.asn1.cms.RevocationInfoChoice=function(e){Je.asn1.cms.RevocationInfoChoice.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(null!=e.crl&&"string"==typeof e.crl){var t=e.crl;return-1!=e.crl.indexOf("-----BEGIN")&&(t=ut(e.crl)),t}if(null!=e.ocsp)return Je.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:new Je.asn1.cms.OtherRevocationFormat(e)}}).tohex();throw new Error("property crl or ocsp undefined")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.RevocationInfoChoice,Je.asn1.ASN1Object),Je.asn1.cms.OtherRevocationFormat=function(e){Je.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);var t=Error,i=Je,n=i.asn1.ASN1Util.newObject,r=i.lang.String.isHex;this.params=null,this.tohex=function(){var e=this.params;if(null==e.ocsp)throw new t("property ocsp not specified");if(!r(e.ocsp)||!Qe.isASN1HEX(e.ocsp))throw new t("ocsp value not ASN.1 hex string");return n({seq:[{oid:"1.3.6.1.5.5.7.16.2"},{asn1:{tlv:e.ocsp}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cms.OtherRevocationFormat,Je.asn1.ASN1Object),Je.asn1.cms.CMSUtil=new function(){},Je.asn1.cms.CMSUtil.newSignedData=function(e){return new Je.asn1.cms.SignedData(e)},Je.asn1.cms.CMSUtil.verifySignedData=function(e){var t=Je,i=t.asn1,n=i.cms;n.SignerInfo,n.SignedData,n.SigningTime,n.SigningCertificate,n.SigningCertificateV2,i.cades.SignaturePolicyIdentifier;var r=t.lang.String.isHex,s=Qe,a=s.getVbyList,o=s.getTLVbyList,c=s.getIdxbyList,d=s.getChildIdx,l=s.getTLV,h=s.oidname,u=t.crypto.Util.hashHex;void 0===e.cms&&r(e.cms);var p=e.cms,g=function(e,t){var i=t.idx;t.signerid_issuer1=o(e,i,[1,0],"30"),t.signerid_serial1=a(e,i,[1,1],"02"),t.hashalg=h(a(e,i,[2,0],"06"));var n=c(e,i,[3],"a0");t.idxSignedAttrs=n,f(e,t,n);var r=d(e,i).length;if(r<6)throw"malformed SignerInfo";t.sigalg=h(a(e,i,[r-2,0],"06")),t.sigval=a(e,i,[r-1],"04")},f=function(e,t,i){var n=d(e,i);t.signedAttrIdxList=n;for(var r=0;r<n.length;r++){var s,o=n[r],c=a(e,o,[0],"06");"2a864886f70d010905"===c?(s=ot(a(e,o,[1,0])),t.saSigningTime=s):"2a864886f70d010904"===c&&(s=a(e,o,[1,0],"04"),t.saMessageDigest=s)}},m=function(e,t,i,n){i.verifyDetail={};var r=i.verifyDetail,s=t.parse.econtent,a=i.hashalg,o=i.saMessageDigest;r.validMessageDigest=!1,u(s,a)===o&&(r.validMessageDigest=!0),function(e,t,i,n){var r,s=t.parse.certsIdx;if(void 0===t.certs){r=[],t.certkeys=[];for(var a=d(e,s),o=0;o<a.length;o++){var c=l(e,a[o]),h=new Ht;h.readCertHex(c),r[o]=h,t.certkeys[o]=h.getPublicKey()}t.certs=r}else r=t.certs;for(t.cccc=r.length,t.cccci=a.length,o=0;o<r.length;o++){var u=h.getIssuerHex(),p=h.getSerialNumberHex();i.signerid_issuer1===u&&i.signerid_serial1===p&&(i.certkey_idx=o)}}(e,t,i),r.validSignatureValue=!1;var c=i.sigalg,h="31"+l(e,i.idxSignedAttrs).substr(2);i.signedattrshex=h;var p=t.certs[i.certkey_idx].getPublicKey(),g=new Je.crypto.Signature({alg:c});g.init(p),g.updateHex(h);var f=g.verify(i.sigval);r.validSignatureValue_isValid=f,!0===f&&(r.validSignatureValue=!0),i.isValid=!1,r.validMessageDigest&&r.validSignatureValue&&(i.isValid=!0)},v={isValid:!1,parse:{}};return function(e,t){if("2a864886f70d010702"!==a(e,0,[0],"06"))return t;t.cmsType="signedData",t.econtent=a(e,0,[1,0,2,1,0]),function(e,t){for(var i,n=3;n<6;n++)if(void 0!==(i=c(e,0,[1,0,n]))){var r=e.substr(i,2);"a0"===r&&(t.certsIdx=i),"a1"===r&&(t.revinfosIdx=i),"31"===r&&(t.signerinfosIdx=i)}}(e,t),t.signerInfos=[],function(e,t){var i=t.signerinfosIdx;if(void 0!==i){var n=d(e,i);t.signerInfoIdxList=n;for(var r=0;r<n.length;r++){var s={idx:n[r]};g(e,s),t.signerInfos.push(s)}}}(e,t)}(p,v.parse),function(e,t){for(var i=t.parse.signerInfos,n=i.length,r=!0,s=0;s<n;s++){var a=i[s];m(e,t,a),a.isValid||(r=!1)}t.isValid=r}(p,v),v},Je.asn1.cms.CMSParser=function(){var e=Error,t=Ht,i=new t,n=Qe,r=n.getV,s=n.getTLV;n.getIdxbyList;var a=n.getTLVbyList,o=n.getTLVbyListEx,c=n.getVbyList,d=n.getVbyListEx,l=n.getChildIdx;this.getCMSSignedData=function(e){var t=a(e,0,[1,0]);return this.getSignedData(t)},this.getSignedData=function(e){var t=l(e,0),i={},n=r(e,t[0]),a=parseInt(n,16);i.version=a;var c=s(e,t[1]);i.hashalgs=this.getHashAlgArray(c);var d=s(e,t[2]);i.econtent=this.getEContent(d);var h=o(e,0,["[0]"]);null!=h&&(i.certs=this.getCertificateSet(h)),o(e,0,["[1]"]);var u=o(e,0,[3]);return i.sinfos=this.getSignerInfos(u),i},this.getHashAlgArray=function(e){for(var i=l(e,0),n=new t,r=[],a=0;a<i.length;a++){var o=s(e,i[a]),c=n.getAlgorithmIdentifierName(o);r.push(c)}return r},this.getEContent=function(e){var t={},i=c(e,0,[0]),n=c(e,0,[1,0]);return t.type=Je.asn1.x509.OID.oid2name(Qe.hextooidstr(i)),t.content={hex:n},t},this.getSignerInfos=function(e){for(var t=[],i=l(e,0),n=0;n<i.length;n++){var r=s(e,i[n]),a=this.getSignerInfo(r);t.push(a)}return t},this.getSignerInfo=function(e){var t={},r=l(e,0),a=n.getInt(e,r[0],-1);-1!=a&&(t.version=a);var c=s(e,r[1]),h=this.getIssuerAndSerialNumber(c);t.id=h;var u=s(e,r[2]),p=i.getAlgorithmIdentifierName(u);t.hashalg=p;var g=o(e,0,["[0]"]);if(null!=g){var f=this.getAttributeList(g);t.sattrs=f}var m=o(e,0,[3]),v=i.getAlgorithmIdentifierName(m);t.sigalg=v;var y=d(e,0,[4]);t.sighex=y;var S=o(e,0,["[1]"]);if(null!=S){var b=this.getAttributeList(S);t.uattrs=b}return t},this.getSignerIdentifier=function(e){if("30"==e.substr(0,2))return this.getIssuerAndSerialNumber(e);throw new Error("SKID of signerIdentifier not supported")},this.getIssuerAndSerialNumber=function(e){var t={type:"isssn"},n=l(e,0),a=s(e,n[0]);t.issuer=i.getX500Name(a);var o=r(e,n[1]);return t.serial={hex:o},t},this.getAttributeList=function(e){for(var t=[],i=l(e,0),n=0;n<i.length;n++){var r=s(e,i[n]),a=this.getAttribute(r);t.push(a)}return{array:t}},this.getAttribute=function(e){var t={},i=l(e,0),r=n.getOID(e,i[0]),a=Je.asn1.x509.OID.oid2name(r);t.attr=a;var o=s(e,i[1]),c=l(o,0);if(1==c.length)t.valhex=s(o,c[0]);else{for(var d=[],h=0;h<c.length;h++)d.push(s(o,c[h]));t.valhex=d}return"contentType"==a?this.setContentType(t):"messageDigest"==a?this.setMessageDigest(t):"signingTime"==a?this.setSigningTime(t):"signingCertificate"==a?this.setSigningCertificate(t):"signingCertificateV2"==a?this.setSigningCertificateV2(t):"signaturePolicyIdentifier"==a&&this.setSignaturePolicyIdentifier(t),t},this.setContentType=function(e){var t=n.getOIDName(e.valhex,0,null);null!=t&&(e.type=t,delete e.valhex)},this.setSigningTime=function(e){var t=ot(r(e.valhex,0));e.str=t,delete e.valhex},this.setMessageDigest=function(e){var t=r(e.valhex,0);e.hex=t,delete e.valhex},this.setSigningCertificate=function(e){var t=l(e.valhex,0);if(t.length>0){for(var i=s(e.valhex,t[0]),n=l(i,0),r=[],a=0;a<n.length;a++){var o=s(i,n[a]),c=this.getESSCertID(o);r.push(c)}e.array=r}if(t.length>1){var d=s(e.valhex,t[1]);e.polhex=d}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var i=l(e.valhex,0);if(i.length>0){var a=n.getOID(e.valhex,i[0]);e.oid=a}if(i.length>1){var o=new t,c=l(e.valhex,i[1]),d=s(e.valhex,c[0]),h=o.getAlgorithmIdentifierName(d);e.alg=h;var u=r(e.valhex,c[1]);e.hash=u}delete e.valhex},this.setSigningCertificateV2=function(e){var t=l(e.valhex,0);if(t.length>0){for(var i=s(e.valhex,t[0]),n=l(i,0),r=[],a=0;a<n.length;a++){var o=s(i,n[a]),c=this.getESSCertIDv2(o);r.push(c)}e.array=r}if(t.length>1){var d=s(e.valhex,t[1]);e.polhex=d}delete e.valhex},this.getESSCertID=function(e){var t={},i=l(e,0);if(i.length>0){var n=r(e,i[0]);t.hash=n}if(i.length>1){var a=s(e,i[1]),o=this.getIssuerSerial(a);null!=o.serial&&(t.serial=o.serial),null!=o.issuer&&(t.issuer=o.issuer)}return t},this.getESSCertIDv2=function(t){var n={},a=l(t,0);if(a.length<1||3<a.length)throw new e("wrong number of elements");var o=0;if("30"==t.substr(a[0],2)){var c=s(t,a[0]);n.alg=i.getAlgorithmIdentifierName(c),o++}else n.alg="sha256";var d=r(t,a[o]);if(n.hash=d,a.length>o+1){var h=s(t,a[o+1]),u=this.getIssuerSerial(h);n.issuer=u.issuer,n.serial=u.serial}return n},this.getIssuerSerial=function(e){var t={},n=l(e,0),a=s(e,n[0]),o=i.getGeneralNames(a)[0].dn;t.issuer=o;var c=r(e,n[1]);return t.serial={hex:c},t},this.getCertificateSet=function(e){for(var t=l(e,0),i=[],n=0;n<t.length;n++){var r=s(e,t[n]);if("30"==r.substr(0,2)){var a=ht(r,"CERTIFICATE");i.push(a)}}return{array:i,sortflag:!1}}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.tsp&&Je.asn1.tsp||(Je.asn1.tsp={}),Je.asn1.tsp.TimeStampToken=function(e){var t=Je.asn1.tsp;t.TimeStampToken.superclass.constructor.call(this),this.params=null,this.getEncodedHexPrepare=function(){var e=new t.TSTInfo(this.params.econtent.content);this.params.econtent.content.hex=e.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampToken,Je.asn1.cms.SignedData),Je.asn1.tsp.TSTInfo=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERInteger,r=t.DERBoolean,s=t.DERGeneralizedTime,a=t.DERObjectIdentifier,o=t.DERTaggedObject,c=t.tsp,d=c.MessageImprint,l=c.Accuracy;t.x509.X500Name;var h=t.x509.GeneralName;if(c.TSTInfo.superclass.constructor.call(this),this.dVersion=new n({int:1}),this.dPolicy=null,this.dMessageImprint=null,this.dSerial=null,this.dGenTime=null,this.dAccuracy=null,this.dOrdering=null,this.dNonce=null,this.dTsa=null,this.tohex=function(){var e=[this.dVersion];if(null==this.dPolicy)throw new Error("policy shall be specified.");if(e.push(this.dPolicy),null==this.dMessageImprint)throw new Error("messageImprint shall be specified.");if(e.push(this.dMessageImprint),null==this.dSerial)throw new Error("serialNumber shall be specified.");if(e.push(this.dSerial),null==this.dGenTime)throw new Error("genTime shall be specified.");e.push(this.dGenTime),null!=this.dAccuracy&&e.push(this.dAccuracy),null!=this.dOrdering&&e.push(this.dOrdering),null!=this.dNonce&&e.push(this.dNonce),null!=this.dTsa&&e.push(this.dTsa);var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){if("string"==typeof e.policy){if(!e.policy.match(/^[0-9.]+$/))throw"policy shall be oid like 0.1.4.134";this.dPolicy=new a({oid:e.policy})}void 0!==e.messageImprint&&(this.dMessageImprint=new d(e.messageImprint)),void 0!==e.serial&&(this.dSerial=new n(e.serial)),void 0!==e.genTime&&(this.dGenTime=new s(e.genTime)),void 0!==e.accuracy&&(this.dAccuracy=new l(e.accuracy)),void 0!==e.ordering&&1==e.ordering&&(this.dOrdering=new r),void 0!==e.nonce&&(this.dNonce=new n(e.nonce)),void 0!==e.tsa&&(this.dTsa=new o({tag:"a0",explicit:!0,obj:new h({dn:e.tsa})}))}},Nt(Je.asn1.tsp.TSTInfo,Je.asn1.ASN1Object),Je.asn1.tsp.Accuracy=function(e){var t=Je.asn1,i=t.ASN1Util.newObject;t.tsp.Accuracy.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return null!=e.seconds&&"number"==typeof e.seconds&&t.push({int:e.seconds}),null!=e.millis&&"number"==typeof e.millis&&t.push({tag:{tagi:"80",obj:{int:e.millis}}}),null!=e.micros&&"number"==typeof e.micros&&t.push({tag:{tagi:"81",obj:{int:e.micros}}}),i({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.Accuracy,Je.asn1.ASN1Object),Je.asn1.tsp.MessageImprint=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DEROctetString,r=t.x509.AlgorithmIdentifier;t.tsp.MessageImprint.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=new r({name:e.alg}),s=new n({hex:e.hash});return new i({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.tsp.MessageImprint,Je.asn1.ASN1Object),Je.asn1.tsp.TimeStampReq=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERInteger,r=t.DERBoolean;t.ASN1Object;var s=t.DERObjectIdentifier,a=t.tsp,o=a.MessageImprint;a.TimeStampReq.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return t.push(new n({int:1})),e.messageImprint instanceof Je.asn1.ASN1Object?t.push(e.messageImprint):t.push(new o(e.messageImprint)),null!=e.policy&&t.push(new s(e.policy)),null!=e.nonce&&t.push(new n(e.nonce)),1==e.certreq&&t.push(new r),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampReq,Je.asn1.ASN1Object),Je.asn1.tsp.TimeStampResp=function(e){var t=Je.asn1,i=t.DERSequence;t.ASN1Object;var n=t.tsp,r=n.PKIStatusInfo;n.TimeStampResp.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,s=[];if(null!=e.econtent||null!=e.tst)if(null!=e.statusinfo?s.push(new r(e.statusinfo)):s.push(new r("granted")),null!=e.econtent)s.push(new n.TimeStampToken(e).getContentInfo());else{if(!(e.tst instanceof t.ASN1Object))throw new Error("improper member tst value");s.push(e.tst)}else{if(null==e.statusinfo)throw new Error("parameter for token nor statusinfo not specified");s.push(new r(e.statusinfo))}return new i({array:s}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.TimeStampResp,Je.asn1.ASN1Object),Je.asn1.tsp.PKIStatusInfo=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.tsp,s=r.PKIStatus,a=r.PKIFreeText,o=r.PKIFailureInfo;r.PKIStatusInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,i=[];if("string"==typeof e)i.push(new s(e));else{if(null==e.status)throw new t("property 'status' unspecified");i.push(new s(e.status)),null!=e.statusstr&&i.push(new a(e.statusstr)),null!=e.failinfo&&i.push(new o(e.failinfo))}return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIStatusInfo,Je.asn1.ASN1Object),Je.asn1.tsp.PKIStatus=function(e){var t=Error,i=Je.asn1,n=i.DERInteger;i.tsp.PKIStatus.superclass.constructor.call(this);var r={granted:0,grantedWithMods:1,rejection:2,waiting:3,revocationWarning:4,revocationNotification:5};this.params=null,this.tohex=function(){var e,i=this.params;if("string"==typeof i)try{e=r[i]}catch(e){throw new t("undefined name: "+i)}else{if("number"!=typeof i)throw new t("unsupported params");e=i}return new n({int:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIStatus,Je.asn1.ASN1Object),Je.asn1.tsp.PKIFreeText=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERUTF8String;i.tsp.PKIFreeText.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(!e instanceof Array)throw new t("wrong params: not array");for(var i=[],s=0;s<e.length;s++)i.push(new r({str:e[s]}));return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIFreeText,Je.asn1.ASN1Object),Je.asn1.tsp.PKIFailureInfo=function(e){var t=Error,i=Je.asn1,n=i.DERBitString,r=i.tsp.PKIFailureInfo,s={badAlg:0,badRequest:2,badDataFormat:5,timeNotAvailable:14,unacceptedPolicy:15,unacceptedExtension:16,addInfoNotAvailable:17,systemFailure:25};r.superclass.constructor.call(this),this.params=null,this.getBinValue=function(){var e=this.params,i=0;if("number"==typeof e&&0<=e&&e<=25){for(var n=(i|=1<<e).toString(2),r="",a=n.length-1;a>=0;a--)r+=n[a];return r}if("string"==typeof e&&null!=s[e])return Pt([e],s);if("object"==typeof e&&null!=e.length)return Pt(e,s);throw new t("wrong params")},this.tohex=function(){this.params;var e=this.getBinValue();return new n({bin:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.tsp.PKIFailureInfo,Je.asn1.ASN1Object),Je.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},Je.asn1.tsp.SimpleTSAAdapter=function(e){var t=Je,i=t.asn1.tsp,n=t.crypto.Util.hashHex;i.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var r=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:r},this.params.econtent.content.serial={int:this.serial++};var s=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:s},new i.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.tsp.SimpleTSAAdapter,Je.asn1.tsp.AbstractTSAAdapter),Je.asn1.tsp.FixedTSAAdapter=function(e){var t=Je,i=t.asn1.tsp,n=t.crypto.Util.hashHex;i.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var r=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:r},new i.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},Nt(Je.asn1.tsp.FixedTSAAdapter,Je.asn1.tsp.AbstractTSAAdapter),Je.asn1.tsp.TSPUtil=new function(){},Je.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new Je.asn1.tsp.TimeStampToken(e)},Je.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new Je.asn1.tsp.TSPParser).getTimeStampReq(e)},Je.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new Je.asn1.tsp.TSPParser).getMessageImprint(e)},Je.asn1.tsp.TSPParser=function(){var e=new Ht,t=Qe,i=t.getV,n=t.getTLV,r=t.getIdxbyList;t.getTLVbyListEx;var s=t.getChildIdx,a=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],o={0:"badAlg",2:"badRequest",5:"badDataFormat",14:"timeNotAvailable",15:"unacceptedPolicy",16:"unacceptedExtension",17:"addInfoNotAvailable",25:"systemFailure"};this.getResponse=function(e){var t=s(e,0);if(1==t.length)return this.getPKIStatusInfo(n(e,t[0]));if(t.length>1){var i=this.getPKIStatusInfo(n(e,t[0])),r=n(e,t[1]),a=this.getToken(r);return a.statusinfo=i,a}},this.getToken=function(e){var t=(new Je.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var i=t.content.hex,n=this.getTSTInfo(i);t.content=n}},this.getTSTInfo=function(t){var r={},a=s(t,0),o=i(t,a[1]);r.policy=xt(o);var c=n(t,a[2]);r.messageImprint=this.getMessageImprint(c);var d=i(t,a[3]);r.serial={hex:d};var l=i(t,a[4]);r.genTime={str:ot(l)};var h=0;if(a.length>5&&"30"==t.substr(a[5],2)){var u=n(t,a[5]);r.accuracy=this.getAccuracy(u),h++}a.length>5+h&&"01"==t.substr(a[5+h],2)&&("ff"==i(t,a[5+h])&&(r.ordering=!0),h++);if(a.length>5+h&&"02"==t.substr(a[5+h],2)){var p=i(t,a[5+h]);r.nonce={hex:p},h++}if(a.length>5+h&&"a0"==t.substr(a[5+h],2)){var g=n(t,a[5+h]);g="30"+g.substr(2),pGeneralNames=e.getGeneralNames(g);var f=pGeneralNames[0].dn;r.tsa=f,h++}if(a.length>5+h&&"a1"==t.substr(a[5+h],2)){var m=n(t,a[5+h]);m="30"+m.substr(2);var v=e.getExtParamArray(m);r.ext=v,h++}return r},this.getAccuracy=function(e){for(var t={},n=s(e,0),r=0;r<n.length;r++){var a=e.substr(n[r],2),o=i(e,n[r]),c=parseInt(o,16);"02"==a?t.seconds=c:"80"==a?t.millis=c:"81"==a&&(t.micros=c)}return t},this.getMessageImprint=function(e){if("30"!=e.substr(0,2))throw new Error("head of messageImprint hex shall be x30");var n={};s(e,0);var a=r(e,0,[0,0]),o=i(e,a),c=t.hextooidstr(o),d=Je.asn1.x509.OID.oid2name(c);if(""==d)throw new Error("hashAlg name undefined: "+c);var l=d,h=r(e,0,[1]);return n.alg=l,n.hash=i(e,h),n},this.getPKIStatusInfo=function(e){var t={},r=s(e,0),o=0;try{var c=i(e,r[0]),d=parseInt(c,16);t.status=a[d]}catch(e){}if(r.length>1&&"30"==e.substr(r[1],2)){var l=n(e,r[1]);t.statusstr=this.getPKIFreeText(l),o++}if(r.length>o&&"03"==e.substr(r[1+o],2)){var h=n(e,r[1+o]);t.failinfo=this.getPKIFailureInfo(h)}return t},this.getPKIFreeText=function(e){for(var i=[],n=s(e,0),r=0;r<n.length;r++)i.push(t.getString(e,n[r]));return i},this.getPKIFailureInfo=function(e){var i=t.getInt(e,0);return null!=o[i]?o[i]:i},this.getTimeStampReq=function(e){var r={certreq:!1},a=s(e,0);if(a.length<2)throw new Error("TimeStampReq must have at least 2 items");var o=n(e,a[1]);r.messageImprint=Je.asn1.tsp.TSPUtil.parseMessageImprint(o);for(var c=2;c<a.length;c++){var d=a[c],l=e.substr(d,2);if("06"==l){var h=i(e,d);r.policy=t.hextooidstr(h)}"02"==l&&(r.nonce=i(e,d)),"01"==l&&(r.certreq=!0)}return r}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.cades&&Je.asn1.cades||(Je.asn1.cades={}),Je.asn1.cades.SignaturePolicyIdentifier=function(e){var t=Je.asn1.cades,i=t.SignaturePolicyId;t.SignaturePolicyIdentifier.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.15",this.params=null,this.getValueArray=function(){return[new i(this.params)]},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignaturePolicyIdentifier,Je.asn1.cms.Attribute),Je.asn1.cades.SignaturePolicyId=function(e){var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier;t.x509.AlgorithmIdentifier;var r=t.cades,s=r.SignaturePolicyId,a=r.OtherHashAlgAndValue;s.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];return t.push(new n(e.oid)),t.push(new a(e)),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignaturePolicyId,Je.asn1.ASN1Object),Je.asn1.cades.OtherHashAlgAndValue=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DEROctetString,s=i.x509.AlgorithmIdentifier;i.cades.OtherHashAlgAndValue.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if(null==e.alg)throw new t("property 'alg' not specified");if(null==e.hash&&null==e.cert)throw new t("property 'hash' nor 'cert' not specified");var i=null;if(null!=e.hash)i=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var a=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(a=ut(e.cert)),i=Je.crypto.Util.hashHex(a,e.alg)}var o=[];return o.push(new s({name:e.alg})),o.push(new r({hex:i})),new n({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHashAlgAndValue,Je.asn1.ASN1Object),Je.asn1.cades.OtherHashValue=function(e){Je.asn1.cades.OtherHashValue.superclass.constructor.call(this);var t=Error,i=Je;i.lang.String.isHex;var n=i.asn1.DEROctetString;i.crypto.Util.hashHex,this.params=null,this.tohex=function(){var e=this.params;if(null==e.hash&&null==e.cert)throw new t("hash or cert not specified");var i=null;if(null!=e.hash)i=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var r=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(r=ut(e.cert)),i=Je.crypto.Util.hashHex(r,"sha1")}return new n({hex:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHashValue,Je.asn1.ASN1Object),Je.asn1.cades.SignatureTimeStamp=function(e){var t=Error,i=Je,n=i.lang.String.isHex,r=i.asn1,s=r.ASN1Object;r.x509,r.cades.SignatureTimeStamp.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.14",this.params=null,this.getValueArray=function(){var e=this.params;if(null!=e.tst){if(n(e.tst))return(i=new s).hTLV=e.tst,[i];if(e.tst instanceof s)return[e.tst];throw new t("params.tst has wrong value")}if(null!=e.res){var i,r=e.res;if(r instanceof s&&(r=r.tohex()),"string"!=typeof r||!n(r))throw new t("params.res has wrong value");return Qe.getTLVbyList(r,0,[1]),(i=new s).hTLV=e.tst,[i]}},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.SignatureTimeStamp,Je.asn1.cms.Attribute),Je.asn1.cades.CompleteCertificateRefs=function(e){var t=Error,i=Je,n=i.asn1,r=n.DERSequence,s=n.cades,a=s.OtherCertID,o=i.lang.String.isHex;s.CompleteCertificateRefs.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.16.2.21",this.params=null,this.getValueArray=function(){for(var e=this.params,i=[],n=0;n<e.array.length;n++){var s=e.array[n];if("string"==typeof s)if(-1!=s.indexOf("-----BEGIN"))s={cert:s};else{if(!o(s))throw new t("unsupported value: "+s);s={hash:s}}null!=e.alg&&null==s.alg&&(s.alg=e.alg),null!=e.hasis&&null==s.hasis&&(s.hasis=e.hasis);var c=new a(s);i.push(c)}return[new r({array:i})]},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.CompleteCertificateRefs,Je.asn1.cms.Attribute),Je.asn1.cades.OtherCertID=function(e){var t=Je.asn1,i=t.DERSequence,n=t.cms.IssuerSerial,r=t.cades,s=r.OtherHashValue,a=r.OtherHashAlgAndValue;r.OtherCertID.superclass.constructor.call(this),this.params=e,this.tohex=function(){var e=this.params;"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?e={cert:e}:_isHex(e)&&(e={hash:e}));var t=[],r=null;if(r=null!=e.alg?new a(e):new s(e),t.push(r),null!=e.cert&&1==e.hasis||null!=e.issuer&&null!=e.serial){var o=new n(e);t.push(o)}return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherCertID,Je.asn1.ASN1Object),Je.asn1.cades.OtherHash=function(e){var t=Je,i=t.asn1;i.cms;var n=i.cades,r=n.OtherHashAlgAndValue,s=n.OtherHashValue;t.crypto.Util.hashHex;var a=t.lang.String.isHex;n.OtherHash.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?e={cert:e}:a(e)&&(e={hash:e}));return(null!=e.alg?new r(e):new s(e)).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.cades.OtherHash,Je.asn1.ASN1Object),Je.asn1.cades.CAdESUtil=new function(){},Je.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned=function(e){return(new Je.asn1.cms.CMSParser).getCMSSignedData(e)},Je.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned=function(e,t,i){var n=Qe,r=n.getChildIdx,s=n.getTLV,a=n.getV,o=Je.asn1,c=o.ASN1Object,d=o.cms,l=d.AttributeList,h=d.SignerInfo,u={},p=r(e,t);if(6!=p.length)throw"not supported items for SignerInfo (!=6)";var g=p.shift();u.version=s(e,g);var f=p.shift();u.si=s(e,f);var m=p.shift();u.digalg=s(e,m);var v=p.shift();u.sattrs=s(e,v);var y=p.shift();u.sigalg=s(e,y);var S=p.shift();u.sig=s(e,S),u.sigval=a(e,S);var b=null;return u.obj=new h,(b=new c).hTLV=u.version,u.obj.dCMSVersion=b,(b=new c).hTLV=u.si,u.obj.dSignerIdentifier=b,(b=new c).hTLV=u.digalg,u.obj.dDigestAlgorithm=b,(b=new c).hTLV=u.sattrs,u.obj.dSignedAttrs=b,(b=new c).hTLV=u.sigalg,u.obj.dSigAlg=b,(b=new c).hTLV=u.sig,u.obj.dSig=b,u.obj.dUnsignedAttrs=new l,u},void 0!==Je.asn1.csr&&Je.asn1.csr||(Je.asn1.csr={}),Je.asn1.csr.CertificationRequest=function(e){var t=Je.asn1,i=t.DERBitString,n=t.DERSequence,r=t.csr;t.x509;var s=r.CertificationRequestInfo;r.CertificationRequest.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.sign=function(){var e=new s(this.params).tohex(),t=new Je.crypto.Signature({alg:this.params.sigalg});t.init(this.params.sbjprvkey),t.updateHex(e);var i=t.sign();this.params.sighex=i},this.getPEM=function(){return ht(this.tohex(),"CERTIFICATE REQUEST")},this.tohex=function(){var e=this.params,t=new Je.asn1.csr.CertificationRequestInfo(this.params),r=new Je.asn1.x509.AlgorithmIdentifier({name:e.sigalg});if(null==e.sighex&&null!=e.sbjprvkey&&this.sign(),null==e.sighex)throw new Error("sighex or sbjprvkey parameter not defined");var s=new i({hex:"00"+e.sighex});return new n({array:[t,r,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.csr.CertificationRequest,Je.asn1.ASN1Object),Je.asn1.csr.CertificationRequestInfo=function(e){var t=Je.asn1;t.DERBitString;var i=t.DERSequence,n=t.DERInteger,r=t.DERUTF8String,s=t.DERTaggedObject,a=t.ASN1Util.newObject,o=t.csr,c=t.x509,d=c.X500Name,l=c.Extensions,h=c.SubjectPublicKeyInfo;o.AttributeList,o.CertificationRequestInfo.superclass.constructor.call(this),this.params=null,this.setByParam=function(e){null!=e&&(this.params=e)},this.tohex=function(){var e=this.params,t=[];if(t.push(new n({int:0})),t.push(new d(e.subject)),t.push(new h(kt.getKey(e.sbjpubkey))),null!=e.attrs){var o=function(e){for(var t=Error,i=Je.asn1.x509.Extensions,n=[],r=0;r<e.length;r++){var s=e[r],a=s.attr;if("extensionRequest"==a){var o={seq:[{oid:"1.2.840.113549.1.9.14"},{set:[new i(s.ext)]}]};n.push(o)}else if("unstructuredName"==a){o={seq:[{oid:"1.2.840.113549.1.9.2"},{set:s.names}]};n.push(o)}else{if("challengePassword"!=a)throw new t("unknown CSR attribute");o={seq:[{oid:"1.2.840.113549.1.9.7"},{set:[{utf8str:s.password}]}]};n.push(o)}}return{set:n}}(e.attrs),c=a({tag:{tage:"a0",obj:o}});t.push(c)}else if(null!=e.extreq){var u=new l(e.extreq);c=a({tag:{tage:"a0",obj:{seq:[{oid:"1.2.840.113549.1.9.14"},{set:[u]}]}}});t.push(c)}else t.push(new s({tag:"a0",explicit:!1,obj:new r({str:""})}));return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},Nt(Je.asn1.csr.CertificationRequestInfo,Je.asn1.ASN1Object),Je.asn1.csr.AttributeList=function(e){},Nt(Je.asn1.csr.AttributeList,Je.asn1.ASN1Object),Je.asn1.csr.CSRUtil=new function(){},Je.asn1.csr.CSRUtil.newCSRPEM=function(e){return new Je.asn1.csr.CertificationRequest(e).getPEM()},Je.asn1.csr.CSRUtil.getParam=function(e,t){var i=Qe,n=i.getV,r=i.getIdxbyList,s=i.getTLVbyList,a=i.getTLVbyListEx,o=i.getVbyListEx,c={};if(-1==e.indexOf("-----BEGIN CERTIFICATE REQUEST"))throw new Error("argument is not PEM file");var d=ut(e,"CERTIFICATE REQUEST");t&&(c.tbs=s(d,0,[0]));try{var l=a(d,0,[0,1]);if("3000"==l)c.subject={};else{var h=new Ht;c.subject=h.getX500Name(l)}}catch(e){}var u=a(d,0,[0,2]),p=kt.getKey(u,null,"pkcs8pub");c.sbjpubkey=kt.getPEM(p,"PKCS8PUB");var g=function(e){var t=r(e,0,[0,3,0,0],"06");return"2a864886f70d01090e"!=n(e,t)?null:s(e,0,[0,3,0,1,0],"30")}(d);h=new Ht;null!=g&&(c.extreq=h.getExtParamArray(g));try{var f=a(d,0,[1],"30");h=new Ht;c.sigalg=h.getAlgorithmIdentifierName(f)}catch(e){}try{var m=o(d,0,[2]);c.sighex=m}catch(e){}return c},Je.asn1.csr.CSRUtil.verifySignature=function(e){try{var t=null;if("string"==typeof e&&-1!=e.indexOf("-----BEGIN CERTIFICATE REQUEST")?t=Je.asn1.csr.CSRUtil.getParam(e,!0):"object"==typeof e&&null!=e.sbjpubkey&&null!=e.sigalg&&null!=e.sighex&&null!=e.tbs&&(t=e),null==t)return!1;var i=new Je.crypto.Signature({alg:t.sigalg});return i.init(t.sbjpubkey),i.updateHex(t.tbs),i.verify(t.sighex)}catch(e){return alert(e),!1}},void 0!==Je&&Je||(Je={}),void 0!==Je.asn1&&Je.asn1||(Je.asn1={}),void 0!==Je.asn1.ocsp&&Je.asn1.ocsp||(Je.asn1.ocsp={}),Je.asn1.ocsp.DEFAULT_HASH="sha1",Je.asn1.ocsp.OCSPResponse=function(e){Je.asn1.ocsp.OCSPResponse.superclass.constructor.call(this),Je.asn1.DEREnumerated;var t=Je.asn1.ASN1Util.newObject,i=Je.asn1.ocsp.ResponseBytes,n=["successful","malformedRequest","internalError","tryLater","_not_used_","sigRequired","unauthorized"];this.params=null,this._getStatusCode=function(){var e=this.params.resstatus;return"number"==typeof e?e:"string"!=typeof e?-1:n.indexOf(e)},this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params,n=this._getStatusCode();if(-1==n)throw new Error("responseStatus not supported: "+e.resstatus);if(0!=n)return t({seq:[{enum:{int:n}}]}).tohex();var r=new i(e);return t({seq:[{enum:{int:0}},{tag:{tag:"a0",explicit:!0,obj:r}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.OCSPResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponseBytes=function(e){Je.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERObjectIdentifier,r=t.DEROctetString,s=t.ocsp.BasicOCSPResponse;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e=this.params;if("ocspBasic"!=e.restype)throw new Error("not supported responseType: "+e.restype);var t=new s(e),a=[];return a.push(new n({name:"ocspBasic"})),a.push(new r({hex:t.tohex()})),new i({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponseBytes,Je.asn1.ASN1Object),Je.asn1.ocsp.BasicOCSPResponse=function(e){Je.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);var t=Error,i=Je.asn1,n=i.ASN1Object,r=i.DERSequence;i.DERGeneralizedTime;var s=i.DERTaggedObject,a=i.DERBitString;i.x509.Extensions;var o=i.x509.AlgorithmIdentifier,c=i.ocsp;c.ResponderID,_SingleResponseList=c.SingleResponseList,_ResponseData=c.ResponseData,this.params=null,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.tbsresp.tohex(),i=new Je.crypto.Signature({alg:e.sigalg});i.init(e.reskey),i.updateHex(t),e.sighex=i.sign()},this.tohex=function(){var e=this.params;null==e.tbsresp&&(e.tbsresp=new _ResponseData(e)),null==e.sighex&&null!=e.reskey&&this.sign();var i=[];if(i.push(e.tbsresp),i.push(new o({name:e.sigalg})),i.push(new a({hex:"00"+e.sighex})),null!=e.certs&&null!=e.certs.length){for(var c=[],d=0;d<e.certs.length;d++){var l=e.certs[d],h=null;if(Qe.isASN1HEX(l))h=l;else{if(!l.match(/-----BEGIN/))throw new t("certs["+d+"] not hex or PEM");h=ut(l)}c.push(new n({tlv:h}))}var u=new r({array:c});i.push(new s({tag:"a0",explicit:!0,obj:u}))}return new r({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.BasicOCSPResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponseData=function(e){Je.asn1.ocsp.ResponseData.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.DERGeneralizedTime,r=t.DERTaggedObject,s=t.x509.Extensions,a=t.ocsp,o=a.ResponderID;_SingleResponseList=a.SingleResponseList,this.params=null,this.tohex=function(){var e=this.params;e.respid,e.prodat,e.array;var t=[];if(t.push(new o(e.respid)),t.push(new n(e.prodat)),t.push(new _SingleResponseList(e.array)),null!=e.ext){var a=new s(e.ext);t.push(new r({tag:"a1",explicit:!0,obj:a}))}return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponseData,Je.asn1.ASN1Object),Je.asn1.ocsp.ResponderID=function(e){Je.asn1.ocsp.ResponderID.superclass.constructor.call(this);var t=Je,i=t.asn1,n=i.ASN1Util.newObject,r=i.x509.X500Name,s=t.lang.String.isHex,a=Error;this.params=null,this.tohex=function(){var e=this.params;if(null!=e.key){var t,i=null;if("string"==typeof e.key){if(s(e.key)&&(i=e.key),e.key.match(/-----BEGIN CERTIFICATE/))null!=(t=new Ht(e.key).getExtSubjectKeyIdentifier())&&(i=t.kid.hex)}else if(e.key instanceof Ht)null!=(t=e.key.getExtSubjectKeyIdentifier())&&(i=t.kid.hex);if(null==i)throw new a("wrong key member value");return n({tag:{tag:"a2",explicit:!0,obj:{octstr:{hex:i}}}}).tohex()}if(null!=e.name){var o=null;if("string"==typeof e.name&&e.name.match(/-----BEGIN CERTIFICATE/))o=new Ht(e.name).getSubject();else e.name instanceof Ht?o=e.name.getSubject():"object"!=typeof e.name||null==e.name.array&&null==e.name.str||(o=e.name);if(null==o)throw new a("wrong name member value");return n({tag:{tag:"a1",explicit:!0,obj:new r(o)}}).tohex()}throw new a("key or name not specified")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.ResponderID,Je.asn1.ASN1Object),Je.asn1.ocsp.SingleResponseList=function(e){Je.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);var t=Je.asn1,i=t.DERSequence,n=t.ocsp.SingleResponse;this.params=null,this.tohex=function(){var e=this.params;if("object"!=typeof e||null==e.length)throw new Error("params not specified properly");for(var t=[],r=0;r<e.length;r++)t.push(new n(e[r]));return new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.SingleResponseList,Je.asn1.ASN1Object),Je.asn1.ocsp.SingleResponse=function(e){var t=Error,i=Je.asn1,n=i.DERSequence,r=i.DERGeneralizedTime,s=i.DERTaggedObject,a=i.ocsp,o=a.CertID,c=a.CertStatus,d=i.x509.Extensions;a.SingleResponse.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,i=[];if(null==e.certid)throw new t("certid unspecified");if(null==e.status)throw new t("status unspecified");if(null==e.thisupdate)throw new t("thisupdate unspecified");if(i.push(new o(e.certid)),i.push(new c(e.status)),i.push(new r(e.thisupdate)),null!=e.nextupdate){var a=new r(e.nextupdate);i.push(new s({tag:"a0",explicit:!0,obj:a}))}if(null!=e.ext){var l=new d(e.ext);i.push(new s({tag:"a1",explicit:!0,obj:l}))}return new n({array:i}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.SingleResponse,Je.asn1.ASN1Object),Je.asn1.ocsp.CertID=function(e){var t=Je,i=t.asn1,n=i.DEROctetString,r=i.DERInteger,s=i.DERSequence,a=i.x509.AlgorithmIdentifier,o=i.ocsp;o.DEFAULT_HASH;var c=t.crypto.Util.hashHex,d=Ht,l=Qe.getVbyList;o.CertID.superclass.constructor.call(this),this.DEFAULT_HASH="sha1",this.params=null,this.setByValue=function(e,t,i,n){null==n&&(n=this.DEFAULT_HASH),this.params={alg:n,issname:e,isskey:t,sbjsn:i}},this.setByCert=function(e,t,i){null==i&&(i=this.DEFAULT_HASH),this.params={alg:i,issuerCert:e,subjectCert:t}},this.getParamByCerts=function(e,t,i){null==i&&(i=this.DEFAULT_HASH);var n=new d(e),r=new d(t),s=c(n.getSubjectHex(),i),a=n.getPublicKeyHex();return{alg:i,issname:s,isskey:c(l(a,0,[1],"03",!0),i),sbjsn:r.getSerialNumberHex()}},this.tohex=function(){if("object"!=typeof this.params)throw new Error("params not set");var e,t,i,o,c=this.params;if(o=null==c.alg?this.DEFAULT_HASH:c.alg,null!=c.issuerCert&&null!=c.subjectCert){var d=this.getParamByCerts(c.issuerCert,c.subjectCert,o);e=d.issname,t=d.isskey,i=d.sbjsn}else{if(null==c.issname||null==c.isskey||null==c.sbjsn)throw new Error("required param members not defined");e=c.issname,t=c.isskey,i=c.sbjsn}var l=new a({name:o}),h=new n({hex:e}),u=new n({hex:t}),p=new r({hex:i}),g=new s({array:[l,h,u,p]});return this.hTLV=g.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.CertID,Je.asn1.ASN1Object),Je.asn1.ocsp.CertStatus=function(e){Je.asn1.ocsp.CertStatus.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params;if("good"==e.status)return"8000";if("unknown"==e.status)return"8200";if("revoked"==e.status){var t=[{gentime:{str:e.time}}];null!=e.reason&&t.push({tag:{tag:"a0",explicit:!0,obj:{enum:{int:e.reason}}}});var i={tag:"a1",explicit:!1,obj:{seq:t}};return Je.asn1.ASN1Util.newObject({tag:i}).tohex()}throw new Error("bad status")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},Nt(Je.asn1.ocsp.CertStatus,Je.asn1.ASN1Object),Je.asn1.ocsp.Request=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;if(n.Request.superclass.constructor.call(this),this.dReqCert=null,this.dExt=null,this.tohex=function(){var e=[];if(null===this.dReqCert)throw"reqCert not set";e.push(this.dReqCert);var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){var r=new n.CertID(e);this.dReqCert=r}},Nt(Je.asn1.ocsp.Request,Je.asn1.ASN1Object),Je.asn1.ocsp.TBSRequest=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;n.TBSRequest.superclass.constructor.call(this),this.version=0,this.dRequestorName=null,this.dRequestList=[],this.dRequestExt=null,this.setRequestListByParam=function(e){for(var t=[],i=0;i<e.length;i++){var r=new n.Request(e[0]);t.push(r)}this.dRequestList=t},this.tohex=function(){var e=[];if(0!==this.version)throw"not supported version: "+this.version;if(null!==this.dRequestorName)throw"requestorName not supported";var t=new i({array:this.dRequestList});if(e.push(t),null!==this.dRequestExt)throw"requestExtensions not supported";var n=new i({array:e});return this.hTLV=n.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList&&this.setRequestListByParam(e.reqList)},Nt(Je.asn1.ocsp.TBSRequest,Je.asn1.ASN1Object),Je.asn1.ocsp.OCSPRequest=function(e){var t=Je.asn1,i=t.DERSequence,n=t.ocsp;if(n.OCSPRequest.superclass.constructor.call(this),this.dTbsRequest=null,this.dOptionalSignature=null,this.tohex=function(){var e=[];if(null===this.dTbsRequest)throw"tbsRequest not set";if(e.push(this.dTbsRequest),null!==this.dOptionalSignature)throw"optionalSignature not supported";var t=new i({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList){var r=new n.TBSRequest(e);this.dTbsRequest=r}},Nt(Je.asn1.ocsp.OCSPRequest,Je.asn1.ASN1Object),Je.asn1.ocsp.OCSPUtil={},Je.asn1.ocsp.OCSPUtil.getRequestHex=function(e,t,i){var n=Je.asn1.ocsp;void 0===i&&(i=n.DEFAULT_HASH);var r={alg:i,issuerCert:e,subjectCert:t};return new n.OCSPRequest({reqList:[r]}).tohex()},Je.asn1.ocsp.OCSPUtil.getOCSPResponseInfo=function(e){var t=Qe,i=t.getVbyList,n=t.getVbyListEx,r=t.getIdxbyList;t.getIdxbyListEx;var s=t.getV,a={};try{var o=n(e,0,[0],"0a");a.responseStatus=parseInt(o,16)}catch(e){}if(0!==a.responseStatus)return a;try{var c=r(e,0,[1,0,1,0,0,2,0,1]);"80"===e.substr(c,2)?a.certStatus="good":"a1"===e.substr(c,2)?(a.certStatus="revoked",a.revocationTime=ot(i(e,c,[0]))):"82"===e.substr(c,2)&&(a.certStatus="unknown")}catch(e){}try{var d=r(e,0,[1,0,1,0,0,2,0,2]);a.thisUpdate=ot(s(e,d))}catch(e){}try{var l=r(e,0,[1,0,1,0,0,2,0,3]);"a0"===e.substr(l,2)&&(a.nextUpdate=ot(i(e,l,[0])))}catch(e){}return a},Je.asn1.ocsp.OCSPParser=function(){var e=Error,t=Ht,i=new t,n=Qe,r=n.getV,s=n.getTLV,a=n.getIdxbyList,o=n.getVbyList,c=n.getTLVbyList,d=n.getVbyListEx,l=n.getTLVbyListEx,h=n.getChildIdx;this.getOCSPRequest=function(t){var i=h(t,0);if(1!=i.length&&2!=i.length)throw new e("wrong number elements: "+i.length);return this.getTBSRequest(s(t,i[0]))},this.getTBSRequest=function(e){var t={},n=l(e,0,[0],"30");t.array=this.getRequestList(n);var r=l(e,0,["[2]",0],"30");return null!=r&&(t.ext=i.getExtParamArray(r)),t},this.getRequestList=function(e){for(var t=[],i=h(e,0),n=0;n<i.length;n++){e=s(e,i[n]);t.push(this.getRequest(e))}return t},this.getRequest=function(t){var n=h(t,0);if(1!=n.length&&2!=n.length)throw new e("wrong number elements: "+n.length);var r=this.getCertID(s(t,n[0]));if(2==n.length){var o=a(t,0,[1,0]);r.ext=i.getExtParamArray(s(t,o))}return r},this.getCertID=function(i){var n=h(i,0);if(4!=n.length)throw new e("wrong number elements: "+n.length);var a=new t,o={};return o.alg=a.getAlgorithmIdentifierName(s(i,n[0])),o.issname=r(i,n[1]),o.isskey=r(i,n[2]),o.sbjsn=r(i,n[3]),o},this.getOCSPResponse=function(e){var t,i=h(e,0),n=r(e,i[0]),s=parseInt(n);if(1==i.length)return{resstatus:s};var a=c(e,0,[1,0]);return(t=this.getResponseBytes(a)).resstatus=s,t},this.getResponseBytes=function(e){var t,i=h(e,0),n=c(e,0,[1,0]);t=this.getBasicOCSPResponse(n);var s=r(e,i[0]);return t.restype=Je.asn1.x509.OID.oid2name(xt(s)),t},this.getBasicOCSPResponse=function(e){var t,i=h(e,0);t=this.getResponseData(s(e,i[0]));var n=new Ht;t.alg=n.getAlgorithmIdentifierName(s(e,i[1]));var a=r(e,i[2]);t.sighex=a.substr(2);var o=d(e,0,["[0]"]);if(null!=o){for(var c=h(o,0),l=[],u=0;u<c.length;u++){var p=s(o,c[u]);l.push(p)}t.certs=l}return t},this.getResponseData=function(e){var t=h(e,0),i=t.length,n={},a=0;"a0"==e.substr(t[0],2)&&a++,n.respid=this.getResponderID(s(e,t[a++]));var o=r(e,t[a++]);if(n.prodat=ot(o),n.array=this.getSingleResponseList(s(e,t[a++])),"a1"==e.substr(t[i-1],2)){var d=c(e,t[i-1],[0]),l=new Ht;n.ext=l.getExtParamArray(d)}return n},this.getResponderID=function(e){var t={};if("a2"==e.substr(0,2)){var i=o(e,0,[0]);t.key=i}if("a1"==e.substr(0,2)){var n=c(e,0,[0]),r=new Ht;t.name=r.getX500Name(n)}return t},this.getSingleResponseList=function(e){for(var t=h(e,0),i=[],n=0;n<t.length;n++){var r=this.getSingleResponse(s(e,t[n]));i.push(r)}return i},this.getSingleResponse=function(e){var t=h(e,0),i={},n=this.getCertID(s(e,t[0]));i.certid=n;var a=this.getCertStatus(s(e,t[1]));if(i.status=a,"18"==e.substr(t[2],2)){var d=r(e,t[2]);i.thisupdate=ot(d)}for(var l=3;l<t.length;l++){if("a0"==e.substr(t[l],2)){var u=o(e,t[l],[0],"18");i.nextupdate=ot(u)}if("a1"==e.substr(t[l],2)){var p=new Ht,g=c(e,0,[l,0]);i.ext=p.getExtParamArray(g)}}return i},this.getCertStatus=function(e){var t={};if("8000"==e)return{status:"good"};if("8200"==e)return{status:"unknown"};if("a1"==e.substr(0,2)){t.status="revoked";var i=ot(o(e,0,[0]));t.time=i}return t}},void 0!==Je&&Je||(Je={}),void 0!==Je.lang&&Je.lang||(Je.lang={}),Je.lang.String=function(){},"function"==typeof Buffer?(Ze=function(e){return it(Buffer.from(e,"utf8").toString("base64"))},Xe=function(e){return Buffer.from(nt(e),"base64").toString("utf8")}):(Ze=function(e){return rt(gt(Ct(e)))},Xe=function(e){return decodeURIComponent(ft(st(e)))}),Je.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},Je.lang.String.isHex=function(e){return $t(e)},Je.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},Je.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=nt(e),Je.lang.String.isBase64(e))},Je.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},Je.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},Je.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},Je.lang.String.isMail=function(e){return null!==e.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/)};var At=function(e,t,i){return null==i&&(i="0"),e.length>=t?e:new Array(t-e.length+1).join(i)+e};function Pt(e,t){for(var i=0,n=0;n<e.length;n++)i|=1<<t[e[n]];var r=i.toString(2),s="";for(n=r.length-1;n>=0;n--)s+=r[n];return s}function Dt(e,t,i){if("object"==typeof e){t=String(t).split(".");for(var n=0;n<t.length&&e;n++){var r=t[n];r.match(/^[0-9]+$/)&&(r=parseInt(r)),e=e[r]}return e||!1===e?e:i}}function Nt(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:ne.algo.MD5,sha1:ne.algo.SHA1,sha224:ne.algo.SHA224,sha256:ne.algo.SHA256,sha384:ne.algo.SHA384,sha512:ne.algo.SHA512,ripemd160:ne.algo.RIPEMD160},this.getDigestInfoHex=function(e,t){if(void 0===this.DIGESTINFOHEAD[t])throw"alg not supported in Util.DIGESTINFOHEAD: "+t;return this.DIGESTINFOHEAD[t]+e},this.getPaddedDigestInfoHex=function(e,t,i){var n=this.getDigestInfoHex(e,t),r=i/4;if(n.length+22>r)throw"key is too short for SigAlg: keylen="+i+","+t;for(var s="0001",a="00"+n,o="",c=r-4-a.length,d=0;d<c;d+=2)o+="ff";return s+o+a},this.hashString=function(e,t){return new Je.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new Je.crypto.MessageDigest({alg:t}).digestHex(e)},this.sha1=function(e){return this.hashString(e,"sha1")},this.sha256=function(e){return this.hashString(e,"sha256")},this.sha256Hex=function(e){return this.hashHex(e,"sha256")},this.sha512=function(e){return this.hashString(e,"sha512")},this.sha512Hex=function(e){return this.hashHex(e,"sha512")},this.isKey=function(e){return e instanceof Ge||e instanceof Je.crypto.DSA||e instanceof Je.crypto.ECDSA}},Je.crypto.Util.md5=function(e){return new Je.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},Je.crypto.Util.ripemd160=function(e){return new Je.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},Je.crypto.Util.SECURERANDOMGEN=new Ve,Je.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return Je.crypto.Util.SECURERANDOMGEN.nextBytes(t),et(t)},Je.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new de(Je.crypto.Util.getRandomHexOfNbytes(e),16)},Je.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,i=new Array((e-t)/8+1);return Je.crypto.Util.SECURERANDOMGEN.nextBytes(i),i[0]=(255<<t&255^255)&i[0],et(i)},Je.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new de(Je.crypto.Util.getRandomHexOfNbits(e),16)},Je.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var i=Je.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(i))return i}},Je.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var i=e.compareTo(t);if(1==i)throw"biMin is greater than biMax";if(0==i)return e;var n=t.subtract(e);return Je.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},Je.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=Je.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=Je.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=Je.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[e].create()}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=ne.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(ne.enc.Hex)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}if(-1!=":sha256:".indexOf(e)&&"sjcl"==t){try{this.md=new sjcl.hash.sha256}catch(t){throw"setAlgAndProvider hash alg set fail alg="+e+"/"+t}this.updateString=function(e){this.md.update(e)},this.updateHex=function(e){var t=sjcl.codec.hex.toBits(e);this.md.update(t)},this.digest=function(){var e=this.md.finalize();return sjcl.codec.hex.fromBits(e)},this.digestString=function(e){return this.updateString(e),this.digest()},this.digestHex=function(e){return this.updateHex(e),this.digest()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==e&&void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},Je.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},Je.crypto.MessageDigest.getHashLength=function(e){var t=Je.crypto.MessageDigest,i=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[i])throw"not supported algorithm: "+e;return t.HASHLENGTH[i]},Je.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},Je.crypto.Mac=function(e){this.setAlgAndProvider=function(e,t){if(null==(e=e.toLowerCase())&&(e="hmacsha1"),"hmac"!=(e=e.toLowerCase()).substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+e;void 0===t&&(t=Je.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var i=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(i)&&"cryptojs"==t){try{var n=Je.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[i];this.mac=ne.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+i+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=ne.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(ne.enc.Hex)},this.doFinalString=function(e){return this.updateString(e),this.doFinal()},this.doFinalHex=function(e){return this.updateHex(e),this.doFinal()}}},this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(e){if("string"==typeof e){var t=e;return e.length%2!=1&&e.match(/^[0-9A-Fa-f]+$/)||(t=lt(e)),void(this.pass=ne.enc.Hex.parse(t))}if("object"!=typeof e)throw"KJUR.crypto.Mac unsupported password type: "+e;t=null;if(void 0!==e.hex){if(e.hex.length%2!=0||!e.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+e.hex;t=e.hex}if(void 0!==e.utf8&&(t=at(e.utf8)),void 0!==e.rstr&&(t=lt(e.rstr)),void 0!==e.b64&&(t=ce(e.b64)),void 0!==e.b64u&&(t=st(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=ne.enc.Hex.parse(t)},void 0!==e&&(void 0!==e.pass&&this.setPassword(e.pass),void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov&&(this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},Je.crypto.Signature=function(e){var t=null;if(this._setAlgNames=function(){var e=this.algName.match(/^(.+)with(.+)$/);e&&(this.mdAlgName=e[1].toLowerCase(),this.pubkeyAlgName=e[2].toLowerCase(),"rsaandmgf1"==this.pubkeyAlgName&&"sha"==this.mdAlgName&&(this.mdAlgName="sha1"))},this._zeroPaddingOfSignature=function(e,t){for(var i="",n=t/4-e.length,r=0;r<n;r++)i+="0";return i+e},this.setAlgAndProvider=function(e,t){if(this._setAlgNames(),"cryptojs/jsrsa"!=t)throw new Error("provider not supported: "+t);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=new Je.crypto.MessageDigest({alg:this.mdAlgName})}catch(e){throw new Error("setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+e)}this.init=function(e,t){var i=null;try{i=void 0===t?kt.getKey(e):kt.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===i.isPrivate)this.prvKey=i,this.state="SIGN";else{if(!0!==i.isPublic)throw"init failed.:"+i;this.pubKey=i,this.state="VERIFY"}},this.updateString=function(e){this.md.updateString(e)},this.updateHex=function(e){this.md.updateHex(e)},this.sign=function(){if(this.sHashHex=this.md.digest(),void 0===this.prvKey&&void 0!==this.ecprvhex&&void 0!==this.eccurvename&&void 0!==Je.crypto.ECDSA&&(this.prvKey=new Je.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof Ge&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof Ge&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof Je.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof Je.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(e){return this.updateString(e),this.sign()},this.signHex=function(e){return this.updateHex(e),this.sign()},this.verify=function(e){if(this.sHashHex=this.md.digest(),void 0===this.pubKey&&void 0!==this.ecpubhex&&void 0!==this.eccurvename&&void 0!==Je.crypto.ECDSA&&(this.pubKey=new Je.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof Ge&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof Ge&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==Je.crypto.ECDSA&&this.pubKey instanceof Je.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==Je.crypto.DSA&&this.pubKey instanceof Je.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(e,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(e){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(e){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(e){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(e){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(e){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=e,void 0!==e&&(void 0!==e.alg&&(this.algName=e.alg,void 0===e.prov?this.provName=Je.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=e.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==e.psssaltlen&&(this.pssSaltLen=e.psssaltlen),void 0!==e.prvkeypem)){if(void 0!==e.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{t=kt.getKey(e.prvkeypem);this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},Je.crypto.Cipher=function(e){},Je.crypto.Cipher.encrypt=function(e,t,i,n){if(null!=Dt(n,"enclag")&&(i=n.encalg),"string"==typeof i&&"-CBC"==i.substr(-4)){var r=t,s=e;null!=Dt(n,"key")&&(r=n.key),null!=Dt(n,"enc")&&(hEnc=n.enc);var a,o=ne.enc.Hex.parse(r),c=ne.enc.Hex.parse(s),d=ne.enc.Hex.parse(n.iv);if("des-EDE3-CBC"==i)a=ne.TripleDES.encrypt(c,o,{iv:d});else{if("aes128-CBC"!=i&&"aes256-CBC"!=i)throw new Error("unsupported algorithm: "+i);a=ne.AES.encrypt(c,o,{iv:d})}return a+""}throw new Error("Cipher.encrypt: unsupported key or algorithm")},Je.crypto.Cipher.decrypt=function(e,t,i,n){if(null!=Dt(n,"enclag")&&(i=n.encalg),"string"==typeof i&&"-CBC"==i.substr(-4)){var r=t,s=e;null!=Dt(n,"key")&&(r=n.key),null!=Dt(n,"enc")&&(s=n.enc);var a,o=ne.enc.Hex.parse(r),c=ne.enc.Hex.parse(s),d=ne.enc.Hex.parse(n.iv);if("des-EDE3-CBC"==i)a=ne.TripleDES.decrypt({ciphertext:c},o,{iv:d});else{if("aes128-CBC"!=i&&"aes256-CBC"!=i)throw new Error("unsupported algorithm: "+i);a=ne.AES.decrypt({ciphertext:c},o,{iv:d})}return ne.enc.Hex.stringify(a)}throw new Error("Cipher.decrypt: unsupported key or algorithm")},Je.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040022":"secp384r1","2b81040023":"secp521r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.ECDSA=function(e){var t=Error,i=de,n=We,r=Je.crypto.ECDSA,s=Je.crypto.ECParameterDB,a=r.getName,o=Qe,c=o.getVbyListEx,d=o.isASN1HEX,l=new Ve;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new i(e.bitLength(),l).mod(e.subtract(i.ONE)).add(i.ONE)},this.setNamedCurve=function(e){this.ecparams=s.getByName(e),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=e},this.setPrivateKeyHex=function(e){this.isPrivate=!0,this.prvKeyHex=e},this.setPublicKeyHex=function(e){this.isPublic=!0,this.pubKeyHex=e},this.getPublicKeyXYHex=function(){var e=this.pubKeyHex;if("04"!==e.substr(0,2))throw"this method supports uncompressed format(04) only";var t=this.ecparams.keycharlen;if(e.length!==2+2*t)throw"malformed public key hex length";var i={};return i.x=e.substr(2,t),i.y=e.substr(2+t),i},this.getShortNISTPCurveName=function(){var e=this.curveName;return"secp256r1"===e||"NIST P-256"===e||"P-256"===e||"prime256v1"===e?"P-256":"secp384r1"===e||"NIST P-384"===e||"P-384"===e?"P-384":"secp521r1"===e||"NIST P-521"===e||"P-521"===e?"P-521":null},this.generateKeyPairHex=function(){var e=this.ecparams.n,t=this.getBigRandom(e),i=this.ecparams.keycharlen,n=("0000000000"+t.toString(16)).slice(-i);return this.setPrivateKeyHex(n),{ecprvhex:n,ecpubhex:this.generatePublicKeyHex()}},this.generatePublicKeyHex=function(){var e=new i(this.prvKeyHex,16),t=this.ecparams.G.multiply(e),n=t.getX().toBigInteger(),r=t.getY().toBigInteger(),s=this.ecparams.keycharlen,a="04"+("0000000000"+n.toString(16)).slice(-s)+("0000000000"+r.toString(16)).slice(-s);return this.setPublicKeyHex(a),a},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new i(t,16),s=this.ecparams.n,a=new i(e.substring(0,this.ecparams.keycharlen),16);do{var o=this.getBigRandom(s),c=this.ecparams.G.multiply(o).getX().toBigInteger().mod(s)}while(c.compareTo(i.ZERO)<=0);var d=o.modInverse(s).multiply(a.add(n.multiply(c))).mod(s);return r.biRSSigToASN1Sig(c,d)},this.sign=function(e,t){var n=t,r=this.ecparams.n,s=i.fromByteArrayUnsigned(e);do{var a=this.getBigRandom(r),o=this.ecparams.G.multiply(a).getX().toBigInteger().mod(r)}while(o.compareTo(de.ZERO)<=0);var c=a.modInverse(r).multiply(s.add(n.multiply(o))).mod(r);return this.serializeSig(o,c)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,s){try{var a,o,c=r.parseSigHex(t);a=c.r,o=c.s;var d=n.decodeFromHex(this.ecparams.curve,s),l=new i(e.substring(0,this.ecparams.keycharlen),16);return this.verifyRaw(l,a,o,d)}catch(e){return!1}},this.verify=function(e,t,r){var s,a,o;if(Bitcoin.Util.isArray(t)){var c=this.parseSig(t);s=c.r,a=c.s}else{if("object"!=typeof t||!t.r||!t.s)throw"Invalid value for signature";s=t.r,a=t.s}if(r instanceof We)o=r;else{if(!Bitcoin.Util.isArray(r))throw"Invalid format for pubkey value, must be byte array or ECPointFp";o=n.decodeFrom(this.ecparams.curve,r)}var d=i.fromByteArrayUnsigned(e);return this.verifyRaw(d,s,a,o)},this.verifyRaw=function(e,t,n,r){var s=this.ecparams.n,a=this.ecparams.G;if(t.compareTo(i.ONE)<0||t.compareTo(s)>=0)return!1;if(n.compareTo(i.ONE)<0||n.compareTo(s)>=0)return!1;var o=n.modInverse(s),c=e.multiply(o).mod(s),d=t.multiply(o).mod(s);return a.multiply(c).add(r.multiply(d)).getX().toBigInteger().mod(s).equals(t)},this.serializeSig=function(e,t){var i=e.toByteArraySigned(),n=t.toByteArraySigned(),r=[];return r.push(2),r.push(i.length),(r=r.concat(i)).push(2),r.push(n.length),(r=r.concat(n)).unshift(r.length),r.unshift(48),r},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var r=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:i.fromByteArrayUnsigned(n),s:i.fromByteArrayUnsigned(r)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:i.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:i.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===d(e))throw new Error("not ASN.1 hex string");var t,i,n;try{t=c(e,0,["[0]",0],"06"),i=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=a(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(i),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===d(e))throw new t("not ASN.1 hex string");var i,n,r;try{c(e,0,[1,0],"06"),i=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{r=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=a(i),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(r),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===d(e))throw new t("not ASN.1 hex string");var i,n;try{c(e,0,[0,0],"06"),i=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=a(i),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,i){if(!1===d(e))throw new t("not ASN.1 hex string");var n,r;try{n=c(e,0,[0,5,0,1],"06"),r=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=a(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(r)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},Je.crypto.ECDSA.parseSigHex=function(e){var t=Je.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new de(t.r,16),s:new de(t.s,16)}},Je.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=Qe,i=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var r=i(e,0);if(2!=r.length)throw new Error("signature shall have two elements");var s=r[0],a=r[1];if("02"!=e.substr(s,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(a,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,s),s:n(e,a)}},Je.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=Je.crypto.ECDSA.parseSigHexInHexRS(e),i=t.r,n=t.s;if(i.length>=130&&i.length<=134){if(i.length%2!=0)throw Error("unknown ECDSA sig r length error");if(n.length%2!=0)throw Error("unknown ECDSA sig s length error");"00"==i.substr(0,2)&&(i=i.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var r=Math.max(i.length,n.length);return(i=("000000"+i).slice(-r))+(n=("000000"+n).slice(-r))}if("00"==i.substr(0,2)&&i.length%32==2&&(i=i.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),i.length%32==30&&(i="00"+i),n.length%32==30&&(n="00"+n),i.length%32!=0)throw Error("unknown ECDSA sig r length error");if(n.length%32!=0)throw Error("unknown ECDSA sig s length error");return i+n},Je.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length%4!=0)throw Error("unknown ECDSA concatinated r-s sig length error");var t=e.substr(0,e.length/2),i=e.substr(e.length/2);return Je.crypto.ECDSA.hexRSSigToASN1Sig(t,i)},Je.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var i=new de(e,16),n=new de(t,16);return Je.crypto.ECDSA.biRSSigToASN1Sig(i,n)},Je.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var i=Je.asn1,n=new i.DERInteger({bigint:e}),r=new i.DERInteger({bigint:t});return new i.DERSequence({array:[n,r]}).tohex()},Je.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":"2b81040023"===e?"secp521r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":-1!=="|secp521r1|NIST P-521|P-521|".indexOf(e)?"secp521r1":null},void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.ECParameterDB=new function(){var e={},t={};function i(e){return new de(e,16)}this.getByName=function(i){var n=i;if(void 0!==t[n]&&(n=t[i]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,r,s,a,o,c,d,l,h,u,p,g){e[n]={};var f=i(s),m=i(a),v=i(o),y=i(c),S=i(d),b=new ze(f,m,v),w=b.decodePointHex("04"+l+h);e[n].name=n,e[n].keylen=r,e[n].keycharlen=2*Math.ceil(r/8),e[n].curve=b,e[n].G=w,e[n].n=y,e[n].h=S,e[n].oid=p,e[n].info=g;for(var E=0;E<u.length;E++)t[u[E]]=n}},Je.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),Je.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),Je.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),Je.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),Je.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),Je.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),Je.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),Je.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),Je.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),Je.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]),void 0!==Je&&Je||(Je={}),void 0!==Je.crypto&&Je.crypto||(Je.crypto={}),Je.crypto.DSA=function(){var e=Qe;e.getVbyList;var t=e.getVbyListEx,i=e.isASN1HEX,n=de;this.p=null,this.q=null,this.g=null,this.y=null,this.x=null,this.type="DSA",this.isPrivate=!1,this.isPublic=!1,this.setPrivate=function(e,t,i,n,r){this.isPrivate=!0,this.p=e,this.q=t,this.g=i,this.y=n,this.x=r},this.setPrivateHex=function(e,t,i,n,r){var s,a,o,c,d;s=new de(e,16),a=new de(t,16),o=new de(i,16),c="string"==typeof n&&n.length>1?new de(n,16):null,d=new de(r,16),this.setPrivate(s,a,o,c,d)},this.setPublic=function(e,t,i,n){this.isPublic=!0,this.p=e,this.q=t,this.g=i,this.y=n,this.x=null},this.setPublicHex=function(e,t,i,n){var r,s,a,o;r=new de(e,16),s=new de(t,16),a=new de(i,16),o=new de(n,16),this.setPublic(r,s,a,o)},this.signWithMessageHash=function(e){var t=this.p,i=this.q,n=this.g;this.y;var r=this.x,s=Je.crypto.Util.getRandomBigIntegerMinToMax(de.ONE.add(de.ONE),i.subtract(de.ONE)),a=new de(e.substr(0,i.bitLength()/4),16),o=n.modPow(s,t).mod(i),c=s.modInverse(i).multiply(a.add(r.multiply(o))).mod(i);return Je.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:o}},{int:{bigint:c}}]})},this.verifyWithMessageHash=function(e,t){var i=this.p,n=this.q,r=this.g,s=this.y,a=this.parseASN1Signature(t),o=a[0],c=a[1],d=new de(e.substr(0,n.bitLength()/4),16);if(de.ZERO.compareTo(o)>0||o.compareTo(n)>0)throw"invalid DSA signature";if(de.ZERO.compareTo(c)>=0||c.compareTo(n)>0)throw"invalid DSA signature";var l=c.modInverse(n),h=d.multiply(l).mod(n),u=o.multiply(l).mod(n);return 0==r.modPow(h,i).multiply(s.modPow(u,i)).mod(i).mod(n).compareTo(o)},this.parseASN1Signature=function(e){try{return[new n(t(e,0,[0],"02"),16),new n(t(e,0,[1],"02"),16)]}catch(e){throw new Error("malformed ASN.1 DSA signature")}},this.readPKCS5PrvKeyHex=function(e){var n,r,s,a,o;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),r=t(e,0,[2],"02"),s=t(e,0,[3],"02"),a=t(e,0,[4],"02"),o=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,r,s,a,o)},this.readPKCS8PrvKeyHex=function(e){var n,r,s,a;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),r=t(e,0,[1,1,1],"02"),s=t(e,0,[1,1,2],"02"),a=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,r,s,null,a)},this.readPKCS8PubKeyHex=function(e){var n,r,s,a;if(!1===i(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),r=t(e,0,[0,1,1],"02"),s=t(e,0,[0,1,2],"02"),a=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,r,s,a)},this.readCertPubKeyHex=function(e,n){var r,s,a,o;if(!1===i(e))throw new Error("not ASN.1 hex string");try{r=t(e,0,[0,5,0,1,0],"02"),s=t(e,0,[0,5,0,1,1],"02"),a=t(e,0,[0,5,0,1,2],"02"),o=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(r,s,a,o)}};var kt=function(){var e=function(e,i,n){return t(ne.AES,e,i,n)},t=function(e,t,i,n){var r=ne.enc.Hex.parse(t),s=ne.enc.Hex.parse(i),a=ne.enc.Hex.parse(n),o={};o.key=s,o.iv=a,o.ciphertext=r;var c=e.decrypt(o,s,{iv:a});return ne.enc.Hex.stringify(c)},i=function(e,t,i){return n(ne.AES,e,t,i)},n=function(e,t,i,n){var r=ne.enc.Hex.parse(t),s=ne.enc.Hex.parse(i),a=ne.enc.Hex.parse(n),o=e.encrypt(r,s,{iv:a}),c=ne.enc.Hex.parse(o.toString());return ne.enc.Base64.stringify(c)},r={"AES-256-CBC":{proc:e,eproc:i,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:i,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:i,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,i,n){return t(ne.TripleDES,e,i,n)},eproc:function(e,t,i){return n(ne.TripleDES,e,t,i)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,i,n){return t(ne.DES,e,i,n)},eproc:function(e,t,i){return n(ne.DES,e,t,i)},keylen:8,ivlen:8}},s=function(e){var t={},i=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));i&&(t.cipher=i[1],t.ivsalt=i[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var r=-1,s=0;-1!=e.indexOf("\r\n\r\n")&&(r=e.indexOf("\r\n\r\n"),s=2),-1!=e.indexOf("\n\n")&&(r=e.indexOf("\n\n"),s=1);var a=e.indexOf("-----END");if(-1!=r&&-1!=a){var o=e.substring(r+2*s,a-s);o=o.replace(/\s+/g,""),t.data=o}return t},a=function(e,t,i){for(var n=i.substring(0,16),s=ne.enc.Hex.parse(n),a=ne.enc.Utf8.parse(t),o=r[e].keylen+r[e].ivlen,c="",d=null;;){var l=ne.algo.MD5.create();if(null!=d&&l.update(d),l.update(a),l.update(s),d=l.finalize(),(c+=ne.enc.Hex.stringify(d)).length>=2*o)break}var h={};return h.keyhex=c.substr(0,2*r[e].keylen),h.ivhex=c.substr(2*r[e].keylen,2*r[e].ivlen),h},o=function(e,t,i,n){var s=ne.enc.Base64.parse(e),a=ne.enc.Hex.stringify(s);return(0,r[t].proc)(a,i,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return s(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,i){return a(e,t,i)},decryptKeyB64:function(e,t,i,n){return o(e,t,i,n)},getDecryptedKeyHex:function(e,t){var i=s(e),n=i.cipher,r=i.ivsalt,c=i.data,d=a(n,t,r).keyhex;return o(c,n,d,r)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,i,n,s){var o="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===r[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===s||null==s){var c=function(e){var t=ne.lib.WordArray.random(e);return ne.enc.Hex.stringify(t)}(r[n].ivlen);s=c.toUpperCase()}var d=function(e,t,i,n){return(0,r[t].eproc)(e,i,n)}(t,n,a(n,i,s).keyhex,s);o="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return o+="Proc-Type: 4,ENCRYPTED\r\n",o+="DEK-Info: "+n+","+s+"\r\n",o+="\r\n",o+=d.replace(/(.{64})/g,"$1\r\n"),o+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},getEncryptedPKCS8PEM:function(e,t,i){return ht(this.getEncryptedPKCS8Hex(e,t,i),"ENCRYPTED PRIVATE KEY")},getEncryptedPKCS8Hex:function(e,t,i){var n;(n=null==i||null==i?{}:JSON.parse(JSON.stringify(i))).plain=e,this.initPBES2Param(n),this.encryptPBES2Param(n,t);var r=this.generatePBES2ASN1Param(n);return Je.asn1.ASN1Util.newObject(r).tohex()},initPBES2Param:function(e){var t;(null==Dt(e,"encalg")&&(e.encalg="aes256-CBC"),null==Dt(e,"iter")&&(e.iter=2048),null==Dt(e,"prf")&&(e.prf="hmacWithSHA256"),null==Dt(e,"salt")&&(e.salt=ne.enc.Hex.stringify(ne.lib.WordArray.random(8))),null==Dt(e,"enciv"))&&("des-EDE3-CBC"==e.encalg&&(t=8),"aes128-CBC"==e.encalg&&(t=16),"aes256-CBC"==e.encalg&&(t=16),e.enciv=ne.enc.Hex.stringify(ne.lib.WordArray.random(t)))},encryptPBES2Param:function(e,t){var i=kt.getDKFromPBES2Param(e,t);try{var n=Je.crypto.Cipher.encrypt(e.plain,i,e.encalg,{iv:e.enciv})}catch(t){throw new Error("encrypt error: "+e.plain+" "+i+" "+e.encalg+" "+e.enciv)}e.enc=n},generatePBES2ASN1Param:function(e){var t={seq:[{seq:[{oid:"pkcs5PBES2"},{seq:[{seq:[{oid:"pkcs5PBKDF2"},{seq:[{octstr:{hex:e.salt}},{int:{hex:It(e.iter)}}]}]},{seq:[{oid:e.encalg},{octstr:{hex:e.enciv}}]}]}]},{octstr:{hex:e.enc}}]};return"hmacWithSHA1"!=e.prf&&t.seq[0].seq[1].seq[0].seq[1].seq.push({seq:[{oid:e.prf},{null:""}]}),t},parseHexOfEncryptedPKCS8:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={},s=i(e,0);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+s.length);r.ciphertext=n(e,s[1]);var a=i(e,s[0]);if(2!=a.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+a.length);if("2a864886f70d01050d"!=n(e,a[0]))throw new Error("this only supports pkcs5PBES2");var o=i(e,a[1]);if(2!=a.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+o.length);var c=i(e,o[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";r.encryptionSchemeAlg="TripleDES",r.encryptionSchemeIV=n(e,c[1]);var d=i(e,o[0]);if(2!=d.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+d.length);if("2a864886f70d01050c"!=n(e,d[0]))throw new Error("this only supports pkcs5PBKDF2");var l=i(e,d[1]);if(l.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+l.length);r.pbkdf2Salt=n(e,l[0]);var h=n(e,l[1]);try{r.pbkdf2Iter=parseInt(h,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+h)}return r},getPBKDF2KeyHexFromParam:function(e,t){var i=ne.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,r=ne.PBKDF2(t,i,{keySize:6,iterations:n});return ne.enc.Hex.stringify(r)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var i=ut(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(i),r=kt.getPBKDF2KeyHexFromParam(n,t),s={};s.ciphertext=ne.enc.Hex.parse(n.ciphertext);var a=ne.enc.Hex.parse(r),o=ne.enc.Hex.parse(n.encryptionSchemeIV),c=ne.TripleDES.decrypt(s,a,{iv:o});return ne.enc.Hex.stringify(c)},parsePBES2:function(e){var t=Qe.parse(e);if("pkcs5PBES2"!=Dt(t,"seq.0.seq.0.oid")||"pkcs5PBKDF2"!=Dt(t,"seq.0.seq.1.seq.0.seq.0.oid"))throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");var i=Dt(t,"seq.0.seq.1.seq.0.seq.1.seq");if(null==i)throw new Error("PBKDF2 parameter not found");var n=Dt(i,"0.octstr.hex"),r=Dt(i,"1.int.hex"),s=Dt(i,"2.seq.0.oid","hmacWithSHA1"),a=-1;try{a=parseInt(r,16)}catch(e){throw new Error("iter not proper value")}var o=Dt(t,"seq.0.seq.1.seq.1.seq.0.oid"),c=Dt(t,"seq.0.seq.1.seq.1.seq.1.octstr.hex"),d=Dt(t,"seq.1.octstr.hex");if(null==o||null==c||null==d)throw new Error("encalg, enciv or enc is undefined");return{salt:n,iter:a,prf:s,encalg:o,enciv:c,enc:d}},getDKFromPBES2Param:function(e,t){var i={hmacWithSHA1:ne.algo.SHA1,hmacWithSHA224:ne.algo.SHA224,hmacWithSHA256:ne.algo.SHA256,hmacWithSHA384:ne.algo.SHA384,hmacWithSHA512:ne.algo.SHA512}[e.prf];if(null==i)throw new Error("unsupported prf");var n={"des-EDE3-CBC":6,"aes128-CBC":4,"aes256-CBC":8}[e.encalg];if(null==n)throw new Error("unsupported encalg");var r=ne.enc.Hex.parse(e.salt),s=e.iter;try{var a=ne.PBKDF2(t,r,{keySize:n,iterations:s,hasher:i});return ne.enc.Hex.stringify(a)}catch(i){throw new Error("PBKDF2 error: "+i+" "+JSON.stringify(e)+" "+t)}},getPlainHexFromEncryptedPKCS8PEM:function(e,t){if(-1==e.indexOf("BEGIN ENCRYPTED PRIVATE KEY"))throw new Error("not Encrypted PKCS#8 PEM string");var i,n=ut(e);try{i=kt.parsePBES2(n)}catch(e){throw new Error("malformed PBES2 format: "+e.message)}var r=kt.getDKFromPBES2Param(i,t);return Je.crypto.Cipher.decrypt(i.enc,r,i.encalg,{iv:i.enciv})},getKeyFromEncryptedPKCS8PEM:function(e,t){var i=this.getPlainHexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(i)},parsePlainPrivatePKCS8Hex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var s=i(e,0);if(s.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(s[1],2))throw new Error("malformed PKCS8 private key(code:003)");var a=i(e,s[1]);if(2!=a.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(r.algoid=n(e,a[0]),"06"==e.substr(a[1],2)&&(r.algparam=n(e,a[1])),"04"!=e.substr(s[2],2))throw new Error("malformed PKCS8 private key(code:006)");return r.keyidx=t.getVidx(e,s[2]),r},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=ut(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,i=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==i.algoid)t=new Ge;else if("2a8648ce380401"==i.algoid)t=new Je.crypto.DSA;else{if("2a8648ce3d0201"!=i.algoid)throw new Error("unsupported private key algorithm");t=new Je.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,i=Qe.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===i)t=new Ge;else if("2a8648ce380401"===i)t=new Je.crypto.DSA;else{if("2a8648ce3d0201"!==i)throw new Error("unsupported PKCS#8 public key hex");t=new Je.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var s=i(e,0);if(2!=s.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(s[0],2))throw new Error("malformed RSA key(code:003)");if(r.n=n(e,s[0]),"02"!=e.substr(s[1],2))throw new Error("malformed RSA key(code:004)");return r.e=n(e,s[1]),r},parsePublicPKCS8Hex:function(e){var t=Qe,i=t.getChildIdx,n=t.getV,r={algparam:null},s=i(e,0);if(2!=s.length)throw new Error("outer DERSequence shall have 2 elements: "+s.length);var a=s[0];if("30"!=e.substr(a,2))throw new Error("malformed PKCS8 public key(code:001)");var o=i(e,a);if(2!=o.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(o[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(r.algoid=n(e,o[0]),"06"==e.substr(o[1],2)?r.algparam=n(e,o[1]):"30"==e.substr(o[1],2)&&(r.algparam={},r.algparam.p=t.getVbyList(e,o[1],[0],"02"),r.algparam.q=t.getVbyList(e,o[1],[1],"02"),r.algparam.g=t.getVbyList(e,o[1],[2],"02")),"03"!=e.substr(s[1],2))throw new Error("malformed PKCS8 public key(code:004)");return r.key=n(e,s[1]).substr(2),r}}}();function Ot(e,t){for(var i="",n=t/4-e.length,r=0;r<n;r++)i+="0";return i+e}function Ft(e,t,i){for(var n="",r=0;n.length<t;)n+=dt(i(lt(e+String.fromCharCode.apply(String,[(4278190080&r)>>24,(16711680&r)>>16,(65280&r)>>8,255&r])))),r+=1;return n}function Mt(e){for(var t in Je.crypto.Util.DIGESTINFOHEAD){var i=Je.crypto.Util.DIGESTINFOHEAD[t],n=i.length;if(e.substring(0,n)==i)return[t,e.substring(n)]}return[]}function Ht(e){var t=Qe,i=t.getChildIdx,n=t.getV;t.dump;var r,s=t.parse,a=t.getTLV,o=t.getVbyList,c=t.getVbyListEx,d=t.getTLVbyList,l=t.getTLVbyListEx,h=t.getIdxbyList,u=t.getIdxbyListEx,p=t.getVidx,g=t.getInt,f=t.oidname,m=t.hextooidstr,v=ut,y=Error;try{r=Je.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=d(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=d(e,0,[0]),i=g(t,0);if(i<0||2<i)throw new Error("malformed version field");return this.version=i+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return c(this.hex,0,[0,0],"02")},this.getSignatureAlgorithmField=function(){var e=l(this.hex,0,[0,1]);return this.getAlgorithmIdentifierName(e)},this.getAlgorithmIdentifierName=function(e){for(var t in r)if(e===r[t])return t;return f(c(e,0,[0],"06"))},this.getIssuer=function(e,t){return this.getX500Name(this.getIssuerHex(),e,t)},this.getIssuerHex=function(){return d(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return this.getIssuer().str},this.getSubject=function(e,t){return this.getX500Name(this.getSubjectHex(),e,t)},this.getSubjectHex=function(){return d(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=o(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getNotAfter=function(){var e=o(this.hex,0,[0,4+this.foffset,1]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getPublicKeyHex=function(){return this.getSPKI()},this.getSPKI=function(){return d(this.hex,0,[0,6+this.foffset],"30")},this.getSPKIValue=function(){var e=this.getSPKI();return null==e?null:o(e,0,[1],"03",!0)},this.getPublicKeyIdx=function(){return h(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return h(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return kt.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=d(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return o(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),i=this.getSignatureValueHex(),n=d(this.hex,0,[0],"30"),r=new Je.crypto.Signature({alg:t});return r.init(e),r.updateHex(n),r.verify(i)},this.parseExt=function(e){var r,s,a;if(void 0===e){if(a=this.hex,3!==this.version)return-1;r=h(a,0,[0,7,0],"30"),s=i(a,r)}else{a=ut(e);var c=h(a,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=n(a,c))return void(this.aExtInfo=new Array);r=h(a,0,[0,3,0,1,0],"30"),s=i(a,r),this.hex=a}this.aExtInfo=new Array;for(var d=0;d<s.length;d++){var l={critical:!1},u=0;3===i(a,s[d]).length&&(l.critical=!0,u=1),l.oid=t.hextooidstr(o(a,s[d],[0],"06"));var g=h(a,s[d],[1+u]);l.vidx=p(a,g),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,i=e;if(e.match(/^[0-9.]+$/)||(i=Je.asn1.x509.OID.name2oid(e)),""!==i)for(var n=0;n<t.length;n++)if(t[n].oid===i)return t[n]},this.getCriticalExtV=function(e,t,i){if(null!=t)return[t,i];var n=this.getExtInfo(e);return null==n?[null,null]:[a(this.hex,n.vidx),n.critical]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("basicConstraints");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var r={extname:"basicConstraints"};if(t&&(r.critical=!0),"3000"===e)return r;if("30030101ff"===e)return r.cA=!0,r;if("30060101ff02"===e.substr(0,12)){var s=n(e,10),o=parseInt(s,16);return r.cA=!0,r.pathLen=o,r}throw new Error("hExtV parse error: "+e)},this.getExtNameConstraints=function(e,t){var n=this.getCriticalExtV("nameConstraints",e,t);if(e=n[0],t=n[1],null!=e){var r={extname:"nameConstraints"};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){for(var c=[],d=i(e,s[o]),l=0;l<d.length;l++){var h=a(e,d[l]),u=this.getGeneralSubtree(h);c.push(u)}var p=e.substr(s[o],2);"a0"==p?r.permit=c:"a1"==p&&(r.exclude=c)}return r}},this.getGeneralSubtree=function(e){var t=i(e,0),r=t.length;if(r<1||2<r)throw new Error("wrong num elements");for(var s=this.getGeneralName(a(e,t[0])),o=1;o<r;o++){var c=e.substr(t[o],2),d=n(e,t[o]),l=parseInt(d,16);"80"==c&&(s.min=l),"81"==c&&(s.max=l)}return s},this.getExtKeyUsage=function(e,t){var i=this.getCriticalExtV("keyUsage",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"keyUsage"};return t&&(n.critical=!0),n.names=this.getExtKeyUsageString(e).split(","),n}},this.getExtKeyUsageBin=function(e){if(void 0===e){var t=this.getExtInfo("keyUsage");if(void 0===t)return"";e=a(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var i="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(i=i.slice(-8)),10==e.length&&(i=i.slice(-16)),""==(i=i.replace(/0+$/,""))&&(i="0"),i},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),i=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&i.push(Ht.KEYUSAGE_NAME[n]);return i.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectKeyIdentifier");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var r={extname:"subjectKeyIdentifier"};t&&(r.critical=!0);var s=n(e,0);return r.kid={hex:s},r},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("authorityKeyIdentifier");if(void 0===r)return;e=a(this.hex,r.vidx),t=r.critical}var s={extname:"authorityKeyIdentifier"};t&&(s.critical=!0);for(var o=i(e,0),c=0;c<o.length;c++){var d=e.substr(o[c],2);if("80"===d&&(s.kid={hex:n(e,o[c])}),"a1"===d){var l=a(e,o[c]),h=this.getGeneralNames(l);s.issuer=h[0].dn}"82"===d&&(s.sn={hex:n(e,o[c])})}return s},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("extKeyUsage");if(void 0===r)return;e=a(this.hex,r.vidx),t=r.critical}var s={extname:"extKeyUsage",array:[]};t&&(s.critical=!0);for(var o=i(e,0),c=0;c<o.length;c++)s.array.push(f(n(e,o[c])));return s},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,r=a(this.hex,e.vidx);if(""===r)return t;for(var s=i(r,0),o=0;o<s.length;o++)t.push(f(n(r,s[o])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectAltName");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"subjectAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getExtIssuerAltName=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("issuerAltName");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=i(e,0),n=[],r=0;r<t.length;r++){var s=this.getGeneralName(a(e,t[r]));void 0!==s&&n.push(s)}return n},this.getGeneralName=function(e){var t=e.substr(0,2),i=n(e,0),r=dt(i);return"81"==t?{rfc822:r}:"82"==t?{dns:r}:"86"==t?{uri:r}:"87"==t?{ip:yt(i)}:"a4"==t?{dn:this.getX500Name(i)}:"a0"==t?{other:this.getOtherName(e)}:void 0},this.getExtSubjectAltName2=function(){var e,t,r,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var o=new Array,c=a(this.hex,s.vidx),d=i(c,0),l=0;l<d.length;l++)r=c.substr(d[l],2),e=n(c,d[l]),"81"===r&&(t=ot(e),o.push(["MAIL",t])),"82"===r&&(t=ot(e),o.push(["DNS",t])),"84"===r&&(t=Ht.hex2dn(e,0),o.push(["DN",t])),"86"===r&&(t=ot(e),o.push(["URI",t])),"87"===r&&(t=yt(e),o.push(["IP",t]));return o},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("cRLDistributionPoints");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"cRLDistributionPoints",array:[]};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){var c=a(e,s[o]);r.array.push(this.getDistributionPoint(c))}return r},this.getDistributionPoint=function(e){for(var t={},n=i(e,0),r=0;r<n.length;r++){var s=e.substr(n[r],2),o=a(e,n[r]);"a0"==s&&(t.dpname=this.getDistributionPointName(o))}return t},this.getDistributionPointName=function(e){for(var t={},n=i(e,0),r=0;r<n.length;r++){var s=e.substr(n[r],2),o=a(e,n[r]);"a0"==s&&(t.full=this.getGeneralNames(o))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtCRLDistributionPoints();if(null==e)return e;for(var t=e.array,i=[],n=0;n<t.length;n++)try{null!=t[n].dpname.full[0].uri&&i.push(t[n].dpname.full[0].uri)}catch(e){}return i},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},n=i(this.hex,e.vidx),r=0;r<n.length;r++){var s=o(this.hex,n[r],[0],"06"),a=o(this.hex,n[r],[1],"86");"2b06010505073001"===s&&t.ocsp.push(ot(a)),"2b06010505073002"===s&&t.caissuer.push(ot(a))}return t},this.getExtAuthorityInfoAccess=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("authorityInfoAccess");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"authorityInfoAccess",array:[]};t&&(r.critical=!0);for(var s=i(e,0),d=0;d<s.length;d++){var l=c(e,s[d],[0],"06"),h=ot(o(e,s[d],[1],"86"));if("2b06010505073001"==l)r.array.push({ocsp:h});else{if("2b06010505073002"!=l)throw new Error("unknown method: "+l);r.array.push({caissuer:h})}}return r},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("certificatePolicies");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"certificatePolicies",array:[]};t&&(r.critical=!0);for(var s=i(e,0),o=0;o<s.length;o++){var c=a(e,s[o]),d=this.getPolicyInformation(c);r.array.push(d)}return r},this.getPolicyInformation=function(e){var t={},n=o(e,0,[0],"06");t.policyoid=f(n);var r=u(e,0,[1],"30");if(-1!=r){t.array=[];for(var s=i(e,r),c=0;c<s.length;c++){var d=a(e,s[c]),l=this.getPolicyQualifierInfo(d);t.array.push(l)}}return t},this.getOtherName=function(e){var t={},n=i(e,0),r=o(e,n[0],[],"06"),a=o(e,n[1],[]);return t.oid=f(r),t.value=s(a),t},this.getPolicyQualifierInfo=function(e){var t={},i=o(e,0,[0],"06");if("2b06010505070201"===i){var n=c(e,0,[1],"16");t.cps=dt(n)}else if("2b06010505070202"===i){var r=d(e,0,[1],"30");t.unotice=this.getUserNotice(r)}return t},this.getUserNotice=function(e){var i=null;try{return i=t.parse(e),this._asn1ToUnotice(i)}catch(e){return}},this._asn1ToUnotice=function(e){try{for(var t={},i=Dt(e,"seq"),n=0;n<i.length;n++){var r=this._asn1ToNoticeRef(i[n]);null!=r&&(t.noticeref=r);var s=this.asn1ToDisplayText(i[n]);null!=s&&(t.exptext=s)}return Object.keys(t).length>0?t:void 0}catch(e){return}},this._asn1ToNoticeRef=function(e){try{for(var t={},i=Dt(e,"seq"),n=0;n<i.length;n++){var r=this._asn1ToNoticeNum(i[n]);null!=r&&(t.noticenum=r);var s=this.asn1ToDisplayText(i[n]);null!=s&&(t.org=s)}return Object.keys(t).length>0?t:void 0}catch(e){return}},this._asn1ToNoticeNum=function(e){try{for(var t=Dt(e,"seq"),i=[],n=0;n<t.length;n++){var r=t[n];i.push(parseInt(Dt(r,"int.hex"),16))}return i}catch(e){return}},this.getDisplayText=function(e){var t={};return t.type={"0c":"utf8",16:"ia5","1a":"vis","1e":"bmp"}[e.substr(0,2)],t.str=dt(n(e,0)),t},this.asn1ToDisplayText=function(e){return null!=e.utf8str?{type:"utf8",str:e.utf8str.str}:null!=e.ia5str?{type:"ia5",str:e.ia5str.str}:null!=e.visstr?{type:"vis",str:e.visstr.str}:null!=e.bmpstr?{type:"bmp",str:e.bmpstr.str}:null!=e.prnstr?{type:"prn",str:e.prnstr.str}:void 0},this.getExtPolicyMappings=function(e,t){var i=this.getCriticalExtV("policyMappings",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"policyMappings"};t&&(n.critical=!0);try{for(var r=s(e).seq,a=[],o=0;o<r.length;o++){var c=r[o].seq;a.push([c[0].oid,c[1].oid])}n.array=a}catch(e){throw new y("malformed policyMappings")}return n}},this.getExtPolicyConstraints=function(e,t){var i=this.getCriticalExtV("policyConstraints",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"policyConstraints"};t&&(n.critical=!0);var r=s(e);try{for(var a=r.seq,o=0;o<a.length;o++){var c=a[o].tag;0==c.explicit&&("80"==c.tag&&(n.reqexp=parseInt(c.hex,16)),"81"==c.tag&&(n.inhibit=parseInt(c.hex,16)))}}catch(e){return new y("malformed policyConstraints value")}return n}},this.getExtInhibitAnyPolicy=function(e,t){var i=this.getCriticalExtV("inhibitAnyPolicy",e,t);if(e=i[0],t=i[1],null!=e){var n={extname:"inhibitAnyPolicy"};t&&(n.critical=!0);var r=g(e,0);return-1==r?new y("wrong value"):(n.skip=r,n)}},this.getExtCRLNumber=function(e,t){var i={extname:"cRLNumber"};if(t&&(i.critical=!0),"02"==e.substr(0,2))return i.num={hex:n(e,0)},i;throw new y("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var i={extname:"cRLReason"};if(t&&(i.critical=!0),"0a"==e.substr(0,2))return i.code=parseInt(n(e,0),16),i;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var i={extname:"ocspNonce"};t&&(i.critical=!0);var r=n(e,0);return i.hex=r,i},this.getExtOcspNoCheck=function(e,t){var i={extname:"ocspNoCheck"};return t&&(i.critical=!0),i},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("adobeTimeStamp");if(void 0===n)return;e=a(this.hex,n.vidx),t=n.critical}var r={extname:"adobeTimeStamp"};t&&(r.critical=!0);var s=i(e,0);if(s.length>1){var o=a(e,s[1]),c=this.getGeneralName(o);null!=c.uri&&(r.uri=c.uri)}if(s.length>2){var d=a(e,s[2]);"0101ff"==d&&(r.reqauth=!0),"010100"==d&&(r.reqauth=!1)}return r},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("subjectDirectoryAttributes");if(void 0===i)return;e=a(this.hex,i.vidx),t=i.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var r=s(e),o=[],c=0;c<r.seq.length;c++){var d=r.seq[c],l=Dt(d,"seq.0.oid"),h=Dt(d,"seq.1.set");if(null==l||null==h)throw"error";o.push({attr:l,array:h})}return n.array=o,n}catch(e){throw new Error("malformed subjectDirectoryAttributes extension value")}};var S=function(e){var t={};try{var i=e.seq[0].oid,n=Je.asn1.x509.OID.name2oid(i);t.type=Je.asn1.x509.OID.oid2atype(n);var r=e.seq[1];if(null!=r.utf8str)t.ds="utf8",t.value=r.utf8str.str;else if(null!=r.numstr)t.ds="num",t.value=r.numstr.str;else if(null!=r.telstr)t.ds="tel",t.value=r.telstr.str;else if(null!=r.prnstr)t.ds="prn",t.value=r.prnstr.str;else if(null!=r.ia5str)t.ds="ia5",t.value=r.ia5str.str;else if(null!=r.visstr)t.ds="vis",t.value=r.visstr.str;else{if(null==r.bmpstr)throw"error";t.ds="bmp",t.value=r.bmpstr.str}return t}catch(e){throw new Erorr("improper ASN.1 parsed AttrTypeAndValue")}},b=function(e){try{return e.set.map((function(e){return S(e)}))}catch(e){throw new Error("improper ASN.1 parsed RDN: "+e)}};this.getX500NameRule=function(e){for(var t=null,i=[],n=0;n<e.length;n++)for(var r=e[n],s=0;s<r.length;s++)i.push(r[s]);for(n=0;n<i.length;n++){var a=i[n],o=a.ds,c=a.value,d=a.type;if("prn"!=o&&"utf8"!=o&&"ia5"!=o)return"mixed";if("ia5"==o){if("CN"!=d)return"mixed";if(Je.lang.String.isMail(c))continue;return"mixed"}if("C"==d){if("prn"==o)continue;return"mixed"}if(null==t)t=o;else if(t!==o)return"mixed"}return null==t?"prn":t},this.getAttrTypeAndValue=function(e){var t=s(e);return S(t)},this.getRDN=function(e){var t=s(e);return b(t)},this.getX500NameArray=function(e){return function(e){try{return e.seq.map((function(e){return b(e)}))}catch(e){throw new Error("improper ASN.1 parsed X500Name: "+e)}}(s(e))},this.getX500Name=function(e,t,i){var n=this.getX500NameArray(e),r={str:this.dnarraytostr(n)};return r.array=n,1==i&&(r.hex=e),1==t&&(r.canon=this.c14nRDNArray(n)),r},this.readCertPEM=function(e){this.readCertHex(v(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{h(this.hex,0,[0,7],"a3"),this.parseExt()}catch(e){}},this.getParam=function(e){var t={};return null==e&&(e={}),t.version=this.getVersion(),t.serial={hex:this.getSerialNumberHex()},t.sigalg=this.getSignatureAlgorithmField(),t.issuer=this.getIssuer(e.dncanon,e.dnhex),t.notbefore=this.getNotBefore(),t.notafter=this.getNotAfter(),t.subject=this.getSubject(e.dncanon,e.dnhex),t.sbjpubkey=ht(this.getPublicKeyHex(),"PUBLIC KEY"),null!=this.aExtInfo&&this.aExtInfo.length>0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=d(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=u(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=i(e,0),r=0;r<n.length;r++){var s=a(e,n[r]),o=this.getExtParam(s);null!=o&&t.push(o)}return t},this.getExtParam=function(e){var t=i(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var n=m(o(e,0,[0],"06")),r=!1;3==t&&"0101ff"==d(e,0,[1])&&(r=!0);var a=d(e,0,[t-1,0]),c=void 0;if("2.5.29.14"==n?c=this.getExtSubjectKeyIdentifier(a,r):"2.5.29.15"==n?c=this.getExtKeyUsage(a,r):"2.5.29.17"==n?c=this.getExtSubjectAltName(a,r):"2.5.29.18"==n?c=this.getExtIssuerAltName(a,r):"2.5.29.19"==n?c=this.getExtBasicConstraints(a,r):"2.5.29.30"==n?c=this.getExtNameConstraints(a,r):"2.5.29.31"==n?c=this.getExtCRLDistributionPoints(a,r):"2.5.29.32"==n?c=this.getExtCertificatePolicies(a,r):"2.5.29.33"==n?c=this.getExtPolicyMappings(a,r):"2.5.29.35"==n?c=this.getExtAuthorityKeyIdentifier(a,r):"2.5.29.36"==n?c=this.getExtPolicyConstraints(a,r):"2.5.29.37"==n?c=this.getExtExtKeyUsage(a,r):"2.5.29.54"==n?c=this.getExtInhibitAnyPolicy(a,r):"1.3.6.1.5.5.7.1.1"==n?c=this.getExtAuthorityInfoAccess(a,r):"2.5.29.20"==n?c=this.getExtCRLNumber(a,r):"2.5.29.21"==n?c=this.getExtCRLReason(a,r):"2.5.29.9"==n?c=this.getExtSubjectDirectoryAttributes(a,r):"1.3.6.1.5.5.7.48.1.2"==n?c=this.getExtOcspNonce(a,r):"1.3.6.1.5.5.7.48.1.5"==n?c=this.getExtOcspNoCheck(a,r):"1.2.840.113583.1.1.9.1"==n?c=this.getExtAdobeTimeStamp(a,r):null!=Ht.EXT_PARSER[n]&&(c=Ht.EXT_PARSER[n](n,r,a)),null!=c)return c;var l={extname:n,extn:a};try{l.extn=s(a)}catch(e){}return r&&(l.critical=!0),l},this.findExt=function(e,t){for(var i=0;i<e.length;i++)if(e[i].extname==t)return e[i];return null},this.updateExtCDPFullURI=function(e,t){var i=this.findExt(e,"cRLDistributionPoints");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)if(null!=n[r].dpname&&null!=n[r].dpname.full)for(var s=n[r].dpname.full,a=0;a<s.length;a++){var o=s[r];null!=o.uri&&(o.uri=t)}},this.updateExtAIAOCSP=function(e,t){var i=this.findExt(e,"authorityInfoAccess");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)null!=n[r].ocsp&&(n[r].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var i=this.findExt(e,"authorityInfoAccess");if(null!=i&&null!=i.array)for(var n=i.array,r=0;r<n.length;r++)null!=n[r].caissuer&&(n[r].caissuer=t)},this.dnarraytostr=function(e){return"/"+e.map((function(e){return function(e){return e.map((function(e){return function(e){return e.type+"="+e.value}(e).replace(/\+/,"\\+")})).join("+")}(e).replace(/\//,"\\/")})).join("/")},this.setCanonicalizedDN=function(e){var t;if(null!=e.str&&null==e.array){var i=new Je.asn1.x509.X500Name({str:e.str}).tohex();t=this.getX500NameArray(i)}else t=e.array;null==e.canon&&(e.canon=this.c14nRDNArray(t))},this.c14nRDNArray=function(e){for(var t=[],i=0;i<e.length;i++){for(var n=e[i],r=[],s=0;s<n.length;s++){var a=n[s],o=a.value;o=(o=(o=(o=o.replace(/^\s*/,"")).replace(/\s*$/,"")).replace(/\s+/g," ")).toLowerCase(),r.push(a.type.toLowerCase()+"="+o)}t.push(r.join("+"))}return"/"+t.join("/")},this.getInfo=function(){var e,t,i,n=function(e){for(var t="",i=" ",n="\n",r=e.array,s=0;s<r.length;s++){var a=r[s];if(null!=a.dn&&(t+=i+"dn: "+a.dn.str+n),null!=a.ip&&(t+=i+"ip: "+a.ip+n),null!=a.rfc822&&(t+=i+"rfc822: "+a.rfc822+n),null!=a.dns&&(t+=i+"dns: "+a.dns+n),null!=a.uri&&(t+=i+"uri: "+a.uri+n),null!=a.other)t+=i+"other: "+a.other.oid+"="+JSON.stringify(a.other.value).replace(/\"/g,"")+n}return t=t.replace(/\n$/,"")},r=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];if(t+=" policy oid: "+r.policyoid+"\n",void 0!==r.array)for(var s=0;s<r.array.length;s++){var a=r.array[s];void 0!==a.cps&&(t+=" cps: "+a.cps+"\n")}}return t},s=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];try{void 0!==r.dpname.full[0].uri&&(t+=" "+r.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==r.dname.full[0].dn.hex&&(t+=" "+Ht.hex2dn(r.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},a=function(e){for(var t="",i=e.array,n=0;n<i.length;n++){var r=i[n];void 0!==r.caissuer&&(t+=" caissuer: "+r.caissuer+"\n"),void 0!==r.ocsp&&(t+=" ocsp: "+r.ocsp+"\n")}return t};if(e="Basic Fields\n",e+=" serial number: "+this.getSerialNumberHex()+"\n",e+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n",e+=" issuer: "+this.getIssuerString()+"\n",e+=" notBefore: "+this.getNotBefore()+"\n",e+=" notAfter: "+this.getNotAfter()+"\n",e+=" subject: "+this.getSubjectString()+"\n",e+=" subject public key info: \n",e+=" key algorithm: "+(t=this.getPublicKey()).type+"\n","RSA"===t.type&&(e+=" n="+_t(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+_t(t.e.toString(16))+"\n"),null!=(i=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var o=0;o<i.length;o++){var c=i[o],d=Je.asn1.x509.OID.oid2name(c.oid);""===d&&(d=c.oid);var l="";if(!0===c.critical&&(l="CRITICAL"),e+=" "+d+" "+l+":\n","basicConstraints"===d){var h=this.getExtBasicConstraints();void 0===h.cA?e+=" {}\n":(e+=" cA=true",void 0!==h.pathLen&&(e+=", pathLen="+h.pathLen),e+="\n")}else{var u;if("policyMappings"==d)e+=" "+this.getExtPolicyMappings().array.map((function(e){var t=e;return t[0]+":"+t[1]})).join(", ")+"\n";else if("policyConstraints"==d)e+=" ",null!=(u=this.getExtPolicyConstraints()).reqexp&&(e+=" reqexp="+u.reqexp),null!=u.inhibit&&(e+=" inhibit="+u.inhibit),e+="\n";else if("inhibitAnyPolicy"==d)e+=" skip="+(u=this.getExtInhibitAnyPolicy()).skip+"\n";else if("keyUsage"==d)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"==d)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"==d){var p=this.getExtAuthorityKeyIdentifier();void 0!==p.kid&&(e+=" kid="+p.kid.hex+"\n")}else{if("extKeyUsage"==d)e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n";else if("subjectAltName"==d)e+=n(this.getExtSubjectAltName())+"\n";else if("cRLDistributionPoints"==d)e+=s(this.getExtCRLDistributionPoints());else if("authorityInfoAccess"==d)e+=a(this.getExtAuthorityInfoAccess());else"certificatePolicies"==d&&(e+=r(this.getExtCertificatePolicies()))}}}}return e+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n",e+="signature: "+this.getSignatureValueHex().substr(0,16)+"...\n"},"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?this.readCertPEM(e):Je.lang.String.isHex(e)&&this.readCertHex(e))}kt.getKey=function(e,t,i){var n=(m=Qe).getChildIdx;m.getV;var r=m.getVbyList,s=Je.crypto,a=s.ECDSA,o=s.DSA,c=Ge,d=ut,l=kt;if(void 0!==c&&e instanceof c)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==o&&e instanceof o)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new a({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new a({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(x=new c).setPublic(e.n,e.e),x;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.co&&void 0===e.qi)return(x=new c).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),x;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(x=new c).setPrivate(e.n,e.e,e.d),x;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(x=new o).setPublic(e.p,e.q,e.g,e.y),x;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(x=new o).setPrivate(e.p,e.q,e.g,e.y,e.x),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(x=new c).setPublic(st(e.n),st(e.e)),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0!==e.p&&void 0!==e.q&&void 0!==e.dp&&void 0!==e.dq&&void 0!==e.qi)return(x=new c).setPrivateEx(st(e.n),st(e.e),st(e.d),st(e.p),st(e.q),st(e.dp),st(e.dq),st(e.qi)),x;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(x=new c).setPrivate(st(e.n),st(e.e),st(e.d)),x;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var h=(_=new a({curve:e.crv})).ecparams.keycharlen,u="04"+("0000000000"+st(e.x)).slice(-h)+("0000000000"+st(e.y)).slice(-h);return _.setPublicKeyHex(u),_}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){h=(_=new a({curve:e.crv})).ecparams.keycharlen,u="04"+("0000000000"+st(e.x)).slice(-h)+("0000000000"+st(e.y)).slice(-h);var p=("0000000000"+st(e.d)).slice(-h);return _.setPublicKeyHex(u),_.setPrivateKeyHex(p),_}if("pkcs5prv"===i){var g,f=e,m=Qe;if(9===(g=n(f,0)).length)(x=new c).readPKCS5PrvKeyHex(f);else if(6===g.length)(x=new o).readPKCS5PrvKeyHex(f);else{if(!(g.length>2&&"04"===f.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(x=new a).readPKCS5PrvKeyHex(f)}return x}if("pkcs8prv"===i)return x=l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===i)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===i)return Ht.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return Ht.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var v=ut(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(v)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var y=d(e,"RSA PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var S=r(A=d(e,"DSA PRIVATE KEY"),0,[1],"02"),b=r(A,0,[2],"02"),w=r(A,0,[3],"02"),E=r(A,0,[4],"02"),C=r(A,0,[5],"02");return(x=new o).setPrivate(new de(S,16),new de(b,16),new de(w,16),new de(E,16),new de(C,16)),x}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){y=d(e,"EC PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END PRIVATE KEY-"))return l.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var $=l.getDecryptedKeyHex(e,t),T=new Ge;return T.readPKCS5PrvKeyHex($),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var _,x=r(A=l.getDecryptedKeyHex(e,t),0,[1],"04"),I=r(A,0,[2,0],"06"),R=r(A,0,[3,0],"03").substr(2);if(void 0===Je.crypto.OID.oidhex2name[I])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+I);return(_=new a({curve:Je.crypto.OID.oidhex2name[I]})).setPublicKeyHex(R),_.setPrivateKeyHex(x),_.isPublic=!1,_}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var A;S=r(A=l.getDecryptedKeyHex(e,t),0,[1],"02"),b=r(A,0,[2],"02"),w=r(A,0,[3],"02"),E=r(A,0,[4],"02"),C=r(A,0,[5],"02");return(x=new o).setPrivate(new de(S,16),new de(b,16),new de(w,16),new de(E,16),new de(C,16)),x}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},kt.generateKeypair=function(e,t){if("RSA"==e){var i=t;(a=new Ge).generate(i,"10001"),a.isPrivate=!0,a.isPublic=!0;var n=new Ge,r=a.n.toString(16),s=a.e.toString(16);return n.setPublic(r,s),n.isPrivate=!1,n.isPublic=!0,(o={}).prvKeyObj=a,o.pubKeyObj=n,o}if("EC"==e){var a,o,c=t,d=new Je.crypto.ECDSA({curve:c}).generateKeyPairHex();return(a=new Je.crypto.ECDSA({curve:c})).setPublicKeyHex(d.ecpubhex),a.setPrivateKeyHex(d.ecprvhex),a.isPrivate=!0,a.isPublic=!1,(n=new Je.crypto.ECDSA({curve:c})).setPublicKeyHex(d.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(o={}).prvKeyObj=a,o.pubKeyObj=n,o}throw new Error("unknown algorithm: "+e)},kt.getPEM=function(e,t,i,n,r,s){var a=Je,o=a.asn1,c=o.DERObjectIdentifier,d=o.DERInteger,l=o.ASN1Util.newObject,h=o.x509.SubjectPublicKeyInfo,u=a.crypto,p=u.DSA,g=u.ECDSA,f=Ge;function m(e){return l({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function v(e){return l({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function y(e){return l({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==f&&e instanceof f||void 0!==p&&e instanceof p||void 0!==g&&e instanceof g)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return ht(E=new h(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===i||null==i)&&1==e.isPrivate)return ht(E=m(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===i||null==i)&&1==e.isPrivate){var S=new c({name:e.curveName}).tohex(),b=v(e).tohex(),w="";return w+=ht(S,"EC PARAMETERS"),w+=ht(b,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===i||null==i)&&1==e.isPrivate)return ht(E=y(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==i&&null!=i&&1==e.isPrivate){var E=m(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,i,n,s)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==i&&null!=i&&1==e.isPrivate){E=v(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,i,n,s)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==i&&null!=i&&1==e.isPrivate){E=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,i,n,s)}var C=function(e,t){if("string"==typeof t)return kt.getEncryptedPKCS8PEM(e,t);if("object"==typeof t&&null!=Dt(t,"passcode")){var i=JSON.parse(JSON.stringify(t)),n=i.passcode;return delete i.passcode,kt.getEncryptedPKCS8PEM(e,n,i)}};if("PKCS8PRV"==t&&null!=f&&e instanceof f&&1==e.isPrivate){var $=m(e).tohex();E=l({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){var T={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&T.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});$=new l(T).tohex(),E=l({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){$=new d({bigint:e.x}).tohex(),E=l({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:$}}]}).tohex();return void 0===i||null==i?ht(E,"PRIVATE KEY"):C(E,i)}throw new Error("unsupported object nor format")},kt.getKeyFromCSRPEM=function(e){var t=ut(e,"CERTIFICATE REQUEST");return kt.getKeyFromCSRHex(t)},kt.getKeyFromCSRHex=function(e){var t=kt.parseCSRHex(e);return kt.getKey(t.p8pubkeyhex,null,"pkcs8pub")},kt.parseCSRHex=function(e){var t=Qe,i=t.getChildIdx,n=t.getTLV,r={},s=e;if("30"!=s.substr(0,2))throw new Error("malformed CSR(code:001)");var a=i(s,0);if(a.length<1)throw new Error("malformed CSR(code:002)");if("30"!=s.substr(a[0],2))throw new Error("malformed CSR(code:003)");var o=i(s,a[0]);if(o.length<3)throw new Error("malformed CSR(code:004)");return r.p8pubkeyhex=n(s,o[2]),r},kt.getKeyID=function(e){var t=kt,i=Qe;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=ut(t.getPEM(e)),r=i.getIdxbyList(n,0,[1]),s=i.getV(n,r).substring(2);return Je.crypto.Util.hashHex(s,"sha1")},kt.getJWK=function(e,t,i,n,r){var s,a,o={},c=Je.crypto.Util.hashHex;if("string"==typeof e)s=kt.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(a=ut(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof Ht?(s=e.getPublicKey(),a=e.hex):s=e}if(s instanceof Ge&&s.isPrivate)o.kty="RSA",o.n=rt(s.n.toString(16)),o.e=rt(s.e.toString(16)),o.d=rt(s.d.toString(16)),o.p=rt(s.p.toString(16)),o.q=rt(s.q.toString(16)),o.dp=rt(s.dmp1.toString(16)),o.dq=rt(s.dmq1.toString(16)),o.qi=rt(s.coeff.toString(16));else if(s instanceof Ge&&s.isPublic)o.kty="RSA",o.n=rt(s.n.toString(16)),o.e=rt(s.e.toString(16));else if(s instanceof Je.crypto.ECDSA&&s.isPrivate){if("P-256"!==(l=s.getShortNISTPCurveName())&&"P-384"!==l&&"P-521"!==l)throw new Error("unsupported curve name for JWT: "+l);var d=s.getPublicKeyXYHex();o.kty="EC",o.crv=l,o.x=rt(d.x),o.y=rt(d.y),o.d=rt(s.prvKeyHex)}else if(s instanceof Je.crypto.ECDSA&&s.isPublic){var l;if("P-256"!==(l=s.getShortNISTPCurveName())&&"P-384"!==l&&"P-521"!==l)throw new Error("unsupported curve name for JWT: "+l);d=s.getPublicKeyXYHex();o.kty="EC",o.crv=l,o.x=rt(d.x),o.y=rt(d.y)}if(null==o.kty)throw new Error("unsupported keyinfo");return s.isPrivate||1==t||(o.kid=Je.jws.JWS.getJWKthumbprint(o)),null!=a&&1!=i&&(o.x5c=[oe(a)]),null!=a&&1!=n&&(o.x5t=it(oe(c(a,"sha1")))),null!=a&&1!=r&&(o["x5t#S256"]=it(oe(c(a,"sha256")))),o},kt.getJWKFromKey=function(e){return kt.getJWK(e,!0,!0,!0,!0)},Ge.getPosArrayOfChildrenFromHex=function(e){return Qe.getChildIdx(e,0)},Ge.getHexValueArrayOfChildrenFromHex=function(e){var t,i=Qe.getV,n=i(e,(t=Ge.getPosArrayOfChildrenFromHex(e))[0]),r=i(e,t[1]),s=i(e,t[2]),a=i(e,t[3]),o=i(e,t[4]),c=i(e,t[5]),d=i(e,t[6]),l=i(e,t[7]),h=i(e,t[8]);return(t=new Array).push(n,r,s,a,o,c,d,l,h),t},Ge.prototype.readPrivateKeyFromPEMString=function(e){var t=ut(e),i=Ge.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8])},Ge.prototype.readPKCS5PrvKeyHex=function(e){var t=Ge.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},Ge.prototype.readPKCS8PrvKeyHex=function(e){var t,i,n,r,s,a,o,c,d=Qe,l=d.getVbyListEx;if(!1===d.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=l(e,0,[2,0,1],"02"),i=l(e,0,[2,0,2],"02"),n=l(e,0,[2,0,3],"02"),r=l(e,0,[2,0,4],"02"),s=l(e,0,[2,0,5],"02"),a=l(e,0,[2,0,6],"02"),o=l(e,0,[2,0,7],"02"),c=l(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,i,n,r,s,a,o,c)},Ge.prototype.readPKCS5PubKeyHex=function(e){var t=Qe,i=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var r=i(e,n[0]),s=i(e,n[1]);this.setPublic(r,s)},Ge.prototype.readPKCS8PubKeyHex=function(e){var t=Qe;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var i=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(i)},Ge.prototype.readCertPubKeyHex=function(e,t){var i,n;(i=new Ht).readCertHex(e),n=i.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},Ge.prototype.sign=function(e,t){var i=function(e){return Je.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(i,t)},Ge.prototype.signWithMessageHash=function(e,t){var i=qe(Je.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return Ot(this.doPrivate(i).toString(16),this.n.bitLength())},Ge.prototype.signPSS=function(e,t,i){var n=function(e){return Je.crypto.Util.hashHex(e,t)}(lt(e));return void 0===i&&(i=-1),this.signWithMessageHashPSS(n,t,i)},Ge.prototype.signWithMessageHashPSS=function(e,t,i){var n,r=dt(e),s=r.length,a=this.n.bitLength()-1,o=Math.ceil(a/8),c=function(e){return Je.crypto.Util.hashHex(e,t)};if(-1===i||void 0===i)i=s;else if(-2===i)i=o-s-2;else if(i<-2)throw new Error("invalid salt length");if(o<s+i+2)throw new Error("data too long");var d="";i>0&&(d=new Array(i),(new Ve).nextBytes(d),d=String.fromCharCode.apply(String,d));var l=dt(c(lt("\0\0\0\0\0\0\0\0"+r+d))),h=[];for(n=0;n<o-i-s-2;n+=1)h[n]=0;var u=String.fromCharCode.apply(String,h)+""+d,p=Ft(l,u.length,c),g=[];for(n=0;n<u.length;n+=1)g[n]=u.charCodeAt(n)^p.charCodeAt(n);var f=65280>>8*o-a&255;for(g[0]&=~f,n=0;n<s;n++)g.push(l.charCodeAt(n));return g.push(188),Ot(this.doPrivate(new de(g)).toString(16),this.n.bitLength())},Ge.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var i=qe(t,16),n=this.n.bitLength();if(i.bitLength()>n)return!1;var r=this.doPublic(i).toString(16);if(r.length+3!=n/4)return!1;var s=Mt(r.replace(/^1f+00/,""));if(0==s.length)return!1;var a=s[0],o=s[1],c=function(e){return Je.crypto.Util.hashString(e,a)}(e);return o==c},Ge.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i=qe(t,16);if(i.bitLength()>this.n.bitLength())return 0;var n=Mt(this.doPublic(i).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},Ge.prototype.verifyPSS=function(e,t,i,n){var r,s=(r=lt(e),Je.crypto.Util.hashHex(r,i));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(s,t,i,n)},Ge.prototype.verifyWithMessageHashPSS=function(e,t,i,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r,s=new de(t,16),a=function(e){return Je.crypto.Util.hashHex(e,i)},o=dt(e),c=o.length,d=this.n.bitLength()-1,l=Math.ceil(d/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=l-c-2;else if(n<-2)throw new Error("invalid salt length");if(l<c+n+2)throw new Error("data too long");var h=this.doPublic(s).toByteArray();for(r=0;r<h.length;r+=1)h[r]&=255;for(;h.length<l;)h.unshift(0);if(188!==h[l-1])throw new Error("encoded message does not end in 0xbc");var u=(h=String.fromCharCode.apply(String,h)).substr(0,l-c-1),p=h.substr(u.length,c),g=65280>>8*l-d&255;if(0!=(u.charCodeAt(0)&g))throw new Error("bits beyond keysize not zero");var f=Ft(p,u.length,a),m=[];for(r=0;r<u.length;r+=1)m[r]=u.charCodeAt(r)^f.charCodeAt(r);m[0]&=~g;var v=l-c-n-2;for(r=0;r<v;r+=1)if(0!==m[r])throw new Error("leftmost octets not zero");if(1!==m[v])throw new Error("0x01 marker not found");return p===dt(a(lt("\0\0\0\0\0\0\0\0"+o+String.fromCharCode.apply(String,m.slice(-n)))))},Ge.SALT_LEN_HLEN=-1,Ge.SALT_LEN_MAX=-2,Ge.SALT_LEN_RECOVER=-2,Ht.EXT_PARSER={},Ht.registExtParser=function(e,t){Ht.EXT_PARSER[e]=t},Ht.hex2dn=function(e,t){void 0===t&&(t=0);var i=new Ht;return Qe.getTLV(e,t),i.getX500Name(e).str},Ht.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var i=new Array,n=Qe.getChildIdx(e,t),r=0;r<n.length;r++)i.push(Ht.hex2attrTypeValue(e,n[r]));return i=i.map((function(e){return e.replace("+","\\+")})),i.join("+")},Ht.hex2attrTypeValue=function(e,t){var i=Qe,n=i.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var r=i.getChildIdx(e,t);2!==r.length||e.substr(r[0],2);var s=n(e,r[0]),a=Je.asn1.ASN1Util.oidHexToInt(s);return Je.asn1.x509.OID.oid2atype(a)+"="+dt(n(e,r[1]))},Ht.getPublicKeyFromCertHex=function(e){var t=new Ht;return t.readCertHex(e),t.getPublicKey()},Ht.getPublicKeyFromCertPEM=function(e){var t=new Ht;return t.readCertPEM(e),t.getPublicKey()},Ht.getPublicKeyInfoPropOfCertPEM=function(e){var t,i,n=Qe.getVbyList,r={};return r.algparam=null,(t=new Ht).readCertPEM(e),i=t.getPublicKeyHex(),r.keyhex=n(i,0,[1],"03").substr(2),r.algoid=n(i,0,[0,0],"06"),"2a8648ce3d0201"===r.algoid&&(r.algparam=n(i,0,[0,1],"06")),r},Ht.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==Je&&Je||(Je={}),void 0!==Je.jws&&Je.jws||(Je.jws={}),Je.jws.JWS=function(){var e=Je.jws.JWS.isSafeJSONString;this.parseJWS=function(t,i){if(void 0===this.parsedJWS||!i&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var r=n[1],s=n[2],a=n[3],o=r+"."+s;if(this.parsedJWS={},this.parsedJWS.headB64U=r,this.parsedJWS.payloadB64U=s,this.parsedJWS.sigvalB64U=a,this.parsedJWS.si=o,!i){var c=st(a),d=qe(c,16);this.parsedJWS.sigvalH=c,this.parsedJWS.sigvalBI=d}var l=Xe(r),h=Xe(s);if(this.parsedJWS.headS=l,this.parsedJWS.payloadS=h,!e(l,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+l}}},Je.jws.JWS.sign=function(e,t,i,n,r){var s=Je,a=s.jws.JWS,o=a.readSafeJSONString,c=a.isSafeJSONString,d=s.crypto;d.ECDSA;var l,h,u,p=d.Mac,g=d.Signature,f=JSON;if("string"!=typeof t&&"object"!=typeof t)throw"spHeader must be JSON string or object: "+t;if("object"==typeof t&&(h=t,l=f.stringify(h)),"string"==typeof t){if(!c(l=t))throw"JWS Head is not safe JSON string: "+l;h=o(l)}if(u=i,"object"==typeof i&&(u=f.stringify(i)),""!=e&&null!=e||void 0===h.alg||(e=h.alg),""!=e&&null!=e&&void 0===h.alg&&(h.alg=e,l=f.stringify(h)),e!==h.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+h.alg;var m=null;if(void 0===a.jwsalg2sigalg[e])throw"unsupported alg name: "+e;m=a.jwsalg2sigalg[e];var v=Ze(l)+"."+Ze(u),y="";if("Hmac"==m.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var S=new p({alg:m,prov:"cryptojs",pass:n});S.updateString(v),y=S.doFinal()}else if(-1!=m.indexOf("withECDSA")){(w=new g({alg:m})).init(n,r),w.updateString(v);var b=w.sign();y=Je.crypto.ECDSA.asn1SigToConcatSig(b)}else{var w;if("none"!=m)(w=new g({alg:m})).init(n,r),w.updateString(v),y=w.sign()}return v+"."+rt(y)},Je.jws.JWS.verify=function(e,t,i){var n,r=Je,s=r.jws.JWS,a=s.readSafeJSONString,o=r.crypto,c=o.ECDSA,d=o.Mac,l=o.Signature;if(n=Ge,!Tt(e))return!1;var h=e.split(".");if(3!==h.length)return!1;var u=h[0]+"."+h[1],p=st(h[2]),g=a(Xe(h[0])),f=null,m=null;if(void 0===g.alg)throw"algorithm not specified in header";if((m=(f=g.alg).substr(0,2),null!=i&&"[object Array]"===Object.prototype.toString.call(i)&&i.length>0)&&-1==(":"+i.join(":")+":").indexOf(":"+f+":"))throw"algorithm '"+f+"' not accepted in the list";if("none"!=f&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=kt.getKey(t)),!("RS"!=m&&"PS"!=m||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==m&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var v=null;if(void 0===s.jwsalg2sigalg[g.alg])throw"unsupported alg name: "+f;if("none"==(v=s.jwsalg2sigalg[f]))throw"not supported";if("Hmac"==v.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var y=new d({alg:v,pass:t});return y.updateString(u),p==y.doFinal()}if(-1!=v.indexOf("withECDSA")){var S,b=null;try{b=c.concatSigToASN1Sig(p)}catch(e){return!1}return(S=new l({alg:v})).init(t),S.updateString(u),S.verify(b)}return(S=new l({alg:v})).init(t),S.updateString(u),S.verify(p)},Je.jws.JWS.parse=function(e){var t,i,n,r=e.split("."),s={};if(2!=r.length&&3!=r.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=r[0],i=r[1],3==r.length&&(n=r[2]),s.headerObj=Je.jws.JWS.readSafeJSONString(Xe(t)),s.payloadObj=Je.jws.JWS.readSafeJSONString(Xe(i)),s.headerPP=JSON.stringify(s.headerObj,null," "),null==s.payloadObj?s.payloadPP=Xe(i):s.payloadPP=JSON.stringify(s.payloadObj,null," "),void 0!==n&&(s.sigHex=st(n)),s},Je.jws.JWS.verifyJWT=function(e,t,i){var n=Je.jws,r=n.JWS,s=r.readSafeJSONString,a=r.inArray,o=r.includedArray;if(!Tt(e))return!1;var c=e.split(".");if(3!=c.length)return!1;var d=c[0],l=c[1];st(c[2]);var h=s(Xe(d)),u=s(Xe(l));if(void 0===h.alg)return!1;if(void 0===i.alg)throw"acceptField.alg shall be specified";if(!a(h.alg,i.alg))return!1;if(void 0!==u.iss&&"object"==typeof i.iss&&!a(u.iss,i.iss))return!1;if(void 0!==u.sub&&"object"==typeof i.sub&&!a(u.sub,i.sub))return!1;if(void 0!==u.aud&&"object"==typeof i.aud)if("string"==typeof u.aud){if(!a(u.aud,i.aud))return!1}else if("object"==typeof u.aud&&!o(u.aud,i.aud))return!1;var p=n.IntDate.getNow();return void 0!==i.verifyAt&&"number"==typeof i.verifyAt&&(p=i.verifyAt),void 0!==i.gracePeriod&&"number"==typeof i.gracePeriod||(i.gracePeriod=0),!(void 0!==u.exp&&"number"==typeof u.exp&&u.exp+i.gracePeriod<p)&&(!(void 0!==u.nbf&&"number"==typeof u.nbf&&p<u.nbf-i.gracePeriod)&&(!(void 0!==u.iat&&"number"==typeof u.iat&&p<u.iat-i.gracePeriod)&&((void 0===u.jti||void 0===i.jti||u.jti===i.jti)&&!!r.verify(e,t,i.alg))))},Je.jws.JWS.includedArray=function(e,t){var i=Je.jws.JWS.inArray;if(null===e)return!1;if("object"!=typeof e)return!1;if("number"!=typeof e.length)return!1;for(var n=0;n<e.length;n++)if(!i(e[n],t))return!1;return!0},Je.jws.JWS.inArray=function(e,t){if(null===t)return!1;if("object"!=typeof t)return!1;if("number"!=typeof t.length)return!1;for(var i=0;i<t.length;i++)if(t[i]==e)return!0;return!1},Je.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",ES512:"SHA512withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},Je.jws.JWS.isSafeJSONString=function(e,t,i){var n=null;try{return"object"!=typeof(n=Ye(e))||n.constructor===Array?0:(t&&(t[i]=n),1)}catch(e){return 0}},Je.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=typeof(t=Ye(e))||t.constructor===Array?null:t}catch(e){return null}},Je.jws.JWS.getEncodedSignatureValueFromJWS=function(e){var t=e.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(null==t)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return t[1]},Je.jws.JWS.getJWKthumbprint=function(e){if("RSA"!==e.kty&&"EC"!==e.kty&&"oct"!==e.kty)throw"unsupported algorithm for JWK Thumprint";var t="{";if("RSA"===e.kty){if("string"!=typeof e.n||"string"!=typeof e.e)throw"wrong n and e value for RSA key";t+='"e":"'+e.e+'",',t+='"kty":"'+e.kty+'",',t+='"n":"'+e.n+'"}'}else if("EC"===e.kty){if("string"!=typeof e.crv||"string"!=typeof e.x||"string"!=typeof e.y)throw"wrong crv, x and y value for EC key";t+='"crv":"'+e.crv+'",',t+='"kty":"'+e.kty+'",',t+='"x":"'+e.x+'",',t+='"y":"'+e.y+'"}'}else if("oct"===e.kty){if("string"!=typeof e.k)throw"wrong k value for oct(symmetric) key";t+='"kty":"'+e.kty+'",',t+='"k":"'+e.k+'"}'}var i=lt(t);return rt(Je.crypto.Util.hashHex(i,"sha256"))},Je.jws.IntDate={},Je.jws.IntDate.get=function(e){var t=Je.jws.IntDate,i=t.getNow,n=t.getZulu;if("now"==e)return i();if("now + 1hour"==e)return i()+3600;if("now + 1day"==e)return i()+86400;if("now + 1month"==e)return i()+2592e3;if("now + 1year"==e)return i()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},Je.jws.IntDate.getZulu=function(e){return pt(e)},Je.jws.IntDate.getNow=function(){return~~(new Date/1e3)},Je.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},Je.jws.IntDate.intDate2Zulu=function(e){var t=new Date(1e3*e);return("0000"+t.getUTCFullYear()).slice(-4)+("00"+(t.getUTCMonth()+1)).slice(-2)+("00"+t.getUTCDate()).slice(-2)+("00"+t.getUTCHours()).slice(-2)+("00"+t.getUTCMinutes()).slice(-2)+("00"+t.getUTCSeconds()).slice(-2)+"Z"},void 0!==Je&&Je||(Je={}),void 0!==Je.jws&&Je.jws||(Je.jws={}),Je.jws.JWSJS=function(){var e=Je.jws.JWS,t=e.readSafeJSONString;this.aHeader=[],this.sPayload="",this.aSignature=[],this.init=function(){this.aHeader=[],this.sPayload=void 0,this.aSignature=[]},this.initWithJWS=function(e){this.init();var t=e.split(".");if(3!=t.length)throw"malformed input JWS";this.aHeader.push(t[0]),this.sPayload=t[1],this.aSignature.push(t[2])},this.addSignature=function(e,t,i,n){if(void 0===this.sPayload||null===this.sPayload)throw"there's no JSON-JS signature to add.";var r=this.aHeader.length;if(this.aHeader.length!=this.aSignature.length)throw"aHeader.length != aSignature.length";try{var s=Je.jws.JWS.sign(e,t,this.sPayload,i,n).split(".");s[0],s[2];this.aHeader.push(s[0]),this.aSignature.push(s[2])}catch(e){throw this.aHeader.length>r&&this.aHeader.pop(),this.aSignature.length>r&&this.aSignature.pop(),"addSignature failed: "+e}},this.verifyAll=function(e){if(this.aHeader.length!==e.length||this.aSignature.length!==e.length)return!1;for(var t=0;t<e.length;t++){var i=e[t];if(2!==i.length)return!1;if(!1===this.verifyNth(t,i[0],i[1]))return!1}return!0},this.verifyNth=function(t,i,n){if(this.aHeader.length<=t||this.aSignature.length<=t)return!1;var r=this.aHeader[t],s=this.aSignature[t],a=r+"."+this.sPayload+"."+s,o=!1;try{o=e.verify(a,i,n)}catch(e){return!1}return o},this.readJWSJS=function(e){if("string"==typeof e){var i=t(e);if(null==i)throw"argument is not safe JSON object string";this.aHeader=i.headers,this.sPayload=i.payload,this.aSignature=i.signatures}else try{if(!(e.headers.length>0))throw"malformed header";if(this.aHeader=e.headers,"string"!=typeof e.payload)throw"malformed signatures";if(this.sPayload=e.payload,!(e.signatures.length>0))throw"malformed signatures";this.aSignature=e.signatures}catch(e){throw"malformed JWS-JS JSON object: "+e}},this.getJSON=function(){return{headers:this.aHeader,payload:this.sPayload,signatures:this.aSignature}},this.isEmpty=function(){return 0==this.aHeader.length?1:0}},Je.crypto.ECDSA,Je.crypto.DSA,Je.crypto.Signature,Je.crypto.MessageDigest,Je.crypto.Mac;var Lt=kt,jt=Xe,Bt=Je;Je.crypto,Je.asn1,Je.jws,Je.lang;var Ut=(e,t)=>{const i={};return Object.getOwnPropertyNames(e).forEach((t=>{i[t]=e[t]})),new t(i)};class Vt{type;id;extensions;endpointCustom;endpointSccp;endpointSip;static parse(e){return new Vt({id:e.id,extensions:e.extensions,endpointCustom:e.endpoint_custom||null,endpointSccp:e.endpoint_sccp||null,endpointSip:e.endpoint_sip||null})}static newFrom(e){return Ut(e,Vt)}is(e){return!!e&&this.id===e.id}hasExtension(e){return!!this.extensions&&this.extensions.some((t=>t.exten===e))}constructor({id:e,extensions:t,endpointCustom:i,endpointSccp:n,endpointSip:r}={}){this.id=e,this.extensions=t,this.endpointCustom=i||null,this.endpointSccp=n||null,this.endpointSip=r||null,this.type="Line"}}const qt={BUSY:"busy",NO_ANSWER:"noanswer",UNCONDITIONAL:"unconditional"};class Gt{destination;enabled;key;static parse(e,t){return new Gt({destination:e.destination||"",enabled:e.enabled,key:t})}static newFrom(e){return Ut(e,Gt)}constructor({destination:e,enabled:t,key:i}={}){this.destination=e,this.enabled=t,this.key=i}setDestination(e){return this.destination=e,this}setEnabled(e){return this.enabled=e,this}is(e){return this.key===e.key}}class Kt{id;extensions;extension;type="Incall";constructor({id:e,extensions:t}={}){this.id=e,this.extensions=t,this.extension=t?.[0]?.exten}static parse(e){return new Kt({id:e.id,extensions:e.extensions})}static newFrom(e){return Ut(e,Kt)}hasExtension(e){return!!this.extensions&&this.extensions.some((t=>t.exten===e))}}const Wt={AVAILABLE:"available",UNAVAILABLE:"unavailable",INVISIBLE:"invisible",DISCONNECTED:"disconnected",AWAY:"away"},zt={AVAILABLE:"available",HOLDING:"holding",RINGING:"ringing",TALKING:"talking",UNAVAILABLE:"unavailable",PROGRESSING:"progressing"};class Yt{id;firstName;lastName;email;lines;sipLines;incalls;username;mobileNumber;forwards;doNotDisturb;onlineCallRecordEnabled;state;ringSeconds;voicemail;status;subscriptionType;agent;switchboards;callPickupTargetUsers;static parse(e){return new Yt({id:e.uuid,firstName:e.firstName||e.firstname||"",lastName:e.lastName||e.lastname||"",email:e.email,lines:e.lines.map((e=>Vt.parse(e))),incalls:e.incalls,username:e.username,mobileNumber:e.mobile_phone_number||"",ringSeconds:e.ring_seconds,forwards:[Gt.parse(e.forwards.unconditional,qt.UNCONDITIONAL),Gt.parse(e.forwards.noanswer,qt.NO_ANSWER),Gt.parse(e.forwards.busy,qt.BUSY)],doNotDisturb:e.services.dnd.enabled,subscriptionType:e.subscription_type,voicemail:e.voicemail,switchboards:e.switchboards||[],agent:e.agent,status:"",callPickupTargetUsers:e.call_pickup_target_users||[],onlineCallRecordEnabled:e.online_call_record_enabled})}static newFrom(e){return Ut(e,Yt)}constructor({id:e,firstName:t,lastName:i,email:n,lines:r,username:s,mobileNumber:a,forwards:o,doNotDisturb:c,state:d,subscriptionType:l,voicemail:h,switchboards:u,agent:p,status:g,ringSeconds:f,sipLines:m,callPickupTargetUsers:v,onlineCallRecordEnabled:y,incalls:S}){this.id=e,this.firstName=t,this.lastName=i,this.email=n,this.lines=r,this.username=s,this.mobileNumber=a,this.forwards=o,this.doNotDisturb=c,this.state=d,this.voicemail=h,this.subscriptionType=l,this.switchboards=u,this.agent=p,this.status=g,this.callPickupTargetUsers=v,this.onlineCallRecordEnabled=y,this.ringSeconds=f,this.sipLines=m||[],this.incalls=S?.map(Kt.parse)||[]}static getLinesState(e){let t=zt.UNAVAILABLE;for(const i of e){if(i.state===zt.RINGING){t=zt.RINGING;break}if(i.state===zt.TALKING){t=zt.TALKING;break}i.state===zt.AVAILABLE&&(t=zt.AVAILABLE)}return t}hasId(e){return e===this.id}setMobileNumber(e){return this.mobileNumber=e,this}setForwardOption(e){const t=this.forwards.slice(),i=t.findIndex((t=>t.is(e)));return t.splice(i,1,e),this.forwards=t,this}setDoNotDisturb(e){return this.doNotDisturb=e,this}setState(e){return this.state=e,this}}const Jt={OFFICE365:"office365",PERSONAL:"personal",GOOGLE:"google",WAZO:"wazo",CONFERENCE:"conference",PHONEBOOK:"phonebook"},Zt="mobile";class Xt{static BACKEND=Jt;type;id;uuid;name;number;numbers;favorited;email;emails;entreprise;birthday;address;note;endpointId;personal;state;lineState;previousPresential;lastActivity;mobile;source;sourceId;status;backend;personalStatus;sessions;connected;doNotDisturb;ringing;lines;static merge(e,t){return t.map((t=>{const i=e.find((e=>e&&e.is(t)));return i?t.merge(i):t}))}static sortContacts(e,t){const i=e.separateName(),n=t.separateName(),r=i.lastName,s=n.lastName;return r===s?i.firstName.localeCompare(n.firstName):r.localeCompare(s)}static parseMany(e,t=0,i=null){if(!e||!e.results||0===i)return[];return(null!==i&&i>0?e.results.slice(t,i):t>0?e.results.slice(t):e.results).map((t=>Xt.parse(t,e.column_types)))}static manyGraphQlWithNumbersParser(e){return t=>t.data&&t.data.me&&t.data.me.contacts?t.data.me.contacts.edges.map(((t,i)=>{if(!t.node)return null;const{email:n}=t.node,r=t.node.firstname&&t.node.lastname?`${t.node.firstname||""} ${t.node.lastname||""}`:t.node.wazoReverse;return new Xt({name:r,number:e[i],numbers:[{label:"primary",number:e[i]}],backend:t.node.wazoBackend,source:t.node.wazoSourceName,sourceId:t.node.wazoSourceEntryId||"",email:n||"",emails:n?[{label:"primary",email:n}]:[],uuid:t.node.userUuid})})).filter((e=>!!e)):[]}static fetchNumbers(e,t){const i=t.map(((e,t)=>({index:t,columnName:e}))).filter((e=>"number"===e.columnName||"callable"===e.columnName)).map((e=>e.index));return e.column_values.filter(((e,t)=>i.some((e=>e===t))&&null!==e))}static parse(e,t){const i=Xt.fetchNumbers(e,t),n=e.column_values[t.indexOf("email")];return new Xt({name:e.column_values[t.indexOf("name")],number:i.length?i[0]:"",numbers:i.map(((e,t)=>({label:0===t?"primary":"secondary",number:e}))),favorited:e.column_values[t.indexOf("favorite")],email:n||"",emails:n?[{label:"primary",email:n}]:[],entreprise:e.column_values[t.indexOf("entreprise")]||"",birthday:e.column_values[t.indexOf("birthday")]||"",address:e.column_values[t.indexOf("address")]||"",note:e.column_values[t.indexOf("note")]||"",endpointId:e.relations.endpoint_id,personal:e.column_values[t.indexOf("personal")],source:e.source,sourceId:e.relations.source_entry_id||"",uuid:e.relations.user_uuid,backend:e.backend||""})}static parseManyPersonal(e){return e.map((e=>Xt.parsePersonal(e)))}static parsePersonal(e){return new Xt({name:`${e.firstName||e.firstname||""} ${e.lastName||e.lastname||""}`,number:e.number||"",numbers:e.number?[{label:"primary",number:e.number}]:[],email:e.email||"",emails:e.email?[{label:"primary",email:e.email}]:[],source:"personal",sourceId:e.id||"",entreprise:e.entreprise||"",birthday:e.birthday||"",address:e.address||"",note:e.note||"",favorited:e.favorited,personal:!0,backend:e.backend||Jt.PERSONAL})}static parseMobile(e){let t="";if(e.postalAddresses.length){const i=e.postalAddresses[0];t=`${i.street} ${i.city} ${i.postCode} ${i.country}`}const i=e.givenName||"",n=e.familyName||"",r=e.company||"";return new Xt({name:!i&&!n?r:`${i} ${n}`,number:e.phoneNumbers.length?e.phoneNumbers[0].number:"",numbers:[...new Map(e.phoneNumbers.map((e=>[e.number,e]))).values()].map(((e,t)=>({label:0===t?"primary":"secondary",number:e.number}))),email:e.emailAddresses.length?e.emailAddresses[0].email:"",emails:e.emailAddresses.length?[{label:"primary",email:e.emailAddresses[0].email}]:[],source:Zt,sourceId:e.recordID||"",birthday:e.birthday?`${e.birthday.year}-${e.birthday.month}-${e.birthday.day}`:"",address:t,note:e.note||"",favorited:!1,personal:!0})}static parseManyOffice365(e,t){return e.map((e=>Xt.parseOffice365(e,t)))}static parseOffice365(e,t){const i=[],n=[];return e.emailAddresses&&e.emailAddresses.map((e=>i.push({email:e.address}))),e.businessPhones&&e.businessPhones.map((e=>n.push({label:"business",number:e}))),e.mobilePhone&&n.push({label:"mobile",number:e.mobilePhone}),e.homePhones&&e.homePhones.map((e=>n.push({label:"home",number:e}))),new Xt({sourceId:e.id||"",name:e.displayName||"",number:n.length?n[0].number:"",numbers:n,emails:i,source:t.name,backend:Jt.OFFICE365})}static parseManyGoogle(e,t){return e.map((e=>Xt.parseGoogle(e,t)))}static parseGoogle(e,t){const i=[];return e.emails&&e.emails.forEach((e=>"object"==typeof e?{email:e.address,label:e.label}:{email:e})),e.numbers_by_label?Object.keys(e.numbers_by_label).forEach((t=>i.push({label:t,number:e.numbers_by_label[t]}))):e.numbers&&e.numbers.forEach((e=>i.push({number:e}))),new Xt({sourceId:e.id||"",name:e.name||"",number:i.length?i[0].number:"",numbers:i,emails:[],source:t.name,backend:Jt.GOOGLE})}static parseManyWazo(e,t){return e.map((e=>Xt.parseWazo(e,t)))}static parseWazo(e,t){const i=[],n=[];return e.email&&i.push({label:"email",email:e.email}),e.exten&&n.push({label:"exten",number:e.exten}),e.mobile_phone_number&&n.push({label:"mobile",number:e.mobile_phone_number}),new Xt({uuid:e.uuid,sourceId:String(e.id)||"",name:`${e.firstname}${e.lastname?` ${e.lastname}`:""}`,number:n.length?n[0].number:"",numbers:n,emails:i,source:t.name,backend:Jt.WAZO})}static parseManyConference(e,t){return e.map((e=>Xt.parseConference(e,t)))}static parseConference(e,t){const i=[];let n="";return e&&e.extensions&&e.extensions.length>0&&e.extensions[0].exten&&(n=e.extensions[0].exten,i.push({label:"exten",number:n})),new Xt({sourceId:String(e.id),name:e.name,number:n,numbers:i,source:t.name,backend:Jt.CONFERENCE})}static newFrom(e){return Ut(e,Xt)}constructor({id:e,uuid:t,name:i,number:n,numbers:r,email:s,emails:a,source:o,sourceId:c,entreprise:d,birthday:l,address:h,note:u,state:p,lineState:g,lastActivity:f,mobile:m,status:v,endpointId:y,personal:S,favorited:b,backend:w,personalStatus:E,sessions:C,connected:$,doNotDisturb:T,ringing:_,previousPresential:x,lines:I}={}){this.id=e,this.uuid=t,this.name=i||"",this.number=n,this.numbers=r,this.email=s,this.emails=a,this.source=o,this.sourceId=c,this.entreprise=d,this.birthday=l,this.address=h,this.note=u,this.state=p,this.lineState=g,this.lastActivity=f,this.mobile=m,this.status=v,this.endpointId=y,this.personal=S,this.favorited=b,this.backend=w,this.personalStatus=E||"",this.sessions=C||[],this.connected=$,this.doNotDisturb=T,this.ringing=_,this.previousPresential=x,this.lines=I||[],this.type="Contact"}setFavorite(e){return this.favorited=e,this}is(e){const t=null!==this.sourceId&&null!==e.sourceId&&this.sourceId===e.sourceId,i=!!this.uuid&&!!e.uuid&&this.uuid===e.uuid,n=t||i,r=!!this.backend&&!!e.backend&&this.backend===e.backend,s=!!this.source&&!!e.source&&this.source===e.source;return!!e&&n&&r&&s}hasId(e){return this.uuid===e}hasNumber(e){return this.number===e}hasEndpointId(e){return this.endpointId===e}isAvailable(){return this.state===Wt.AVAILABLE}isAway(){return this.state===Wt.AWAY}isUnavailable(){return this.state===Wt.UNAVAILABLE}isInvisible(){return this.state===Wt.INVISIBLE}isInCall(){return this.lineState===zt.TALKING||this.lineState===zt.HOLDING}isRinging(){return this.ringing}isInUseOrRinging(){return this.lineState===zt.TALKING||this.lineState===zt.RINGING}isProgressing(){return this.lineState===zt.PROGRESSING}merge(e){return Object.keys(e).filter((e=>"lineState"!==e)).forEach((t=>{this[t]=e[t]||this[t]})),e.lineState&&(this.lineState=e.lineState),this}isIntern(){return!!this.uuid}hasSourceId(){return!!this.sourceId}isCallable(e){return!!this.number&&!!e&&!e.is(this)}isFromMobile(){return this.source===Zt}isFavorite(){return this.favorited}separateName(){if(!this.name)return{firstName:"",lastName:""};const e=this.name.split(/\s+/);return{firstName:e[0],lastName:e.slice(1).join(" ")}}}const{jws:Qt}=Bt,ei=Lt.getKey("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmkXOuNfY8u5xoTiIhkb8\ndjnbIwG/Wrz3vpo8BZir8L5e1a1nSy740qBjP7ZINBQoALDhFfmdOfJnCyEGiHuz\nZW6jbG6C3PryE3Bu6GKwqSmD6k3q4Zk27fpwYAnNl+rWhYYM563rJZBda/INyHNN\npK7M1mixWi7gNdjjXwoEXSSBx+VpYMkY6LiAB2mvHXTY9M1qI14dvgGoQISZQoKi\nNMTRCg5UP2ic0Dd9nSz/XpcOxGfa+0fwIl1F7RC1tJXOqvkGGPTOV4LLfg/Yta3h\nnUPX9EZZDIX6vO/0IBV1LzjSl2A1bYFYAjJfowv3i1CpvONBOClHjSY5t9Y8MH6p\nBwIDAQAB\n-----END PUBLIC KEY-----");let ti=class e{acl;contact;token;refreshToken;uuid;tenantUuid;stackUuid;sessionUuid;engineVersion;_stackHostFromHeader;profile;expiresAt;authorizations;static parse(t){const i=t.data.metadata?t.data.metadata.jwt:null;let n=[];if(i){if(Qt.JWS.verifyJWT(i,ei,{alg:["RS256"],verifyAt:new Date})){const e=Qt.JWS.readSafeJSONString(jt(i.split(".")[1]));n=e?e.authorizations:[]}}return new e({token:t.data.token,refreshToken:t.data.refresh_token||null,uuid:t.data.metadata?t.data.metadata.uuid:null,sessionUuid:t.data.session_uuid,authorizations:n,acl:t.data.acls?t.data.acls:t.data.acl?t.data.acl:[],tenantUuid:t.data.metadata?t.data.metadata.tenant_uuid:void 0,expiresAt:_.utc(t.data.utc_expires_at).toDate(),stackUuid:t.data.xivo_uuid,stackHostFromHeader:t._headers?.get?.("wazo-stack-host")})}static newFrom(t){return Ut(t,e)}constructor({token:e,uuid:t,tenantUuid:i,profile:n,expiresAt:r,authorizations:s,acl:a,engineVersion:o,refreshToken:c,sessionUuid:d,stackUuid:l,stackHostFromHeader:h}){this.token=e,this.uuid=t,this.tenantUuid=i||null,this.profile=n,this.expiresAt=r,this.authorizations=s||[],this.acl=a||[],this.engineVersion=o,this.refreshToken=c,this.sessionUuid=d,this.stackUuid=l,this._stackHostFromHeader=h}hasExpired(e=new Date){return e>=this.expiresAt}is(e){return Boolean(e)&&this.uuid===e.uuid}using(e){return this.profile=e,this}hasAuthorizations(){return this.authorizations&&!!this.authorizations.length}displayName(){return this.profile?`${this.profile.firstName} ${this.profile.lastName}`:""}hasAccessToVoicemail(){return!!this.profile&&!!this.profile.voicemail}primaryLine(){return this.profile&&this.profile.lines.length>0?this.profile.lines[0]:null}primarySipLine(){return this.profile&&this.profile.sipLines.length>0?this.profile.sipLines[0]:null}primaryWebRtcLine(){return this.profile&&(this.profile.sipLines||[]).find((e=>e&&e.isWebRtc()))}primaryCtiLine(){return this.profile&&(this.profile.sipLines||[]).find((e=>e&&!e.isWebRtc()))}getContact(){if(this.contact)return this.contact;const{email:e,firstName:t,lastName:i,mobileNumber:n,state:r,status:s}=this.profile||{},a=this.primaryNumber()||"",o=[{label:"primary",number:a}];return n&&o.push({label:"mobile",number:n}),new Xt({uuid:this.uuid||"",email:e,name:`${t} ${i}`,number:a,numbers:o,state:r||"",status:s,backend:"wazo",source:"default"})}primaryContext(){if(this.engineVersion&&this.hasEngineVersionGte("19.08"))return"default";const e=this.primaryLine();return e&&Array.isArray(e.extensions)&&e.extensions.length>0?e.extensions[0].context:"default"}hasEngineVersionGte(e){return!!this.engineVersion&&((e,t)=>{let i,n;const r=/(\.0+)+$/,s=e.replace(r,"").split("."),a=t.replace(r,"").split("."),o=Math.min(s.length,a.length);for(i=0;i<o;i++)if(n=parseInt(s[i],10)-parseInt(a[i],10),n)return n;return s.length-a.length})(String(this.engineVersion),String(e))>=0}primaryNumber(){const e=this.primaryLine();return e&&Array.isArray(e.extensions)&&e.extensions.length?e.extensions[0].exten:null}allLines(){return this.profile&&this.profile.lines||[]}allNumbers(){const e=this.allLines().map((e=>e.extensions?.map((e=>e.exten))||[]));return e.length?e.reduce(((e,t)=>e.concat(t))):[]}hasExtension(e){return this.allNumbers().some((t=>t===e))}getHostFromHeader(){return this._stackHostFromHeader}get acls(){return console.warn("`acls` property of Session has been removed in Wazo's SDK, please use `acl` instead."),this.acl}get engineUuid(){return console.warn("`engineUuid` property of Session has been removed in Wazo's SDK, please use `stackUuid` instead."),this.stackUuid}toJSON(){return{...this,engineUuid:this.engineUuid}}};const ii="wazo_user",ni=3600;class ri{number;idType;type;static parse(e){return new ri({number:e.number,type:e.type})}static parseMany(e){return e.items.map((e=>ri.parse(e)))}static newFrom(e){return Ut(e,ri)}constructor({type:e,number:t}){this.idType=e,this.number=t,this.type="CallerID"}}const si=["vp8","vp9","h264"];class ai{id;uuid;tenantUuid;username;secret;type;host;options;endpointSectionOptions;links;trunk;line;static parse(e){let{username:t,secret:i,host:n}=e;if(e.auth_section_options){const r=(e,t)=>e.find((e=>e[0]===t)),s=r(e.auth_section_options,"username"),a=r(e.auth_section_options,"password"),o=r(e.endpoint_section_options,"media_address");t=s?s[1]:"",i=a?a[1]:"",n=o?o[1]:""}return new ai({id:e.id,uuid:e.uuid,tenantUuid:e.tenant_uuid,username:t,secret:i,type:e.type,host:n,options:e.options,endpointSectionOptions:e.endpoint_section_options,links:e.links,trunk:e.trunk,line:e.line})}static newFrom(e){return Ut(e,ai)}is(e){return e.uuid?this.uuid===e.uuid:this.id===e.id}getOptions(){return this.endpointSectionOptions||this.options||[]}isWebRtc(){return this.getOptions().some((e=>"webrtc"===e[0]&&"yes"===e[1]))}hasVideo(){const e=this.getOptions().find((e=>"allow"===e[0]));return Array.isArray(e)&&e[1].split(",").some((e=>si.some((t=>t===e))))}hasVideoConference(){return this.getOptions().some((e=>"max_audio_streams"===e[0]&&parseInt(e[1],10)>0))&&this.getOptions().some((e=>"max_video_streams"===e[0]&&parseInt(e[1],10)>1))}constructor({id:e,uuid:t,tenantUuid:i,username:n,secret:r,type:s,host:a,options:o,endpointSectionOptions:c,links:d,trunk:l,line:h}){this.id=e,this.uuid=t,this.tenantUuid=i,this.username=n,this.secret=r,this.type=s,this.host=a,this.options=o,this.endpointSectionOptions=c,this.links=d,this.trunk=l,this.line=h,this.type="SipLine"}}class oi{name;type;configuration;static parse(e){return new oi({name:e.name,configuration:e.configuration})}static parseMany(e){return e.items.map((e=>oi.parse(e)))}static newFrom(e){return Ut(e,oi)}constructor({name:e,configuration:t}={}){this.name=e,this.configuration=t,this.type="ExternalApp"}}class ci{type;guestSipAuthorization;uri;uuid;name;port;extension;persistent;ownerUuids;creationTime;pendingAuthorizations;requireAuthorization;static parse(e){return new ci({guestSipAuthorization:e.guest_sip_authorization,uri:e.ingress_http_uri,name:e.name,ownerUuids:e.owner_uuids,port:e.port,uuid:e.uuid,extension:e.exten,persistent:e.persistent,creationTime:_(e.creation_time).toDate(),requireAuthorization:e.require_authorization})}static parseMany(e){return e?e.map((e=>ci.parse(e))):[]}static newFrom(e){return Ut(e,ci)}constructor({uuid:e,name:t,guestSipAuthorization:i,ownerUuids:n,port:r,uri:s,extension:a,persistent:o,creationTime:c,requireAuthorization:d}={}){this.guestSipAuthorization=i,this.uri=s,this.name=t,this.ownerUuids=n,this.port=r,this.uuid=e,this.extension=a,this.persistent=o,this.creationTime=c,this.requireAuthorization=d,this.type="Meeting"}getGuestSipCredentials(){const[e,t]=Buffer.from(this.guestSipAuthorization,"base64").toString("ascii").split(":");return{username:e,secret:t}}}class di{static PENDING="pending";static ACCEPTED="accepted";static REJECTED="rejected";static POST_PROCESSING="post_processing";static POST_PROCESSED_SUCCESS="post_processed_success";static POST_PROCESSED_ERROR="post_processed_error";meetingUuid;uuid;userUuid;userName;status;constructor({meetingUuid:e,uuid:t,userUuid:i,userName:n}={}){this.meetingUuid=e,this.uuid=t,this.userUuid=i,this.userName=n}setStatus(e){this.status=e}getStatus(){return this.status}static parse(e){const{meeting_uuid:t,uuid:i,guest_uuid:n,guest_name:r}=e;return new di({meetingUuid:t,uuid:i,userUuid:n,userName:r})}static parseMany(e){return e?e.map(di.parse):[]}}const li=e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Input is not an object");return Object.keys(e).reduce(((t,i)=>(t[I(i)]="object"!=typeof e[i]||Array.isArray(e[i])?e[i]:li(e[i]),t)),{})};var hi=(e,t)=>({listUsers:()=>e.get(`${t}/users`,null),getUser:i=>e.get(`${t}/users/${i}`,null).then(Yt.parse),updateUser:(i,n)=>{const r={firstname:n.firstName,lastname:n.lastName,email:n.email,mobile_phone_number:n.mobileNumber};return e.put(`${t}/users/${i}`,r,null,G.successResponseParser)},updateForwardOption:(i,n,r,s)=>{const a=`${t}/users/${i}/forwards/${n}`;return e.put(a,{destination:r,enabled:s},null,G.successResponseParser)},updateDoNotDisturb:(i,n)=>e.put(`${t}/users/${i}/services/dnd`,{enabled:n},null,G.successResponseParser),getUserLineSip:(i,n)=>e.get(`${t}/users/${i}/lines/${n}/associated/endpoints/sip?view=merged`).then(ai.parse),getUserLinesSip(e,t){return Promise.all(t.map((t=>this.getUserLineSip(e,t).catch((()=>null)))))},getUserLineSipFromToken(e){return this.getUser(e).then((t=>{if(!t.lines.length)return console.warn(`No sip line for user: ${e}`),null;const i=t.lines[0];return this.getUserLineSip(e,i.uuid||i.id)}))},listApplications:()=>e.get(`${t}/applications`,null),getInfos:()=>e.get(`${t}/infos`,null),getExternalApps:i=>e.get(`${t}/users/${i}/external/apps`).then(oi.parseMany),getExternalApp:async(i,n)=>{const r=`${t}/users/${i}/external/apps/${n}?view=fallback`;try{return await e.get(r).then(oi.parse)}catch(e){return null}},getMyMeetings:()=>e.get(`${t}/users/me/meetings`).then((e=>ci.parseMany(e.items))),createMyMeeting:i=>e.post(`${t}/users/me/meetings`,li(i)).then(ci.parse),updateMyMeeting:(i,n)=>e.put(`${t}/users/me/meetings/${i}`,li(n),null,G.successResponseParser),deleteMyMeeting:i=>e.delete(`${t}/users/me/meetings/${i}`,null),getMeeting:i=>e.get(`${t}/meetings/${i}`,null).then(ci.parse),meetingAuthorizations:i=>e.get(`${t}/users/me/meetings/${i}/authorizations`,null).then((e=>di.parseMany(e.items))),meetingAuthorizationReject:(i,n)=>e.put(`${t}/users/me/meetings/${i}/authorizations/${n}/reject`,{},null,G.successResponseParser),meetingAuthorizationAccept:(i,n)=>e.put(`${t}/users/me/meetings/${i}/authorizations/${n}/accept`,{},null,G.successResponseParser),guestGetMeeting:i=>e.get(`${t}/guests/me/meetings/${i}`,null).then(ci.parse),guestAuthorizationRequest:(i,n,r)=>e.post(`${t}/guests/${i}/meetings/${n}/authorizations`,{guest_name:r}).then(di.parse),guestAuthorizationCheck:(i,n,r)=>e.get(`${t}/guests/${i}/meetings/${n}/authorizations/${r}`,null),getOutgoingCallerIDs:i=>e.get(`${t}/users/${i}/callerids/outgoing`,null).then(ri.parseMany)});class ui{static MIN_ENGINE_VERSION_REQUIRED;relocatedCall;initiatorCall;recipientCall;static parse(e){return new ui({initiatorCall:e.initiator_call,recipientCall:e.recipient_call,relocatedCall:e.relocated_call})}constructor({relocatedCall:e,initiatorCall:t,recipientCall:i}){this.initiatorCall=t||"",this.relocatedCall=e||"",this.recipientCall=i||""}}ui.MIN_ENGINE_VERSION_REQUIRED="19.09";class pi{type;uuid;content;date;alias;userUuid;roomUuid;read;static parseMany(e){return e&&e.items?e.items.map((e=>pi.parse(e))):[]}static parse(e){return new pi({uuid:e.uuid,date:_(e.created_at).toDate(),content:e.content,alias:e.alias,userUuid:e.user_uuid,read:!0,roomUuid:e.room?e.room.uuid:null})}static newFrom(e){return Ut(e,pi)}constructor({uuid:e,date:t,content:i,userUuid:n,alias:r,roomUuid:s,read:a}={}){this.uuid=e,this.date=t,this.content=i,this.userUuid=n,this.alias=r,this.roomUuid=s,this.read=a,this.type="ChatMessage"}is(e){return this.uuid===e.uuid}isIncoming(e){return this.userUuid!==e}acknowledge(){return this.read=!0,this}}class gi{type;id;date;duration;unread;caller;static parse(e){return new gi({id:e.id,date:_(1e3*e.timestamp).toDate(),duration:1e3*e.duration,caller:{name:e.caller_id_name,number:e.caller_id_num},unread:e.folder?"new"===e.folder.type:null})}static parseMany(e){if(!e)return[];const t=e.folders.filter((e=>"new"===e.type))[0].messages,i=e.folders.filter((e=>"old"===e.type))[0].messages;return[...t.map((e=>gi.parse(e))).map((e=>e.makeAsUnRead())),...i.map((e=>gi.parse(e))).map((e=>e.acknowledge()))]}static newFrom(e){return Ut(e,gi)}constructor({id:e,date:t,duration:i,caller:n,unread:r}){this.id=e,this.date=t,this.duration=i,this.caller=n,this.unread=r,this.type="Voicemail"}is(e){return e&&this.id===e.id}acknowledge(){return this.unread=!1,this}makeAsUnRead(){return this.unread=!0,this}contains(e){return!e||(this.caller.name.toUpperCase().includes(e.toUpperCase())||this.caller.number.includes(e))}}class fi{type;id;sipCallId;callerName;callerNumber;calleeName;calleeNumber;dialedExtension;lineId;isCaller;isVideo;onHold;muted;status;startingTime;talkingToIds;recording;static parseMany(e){return e?e.map((e=>fi.parse(e))):[]}static parse(e){return new fi({id:e.call_id,sipCallId:e.sip_call_id,callerName:e.caller_id_name,callerNumber:e.caller_id_number,calleeName:e.peer_caller_id_name,calleeNumber:e.peer_caller_id_number,dialedExtension:e.dialed_extension,isCaller:e.is_caller,isVideo:e.is_video,muted:e.muted,onHold:e.on_hold,status:e.status,lineId:e.line_id,startingTime:_(e.creation_time).toDate(),talkingToIds:Object.keys(e.talking_to||{}),recording:"active"===e.record_state})}static newFrom(e){return Ut(e,fi)}constructor({id:e,sipCallId:t,callerName:i,callerNumber:n,calleeName:r,calleeNumber:s,dialedExtension:a,isCaller:o,isVideo:c,lineId:d,muted:l,onHold:h,status:u,startingTime:p,talkingToIds:g,recording:f}){this.id=e,this.sipCallId=t,this.callerName=i,this.callerNumber=n,this.calleeName=r,this.calleeNumber=s,this.dialedExtension=a,this.muted=l,this.onHold=h,this.isCaller=o,this.lineId=d,this.status=u,this.startingTime=p,this.talkingToIds=g||[],this.recording=f,this.isVideo=!!c,this.type="Call"}getElapsedTimeInSeconds(){return(Date.now()-+this.startingTime)/1e3}separateCalleeName(){const e=this.calleeName.split(" ");return{firstName:e[0],lastName:e.slice(1).join(" ")}}is(e){return!!e&&this.id===e.id}hasACalleeName(){return this.calleeName.length>0}hasNumber(e){return this.calleeNumber===e}isUp(){return"Up"===this.status}isDown(){return"Down"===this.status}isRinging(){return this.isRingingIncoming()||this.isRingingOutgoing()}isRingingIncoming(){return"Ringing"===this.status}isRingingOutgoing(){return"Ring"===this.status}isFromTransfer(){return"Down"===this.status||"Ringing"===this.status}isOnHold(){return this.onHold}putOnHold(){this.onHold=!0}resume(){this.onHold=!1}isRecording(){return this.recording}}var mi;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(mi=mi||(mi={}));var vi=(e,t)=>{Object.keys(t).forEach((i=>{(!e[i]&&t[i]||void 0!==e[i]&&void 0!==t[i]&&e[i]!==t[i])&&(e[i]=t[i])}))};class yi{call;callId;displayName;realDisplayName;updatedNumber;number;callerNumber;creationTime;startTime;answerTime;endTime;isCaller;answeredBySystem;dialedExtension;ringing;paused;sipCallId;sipStatus;muted;videoMuted;videoRemotelyDowngraded;cameraEnabled;autoAnswer;ignored;screensharing;type;recording;recordingPaused;sipSession;conference;constructor({answered:e,answeredBySystem:t,isCaller:i,displayName:n,callId:r,muted:s,videoMuted:a,number:o,paused:c,ringing:d,startTime:l,creationTime:h,endTime:u,cameraEnabled:p,dialedExtension:g,sipCallId:f,sipStatus:m,callerNumber:v,call:y,autoAnswer:S,ignored:b,screensharing:w,recording:E,recordingPaused:C,videoRemotelyDowngraded:$,sipSession:T,answerTime:_,conference:x}){this.callId=r,this.sipCallId=f,this.displayName=n,this.number=o,this.creationTime=h,this.startTime=l,this.endTime=u,this.isCaller=i,this.answered=e,this.answeredBySystem=t,this.ringing=d,this.paused=c,this.muted=s,this.videoMuted=a,this.callerNumber=v,this.cameraEnabled=p,this.dialedExtension=g||"",this.call=y,this.sipStatus=m,this.autoAnswer=S||!1,this.ignored=b||!1,this.screensharing=w||!1,this.recording=E||!1,this.recordingPaused=C||!1,this.videoRemotelyDowngraded=$,this.sipSession=T,this.answerTime=_||this.answerTime,this.conference=x,this.type="CallSession"}resume(){this.paused=!1}hold(){this.paused=!0}mute(){this.muted=!0}unmute(){this.muted=!1}muteVideo(){this.videoMuted=!0}unmuteVideo(){this.videoMuted=!1}answer(){this.answerTime=new Date}systemAnswer(){this.answeredBySystem=!0}enableCamera(){this.cameraEnabled=!0}disableCamera(){this.cameraEnabled=!1}ignore(){this.ignored=!0}startScreenSharing(){this.screensharing=!0}stopScreenSharing(){this.screensharing=!1}setIsConference(e){this.conference=e}isIncoming(){return!this.isCaller&&!this.answered}isOutgoing(){return this.isCaller&&!this.answered}isActive(){return this.answered||this.isOutgoing()}isAnswered(){return this.answered}isAnsweredBySystem(){return this.answeredBySystem}isRinging(){return this.ringing}isOnHold(){return this.paused}isMuted(){return this.muted}isVideoMuted(){return this.videoMuted}isCameraEnabled(){return this.cameraEnabled}isIgnored(){return this.ignored}isScreenSharing(){return this.screensharing}isRecording(){return this.recording}recordingIsPaused(){return this.recordingPaused}hasAnInitialInterceptionNumber(){return this.number.startsWith("*8")}isAnInterception(){return this.dialedExtension.startsWith("*8")}isEstablished(){return this.sipStatus===mi.Established}isTerminating(){return this.sipStatus===mi.Terminating}isTerminated(){return this.sipStatus===mi.Terminated}isConference(){return this.conference}getElapsedTimeInSeconds(){return this.startTime?(Date.now()-this.startTime)/1e3:0}getId(){return this.sipCallId||this.callId}is(e){return!!e&&(this.isId(e.sipCallId)||this.isId(e.callId))}isId(e){return this.getId()===e||!!this.sipCallId&&this.sipCallId===e||!!this.callId&&this.callId===e}updateFrom(e){vi(this,e)}separateDisplayName(){const e=this.displayName.split(" ");return{firstName:e[0],lastName:e.slice(1).join(" ")}}getTalkingToIds(){return this.call?this.call.talkingToIds:[]}setVideoRemotelyDowngraded(e){this.videoRemotelyDowngraded=e}isVideoRemotelyDowngraded(){return this.videoRemotelyDowngraded}static newFrom(e){return Ut(e,yi)}set answered(e){this.answerTime=e?this.answerTime||new Date:null}get answered(){return!!this.answerTime}toJSON(){const e={...this};return e.answered=this.answered,e}static parseCall(e){return new yi({callId:e.id,sipCallId:e.sipCallId,displayName:e.calleeName||e.calleeNumber,number:e.calleeNumber,callerNumber:e.callerNumber,startTime:+e.startingTime,paused:e.isOnHold(),isCaller:e.isCaller,muted:e.muted,videoMuted:!1,screensharing:!1,recording:e.isRecording(),recordingPaused:!1,ringing:e.isRinging(),answered:e.isUp(),answeredBySystem:e.isUp()&&0===e.talkingToIds.length,cameraEnabled:e.isVideo,dialedExtension:e.dialedExtension,call:e,conference:!1})}}var Si,bi={exports:{}},wi="object"==typeof Reflect?Reflect:null,Ei=wi&&"function"==typeof wi.apply?wi.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};Si=wi&&"function"==typeof wi.ownKeys?wi.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Ci=Number.isNaN||function(e){return e!=e};function $i(){$i.init.call(this)}bi.exports=$i,bi.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}ki(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&ki(e,"error",t,i)}(e,r,{once:!0})}))},$i.EventEmitter=$i,$i.prototype._events=void 0,$i.prototype._eventsCount=0,$i.prototype._maxListeners=void 0;var Ti=10;function _i(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function xi(e){return void 0===e._maxListeners?$i.defaultMaxListeners:e._maxListeners}function Ii(e,t,i,n){var r,s,a,o;if(_i(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=xi(e))>0&&a.length>r&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.length,o=c,console&&console.warn&&console.warn(o)}return e}function Ri(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Ai(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=Ri.bind(n);return r.listener=i,n.wrapFn=r,r}function Pi(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):Ni(r,r.length)}function Di(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function Ni(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function ki(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}Object.defineProperty($i,"defaultMaxListeners",{enumerable:!0,get:function(){return Ti},set:function(e){if("number"!=typeof e||e<0||Ci(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Ti=e}}),$i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},$i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Ci(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},$i.prototype.getMaxListeners=function(){return xi(this)},$i.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var o=r[e];if(void 0===o)return!1;if("function"==typeof o)Ei(o,this,t);else{var c=o.length,d=Ni(o,c);for(i=0;i<c;++i)Ei(d[i],this,t)}return!0},$i.prototype.addListener=function(e,t){return Ii(this,e,t,!1)},$i.prototype.on=$i.prototype.addListener,$i.prototype.prependListener=function(e,t){return Ii(this,e,t,!0)},$i.prototype.once=function(e,t){return _i(t),this.on(e,Ai(this,e,t)),this},$i.prototype.prependOnceListener=function(e,t){return _i(t),this.prependListener(e,Ai(this,e,t)),this},$i.prototype.removeListener=function(e,t){var i,n,r,s,a;if(_i(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},$i.prototype.off=$i.prototype.removeListener,$i.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},$i.prototype.listeners=function(e){return Pi(this,e,!0)},$i.prototype.rawListeners=function(e){return Pi(this,e,!1)},$i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Di.call(e,t)},$i.prototype.listenerCount=Di,$i.prototype.eventNames=function(){return this._eventsCount>0?Si(this._events):[]};var Oi=C(bi.exports);class Fi{eventEmitter;constructor(){this.eventEmitter=new Oi}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.removeListener(e,t)}unbind(){this.eventEmitter.removeAllListeners()}}class Mi{static async fetchCallLogs(e,t){return pn().callLogd.listCallLogs(e,t)}static async fetchDistinctCallLogs(e,t,i="peer_exten"){return pn().callLogd.listDistinctCallLogs(e,t,i)}static async fetchActiveCalls(){return pn().calld.listCalls()}static async fetchCallLogsFromDate(e,t){return pn().callLogd.listCallLogsFromDate(e,t)}static async search(e,t){return pn().callLogd.search(e,t)}static async searchBy(e,t,i){return pn().callLogd.searchBy(e,t,i)}static async fetchSIP(e,t){const i=t||e.primaryLine();return pn().confd.getUserLineSip(e.uuid,i?i.id:"")}static async cancelCall(e){return pn().calld.cancelCall(e.callId)}static async makeCall(e,t,i=!1,n=!1){const r=e?e.id:null,s=await pn().calld.makeCall(t,i,r,n);return fi.parse(s)}static async relocateCall(e,t,i){return pn().calld.relocateCall(e,"line",t,i)}static async hold(e){return pn().calld.hold(e)}static async resume(e){return pn().calld.resume(e)}static async mute(e){return pn().calld.mute(e)}static async sendDTMF(e,t){return pn().calld.sendDTMF(e,t)}static async unmute(e){return pn().calld.unmute(e)}static async transferCall(e,t,i){return pn().calld.transferCall(e,t,i)}static async cancelCallTransfer(e){return pn().calld.cancelCallTransfer(e)}static async confirmCallTransfer(e){return pn().calld.confirmCallTransfer(e)}}const Hi="blind",Li=B?B.loggerFor("cti-phone"):console;class ji extends Fi{session;isMobile;callbackAllLines;currentCall;client=null;constructor(e,t=!1,i=!1){super(),Li.info("CTI Phone created"),this.session=e,this.isMobile=t,this.callbackAllLines=i}getOptions(){return{accept:!1,decline:!0,mute:!0,hold:!1,transfer:!0,sendKey:!0,addParticipant:!1,record:!0,merge:!1}}hasAnActiveCall(){return!!this.currentCall}callCount(){return this.currentCall?1:0}isWebRTC(){return!1}getUserAgent(){return"cti-phone"}startHeartbeat(){}setOnHeartbeatTimeout(){}setOnHeartbeatCallback(){}stopHeartbeat(){}bindClientEvents(){}onConnect(){return Promise.resolve()}onDisconnect(){}async makeCall(e,t){if(Li.info("make CTI call",{number:e}),!e)return null;try{this.currentCall=await Mi.makeCall(t,e,this.isMobile,this.callbackAllLines)}catch(e){}if(!this.currentCall)return null;const i=yi.parseCall(this.currentCall);return this.eventEmitter.emit("onCallOutgoing",i),i}accept(e){return e?(Li.info("accept CTI call",{callId:e.getId(),number:e.number}),this.currentCall||(this.currentCall=e.call),Promise.resolve(e.getId())):Promise.resolve(null)}endCurrentCall(e){e&&(Li.info("end current CTI call",{callId:e.getId(),number:e.number}),this.currentCall=void 0,this.eventEmitter.emit("onCallEnded",e))}async hangup(e){if(!e)return Promise.resolve(!1);Li.info("hangup CTI call",{callId:e.getId(),number:e.number});try{return await Mi.cancelCall(e),this.currentCall&&e.callId===this.currentCall.id&&this.endCurrentCall(e),this.eventEmitter.emit("onCallEnded",e),!0}catch(t){return Li.error("hangup CTI call, error",t),this.eventEmitter.emit("onCallFailed",e),!1}}ignore(){}async reject(e){e&&(Li.info("reject CTI call",{callId:e.getId(),number:e.number}),await Mi.cancelCall(e),this.eventEmitter.emit("onCallEnded",e))}async transfer(e,t){e&&(Li.info("transfer CTI call",{callId:e.getId(),number:e.number,to:t}),await Mi.transferCall(e.callId,t,Hi))}indirectTransfer(){return Promise.resolve(!1)}async initiateCTIIndirectTransfer(e,t){return e?(Li.info("indirect CTI transfer",{callId:e.getId(),number:e.number,to:t}),Mi.transferCall(e.callId,t,"attended")):Promise.resolve(null)}async cancelCTIIndirectTransfer(e){return Li.info("cancel CTI transfer",{transferId:e}),Mi.cancelCallTransfer(e)}async confirmCTIIndirectTransfer(e){return Li.info("confirm CTI transfer",{transferId:e}),Mi.confirmCallTransfer(e)}sendKey(e,t){e&&(Li.info("send CTI key",{callId:e.getId(),number:e.number,digits:t}),Mi.sendDTMF(e.callId,t))}onConnectionMade(){Li.info("on CTI connection made"),this.eventEmitter.emit("onCallAccepted")}async close(){return Li.info("CTI close"),Promise.resolve()}async hold(e){return!!e&&(Li.info("CTI hold",{callId:e.getId(),number:e.number}),Mi.hold(e.callId))}async resume(e){return!!e&&(Li.info("CTI resume",{callId:e.getId(),number:e.number}),Mi.resume(e.callId))}async mute(e){e&&(Li.info("CTI mute",{callId:e.getId(),number:e.number}),await Mi.mute(e.callId))}async unmute(e){e&&(Li.info("CTI unmute",{callId:e.getId(),number:e.number}),await Mi.unmute(e.callId))}putOnSpeaker(){}putOffSpeaker(){}turnCameraOff(){}turnCameraOn(){}changeAudioInputDevice(){return Promise.resolve(null)}changeVideoInputDevice(){return Promise.resolve(null)}changeAudioDevice(){return Promise.resolve()}changeRingDevice(){}changeAudioVolume(){}changeRingVolume(){}hasVideo(){return!1}hasAVideoTrack(){return!1}getLocalStreamForCall(){return null}getRemoteStreamForCall(){return null}getLocalVideoStream(){return null}setActiveSipSession(){}isRegistered(){return!0}hasIncomingCallSession(){return!0}hasActiveRemoteVideoStream(){return!1}getCurrentCallSession(){return this.currentCall?yi.parseCall(this.currentCall):null}enableRinging(){}sendMessage(){}disableRinging(){}getLocalStream(){return null}getRemoteStream(){return null}getRemoteVideoStream(){return null}getRemoteAudioStream(){return null}hasLocalVideo(){return!1}useLocalVideoElement(){}setMediaConstraints(){}register(){return Promise.resolve(null)}}var Bi={},Ui={};Object.defineProperty(Ui,"__esModule",{value:!0}),Ui.EnumType=void 0;var Vi=function(e){this.value=e};Ui.EnumType=Vi;var qi={};Object.defineProperty(qi,"__esModule",{value:!0}),qi.VariableType=void 0;var Gi=function(){function e(e){this.value=e}return e.prototype.toJSON=function(){return"$".concat(this.value)},e}();qi.VariableType=Gi,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.jsonToGraphQLQuery=e.configFields=void 0;var t=Ui,i=qi;function n(e){if(e instanceof t.EnumType)return e.value;if(e instanceof i.VariableType)return"$".concat(e.value);if("object"!=typeof e||null===e)return JSON.stringify(e);if(Array.isArray(e))return"[".concat(e.map((function(e){return n(e)})).join(", "),"]");var r=Object.keys(e).map((function(t){return"".concat(t,": ").concat(n(e[t]))})).join(", ");return"{".concat(r,"}")}function r(t,i){return-1==e.configFields.indexOf(t)&&-1==i.indexOf(t)}function s(e,t,i,a){Object.keys(e).filter((function(e){return r(e,a.ignoreFields)})).forEach((function(o){var c=e[o];if("object"==typeof c){if(Array.isArray(c)&&!(c=c.find((function(e){return e&&"object"==typeof e}))))return void i.push(["".concat(o),t]);if(c&&0===Object.keys(c).filter((function(e){return!1!==c[e]||a.includeFalsyKeys})).length)return;var d=Object.keys(c).filter((function(e){return r(e,a.ignoreFields)})).length>0,l="object"==typeof c.__args&&Object.keys(c.__args).length>0,h="object"==typeof c.__directives,u=c.__all_on instanceof Array,p="object"==typeof c.__on,g="".concat(o);if("string"==typeof c.__name&&(g="".concat(g," ").concat(c.__name)),"string"==typeof c.__aliasFor&&(g="".concat(g,": ").concat(c.__aliasFor)),"object"==typeof c.__variables&&Object.keys(c.__variables).length>0)g="".concat(g," (").concat(function(e){var t=[];for(var i in e)t.push("$".concat(i,": ").concat(e[i]));return t.join(", ")}(c.__variables),")");else if(l||h){var f="",m="";h&&(m=Object.entries(c.__directives).map((function(e){var t;return"@".concat(function(e){var t=Object.keys(e)[0],i=e[t];if("boolean"==typeof i||"object"==typeof i&&0===Object.keys(i).length)return t;if("object"==typeof i){var r=[];for(var s in i){var a=n(i[s]).replace(/"/g,"");r.push("".concat(s,": ").concat(a))}return"".concat(t,"(").concat(r.join(", "),")")}throw new Error("Unsupported type for directive: ".concat(typeof i,". Types allowed: object, boolean.\n")+"Offending object: ".concat(JSON.stringify(e)))}(((t={})[e[0]]=e[1],t)))})).join(" ")),l&&(f="(".concat(function(e){var t=[];for(var i in e)t.push("".concat(i,": ").concat(n(e[i])));return t.join(", ")}(c.__args),")"));var v=h&&l?" ":"";g="".concat(g," ").concat(f).concat(v).concat(m)}if(i.push([g+(d||p||u?" {":""),t]),s(c,t+1,i,a),u&&c.__all_on.forEach((function(e){i.push(["...".concat(e),t+1])})),p)(c.__on instanceof Array?c.__on:[c.__on]).forEach((function(e){var n=e.__typeName;i.push(["... on ".concat(n," {"),t+1]),s(e,t+2,i,a),i.push(["}",t+1])}));(d||p||u)&&i.push(["}",t])}else(!0===a.includeFalsyKeys||c)&&i.push(["".concat(o),t])}))}e.configFields=["__args","__alias","__aliasFor","__variables","__directives","__on","__all_on","__typeName","__name"],e.jsonToGraphQLQuery=function(e,t){if(void 0===t&&(t={}),!e||"object"!=typeof e)throw new Error("query object not specified");if(0==Object.keys(e).length)throw new Error("query object has no data");t.ignoreFields instanceof Array||(t.ignoreFields=[]);var i=[];s(e,0,i,t);var n="";return i.forEach((function(e){var i=e[0],r=e[1];t.pretty?(n&&(n+="\n"),n+=function(e){return Array(4*e+1).join(" ")}(r)+i):(n&&(n+=" "),n+=i)})),n}}(Bi);const Ki=e=>({email:e.email,firstname:e.firstName?e.firstName:"",lastname:e.lastName?e.lastName:"",number:e.phoneNumber?e.phoneNumber:"",entreprise:e.entreprise?e.entreprise:"",birthday:e.birthday?e.birthday:"",address:e.address?e.address:"",note:e.note?e.note:""});class Wi{deleted;end;fileName;start;uuid;static parseMany(e=[]){return e?e.map((e=>Wi.parse(e))):[]}static parse(e){return new Wi({deleted:e.deleted,fileName:e.filename,end:e.end_time?_(e.end_time).toDate():null,start:_(e.start_time).toDate(),uuid:e.uuid})}constructor({deleted:e,end:t,fileName:i,start:n,uuid:r}){this.deleted=e,this.end=t,this.fileName=i,this.start=n,this.uuid=r}}class zi{type;answer;answered;newMissedCall;callDirection;destination;recordings;source;id;duration;start;end;static merge(e,t){const i=e.concat(t);return i.map((e=>e.id)).filter(((e,t,i)=>i.indexOf(e)===t)).map((e=>i.find((t=>t&&t.id===e))))}static parseMany(e){return e&&e.items?e.items.map((e=>zi.parse(e))):[]}static parse(e){return new zi({answer:e.answer?_(e.answer).toDate():null,answered:e.answered,callDirection:e.call_direction,destination:{extension:e.requested_extension||e.destination_extension||`meeting-${e.requested_name||e.destination_name||""}`,name:e.requested_name||e.destination_name||"",uuid:e.destination_user_uuid},source:{extension:e.source_extension,name:e.source_name,uuid:e.source_user_uuid},id:e.id,duration:1e3*(e.duration||0),start:_(e.start).toDate(),end:e.end?_(e.end).toDate():null,recordings:Wi.parseMany(e.recordings||[])})}static parseNew(e,t){const i=zi.parse(e);return i.newMissedCall=t&&t.hasExtension(e.requested_extension||e.destination_extension)&&!e.answered,i}static newFrom(e){return Ut(e,zi)}constructor({answer:e,answered:t,callDirection:i,destination:n,source:r,id:s,duration:a,start:o,end:c,recordings:d}){this.answer=e,this.answered=t,this.callDirection=i,this.destination=n,this.source=r,this.id=s,this.duration=a,this.start=o,this.end=c,this.recordings=d||[],this.type="CallLog"}isFromSameParty(e,t){return this.theOtherParty(t).extension===e.theOtherParty(t).extension}theOtherParty(e){return"inbound"===this.callDirection?this.source:"outbound"===this.callDirection||e&&e.hasExtension(this.source.extension)?this.destination:this.source}isNewMissedCall(){return this.newMissedCall}acknowledgeCall(){return this.newMissedCall=!1,this}isAcknowledged(){return this.newMissedCall}isAnswered(){return this.answered}isOutgoing(e){return"internal"===this.callDirection?e.hasExtension(this.source.extension):"outbound"===this.callDirection}isIncoming(e){return"internal"===this.callDirection?e.hasExtension(this.destination.extension):"inbound"===this.callDirection}isAnOutgoingCall(e){return console.warn("@wazo/sdk \n CallLog.isAnOutgoingcall(session) method is obsolete.\n Please use CallLog.isOutgoing(session).\n "),e.hasExtension(this.source.extension)&&this.answered}isAMissedOutgoingCall(e){return e.hasExtension(this.source.extension)&&!this.answered}isAnIncomingCall(e){return console.warn("@wazo/sdk\n CallLog.isAnIncomingCall(session) method is obsolete.\n Please use CallLog.isIncoming(session).\n "),e.hasExtension(this.destination.extension)&&this.answered}isADeclinedCall(e){return!this.answered&&e.hasExtension(this.destination.extension)}getRecordings(){return this.recordings}}class Yi{type;uuid;name;users;static parseMany(e){return e&&e.items?e.items.map((e=>Yi.parse(e))):[]}static parse(e){return new Yi({uuid:e.uuid,name:e.name,users:e.users})}static newFrom(e){return Ut(e,Yi)}constructor({uuid:e,name:t,users:i}={}){this.uuid=e,this.name=t,this.users=i,this.type="ChatRoom"}}var Ji=(e,t)=>({updateState:(i,n)=>e.put(`${t}/users/${i}/presences`,{state:n},null,G.successResponseParser),updateStatus:(i,n,r)=>{const s={state:n,status:r};return e.put(`${t}/users/${i}/presences`,s,null,G.successResponseParser)},getState:async i=>e.get(`${t}/users/${i}/presences`).then((e=>e.state)),getContactStatusInfo:async i=>e.get(`${t}/users/${i}/presences`).then((e=>e)),getLineState:async i=>e.get(`${t}/users/${i}/presences`).then((e=>Yt.getLinesState(e.lines))),async getMultipleLineState(i){const n={},r=i||[];if(r.length>30){const e=r.reduce(((e,t,i)=>(i%30==0&&e.push(this.getMultipleLineState(r.slice(i,i+30))),e)),[]);return(await Promise.all(e)).flat()}return r.length&&(n.user_uuid=r.join(",")),e.get(`${t}/users/presences`,n).then((e=>e.items))},getUserRooms:async()=>e.get(`${t}/users/me/rooms`).then(Yi.parseMany),createRoom:async(i,n)=>e.post(`${t}/users/me/rooms`,{name:i,users:n}).then(Yi.parse),getRoomMessages:async(i,n)=>{const r=G.getQueryString(n||{});return e.get(`${t}/users/me/rooms/${i}/messages${r.length?`?${r}`:""}`).then((e=>pi.parseMany(e)))},sendRoomMessage:async(i,n)=>e.post(`${t}/users/me/rooms/${i}/messages`,n).then(pi.parse),getMessages:async i=>e.get(`${t}/users/me/rooms/messages`,i)});class Zi{status;id;sourceId;destinationId;constructor({sourceId:e,destinationId:t,status:i,id:n}){this.sourceId=e,this.destinationId=t,this.status=i,this.id=n}static parseFromCallSession(e,t){return new Zi({sourceId:e.getId(),destinationId:t.getId()})}static parseFromApi(e){return new Zi({id:e.id,status:e.status,sourceId:e.initiator_call,destinationId:e.recipient_call})}destinationIs(e){return e.isId(this.destinationId)}sourceIs(e){return e.isId(this.sourceId)}updateFrom(e){vi(this,e)}static newFrom(e){return Ut(e,Zi)}}class Xi{type;full;constructor({full:e}={}){this.full=e,this.type="MeetingStatus"}static parse(e){return new Xi({full:e.full})}}class Qi{context;extension;id;logged;number;paused;pausedReason;static parse(e){return new Qi({context:e.context,extension:e.extension,id:e.id,logged:e.logged,number:e.number,paused:e.paused,pausedReason:e.paused_reason})}constructor({context:e,extension:t,id:i,logged:n,number:r,paused:s,pausedReason:a}){this.context=e,this.extension=t,this.id=i,this.logged=n,this.number=r,this.paused=s,this.pausedReason=a}}class en{name;events;config;uuid;service;eventsUserUuid;eventsWazoUuid;metadata;ownerTenantUuid;ownerUserUuid;static parse(e){return new en({name:e.name,events:e.events,config:e.config,uuid:e.uuid,service:e.service,eventsUserUuid:e.events_user_uuid,eventsWazoUuid:e.events_wazo_uuid,metadata:e.metadata,ownerTenantUuid:e.owner_tenant_uuid,ownerUserUuid:e.owner_user_uuid})}static parseMany(e){return e.items.map((e=>en.parse(e)))}constructor({name:e,events:t,config:i,uuid:n,service:r,eventsUserUuid:s,eventsWazoUuid:a,metadata:o,ownerTenantUuid:c,ownerUserUuid:d}){this.name=e,this.events=t,this.config=i,this.uuid=n,this.service=r,this.eventsUserUuid=s,this.eventsWazoUuid=a,this.metadata=o,this.ownerTenantUuid=c,this.ownerUserUuid=d}}const tn=B?B.loggerFor("api"):console;class nn{client;auth;application;confd;ctidNg;dird;callLogd;chatd;calld;agentd;webhookd;amid;refreshToken;onRefreshToken;onRefreshTokenError;refreshExpiration;refreshBackend;refreshTenantId;refreshDomainName;isMobile;fetchOptions;constructor({server:e,agent:t=null,refreshToken:i,clientId:n,isMobile:r=!1,fetchOptions:s}){this.updateParameters({server:e,agent:t,clientId:n,fetchOptions:s}),this.refreshToken=i,this.isMobile=r||!1}initializeEndpoints(){var e,t;this.auth=(e=this.client,t="auth/0.1",{checkToken:i=>e.head(`${t}/token/${i}`,null,{}),authenticate:i=>e.get(`${t}/token/${i}`,null,{}).then((e=>ti.parse(e))),logIn(i){const n={backend:i.backend||ii,expiration:i.expiration||ni},r={Authorization:`Basic ${G.base64Encode(`${i.username}:${i.password}`)}`,"Content-Type":"application/json"};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),i.mobile&&(r["Wazo-Session-Type"]="mobile"),i.tenantId&&(console.warn("Use of `tenantId` is deprecated when calling logIn() method, use `domainName` instead."),n.tenant_id=i.tenantId),i.domainName&&(n.domain_name=i.domainName),e.post(`${t}/token`,n,r).then((e=>ti.parse(e)))},logOut:i=>e.delete(`${t}/token/${i}`,null,{},G.successResponseParser),samlLogIn:async i=>{const n={saml_session_id:i};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),e.post(`${t}/token`,n).then(ti.parse)},initiateIdpAuthentication:async(i,n)=>{const r={domain:i,redirect_url:n};return e.post(`${t}/saml/sso`,r,{Accept:"application/json","Content-Type":"application/json"})},refreshToken:(i,n,r,s,a,o)=>{const c={backend:n||ii,expiration:r||ni,refresh_token:i,client_id:e.clientId};a&&(console.warn("Use of `tenantId` is deprecated when calling refreshToken() method, use `domainName` instead."),c.tenant_id=a),o&&(c.domain_name=o);const d={"Content-Type":"application/json",...s?{"Wazo-Session-Type":"mobile"}:{}};return e.post(`${t}/token`,c,d,G.defaultParser,!1).then(ti.parse)},deleteRefreshToken:i=>e.delete(`${t}/users/me/tokens/${i}`,null,null,G.successResponseParser),updatePassword:(i,n,r)=>{const s={new_password:r,old_password:n};return e.put(`${t}/users/${i}/password`,s,null,G.successResponseParser)},sendDeviceToken:(i,n,r,s)=>{const a={token:n};return r&&(a.apns_token=r,a.apns_voip_token=r),s&&(a.apns_notification_token=s),e.post(`${t}/users/${i}/external/mobile`,a)},getPushNotificationSenderId:i=>e.get(`${t}/users/${i}/external/mobile/sender_id`,null).then((e=>e.sender_id)),sendResetPasswordEmail:({username:i,email:n})=>{const r={};return i&&(r.username=i),n&&(r.email=n),e.get(`${t}/users/password/reset`,r,{},G.successResponseParser)},resetPassword:(i,n)=>{const r={password:n};return e.post(`${t}/users/password/reset?user_uuid=${i}`,r,null,G.successResponseParser)},removeDeviceToken:i=>e.delete(`${t}/users/${i}/external/mobile`),createUser:(i,n,r,s)=>{const a={username:i,password:n,firstname:r,lastname:s};return e.post(`${t}/users`,a)},addUserEmail:(i,n,r)=>{const s={emails:[{address:n,main:r}]};return e.put(`${t}/users/${i}/emails`,s)},addUserPolicy:(i,n)=>e.put(`${t}/users/${i}/policies/${n}`),getRestrictionPolicies:i=>e.post(`${t}/token/${e.token}/scopes/check`,{scopes:i}),deleteUserPolicy:(i,n)=>e.delete(`${t}/users/${i}/policies/${n}`),addUserGroup:(i,n)=>e.put(`${t}/groups/${n}/users/${i}`),listUsersGroup:i=>e.get(`${t}/groups/${i}/users`),deleteUserGroup:(i,n)=>e.delete(`${t}/groups/${n}/users/${i}`),getUser:i=>e.get(`${t}/users/${i}`),getUserSession:i=>e.get(`${t}/users/${i}/sessions`),deleteUserSession:(i,n)=>e.delete(`${t}/users/${i}/sessions/${n}`),listUsers:()=>e.get(`${t}/users`),deleteUser:i=>e.delete(`${t}/users/${i}`),listTenants:()=>e.get(`${t}/tenants`),getTenant:i=>e.get(`${t}/tenants/${i}`),createTenant:i=>e.post(`${t}/tenants`,{name:i}),updateTenant:(i,n,r,s,a)=>{const o={name:n,contact:r,phone:s,address:a};return e.put(`${t}/tenants/${i}`,o)},deleteTenant:i=>e.delete(`${t}/tenants/${i}`),createGroup:i=>e.post(`${t}/groups`,{name:i}),listGroups:()=>e.get(`${t}/groups`),deleteGroup:i=>e.delete(`${t}/groups/${i}`),createPolicy:(i,n,r)=>{const s={name:i,description:n,acl_templates:r,acl:r};return e.post(`${t}/policies`,s)},listPolicies:()=>e.get(`${t}/policies`),deletePolicy:i=>e.delete(`${t}/policies/${i}`),getProviders:i=>e.get(`${t}/users/${i}/external`),getProviderToken:(i,n)=>e.get(`${t}/users/${i}/external/${n}`),getProviderAuthUrl:(i,n)=>e.post(`${t}/users/${i}/external/${n}`,{}),deleteProviderToken:(i,n)=>e.delete(`${t}/users/${i}/external/${n}`)}),this.application=((e,t)=>({bridgeCall(i,n,r,s,a,o){const c=`${t}/${i}/nodes`,d={calls:[{id:n}]};return e.post(c,d,null,(e=>e.json().then((e=>e.uuid)))).then((t=>e.post(`${c}/${t}/calls`,{context:r,exten:s,autoanswer:a,displayed_caller_id_number:o}).then((e=>({nodeUuid:t,data:e})))))},answerCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/answer`,{},null,G.successResponseParser),calls:i=>e.get(`${t}/${i}/calls`),hangupCall:(i,n)=>e.delete(`${t}/${i}/calls/${n}`),startPlaybackCall:(i,n,r,s)=>e.post(`${t}/${i}/calls/${n}/playbacks`,{language:r,uri:s}),stopPlaybackCall:(i,n)=>e.delete(`${t}/${i}/playbacks/${n}`),startProgressCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/progress/start`,{},null,G.successResponseParser),stopProgressCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/progress/stop`,{},null,G.successResponseParser),startMohCall:(i,n,r)=>e.put(`${t}/${i}/calls/${n}/moh/${r}/start`,{},null,G.successResponseParser),stopMohCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/moh/stop`,{},null,G.successResponseParser),startHoldCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/hold/start`,{},null,G.successResponseParser),stopHoldCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/hold/stop`,{},null,G.successResponseParser),startMuteCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/mute/start`,{},null,G.successResponseParser),stopMuteCall:(i,n)=>e.put(`${t}/${i}/calls/${n}/mute/stop`,{},null,G.successResponseParser),sendDTMFCall:(i,n,r)=>e.put(`${t}/${i}/calls/${n}/dtmf`,{digits:r},null,G.successResponseParser),addCallNodes:(i,n,r)=>e.put(`${t}/${i}/nodes/${n}/calls/${r}`,{},null,G.successResponseParser),createNewNodeWithCall:(i,n)=>e.post(`${t}/${i}/nodes`,{calls:n}),addNewCallNodes:(i,n,r,s,a)=>e.post(`${t}/${i}/nodes/${n}/calls`,{context:r,exten:s,autoanswer:a}),listCallsNodes:(i,n)=>e.get(`${t}/${i}/nodes/${n}`),listNodes:i=>e.get(`${t}/${i}/nodes`),removeNode:(i,n)=>e.delete(`${t}/${i}/nodes/${n}`),removeCallNodes:(i,n,r)=>e.delete(`${t}/${i}/nodes/${n}/calls/${r}`),listSnoop:i=>e.get(`${t}/${i}/snoops`),removeSnoop:(i,n)=>e.delete(`${t}/${i}/snoops/${n}`),viewSnoop:(i,n)=>e.get(`${t}/${i}/snoops/${n}`),createSnoop:(i,n,r,s)=>e.post(`${t}/${i}/calls/${n}/snoops`,{snooping_call_id:r,whisper_mode:s}),updateSnoop:(i,n,r)=>e.put(`${t}/${i}/snoops/${n}`,{whisper_mode:r},null,G.successResponseParser)}))(this.client,"calld/1.0/applications"),this.confd=hi(this.client,"confd/1.1"),this.ctidNg=((e,t)=>({updatePresence:i=>e.put(`${t}/users/me/presences`,{presence:i},null,G.successResponseParser),listMessages:(i,n)=>{const r={};return i&&(r.participant_user_uuid=i),n&&(r.limit=n),e.get(`${t}/users/me/chats`,r).then(pi.parseMany)},sendMessage:(i,n,r)=>{const s={alias:i,msg:n,to:r};return e.post(`${t}/users/me/chats`,s,null,G.successResponseParser)},makeCall:(i,n,r,s=!1)=>{const a={from_mobile:n,extension:i};return r&&(a.line_id=r),s&&(a.all_lines=!0),e.post(`${t}/users/me/calls`,a)},cancelCall:i=>e.delete(`${t}/users/me/calls/${i}`),listCalls:()=>e.get(`${t}/users/me/calls`).then((e=>fi.parseMany(e.items))),relocateCall(i,n,r,s){const a={completions:["answer"],destination:n,initiator_call:i,auto_answer:!0};return(r||s)&&(a.location={}),r&&(a.location.line_id=r),s&&(a.location.contact=s),e.post(`${t}/users/me/relocates`,a).then(ui.parse)},transferCall(i,n,r=Hi){const s={exten:n,flow:r,initiator_call:i};return e.post(`${t}/users/me/transfers`,s)},cancelCallTransfer:i=>e.delete(`${t}/users/me/transfers/${i}`),confirmCallTransfer:i=>e.put(`${t}/users/me/transfers/${i}/complete`),listVoicemails:()=>e.get(`${t}/users/me/voicemails`,null).then((e=>gi.parseMany(e))),deleteVoicemail:i=>e.delete(`${t}/users/me/voicemails/messages/${i}`,null),getPresence:i=>e.get(`${t}/users/${i}/presences`,null),getStatus:i=>e.get(`${t}/lines/${i}/presences`,null),fetchSwitchboardHeldCalls:i=>e.get(`${t}/switchboards/${i}/calls/held`,null),holdSwitchboardCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}`,null,null,G.successResponseParser),answerSwitchboardHeldCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}/answer`,null),fetchSwitchboardQueuedCalls:i=>e.get(`${t}/switchboards/${i}/calls/queued`,null),answerSwitchboardQueuedCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/queued/${n}/answer`,null),sendFax:(i,n,r=null)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},a=G.getQueryString({extension:i,caller_id:r});return e.post(`${t}/users/me/faxes?${a}`,n,s)}}))(this.client,"ctid-ng/1.0"),this.dird=((e,t)=>({search:(i,n,r=0,s=null)=>e.get(`${t}/directories/lookup/${i}`,{term:n}).then((e=>Xt.parseMany(e,r,s))),listPersonalContacts:i=>e.get(`${t}/personal`,i).then((e=>Xt.parseManyPersonal(e.items))),fetchPersonalContact:i=>e.get(`${t}/personal/${i}`).then(Xt.parsePersonal),addContact:i=>e.post(`${t}/personal`,Ki(i)).then(Xt.parsePersonal),editContact:i=>e.put(`${t}/personal/${i.sourceId||i.id||""}`,Ki(i)).then(Xt.parsePersonal),importContacts:async i=>{const n={"Content-Type":"text/csv; charset=utf-8","X-Auth-Token":e.token};return e.post(`${t}/personal/import`,i,n).then((e=>Xt.parseManyPersonal(e.created)))},deleteContact:i=>e.delete(`${t}/personal/${i}`),listFavorites:i=>e.get(`${t}/directories/favorites/${i}`).then(Xt.parseMany),markAsFavorite:(i,n)=>{const r=`${t}/directories/favorites/${i}/${n}`;return e.put(r,null,null,G.successResponseParser)},removeFavorite:(i,n)=>e.delete(`${t}/directories/favorites/${i}/${n}`),fetchOffice365Source:i=>e.get(`${t}/directories/${i}/sources`,{backend:"office365"}),fetchOffice365Contacts:async(i,n)=>i?e.get(`${t}/backends/office365/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyOffice365(e.items,i))):Promise.resolve([]),fetchWazoSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"wazo"}),fetchWazoContacts:async(i,n)=>i?e.get(`${t}/backends/wazo/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyWazo(e.items,i))):Promise.resolve([]),fetchGoogleSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"google"}),fetchGoogleContacts:async(i,n)=>i?e.get(`${t}/backends/google/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyGoogle(e.items,i))):Promise.resolve([]),fetchConferenceSource:i=>e.get(`${t}/directories/${i}/sources`,{backend:"conference"}),fetchSourcesFor:(i,n)=>e.get(`${t}/directories/${i}/sources`,{backend:n}),fetchPhonebookContacts:async(i,n)=>i?e.get(`${t}/backends/phonebook/sources/${i.uuid}/contacts`,n):Promise.resolve({items:[],total:0}),fetchConferenceContacts:async(i,n)=>i?e.get(`${t}/backends/conference/sources/${i.uuid}/contacts`,n).then((e=>Xt.parseManyConference(e.items,i))):Promise.resolve([]),findMultipleContactsByNumber:(i,n)=>{const r=Bi.jsonToGraphQLQuery({me:{contacts:{__args:{profile:"default",extens:i},edges:{node:n||{firstname:!0,lastname:!0,wazoReverse:!0,wazoBackend:!0,email:!0,wazoSourceEntryId:!0,wazoSourceName:!0,"... on WazoContact":{userUuid:!0}}}}}});return e.post(`${t}/graphql`,{query:`{${r}}`}).then(Xt.manyGraphQlWithNumbersParser(i))}}))(this.client,"dird/0.1"),this.callLogd=((e,t)=>({search:(i,n=5)=>e.get(`${t}/users/me/cdr`,{search:i,limit:n}).then(zi.parseMany),searchBy:(i,n,r=5)=>e.get(`${t}/users/me/cdr`,{[i]:n,limit:r}).then(zi.parseMany),listCallLogs:(i,n=5)=>e.get(`${t}/users/me/cdr`,{offset:i,limit:n}).then(zi.parseMany),listDistinctCallLogs:(i,n=5,r=void 0)=>e.get(`${t}/users/me/cdr`,{offset:i,limit:n,distinct:r}).then(zi.parseMany),listCallLogsFromDate:(i,n)=>e.get(`${t}/users/me/cdr`,{from:i.toISOString(),number:n}).then(zi.parseMany)}))(this.client,"call-logd/1.0"),this.chatd=Ji(this.client,"chatd/1.0"),this.calld=((e,t)=>({updatePresence:i=>e.put(`${t}/users/me/presences`,{presence:i},null,G.successResponseParser),listMessages:(i,n)=>{const r={};return i&&(r.participant_user_uuid=i),n&&(r.limit=n),e.get(`${t}/users/me/chats`,r).then((e=>pi.parseMany(e)))},sendMessage:(i,n,r)=>{const s={alias:i,msg:n,to:r};return e.post(`${t}/users/me/chats`,s,null,G.successResponseParser)},makeCall:(i,n,r,s=!1)=>{const a={from_mobile:n,extension:i};return r&&(a.line_id=r),s&&(a.all_lines=!0),e.post(`${t}/users/me/calls`,a)},cancelCall:i=>e.delete(`${t}/users/me/calls/${i}`,null),listCalls:()=>e.get(`${t}/users/me/calls`,null).then((e=>fi.parseMany(e.items))),relocateCall(i,n,r,s){const a={completions:["answer"],destination:n,initiator_call:i,auto_answer:!0};return(r||s)&&(a.location={}),r&&(a.location.line_id=r),s&&(a.location.contact=s),e.post(`${t}/users/me/relocates`,a).then((e=>ui.parse(e)))},listVoicemails:()=>e.get(`${t}/users/me/voicemails`).then((e=>gi.parseMany(e))),deleteVoicemail:i=>e.delete(`${t}/users/me/voicemails/messages/${i}`),getVoicemailUrl:i=>{const n={token:e.token};return e.computeUrl("get",`${t}/users/me/voicemails/messages/${i.id}/recording`,n)},fetchSwitchboardHeldCalls:i=>e.get(`${t}/switchboards/${i}/calls/held`),holdSwitchboardCall:(i,n)=>e.put(`${t}/switchboards/${i}/calls/held/${n}`,null,null,G.successResponseParser),answerSwitchboardHeldCall:(i,n,r=null)=>e.put(`${t}/switchboards/${i}/calls/held/${n}/answer${r?`?line_id=${r}`:""}`),fetchSwitchboardQueuedCalls:i=>e.get(`${t}/switchboards/${i}/calls/queued`),answerSwitchboardQueuedCall:(i,n,r=null)=>e.put(`${t}/switchboards/${i}/calls/queued/${n}/answer${r?`?line_id=${r}`:""}`),sendFax:(i,n,r)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},a=G.getQueryString({extension:i,caller_id:r});return e.post(`${t}/users/me/faxes?${a}`,n,s)},getConferenceParticipantsAsUser:async i=>e.get(`${t}/users/me/conferences/${i}/participants`),getMeetingParticipantsAsUser:async i=>e.get(`${t}/users/me/meetings/${i}/participants`),banMeetingParticipant:(i,n)=>e.delete(`${t}/users/me/meetings/${i}/participants/${n}`,null,null,G.successResponseParser),listTrunks:()=>e.get(`${t}/trunks`),mute:i=>e.put(`${t}/users/me/calls/${i}/mute/start`,null,null,G.successResponseParser),unmute:i=>e.put(`${t}/users/me/calls/${i}/mute/stop`,null,null,G.successResponseParser),hold:i=>e.put(`${t}/users/me/calls/${i}/hold/start`,null,null,G.successResponseParser),resume:i=>e.put(`${t}/users/me/calls/${i}/hold/stop`,null,null,G.successResponseParser),transferCall:(i,n,r)=>e.post(`${t}/users/me/transfers`,{initiator_call:i,exten:n,flow:r}).then(Zi.parseFromApi),confirmCallTransfer:i=>e.put(`${t}/users/me/transfers/${i}/complete`,null,null,G.successResponseParser),cancelCallTransfer:i=>e.delete(`${t}/users/me/transfers/${i}`,null,null,G.successResponseParser),sendDTMF:(i,n)=>e.put(`${t}/users/me/calls/${i}/dtmf?digits=${encodeURIComponent(n)}`,null,null,G.successResponseParser),isAhHocConferenceAPIEnabled:()=>e.head(`${t}/users/me/conferences/adhoc`,null,null,G.successResponseParser),createAdHocConference:(i,n)=>e.post(`${t}/users/me/conferences/adhoc`,{host_call_id:i,participant_call_ids:n}),addAdHocConferenceParticipant:(i,n)=>e.put(`${t}/users/me/conferences/adhoc/${i}/participants/${n}`,null,null,G.successResponseParser),removeAdHocConferenceParticipant:(i,n)=>e.delete(`${t}/users/me/conferences/adhoc/${i}/participants/${n}`,null,null,G.successResponseParser),deleteAdHocConference:i=>e.delete(`${t}/users/me/conferences/adhoc/${i}`,null,null,G.successResponseParser),startRecording:i=>e.put(`${t}/users/me/calls/${i}/record/start`,null,null,G.successResponseParser),stopRecording:i=>e.put(`${t}/users/me/calls/${i}/record/stop`,null,null,G.successResponseParser),pauseRecording:i=>e.put(`${t}/users/me/calls/${i}/record/pause`,null,null,G.successResponseParser),resumeRecording:i=>e.put(`${t}/users/me/calls/${i}/record/resume`,null,null,G.successResponseParser),guestGetMeetingStatus:i=>e.get(`${t}/guests/me/meetings/${i}/status`).then(Xi.parse)}))(this.client,"calld/1.0"),this.agentd=((e,t)=>({getAgent:i=>e.get(`${t}/agents/by-id/${i}`,null).then(Qi.parse),login:(i,n,r)=>e.post(`${t}/agents/by-number/${i}/login`,{context:n,extension:r},null,G.successResponseParser),loginWithLineId:i=>e.post(`${t}/users/me/agents/login`,{line_id:i},null,G.successResponseParser),logout:i=>e.post(`${t}/agents/by-number/${i}/logoff`,null,null,G.successResponseParser),pause:i=>e.post(`${t}/agents/by-number/${i}/pause`,{reason:"songbird_reason"},null,G.successResponseParser),resume:i=>e.post(`${t}/agents/by-number/${i}/unpause`,null,null,G.successResponseParser),getStatus:()=>e.get(`${t}/users/me/agents`,null).then(Qi.parse),staticLogout:()=>e.post(`${t}/users/me/agents/logoff`,null,null,G.successResponseParser),staticPause:()=>e.post(`${t}/users/me/agents/pause`,{reason:"songbird_reason"},null,G.successResponseParser),staticResume:()=>e.post(`${t}/users/me/agents/unpause`,null,null,G.successResponseParser)}))(this.client,"agentd/1.0"),this.webhookd=((e,t)=>({getSubscriptions:()=>e.get(`${t}/users/me/subscriptions`).then(en.parseMany),getSubscription:i=>e.get(`${t}/users/me/subscriptions/${i}`).then(en.parse),createSubscription:i=>e.post(`${t}/users/me/subscriptions`,i),removeSubscription:i=>e.delete(`${t}/users/me/subscriptions/${i}`)}))(this.client,"webhookd/1.0"),this.amid=((e,t)=>({action:(i,n={})=>e.post(`${t}/action/${i}`,n),getAors:async i=>{try{const n=await e.post(`${t}/action/PJSIPShowEndpoint`,{Endpoint:i})||[];return n?n.filter((e=>"ContactStatusDetail"===e.Event)):[]}catch{return[]}}}))(this.client,"amid/1.0")}updateParameters({server:e,agent:t,clientId:i,fetchOptions:n}){const r=this.refreshTokenCallback.bind(this);this.client=new G({server:e,agent:t,refreshTokenCallback:r,clientId:i,fetchOptions:n}),this.initializeEndpoints()}async forceRefreshToken(){return tn.info("forcing refresh token, calling callback"),this.refreshTokenCallback()}async refreshTokenCallback(){if(tn.info("refresh token callback called",{refreshToken:R(this.refreshToken),refreshBackend:this.refreshBackend,refreshTenantId:this.refreshTenantId,refreshDomainName:this.refreshDomainName,refreshExpiration:this.refreshExpiration,isMobile:this.isMobile}),!this.refreshToken)return null;try{const e=await this.auth.refreshToken(this.refreshToken,this.refreshBackend,this.refreshExpiration,this.isMobile,this.refreshTenantId,this.refreshDomainName);return e?(tn.info("token refreshed",{token:R(e.token)}),this.onRefreshToken&&this.onRefreshToken(e.token,e),this.setToken(e.token),e.token):null}catch(e){tn.error("token refresh, error",e),this.onRefreshTokenError&&this.onRefreshTokenError(e)}return null}setToken(e){this.client.setToken(e)}setTenant(e){this.client.setTenant(e)}setRefreshToken(e){this.refreshToken=e}setRequestTimeout(e){this.client.setRequestTimeout(e)}setClientId(e){this.client.clientId=e}setOnRefreshToken(e){this.onRefreshToken=e}setOnRefreshTokenError(e){this.onRefreshTokenError=e}setRefreshExpiration(e){this.refreshExpiration=e}setRefreshBackend(e){this.refreshBackend=e}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead"),this.refreshTenantId=e}setRefreshDomainName(e){this.refreshDomainName=e}setIsMobile(e){this.isMobile=e}setFetchOptions(e){this.fetchOptions=e,this.client.setFetchOptions(e)}disableErrorLogging(){this.client.disableErrorLogging()}}global.wazoClients=global.wazoClients||{},global.wazoClientId=global.wazoClientId||{},global.wazoClientToken=global.wazoClientToken||{},global.wazoRefreshToken=global.wazoRefreshToken||{},global.wazoRefreshTenantId=global.wazoRefreshTenantId||{},global.wazoRefreshDomainName=global.wazoRefreshDomainName||{},global.wazoOnRefreshToken=global.wazoOnRefreshToken||{},global.wazoOnRefreshTokenError=global.wazoOnRefreshTokenError||{},global.wazoRefreshExpiration=global.wazoRefreshExpiration||{},global.wazoRefreshBackend=global.wazoRefreshBackend||{},global.wazoIsMobile=global.wazoIsMobile||{},global.wazoRequestApiTimeout=global.wazoRequestApiTimeout||{},global.wazoFetchOptions=global.wazoFetchOptions||{};const rn=(e,t=null)=>{global.wazoClientId[String(t)]=e},sn=e=>{global.wazoCurrentServer=e},an=(e,t=null)=>{global.wazoClientToken[String(t)]=e},on=(e,t=null)=>{global.wazoRefreshToken[String(t)]=e},cn=(e,t=null)=>{global.wazoOnRefreshToken[String(t)]=e},dn=(e,t=null)=>{global.wazoOnRefreshTokenError[String(t)]=e},ln=(e,t=null)=>{global.wazoFetchOptions[String(t)]=e},hn=(e=null)=>(e?global.wazoFetchOptions[e]:global.wazoFetchOptions.null)||global.wazoFetchOptions.null,un=e=>{const{server:t,token:i,clientId:n}=e.client,r=global.wazoRefreshTenantId[t]||global.wazoRefreshTenantId.null||e.refreshTenantId,s=global.wazoRequestApiTimeout[t]||global.wazoRequestApiTimeout.null;return e.setToken(global.wazoClientToken[t]||global.wazoClientToken.null||i),e.setClientId(global.wazoClientId[t]||global.wazoClientId.null||n),e.setRefreshToken(global.wazoRefreshToken[t]||global.wazoRefreshToken.null||e.refreshToken),r&&e.setRefreshTenantId(r),e.setRefreshDomainName(global.wazoRefreshDomainName[t]||global.wazoRefreshDomainName.null||e.refreshDomainName),e.setFetchOptions(global.wazoFetchOptions[t]||global.wazoFetchOptions.null||e.fetchOptions),e.setOnRefreshToken(global.wazoOnRefreshToken[t]||global.wazoOnRefreshToken.null||e.onRefreshToken),e.setOnRefreshTokenError(global.wazoOnRefreshTokenError[t]||global.wazoOnRefreshTokenError.null||e.onRefreshTokenError),e.setRefreshExpiration(global.wazoRefreshExpiration[t]||global.wazoRefreshExpiration.null||e.refreshExpiration),e.setRefreshBackend(global.wazoRefreshBackend[t]||global.wazoRefreshBackend.null||e.refreshBackend),e.setIsMobile(global.wazoIsMobile[t]||global.wazoIsMobile.null||e.isMobile),s&&e.setRequestTimeout(s),e};var pn=(e=null)=>{const t=e||global.wazoCurrentServer||"";return t in global.wazoClients||(global.wazoClients[t]=new nn({server:t})),un(global.wazoClients[t])};class gn extends Error{}class fn extends Error{}class mn extends Error{}class vn extends Error{}class yn extends Error{}class Sn extends Error{}const bn=B.loggerFor("simple-auth");class wn{clientId;expiration;minSubscriptionType;authorizationName;host;session;onRefreshTokenCallback;onRefreshTokenCallbackError;onHostFromHeadersCallback;authenticated;mobile;BACKEND_WAZO;BACKEND_LDAP;usingEdgeServer;onSetUsingEdgeServer;constructor(){this.expiration=ni,this.authenticated=!1,this.minSubscriptionType=null,this.BACKEND_WAZO=ii,this.BACKEND_LDAP="ldap_user"}init(e,t,i,n,r){this.clientId=e,this.expiration=t,this.minSubscriptionType=void 0===i?null:i,this.authorizationName=n,this.host=null,this.session=null,this.mobile=r||!1,rn(this.clientId),((e,t=null)=>{global.wazoRefreshExpiration[String(t)]=e})(this.expiration),cn(((e,t)=>{bn.info("on refresh token done",{token:R(e)}),an(e),Ol.Websocket.updateToken(e),this.onRefreshTokenCallback&&this.onRefreshTokenCallback(e,t)})),dn((e=>{bn.error("on refresh token error",e),this.onRefreshTokenCallbackError&&this.onRefreshTokenCallbackError(e)}))}setFetchOptions(e){ln(e)}async logIn(e,t,i,n){let r=null,s=null;if("string"==typeof n&&(r=n),n&&"object"==typeof n&&(s=n.domainName),i&&i!==this.BACKEND_WAZO&&!r&&!s){if(!r)throw new mn("No tenant id");if(!s)throw new vn("No domain name")}this.authenticated=!1,this.session=null;const a=await pn().auth.logIn({username:e,password:t,backend:i,tenantId:r,domainName:s,expiration:this.expiration,mobile:this.mobile});if(a){const e=a.getHostFromHeader();e&&(this.setHost(e),this.onHostFromHeadersCallback&&this.onHostFromHeadersCallback(e))}return i&&pn().setRefreshBackend(i),r&&pn().setRefreshTenantId(r),s&&pn().setRefreshDomainName(s),this._onAuthenticated(a)}async samlLogIn(e){const t=await pn().auth.samlLogIn(e);return this._onAuthenticated(t)}async initiateIdpAuthentication(e,t){try{return await pn().auth.initiateIdpAuthentication(e,t)}catch(e){if(bn.error("Error during IdP authentication initialization:",e.message),404===e.status)throw new yn("No route found for SAML SSO");if(500===e.status)throw new Sn("SAML/server configuration error");throw e}}async logInViaRefreshToken(e){const t=await pn().auth.refreshToken(e,"",this.expiration,this.mobile);return this._onAuthenticated(t)}async validateToken(e,t,i){if(e){this.usingEdgeServer&&"string"==typeof i&&(bn.info("using edge server, setting user UUID header",{headerUserUuid:i}),this.setHttpUserUuidHeader(i)),t&&on(t);try{const t=await pn().auth.authenticate(e);return this._onAuthenticated(t)}catch(e){bn.error("on validate token error",e),console.warn(e)}}}async generateNewToken(e){return pn().auth.refreshToken(e,"",this.expiration)}async logout(e=!0){try{Ol.Websocket.close(!0),this.clientId&&e&&await pn().auth.deleteRefreshToken(this.clientId)}catch(e){}try{this.session?.token&&await pn().auth.logOut(this.session.token)}catch(e){}an(null),on(null),this.session=null,this.authenticated=!1,this.usingEdgeServer=void 0,ln({})}setOnHostFromHeaders(e){this.onHostFromHeadersCallback=e}setOnSetUsingEdgeServer(e){bn.info("setting onSetUsingEdgeServer callback",{callback:"function"==typeof e}),this.onSetUsingEdgeServer=e}setOnRefreshToken(e){this.onRefreshTokenCallback=e}setOnRefreshTokenError(e){this.onRefreshTokenCallbackError=e}checkAuthorizations(e,t){if(!t)return;const{authorizations:i}=e;if(!i.find((e=>e.rules.find((e=>e.name===t)))))throw new fn(`No authorization '${t||""}' found for your account.`)}checkSubscription(e,t){const i=e.profile?.subscriptionType||null;if(null===i||i<=t){throw new gn(`Invalid subscription ${i||"n/a"}, required at least ${t}`)}}setHost(e){this.host=e,sn(e)}setApiToken(e){an(e)}setRefreshToken(e){on(e)}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead."),((e,t=null)=>{console.warn("Use of `setRefreshTenantId` is deprecated, please use `setRefreshDomainName` instead"),global.wazoRefreshTenantId[String(t)]=e})(e),pn().setRefreshTenantId(e)}setRefreshDomainName(e){((e,t=null)=>{global.wazoRefreshDomainName[String(t)]=e})(e),pn().setRefreshDomainName(e)}setRequestTimeout(e){((e,t=null)=>{global.wazoRequestApiTimeout[String(t)]=e})(e),pn().setRequestTimeout(e)}forceRefreshToken(){return pn().forceRefreshToken()}setIsMobile(e){this.mobile=e}getHost(){return this.host||void 0}getSession(){return this.session||void 0}getFirstName(){return this.session&&this.session.profile?this.session.profile.firstName:""}getLastName(){return this.session&&this.session.profile?this.session.profile.lastName:""}setClientId(e){this.clientId=e,rn(this.clientId)}getName(){return`${this.getFirstName()} ${this.getLastName()}`}_getHttpUserUuidHeaders(e){return{...hn()?.headers||{},"X-User-UUID":e}}setHttpUserUuidHeader(e){if(bn.info("Setting http header user uuid",{uuid:e}),!e)return void bn.warn("attempting to set a null value to user uuid header");const t=this._getHttpUserUuidHeaders(e);ln({...hn(),headers:t})}async checkHttpUserUuidHeader(e){if(bn.info("Checking user uuid http header",{uuid:e}),!e)return;const t=this._getHttpUserUuidHeaders(e);try{const i=await pn().client.head("auth/0.1/status",null,t,(e=>e)),n=i.headers.get("access-control-allow-headers")?.includes("X-User-UUID");if(this.mobile&&!n)throw new Error("Server does not allow user UUID header on mobile");this.setHttpUserUuidHeader(e),this.usingEdgeServer=!0,bn.info("Setting usingEdgeServer value to TRUE",{requestHeaders:t,responseHeaders:i.headers,allowsUserUuidHeader:n})}catch(e){this.usingEdgeServer=!1,bn.info("Setting usingEdgeServer to FALSE",{justification:e})}"function"==typeof this.onSetUsingEdgeServer&&(bn.info("calling onSetUsingEdgeServer",{usingEdgeServer:this.usingEdgeServer}),this.onSetUsingEdgeServer(this.usingEdgeServer))}async _onAuthenticated(e){if(this.authenticated&&this.session)return this.session;const t=e;if(!t)return null;this.usingEdgeServer?this.setHttpUserUuidHeader(t.uuid):void 0===this.usingEdgeServer&&await this.checkHttpUserUuidHeader(t.uuid),an(t.token),t.refreshToken&&on(t.refreshToken);try{const[e,{wazo_version:i}]=await Promise.all([pn().confd.getUser(t.uuid),pn().confd.getInfos()]);t.engineVersion=i,t.profile=e,this.checkAuthorizations(t,this.authorizationName),null!==this.minSubscriptionType&&this.checkSubscription(t,+this.minSubscriptionType)}catch(e){throw bn.error("on authenticated error",e),this.clientId&&await pn().auth.deleteRefreshToken(this.clientId),t&&await pn().auth.logOut(t.token),e}try{const e=t.profile?.lines.filter((e=>!e.endpointSccp)).map((e=>String(e.id))),i=await pn().confd.getUserLinesSip(t.uuid,e);t.profile.sipLines=i.filter((e=>e instanceof ai))}catch(e){}return this.authenticated=!0,Ol.Websocket.open(this.host,t),this.session=t,t}}global.wazoAuthInstance||(global.wazoAuthInstance=new wn);var En=global.wazoAuthInstance;class Cn{phone;host;participants;started;finished;conferenceId;answerTime;muted;paused;constructor({phone:e,host:t,participants:i,started:n,finished:r,answerTime:s,conferenceId:a,muted:o,paused:c}){this.phone=e,this.host=t,this.participants=i||{},this.started=n||!1,this.finished=r||!1,this.answerTime=s,this.conferenceId=a||"",this.muted=o||!1,this.paused=c||!1,this.host&&this.host.setIsConference(!0)}async start(){this.started=!0,this.answerTime=Object.values(this.participants).length?Object.values(this.participants)[0].answerTime:null;const e=Object.keys(this.participants),t=await pn().calld.createAdHocConference(this.host.callId,e);return this.conferenceId=t.conference_id,this}getParticipants(){return Object.values(this.participants)}async addParticipant(e){const t=e.getTalkingToIds()[0],i={...this.participants,[t]:e};return await pn().calld.addAdHocConferenceParticipant(this.conferenceId,t),new Cn({...this,participants:i})}participantHasLeft(e){return delete this.participants[e.getId()],new Cn({...this,participants:this.participants})}hasParticipants(){return Object.keys(this.participants).length>0}mute(){return this.muted=!0,this.phone.mute(this.host),new Cn({...this})}unmute(){return this.muted=!1,this.phone.unmute(this.host),new Cn({...this})}hold(){return this.paused=!0,this.phone.hold(this.host),new Cn({...this})}resume(){return this.paused=!1,this.phone.resume(this.host),new Cn({...this})}isOnHold(){return this.paused}isMuted(){return this.muted}async hangup(){return await pn().calld.deleteAdHocConference(this.conferenceId),new Cn({...this,finished:!0,participant:[]})}async removeParticipant(e){const t=e.getTalkingToIds()[0];return delete this.participants[t],await pn().calld.removeAdHocConferenceParticipant(this.conferenceId,t),new Cn({...this,participants:this.participants})}}class $n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class Tn extends $n{constructor(e){super(e||"Unsupported content type.")}}class _n extends $n{constructor(e){super(e||"Request pending.")}}class xn extends $n{constructor(e){super(e||"Unspecified session description handler error.")}}class In extends $n{constructor(){super("The session has terminated.")}}class Rn extends $n{constructor(e){super(e||"An error occurred during state transition.")}}class An{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Pn{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class Dn{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class Nn{constructor(){this.listeners=new Array}addListener(e,t){const i=t=>{this.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}emit(e){this.listeners.slice().forEach((t=>t(e)))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class kn{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class On{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class Fn extends On{constructor(e,t,i){super(i),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new Fn(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class Mn extends On{constructor(e="sip",t,i,n,r,s){if(super(r||{}),this.headers={},!i)throw new TypeError('missing or invalid "host" parameter');for(const e in s)s.hasOwnProperty(e)&&this.setHeader(e,s[e]);this.raw={scheme:e,user:t,host:i,port:n},this.normal={scheme:e.toLowerCase(),user:t,host:i.toLowerCase(),port:n}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new Mn(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const i=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&i.push(e+"="+this.headers[e][t]);return i.length>0&&(t+="?"+i.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),n=i.length;let r="";for(let e=0;e<n;e++)0!==e&&(r+="-"),r+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[r]&&(r=t[r]),r}}function Hn(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){const i=Object.keys(e.parameters),n=Object.keys(t.parameters);return!!i.filter((e=>n.includes(e))).every((i=>e.parameters[i]===t.parameters[i]))&&(!!["user","ttl","method","transport"].every((i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i)))&&!!["maddr"].every((i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i))))}(e,t))return!1;const i=Object.keys(e.headers),n=Object.keys(t.headers);if(0!==i.length||0!==n.length){if(i.length!==n.length)return!1;const r=i.filter((e=>n.includes(e)));if(r.length!==n.length)return!1;if(!r.every((i=>e.headers[i].length&&t.headers[i].length&&e.headers[i][0]===t.headers[i][0])))return!1}return!0}function Ln(e,t,i){return i=i||" ",e.length>t?e:(t-=e.length,e+(i+=i.repeat(t)).slice(0,t))}class jn extends Error{constructor(e,t,i,n){super(),this.message=e,this.expected=t,this.found=i,this.location=n,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,jn.prototype):this.__proto__=jn.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,jn)}static buildMessage(e,t){function i(e){return e.charCodeAt(0).toString(16).toUpperCase()}function n(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(e=>"\\x0"+i(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+i(e)))}function r(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(e=>"\\x0"+i(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+i(e)))}function s(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":const t=e.parts.map((e=>Array.isArray(e)?r(e[0])+"-"+r(e[1]):r(e)));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(s);let i,n;if(t.sort(),t.length>0){for(i=1,n=1;i<t.length;i++)t[i-1]!==t[i]&&(t[n]=t[i],n++);t.length=n}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((a=t)?'"'+n(a)+'"':"end of input")+" found.");var a}format(e){let t="Error: "+this.message;if(this.location){let i,n=null;for(i=0;i<e.length;i++)if(e[i].source===this.location.source){n=e[i].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,s=this.location.source+":"+r.line+":"+r.column;if(n){let e=this.location.end,i=Ln("",r.line.toString().length," "),a=n[r.line-1],o=r.line===e.line?e.column:a.length+1;t+="\n --\x3e "+s+"\n"+i+" |\n"+r.line+" | "+a+"\n"+i+" | "+Ln("",r.column-1," ")+Ln("",o-r.column,"^")}else t+="\n at "+s}return t}}const Bn=function(e,t){const i={},n=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let s=119;const a=["\r\n",v("\r\n",!1),/^[0-9]/,y([["0","9"]],!1,!1),/^[a-zA-Z]/,y([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,y([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,y([["\0","ÿ"]],!1,!1),/^["]/,y(['"'],!1,!1)," ",v(" ",!1),"\t",v("\t",!1),/^[a-zA-Z0-9]/,y([["a","z"],["A","Z"],["0","9"]],!1,!1),";",v(";",!1),"/",v("/",!1),"?",v("?",!1),":",v(":",!1),"@",v("@",!1),"&",v("&",!1),"=",v("=",!1),"+",v("+",!1),"$",v("$",!1),",",v(",",!1),"-",v("-",!1),"_",v("_",!1),".",v(".",!1),"!",v("!",!1),"~",v("~",!1),"*",v("*",!1),"'",v("'",!1),"(",v("(",!1),")",v(")",!1),"%",v("%",!1),function(){return" "},function(){return":"},/^[!-~]/,y([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,y([["",""]],!1,!1),/^[\x80-\xBF]/,y([["","¿"]],!1,!1),/^[a-f]/,y([["a","f"]],!1,!1),"`",v("`",!1),"<",v("<",!1),">",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\v-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(f().slice(0,-1))},function(){(t=t||{data:{}}).data.password=f()},function(){return(t=t||{data:{}}).data.host=f(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",f()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",f()},function(){return(t=t||{data:{}}).data.host_type="IPv4",f()},"25",v("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,i){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),i=null===i?void 0:i[1],t.data.uri_params[e.toLowerCase()]=i},function(e,i){e=e.join("").toLowerCase(),i=i.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(i):t.data.uri_headers[e]=[i]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new Mn(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=f()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=f()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=f(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=f()},function(){(t=t||{data:{}}).data=f()},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Fn(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(e){'"'===(e=f().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",v("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",v("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",v("0",!1),function(){return parseFloat(f())},function(e,i){(t=t||{data:{}}).data.params||(t.data.params={}),i=null===i?void 0:i[1],t.data.params[e.toLowerCase()]=i},"render",v("render",!0),"session",v("session",!0),"icon",v("icon",!0),"alert",v("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=f().toLowerCase())},"handling",v("handling",!0),"optional",v("optional",!0),"required",v("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=f()},"text",v("text",!0),"image",v("image",!0),"audio",v("audio",!0),"video",v("video",!0),"application",v("application",!0),"message",v("message",!0),"multipart",v("multipart",!0),"x-",v("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Fn(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",v("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new Fn(t.data.uri,t.data.displayName,t.data.params)},"digest",v("Digest",!0),"realm",v("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",v("domain",!0),"nonce",v("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",v("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",v("stale",!0),"true",v("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",v("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",v("algorithm",!0),"md5",v("MD5",!0),"md5-sess",v("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",v("qop",!0),"auth-int",v("auth-int",!0),"auth",v("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new Fn(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:c,offset:m().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new Fn(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",v("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",v("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",v("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",v("active",!0),"pending",v("pending",!0),"terminated",v("terminated",!0),function(){(t=t||{data:{}}).data.state=f()},"reason",v("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",v("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",v("deactivated",!0),"probation",v("probation",!0),"rejected",v("rejected",!0),"timeout",v("timeout",!0),"giveup",v("giveup",!0),"noresource",v("noresource",!0),"invariant",v("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new Fn(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",v("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",v("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",v("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",v("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",v("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},v("UDP",!0),v("TCP",!0),v("TLS",!0),v("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=f()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",v("refresher",!1),"uas",v("uas",!1),"uac",v("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",v("stuns",!0),"stun",v("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",v("?transport=",!1),"turns",v("turns",!0),"turn",v("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=f()},"Referred-By",v("Referred-By",!1),"b",v("b",!1),"cid",v("cid",!1)],o=[E('2 ""6 7!'),E('4"""5!7#'),E('4$""5!7%'),E('4&""5!7\''),E(";'.# &;("),E('4(""5!7)'),E('4*""5!7+'),E('2,""6,7-'),E('2.""6.7/'),E('40""5!71'),E('22""6273. &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E(";).# &;,"),E('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),E('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),E('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),E(';.." &"'),E("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),E('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E('4\\""5!7].# &;3'),E('4^""5!7_'),E('4`""5!7a'),E(';!.) &4b""5!7c'),E('%$;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G. &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('%$;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/#0*;). &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273. &28""6879. &2j""6j7k. &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),E('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W. &2f""6f7g. &2h""6h7i. &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),E("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),E("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),E("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),E("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),E("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),E('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),E('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),E("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),E("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),E("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),E("%;//0#;&/'$8\":~\" )(\"'#&'#"),E("%;&/0#;//'$8\":~\" )(\"'#&'#"),E("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),E('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),E("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),E("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),E(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),E('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),E("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),E("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),E('%3""5$7.) &3""5#7/\' 8!:!! )'),E('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),E("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),E('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),E('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:! )'),E('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:! )"),E('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),E('$4""5!7/,#0)*4""5!7&&&#'),E('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),E('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),E('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),E('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),E("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),E('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),E('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),E(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),E('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),E('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),E('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),E('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),E('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),E('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),E('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),E('%$;j/�#*;j&&&#/"!&,)'),E('%$;j/�#*;j&&&#/"!&,)'),E(";k.) &;+.# &;-"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),E('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),E('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),E("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),E("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),E(";.# &;r"),E("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E(";M.# &;t"),E("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),E('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),E('%24""6475/,#;{/#$+")("\'#&\'#'),E("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),E(";*.) &;+.# &;-"),E(';+. &;-. &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E("$;~0#*;~&"),E(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),E(";.# &;"),E('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),E('$;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/#0*;+. &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),E("$;y0#*;y&"),E('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),E('2Õ""6Õ7Ö'),E('2×""6×7Ø'),E('2Ù""6Ù7Ú'),E('2Û""6Û7Ü'),E('2Ý""6Ý7Þ'),E('2ß""6ß7à'),E('2á""6á7â'),E('2ã""6ã7ä'),E('2å""6å7æ'),E('2ç""6ç7è'),E('2é""6é7ê'),E("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),E("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%;/' 8!:ì!! )"),E("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),E("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),E("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),E("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),E("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),E("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),E("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),E(";.) &;.# &; "),E("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),E("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ø!! )"),E('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),E('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),E(";6.) &;T.# &;H"),E("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),E(";¥.# &; "),E('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:Č!! )"),E("%;©/& 8!:č! )"),E("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";«.# &;¬"),E('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),E('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),E(";6.# &;®"),E('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),E(";.# &;6"),E("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),E(";6.# &;H"),E("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),E("%;/' 8!:ğ!! )"),E('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),E('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),E(";¹.# &; "),E("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),E("%;/' 8!:Ħ!! )"),E("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),E(";¾"),E("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),E("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),E(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),E("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:Ĭ!! )"),E("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),E(";t.# &;w"),E("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:ı!! )"),E("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),E('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),E('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),E('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),E('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),E("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),E("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),E('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),E("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),E("%;/& 8!:Ő! )"),E('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),E("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),E("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),E("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),E('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),E(';1." &"'),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),E("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),E(";¹.# &; "),E("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),E("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),E("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),E("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),E("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),E("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),E("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),E('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),E('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),E('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),E('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),E(";¾"),E('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),E(";ô.# &; "),E('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),E('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),E("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),E("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),E("$;%0#*;%&"),E("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),E('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),E('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),E(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),E('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),E('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),E('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),E("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),E("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),E("%;ă/,#;ă/#$+\")(\"'#&'#"),E("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),E("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),E('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),E(";.# &;L"),E("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),E("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,d=0;const l=[{line:1,column:1}];let h,u=0,p=[],g=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');s=r[t.startRule]}function f(){return e.substring(d,c)}function m(){return b(d,c)}function v(e,t){return{type:"literal",text:e,ignoreCase:t}}function y(e,t,i){return{type:"class",parts:e,inverted:t,ignoreCase:i}}function S(t){let i,n=l[t];if(n)return n;for(i=t-1;!l[i];)i--;for(n=l[i],n={line:n.line,column:n.column};i<t;)10===e.charCodeAt(i)?(n.line++,n.column=1):n.column++,i++;return l[t]=n,n}function b(e,t){const i=S(e),r=S(t);return{source:n,start:{offset:e,line:i.line,column:i.column},end:{offset:t,line:r.line,column:r.column}}}function w(e){c<u||(c>u&&(u=c,p=[]),p.push(e))}function E(e){return e.split("").map((e=>e.charCodeAt(0)-32))}if(t.data={},h=function t(n){const r=o[n];let s=0;const l=[];let h=r.length;const u=[],p=[];let f;for(;;){for(;s<h;)switch(r[s]){case 0:p.push(a[r[s+1]]),s+=2;break;case 1:p.push(void 0),s++;break;case 2:p.push(null),s++;break;case 3:p.push(i),s++;break;case 4:p.push([]),s++;break;case 5:p.push(c),s++;break;case 6:p.pop(),s++;break;case 7:c=p.pop(),s++;break;case 8:p.length-=r[s+1],s+=2;break;case 9:p.splice(-2,1),s++;break;case 10:p[p.length-2].push(p.pop()),s++;break;case 11:p.push(p.splice(p.length-r[s+1],r[s+1])),s+=2;break;case 12:p.push(e.substring(p.pop(),c)),s++;break;case 13:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 14:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]===i?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 15:u.push(h),l.push(s+3+r[s+1]+r[s+2]),p[p.length-1]!==i?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 16:p[p.length-1]!==i?(u.push(h),l.push(s),h=s+2+r[s+1],s+=2):s+=2+r[s+1];break;case 17:u.push(h),l.push(s+3+r[s+1]+r[s+2]),e.length>c?(h=s+3+r[s+1],s+=3):(h=s+3+r[s+1]+r[s+2],s+=3+r[s+1]);break;case 18:u.push(h),l.push(s+4+r[s+2]+r[s+3]),e.substr(c,a[r[s+1]].length)===a[r[s+1]]?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 19:u.push(h),l.push(s+4+r[s+2]+r[s+3]),e.substr(c,a[r[s+1]].length).toLowerCase()===a[r[s+1]]?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 20:u.push(h),l.push(s+4+r[s+2]+r[s+3]),a[r[s+1]].test(e.charAt(c))?(h=s+4+r[s+2],s+=4):(h=s+4+r[s+2]+r[s+3],s+=4+r[s+2]);break;case 21:p.push(e.substr(c,r[s+1])),c+=r[s+1],s+=2;break;case 22:p.push(a[r[s+1]]),c+=a[r[s+1]].length,s+=2;break;case 23:p.push(i),0===g&&w(a[r[s+1]]),s+=2;break;case 24:d=p[p.length-1-r[s+1]],s+=2;break;case 25:d=c,s++;break;case 26:f=r.slice(s+4,s+4+r[s+3]).map((function(e){return p[p.length-1-e]})),p.splice(p.length-r[s+2],r[s+2],a[r[s+1]].apply(null,f)),s+=4+r[s+3];break;case 27:p.push(t(r[s+1])),s+=2;break;case 28:g++,s++;break;case 29:g--,s++;break;default:throw new Error("Invalid opcode: "+r[s]+".")}if(!(u.length>0))break;h=u.pop(),s=l.pop()}return p[0]}(s),h!==i&&c===e.length)return h;throw h!==i&&c<e.length&&w({type:"end"}),C=p,$=u<e.length?e.charAt(u):null,T=u<e.length?b(u,u+1):b(u,u),new jn(jn.buildMessage(C,$),C,$,T);var C,$,T};var Un;!function(e){e.parse=function(e,t){const i={startRule:t};try{Bn(e,i)}catch(e){i.data=-1}return i.data},e.nameAddrHeaderParse=function(t){const i=e.parse(t,"Name_Addr_Header");return-1!==i?i:void 0},e.URIParse=function(t){const i=e.parse(t,"SIP_URI");return-1!==i?i:void 0}}(Un=Un||(Un={}));const Vn={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function qn(e,t=32){let i="";for(let n=0;n<e;n++){i+=Math.floor(Math.random()*t).toString(t)}return i}function Gn(e){return Vn[e]||""}function Kn(){return qn(10)}function Wn(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),n=i.length;let r="";for(let e=0;e<n;e++)0!==e&&(r+="-"),r+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[r]&&(r=t[r]),r}function zn(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class Yn{constructor(){this.headers={}}addHeader(e,t){const i={raw:t};e=Wn(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[Wn(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[Wn(e)],i=[];if(!t)return[];for(const e of t)i.push(e.raw);return i}hasHeader(e){return!!this.headers[Wn(e)]}parseHeader(e,t=0){if(e=Wn(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const i=this.headers[e][t],n=i.raw;if(i.parsed)return i.parsed;const r=Un.parse(n,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(i.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Wn(e)]=[{raw:t}]}toString(){return this.data}}class Jn extends Yn{constructor(){super()}}class Zn extends Yn{constructor(){super()}}class Xn{constructor(e,t,i,n,r,s,a){this.headers={},this.extraHeaders=[],this.options=Xn.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),s&&s.length&&(this.extraHeaders=s.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Kn(),this.from=Xn.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=n.clone(),this.toTag=this.options.toTag,this.to=Xn.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+qn(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,i){const n={};return i&&(n.tag=i),new Fn(e,t,n)}getHeader(e){const t=this.headers[Wn(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[Wn(e)];if(i)for(const e of i)t.push(e);else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)i.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[Wn(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[Wn(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const i of this.headers[t])e+=t+": "+i+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+zn(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+zn(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Qn(e){return"application/sdp"===e?"session":"render"}function er(e){const t="string"==typeof e?e:e.body,i="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Qn(i),contentType:i,content:t}}function tr(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function ir(e){let t,i,n;if(e instanceof Jn&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,i=e.parseHeader("Content-Type"),n=e.body}if(e instanceof Zn&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,i=e.parseHeader("Content-Type"),n=e.body}if(e instanceof Xn&&e.body)if(t=e.getHeader("Content-Disposition"),i=e.getHeader("Content-Type"),"string"==typeof e.body){if(!i)throw new Error("Header content type header does not equal body content type.");n=e.body}else{if(i&&i!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");i=e.body.contentType,n=e.body.body}if(tr(e)&&(t=e.contentDisposition,i=e.contentType,n=e.content),n){if(i&&!t&&(t=Qn(i)),!t)throw new Error("Content disposition undefined.");if(!i)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:i,content:n}}}var nr,rr;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(nr=nr||(nr={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(rr=rr||(rr={}));const sr=500,ar=5e3,or={T1:sr,T2:4e3,T4:ar,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class cr extends $n{constructor(e){super(e||"Transaction state error.")}}var dr;!function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(dr=dr||(dr={}));const lr=[dr.ACK,dr.BYE,dr.CANCEL,dr.INFO,dr.INVITE,dr.MESSAGE,dr.NOTIFY,dr.OPTIONS,dr.PRACK,dr.REFER,dr.REGISTER,dr.SUBSCRIBE];class hr{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class ur{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class pr{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Fn))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const i=((e=e||{}).extraHeaders||[]).slice(),n=this.replaces;n&&i.push("Replaces: "+decodeURIComponent(n));const r=this.referredBy;return r&&i.push("Referred-By: "+r),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}class gr{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=mi.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Nn,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case mi.Initial:case mi.Establishing:break;case mi.Established:return new Promise((e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})}));case mi.Terminating:case mi.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case mi.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case mi.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case mi.Established:{const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._bye(t,i)}case mi.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case mi.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==mi.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._info(t,i)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==mi.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new _n("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const i=ir(t.message);if(!i)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(mi.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(i,n).then((e=>{t.ack({body:e})})).catch((e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===mi.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(mi.Terminated))})).then((()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))}else{const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(i,n).then((()=>{t.ack()})).catch((e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==mi.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(mi.Terminated)):t.ack()})).then((()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch((e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==mi.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated)}})).then((()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)}))},onTrying:e=>{}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+lr.toString()),i.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,i))}const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(n).then((e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=e,this.dialog.invite(t,i)})).catch((e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e}))}message(e={}){if(this.state!==mi.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._message(t,i)}refer(e,t={}){if(this.state!==mi.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof gr&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,n=this.copyRequestOptions(t.requestOptions);return n.extraHeaders=n.extraHeaders?n.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,i,n)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const i=this.dialog;switch(i.sessionState){case nr.Initial:case nr.Early:throw new Error(`Invalid dialog state ${i.sessionState}`);case nr.AckWait:return this.stateTransition(mi.Terminating),new Promise((n=>{i.delegate={onAck:()=>{const r=i.bye(e,t);return this.stateTransition(mi.Terminated),n(r),Promise.resolve()},onAckTimeout:()=>{const r=i.bye(e,t);this.stateTransition(mi.Terminated),n(r)}}}));case nr.Confirmed:{const n=i.bye(e,t);return this.stateTransition(mi.Terminated),Promise.resolve(n)}case nr.Terminated:throw new Error(`Invalid dialog state ${i.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const n=[];t&&n.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:n})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==mi.Established&&this.state!==mi.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new An(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case rr.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.Stable:{const n=ir(e.message);return n?"render"===n.contentDisposition?(this._renderbody=n.content,this._rendertype=n.contentType,Promise.resolve()):"session"!==n.contentDisposition?Promise.resolve():this.setAnswer(n,i).catch((e=>{this.logger.error(e.message);const i=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:i}),this.stateTransition(mi.Terminated)})):Promise.resolve()}case rr.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated),Promise.resolve()}case rr.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===mi.Established){if(this.delegate&&this.delegate.onBye){const t=new Pn(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(mi.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===mi.Established)if(this.delegate&&this.delegate.onInfo){const t=new kn(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==mi.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=Un.nameAddrHeaderParse(t)}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then((i=>{const n=e.accept({statusCode:200,extraHeaders:t,body:i});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,200)})).catch((t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState!==rr.Stable)this.rollbackOffer().then((()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)})).catch((t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const i=e.reject({statusCode:488});if(this.state!==mi.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(mi.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,488)}));else{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}}))}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===mi.Established)if(this.delegate&&this.delegate.onMessage){const t=new hr(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===mi.Established)if(this.onNotify){const t=new ur(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new ur(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===mi.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==mi.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new pr(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then((()=>t.makeInviter(this._referralInviterOptions).invite())).catch((e=>{this.logger.error(e.message)})))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const i=ir(e.message);return i&&"session"===i.contentDisposition?this.setOfferAndGetAnswer(i,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case rr.Initial:return this.getOffer(e);case rr.HaveLocalOffer:return Promise.resolve(void 0);case rr.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case rr.Stable:return this.state!==mi.Established?Promise.resolve(void 0):this.getOffer(e);case rr.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(i,n).then((e=>er(e))).catch((e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch((e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const i=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Tn)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,n,r).catch((e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const i=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Tn)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,n,r).then((()=>i.getDescription(n,r))).then((e=>er(e))).catch((e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t}))}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case mi.Initial:e!==mi.Establishing&&e!==mi.Established&&e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Establishing:e!==mi.Established&&e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Established:e!==mi.Terminating&&e!==mi.Terminated&&t();break;case mi.Terminating:e!==mi.Terminated&&t();break;case mi.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===mi.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const i=e;let n=Gn(e);return!n&&t&&(n=t),"SIP;cause="+i+';text="'+n+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof Mn)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,n=e.dialog.remoteTarget.toString(),r=e.dialog.callId,s=e.dialog.remoteTag,a=e.dialog.localTag;t=`"${i}" <${n}?Replaces=${encodeURIComponent(`${r};to-tag=${s};from-tag=${a}`)}>`}return t}}var fr;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(fr=fr||(fr={}));const mr={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class vr extends gr{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const i=this.incomingInviteRequest.message,n=i.getHeader("require");n&&n.toLowerCase().includes("100rel")&&(this.rel100="required");const r=i.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),i.toTag=t.toTag,"string"!=typeof i.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout((()=>{t.reject({statusCode:480}),this.stateTransition(mi.Terminated)}),this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),i.hasHeader("expires")){const e=1e3*Number(i.getHeader("expires")||0);this.expiresTimer=setTimeout((()=>{this.state===mi.Initial&&(t.reject({statusCode:487}),this.stateTransition(mi.Terminated))}),e)}const s=this.request.getHeader("P-Asserted-Identity");s&&(this._assertedIdentity=Un.nameAddrHeaderParse(s)),this._contact=this.userAgent.contact.toString();const a=i.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=i.body,this._rendertype=i.getHeader("Content-Type")),this._id=i.callId+i.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case mi.Initial:case mi.Establishing:return this.reject().then((()=>super.dispose()));case mi.Established:case mi.Terminating:case mi.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==mi.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(mi.Establishing),this.sendAccept(e).then((({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(mi.Established),this._replacee&&this._replacee._bye()})).catch((e=>this.handleResponseError(e)))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==mi.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then((()=>{})).catch((e=>this.handleResponseError(e))):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===fr.Required?this.sendProgressReliableWaitForPrack(e).then((()=>{})).catch((e=>this.handleResponseError(e))):this.sendProgress(e).then((()=>{})).catch((e=>this.handleResponseError(e)))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==mi.Initial&&this.state!==mi.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:Gn(t),n=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?er(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:i,extraHeaders:n,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:i,extraHeaders:n,body:r}),this.stateTransition(mi.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===mi.Initial||this.state===mi.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new Dn(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(mi.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=ir(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case rr.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case rr.Stable:return this.setAnswer(t,i).then((()=>{}));case rr.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case rr.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case rr.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof Tn?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof xn?this.logger.error("A session description handler occurred while sending response"):e instanceof In?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof cr&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===mi.Initial||this.state===mi.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(mi.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(mi.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then((()=>clearTimeout(this.userNoAnswerTimer))).then((()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t))).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i}))):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i}))))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),r=e.body?er(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:n,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:e}))).then((e=>(this._dialog=e.session,e)))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let s;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise(((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>(s=e,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:s})))).then((t=>{let o,c;this._dialog=t.session,t.session.delegate={onPrack:i=>{o=i,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(o).then((i=>{try{c=o.accept({statusCode:200,body:i}),this.prackArrived(),e({prackRequest:o,prackResponse:c,progressResponse:t})}catch(e){a(e)}})).catch((e=>a(e))))}};const d=setTimeout((()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then((()=>a(new In))).catch((e=>a(e))))}),64*or.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:n,extraHeaders:r,body:s})}catch(e){return this.waitingForPrack=!1,void a(e)}u=setTimeout(l,h*=2)};let h=or.T1,u=setTimeout(l,h)})).catch((e=>{this.waitingForPrack=!1,a(e)}))}))}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t})),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new In),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class yr extends gr{constructor(e,t,i={}){super(e,i),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:this.earlyMedia,this.fromTag=Kn(),this.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},i);n.params=Object.assign({},i.params);const r=i.anonymous||!1,s=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let a=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(a="string"==typeof n.params.fromUri?Un.URIParse(n.params.fromUri):n.params.fromUri),!a)throw new TypeError("Invalid from URI: "+n.params.fromUri);let o=t;if(n.params.toUri&&(o="string"==typeof n.params.toUri?Un.URIParse(n.params.toUri):n.params.toUri),!o)throw new TypeError("Invalid to URI: "+n.params.toUri);const c=Object.assign({},n.params);c.fromTag=this.fromTag;const d=(n.extraHeaders||[]).slice();r&&e.configuration.uri&&(d.push("P-Preferred-Identity: "+e.configuration.uri.toString()),d.push("Privacy: id")),d.push("Contact: "+s),d.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===fr.Required&&d.push("Require: 100rel"),e.configuration.sipExtensionReplaces===fr.Required&&d.push("Require: replaces"),n.extraHeaders=d;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(dr.INVITE,t,a,o,c,d,undefined),this._contact=s,this._referralInviterOptions=n,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case mi.Initial:case mi.Establishing:return this.cancel().then((()=>super.dispose()));case mi.Established:case mi.Terminating:case mi.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==mi.Initial&&this.state!==mi.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(mi.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Gn(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(mi.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==mi.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(mi.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then((t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(mi.Establishing),this.sendInvite(e)))).catch((e=>{throw this.logger.log(e.message),this.state!==mi.Terminated&&this.stateTransition(mi.Terminated),e}))}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(mi.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then((()=>{this.disposeEarlyMedia()})).catch((()=>{this.disposeEarlyMedia()})).then((()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)}))),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch((()=>{this.disposeEarlyMedia()})).then((()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)})))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach((e=>{e.close()})),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof gr))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==mi.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,i=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Un.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),i.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=i,i.signalingState){case rr.Initial:case rr.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(mi.Terminated),Promise.reject(new Error("Bad Media Description"));case rr.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then((t=>{e.ack({body:t}),this.stateTransition(mi.Established)})).catch((t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(mi.Terminated),t}))}case rr.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(mi.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(mi.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(mi.Established),Promise.resolve()}const t=i.answer;if(!t)throw new Error("Answer is undefined.");const n={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,n).then((()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(mi.Established)})).catch((t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(mi.Terminated),t}))}case rr.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==mi.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const i=e.message,n=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Un.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));const r=i.getHeader("require"),s=i.getHeader("rseq"),a=!!(r&&r.includes("100rel")&&s?Number(s):void 0),o=[];switch(a&&o.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),n.signalingState){case rr.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:o})),Promise.resolve();case rr.HaveLocalOffer:return a&&e.prack({extraHeaders:o}),Promise.resolve();case rr.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(n.id,r),r.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then((()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers))).then((t=>{const i={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:o,body:i})})).catch((e=>{throw this.stateTransition(mi.Terminated),e}))}case rr.Stable:if(a&&e.prack({extraHeaders:o}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=n;const e=n.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch((e=>{throw this.stateTransition(mi.Terminated),e}))}return Promise.resolve();case rr.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===mi.Establishing||this.state===mi.Terminating?this.stateTransition(mi.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===mi.Establishing||this.state===mi.Terminating?this.stateTransition(mi.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===mi.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class Sr{constructor(e,t,i,n="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let s=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(s="string"==typeof r.params.fromUri?Un.URIParse(r.params.fromUri):r.params.fromUri),!s)throw new TypeError("Invalid from URI: "+r.params.fromUri);let a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?Un.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);const o=r.params?Object.assign({},r.params):{},c=(r.extraHeaders||[]).slice(),d={contentDisposition:"render",contentType:n,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(dr.MESSAGE,t,s,a,o,c,d),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var br,wr,Er,Cr,$r,Tr,_r;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(br=br||(br={}));class xr{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=br.Initial,this._waiting=!1,this._stateEventEmitter=new Nn,this._waitingEventEmitter=new Nn,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},xr.defaultOptions()),{registrar:i}),xr.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===Un.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const n=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,s=this.options.params&&this.options.params.toUri||e.configuration.uri,a=this.options.params||{},o=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(dr.REGISTER,n,r,s,a,o,void 0),this.expires=this.options.expires||xr.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||xr.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))}))),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:xr.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Mn("sip","anonymous","anonymous.invalid"),refreshFrequency:xr.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t)),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise((e=>{const t=()=>{if(!this.waiting&&this._state===br.Registered)return this.stateChange.addListener((()=>{this.terminated(),e()}),{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener((()=>{t()}),{once:!0}):t()})))}register(e={}){if(this.state===br.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new _n("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let i;t.message.hasHeader("expires")&&(i=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let n,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(n=t.message.parseHeader("contact",r),!n)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Hn(n.uri,this.userAgent.contact.pubGruu)){i=Number(n.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(n.uri.user===this.userAgent.contact.uri.user){i=Number(n.getParam("expires"));break}}else if(Hn(n.uri,this.userAgent.contact.uri)){i=Number(n.getParam("expires"));break}n=void 0}if(void 0===n)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===i)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(n.hasParam("temp-gruu")){const e=n.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=Un.URIParse(e.replace(/"/g,"")))}if(n.hasParam("pub-gruu")){const e=n.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Un.URIParse(e.replace(/"/g,"")))}this.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let i=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(i=Number.parseInt(e,void 0))}this._retryAfter=isNaN(i)?void 0:i,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}unregister(e={}){if(this.state===br.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==br.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new _n("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===br.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach((e=>{t+=";"+e})),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout((()=>{this.registrationTimer=void 0,this.register()}),this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout((()=>{this.logger.warn("Registration expired"),this.unregistered()}),1e3*e),this._state!==br.Registered&&this.stateTransition(br.Registered)}unregistered(){this.clearTimers(),this._state!==br.Unregistered&&this.stateTransition(br.Unregistered)}terminated(){this.clearTimers(),this._state!==br.Terminated&&this.stateTransition(br.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case br.Initial:e!==br.Registered&&e!==br.Unregistered&&e!==br.Terminated&&t();break;case br.Registered:e!==br.Unregistered&&e!==br.Terminated&&t();break;case br.Unregistered:e!==br.Registered&&e!==br.Terminated&&t();break;case br.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===br.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===br.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}xr.defaultExpires=600,xr.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(wr=wr||(wr={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(Er=Er||(Er={})),function(e){e.Started="Started",e.Stopped="Stopped"}(Cr=Cr||(Cr={}));class Ir{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=Ir.hexChars,i=Ir.hexOut;let n,r,s,a;for(a=0;a<4;a+=1)for(r=8*a,n=e[a],s=0;s<8;s+=2)i[r+1+s]=t.charAt(15&n),n>>>=4,i[r+0+s]=t.charAt(15&n),n>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],n=e[1],r=e[2],s=e[3];i+=(n&r|~n&s)+t[0]-680876936|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[1]-389564586|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[2]+606105819|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[3]-1044525330|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[4]-176418897|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[5]+1200080426|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[6]-1473231341|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[7]-45705983|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[8]+1770035416|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[9]-1958414417|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[10]-42063|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[11]-1990404162|0,n=(n<<22|n>>>10)+r|0,i+=(n&r|~n&s)+t[12]+1804603682|0,i=(i<<7|i>>>25)+n|0,s+=(i&n|~i&r)+t[13]-40341101|0,s=(s<<12|s>>>20)+i|0,r+=(s&i|~s&n)+t[14]-1502002290|0,r=(r<<17|r>>>15)+s|0,n+=(r&s|~r&i)+t[15]+1236535329|0,n=(n<<22|n>>>10)+r|0,i+=(n&s|r&~s)+t[1]-165796510|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[6]-1069501632|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[11]+643717713|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[0]-373897302|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[5]-701558691|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[10]+38016083|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[15]-660478335|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[4]-405537848|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[9]+568446438|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[14]-1019803690|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[3]-187363961|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[8]+1163531501|0,n=(n<<20|n>>>12)+r|0,i+=(n&s|r&~s)+t[13]-1444681467|0,i=(i<<5|i>>>27)+n|0,s+=(i&r|n&~r)+t[2]-51403784|0,s=(s<<9|s>>>23)+i|0,r+=(s&n|i&~n)+t[7]+1735328473|0,r=(r<<14|r>>>18)+s|0,n+=(r&i|s&~i)+t[12]-1926607734|0,n=(n<<20|n>>>12)+r|0,i+=(n^r^s)+t[5]-378558|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[8]-2022574463|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[11]+1839030562|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[14]-35309556|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[1]-1530992060|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[4]+1272893353|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[7]-155497632|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[10]-1094730640|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[13]+681279174|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[0]-358537222|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[3]-722521979|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[6]+76029189|0,n=(n<<23|n>>>9)+r|0,i+=(n^r^s)+t[9]-640364487|0,i=(i<<4|i>>>28)+n|0,s+=(i^n^r)+t[12]-421815835|0,s=(s<<11|s>>>21)+i|0,r+=(s^i^n)+t[15]+530742520|0,r=(r<<16|r>>>16)+s|0,n+=(r^s^i)+t[2]-995338651|0,n=(n<<23|n>>>9)+r|0,i+=(r^(n|~s))+t[0]-198630844|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[7]+1126891415|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[14]-1416354905|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[5]-57434055|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[12]+1700485571|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[3]-1894986606|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[10]-1051523|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[1]-2054922799|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[8]+1873313359|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[15]-30611744|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[6]-1560198380|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[13]+1309151649|0,n=(n<<21|n>>>11)+r|0,i+=(r^(n|~s))+t[4]-145523070|0,i=(i<<6|i>>>26)+n|0,s+=(n^(i|~r))+t[11]-1120210379|0,s=(s<<10|s>>>22)+i|0,r+=(i^(s|~n))+t[2]+718787259|0,r=(r<<15|r>>>17)+s|0,n+=(s^(r|~i))+t[9]-343485551|0,n=(n<<21|n>>>11)+r|0,e[0]=i+e[0]|0,e[1]=n+e[1]|0,e[2]=r+e[2]|0,e[3]=s+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Ir.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let n,r,s=this._bufferLength;for(r=0;r<e.length;r+=1){if(n=e.charCodeAt(r),n<128)t[s++]=n;else if(n<2048)t[s++]=192+(n>>>6),t[s++]=63&n|128;else if(n<55296||n>56319)t[s++]=224+(n>>>12),t[s++]=n>>>6&63|128,t[s++]=63&n|128;else{if(n=1024*(n-55296)+(e.charCodeAt(++r)-56320)+65536,n>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[s++]=240+(n>>>18),t[s++]=n>>>12&63|128,t[s++]=n>>>6&63|128,t[s++]=63&n|128}s>=64&&(this._dataLength+=64,Ir._md5cycle(this._state,i),s-=64,i[0]=i[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let n,r=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-r);n--;)t[r++]=e.charCodeAt(s++);if(r<64)break;this._dataLength+=64,Ir._md5cycle(this._state,i),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let n,r=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-r);n--;)t[r++]=e[s++];if(r<64)break;this._dataLength+=64,Ir._md5cycle(this._state,i),r=0}return this._bufferLength=r,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,i=e.state,n=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,i=this._buffer8,n=this._buffer32,r=1+(t>>2);let s;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,n.set(Ir.buffer32Identity.subarray(r),r),t>55&&(Ir._md5cycle(this._state,n),n.set(Ir.buffer32Identity)),s=8*this._dataLength,s<=4294967295)n[14]=s;else{const e=s.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),i=parseInt(e[1],16)||0;n[14]=t,n[15]=i}return Ir._md5cycle(this._state,n),e?this._state:Ir._hex(this._state)}}function Rr(e){return Ir.hashStr(e)}Ir.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Ir.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ir.hexChars="0123456789abcdef",Ir.hexOut=[],Ir.onePassHasher=new Ir,"5d41402abc4b2a76b9719d911017c592"!==Ir.hashStr("hello")&&console.error("Md5 self test failed.");class Ar{constructor(e,t,i,n){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=n,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=qn(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,i;t=this.ha1,""!==t&&void 0!==t||(t=Rr(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(i=Rr(this.method+":"+this.uri),this.response=Rr(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):"auth-int"===this.qop?(i=Rr(this.method+":"+this.uri+":"+Rr(e||"")),this.response=Rr(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):void 0===this.qop&&(i=Rr(this.method+":"+this.uri),this.response=Rr(t+":"+this.nonce+":"+i))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}($r=$r||($r={}));class Pr{constructor(e,t,i){this.logger=e,this.category=t,this.label=i}error(e){this.genericLog($r.error,e)}warn(e){this.genericLog($r.warn,e)}log(e){this.genericLog($r.log,e)}debug(e){this.genericLog($r.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class Dr{constructor(){this.builtinEnabled=!0,this._level=$r.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:$r.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new Pr(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Pr(this,e);return this.loggers[e]=t,t}}genericLog(e,t,i,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,n),this.connector&&this.connector($r[e],t,i,n)}print(e,t,i,n){if("string"==typeof n){const e=[new Date,t];i&&e.push(i),n=e.concat(n).join(" | ")}switch(e){case $r.error:console.error(n);break;case $r.warn:console.warn(n);break;case $r.log:console.log(n);break;case $r.debug:console.debug(n)}}}function Nr(e,t){const i="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const n=t.reasonPhrase?t.reasonPhrase:Gn(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+n+i;t.statusCode>=100&&t.statusCode,t.statusCode;const s="From: "+e.getHeader("From")+i,a="Call-ID: "+e.callId+i,o="CSeq: "+e.cseq+" "+e.method+i,c=e.getHeaders("via").reduce(((e,t)=>e+"Via: "+t+i),"");let d="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Kn()),d+=";tag="+e}d+=i;let l="";t.supported&&(l="Supported: "+t.supported.join(", ")+i);let h="";t.userAgent&&(h="User-Agent: "+t.userAgent+i);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce(((e,t)=>e+t.trim()+i),"")),r+=c,r+=s,r+=d,r+=o,r+=a,r+=l,r+=h,r+=u,t.body?(r+="Content-Type: "+t.body.contentType+i,r+="Content-Length: "+zn(t.body.content)+i+i,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let i=t,n=0,r=0;if(e.substring(i,i+2).match(/(^\r\n)/))return-2;for(;0===n;){if(r=e.indexOf("\r\n",i),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?i=r+2:n=r}return n}function i(e,t,i,n){const r=t.indexOf(":",i),s=t.substring(i,r).trim(),a=t.substring(r+1,n).trim();let o;switch(s.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(o=e.parseHeader("Via"),o&&(e.via=o,e.viaBranch=o.branch)):o=0;break;case"from":case"f":e.setHeader("from",a),o=e.parseHeader("from"),o&&(e.from=o,e.fromTag=o.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),o=e.parseHeader("to"),o&&(e.to=o,e.toTag=o.getParam("tag"));break;case"record-route":if(o=Un.parse(a,"Record_Route"),-1===o){o=void 0;break}if(!(o instanceof Array)){o=void 0;break}o.forEach((t=>{e.addHeader("record-route",a.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed}));break;case"call-id":case"i":e.setHeader("call-id",a),o=e.parseHeader("call-id"),o&&(e.callId=a);break;case"contact":case"m":if(o=Un.parse(a,"Contact"),-1===o){o=void 0;break}if(!(o instanceof Array)){o=void 0;break}o.forEach((t=>{e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed}));break;case"content-length":case"l":e.setHeader("content-length",a),o=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),o=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),o=e.parseHeader("cseq"),o&&(e.cseq=o.value),e instanceof Zn&&(e.method=o.method);break;case"max-forwards":e.setHeader("max-forwards",a),o=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),o=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),o=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),o=e.parseHeader("refer-to"),o&&(e.referTo=o);break;default:e.addHeader(s.toLowerCase(),a),o=0}return void 0!==o||{error:"error parsing header '"+s+"'"}}e.getHeader=t,e.parseHeader=i,e.parseMessage=function(e,n){let r=0,s=e.indexOf("\r\n");if(-1===s)return void n.warn("no CRLF found, not a SIP message, discarded");const a=e.substring(0,s),o=Un.parse(a,"Request_Response");let c,d;if(-1!==o){for(o.status_code?(c=new Zn,c.statusCode=o.status_code,c.reasonPhrase=o.reason_phrase):(c=new Jn,c.method=o.method,c.ruri=o.uri),c.data=e,r=s+2;;){if(s=t(e,r),-2===s){d=r+2;break}if(-1===s)return void n.error("malformed message");const a=i(c,e,r,s);if(a&&!0!==a)return void n.error(a.error);r=s+2}return c.hasHeader("content-length")?c.body=e.substr(d,Number(c.getHeader("content-length"))):c.body=e.substring(d),c}n.warn('error parsing first line of SIP message: "'+a+'"')}}(Tr=Tr||(Tr={}));class kr extends $n{constructor(e){super(e||"Unspecified transport error.")}}class Or{constructor(e,t,i,n,r){this._transport=e,this._user=t,this._id=i,this._state=n,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,i),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const i=()=>{this.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach((e=>e()))}removeStateChangeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch((e=>{if(e instanceof kr)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new kr(e.message):new kr,this.onTransportError(t),t}))}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Fr extends Or{constructor(e,t,i,n,r){super(t,i,e.viaBranch,n,r),this._request=e,this.user=i}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(_r=_r||(_r={}));class Mr extends Fr{constructor(e,t,i){super(e,t,i,_r.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case _r.Proceeding:if(e.method===dr.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case _r.Accepted:if(e.method===dr.INVITE)return;break;case _r.Completed:if(e.method===dr.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of final response.")}))}if(e.method===dr.ACK)return void this.stateTransition(_r.Confirmed);break;case _r.Confirmed:case _r.Terminated:if(e.method===dr.INVITE||e.method===dr.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case _r.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 1xx response.")}));if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(_r.Accepted),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send non-2xx final response.")}));break;case _r.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));break;case _r.Completed:case _r.Confirmed:case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}retransmitAcceptedResponse(){this.state===_r.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}))}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Proceeding:t();break;case _r.Accepted:case _r.Completed:this.state!==_r.Proceeding&&t();break;case _r.Confirmed:this.state!==_r.Completed&&t();break;case _r.Terminated:this.state!==_r.Accepted&&this.state!==_r.Completed&&this.state!==_r.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===_r.Accepted&&(this.L=setTimeout((()=>this.timerL()),or.TIMER_L)),e===_r.Completed&&(this.H=setTimeout((()=>this.timerH()),or.TIMER_H)),e===_r.Confirmed&&(this.I=setTimeout((()=>this.timerI()),or.TIMER_I)),e===_r.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval((()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}))}),or.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===_r.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(_r.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(_r.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===_r.Accepted&&this.stateTransition(_r.Terminated)}}class Hr extends Or{constructor(e,t,i,n,r){super(t,i,Hr.makeId(e),n,r),this._request=e,this.user=i,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class Lr extends Hr{constructor(e,t,i){super(e,t,i,_r.Trying,"sip.transaction.nict"),this.F=setTimeout((()=>this.timerF()),or.TIMER_F),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send initial outgoing request.")}))}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case _r.Trying:if(t>=100&&t<=199)return this.stateTransition(_r.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(_r.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(_r.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Completed:case _r.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Trying:i();break;case _r.Proceeding:this.state!==_r.Trying&&i();break;case _r.Completed:this.state!==_r.Trying&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Trying&&this.state!==_r.Proceeding&&this.state!==_r.Completed&&(t||i());break;default:i()}e===_r.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((()=>this.timerK()),or.TIMER_K)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==_r.Trying&&this.state!==_r.Proceeding||(this.onRequestTimeout(),this.stateTransition(_r.Terminated))}timerK(){this.state===_r.Completed&&this.stateTransition(_r.Terminated)}}class jr{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const i=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const r=n.uri,s=e.cseq,a=e.callId,o=e.fromTag,c=t.toTag;if(!a)throw new Error("Call id undefined.");if(!o)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const d=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+o+c,early:t.statusCode<200,callId:a,localTag:o,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:d,remoteURI:l,remoteTarget:r,routeSet:i,secure:!1}}static initialDialogStateForUserAgentServer(e,t,i=!1){const n=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,a=e.cseq,o=e.callId,c=t,d=e.fromTag,l=e.from.uri;return{id:o+c+d,early:i,callId:o,localTag:c,remoteTag:d,localSequenceNumber:undefined,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:n,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==dr.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const i=this.remoteURI,n=this.remoteTag,r=this.localURI,s=this.localTag,a=this.callId;let o;o=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,d=this.routeSet,l=t&&t.extraHeaders,h=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,i,{callId:a,cseq:o,fromTag:s,toTag:n,routeSet:d},l,h)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===dr.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Br extends Hr{constructor(e,t,i){super(e,t,i,_r.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout((()=>this.timerB()),or.TIMER_B),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send initial outgoing request.")}))}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch((e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")}))}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case _r.Calling:if(t>=100&&t<=199)return this.stateTransition(_r.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(_r.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(_r.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(_r.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(_r.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case _r.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch((e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")})):void 0}break;case _r.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,i=this.request.callId,n=this.request.cseq,r=this.request.getHeader("from"),s=e.getHeader("to"),a=this.request.getHeader("via"),o=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;o&&(c+=`Route: ${o}\r\n`),c+=`Via: ${a}\r\n`,c+=`To: ${s}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${i}\r\n`,c+=`CSeq: ${n} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch((e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")}))}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Calling:i();break;case _r.Proceeding:this.state!==_r.Calling&&i();break;case _r.Accepted:case _r.Completed:this.state!==_r.Calling&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Calling&&this.state!==_r.Accepted&&this.state!==_r.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),_r.Proceeding,e===_r.Completed&&(this.D=setTimeout((()=>this.timerD()),or.TIMER_D)),e===_r.Accepted&&(this.M=setTimeout((()=>this.timerM()),or.TIMER_M)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===_r.Calling&&(this.onRequestTimeout(),this.stateTransition(_r.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===_r.Completed&&this.stateTransition(_r.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===_r.Accepted&&this.stateTransition(_r.Terminated)}}class Ur{constructor(e,t,i,n){this.transactionConstructor=e,this.core=t,this.message=i,this.delegate=n,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const i=this.core.makeOutgoingRequestMessage(dr.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),e&&i.setHeader("Reason",e),this.transaction.state===_r.Proceeding?new Ur(Lr,this.core,i):this.transaction.addStateChangeListener((()=>{this.transaction&&this.transaction.state===_r.Proceeding&&new Ur(Lr,this.core,i)}),{once:!0}),i}authenticationGuard(e,t){const i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;let n,r;if(401===i?(n=e.parseHeader("www-authenticate"),r="authorization"):(n=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);let s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new Zn;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new Zn;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===_r.Terminated&&(this.core.userAgentClients.delete(i),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id+t.request.method;this.core.userAgentClients.set(i,this)}}class Vr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.BYE,i);super(Lr,e.userAgentCore,n,t),e.dispose()}}class qr extends Fr{constructor(e,t,i){super(e,t,i,_r.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case _r.Trying:break;case _r.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case _r.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of final response.")}));break;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case _r.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(_r.Proceeding),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case _r.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(_r.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case _r.Completed:return;case _r.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(_r.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case _r.Trying:i();break;case _r.Proceeding:this.state!==_r.Trying&&i();break;case _r.Completed:this.state!==_r.Trying&&this.state!==_r.Proceeding&&i();break;case _r.Terminated:this.state!==_r.Proceeding&&this.state!==_r.Completed&&(t||i());break;default:i()}e===_r.Completed&&(this.J=setTimeout((()=>this.timerJ()),or.TIMER_J)),e===_r.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===_r.Completed&&this.stateTransition(_r.Terminated)}}class Gr{constructor(e,t,i,n){this.transactionConstructor=e,this.core=t,this.message=i,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=i.toTag?i.toTag:Kn(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new cr(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new cr(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new cr(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const i=t.statusCode;if(i<300||i>399)throw new TypeError(`Invalid statusCode: ${i}`);const n=new Array;e.forEach((e=>n.push(`Contact: ${e.toString()}`))),t.extraHeaders=(t.extraHeaders||[]).concat(n);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new cr(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new cr(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding||this.transaction.state===_r.Accepted;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying||this.transaction.state===_r.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Mr)return this.transaction.state===_r.Proceeding;if(this.transaction instanceof qr)return this.transaction.state===_r.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=Nr(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===_r.Terminated&&(this.core.userAgentServers.delete(i),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id;this.core.userAgentServers.set(t.id,this)}}class Kr extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i)}}class Wr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.INFO,i);super(Lr,e.userAgentCore,n,t)}}class zr extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i)}}class Yr extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class Jr extends Gr{constructor(e,t,i){super(qr,e,t,i)}}class Zr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.NOTIFY,i);super(Lr,e.userAgentCore,n,t)}}class Xr extends Gr{constructor(e,t,i){const n=void 0!==e.userAgentCore?e.userAgentCore:e;super(qr,n,t,i)}}class Qr extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.PRACK,i);super(Lr,e.userAgentCore,n,t),e.signalingStateTransition(n)}}class es extends Gr{constructor(e,t,i){super(qr,e.userAgentCore,t,i),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class ts extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.INVITE,i);super(Br,e.userAgentCore,n,t),this.delegate=t,e.signalingStateTransition(n),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class is extends Gr{constructor(e,t,i){super(Mr,e.userAgentCore,t,i),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map((e=>`Record-Route: ${e}`)));const t=super.accept(e),i=this.dialog,n=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),n}progress(e={statusCode:180}){const t=super.progress(e),i=this.dialog,n=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class ns extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.REFER,i);super(Lr,e.userAgentCore,n,t)}}class rs extends Gr{constructor(e,t,i){const n=void 0!==e.userAgentCore?e.userAgentCore:e;super(qr,n,t,i)}}class ss extends jr{constructor(e,t,i,n){super(t,i),this.initialTransaction=e,this._signalingState=rr.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=n,e instanceof Mr&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=rr.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?nr.Early:this.ackWait?nr.AckWait:this._signalingState===rr.Closed?nr.Terminated:nr.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Br))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const i=this.createOutgoingRequestMessage(dr.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(i),this.signalingStateTransition(i),{message:i}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Mr){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==_r.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new Vr(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Wr(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new ts(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const i=this.createOutgoingRequestMessage(dr.MESSAGE,t);return new Yr(this.core,i,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Zr(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Qr(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new ns(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==dr.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===dr.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},i=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.ackWait&&this.signalingState!==rr.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:i});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===dr.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case dr.BYE:{const t=new Kr(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case dr.INFO:{const t=new zr(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case dr.INVITE:{const t=new is(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case dr.MESSAGE:{const t=new Jr(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case dr.NOTIFY:{const t=new Xr(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case dr.PRACK:{const t=new es(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case dr.REFER:{const t=new rs(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Br)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then((()=>this.ackProcessing=!1)).catch((()=>this.ackProcessing=!1)))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),i=e.getHeader("rseq"),n=t&&t.includes("100rel")&&i?Number(i):void 0;if(n){if(this.rseq&&this.rseq+1!==n)return!1;this.rseq=this.rseq?this.rseq+1:n}}return!0}signalingStateRollback(){this._signalingState!==rr.HaveLocalOffer&&this.signalingState!==rr.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=rr.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=ir(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===rr.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Jn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.HaveRemoteOffer:case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Zn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.HaveRemoteOffer:case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Xn)switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:break;case rr.HaveRemoteOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}if(tr(e))switch(this._signalingState){case rr.Initial:case rr.Stable:this._signalingState=rr.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case rr.HaveLocalOffer:break;case rr.HaveRemoteOffer:this._signalingState=rr.Stable,this._answer=t;break;case rr.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Mr){const e=this.initialTransaction;let t=or.T1;const i=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,or.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const n=()=>{e.state===_r.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(n)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Mr){const e=this.reinviteUserAgentServer.transaction;let t=or.T1;const i=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,or.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const n=()=>{e.state===_r.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(n)}}}class as extends Ur{constructor(e,t,i){super(Br,e,t,i),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=i}dispose(){this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===_r.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=jr.initialDialogStateForUserAgentClient(this.message,e);let i=this.earlyDialogs.get(t.id);if(!i){const e=this.transaction;if(!(e instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");i=new ss(e,this.core,t),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");i.signalingState!==rr.Initial&&i.signalingState!==rr.HaveLocalOffer||i.signalingStateTransition(e);const n=i;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:n,prack:e=>n.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=jr.initialDialogStateForUserAgentClient(this.message,e);let i=this.confirmedDialogs.get(t.id);if(i){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Br))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(i=this.earlyDialogs.get(t.id),i)i.confirm(),i.recomputeRouteSet(e),this.earlyDialogs.delete(i.id),this.confirmedDialogs.set(i.id,i);else{const e=this.transaction;if(!(e instanceof Br))throw new Error("Transaction not instance of InviteClientTransaction.");i=new ss(e,this.core,t),this.confirmedDialogs.set(i.id,i)}i.signalingState!==rr.Initial&&i.signalingState!==rr.HaveLocalOffer||i.signalingStateTransition(e);const n=i;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:n,ack:e=>{const t=n.ack(e);return this.confirmedDialogAcks.set(n.id,t),t}});else{const e=n.ack();this.confirmedDialogAcks.set(n.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class os extends Gr{constructor(e,t,i){super(Mr,e,t,i),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new cr(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Mr))throw new Error("Transaction not instance of InviteClientTransaction.");const t=jr.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new ss(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),i=`Contact: ${this.core.configuration.contact.toString()}`,n="Allow: "+lr.toString();if(!e.body)if(this.confirmedDialog.signalingState===rr.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===rr.Initial||this.confirmedDialog.signalingState===rr.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(n),e.extraHeaders.push(i);const r=super.accept(e),s=this.confirmedDialog,a=Object.assign(Object.assign({},r),{session:s});return e.body&&this.confirmedDialog.signalingState!==rr.Stable&&this.confirmedDialog.signalingStateTransition(e.body),a}progress(e={statusCode:180}){if(!this.progressable)throw new cr(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Mr))throw new Error("Transaction not instance of InviteClientTransaction.");const t=jr.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new ss(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),i=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i);const n=super.progress(e),r=this.earlyDialog,s=Object.assign(Object.assign({},n),{session:r});return e.body&&this.earlyDialog.signalingState!==rr.Stable&&this.earlyDialog.signalingStateTransition(e.body),s}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class cs extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class ds extends Ur{constructor(e,t,i){super(Lr,e,t,i)}}class ls extends Gr{constructor(e,t,i){super(qr,e,t,i),this.core=e}}class hs extends Ur{constructor(e,t,i){const n=e.createOutgoingRequestMessage(dr.SUBSCRIBE,i);super(Lr,e.userAgentCore,n,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class us extends jr{constructor(e,t,i,n,r,s){super(n,r),this.delegate=s,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=i,this.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const i=t.getHeaders("record-route"),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof Fn))throw new Error("Contact not instance of NameAddrHeader.");const r=n.uri,s=e.cseq,a=e.callId,o=e.fromTag,c=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!o)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+o+c,early:!1,callId:a,localTag:o,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:i,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===dr.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+lr.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var i;if(this.subscriptionState!==wr.Pending&&this.subscriptionState!==wr.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const n=new hs(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(i=t.extraHeaders)||void 0===i?void 0:i.includes("Expires: 0"))||(this.N=setTimeout((()=>this.timerN()),or.TIMER_N)),n}terminate(){this.stateTransition(wr.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+lr.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const i=e.parseHeader("Subscription-State");if(!i||!i.state)return void this.core.replyStateless(e,{statusCode:489});const n=i.state,r=i.expires?Math.max(i.expires,0):void 0;switch(n){case"pending":this.stateTransition(wr.Pending,r);break;case"active":this.stateTransition(wr.Active,r);break;case"terminated":this.stateTransition(wr.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const s=new Xr(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout((()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())}),e)}}stateTransition(e,t){const i=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case wr.Initial:case wr.NotifyWait:return void i();case wr.Pending:if(this.subscriptionState!==wr.NotifyWait&&this.subscriptionState!==wr.Pending)return void i();break;case wr.Active:case wr.Terminated:if(this.subscriptionState!==wr.NotifyWait&&this.subscriptionState!==wr.Pending&&this.subscriptionState!==wr.Active)return void i();break;default:return void i()}e===wr.Pending&&t&&(this.subscriptionExpires=t),e===wr.Active&&t&&(this.subscriptionExpires=t),e===wr.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==wr.Terminated&&(this.stateTransition(wr.Terminated),this.onTerminated())}}class ps extends Ur{constructor(e,t,i){const n=t.getHeader("Event");if(!n)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(Lr,e,t,i),this.delegate=i,this.subscriberId=t.callId+t.fromTag+n,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=n,this.subscriptionState=wr.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const i=e.message.parseHeader("Subscription-State");if(!i||!i.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=i.state;switch(n){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${n}`),void e.reject({statusCode:489})}if("terminated"!==n){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=i.expires?Math.min(this.subscriptionExpires,Math.max(i.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=wr.Pending;break;case"active":this.subscriptionState=wr.Active;break;case"terminated":this.subscriptionState=wr.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==wr.Terminated){const t=us.initialDialogStateForSubscription(this.message,e.message);this.dialog=new us(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,i=this.dialog;this.delegate.onNotify({request:t,subscription:i})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((()=>this.timerN()),or.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class gs extends Gr{constructor(e,t,i){super(qr,e,t,i),this.core=e}}const fs=["application/sdp","application/dtmf-relay"];class ms{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach((e=>e.dispose())),this.dialogs.clear(),this.subscribers.forEach((e=>e.dispose())),this.subscribers.clear(),this.userAgentClients.forEach((e=>e.dispose())),this.userAgentClients.clear(),this.userAgentServers.forEach((e=>e.dispose())),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new as(this,e,t)}message(e,t){return new Yr(this,e,t)}publish(e,t){return new cs(this,e,t)}register(e,t){return new ds(this,e,t)}subscribe(e,t){return new ps(this,e,t)}request(e,t){return new Ur(Lr,this,e,t)}makeOutgoingRequestMessage(e,t,i,n,r,s,a){const o=this.configuration.sipjsId,c=this.configuration.displayName,d=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===dr.REGISTER&&h.push("path","gruu"),e===dr.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");const u={callIdPrefix:o,forceRport:d,fromDisplayName:c,hackViaTcp:l,optionTags:h,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},p=Object.assign(Object.assign({},u),r);return new Xn(e,t,i,n,p,s,a)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const i=this.configuration.userAgentHeaderFieldValue,n=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:i,supported:n});const r=Nr(e,t);return this.transport.send(r.message).catch((t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)})),r}receiveRequestFromTransport(e){const t=e.viaBranch,i=this.userAgentServers.get(t);e.method===dr.ACK&&i&&i.transaction.state===_r.Accepted&&i instanceof os?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==dr.CANCEL?i?i.transaction.receiveRequest(e):this.receiveRequest(e):i?(this.replyStateless(e,{statusCode:200}),i.transaction instanceof Mr&&i.transaction.state===_r.Proceeding&&i instanceof os&&i.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!lr.includes(e.method)){const t="Allow: "+lr.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,i=e=>!!e&&e.user===t.user;if(!i(this.configuration.aor)&&!(i(this.configuration.contact.uri)||i(this.configuration.contact.pubGruu)||i(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==dr.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==dr.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some((t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq)))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===dr.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const i=e.callId+e.toTag+t.event,n=this.subscribers.get(i);if(n){const t=new Xr(this,e);return void n.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,i=this.dialogs.get(t);if(i){if(e.method===dr.OPTIONS){const t="Allow: "+lr.toString(),i="Accept: "+fs.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}i.receiveRequest(e)}else e.method!==dr.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case dr.ACK:break;case dr.BYE:this.replyStateless(e,{statusCode:481});break;case dr.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case dr.INFO:this.replyStateless(e,{statusCode:405});break;case dr.INVITE:{const t=new os(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case dr.MESSAGE:{const t=new Jr(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case dr.NOTIFY:{const t=new Xr(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case dr.OPTIONS:{const t="Allow: "+lr.toString(),i="Accept: "+fs.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}break;case dr.REFER:{const t=new rs(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case dr.REGISTER:{const t=new ls(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case dr.SUBSCRIBE:{const t=new gs(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,i=this.userAgentClients.get(t);i?i.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class vs{constructor(e,t,i){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=i,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==i?void 0:i.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach((e=>{e.track&&e.track.stop()})),this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.stop()})),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach((t=>{t.track&&(t.track.enabled=e)}))}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach((t=>{t.track&&(t.track.enabled=e)}))}getDescription(e,t){var i,n;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(i=null==e?void 0:e.offerOptions)||void 0===i?void 0:i.iceRestart,s=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(n=this.sessionDescriptionHandlerConfiguration)||void 0===n?void 0:n.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then((()=>this.updateDirection(e))).then((()=>this.createDataChannel(e))).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.applyModifiers(e,t))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(r,s))).then((()=>this.getLocalSessionDescription())).then((e=>({body:e.sdp,contentType:"application/sdp"}))).catch((e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e}))}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const i=this._peerConnection.getSenders();if(0===i.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const n=i[0].dtmf;if(!n)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{n.insertDTMF(e,r,s)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,i){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const n="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then((()=>this.applyModifiers({sdp:e,type:n},i))).then((e=>this.setRemoteSessionDescription(e))).catch((e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e}))}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)).then((e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}})):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then((e=>this.setLocalMediaStream(e)))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,i=this._localMediaStream,n=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const s=t.getSenders().find((e=>e.track&&e.track.kind===r));s?n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()})).then((()=>s.replaceTrack(e).then((()=>{const t=i.getTracks().find((e=>e.kind===r));t&&(t.stop(),i.removeTrack(t),vs.dispatchRemoveTrackEvent(i,t)),i.addTrack(e),vs.dispatchAddTrackEvent(i,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))))):n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()})).then((()=>{try{t.addTrack(e,i)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}i.addTrack(e),vs.dispatchAddTrackEvent(i,e)})))},s=e.getAudioTracks();s.length&&r(s[0]);const a=e.getVideoTracks();return a.length&&r(a[0]),n.reduce(((e,t)=>e.then((()=>t))),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let i;switch(this._peerConnection.signalingState){case"stable":i="offer";break;case"have-local-offer":i="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:i}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach((e=>{e.stop(),t.removeTrack(e),vs.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),vs.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach((e=>{e.stop(),t.removeTrack(e),vs.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),vs.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach((e=>{if(e.direction){const i=t(e.direction);e.direction!==i&&(e.direction=i)}}))}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),i=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach((e=>{e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)}))}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise(((e,i)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=i,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout((()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()}),t))})),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var i;const n=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var i;const n=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var i;const n=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${n}`),"complete"===n&&this.iceGatheringComplete(),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var i;const n=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${n}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const i=e.track.kind,n=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${i} ${n}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function ys(e){return(t,i)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const n={iceGatheringTimeout:void 0!==(null==i?void 0:i.iceGatheringTimeout)?null==i?void 0:i.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==i?void 0:i.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new vs(r,e,n)}}class Ss{constructor(e,t){if(this._state=Er.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new Nn,this.logger=e,t){const e=t,i=null==e?void 0:e.wsServers,n=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==i){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==n){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}i&&!t.server&&("string"==typeof i&&(t.server=i),i instanceof Array&&(t.server=i[0]))}this.configuration=Object.assign(Object.assign({},Ss.defaultOptions),t);const i=this.configuration.server,n=Un.parse(i,"absoluteURI");if(-1===n)throw this.logger.error(`Invalid WebSocket Server URL "${i}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(n.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${i}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=n.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===Er.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case Er.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case Er.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case Er.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Er.Connecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(Er.Connecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",(t=>this.onWebSocketClose(t,e))),e.addEventListener("error",(t=>this.onWebSocketError(t,e))),e.addEventListener("open",(t=>this.onWebSocketOpen(t,e))),e.addEventListener("message",(t=>this.onWebSocketMessage(t,e))),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise(((t,i)=>{this.connectResolve=t,this.connectReject=i,this.transitionState(Er.Disconnected,e)}))}return this.connectPromise=new Promise(((t,i)=>{this.connectResolve=t,this.connectReject=i,this.connectTimeout=setTimeout((()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)}),1e3*this.configuration.connectionTimeout)})),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case Er.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Er.Disconnecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(Er.Disconnecting)}catch(e){if(e instanceof Rn)return Promise.reject(e);throw e}break;case Er.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case Er.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(Er.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise(((t,i)=>{this.disconnectResolve=t,this.disconnectReject=i;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}})),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==Er.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const i=`WebSocket closed ${this.server} (code: ${e.code})`,n=this.disconnectPromise?void 0:new Error(i);n&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(i),this._ws=void 0,this.transitionState(Er.Disconnected,n)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const i=e.data;let n;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{n=(new TextDecoder).decode(new Uint8Array(i))}catch(e){return this.logger.error(e.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+n+"\n")}else n=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===Er.Connected){if(this.onMessage)try{this.onMessage(n)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===Er.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(Er.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new Rn("Loop detected.")}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case Er.Connecting:e!==Er.Connected&&e!==Er.Disconnecting&&e!==Er.Disconnected&&i();break;case Er.Connected:e!==Er.Disconnecting&&e!==Er.Disconnected&&i();break;case Er.Disconnecting:e!==Er.Connecting&&e!==Er.Disconnected&&i();break;case Er.Disconnected:e!==Er.Connecting&&i();break;default:throw new Error("Unknown state.")}const n=this._state;this._state=e;const r=this.connectResolve,s=this.connectReject;n===Er.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,o=this.disconnectReject;if(n===Er.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${n} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===Er.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(n===Er.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(n===Er.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!s)throw new Error("Connect reject undefined.");e===Er.Connected?r():s(t||new Error("Connect aborted."))}if(n===Er.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!o)throw new Error("Disconnect reject undefined.");e===Er.Disconnected?a():o(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout((()=>{this.clearKeepAliveTimeout()}),1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval((()=>{this.sendKeepAlive(),this.startSendingKeepAlives()}),(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Ss.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class bs{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=Cr.Stopped,this._stateEventEmitter=new Nn,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},bs.defaultOptions()),{sipjsId:qn(5)}),{uri:new Mn("sip","anonymous."+qn(6),"anonymous.invalid")}),{viaHost:qn(12)+".invalid"}),bs.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,i=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Dr,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=$r.error;break;case"warn":this.loggerFactory.level=$r.warn;break;case"log":this.loggerFactory.level=$r.log;break;case"debug":this.loggerFactory.level=$r.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach((e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}}))),this.options.transportOptions){const t=this.options.transportOptions,i=t.maxReconnectionAttempts,n=t.reconnectionTimeout;if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==n){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==n&&(this.options.reconnectionDelay=n),void 0===e.reconnectionAttempts&&void 0!==i&&(this.options.reconnectionAttempts=i)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:bs.newUUID(),-1===Un.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Un.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:ys(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:fr.Unsupported,sipExtensionReplaces:fr.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Ss,transportOptions:{},uri:new Mn("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)}))}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t)),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===Cr.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then((()=>this.transport.connect()))}start(){return this.state===Cr.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(Cr.Started),this.transport.connect())}async stop(){if(this.state===Cr.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(Cr.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),i=Object.assign({},this._sessions),n=Object.assign({},this._subscriptions),r=this.transport,s=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._registerers[e],t}));this.logger.log("Dispose of sessions");for(const e in i)i[e]&&await i[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._sessions[e],t}));this.logger.log("Dispose of subscriptions");for(const e in n)n[e]&&await n[e].dispose().catch((t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t}));this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch((e=>{throw this.logger.error(e.message),delete this._publishers[t],e}));this.logger.log("Dispose of transport"),await r.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),s.dispose(),this.transitionState(Cr.Stopped)}_makeInviter(e,t){return new yr(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout((()=>{this.reconnect().then((()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)})).catch((i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)}))}),1===e?0:1e3*i))}initContact(){const e=""!==this.options.contactName?this.options.contactName:qn(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Mn("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const i=e.anonymous||!1,n=e.outbound||!1,r=e.register||!1;let s="<";return s+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,n&&(s+=";ob"),s+=">",this.options.instanceIdAlwaysAdded&&(s+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),s}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===fr.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===fr.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter((e=>mr[e]))),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,i=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new Ar(this.getLoggerFactory(),i,e,t)},transportAccessor:()=>this.transport};return new ms(i,{onInvite:e=>{var t;const i=new vr(this,e);if(e.delegate={onCancel:e=>{i._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==fr.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const n=t.replaces_to_tag;if("string"!=typeof n)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const s=e+n+r,a=this.userAgentCore.dialogs.get(s);if(!a)return void i.reject({statusCode:481});if(!a.early&&!0===t.early_only)return void i.reject({statusCode:486});const o=this._sessions[e+r]||this._sessions[e+n]||void 0;if(!o)throw new Error("Session does not exist.");i._replacee=o}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then((()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(i)})):void this.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new hr(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new ur(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==Cr.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==Cr.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=Tr.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===Cr.Stopped&&t instanceof Jn)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const i=()=>{const e=["from","to","call_id","cseq","via"];for(const i of e)if(!t.hasHeader(i))return this.logger.warn(`Missing mandatory header field : ${i}.`),!1;return!0};if(t instanceof Jn){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=zn(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof Zn){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=zn(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof Jn)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof Zn))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case Cr.Started:e!==Cr.Stopped&&i();break;case Cr.Stopped:e!==Cr.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}const ws="onUserAgent",Es="onRegistered",Cs="onUnRegistered",$s="onProgress",Ts="onCallAccepted",_s="onCallAnswered",xs="onCallIncoming",Is="onCallOutgoing",Rs="onCallMuted",As="onCallUnmuted",Ps="onCallResumed",Ds="onCallHeld",Ns="onCallUnHeld",ks="onCameraDisabled",Os="onCameraResumed",Fs="onCallCanceled",Ms="onCallFailed",Hs="onCallRejected",Ls="onCallEnded",js="onCallEnding",Bs="onMessage",Us="reinvite",Vs="onTrack",qs="onAudioStream",Gs="onVideoStream",Ks="onRemoveStream",Ws="onScreenShareStarted",zs="onScreenShareEnding",Ys="onScreenShareEnded",Js="terminateSound",Zs="playRingingSound",Xs="playInboundCallSignalSound",Qs="playHangupSound",ea="playProgressSound",ta="videoInputChange",ia="onCallError",na="onTrackUpdated",ra="onNetworkStats",sa="phone/ON_CHAT",aa="phone/ON_SIGNAL",oa="onDisconnected",ca="onEarlyMedia",da="message/TYPE_CHAT",la="message/TYPE_SIGNAL",ha=[ws,Es,Cs,$s,Ts,_s,xs,Is,Rs,As,Ps,Ds,Ns,ks,Ms,Ls,Hs,Bs,Us,Vs,qs,Gs,Ks,Ys,Js,Zs,Xs,Qs,ea,ta,Ws,ia,sa,aa,ra,oa,ca],ua=B.loggerFor("webrtc-phone");class pa extends Fi{client;allowVideo;callSessions;incomingSessions;currentSipSession;currentCallSession;audioOutputDeviceId;audioRingDeviceId;audioOutputVolume;audioRingVolume;ringingEnabled;acceptedSessions;rejectedSessions;ignoredSessions;currentScreenShare;lastScreenShare;shouldSendReinvite;constructor(e,t,i=!1,n){super(),this.client=e,this.allowVideo=i,this.callSessions={},this.audioOutputDeviceId=t,this.audioRingDeviceId=n||t,this.audioOutputVolume=1,this.audioRingVolume=1,this.incomingSessions=[],this.ringingEnabled=!0,this.shouldSendReinvite=!1,this.bindClientEvents(),this.acceptedSessions={},this.rejectedSessions={},this.ignoredSessions={}}register(){return ua.info("WebRTC register",{client:!!this.client}),this.client?this.client.register().then((()=>(ua.info("WebRTC register, registered"),this.bindClientEvents()))).catch((e=>{console.error("register error",e,e.message,e.stack),ua.error("WebRTC register error",{message:e.message,stack:e.stack})})):Promise.resolve()}unregister(){return this.client&&this.client.isRegistered()?this.client.unregister():null}stop(){this.client&&(ua.info("WebRTC phone stop"),this.client.stop())}removeIncomingSessions(e){this.incomingSessions=this.incomingSessions.filter((t=>t!==e))}isWebRTC(){return!0}async sendReinvite(e,t=null,i=!1,n=!1,r=!1){const s=this.findSipSession(e);if(ua.info("WebRTC phone - send reinvite",{sessionId:s?s.id:null,constraints:t,audioOnly:n,conference:i,iceRestart:r}),!s)return;const a=t?.screen,o=a||t?.video;if(!t||o){if(o){if(!await this._upgradeToVideo(e,t,i))return}return this.client.reinvite(s,t,i,n,r)}this._downgradeToAudio(e)}getUserAgent(){return this.client?.config?.userAgentString||"webrtc-phone"}startHeartbeat(){ua.info("WebRTC phone - start heartbeat",{client:!!this.client,hasHeartbeat:this.client.hasHeartbeat()}),this.client&&!this.client.hasHeartbeat()&&this.client.startHeartbeat()}stopHeartbeat(){ua.info("WebRTC phone - stopHeartbeat",{client:!!this.client}),this.client&&this.client.stopHeartbeat()}setOnHeartbeatTimeout(e){this.client.setOnHeartbeatTimeout(e)}setOnHeartbeatCallback(e){this.client.setOnHeartbeatCallback(e)}reconnect(){ua.info("WebRTC phone - reconnect",{client:!!this.client}),this.client&&this.client.attemptReconnection()}getOptions(){return{accept:!0,decline:!0,mute:!0,hold:!0,transfer:!0,sendKey:!0,addParticipant:!1,record:!0,merge:!0}}onConnect(){return this.client?this.client.onConnect():Promise.reject(new Error("No webrtc client"))}onDisconnect(){return this.client?this.client.onDisconnect():Promise.reject(new Error("No webrtc client"))}_downgradeToAudio(e,t=!0){const i=this.findSipSession(e);return!!i&&(ua.info("Downgrade to audio",{id:e?e.getId():null,withMessage:t}),this.client.downgradeToAudio(i),e&&(e.cameraEnabled=!1,this._updateCallSession(e)),t&&this._sendReinviteMessage(e,!1),!0)}async _upgradeToVideo(e,t,i){const n=this.findSipSession(e);if(!n)return Promise.resolve(!1);ua.info("Upgrade to video",{id:e?e.getId():null,constraints:t,isConference:i});const r=t&&!!t.screen,s=t&&t.desktop,a=n.sessionDescriptionHandlerOptionsReInvite,o=a?.audioOnly,c=await this.client.upgradeToVideo(n,t,i);return e&&(e.cameraEnabled=!0,this._updateCallSession(e)),!c||(this._sendReinviteMessage(e,!0),r&&this._onScreenSharing(c,n,e,!1,s),!(!i||!o))}_sendReinviteMessage(e,t){const i=this.findSipSession(e);ua.info("Sending reinvite message",{id:e?e.getId():null,isUpgrade:t}),setTimeout((()=>{this.sendMessage(i,JSON.stringify({type:la,content:{type:na,update:t?"upgrade":"downgrade",sipCallId:i&&this.getSipSessionId(i),callId:e?e.callId:null,number:e?e.number:null,callerNumber:e?e.callerNumber:null}}))}),2500)}_bindEvents(e){const t=this.getSipSessionId(e);if(e instanceof vr){const i=e._onCancel.bind(e);e._onCancel=n=>{ua.trace("on sip session canceled",{callId:n.callId,sipSessionId:t}),i(n);const r=-1!==n.data.indexOf("cause=26")&&-1!==n.data.indexOf("completed elsewhere"),s=this._createCallSession(e);delete this.callSessions[t],this.eventEmitter.emit(Fs,s,r)}}if(e.stateChange.addListener((t=>{switch(t){case mi.Terminating:ua.info("WebRTC phone - call terminating",{sipId:e.id}),this.eventEmitter.emit(js,this._createCallSession(e));break;case mi.Terminated:{ua.info("WebRTC phone - call terminated",{sipId:e.id});const t=this._createCallSession(e);t.endTime=new Date;const i=this._onCallTerminated(e);return this.eventEmitter.emit(Ls,t,i)}}})),!e.sessionDescriptionHandler)return;const i=e.sessionDescriptionHandler.peerConnection;i?(i.ontrack=t=>{const i=t,[n]=i.streams,r=i&&i.track&&i.track.kind;return ua.info("on track stream called on the peer connection",{callId:this.getSipSessionId(e),streamId:n?n.id:null,tracks:n?n.getTracks():null,kind:r}),"audio"===r?this.eventEmitter.emit(qs,n):this.eventEmitter.emit(Gs,n,i.track.id,i,e)},i.onremovestream=e=>{ua.info("on remove stream called on the peer connection",{id:e.stream.id,tracks:e.stream.getTracks()}),this.eventEmitter.emit(Ks,e.stream)}):ua.info("null peer connection")}async startScreenSharing(e,t){ua.info("WebRTC - start screen sharing",{constraints:e,id:t?t.getId():null});const i=await this.client.getStreamFromConstraints(e);if(!i)throw new Error(`Can't create media stream for screensharing with: ${JSON.stringify(e)}`);const n=i.getVideoTracks()[0],r=this.currentSipSession,s=r&&this.client.getPeerConnection(this.getSipSessionId(r)),a=s&&s.getSenders&&s.getSenders().find((e=>e&&e.track&&"video"===e.track.kind)),o=r&&this.client.getLocalStream(this.getSipSessionId(r)),c=o?o.getTracks().find((e=>"video"===e.kind)):null,d=!!c;return c&&o&&(c.enabled=!1,c.stop(),o.removeTrack(c)),o&&o.addTrack(n),a&&a.replaceTrack(n),this._onScreenSharing(i,r,t,d,e.desktop),i}async stopScreenSharing(e=!0,t){if(!this.currentScreenShare)return;ua.info("WebRTC phone - stop screen sharing",{restoreLocalStream:e});let i=null;try{if(this.currentScreenShare.stream&&this.currentScreenShare.stream.getTracks().filter((e=>e.enabled&&"video"===e.kind)).forEach((e=>e.stop())),e){const e=t||this.currentCallSession,n=this.isConference(e),r={audio:!1,video:this.currentScreenShare.hadVideo};this._downgradeToAudio(e,!1),await new Promise((e=>setTimeout(e,500))),i=await this.sendReinvite(e,r,n)}}catch(e){console.warn(e)}const n=this.currentSipSession;return this.eventEmitter.emit(Ys,t&&n?this._createCallSession(n,t,{screensharing:!1}):null),this.currentScreenShare=null,i}_onScreenSharing(e,t,i,n,r){const s=e.getVideoTracks()[0],a=this.getSipSessionId(t),o=this.client.getPeerConnection(a),c=o&&o.getSenders&&o.getSenders().find((e=>e&&e.track&&"video"===e.track.kind));ua.info("WebRTC phone - on screensharing",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),s&&(s.onended=()=>{ua.info("WebRTC phone - on screenshare ended",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),this.eventEmitter.emit(zs,this._createCallSession(t,i))}),this.currentScreenShare={stream:e,hadVideo:n,sender:c,sipSessionId:a,desktop:r},this.client.setLocalMediaStream(this.getSipSessionId(t),e),this.eventEmitter.emit(Ws,this._createCallSession(t,i,{screensharing:!0}),e)}_onCallAccepted(e,t){ua.info("WebRTC phone - on call accepted",{sipId:e.id,cameraEnabled:t});const i=this._createAcceptedCallSession(e,t);this.currentSipSession&&!this.isCurrentCallSipSession(i)&&(ua.info("WebRTC phone - on call accepted with another ongoing call, holding it",{sipId:e.id,cameraEnabled:t}),this.holdSipSession(this.currentSipSession,this.currentCallSession,!0)),this.currentSipSession=e,this.currentCallSession=i,this.eventEmitter.emit(Js,i,"call accepted");const n=this.getSipSessionId(e);return n&&this.removeIncomingSessions(n),i.answerTime=new Date,this._updateCallSession(i),this.eventEmitter.emit(Ts,i,t),i}async changeAudioDevice(e){return ua.info("WebRTC phone - change audio device",{deviceId:e}),this.audioOutputDeviceId=e,this.client.changeAudioOutputDevice(e)}createAudioElementFor(e){return this.client.createAudioElementFor(e)}changeRingDevice(e){ua.info("WebRTC phone - changing ring device",{id:e}),this.audioRingDeviceId=e}changeAudioVolume(e){ua.info("WebRTC phone - changing audio volume",{volume:e}),this.audioOutputVolume=e,this.client.changeAudioOutputVolume(e)}changeRingVolume(e){ua.info("WebRTC phone - changing ring volume",{volume:e}),this.audioRingVolume=e}changeAudioInputDevice(e,t){return ua.info("WebRTC phone - changeAudio input device",{deviceId:e}),this.client.changeAudioInputDevice(e,this.currentSipSession,t)}async changeVideoInputDevice(e){return ua.info("WebRTC phone - change video input device",{deviceId:e}),this.client.changeVideoInputDevice(e,this.currentSipSession)}changeSessionVideoInputDevice(e){return ua.info("WebRTC phone - change session video input device",{deviceId:e}),this.currentSipSession&&this.client.changeSessionVideoInputDevice(e,this.currentSipSession)}_onCallTerminated(e){const t=this.getSipSessionId(e);ua.info("WebRTC phone - on call terminated",{sipId:e.id,sipSessionId:t,ids:Object.keys(this.callSessions)});const i=this._createCallSession(e),n=this.isCurrentCallSipSession(i),r=i.is(this.getIncomingCallSession()),s=n?this.incomingSessions.length:r;r&&setTimeout((()=>{this.eventEmitter.emit(Js,i,"call terminated")}),5),t&&this.removeIncomingSessions(t),delete this.callSessions[t],n&&(this.currentSipSession=void 0,this.currentCallSession=void 0);const a=this.hasIncomingCallSession();if(ua.info("WebRTC phone - check to re-trigger incoming call",{sipId:e.id,shouldRetrigger:s,hasIncomingCallSession:a}),this.client.onCallEnded(e),a&&s){const e=this.getIncomingCallSession();setTimeout((()=>{this.ringingEnabled&&(this.currentCallSession?this.eventEmitter.emit(Xs,this.audioOutputDeviceId,this.audioOutputVolume,e):this.eventEmitter.emit(Zs,this.audioRingDeviceId,this.audioRingVolume,e)),this.eventEmitter.emit(xs,e,e?.cameraEnabled)}),100)}return!(i.getId()in this.ignoredSessions)&&(e.isCanceled||setTimeout((()=>{this.eventEmitter.emit(Qs,this.audioOutputDeviceId,this.audioOutputVolume,i)}),10),n)}setActiveSipSession(e){const t=this.findSipSession(e);t&&(this.currentSipSession=t,this.currentCallSession=e)}hasAnActiveCall(){return!!this.currentSipSession}hasActiveRemoteVideoStream(){const e=this.currentSipSession;if(!e)return!1;const t=e.sessionDescriptionHandler.peerConnection.getRemoteStreams().find((e=>!!e.getVideoTracks().length));return t&&t.getVideoTracks().some((e=>!e.muted))}callCount(){return Object.keys(this.callSessions).length}isCurrentCallSipSession(e){return!!this.currentSipSession&&(this.currentSipSession&&this.getSipSessionId(this.currentSipSession)===e.getId())}hasVideo(e){return this.client.hasVideo(e.getId())}hasAVideoTrack(e){return this.client.hasAVideoTrack(e.getId())}getLocalStreamForCall(e){return ua.warn("WebRTCPhone.getLocalStreamForCall is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}getRemoteStreamForCall(e){return ua.warn("WebRTCPhone.getRemoteStreamForCall is deprecated, use WebRTCPhone.getRemoteStream instead"),this.getRemoteVideoStream(e)}getRemoteStreamsForCall(e){return ua.warn("WebRTCPhone.getRemoteStreamsForCall is deprecated, use WebRTCPhone.getRemoteStreams instead"),this.getRemoteStream(e)}accept(e,t){if(ua.info("WebRTC phone - accept call",{id:e?e.getId():"n/a",cameraEnabled:t}),this.currentSipSession&&!this.isCurrentCallSipSession(e)&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0),!e)return ua.warn("no CallSession to accept."),Promise.resolve(null);const i=this.getSipSessionIdFromCallSession(e);if(i&&!(i in this.callSessions))return ua.warn("Call session already ended or not found, can't accept it.",{sipSessionId:i}),Promise.resolve(null);if(e.getId()in this.acceptedSessions)return ua.warn("CallSession already accepted.",{id:e?e.getId():"n/a"}),Promise.resolve(e.sipCallId);this.shouldSendReinvite=!1,e.answerTime=new Date,this._updateCallSession(e),this.acceptedSessions[e.getId()]=!0,this.eventEmitter.emit(_s,e);const n=this.client.getSipSession(e.getId());if(n)return ua.info("accept call, session found",{sipId:n.id}),this.client.answer(n,!!this.allowVideo&&t).then((()=>e.sipCallId)).catch((t=>{throw ua.error(t),this.endCurrentCall(e),t}));const r="No CallSession found to accept.";return ua.warn(r,{id:e?e.getId():"n/a",ids:this.client.getSipSessionIds()}),e&&this.eventEmitter.emit(ia,new Error(r),e),Promise.resolve(null)}isAccepted(e){return e&&e.getId()in this.acceptedSessions}async reject(e){if(ua.info("reject WebRTC called",{id:e.getId()}),this.eventEmitter.emit(Js,e,"call rejected locally"),!e||e.getId()in this.rejectedSessions)return;this.shouldSendReinvite=!1,this.rejectedSessions[e.getId()]=!0;const t=this.findSipSession(e);t&&(ua.info("WebRTC rejecting",{sipId:t.id}),this.client.hangup(t))}async ignore(e){ua.info("WebRTC ignore",{id:e.getId()}),this.eventEmitter.emit(Js,e,"ignoring call"),this.ignoredSessions[e.getId()]=!0,e.ignore()}atxfer(e){const t=this.findSipSession(e);if(t)return ua.info("WebRTC atxfer",{sipId:t.id}),this.client.atxfer(t)}hold(e,t=!0){ua.info("WebRTC hold",{id:e.getId()});const i=this.findSipSession(e);return i?this.holdSipSession(i,e,t):null}unhold(e,t=!0){return console.warn("Please note that `phone.unhold()` is being deprecated; `phone.resume()` is the preferred method"),this.resume(e,t)}resume(e,t=!0){ua.info("WebRTC resume called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return new Promise(((e,t)=>t(new Error("No session to resume"))));ua.info("WebRTC resuming",{sipId:i.id}),this.currentSipSession&&this.currentSipSession.id!==i.id&&(ua.info("WebRTC hold call after resume",{id:this.currentSipSession.id}),this.holdSipSession(this.currentSipSession,this.currentCallSession,t));const n=this.unholdSipSession(i,e,t);return this.currentSipSession=i,e&&(this.currentCallSession=e),n}async holdSipSession(e,t,i=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to hold"))));const n=this.getSipSessionId(e),r=this.client.hasLocalVideo(n);ua.info("WebRTC hold sip session",{sipId:e.id,hasVideo:r}),this.currentScreenShare&&this.currentScreenShare.sipSessionId===n&&(this.lastScreenShare=this.currentScreenShare,await this.stopScreenSharing(!1,t)),r&&await this.client.downgradeToAudio(e);const s=!!t&&t.isConference(),a=this.client.hold(e,s,r);return i&&this.eventEmitter.emit(Ds,this._createCallSession(e,t)),a}async unholdSipSession(e,t,i=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to unhold"))));const n=!!t&&t.isConference(),r=this.getSipSessionId(e);ua.info("WebRTC unhold sip session",{sessionId:r,isConference:n});const{hasVideo:s}=this.client.getHeldSession(r)||{},a=this.lastScreenShare&&this.lastScreenShare.sipSessionId===r,o=this.lastScreenShare&&this.lastScreenShare.desktop,c=this.client.unhold(e,n);if(s){const t={audio:!1,video:!0,screen:a,desktop:o};await this.client.upgradeToVideo(e,t,n)}const d=i=>{const n=this.lastScreenShare&&this.lastScreenShare.hadVideo;i&&this._onScreenSharing(i,e,t,n),this.lastScreenShare=null};if(i){t&&(t.muted=!1);const i=this._createCallSession(e,t);this.eventEmitter.emit(Ns,i),this.eventEmitter.emit(Ps,i)}return c.then((()=>{const e=t?this.getLocalVideoStream(t):null;return a&&d(e),e}))}mute(e,t=!0){ua.info("WebRTC mute called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return;ua.info("WebRTC muting",{sipId:i.id}),this.client.mute(i);const n=this._createCallSession(i,e,{muted:!0});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(Rs,n)}unmute(e,t=!0){ua.info("WebRTC unmute called",{id:e?e.getId():null});const i=this.findSipSession(e);if(!i)return;ua.info("WebRTC unmuting",{sipId:i.id}),this.client.unmute(i);const n=this._createCallSession(i,e,{muted:!1});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(As,n)}isAudioMuted(e){const t=this.findSipSession(e);return!t||this.client.isAudioMuted(t)}turnCameraOn(e){const t=this.findSipSession(e);t&&(ua.info("WebRTC turn camera on",{sipId:t.id}),this.client.toggleCameraOn(t),this.eventEmitter.emit(Os,this._createCameraResumedCallSession(t,e)))}turnCameraOff(e){const t=this.findSipSession(e);t&&(ua.info("WebRTC turn camera off",{sipId:t.id}),this.client.toggleCameraOff(t),this.eventEmitter.emit(ks,this._createCameraDisabledCallSession(t,e)))}sendKey(e,t){const i=this.findSipSession(e);i&&(ua.info("WebRTC send key",{sipId:i.id,tone:t}),this.client.sendDTMF(i,t))}async makeCall(e,t,i,n=!1,r=!1,s={}){if(ua.info("make WebRTC call",{number:e,lineId:t?t.id:null,cameraEnabled:i,audioOnly:n,conference:r,options:s}),!e)return Promise.resolve(null);let a;this.client.isRegistered()||await this.client.register(),this.currentSipSession&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0).catch((e=>{ua.warn("Unable to hold current session when making another call",e)}));try{a=this.client.call(e,!!this.allowVideo&&i,n,r,s),this._bindEvents(a)}catch(e){return ua.warn("make WebRTC call, error",{message:e.message,stack:e.stack}),Promise.resolve(null)}const o=this._createOutgoingCallSession(a,i||!1);return o.setIsConference(r),o.creationTime=new Date,this._updateCallSession(o),this.eventEmitter.emit(ea,this.audioOutputDeviceId,this.audioOutputVolume),this.currentSipSession=a,this.currentCallSession=o,this.eventEmitter.emit(Is,o),a.invitePromise&&a.invitePromise.catch((e=>{this.eventEmitter.emit(ia,e,o)})),Promise.resolve(o)}transfer(e,t){const i=this.findSipSession(e);i&&(ua.info("WebRTC transfer",{sipId:i.id,target:t}),this.client.transfer(i,t))}async indirectTransfer(e,t){const i=this.client.getSipSession(e.sipCallId),n=this.client.getSipSession(t.sipCallId);return ua.info("WebRTC indirect transfer",{sipId:i?i.id:null,target:n?n.id:null}),n?new Promise((e=>{const r={requestDelegate:{onAccept:()=>{setTimeout((()=>{this.hangup(t).then(e)}),200)}}};return n.refer(i,r)})):Promise.reject()}initiateCTIIndirectTransfer(){return Promise.resolve(null)}cancelCTIIndirectTransfer(){}confirmCTIIndirectTransfer(){}async hangup(e){const t=this.findSipSession(e);if(!t)return console.error("Call is unknown to the WebRTC phone",e?e.sipCallId:null,e?e.callId:null),!1;const i=this.getSipSessionId(t);return ua.info("WebRTC hangup",{sipId:t.id,sipSessionId:i}),await this.client.hangup(t),e?this.endCurrentCall(e):i&&delete this.callSessions[i],this.shouldSendReinvite=!1,!0}async getStats(e){const t=this.findSipSession(e);return t?this.client.getStats(t):null}startNetworkMonitoring(e,t=1e3){const i=this.findSipSession(e);return i?this.client.startNetworkMonitoring(i,t):null}stopNetworkMonitoring(e){const t=this.findSipSession(e);return t?this.client.stopNetworkMonitoring(t):null}forceCancel(e){if(e&&e.outgoingInviteRequest)try{e.outgoingInviteRequest.cancel()}catch(e){ua.info("force cancel, error",e)}}endCurrentCall(e){const t=this.isCurrentCallSipSession(e);ua.info("Ending current call",{id:e?e.getId():null,isCurrent:t}),t&&(this.currentSipSession=void 0,this.currentCallSession=void 0),this.eventEmitter.emit(Js,e,"locally ended")}onConnectionMade(){}isConference(e){return!!e&&(this.client&&this.client.isConference(e.sipCallId))}async close(e=!1){ua.info("WebRTC close");try{await Promise.race([this.unregister(),new Promise(((e,t)=>setTimeout((()=>t(new Error("Unregister, timed out"))),3e3)))])}catch(e){ua.error("WebRTC close, unregister error",e)}await this.client.close(e),this.unbind(),this.incomingSessions=[],this.currentSipSession=void 0,this.currentCallSession=void 0,this.shouldSendReinvite=!1,this.rejectedSessions={}}isRegistered(){return this.client&&this.client.isRegistered()}enableRinging(){ua.info("WebRTC enable ringing"),this.ringingEnabled=!0}disableRinging(){ua.info("WebRTC disable ringing"),this.ringingEnabled=!1}getCurrentCallSession(){return this.currentSipSession?this._createCallSession(this.currentSipSession,this.currentCallSession):null}hasIncomingCallSession(){return this.incomingSessions.length>0}getIncomingCallSession(){if(!this.hasIncomingCallSession())return null;const e=this.incomingSessions[0],t=this.client.getSipSession(e);return t?this._createCallSession(t):null}sendMessage(e=null,t,i="text/plain"){return this.client.sendMessage(e,t,i)}getLocalStream(e){return e?this.client.getLocalStream(e.sipCallId):null}getLocalVideoStream(e){return e?this.client.getLocalVideoStream(e.sipCallId):null}getLocalMediaStream(e){return ua.warn("WebRTCPhone.getLocalMediaStream is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}hasLocalVideo(e){return!!e&&this.client.hasLocalVideo(e.sipCallId)}hasALocalVideoTrack(e){return!!e&&this.client.hasALocalVideoTrack(e.sipCallId)}getRemoteStream(e){return e?this.client.getRemoteStream(e.sipCallId):null}getRemoteVideoStream(e){return e?this.client.getRemoteVideoStream(e.sipCallId):null}getRemoteVideoStreamFromPc(e){return e?this.client.getRemoteVideoStreamFromPc(e.sipCallId):null}hasRemoteVideo(e){return!!e&&this.client.hasRemoteVideo(e.sipCallId)}setMediaConstraints(e){this.client.setMediaConstraints(e)}isVideoRemotelyHeld(e){return!!e&&this.client.isVideoRemotelyHeld(e.sipCallId)}bindClientEvents(){this.client.unbind(),this.client.on(this.client.INVITE,((e,t)=>{const i="Auto"===e.request.getHeader("Answer-Mode"),n=!!this.allowVideo&&t;ua.info("WebRTC invite received",{sipId:e.id,withVideo:n,autoAnswer:i});const r=this._createIncomingCallSession(e,n,null,i);this.incomingSessions.push(r.getId()),this._bindEvents(e),this.client.storeSipSession(e),r.creationTime=new Date,this._updateCallSession(r),this.eventEmitter.emit(xs,r,t),this.currentSipSession?this.eventEmitter.emit(Xs,this.audioOutputDeviceId,this.audioOutputVolume,r):this.ringingEnabled&&this.eventEmitter.emit(Zs,this.audioRingDeviceId,this.audioRingVolume,r)})),this.client.on(this.client.ON_REINVITE,((...e)=>{ua.info("WebRTC on reinvite",{sessionId:e[0].id,inviteId:e[1].id,updatedCalleeName:e[2],updatedNumber:e[3]});const t=e[0];setTimeout((()=>{this._createCallSession(t,this.callSessions[this.getSipSessionId(t)]),this.eventEmitter.emit.apply(this.eventEmitter,[this.client.ON_REINVITE,...e])}),2e3)})),this.client.on(this.client.ACCEPTED,(async e=>{const t=this.getSipSessionId(e),i=t in this.callSessions;ua.info("WebRTC call accepted",{sipId:t,hasSession:i}),i?(this._onCallAccepted(e,this.client.hasVideo(t)),this.audioOutputDeviceId&&await this.client.changeAudioOutputDevice(this.audioOutputDeviceId)):ua.warn("Call accepted ignored, session is no longer present in the WebRtcPhone",{sessionId:t})})),this.client.on("ended",(()=>{})),this.client.on(this.client.ON_ERROR,(e=>{ua.error("WebRTC error",e),this.eventEmitter.emit(ia,e)})),this.client.on(this.client.REJECTED,(e=>{ua.info("WebRTC call rejected",e.id);const t=this._createCallSession(e);delete this.callSessions[this.getSipSessionId(e)],t.endTime=new Date,this.eventEmitter.emit(Hs,t)})),this.client.on(this.client.UNREGISTERED,(()=>{ua.info("WebRTC unregistered"),this.eventEmitter.emit(Cs)})),this.client.on(this.client.ON_DISCONNECTED,(()=>{ua.info("WebRTC disconnected"),this.eventEmitter.emit(oa)})),this.client.on(this.client.ON_PROGRESS,(e=>{ua.info("WebRTC progress (180)");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit($s,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.ON_EARLY_MEDIA,(e=>{ua.info("WebRTC early media");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit(ca,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.REGISTERED,(()=>{if(ua.info("WebRTC registered",{shouldSendReinvite:this.shouldSendReinvite,state:this.currentSipSession?this.currentSipSession.state:null,currentSipSession:!!this.currentSipSession}),this.stopHeartbeat(),this.eventEmitter.emit(Es),this.shouldSendReinvite&&this.currentSipSession&&this.currentSipSession.state===mi.Established){this.shouldSendReinvite=!1;const e=this.currentSipSession?.sessionDescriptionHandler?.peerConnection,t=!!e&&e.sfu,i=this.currentCallSession&&this.currentCallSession.cameraEnabled;try{this.sendReinvite(this.currentCallSession,null,t,!i,!0)}catch(e){ua.error("WebRTC reinvite after register, error",{message:e.message,stack:e.stack})}}})),this.client.on(this.client.CONNECTED,(()=>{ua.info("WebRTC client connected"),this.stopHeartbeat()})),this.client.on(this.client.DISCONNECTED,(()=>{ua.info("WebRTC client disconnected"),this.eventEmitter.emit(Cs),this.client.hasHeartbeat()||this.startHeartbeat(),this.shouldSendReinvite=!0})),this.client.on(this.client.ON_TRACK,((e,t)=>{this.eventEmitter.emit(Vs,e,t)})),this.client.on("onVideoInputChange",(e=>{this.eventEmitter.emit(ta,e)})),this.client.on(this.client.MESSAGE,(e=>{this._onMessage(e),this.eventEmitter.emit(Bs,e)})),this.client.on(this.client.ON_NETWORK_STATS,((e,t,i)=>{const n=this.getCallSession(this.getSipSessionId(e));this.eventEmitter.emit(ra,n,t,i)})),this.client.on(this.client.ON_SCREEN_SHARING_REINVITE,((e,t,i)=>{const n=this.getSipSessionId(e),r=this.client.getLocalStream(n),s=this.callSessions[n];ua.info("Updrading directly in screensharing mode",{sipSessionId:n,tracks:r?.getTracks()||null}),this._onScreenSharing(r,e,s,!1,i)}))}findSipSession(e){const t=this.client.getSipSessionIds(),i=t.findIndex((t=>e&&e.isId(t)));if(-1===i){const e=this.currentSipSession?this.getSipSessionId(this.currentSipSession):this.client.getSipSessionIds()[0];return e?this.client.getSipSession(e):null}return this.client.getSipSession(t[i])}getCallSession(e){return this.callSessions[e]}getSipSessionId(e){return this.client.getSipSessionId(e)}getSipSessionIdFromCallSession(e){const t=this.findSipSession(e);return t?this.getSipSessionId(t):null}_updateCallSession(e){const t=this.getSipSessionIdFromCallSession(e);t&&(this.callSessions[t]=e)}_onMessage(e){if(!e||"MESSAGE"!==e.method)return;let t;try{t=JSON.parse(e.body||"")}catch(e){return}const{type:i,content:n}=t;switch(i){case da:this.eventEmitter.emit(sa,n);break;case la:this.eventEmitter.emit(aa,n)}}_createIncomingCallSession(e,t,i,n=!1){return this._createCallSession(e,i,{incoming:!0,ringing:!0,cameraEnabled:t,autoAnswer:n})}_createOutgoingCallSession(e,t,i){return this._createCallSession(e,i,{incoming:!1,ringing:!0,cameraEnabled:t})}_createAcceptedCallSession(e,t,i){return this._createCallSession(e,i,{cameraEnabled:void 0!==t&&t})}_createMutedCallSession(e,t){return this._createCallSession(e,t,{muted:!0})}_createUnmutedCallSession(e,t){return this._createCallSession(e,t,{muted:!1})}_createCameraResumedCallSession(e,t){return this._createCallSession(e,t,{videoMuted:!1})}_createCameraDisabledCallSession(e,t){return this._createCallSession(e,t,{videoMuted:!0})}_createCallSession(e,t,i={}){const n=e?e.remoteIdentity||e.assertedIdentity:null,r=n?n.uri._normal.user:null,{state:s}=e||{},a=this.getSipSessionId(e);t=t||this.callSessions[a];const o=new yi({callId:t&&t.callId,sipCallId:a,sipStatus:s,displayName:n&&n.displayName||r,startTime:t?t.startTime:new Date,creationTime:t?t.creationTime:null,answerTime:t?t.answerTime:null,endTime:t?t.endTime:null,answered:s===mi.Established,paused:this.client.isCallHeld(e),isCaller:t?t.isCaller:"incoming"in i&&!i.incoming,cameraEnabled:t?t.isCameraEnabled():this.client.hasVideo(a),number:r,ringing:!1,muted:t?t.isMuted():this.client.isAudioMuted(e),videoMuted:!!t&&t.isVideoMuted(),recording:!!t&&t.isRecording(),recordingPaused:!1,sipSession:e,conference:!!t&&t.isConference(),...i});return this.callSessions[a]=o,o}}var ga=Object.freeze({__proto__:null,MESSAGE_TYPE_CHAT:da,MESSAGE_TYPE_SIGNAL:la,ON_AUDIO_STREAM:qs,ON_CALL_ACCEPTED:Ts,ON_CALL_ANSWERED:_s,ON_CALL_CANCELED:Fs,ON_CALL_ENDED:Ls,ON_CALL_ENDING:js,ON_CALL_ERROR:ia,ON_CALL_FAILED:Ms,ON_CALL_HELD:Ds,ON_CALL_INCOMING:xs,ON_CALL_MUTED:Rs,ON_CALL_OUTGOING:Is,ON_CALL_REJECTED:Hs,ON_CALL_RESUMED:Ps,ON_CALL_UNHELD:Ns,ON_CALL_UNMUTED:As,ON_CAMERA_DISABLED:ks,ON_CAMERA_RESUMED:Os,ON_CHAT:sa,ON_DISCONNECTED:oa,ON_EARLY_MEDIA:ca,ON_MESSAGE:Bs,ON_MESSAGE_TRACK_UPDATED:na,ON_NETWORK_STATS:ra,ON_PLAY_HANGUP_SOUND:Qs,ON_PLAY_INBOUND_CALL_SIGNAL_SOUND:Xs,ON_PLAY_PROGRESS_SOUND:ea,ON_PLAY_RING_SOUND:Zs,ON_PROGRESS:$s,ON_REGISTERED:Es,ON_REINVITE:Us,ON_REMOVE_STREAM:Ks,ON_SHARE_SCREEN_ENDED:Ys,ON_SHARE_SCREEN_ENDING:zs,ON_SHARE_SCREEN_STARTED:Ws,ON_SIGNAL:aa,ON_TERMINATE_SOUND:Js,ON_TRACK:Vs,ON_UNREGISTERED:Cs,ON_USER_AGENT:ws,ON_VIDEO_INPUT_CHANGE:ta,ON_VIDEO_STREAM:Gs,default:pa,events:ha});let fa=!0,ma=!0;function va(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function ya(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Sa(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(fa=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ba(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ma=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function wa(){if("object"==typeof window){if(fa)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ea(e,t){ma&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ca(e){return"[object Object]"===Object.prototype.toString.call(e)}function $a(e){return Ca(e)?Object.keys(e).reduce((function(t,i){const n=Ca(e[i]),r=n?$a(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Ta(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Ta(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Ta(e,e.get(t),i)}))})))}function _a(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Ta(e,i,r)}))})),r}const xa=wa;function Ia(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let a=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),xa("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return xa("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Ra(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Aa(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ya(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Pa(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Da(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function Na(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>_a(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ya(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>_a(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ka(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Oa(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ka(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Fa(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Ma(e,t){ya(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Ha=Object.freeze({__proto__:null,fixNegotiationNeeded:Ma,shimAddTrackRemoveTrack:Oa,shimAddTrackRemoveTrackWithNative:ka,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:Pa,shimGetStats:Da,shimGetUserMedia:Ia,shimMediaStream:Ra,shimOnTrack:Aa,shimPeerConnection:Fa,shimSenderReceiverGetStats:Na});function La(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Ea("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function ja(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ba(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function Ua(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Va(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ya(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function qa(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ea("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Ga(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ka(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Wa(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function za(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ya(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ja=Object.freeze({__proto__:null,shimAddTransceiver:Ka,shimCreateAnswer:Ya,shimCreateOffer:za,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Wa,shimGetUserMedia:La,shimOnTrack:ja,shimPeerConnection:Ba,shimRTCDataChannel:Ga,shimReceiverGetStats:Va,shimRemoveStream:qa,shimSenderGetStats:Ua});function Za(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Xa(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Qa(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function eo(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(to(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function to(e){return e&&void 0!==e.video?Object.assign({},e,{video:$a(e.video)}):e}function io(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Ea("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function no(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ro(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function so(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ao=Object.freeze({__proto__:null,shimAudioContext:so,shimCallbacksAPI:Qa,shimConstraints:to,shimCreateOfferLegacy:ro,shimGetUserMedia:eo,shimLocalStreamsAPI:Za,shimRTCIceServerUrls:io,shimRemoteStreamsAPI:Xa,shimTrackEventTransceiver:no}),oo={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(oo);var co=oo.exports,lo=C(co),ho=t({__proto__:null,default:lo},[co]);function uo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=lo.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ya(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function po(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ya(e,"icecandidate",(e=>{if(e.candidate){const t=lo.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function go(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=lo.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=lo.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=lo.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function fo(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},ya(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function mo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function vo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function yo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function So(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var bo=Object.freeze({__proto__:null,removeExtmapAllowMixed:vo,shimAddIceCandidateNullOrEmpty:yo,shimConnectionState:mo,shimMaxMessageSize:go,shimParameterlessSetLocalDescription:So,shimRTCIceCandidate:uo,shimRTCIceCandidateRelayProtocol:po,shimSendThrowTypeError:fo});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=wa,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=va(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=va(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=va(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:bo,extractVersion:va,disableLog:Sa,disableWarnings:ba,sdp:ho};switch(n.browser){case"chrome":if(!Ha||!Fa||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Ha,yo(e,n),So(e),Ia(e,n),Ra(e),Fa(e,n),Aa(e),Oa(e,n),Pa(e),Da(e),Na(e),Ma(e,n),uo(e),po(e),mo(e),go(e,n),fo(e),vo(e,n);break;case"firefox":if(!Ja||!Ba||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Ja,yo(e,n),So(e),La(e,n),Ba(e,n),ja(e),qa(e),Ua(e),Va(e),Ga(e),Ka(e),Wa(e),za(e),Ya(e),uo(e),mo(e),go(e,n),fo(e);break;case"safari":if(!ao||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=ao,yo(e,n),So(e),io(e),ro(e),Qa(e),Za(e),Xa(e),no(e),eo(e),so(e),uo(e),po(e),go(e,n),fo(e),vo(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});function wo(e){return e.sdp=((e,t)=>{const i=new RegExp("m="+t+".*$","gm"),n=new RegExp("^a=group:.*$","gm");if(i.test(e)){let i;const r=(e=e.split(/^m=/gm).filter((e=>{if(e.substr(0,t.length)===t){if(i=e.match(/^a=mid:.*$/gm),i){const e=i[0].match(/:.+$/g);e&&(i=e[0].substr(1))}return!1}return!0})).join("m=")).match(n);if(r&&1===r.length){let t=r[0];const s=new RegExp(" *"+i+"[^ ]*","g");t=t.replace(s,""),e=e.split(n).join(t)}}return e})(e.sdp||"","video"),Promise.resolve(e)}function Eo(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const i=e.type;return t&&(/a=(sendrecv|sendonly|recvonly|inactive)/.test(t)?(t=t.replace(/a=sendrecv\r\n/g,"a=sendonly\r\n"),t=t.replace(/a=recvonly\r\n/g,"a=inactive\r\n")):t=t.replace(/(m=[^\r]*\r\n)/g,"$1a=sendonly\r\n")),Promise.resolve({sdp:t,type:i})}var Co={exports:{}};!function(e){e.exports=function(e,t,i){var n;(n=void 0!==E?E:null)&&"undefined"==typeof window&&void 0!==E&&(E.navigator={userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45",getUserMedia:function(){}},E.console||(E.console={}),void 0!==E.console.log&&void 0!==E.console.error||(E.console.error=E.console.log=E.console.log||function(){console.log(arguments)}),"undefined"==typeof document&&(n.document={documentElement:{appendChild:function(){return""}}},document.createElement=document.captureStream=document.mozCaptureStream=function(){var e={getContext:function(){return e},play:function(){},pause:function(){},drawImage:function(){},toDataURL:function(){return""}};return e},n.HTMLVideoElement=function(){}),"undefined"==typeof location&&(n.location={protocol:"file:",href:"",hash:""}),"undefined"==typeof screen&&(n.screen={width:0,height:0}),"undefined"==typeof URL&&(n.URL={createObjectURL:function(){return""},revokeObjectURL:function(){return""}}),"undefined"==typeof MediaStreamTrack&&(n.MediaStreamTrack=function(){}),void 0===r&&(n.RTCPeerConnection=function(){}),n.window=E);var r=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;"undefined"==typeof MediaStreamTrack&&(MediaStreamTrack={});var s={encryption:"sha-256",audio:{send:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},recv:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},bytesSent:0,bytesReceived:0,latency:0,packetsLost:0},video:{send:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},recv:{tracks:[],codecs:[],availableBandwidth:0,streams:0,framerateMean:0,bitrateMean:0},bytesSent:0,bytesReceived:0,latency:0,packetsLost:0},bandwidth:{systemBandwidth:0,sentPerSecond:0,encodedPerSecond:0,helper:{audioBytesSent:0,videoBytestSent:0},speed:0},results:{},connectionType:{systemNetworkType:((navigator.connection||{}).type||"unknown").toString().toLowerCase(),systemIpAddress:"192.168.1.2",local:{candidateType:[],transport:[],ipAddress:[],networkType:[]},remote:{candidateType:[],transport:[],ipAddress:[],networkType:[]}},resolutions:{send:{width:0,height:0},recv:{width:0,height:0}},internal:{audio:{send:{},recv:{}},video:{send:{},recv:{}},candidates:{},getSendrecvType:function(e){var t=e.id.split("_").pop();if("isRemote"in e)!0===e.isRemote&&(t="recv"),!1===e.isRemote&&(t="send");else{var i=e.type.split("-")[0];t="outbound"===i?"send":"inbound"===i?"recv":null}return t}},nomore:function(){d=!0}},a={checkIfOfferer:function(e){"googLibjingleSession"===e.type&&(s.isOfferer=e.googInitiator)}},o=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),c=this;if(!(arguments[0]instanceof r))throw"1st argument is not instance of RTCPeerConnection.";c=arguments[0],arguments[1]instanceof MediaStreamTrack&&(e=arguments[1],t=arguments[2],i=arguments[3]);var d=!1;a.datachannel=function(e){"datachannel"===e.type&&(s.datachannel={state:e.state})},a.googCertificate=function(e){"googCertificate"==e.type&&(s.encryption=e.googFingerprintAlgorithm),"certificate"==e.type&&(s.encryption=e.fingerprintAlgorithm)},a.checkAudioTracks=function(e){if("audio"===e.mediaType){var t=s.internal.getSendrecvType(e);if(t){if(-1===s.audio[t].codecs.indexOf(e.googCodecName||"opus")&&s.audio[t].codecs.push(e.googCodecName||"opus"),e.bytesSent){var i=0;s.internal.audio[t].prevBytesSent||(s.internal.audio[t].prevBytesSent=e.bytesSent);var n=e.bytesSent-s.internal.audio[t].prevBytesSent;s.internal.audio[t].prevBytesSent=e.bytesSent,i=n/1024,s.audio[t].availableBandwidth=i.toFixed(1),s.audio.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.audio[t].prevBytesReceived||(s.internal.audio[t].prevBytesReceived=e.bytesReceived),n=e.bytesReceived-s.internal.audio[t].prevBytesReceived,s.internal.audio[t].prevBytesReceived=e.bytesReceived,i=n/1024,s.audio.bytesReceived=i.toFixed(1)),e.googTrackId&&-1===s.audio[t].tracks.indexOf(e.googTrackId)&&s.audio[t].tracks.push(e.googTrackId),e.googCurrentDelayMs&&(i=0,s.internal.audio.prevGoogCurrentDelayMs||(s.internal.audio.prevGoogCurrentDelayMs=e.googCurrentDelayMs),n=e.googCurrentDelayMs-s.internal.audio.prevGoogCurrentDelayMs,s.internal.audio.prevGoogCurrentDelayMs=e.googCurrentDelayMs,s.audio.latency=n.toFixed(1),s.audio.latency<0&&(s.audio.latency=0)),e.packetsLost&&(i=0,s.internal.audio.prevPacketsLost||(s.internal.audio.prevPacketsLost=e.packetsLost),n=e.packetsLost-s.internal.audio.prevPacketsLost,s.internal.audio.prevPacketsLost=e.packetsLost,s.audio.packetsLost=n.toFixed(1),s.audio.packetsLost<0&&(s.audio.packetsLost=0))}}},a.checkVideoTracks=function(e){if("video"===e.mediaType){var t=s.internal.getSendrecvType(e);if(t){if(-1===s.video[t].codecs.indexOf(e.googCodecName||"VP8")&&s.video[t].codecs.push(e.googCodecName||"VP8"),e.bytesSent){var i=0;s.internal.video[t].prevBytesSent||(s.internal.video[t].prevBytesSent=e.bytesSent);var n=e.bytesSent-s.internal.video[t].prevBytesSent;s.internal.video[t].prevBytesSent=e.bytesSent,i=n/1024,s.video[t].availableBandwidth=i.toFixed(1),s.video.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.video[t].prevBytesReceived||(s.internal.video[t].prevBytesReceived=e.bytesReceived),n=e.bytesReceived-s.internal.video[t].prevBytesReceived,s.internal.video[t].prevBytesReceived=e.bytesReceived,i=n/1024,s.video.bytesReceived=i.toFixed(1)),e.googFrameHeightReceived&&e.googFrameWidthReceived&&(s.resolutions[t].width=e.googFrameWidthReceived,s.resolutions[t].height=e.googFrameHeightReceived),e.googFrameHeightSent&&e.googFrameWidthSent&&(s.resolutions[t].width=e.googFrameWidthSent,s.resolutions[t].height=e.googFrameHeightSent),e.googTrackId&&-1===s.video[t].tracks.indexOf(e.googTrackId)&&s.video[t].tracks.push(e.googTrackId),e.framerateMean&&(s.bandwidth.framerateMean=e.framerateMean,i=0,s.internal.video[t].prevFramerateMean||(s.internal.video[t].prevFramerateMean=e.bitrateMean),n=e.bytesSent-s.internal.video[t].prevFramerateMean,s.internal.video[t].prevFramerateMean=e.framerateMean,i=n/1024,s.video[t].framerateMean=n.toFixed(1)),e.bitrateMean&&(s.bandwidth.bitrateMean=e.bitrateMean,i=0,s.internal.video[t].prevBitrateMean||(s.internal.video[t].prevBitrateMean=e.bitrateMean),n=e.bytesSent-s.internal.video[t].prevBitrateMean,s.internal.video[t].prevBitrateMean=e.bitrateMean,i=n/1024,s.video[t].bitrateMean=n.toFixed(1)),e.googCurrentDelayMs&&(i=0,s.internal.video.prevGoogCurrentDelayMs||(s.internal.video.prevGoogCurrentDelayMs=e.googCurrentDelayMs),n=e.googCurrentDelayMs-s.internal.video.prevGoogCurrentDelayMs,s.internal.video.prevGoogCurrentDelayMs=e.googCurrentDelayMs,s.video.latency=n.toFixed(1),s.video.latency<0&&(s.video.latency=0)),e.packetsLost&&(i=0,s.internal.video.prevPacketsLost||(s.internal.video.prevPacketsLost=e.packetsLost),n=e.packetsLost-s.internal.video.prevPacketsLost,s.internal.video.prevPacketsLost=e.packetsLost,s.video.packetsLost=n.toFixed(1),s.video.packetsLost<0&&(s.video.packetsLost=0))}}},a.bweforvideo=function(e){"VideoBwe"===e.type&&(s.bandwidth.availableSendBandwidth=e.googAvailableSendBandwidth,s.bandwidth.googActualEncBitrate=e.googActualEncBitrate,s.bandwidth.googAvailableSendBandwidth=e.googAvailableSendBandwidth,s.bandwidth.googAvailableReceiveBandwidth=e.googAvailableReceiveBandwidth,s.bandwidth.googRetransmitBitrate=e.googRetransmitBitrate,s.bandwidth.googTargetEncBitrate=e.googTargetEncBitrate,s.bandwidth.googBucketDelay=e.googBucketDelay,s.bandwidth.googTransmitBitrate=e.googTransmitBitrate)},a.candidatePair=function(e){if("googCandidatePair"===e.type||"candidate-pair"===e.type||"local-candidate"===e.type||"remote-candidate"===e.type){if("true"==e.googActiveConnection&&(Object.keys(s.internal.candidates).forEach((function(t){var i=s.internal.candidates[t];-1!==i.ipAddress.indexOf(e.googLocalAddress)&&(s.connectionType.local.candidateType=i.candidateType,s.connectionType.local.ipAddress=i.ipAddress,s.connectionType.local.networkType=i.networkType,s.connectionType.local.transport=i.transport),-1!==i.ipAddress.indexOf(e.googRemoteAddress)&&(s.connectionType.remote.candidateType=i.candidateType,s.connectionType.remote.ipAddress=i.ipAddress,s.connectionType.remote.networkType=i.networkType,s.connectionType.remote.transport=i.transport)})),s.connectionType.transport=e.googTransportType,(t=s.internal.candidates[e.localCandidateId])&&t.ipAddress&&(s.connectionType.systemIpAddress=t.ipAddress),(i=s.internal.candidates[e.remoteCandidateId])&&i.ipAddress&&(s.connectionType.systemIpAddress=i.ipAddress)),"candidate-pair"===e.type&&!0===e.selected&&!0===e.nominated&&"succeeded"===e.state)var t=s.internal.candidates[e.remoteCandidateId],i=s.internal.candidates[e.remoteCandidateId];if("local-candidate"===e.type&&(s.connectionType.local.candidateType=e.candidateType,s.connectionType.local.ipAddress=e.ipAddress,s.connectionType.local.networkType=e.networkType,s.connectionType.local.transport=e.mozLocalTransport||e.transport),"remote-candidate"===e.type&&(s.connectionType.remote.candidateType=e.candidateType,s.connectionType.remote.ipAddress=e.ipAddress,s.connectionType.remote.networkType=e.networkType,s.connectionType.remote.transport=e.mozRemoteTransport||e.transport),o){var n=e.localCandidateId?"send":"recv";if(!n)return;if(e.bytesSent){var r=0;s.internal.video[n].prevBytesSent||(s.internal.video[n].prevBytesSent=e.bytesSent);var a=e.bytesSent-s.internal.video[n].prevBytesSent;s.internal.video[n].prevBytesSent=e.bytesSent,r=a/1024,s.video[n].availableBandwidth=r.toFixed(1),s.video.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=0,s.internal.video[n].prevBytesReceived||(s.internal.video[n].prevBytesReceived=e.bytesReceived),a=e.bytesReceived-s.internal.video[n].prevBytesReceived,s.internal.video[n].prevBytesReceived=e.bytesReceived,r=a/1024,s.video.bytesReceived=r.toFixed(1)),e.availableOutgoingBitrate&&(r=0,s.internal.video[n].prevAvailableOutgoingBitrate||(s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate),a=e.availableOutgoingBitrate-s.internal.video[n].prevAvailableOutgoingBitrate,s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate,r=a/1024,s.video.availableOutgoingBitrate=r.toFixed(1)),e.availableIncomingBitrate&&(r=0,s.internal.video[n].prevAvailableIncomingBitrate||(s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate),a=e.availableIncomingBitrate-s.internal.video[n].prevAvailableIncomingBitrate,s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate,r=a/1024,s.video.availableIncomingBitrate=r.toFixed(1))}}};var l={},h={},u={},p={};a.localcandidate=function(e){"localcandidate"!==e.type&&"local-candidate"!==e.type||e.id&&(l[e.id]||(l[e.id]=[]),h[e.id]||(h[e.id]=[]),u[e.id]||(u[e.id]=[]),p[e.id]||(p[e.id]=[]),e.candidateType&&-1===l[e.id].indexOf(e.candidateType)&&l[e.id].push(e.candidateType),e.transport&&-1===h[e.id].indexOf(e.transport)&&h[e.id].push(e.transport),e.ipAddress&&-1===u[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&u[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===p[e.id].indexOf(e.networkType)&&p[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:l[e.id],ipAddress:u[e.id],portNumber:e.portNumber,networkType:p[e.id],priority:e.priority,transport:h[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.local.candidateType=l[e.id],s.connectionType.local.ipAddress=u[e.id],s.connectionType.local.networkType=p[e.id],s.connectionType.local.transport=h[e.id])};var g={},f={},m={},v={};a.remotecandidate=function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||e.id&&(g[e.id]||(g[e.id]=[]),f[e.id]||(f[e.id]=[]),m[e.id]||(m[e.id]=[]),v[e.id]||(v[e.id]=[]),e.candidateType&&-1===g[e.id].indexOf(e.candidateType)&&g[e.id].push(e.candidateType),e.transport&&-1===f[e.id].indexOf(e.transport)&&f[e.id].push(e.transport),e.ipAddress&&-1===m[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&m[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===v[e.id].indexOf(e.networkType)&&v[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:g[e.id],ipAddress:m[e.id],portNumber:e.portNumber,networkType:v[e.id],priority:e.priority,transport:f[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.remote.candidateType=g[e.id],s.connectionType.remote.ipAddress=m[e.id],s.connectionType.remote.networkType=v[e.id],s.connectionType.remote.transport=f[e.id])},a.dataSentReceived=function(e){!e.googCodecName||"video"!==e.mediaType&&"audio"!==e.mediaType||(e.bytesSent&&(s[e.mediaType].bytesSent=parseInt(e.bytesSent)),e.bytesReceived&&(s[e.mediaType].bytesReceived=parseInt(e.bytesReceived)))},a.inboundrtp=function(e){if(o&&"inbound-rtp"===e.type){var t=e.mediaType||"audio",i=e.isRemote?"recv":"send";if(i){if(e.bytesSent){var n=0;s.internal[t][i].prevBytesSent||(s.internal[t][i].prevBytesSent=e.bytesSent);var r=e.bytesSent-s.internal[t][i].prevBytesSent;s.internal[t][i].prevBytesSent=e.bytesSent,n=r/1024,s[t][i].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][i].prevBytesReceived||(s.internal[t][i].prevBytesReceived=e.bytesReceived),r=e.bytesReceived-s.internal[t][i].prevBytesReceived,s.internal[t][i].prevBytesReceived=e.bytesReceived,n=r/1024,s[t].bytesReceived=n.toFixed(1))}}},a.outboundrtp=function(e){if(o&&"outbound-rtp"===e.type){var t=e.mediaType||"audio",i=e.isRemote?"recv":"send";if(i){if(e.bytesSent){var n=0;s.internal[t][i].prevBytesSent||(s.internal[t][i].prevBytesSent=e.bytesSent);var r=e.bytesSent-s.internal[t][i].prevBytesSent;s.internal[t][i].prevBytesSent=e.bytesSent,n=r/1024,s[t][i].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][i].prevBytesReceived||(s.internal[t][i].prevBytesReceived=e.bytesReceived),r=e.bytesReceived-s.internal[t][i].prevBytesReceived,s.internal[t][i].prevBytesReceived=e.bytesReceived,n=r/1024,s[t].bytesReceived=n.toFixed(1))}}},a.track=function(e){if(o&&"track"===e.type){var t=!0===e.remoteSource?"send":"recv";e.frameWidth&&e.frameHeight&&(s.resolutions[t].width=e.frameWidth,s.resolutions[t].height=e.frameHeight)}};var y={audio:{send:[],recv:[]},video:{send:[],recv:[]}};a.ssrc=function(e){if(e.googCodecName&&("video"===e.mediaType||"audio"===e.mediaType)&&"ssrc"===e.type){var t=e.id.split("_").pop();-1===y[e.mediaType][t].indexOf(e.ssrc)&&y[e.mediaType][t].push(e.ssrc),s[e.mediaType][t].streams=y[e.mediaType][t].length}},function e(){var n;n=function(n){if(n&&n.forEach){n.forEach((function(e){Object.keys(a).forEach((function(t){if("function"==typeof a[t])try{a[t](e)}catch(e){console.error(e.message,e.stack,e)}}))}));try{-1!==c.iceConnectionState.search(/failed|closed|disconnected/gi)&&(d=!0)}catch(e){d=!0}!0===d&&(s.datachannel&&(s.datachannel.state="close"),s.ended=!0),s.results=n,s.audio&&s.video&&(s.bandwidth.speed=s.audio.bytesSent-s.bandwidth.helper.audioBytesSent+(s.video.bytesSent-s.bandwidth.helper.videoBytesSent),s.bandwidth.helper.audioBytesSent=s.audio.bytesSent,s.bandwidth.helper.videoBytesSent=s.video.bytesSent),t(s),d||null!=typeof i&&i&&setTimeout(e,i||1e3)}},c.getStats(window.mediaStreamTrack||null).then((function(e){var t=[];e.forEach((function(e){t.push(e)})),n(t)})).catch(n)}()}}(Co);var $o=C(Co.exports),To={},_o={},xo={exports:{}},Io=xo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Io).forEach((function(e){Io[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ro=xo.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=Ro,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(_o);var Ao=Ro,Po=/%[sdv%]/g,Do=function(e){var t=1,i=arguments,n=i.length;return e.replace(Po,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},No=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return Do.apply(null,n)},ko=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Oo=["i","c","b","a"],Fo=_o,Mo=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||ko,n=t.innerOrder||Oo,r=[];return i.forEach((function(t){Ao[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(No(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(No(t,i,e))}))}))})),e.media.forEach((function(e){r.push(No("m",Ao.m[0],e)),n.forEach((function(t){Ao[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(No(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(No(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"};To.write=Mo,To.parse=Fo.parse,To.parseParams=Fo.parseParams,To.parseFmtpConfig=Fo.parseFmtpConfig,To.parsePayloads=Fo.parsePayloads,To.parseRemoteCandidates=Fo.parseRemoteCandidates,To.parseImageAttributes=Fo.parseImageAttributes,To.parseSimulcastStreamList=Fo.parseSimulcastStreamList;const Ho=(e,t,i=!0)=>{const n=To.parse(e),r=(e=>e.filter((e=>e&&("srflx"===e.type||"relay"===e.type))))(t)[0],s=r?r.ip:null;s&&(n.origin.address=s),n.media=n.media.map((e=>{const n=i&&r?r.port:e.port;return{...e,port:n,candidates:(e.candidates||[]).concat(t),direction:n<10?"inactive":e.direction}}));let a=To.write(n);return s&&(a=a.replace(/IN IP4 0.0.0.0/g,`IN IP4 ${s}`)),a},Lo=e=>{const t=To.parse(e),i=t.media.find((e=>!!e.candidates));if(!i)return e;const{candidates:n}=i;return t.media=t.media.map((e=>({...e,candidates:e.candidates||n}))),To.write(t)},jo=B?B.loggerFor("webrtc-sdh"):console,Bo=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):e.screen&&!e.desktop?navigator.mediaDevices.getDisplayMedia.call(navigator.mediaDevices,e):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream);class Uo extends vs{gatheredCandidates;eventEmitter;isWeb;session;constructor(e,t,i,n,r){super(e,t,i),this.eventEmitter=new Oi,this.isWeb=n,this.session=r}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.removeListener(e,t)}setRemoteSessionDescription(e){try{const t=super.setRemoteSessionDescription(e);return this.eventEmitter.emit("setDescription",e),t}catch(e){throw this.logger.error(`SessionDescriptionHandler.setRemoteSessionDescription: ${e}`),e}}getDescription(e={},t){if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=e.onDataChannel;const i=!!e.offerOptions&&e.offerOptions.iceRestart,n=!!e&&!!e.conference,r=!!e&&!!e.audioOnly,s=!this.session.pendingReinviteAck&&(i||"constraints"in e),a=void 0===e.iceGatheringTimeout?this.sessionDescriptionHandlerConfiguration?.iceGatheringTimeout:e.iceGatheringTimeout;return jo.trace("getting SDP description",{iceRestart:i,shouldWaitForIce:s,iceTimeout:a}),this.gatheredCandidates=[],this.peerConnectionDelegate||(this.peerConnectionDelegate={}),this.peerConnectionDelegate.onicecandidate=e=>{jo.trace("onicecandidate",e.candidate?e.candidate.candidate:{done:!0}),e.candidate&&(this.gatheredCandidates.push((e=>{if(!e)return null;const t=To.parse(0===e.indexOf("a=")?e:`a=${e}`);return t.candidates?t.candidates[0]:null})(e.candidate.candidate)),-1===e.candidate.candidate.indexOf("srflx")&&-1===e.candidate.candidate.indexOf("relay")||(jo.info("A valid ice was found, triggering ice gathering complete callback.",{ice:e.candidate.candidate}),this.iceGatheringComplete()))},this.getLocalMediaStream(e).then((()=>this.updateDirection(e,n,r))).then((()=>this.createDataChannel(e))).then((()=>{!n||!e.constraints||e.constraints.video||"hold"in e||r||this.peerConnection?.addTransceiver&&this.peerConnection.addTransceiver("video",{streams:[this._localMediaStream],direction:"sendrecv"})})).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(i,a))).then((()=>this.getLocalSessionDescription())).then((t=>{const{sdp:i}=t;return-1!==i.indexOf("a=candidate")?{type:t.type,sdp:Lo(i)}:(jo.info("No ICE candidates found in SDP, fixing it with gathered ices",this.gatheredCandidates),{type:t.type,sdp:Ho(i,this.gatheredCandidates,!(!e||!e.constraints)&&e.constraints.video)})})).then((e=>this.applyModifiers(e,t))).then((e=>({body:e.sdp,contentType:"application/sdp"}))).catch((e=>{throw jo.error("error when creating media",e),this.logger.error(`SessionDescriptionHandler.getDescription failed - ${e}`),e}))}sendDtmf(e,t={duration:0,interToneGap:0}){if(this.isWeb)return super.sendDtmf(e,t);this.logger.debug(`DTMF sent via INFO: ${e.toString()}`);const i={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=${t.duration||1e3}`}};return this.session.info({requestOptions:i})}close(){if(jo.info("closing sdh"),this.isWeb)return super.close();this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this.peerConnection?.getLocalStreams&&(this.peerConnection?.getLocalStreams().forEach((e=>{e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))})),this.peerConnection?.getRemoteStreams().forEach((e=>{e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))}))),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}updateDirection(e,t=!1,i=!1){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!this.isWeb)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":{this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");const n=(n,r)=>{if(t)return i&&r.receiver.track&&"video"===r.receiver.track.kind||e&&e.hold?"sendonly":"sendrecv";switch(n){case"inactive":return e&&e.hold?"inactive":t&&!i?"sendrecv":"recvonly";case"recvonly":return e&&e.hold?"inactive":"recvonly";case"sendonly":case"sendrecv":return e&&e.hold?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach((e=>{if(e.direction){const t=n(e.direction,e);e.direction!==t&&(e.direction=t)}}))}break;case"have-remote-offer":{this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");const n=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),r=(()=>{switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return e&&e.hold?"inactive":"recvonly";case"sendrecv":return e&&e.hold?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach((e=>{if(!e.stopped&&e.direction){const{receiver:n}=e;if(t&&i&&n.track&&"video"===n.track.kind)return void(e.direction="inactive");"stopped"!==e.direction&&e.direction!==r&&(e.direction=r)}}))}break;default:return Promise.reject(new Error(`Invalid signaling state ${this._peerConnection.signalingState}`))}return Promise.resolve()}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,{sfu:i}=t,n=this._localMediaStream,r=[],s=e=>{const{kind:s}=e;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const a=t.getSenders&&t.getSenders().find((e=>e.track&&e.track.kind===s));!a||i&&"audio"!==e.kind?r.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${s} track`),e(null)})).then((()=>{try{t.addTrack?t.addTrack(e,n):t.addStream(n)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${s} track`),e}n.addTrack(e),vs.dispatchAddTrackEvent(n,e)}))):(a.track&&(e.enabled=a.track.enabled),r.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e(null)})).then((()=>a.replaceTrack(e).then((()=>{const t=n.getTracks().find((e=>e.kind===s));t&&(t.stop(),n.removeTrack(t),vs.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),vs.dispatchAddTrackEvent(n,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))))))},a=e.getAudioTracks();a.length&&s(a[0]);const o=e.getVideoTracks();return o.length&&s(o[0]),r.reduce(((e,t)=>e.then((()=>t))),Promise.resolve())}getLocalMediaStream(e){if(this.logger.debug("WazoSessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=e.constraints?{...e.constraints}:{};if(this.localMediaStreamConstraints){if(JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this).then((e=>(this.setLocalMediaStream(e),e)))}}class Vo{heartbeatDelay;heartbeatTimeout;maxHeartbeats;hasHeartbeat;_heartbeatDelayTimeout;_heartbeatNotReceivedTimeout;_heartbeatTries;_sendHeartbeatCallback;_onTimeoutCallback;constructor(e=2e3,t=5e3,i=3){this.heartbeatDelay=e,this.heartbeatTimeout=t,this.maxHeartbeats=i,this.hasHeartbeat=!1,this._heartbeatTries=0}setSendHeartbeat(e){this._sendHeartbeatCallback=e}setOnHeartbeatTimeout(e){this._onTimeoutCallback=e}stop(){this.hasHeartbeat=!1,this._heartbeatNotReceivedTimeout&&clearTimeout(this._heartbeatNotReceivedTimeout),this._heartbeatDelayTimeout&&clearTimeout(this._heartbeatDelayTimeout)}start(){this.stop(),this.hasHeartbeat=!0,this._heartbeatTries=0,this._sendHeartbeat()}onHeartbeat(){this._clearTimeouts(),this.hasHeartbeat&&this._sendHeartbeat()}_sendHeartbeat(){this._heartbeatTries>=this.maxHeartbeats||(this._clearTimeouts(),this._heartbeatDelayTimeout=setTimeout((()=>{this._heartbeatTries++,this._sendHeartbeatCallback&&this._sendHeartbeatCallback()}),this.heartbeatDelay),this._onTimeoutCallback&&(this._heartbeatNotReceivedTimeout=setTimeout(this._onTimeoutCallback,this.heartbeatTimeout)))}_clearTimeouts(){this._heartbeatNotReceivedTimeout&&clearTimeout(this._heartbeatNotReceivedTimeout),this._heartbeatDelayTimeout&&clearTimeout(this._heartbeatDelayTimeout)}}const qo=e=>Promise.resolve({...JSON.parse(JSON.stringify(e)),sdp:e.sdp.replace("c=IN IP4 0.0.0.0","c=IN IP4 127.0.0.1")}),Go=["STATUS_NULL","STATUS_NEW","STATUS_CONNECTING","STATUS_CONNECTED","STATUS_COMPLETED"],Ko=B?B.loggerFor("webrtc-client"):console,Wo=B?B.loggerFor("webrtc-stats"):console,zo="registered",Yo="unregistered",Jo="registrationFailed",Zo="invite",Xo="connected",Qo="disconnected",ec="transportError",tc="message",ic="accepted",nc="rejected",rc="onTrack",sc="onProgress",ac="onEarlyMedia",oc="reinvite",cc="onError",dc="onScreenSharingReinvite",lc="onNetworkStats",hc="onDisconnected",uc=[zo,Yo,Jo,Zo],pc=[Xo,Qo,ec,tc];class gc extends Error{}class fc extends Fi{clientId;config;uaConfigOverrides;userAgent;registerer;hasAudio;audio;audioElements;video;audioStreams;audioOutputDeviceId;audioOutputVolume;heldSessions;connectionPromise;_boundOnHeartbeat;heartbeat;heartbeatTimeoutCb;heartbeatCb;statsIntervals;sipSessions;conferences;skipRegister;networkMonitoringInterval;sessionNetworkStats;forceClosed;ON_USER_AGENT;REGISTERED;UNREGISTERED;REGISTRATION_FAILED;INVITE;CONNECTED;DISCONNECTED;TRANSPORT_ERROR;MESSAGE;ACCEPTED;REJECTED;ON_TRACK;ON_REINVITE;ON_ERROR;ON_SCREEN_SHARING_REINVITE;ON_NETWORK_STATS;ON_EARLY_MEDIA;ON_PROGRESS;ON_DISCONNECTED;static isAPrivateIp(e){return null==/^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*/.exec(e)}static getIceServers(e){return fc.isAPrivateIp(e)?[{urls:["stun:stun.l.google.com:19302","stun:stun4.l.google.com:19302"]}]:[]}constructor(e,t,i){super(),this.clientId=Math.ceil(1e3*Math.random()),Ko.info("sdk webrtc constructor",{clientId:this.clientId}),this.uaConfigOverrides=i,this.config=e,this.skipRegister=e.skipRegister,this._buildConfig(e,t).then((e=>{this.config=e,this.userAgent=this.createUserAgent(i)})),this.audioOutputDeviceId=e.audioDeviceOutput,this.audioOutputVolume=e.audioOutputVolume||1,e.media&&(this.configureMedia(e.media),this.setMediaConstraints({audio:e.media.audio,video:e.media.video})),this.heldSessions={},this.statsIntervals={},this.connectionPromise=null,this.sipSessions={},this.conferences={},this.networkMonitoringInterval={},this.sessionNetworkStats={},this.forceClosed=!1,this._boundOnHeartbeat=this._onHeartbeat.bind(this),this.heartbeat=new Vo(e.heartbeatDelay,e.heartbeatTimeout,e.maxHeartbeats),this.heartbeat.setSendHeartbeat(this.pingServer.bind(this)),this.heartbeat.setOnHeartbeatTimeout(this._onHeartbeatTimeout.bind(this)),this.REGISTERED=zo,this.UNREGISTERED=Yo,this.REGISTRATION_FAILED=Jo,this.INVITE=Zo,this.CONNECTED=Xo,this.DISCONNECTED=Qo,this.TRANSPORT_ERROR=ec,this.MESSAGE=tc,this.ACCEPTED=ic,this.REJECTED=nc,this.ON_TRACK=rc,this.ON_REINVITE=oc,this.ON_ERROR=cc,this.ON_SCREEN_SHARING_REINVITE=dc,this.ON_NETWORK_STATS=lc,this.ON_DISCONNECTED=hc,this.ON_EARLY_MEDIA=ac,this.ON_PROGRESS=sc}configureMedia(e){this.hasAudio=!!e.audio,this.audioStreams={},this.audioElements={}}setMediaConstraints(e){this.video=e.video,this.audio=e.audio}createUserAgent(e){const t=this._createUaOptions(e);Ko.info("sdk webrtc, creating UA",{uaOptions:{...t,authorizationPassword:`${t?.authorizationPassword?.slice(0,5)}xxxx`},clientId:this.clientId}),t.delegate={onConnect:this.onConnect.bind(this),onDisconnect:this.onDisconnect.bind(this),onInvite:e=>{Ko.info("sdk webrtc on invite",{method:"delegate.onInvite",clientId:this.clientId,id:e.id,remoteURI:e.remoteURI}),this._setupSession(e);const t=!!e.request.getHeader("alert-info");this.eventEmitter.emit(Zo,e,this.sessionWantsToDoVideo(e),t)}};const i=new bs(t);return i.start(),i.transport&&i.transport.connectPromise&&i.transport.connectPromise.catch((e=>{Ko.warn("Transport connect error",e)})),i.transport.onMessage=e=>{const t=Tr.parseMessage(e,i.transport.logger);i.onTransportMessage(e),this.eventEmitter.emit(tc,t),t&&t.method===dr.MESSAGE&&i.userAgentCore.replyStateless(t,{statusCode:200})},i}isConnected(){return Boolean(this.userAgent?.isConnected())}isConnecting(){return this.userAgent?.transport?.state===Er.Connecting}isRegistered(){return Boolean(this.registerer&&this.registerer.state===br.Registered)}onConnect(){return Ko.info("sdk webrtc connected",{method:"delegate.onConnect",clientId:this.clientId}),this.eventEmitter.emit(Xo),!this.isRegistered()&&this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.register()}async onDisconnect(e){Ko.info("sdk webrtc disconnected",{method:"delegate.onConnect",clientId:this.clientId,error:e}),this.connectionPromise=null,this.eventEmitter.emit(Qo,e),this.isRegistered()&&(await this.unregister(),this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.eventEmitter.emit(Yo))}async register(e=0){const t={clientId:this.clientId,userAgent:!!this.userAgent,registered:this.isRegistered(),connectionPromise:!!this.connectionPromise,registerer:!!this.registerer,waiting:this.registerer&&this.registerer.waiting,tries:e,skipRegister:this.skipRegister};if(this.forceClosed=!1,this.skipRegister)return Ko.info("sdk webrtc skip register...",t),Promise.resolve();if(Ko.info("sdk webrtc registering...",t),this.userAgent||(Ko.info("sdk webrtc recreating User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),!this.userAgent||this.isRegistered())return Ko.info("sdk webrtc registering aborted, already registered or no UA can be created"),Promise.resolve();if(this.connectionPromise||this.registerer?.waiting)return Ko.info("sdk webrtc registering aborted due to a registration in progress.",{clientId:this.clientId}),Promise.resolve();const i=this._isWeb()?{}:{extraContactHeaderParams:["mobility=mobile"]},n=()=>{Ko.info("sdk webrtc registering failed",{tries:e,clientId:this.clientId,registerer:!!this.registerer,forceClosed:this.forceClosed}),this.forceClosed||(this.connectionPromise=null,this.registerer&&this.registerer.waiting&&this.registerer.waitingToggle(!1),e<=5&&(Ko.info("sdk webrtc registering, retrying...",{clientId:this.clientId,tries:e}),setTimeout((()=>this.register(e+1)),300)))};return this._connectIfNeeded().then((()=>{this.userAgent||(Ko.info("sdk webrtc recreating User Agent after connection"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),Ko.info("sdk webrtc registering, transport connected",{registerOptions:i,ua:!!this.userAgent,clientId:this.clientId}),this.registerer=new xr(this.userAgent,i),this.connectionPromise=null,this._monkeyPatchRegisterer(this.registerer),this.registerer.stateChange.addListener((e=>{Ko.info("sdk webrtc registering, state changed",{newState:e,clientId:this.clientId}),e===br.Registered&&this.registerer&&this.registerer.state===br.Registered?this.eventEmitter.emit(zo):e===br.Unregistered&&this.eventEmitter.emit(Yo)}));const e={requestDelegate:{onReject:e=>{Ko.error("sdk webrtc registering, rejected",{clientId:this.clientId,response:e}),n()}}};return this.registerer.register(e).catch((e=>(Ko.error("sdk webrtc registering, error",e),this.eventEmitter.emit(Jo),e)))})).catch((e=>{Ko.error("sdk webrtc registering, transport error",e),n()}))}_monkeyPatchRegisterer(e){if(!e)return;const t=e.waitingToggle.bind(e),i=e.unregistered.bind(e);e.waitingToggle=i=>{e&&e.waiting!==i&&t(i)},e.unregistered=()=>{e&&e.state!==br.Terminated&&i()}}async unregister(){Ko.info("sdk webrtc unregistering..",{clientId:this.clientId,userAgent:!!this.userAgent,registerer:!!this.registerer});try{return new Promise(((e,t)=>{if(!this.registerer)return e();const i=t=>{t===br.Unregistered&&(Ko.info("sdk webrtc unregistered",{clientId:this.clientId}),this.registerer&&this.registerer.stateChange.addListener(i),this._cleanupRegister(),e())};this.registerer.stateChange.addListener(i),this.registerer.unregister().then().catch((e=>{Ko.error("sdk webrtc unregistering, promise error",e),this._cleanupRegister(),t()}))}))}catch(e){Ko.error("sdk webrtc unregistering, error",e),this._cleanupRegister()}}stop(){return Ko.info("sdk webrtc stop",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent?this.userAgent.stop().then((()=>this._cleanupRegister())).catch((e=>{Ko.warn("sdk webrtc stop, error",{message:e.message,stack:e.stack})})):Promise.resolve()}call(e,t,i=!1,n=!1,r={}){Ko.info("sdk webrtc creating call",{clientId:this.clientId,number:e,enableVideo:t,audioOnly:i,conference:n,options:r});const s={sessionDescriptionHandlerOptionsReInvite:{conference:n,audioOnly:i},earlyMedia:!0,...r};i&&(s.sessionDescriptionHandlerModifiersReInvite=[wo]);const a=this._makeURI(e);let o=null;a?o=this.userAgent?new yr(this.userAgent,a,s):null:Ko.error("Null URI"),o&&(this.storeSipSession(o),this._setupSession(o)),n&&(this.conferences[this.getSipSessionId(o)]=!0);const c={requestDelegate:{onAccept:e=>{o?.sessionDescriptionHandler?.peerConnection&&((o?.sessionDescriptionHandler).peerConnection.sfu=n),this._onAccepted(o,e.session,!0)},onProgress:e=>{this._onProgress(e.session,183===e.message.statusCode)},onReject:e=>{Ko.info("on call rejected",{id:o?.id,fromTag:o?.fromTag}),this._stopSendingStats(o),this.stopNetworkMonitoring(o),this.eventEmitter.emit(nc,o,e)}},sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1,n)};return c.sessionDescriptionHandlerOptions&&(c.sessionDescriptionHandlerOptions.audioOnly=i),c.sessionDescriptionHandlerModifiers=[qo],i&&c.sessionDescriptionHandlerModifiers.push(wo),o&&(o.invitePromise=o.invite(c).catch((e=>{Ko.warn("sdk webrtc creating call, error",e)}))),o}answer(e,t){if(Ko.info("sdk webrtc answer call",{clientId:this.clientId,id:e.id,enableVideo:t}),!e||!e.accept){const e="No session to answer, or not an invitation";return Ko.warn(e),Promise.reject(new Error(e))}const i={sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1)};return this._accept(e,i).then((()=>{if(e.isCanceled){const t="accepted a canceled session (or was canceled during the accept phase).";throw Ko.error(t,{id:e.id}),this.onCallEnded(e),new gc(t)}Ko.info("sdk webrtc answer, accepted."),this._onAccepted(e)})).catch((t=>{throw Ko.error(`answer call error for ${e?e.id:"n/a"}`,t),t}))}async hangup(e){const{state:t,id:i}=e;Ko.info("sdk webrtc hangup call",{clientId:this.clientId,id:i,state:t});try{this._stopSendingStats(e),this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)];const i=e instanceof yr,n={[mi.Initial]:i?this._cancel.bind(this,e):this._reject.bind(this,e),[mi.Establishing]:i?this._cancel.bind(this,e):this._reject.bind(this,e),[mi.Established]:this._bye.bind(this,e)};return n[t]?await n[t]():await this._bye(e)}catch(e){Ko.warn("sdk webrtc hangup, error",e)}return Promise.resolve(null)}async getStats(e){const t=e.sessionDescriptionHandler?.peerConnection;return t?t.getStats(null):null}startNetworkMonitoring(e,t=1e3){const i=this.getSipSessionId(e);Ko.info("starting network inspection",{id:i,clientId:this.clientId}),this.sessionNetworkStats[i]=[],this.networkMonitoringInterval[i]=setInterval((()=>this._fetchNetworkStats(i)),t)}stopNetworkMonitoring(e){const t=this.getSipSessionId(e),i=t in this.networkMonitoringInterval;Ko.info("stopping network inspection",{clientId:this.clientId,id:t,exists:i}),i&&(clearInterval(this.networkMonitoringInterval[t]),delete this.networkMonitoringInterval[t],delete this.sessionNetworkStats[t])}async reject(e){Ko.info("sdk webrtc reject call",{clientId:this.clientId,id:e.id});try{if(e instanceof vr)return this._reject(e);if(e instanceof yr)return this._cancel(e)}catch(e){Ko.warn("Error when rejecting call",e.message,e.stack)}}async close(e=!1){if(Ko.info("sdk webrtc closing client",{clientId:this.clientId,userAgent:!!this.userAgent,force:e}),this.forceClosed=e,this._cleanupMedia(),this.connectionPromise=null,Object.values(this.audioElements).forEach((e=>{e.srcObject=null,e.pause()})),this.audioElements={},this.userAgent){this.stopHeartbeat(),this.userAgent&&(this.userAgent.delegate=void 0),this.userAgent.stateChange.removeAllListeners(),await this._disconnectTransport(e),this._cleanupRegister();try{this.userAgent.transport.connectReject=()=>{},this.userAgent.stop().catch(console.error)}catch(e){}this.userAgent=null,Ko.info("sdk webrtc client closed",{clientId:this.clientId})}}getNumber(e){return e?e.remoteIdentity.uri._normal.user:null}mute(e){Ko.info("sdk webrtc mute",{id:e.id}),this._toggleAudio(e,!0)}unmute(e){Ko.info("sdk webrtc unmute",{id:e.id}),this._toggleAudio(e,!1)}isAudioMuted(e){if(!e||!e.sessionDescriptionHandler)return!1;let t=!0;const i=e.sessionDescriptionHandler.peerConnection;if(!i)return!1;if(i.getSenders){if(!i.getSenders().length)return!1;i.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(t=t&&!e.track.enabled)}))}else{if(!i.getLocalStreams().length)return!1;i.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{t=t&&!e.enabled}))}))}return t}toggleCameraOn(e){Ko.info("sdk webrtc toggle camera on",{id:e.id}),this._toggleVideo(e,!1)}toggleCameraOff(e){Ko.info("sdk webrtc toggle camera off",{id:e.id}),this._toggleVideo(e,!0)}hold(e,t=!1,i=!1){const n=this.getSipSessionId(e),r=i||this.hasLocalVideo(n);if(Ko.info("sdk webrtc hold",{sessionId:n,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:r}),n in this.heldSessions)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();this.heldSessions[n]={hasVideo:r,isConference:t},this.mute(e),e.sessionDescriptionHandlerOptionsReInvite={hold:!0,conference:t};const s=this.getMediaConfiguration(!1,t);return this._isWeb()||(s.sessionDescriptionHandlerModifiers=[Eo]),s.sessionDescriptionHandlerOptions={constraints:s.constraints,hold:!0,conference:t},e.sessionDescriptionHandler&&(e.sessionDescriptionHandler.localMediaStreamConstraints=s.constraints),e.invite(s).catch((e=>{Ko.warn("sdk webrtc re-invite during hold, error",e)}))}unhold(e,t=!1){const i=this.getSipSessionId(e),n=i in this.heldSessions&&this.heldSessions[i].hasVideo;if(Ko.info("sdk webrtc unhold",{sessionId:i,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:n}),e.pendingReinvite)return Promise.resolve();this.unmute(e),delete this.heldSessions[this.getSipSessionId(e)],e.sessionDescriptionHandlerOptionsReInvite={hold:!1,conference:t};const r=this.getMediaConfiguration(!1,t);return this._isWeb()||(r.sessionDescriptionHandlerModifiers=[]),r.sessionDescriptionHandlerOptions={constraints:r.constraints,hold:!1,conference:t},e.invite(r).catch((e=>{Ko.warn("sdk webrtc re-invite during resume, error",e)}))}async upgradeToVideo(e,t,i){const n=e.sessionDescriptionHandler?.peerConnection;let r;if(i){const e=n?.getTransceivers()||[],t=((e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1})(e,(e=>null===e.sender.track&&e.mid&&-1===e.mid.indexOf("video")));r=-1!==t?e[t].sender:null}else r=n&&n.getSenders&&n.getSenders().find((e=>null===e.track));if(!r)return;const s=await this.getStreamFromConstraints(t);if(!s)return void console.warn(`Can't create media stream with: ${JSON.stringify(t||{})}`);if(t&&!t.audio){const t=e.sessionDescriptionHandler?.localMediaStream,i=t.getTracks().find((e=>"audio"===e.kind));i&&s.addTrack(i)}const a=s.getVideoTracks()[0];return a&&r.replaceTrack(a),this.setLocalMediaStream(this.getSipSessionId(e),s),s}downgradeToAudio(e){const t=e.sessionDescriptionHandler,i=t?.localMediaStream,n=t?.peerConnection,r=i.getVideoTracks();n?.getSenders&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).forEach((e=>{e.replaceTrack(null)})),r.forEach((e=>{e.enabled=!1,e.stop(),i.removeTrack(e)}))}async getStreamFromConstraints(e,t=!1){const i=e&&e.video,{constraints:n}=this.getMediaConfiguration(i,t,e);let r=null;try{r=await Bo(n)}catch(e){}return r?(r.local=!0,r):null}getHeldSession(e){return this.heldSessions[e]}isCallHeld(e){return this.getSipSessionId(e)in this.heldSessions}isVideoRemotelyHeld(e){const t=this.getPeerConnection(e),i=t&&t.remoteDescription?t.remoteDescription.sdp:null;if(!i)return!1;const n=(e=>{const t=To.parse(e).media.find((e=>"video"===e.type));return t?t.direction:null})(i);return"sendonly"===n}sendDTMF(e,t){return!!e.sessionDescriptionHandler&&(Ko.info("Sending DTMF",{id:this.getSipSessionId(e),tone:t}),e.sessionDescriptionHandler.sendDtmf(t))}message(e,t){const i=this._makeURI(e);if(!this.userAgent||!i)return void Ko.warn("Null value on message",{uri:i,userAgent:this.userAgent});new Sr(this.userAgent,i,t).message()}transfer(e,t){this.hold(e),Ko.info("Transfering a session",{id:this.getSipSessionId(e),target:t});const i={requestDelegate:{onAccept:()=>{this.hangup(e)}}};setTimeout((()=>{const n=this._makeURI(t);n?e.refer(n,i):Ko.warn("transfer timeout: null URI")}),50)}atxfer(e){this.hold(e),Ko.info("webrtc transfer started",{id:this.getSipSessionId(e)});const t={newSession:null,init:async i=>{Ko.info("webrtc transfer initialized",{id:this.getSipSessionId(e),target:i}),t.newSession=await this.call(i)},complete:()=>{Ko.info("webrtc transfer completed",{id:this.getSipSessionId(e),referId:this.getSipSessionId(t.newSession)}),e.refer(t.newSession)},cancel:()=>{this.hangup(t.newSession),this.unhold(e)}};return t}sendMessage(e=null,t,i="text/plain"){if(e){Ko.info("send WebRTC message",{sipId:e.id,contentType:i});try{e.message({requestOptions:{body:{content:t,contentType:i,contentDisposition:""}}})}catch(e){console.warn(e)}}}pingServer(){if(!this.isConnected())return;const e=this.userAgent?.userAgentCore,t=this._makeURI(this.config.authorizationUser||""),i=new Mn("sip","",this.config.host);if(t){const n=e?.makeOutgoingRequestMessage("OPTIONS",i,t,i,{});if(n)return e?.request(n);Ko.warn("pingServer: null message")}Ko.warn("pingServer: null fromURI")}getState(){return this.userAgent?Go[this.userAgent.state]:Cr.Stopped}getContactIdentifier(){return this.userAgent?`${this.userAgent.configuration.contactName}/${this.userAgent.contact.uri}`:null}isFirefox(){return this._isWeb()&&navigator.userAgent.toLowerCase().indexOf("firefox")>-1}changeAudioOutputVolume(e){Ko.info("Changing audio output volume",{volume:e}),Object.values(this.audioElements).forEach((t=>{t instanceof HTMLAudioElement&&(t.volume=e)})),this.audioOutputVolume=e}async changeAudioOutputDevice(e){Ko.info("Changing audio output device",{id:e}),this.audioOutputDeviceId=e;const t=[];Object.values(this.audioElements).forEach((i=>t.push(i.setSinkId(e)))),await Promise.allSettled(t)}async changeAudioInputDevice(e,t,i){const n=this.getAudioDeviceId();if(Ko.info("setting audio input device",{id:e,currentId:n,session:!!t}),!i&&e===n)return null;let r=e;if("default"===e&&navigator.mediaDevices){const e=await navigator.mediaDevices.enumerateDevices(),t=e.find((e=>"default"===e.deviceId));if(t){const s=t.label.replace("Default - ",""),a=e.find((e=>e.label===s));if(a&&(r=a.deviceId,!i&&r===n))return null}}if(this.audio&&(this.audio={deviceId:{exact:r}}),t&&navigator.mediaDevices){const e=t.sessionDescriptionHandler,i=e?.peerConnection,n={audio:{deviceId:{exact:r}}},s=await navigator.mediaDevices.getUserMedia(n),a=s.getAudioTracks()[0],o=i&&i.getSenders&&i.getSenders().find((e=>a&&e&&e.track&&e.track.kind===a.kind));return o&&(o.track&&(a.enabled=o.track.enabled),o.replaceTrack(a)),s}return null}async changeVideoInputDevice(e,t){if(this.setVideoInputDevice(e),t)return this.changeSessionVideoInputDevice(e,t)}setVideoInputDevice(e){const t=this.getVideoDeviceId();if(Ko.info("setting video input device",{id:e,currentId:t}),e===t)return null;const i="object"==typeof this.video?this.video:{};this.video={...i,deviceId:{exact:e}}}changeSessionVideoInputDevice(e,t){if(!this.sessionWantsToDoVideo(t))return Promise.resolve();const i=t.sessionDescriptionHandler.peerConnection,n=this.getSipSessionId(t),r=this.getLocalStream(n);Ko.info("changing video input device",{id:e,sessionId:n}),r&&r.getVideoTracks().filter((e=>e.enabled)).forEach((e=>e.stop()));const s={video:!e||{deviceId:{exact:e}}};return navigator.mediaDevices.getUserMedia(s).then((async e=>{const t=e.getVideoTracks()[0];let r=i&&i.getSenders&&i.getSenders().find((e=>t&&e&&e.track&&e.track.kind===t.kind)),s=!1;return r||(r=i&&i.getSenders&&i.getSenders().find((e=>!e.track))),r&&(s=!!r.track&&r.track.enabled,t.enabled=s,s||t.stop(),r.replaceTrack(s?t:null)),this.eventEmitter.emit("onVideoInputChange",e),this.setLocalMediaStream(n,e),e}))}getAudioDeviceId(){return this.audio&&"object"==typeof this.audio&&"deviceId"in this.audio?this.audio.deviceId?.exact:void 0}getVideoDeviceId(){return this.video&&"object"==typeof this.video&&"deviceId"in this.video?this.video.deviceId?.exact:void 0}reinvite(e,t=null,i=!1,n=!1,r=!1){if(!e)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();const s=this.isAudioMuted(e),a=t?t.video:this.sessionWantsToDoVideo(e),o=t&&t.screen,c=t&&t.desktop;if(Ko.info("Sending reinvite",{clientId:this.clientId,id:this.getSipSessionId(e),newConstraints:t,conference:i,audioOnly:n,wasMuted:s,shouldDoVideo:a,shouldDoScreenSharing:o,desktop:c}),t&&t.video){const t=e.sessionDescriptionHandlerModifiersReInvite;e.sessionDescriptionHandlerModifiersReInvite=t.filter((e=>e!==wo))}e.sessionDescriptionHandlerOptionsReInvite={...e.sessionDescriptionHandlerOptionsReInvite,conference:i,audioOnly:n};const{constraints:d}=this.getMediaConfiguration(a,i,t);return e.invite({requestDelegate:{onAccept:t=>(e instanceof yr&&e.outgoingRequestMessage.body?e.outgoingRequestMessage.body.body=t.message.body:e instanceof vr&&(e.incomingInviteRequest.message.body=t.message.body),Ko.info("on re-INVITE accepted",{id:this.getSipSessionId(e),wasMuted:s,shouldDoScreenSharing:o}),this.updateRemoteStream(this.getSipSessionId(e),!1),s&&this.mute(e),this._onAccepted(e,t.session,!1,!1),o&&this.eventEmitter.emit(dc,e,t,c),this.eventEmitter.emit(oc,e,t))},sessionDescriptionHandlerModifiers:[qo],requestOptions:{extraHeaders:["Subject: "+(o?"screenshare":"upgrade-video")]},sessionDescriptionHandlerOptions:{constraints:d,conference:i,audioOnly:n,offerOptions:{iceRestart:r}}})}async getUserMedia(e){const t={audio:this._getAudioConstraints(),video:this._getVideoConstraints(e.video)};return navigator.mediaDevices.getUserMedia(t)}getPeerConnection(e){const t=this.sipSessions[e];return t&&t.sessionDescriptionHandler?t.sessionDescriptionHandler.peerConnection:null}getLocalStream(e){const t=this.sipSessions[e];return t?.sessionDescriptionHandler?.localMediaStream||null}getLocalTracks(e){const t=this.getLocalStream(e);return t?t.getTracks():[]}hasLocalVideo(e){return this.getLocalTracks(e).some(this._isVideoTrack)}hasALocalVideoTrack(e){return this.getLocalTracks(e).some((e=>"video"===e.kind))}getLocalVideoStream(e){return this.hasLocalVideo(e)?this.getLocalStream(e):null}getRemoteStream(e){const t=this.sipSessions[e];return t?.sessionDescriptionHandler?.remoteMediaStream||null}getRemoteTracks(e){const t=this.getRemoteStream(e);return t?t.getTracks():[]}hasRemoteVideo(e){return this.getRemoteTracks(e).some(this._isVideoTrack)}hasARemoteVideoTrack(e){return this.getRemoteTracks(e).some((e=>"video"===e.kind))}getRemoteVideoStream(e){return this.isVideoRemotelyHeld(e)?null:this.hasRemoteVideo(e)?this.getRemoteStream(e):null}getRemoteVideoStreamFromPc(e){const t=this.getPeerConnection(e);return t?t.getRemoteStreams().find((e=>!!e.getVideoTracks().length)):null}hasVideo(e){return this.hasLocalVideo(e)||this.hasRemoteVideo(e)}hasAVideoTrack(e){return this.hasALocalVideoTrack(e)||this.hasARemoteVideoTrack(e)}getSipSessionId(e){if(!e)return"";const t=e.message;return t?.callId?t.callId.substring(0,36):e instanceof yr&&e.outgoingRequestMessage?e.outgoingRequestMessage.callId.substring(0,36):(e.id||"").substring(0,36)}async waitForRegister(){return new Promise((e=>this.on(zo,e)))}sessionWantsToDoVideo(e){if(!e)return!1;const{body:t}=e.request||e;return(e=>!!e&&!!To.parse(e).media.find((e=>"video"===e.type&&e.port>10&&(!e.direction||"inactive"!==e.direction))))("object"==typeof t&&t?t.body:t)}hasHeartbeat(){return this.heartbeat.hasHeartbeat}startHeartbeat(){Ko.info("sdk webrtc start heartbeat",{userAgent:!!this.userAgent,clientId:this.clientId}),this.userAgent?(this.eventEmitter.off(tc,this._boundOnHeartbeat),this.eventEmitter.on(tc,this._boundOnHeartbeat),this.heartbeat.start()):this.heartbeat.stop()}stopHeartbeat(){Ko.info("sdk webrtc stop heartbeat",{clientId:this.clientId}),this.heartbeat.stop()}setOnHeartbeatTimeout(e){this.heartbeatTimeoutCb=e}setOnHeartbeatCallback(e){this.heartbeatCb=e}onCallEnded(e){this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)],this._stopSendingStats(e),this.stopNetworkMonitoring(e)}attemptReconnection(){Ko.info("attempt reconnection",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent&&this.userAgent.attemptReconnection()}storeSipSession(e){const t=this.getSipSessionId(e);Ko.info("storing sip session",{id:t,clientId:this.clientId}),this.sipSessions[t]=e}getSipSession(e){return e in this.sipSessions?this.sipSessions[e.substring(0,36)]:null}getSipSessionIds(){return Object.keys(this.sipSessions)}setLocalMediaStream(e,t){const i=this.sipSessions[e];i&&(Ko.info("setting local media stream",{sipSessionId:e,tracks:t?t.getTracks():null}),i.sessionDescriptionHandler&&(i.sessionDescriptionHandler._localMediaStream=t))}async updateLocalStream(e,t){const i=this.sipSessions[e];if(!i)return;const n=this.getLocalStream(e);Ko.info("updating local stream",{sipSessionId:e,oldStream:!!n,tracks:t.getTracks()}),n&&this._cleanupStream(n),this.setLocalMediaStream(e,t),await this._setupMedias(i,t)}updateRemoteStream(e,t=!0){const i=this.getRemoteStream(e),n=this.getPeerConnection(e);Ko.info("Updating remote stream",{sessionId:e,tracks:i?i.getTracks():null,receiverTracks:n&&n.getReceivers?n.getReceivers().map((e=>e.track)):null}),n&&i&&(i.getTracks().forEach((e=>{(t||"video"===e.kind)&&i.removeTrack(e)})),n.getReceivers&&n.getReceivers().forEach((e=>{(t||"video"===e.track.kind)&&i.addTrack(e.track)})))}getMediaConfiguration(e,t=!1,i=null){const n=!(!i||!("screen"in i))&&i.screen,r=!(!i||!("desktop"in i))&&i.desktop,s=!i||!("audio"in i)||i.audio,a=i&&"object"==typeof i.video?i.video.mandatory:{};return Ko.info("Retrieving media a configuration",{enableVideo:e,screenSharing:n,isDesktop:r,withAudio:s,constraints:i}),{constraints:{audio:n?!r:!!s&&this._getAudioConstraints(),video:n?r?{mandatory:{chromeMediaSource:"desktop",...a||{}}}:{cursor:"always"}:this._getVideoConstraints(e),screen:n,desktop:r,conference:t},enableVideo:e,conference:t,offerOptions:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:e,mandatory:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:e}}}}isConference(e){return e in this.conferences}async createAudioElementFor(e){const t=document.createElement("audio");return t.setAttribute("id",`audio-${e}`),Ko.info("creating audio element",{sessionId:e,audioOutputDeviceId:this.audioOutputDeviceId}),this.audioOutputDeviceId&&await t.setSinkId(this.audioOutputDeviceId),document.body&&document.body.appendChild(t),this.audioElements[e]=t,t.volume=this.audioOutputVolume,t.autoplay=!0,t}_onTransportError(){Ko.error("on transport error"),this.eventEmitter.emit(ec),this.attemptReconnection()}enableLogger(e){this.userAgent&&(this.userAgent?.transport&&(this.userAgent.transport.configuration.traceSip=!0),this.userAgent.loggerFactory.builtinEnabled=!0,this.userAgent.loggerFactory.level=3,this.userAgent.loggerFactory.connector=e)}_onHeartbeat(e){const t=e&&"object"==typeof e?e.data:e;t&&-1!==t.indexOf("200 OK")&&this.hasHeartbeat()&&(Ko.info("on heartbeat received from Asterisk",{hasHeartbeat:this.hasHeartbeat()}),this.heartbeat.onHeartbeat(),this.heartbeatCb&&this.heartbeatCb())}async _onHeartbeatTimeout(){if(Ko.warn("sdk webrtc heartbeat timed out",{userAgent:!!this.userAgent,cb:!!this.heartbeatTimeoutCb}),this.heartbeatTimeoutCb&&this.heartbeatTimeoutCb(),this.userAgent&&this.userAgent.transport){const e=this.userAgent.transport;if(!e.transitioningState&&!e.disconnectPromise)try{await this.userAgent.transport.disconnect()}catch(e){Ko.error("Transport disconnection after heartbeat timeout, error",e)}this._onTransportError()}}_isWeb(){return"object"==typeof window&&"object"==typeof document}_isVideoTrack(e){return"video"===e.kind&&"live"===e.readyState}_hasAudio(){return this.hasAudio}_getAudioConstraints(){return!this.audio?.deviceId?.exact||this.audio}_getVideoConstraints(e=!1){return!!e&&(!this.video?.deviceId?.exact||this.video)}_connectIfNeeded(){return Ko.info("connect if needed, checking",{connected:this.isConnected(),clientId:this.clientId}),this.userAgent||(Ko.info("need to recreate User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),this.isConnected()?(Ko.info("webrtc sdk, already connected"),Promise.resolve()):this.isConnecting()?(Ko.info("webrtc sdk, already connecting..."),this.connectionPromise=this.userAgent.transport.connectPromise,Promise.resolve(this.connectionPromise)):this.connectionPromise?(Ko.info("webrtc sdk, connection promise connecting..."),this.connectionPromise):(Ko.info("WebRTC UA needs to connect"),this.userAgent&&this.userAgent.state!==Cr.Stopped&&this.userAgent.transitionState(Cr.Stopped),this.userAgent.transport&&this.userAgent.transport.state!==Er.Disconnected&&this.userAgent.transport.transitionState(Er.Disconnected),this.connectionPromise=this.userAgent.start().catch(console.error),this.connectionPromise)}_buildConfig(e,t){if(!t)return new Promise((t=>t(e)));const i=new nn({server:`${e.host}:${String(e.port||443)}`});return i.setToken(t.token),i.setRefreshToken(t.refreshToken),i.confd.getUserLineSipFromToken(t.uuid).then((t=>({authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e.host}`,...e})))}_createUaOptions(e={}){let{host:t}=this.config,i=this.config.port||443;if(this.config.websocketSip){const e=this.config.websocketSip.split(":");[t]=e,i=Number(e[1])}const{userUuid:n}=this.config,r={noAnswerTimeout:86400,authorizationUsername:this.config.authorizationUser,authorizationPassword:this.config.password,displayName:this.config.displayName,hackIpInContact:!0,contactParams:{transport:"wss"},logBuiltinEnabled:this.config.log?this.config.log.builtinEnabled:null,logLevel:this.config.log?this.config.log.logLevel:null,logConnector:this.config.log?this.config.log.connector:null,uri:this._makeURI(this.config.authorizationUser||""),userAgentString:this.config.userAgentString||"wazo-sdk",reconnectionAttempts:1e4,reconnectionDelay:5,sessionDescriptionHandlerFactory:(e,t={})=>{const i=e.userAgent.getLogger("sip.WazoSessionDescriptionHandler"),n=this._isWeb(),r="peerConnectionOptions"in t&&t.peerConnectionOptions.iceGatheringTimeout||3e3,s={...t,iceGatheringTimeout:r,peerConnectionConfiguration:{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require",...t.peerConnectionConfiguration||{}}};return new Uo(i,Bo,s,n,e)},transportOptions:{traceSip:e?.traceSip||!1,wsServers:`wss://${t}:${i}/api/asterisk/ws${n?`?userUuid=${n}`:""}`},sessionDescriptionHandlerFactoryOptions:{modifiers:[qo],alwaysAcquireMediaFirst:this.isFirefox(),constraints:{audio:this._getAudioConstraints(),video:this._getVideoConstraints()},peerConnectionOptions:{iceCheckingTimeout:this.config.iceCheckingTimeout||1e3,iceGatheringTimeout:this.config.iceCheckingTimeout||1e3,rtcConfiguration:{rtcpMuxPolicy:"require",iceServers:fc.getIceServers(this.config.host),...this._getRtcOptions(),...e?.peerConnectionOptions||{}}},peerConnectionConfiguration:{rtcpMuxPolicy:"require",iceServers:fc.getIceServers(this.config.host),...e?.peerConnectionOptions||{}}}};return delete e?.traceSip,{...r,...e}}_getRtcOptions(){return{mandatory:{OfferToReceiveAudio:this._hasAudio(),OfferToReceiveVideo:!1}}}_setupSession(e){const t=this.getSipSessionId(e);e.delegate||(e.delegate={}),e.delegate.onSessionDescriptionHandler=e=>{e.on("error",(e=>{this.eventEmitter.emit(cc,e)})),e.peerConnectionDelegate={onicecandidateerror:e=>{Ko.error("on icecandidate error",{address:e.address,port:e.port,errorCode:e.errorCode,errorText:e.errorText,url:e.url})}}};const i=e.onInviteRequest.bind(e);let n=!1;e.onInviteRequest=e=>{n=this.hasARemoteVideoTrack(t),i(e)},e.delegate.onInvite=async i=>{let r=null,s=null;return e.assertedIdentity&&(s=e.assertedIdentity.uri.normal.user,r=e.assertedIdentity.displayName||s),Ko.info("re-invite received",{updatedCalleeName:r,updatedNumber:s,hadRemoteVideo:n}),e instanceof vr?e.incomingInviteRequest.message.body=i.body:e instanceof yr&&e.outgoingInviteRequest.message.body&&(e.outgoingInviteRequest.message.body.body=i.body),this.updateRemoteStream(t,!1),await this._setupMedias(e),this.eventEmitter.emit(oc,e,i,r,s,n)}}async _onProgress(e,t=!1){await this._setupMedias(e);const i=this.getSipSessionId(e).substr(0,20);this.updateRemoteStream(i),Ko.info("progress received",{sessionId:i,early:t}),this.eventEmitter.emit(t?ac:sc,e)}async _onAccepted(e,t,i=!0,n=!0){Ko.info("on call accepted",{id:e.id,clientId:this.clientId,remoteTag:e.remoteTag}),this.storeSipSession(e),await this._setupMedias(e),this.updateRemoteStream(this.getSipSessionId(e),n);const r=e.sessionDescriptionHandler?.peerConnection,s=t=>{const i=this._isAudioOnly(e),{kind:n,label:r,readyState:s,id:a,muted:o}=t.track;Ko.info("on track event",{isAudioOnly:i,kind:n,label:r,readyState:s,id:a,muted:o}),i&&"video"===n&&t.track.stop(),this.eventEmitter.emit(rc,e,t)},a=e.sessionDescriptionHandler;a?.peerConnection&&a.peerConnection.addEventListener("track",s),a.remoteMediaStream.onaddtrack=s,r&&(r.oniceconnectionstatechange=()=>{Ko.info("on ice connection state changed",{state:r.iceConnectionState}),"disconnected"===r.iceConnectionState&&this.eventEmitter.emit(hc)}),i&&this.eventEmitter.emit(ic,e,t),this._startSendingStats(e)}_isAudioOnly(e){return Boolean(e.sessionDescriptionHandlerModifiersReInvite.find((e=>e===wo)))}async _setupMedias(e,t=null){if(!this._isWeb())return void Ko.info("Setup media on mobile, no need to setup html element, bailing");const i=this.getSipSessionId(e),n=this.isConference(i);if(i in this.audioElements)return void Ko.info("html element already exists for session",{sessionId:i});this._hasAudio()&&this._isWeb()&&!(i in this.audioElements)&&await this.createAudioElementFor(i);const r=this.audioElements[i],s=this.sipSessions[e.callId],a=this.getRemoteStream(i),o=s?.sessionDescriptionHandler,c=o?o.remoteMediaStream:null,d=t||a||c;if(!d)return void Ko.info("Setup media no stream to attach, bailing");const l=r.currentTime>0&&!r.paused&&!r.ended&&r.readyState>2;Ko.info("setting up media",{sessionId:i,streams:{new:!!t,remove:!!a,early:!!c},hasAudio:this._hasAudio(),isConference:n,shouldPause:l}),n||(l&&r.pause(),r.srcObject=d,r.volume=this.audioOutputVolume,r.play().catch((()=>{})))}_cleanupMedia(e){const t=this.getSipSessionId(e),i=this.getLocalStream(t);i&&this._cleanupStream(i);const n=e=>{const t=this.audioElements[e];t&&(t.pause(),t.parentNode&&t.parentNode.removeChild(t),t.srcObject=null,delete this.audioElements[e])};this._hasAudio()&&this._isWeb()&&(e?n(this.getSipSessionId(e)):Object.keys(this.audioElements).forEach((e=>n(e))))}_cleanupStream(e){e.getTracks().filter((e=>e.enabled)).forEach((e=>e.stop()))}_toggleAudio(e,t){const i=e.sessionDescriptionHandler,n=i?.peerConnection||null;n&&(n.getSenders?n.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(e.track.enabled=!t)})):n.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{e.enabled=!t}))})))}_toggleVideo(e,t){const i=e.sessionDescriptionHandler,n=i?.peerConnection;n?.getSenders?n.getSenders().forEach((e=>{e&&e.track&&"video"===e.track.kind&&(e.track.enabled=!t)})):n.getLocalStreams().forEach((e=>{e.getVideoTracks().forEach((e=>{e.enabled=!t}))}))}_getRemoteStream(e){let t=null;return e&&e.getReceivers?(t="undefined"!=typeof global&&global.window&&global.window.MediaStream?new global.window.MediaStream:new window.MediaStream,e.getReceivers().forEach((e=>{const{track:i}=e;i&&t&&t.addTrack(i)}))):e&&([t]=e.getRemoteStreams()),t}_cleanupRegister(){this.registerer&&(this.registerer.stateChange.removeAllListeners(),this.registerer=null)}_startSendingStats(e){const t=e.sessionDescriptionHandler.peerConnection;if(!t)return;const i=this.getSipSessionId(e);$o(t,(e=>{const{results:t,internal:n,nomore:r,...s}=e;this.statsIntervals[i]=r,Wo.trace("stats",{sessionId:i,...s})}),5e3)}_stopSendingStats(e){const t=this.getSipSessionId(e);Ko.trace("Check for stopping stats",{sessionId:t,ids:Object.keys(this.statsIntervals)}),t in this.statsIntervals&&(Ko.trace("Stop sending stats for call",{sessionId:t}),this.statsIntervals[t](),delete this.statsIntervals[t])}_makeURI(e){return bs.makeURI(`sip:${e}@${this.config.host}`)}async _disconnectTransport(e=!1){const t=this.userAgent?.transport;if(e&&t)return t.disconnectResolve=()=>{},void(t._ws&&t._ws.close(1e3));if(t&&!t.disconnectPromise)try{await t.disconnect()}catch(e){Ko.error("WebRTC transport disconnect, error",e)}}async _fetchNetworkStats(e){const t=this.getSipSession(e),i=t?await this.getStats(t):null;if(!i||!(e in this.sessionNetworkStats))return Promise.resolve(null);const n={audioBytesSent:0,videoBytesSent:0,videoBytesReceived:0,audioBytesReceived:0},r=this.sessionNetworkStats[e].length,s=this.sessionNetworkStats[e][r-1],a=s?s.audioBytesSent:0,o=s?s.audioContentSent:0,c=s?s.videoBytesSent:0,d=s?s.audioBytesReceived:0,l=s?s.audioContentReceived:0,h=s?s.videoBytesReceived:0,u=s?s.transportSent:0,p=s?s.transportReceived:0;let g=0,f=0,m=0,v=0,y=0,S=0,b=0,w=0,E=0;i.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.kind&&(g+=Number(e.bytesSent)+Number(e.headerBytesSent),m+=Number(e.bytesSent)),"remote-outbound-rtp"===e.type&&"audio"===e.kind&&(g+=Number(e.bytesSent)),"outbound-rtp"===e.type&&"video"===e.kind&&(y+=Number(e.bytesSent)+Number(e.headerBytesSent)),"inbound-rtp"===e.type&&"audio"===e.kind&&(E+=Number(e.packetsLost),n.packetsReceived=Number(e.packetsReceived),f+=Number(e.bytesReceived)+Number(e.headerBytesReceived),v+=Number(e.bytesReceived)),"inbound-rtp"===e.type&&"video"===e.kind&&(S+=Number(e.bytesReceived)+Number(e.headerBytesReceived)),"outbound-rtp"===e.type&&"video"===e.kind&&("framesPerSecond"in e&&(n.framesPerSecond=Number(e.framesPerSecond)),"framerateMean"in e&&(n.framesPerSecond=Math.round(e.framerateMean))),"remote-inbound-rtp"===e.type&&"audio"===e.kind&&(E+=Number(e.packetsLost),n.roundTripTime=Number(e.roundTripTime),n.jitter=Number(e.jitter)),"remote-inbound-rtp"===e.type&&"video"===e.kind&&(E+=Number(e.packetsLost)),"transport"===e.type&&(b+=Number(e.bytesSent),w+=Number(e.bytesReceived))})),n.packetsLost=E,n.totalAudioBytesSent=g,n.audioBytesSent=g-a,n.totalAudioBytesReceived=f-d,n.audioBytesReceived=f,n.totalAudioContentSent=m,n.audioContentSent=m-o,n.totalAudioBytesReceived=v-l,n.audioContentReceived=v,n.totalVideoBytesSent=y,n.videoBytesSent=y-c,n.totalVideoBytesReceived=S,n.videoBytesReceived=S-h,n.totalTransportSent=b-u,n.transportSent=b,n.totalTransportReceived=w,n.transportReceived=w-p,n.bandwidth=n.audioBytesSent+n.audioBytesReceived+n.videoBytesSent+n.videoBytesReceived+n.transportReceived+n.transportSent,this.sessionNetworkStats[e]&&(this.eventEmitter.emit(lc,t,n,this.sessionNetworkStats[e]),e in this.sessionNetworkStats&&this.sessionNetworkStats[e].push(n))}async _accept(e,t={}){if(e.state===mi.Terminated||e.state===mi.Terminating){const t="Trying to accept a terminated sipSession.";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(e.state!==mi.Initial){const t="Trying to accept a non Initial sipSession.";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(!e.incomingInviteRequest.acceptable){const t="Trying to reject a non `acceptable` session";throw Ko.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}try{return await e.accept(t)}catch(e){Ko.warn("Session accept, error",e)}}async _reject(e,t={}){if(e.state===mi.Initial||e.state===mi.Establishing)if(e.incomingInviteRequest.rejectable)try{return await e.reject(t)}catch(e){Ko.warn("Session reject, error",e)}else Ko.warn("Trying to reject a non `rejectable` session",{state:e.state,sessionId:e.id});else Ko.warn("Trying to reject a session in a wrong state",{state:e.state,sessionId:e.id})}async _cancel(e,t={}){if(e.state===mi.Initial||e.state===mi.Establishing)try{return await e.cancel(t)}catch(e){Ko.warn("Session cancel, error",e)}else Ko.warn("Trying to cancel a session in a wrong state",{state:e.state,sessionId:e.id})}async _bye(e,t={}){if(e.state!==mi.Established)return Ko.warn("Trying to end a session in a wrong state",{state:e.state,sessionId:e.id}),null;try{return await e.bye(t)}catch(e){Ko.warn("Session bye, error",e)}return null}}class mc extends Error{constructor(e="Sorry your user is not configured to support video conference"){super(e),this.name="SFUNotAvailableError"}}const vc=B.loggerFor("simple-phone"),yc=B.loggerFor("sip.js"),Sc=B.loggerFor("sip"),bc=["Received WebSocket text message:","Sending WebSocket message:"];class wc extends Fi{client;phone;session;sipLine;SessionState;ON_USER_AGENT;ON_REGISTERED;ON_UNREGISTERED;ON_PROGRESS;ON_CALL_ACCEPTED;ON_CALL_ANSWERED;ON_CALL_INCOMING;ON_CALL_OUTGOING;ON_CALL_MUTED;ON_CALL_UNMUTED;ON_CALL_RESUMED;ON_CALL_HELD;ON_CALL_UNHELD;ON_CAMERA_DISABLED;ON_CAMERA_RESUMED;ON_CALL_CANCELED;ON_CALL_FAILED;ON_CALL_REJECTED;ON_CALL_ENDED;ON_CALL_ENDING;ON_MESSAGE;ON_REINVITE;ON_TRACK;ON_AUDIO_STREAM;ON_VIDEO_STREAM;ON_REMOVE_STREAM;ON_SHARE_SCREEN_STARTED;ON_SHARE_SCREEN_ENDING;ON_SHARE_SCREEN_ENDED;ON_TERMINATE_SOUND;ON_PLAY_RING_SOUND;ON_PLAY_INBOUND_CALL_SIGNAL_SOUND;ON_PLAY_HANGUP_SOUND;ON_PLAY_PROGRESS_SOUND;ON_VIDEO_INPUT_CHANGE;ON_CALL_ERROR;ON_MESSAGE_TRACK_UPDATED;ON_NETWORK_STATS;ON_CHAT;ON_SIGNAL;ON_DISCONNECTED;ON_EARLY_MEDIA;MESSAGE_TYPE_CHAT;MESSAGE_TYPE_SIGNAL;constructor(){super(),Object.keys(ga).forEach((e=>{this[e]=ga[e]})),this.SessionState=mi}async connect(e={},t=null){const i=e;if(this.phone)return void(i.media&&this.phone.setMediaConstraints(i.media));const n=Ol.Auth.getHost(),r=Ol.Auth.getSession();if(!n||!r)throw new Error("Please connect to the server using `Wazo.Auth.logIn` or `Wazo.Auth.authenticate` before using Room.connect().");if(this.session=r,this.sipLine=t||this.getPrimaryWebRtcLine(),!this.sipLine)throw new Error("Sorry, no sip lines found for this user");i.userUuid=r.uuid||"",this.connectWithCredentials(n,this.sipLine,r.displayName(),i)}connectWithCredentials(e,t,i,n={}){if(this.phone)return;const[r,s=443]=e.split(":"),a=n;a.media=a.media||{audio:!0,video:!1},a.uaConfigOverrides=a.uaConfigOverrides||{},B.enabled&&(a.uaConfigOverrides.traceSip=!0,a.log=a.log||{},a.log.builtinEnabled=!1,a.log.logLevel="debug",a.log.connector=this._logConnector),this.client=new fc({host:r,port:"string"==typeof s?parseInt(s,10):s,displayName:i,authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e}`,...a},void 0,a.uaConfigOverrides),this.phone=new pa(this.client,a.audioDeviceOutput,!0,a.audioDeviceRing),this._transferEvents()}async disconnect(){this.phone&&(this.phone.hasAnActiveCall()&&(vc.info("hangup call on disconnect"),await this.phone.hangup()),await this.phone.close()),this.phone=null}async call(e,t=!1,i=null,n=!1,r=!1){if(!this.phone)return;const s=i||this.getPrimaryWebRtcLine();return this.phone.makeCall(e,s,t,n,r)}async hangup(e){return vc.info("hangup via simple phone",{callId:e.getId()}),!!this.phone&&this.phone.hangup(e)}async accept(e,t){return vc.info("accept via simple phone",{callId:e.getId(),cameraEnabled:t}),this.phone?this.phone.accept(e,t):null}async startConference(e,t){const i=[e,...t].reduce(((e,t)=>(e[t.getTalkingToIds()[0]]=t,e)),{});if(!this.phone)return Promise.reject();return new Cn({phone:this.phone,host:e,participants:i}).start()}mute(e,t=!0){t&&this.muteViaAPI(e),this.phone?.mute(e)}unmute(e,t=!0){t&&this.unmuteViaAPI(e),this.phone?.unmute(e)}muteViaAPI(e){e&&e.callId&&Ol.getApiClient().calld.mute(e.callId).catch((e=>{vc.error("Mute via API, error",e)}))}unmuteViaAPI(e){e&&e.callId&&Ol.getApiClient().calld.unmute(e.callId).catch((e=>{vc.error("Unmute via API, error",e)}))}hold(e){return this.phone?.hold(e,!0)}async unhold(e){return this.phone?.unhold(e,!0)}async resume(e){return this.phone?.resume(e)||null}reject(e){return this.phone?.reject(e)}transfer(e,t){this.phone?.transfer(e,t)}atxfer(e){return this.phone?.atxfer(e)||null}async reinvite(e,t=null,i=!1){return this.phone?this.phone.sendReinvite(e,t,i):null}async getStats(e){return this.phone?this.phone.getStats(e):null}startNetworkMonitoring(e,t=1e3){return this.phone?this.phone.startNetworkMonitoring(e,t):null}stopNetworkMonitoring(e){return this.phone?this.phone.stopNetworkMonitoring(e):null}getSipSessionId(e){return e&&this.phone?this.phone.getSipSessionId(e):null}sendMessage(e,t,i="text/plain"){const n=t||this.getCurrentSipSession();n&&this.phone&&this.phone.sendMessage(n,e,i)}sendChat(e,t){this.sendMessage(JSON.stringify({type:da,content:e}),t,"application/json")}sendSignal(e,t){this.sendMessage(JSON.stringify({type:la,content:e}),t,"application/json")}turnCameraOff(e){this.phone?.turnCameraOff(e)}turnCameraOn(e){this.phone?.turnCameraOn(e)}async startScreenSharing(e,t){return this.phone?.startScreenSharing(e,t)||null}stopScreenSharing(e,t=!0){return this.phone?this.phone.stopScreenSharing(t,e):Promise.resolve()}sendDTMF(e,t){this.phone?.sendKey(t,e)}getLocalStream(e){return this.phone?.getLocalStream(e)}hasLocalVideo(e){return this.phone?.hasLocalVideo(e)||!1}hasALocalVideoTrack(e){return this.phone?.hasALocalVideoTrack(e)||!1}getLocalMediaStream(e){return vc.warn("Phone.getLocalMediaStream is deprecated, use Phone.getLocalStream instead"),this.phone?.getLocalStream(e)}getLocalVideoStream(e){return this.phone?.getLocalVideoStream(e)||null}getRemoteStream(e){return this.phone?.getRemoteStream(e)||null}getRemoteVideoStream(e){return this.phone?.getRemoteVideoStream(e)||null}isVideoRemotelyHeld(e){return this.phone?.isVideoRemotelyHeld(e)||!1}getRemoteStreamForCall(e){return vc.warn("Phone.getRemoteStreamForCall is deprecated, use Phone.getRemoteStream instead"),this.getRemoteStream(e)||null}getRemoteStreamsForCall(e){return vc.warn("Phone.getRemoteStreamsForCall is deprecated, use Phone.getLocalStream instead"),this.getLocalStream(e)||null}getRemoteVideoStreamForCall(e){return vc.warn("Phone.getRemoteVideoStreamForCall is deprecated, use Phone.getRemoteVideoStream instead"),this.getRemoteVideoStream(e)}getRemoteVideoStreamFromPc(e){return this.phone?.getRemoteVideoStreamFromPc(e)||null}hasVideo(e){return!!this.phone&&this.phone.hasVideo(e)}hasAVideoTrack(e){return!!this.phone&&this.phone.hasAVideoTrack(e)}getCurrentSipSession(){return this.phone?.currentSipSession||null}getPrimaryWebRtcLine(){const e=Ol.Auth.getSession();return e?.primaryWebRtcLine()||null}getOutputDevice(){return this.phone?.audioOutputDeviceId||null}getPrimaryLine(){const e=Ol.Auth.getSession();return e?.primarySipLine()||null}getLineById(e){return this.getSipLines().find((t=>t&&t.id===e))||null}getSipLines(){const e=Ol.Auth.getSession();return e&&e.profile?.sipLines||[]}hasSfu(){return this.sipLine?.hasVideoConference()||!1}checkSfu(){if(!this.hasSfu())throw new mc}enableLogger(){this.client.enableLogger(this._logConnector)}_transferEvents(){this.unbind(),[...uc,...pc].forEach((e=>{this.client.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter.emit,[`client-${e}`,...t])))})),Object.values(ga).forEach((e=>{"string"==typeof e&&this.phone&&this.phone.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter,[e,...t])))}))}_logConnector(e,t,i,n){const r=n&&n.indexOf?bc.findIndex((e=>-1!==n.indexOf(e))):-1;if("sip.Transport"===t&&-1!==r){const e=0===r?"receiving":"sending",i=n.replace(`${bc[r]}\n\n`,"").replace("\r\n","\n");Sc.trace(i,{className:t,direction:e})}else yc.trace(n,{className:t})}}global.wazoTelephonyInstance||(global.wazoTelephonyInstance=new wc);var Ec=global.wazoTelephonyInstance,Cc=function(e,t){return Cc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},Cc(e,t)};
|
|
29
29
|
/*! *****************************************************************************
|
|
30
30
|
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
31
31
|
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|