@wazo/sdk 0.40.6 → 0.40.8

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 CHANGED
@@ -16,19 +16,16 @@ function Arcfour(){this.i=0,this.j=0,this.S=new Array}function ARC4init(e){var t
16
16
  */function rng_seed_int(e){rng_pool[rng_pptr++]^=255&e,rng_pool[rng_pptr++]^=e>>8&255,rng_pool[rng_pptr++]^=e>>16&255,rng_pool[rng_pptr++]^=e>>24&255,rng_pptr>=rng_psize&&(rng_pptr-=rng_psize)}function rng_seed_time(){rng_seed_int((new Date).getTime())}if(null==rng_pool){var t;if(rng_pool=new Array,rng_pptr=0,void 0!==window$1&&(void 0!==window$1.crypto||void 0!==window$1.msCrypto)){var crypto=window$1.crypto||window$1.msCrypto;if(crypto.getRandomValues){var ua=new Uint8Array(32);for(crypto.getRandomValues(ua),t=0;t<32;++t)rng_pool[rng_pptr++]=ua[t]}else if("Netscape"==navigator$1.appName&&navigator$1.appVersion<"5"){var z=window$1.crypto.random(32);for(t=0;t<z.length;++t)rng_pool[rng_pptr++]=255&z.charCodeAt(t)}}for(;rng_pptr<rng_psize;)t=Math.floor(65536*Math.random()),rng_pool[rng_pptr++]=t>>>8,rng_pool[rng_pptr++]=255&t;rng_pptr=0,rng_seed_time()}function rng_get_byte(){if(null==rng_state){for(rng_seed_time(),(rng_state=prng_newstate()).init(rng_pool),rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0}return rng_state.next()}function rng_get_bytes(e){var t;for(t=0;t<e.length;++t)e[t]=rng_get_byte()}function SecureRandom(){}
17
17
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
18
18
  */
19
- function parseBigInt(e,t){return new BigInteger(e,t)}function pkcs1pad2(e,t){if(t<e.length+11)throw"Message too long for RSA";for(var r=new Array,n=e.length-1;n>=0&&t>0;){var i=e.charCodeAt(n--);i<128?r[--t]=i:i>127&&i<2048?(r[--t]=63&i|128,r[--t]=i>>6|192):(r[--t]=63&i|128,r[--t]=i>>6&63|128,r[--t]=i>>12|224)}r[--t]=0;for(var s=new SecureRandom,o=new Array;t>2;){for(o[0]=0;0==o[0];)s.nextBytes(o);r[--t]=o[0]}return r[--t]=2,r[--t]=0,new BigInteger(r)}function oaep_mgf1_arr(e,t,r){for(var n="",i=0;n.length<t;)n+=r(String.fromCharCode.apply(String,e.concat([(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return n}function oaep_pad(e,t,r,n){var i=KJUR.crypto.MessageDigest,s=KJUR.crypto.Util,o=null;if(r||(r="sha1"),"string"==typeof r&&(o=i.getCanonicalAlgName(r),n=i.getHashLength(o),r=function(e){return hextorstr(s.hashHex(rstrtohex(e),o))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,d="";for(a=0;a<t-e.length-2*n-2;a+=1)d+="\0";var c=r("")+d+""+e,l=new Array(n);(new SecureRandom).nextBytes(l);var u=oaep_mgf1_arr(l,c.length,r),h=[];for(a=0;a<c.length;a+=1)h[a]=c.charCodeAt(a)^u.charCodeAt(a);var g=oaep_mgf1_arr(h,l.length,r),p=[0];for(a=0;a<l.length;a+=1)p[a+1]=l[a]^g.charCodeAt(a);return new BigInteger(p.concat(h))}function RSAKey(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function RSASetPublic(e,t){if(this.isPublic=!0,this.isPrivate=!1,"string"!=typeof e)this.n=e,this.e=t;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA public key";this.n=parseBigInt(e,16),this.e=parseInt(t,16)}}function RSADoPublic(e){return e.modPowInt(this.e,this.n)}function RSAEncrypt(e){var t=pkcs1pad2(e,this.n.bitLength()+7>>3);if(null==t)return null;var r=this.doPublic(t);if(null==r)return null;var n=r.toString(16);return 0==(1&n.length)?n:"0"+n}function RSAEncryptOAEP(e,t,r){var n=this.n.bitLength()+7>>3,i=oaep_pad(e,n,t,r);if(null==i)return null;var s=this.doPublic(i);if(null==s)return null;for(var o=s.toString(16);o.length<2*n;)o="0"+o;return o}
20
- /*! (c) Tom Wu, Kenji Urushima | http://www-cs-students.stanford.edu/~tjw/jsbn/
21
- */
22
- function pkcs1unpad2(e,t){for(var r=e.toByteArray(),n=0;n<r.length&&0==r[n];)++n;if(r.length-n!=t-1||2!=r[n])return null;for(++n;0!=r[n];)if(++n>=r.length)return null;for(var i="";++n<r.length;){var s=255&r[n];s<128?i+=String.fromCharCode(s):s>191&&s<224?(i+=String.fromCharCode((31&s)<<6|63&r[n+1]),++n):(i+=String.fromCharCode((15&s)<<12|(63&r[n+1])<<6|63&r[n+2]),n+=2)}return i}function oaep_mgf1_str(e,t,r){for(var n="",i=0;n.length<t;)n+=r(e+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])),i+=1;return n}function oaep_unpad(e,t,r,n){var i=KJUR.crypto.MessageDigest,s=KJUR.crypto.Util,o=null;for(r||(r="sha1"),"string"==typeof r&&(o=i.getCanonicalAlgName(r),n=i.getHashLength(o),r=function(e){return hextorstr(s.hashHex(rstrtohex(e),o))}),e=e.toByteArray(),a=0;a<e.length;a+=1)e[a]&=255;for(;e.length<t;)e.unshift(0);if((e=String.fromCharCode.apply(String,e)).length<2*n+2)throw"Cipher too short";var a,d=e.substr(1,n),c=e.substr(n+1),l=oaep_mgf1_str(c,n,r),u=[];for(a=0;a<d.length;a+=1)u[a]=d.charCodeAt(a)^l.charCodeAt(a);var h=oaep_mgf1_str(String.fromCharCode.apply(String,u),e.length-n,r),g=[];for(a=0;a<c.length;a+=1)g[a]=c.charCodeAt(a)^h.charCodeAt(a);if((g=String.fromCharCode.apply(String,g)).substr(0,n)!==r(""))throw"Hash mismatch";var p=(g=g.substr(n)).indexOf("");if((-1!=p?g.substr(0,p).lastIndexOf("\0"):-1)+1!=p)throw"Malformed data";return g.substr(p+1)}function RSASetPrivate(e,t,r){if(this.isPrivate=!0,"string"!=typeof e)this.n=e,this.e=t,this.d=r;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16)}}function RSASetPrivateEx(e,t,r,n,i,s,o,a){if(this.isPrivate=!0,this.isPublic=!1,null==e)throw"RSASetPrivateEx N == null";if(null==t)throw"RSASetPrivateEx E == null";if(0==e.length)throw"RSASetPrivateEx N.length == 0";if(0==t.length)throw"RSASetPrivateEx E.length == 0";if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key in RSASetPrivateEx";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16),this.p=parseBigInt(n,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(s,16),this.dmq1=parseBigInt(o,16),this.coeff=parseBigInt(a,16)}function RSAGenerate(e,t){var r=new SecureRandom,n=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16),s=e/2-100,o=BigInteger.ONE.shiftLeft(s);;){for(;this.p=new BigInteger(e-n,1,r),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(n,1,r),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var a=this.p;this.p=this.q,this.q=a}var d=this.q.subtract(this.p).abs();if(!(d.bitLength()<s||d.compareTo(o)<=0)){var c=this.p.subtract(BigInteger.ONE),l=this.q.subtract(BigInteger.ONE),u=c.multiply(l);if(0==u.gcd(i).compareTo(BigInteger.ONE)&&(this.n=this.p.multiply(this.q),this.n.bitLength()==e)){this.d=i.modInverse(u),this.dmp1=this.d.mod(c),this.dmq1=this.d.mod(l),this.coeff=this.q.modInverse(this.p);break}}}this.isPrivate=!0}function RSADoPrivate(e){if(null==this.p||null==this.q)return e.modPow(this.d,this.n);for(var t=e.mod(this.p).modPow(this.dmp1,this.p),r=e.mod(this.q).modPow(this.dmq1,this.q);t.compareTo(r)<0;)t=t.add(this.p);return t.subtract(r).multiply(this.coeff).mod(this.p).multiply(this.q).add(r)}function RSADecrypt(e){if(e.length!=Math.ceil(this.n.bitLength()/4))throw new Error("wrong ctext length");var t=parseBigInt(e,16),r=this.doPrivate(t);return null==r?null:pkcs1unpad2(r,this.n.bitLength()+7>>3)}function RSADecryptOAEP(e,t,r){if(e.length!=Math.ceil(this.n.bitLength()/4))throw new Error("wrong ctext length");var n=parseBigInt(e,16),i=this.doPrivate(n);return null==i?null:oaep_unpad(i,this.n.bitLength()+7>>3,t,r)}
19
+ function parseBigInt(e,t){return new BigInteger(e,t)}function RSAKey(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function RSASetPublic(e,t){if(this.isPublic=!0,this.isPrivate=!1,"string"!=typeof e)this.n=e,this.e=t;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA public key";this.n=parseBigInt(e,16),this.e=parseInt(t,16)}}function RSADoPublic(e){return e.modPowInt(this.e,this.n)}function RSASetPrivate(e,t,r){if(this.isPrivate=!0,"string"!=typeof e)this.n=e,this.e=t,this.d=r;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16)}}function RSASetPrivateEx(e,t,r,n,i,s,o,a){if(this.isPrivate=!0,this.isPublic=!1,null==e)throw"RSASetPrivateEx N == null";if(null==t)throw"RSASetPrivateEx E == null";if(0==e.length)throw"RSASetPrivateEx N.length == 0";if(0==t.length)throw"RSASetPrivateEx E.length == 0";if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key in RSASetPrivateEx";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16),this.p=parseBigInt(n,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(s,16),this.dmq1=parseBigInt(o,16),this.coeff=parseBigInt(a,16)}function RSAGenerate(e,t){var r=new SecureRandom,n=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16),s=e/2-100,o=BigInteger.ONE.shiftLeft(s);;){for(;this.p=new BigInteger(e-n,1,r),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(n,1,r),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var a=this.p;this.p=this.q,this.q=a}var d=this.q.subtract(this.p).abs();if(!(d.bitLength()<s||d.compareTo(o)<=0)){var c=this.p.subtract(BigInteger.ONE),l=this.q.subtract(BigInteger.ONE),u=c.multiply(l);if(0==u.gcd(i).compareTo(BigInteger.ONE)&&(this.n=this.p.multiply(this.q),this.n.bitLength()==e)){this.d=i.modInverse(u),this.dmp1=this.d.mod(c),this.dmq1=this.d.mod(l),this.coeff=this.q.modInverse(this.p);break}}}this.isPrivate=!0}function RSADoPrivate(e){if(null==this.p||null==this.q)return e.modPow(this.d,this.n);for(var t=e.mod(this.p).modPow(this.dmp1,this.p),r=e.mod(this.q).modPow(this.dmq1,this.q);t.compareTo(r)<0;)t=t.add(this.p);return t.subtract(r).multiply(this.coeff).mod(this.p).multiply(this.q).add(r)}
23
20
  /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
24
21
  */
25
- function ECFieldElementFp(e,t){this.x=t,this.q=e}function feFpEquals(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(e){return new ECFieldElementFp(this.q,this.x.add(e.toBigInteger()).mod(this.q))}function feFpSubtract(e){return new ECFieldElementFp(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))}function feFpMultiply(e){return new ECFieldElementFp(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(e){return new ECFieldElementFp(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))}function ECPointFp(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?BigInteger.ONE:n,this.zinv=null}function pointFpGetX(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpGetY(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpEquals(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(BigInteger.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(BigInteger.ZERO))}function pointFpIsInfinity(){return null==this.x&&null==this.y||this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),r=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(r))return BigInteger.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new BigInteger("3"),i=this.x.toBigInteger(),s=this.y.toBigInteger();e.x.toBigInteger(),e.y.toBigInteger();var o=r.square(),a=o.multiply(r),d=i.multiply(o),c=t.square().multiply(this.z),l=c.subtract(d.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),u=d.multiply(n).multiply(t).subtract(s.multiply(a)).subtract(c.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),h=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(l),this.curve.fromBigInteger(u),h)}function pointFpTwice(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new BigInteger("3"),t=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),s=this.curve.a.toBigInteger(),o=t.square().multiply(e);BigInteger.ZERO.equals(s)||(o=o.add(this.z.square().multiply(s)));var a=(o=o.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),d=o.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(o.square().multiply(o)).mod(this.curve.q),c=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(d),c)}function pointFpMultiply(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new BigInteger("3")),i=this.negate(),s=this,o=this.curve.q.subtract(e),a=o.multiply(new BigInteger("3")),d=new ECPointFp(this.curve,this.x,this.y),c=d.negate();for(t=n.bitLength()-2;t>0;--t){s=s.twice();var l=n.testBit(t);l!=r.testBit(t)&&(s=s.add(l?this:i))}for(t=a.bitLength()-2;t>0;--t){d=d.twice();var u=a.testBit(t);u!=o.testBit(t)&&(d=d.add(u?d:c))}return s}function pointFpMultiplyTwo(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),s=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(s):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i}function ECCurveFp(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(e){return new ECFieldElementFp(this.q,e)}function curveFpDecodePointHex(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:var t=e.substr(0,2);e.substr(2);var r=this.fromBigInteger(new BigInteger(a,16)),n=this.getA(),i=this.getB(),s=r.square().add(n).multiply(r).add(i).sqrt();return"03"==t&&(s=s.negate()),new ECPointFp(this,r,s);case 4:case 6:case 7:var o=(e.length-2)/2,a=e.substr(2,o),d=e.substr(o+2,o);return new ECPointFp(this,this.fromBigInteger(new BigInteger(a,16)),this.fromBigInteger(new BigInteger(d,16)));default:return null}}SecureRandom.prototype.nextBytes=rng_get_bytes,RSAKey.prototype.doPublic=RSADoPublic,RSAKey.prototype.setPublic=RSASetPublic,RSAKey.prototype.encrypt=RSAEncrypt,RSAKey.prototype.encryptOAEP=RSAEncryptOAEP,RSAKey.prototype.type="RSA",RSAKey.prototype.doPrivate=RSADoPrivate,RSAKey.prototype.setPrivate=RSASetPrivate,RSAKey.prototype.setPrivateEx=RSASetPrivateEx,RSAKey.prototype.generate=RSAGenerate,RSAKey.prototype.decrypt=RSADecrypt,RSAKey.prototype.decryptOAEP=RSADecryptOAEP,ECFieldElementFp.prototype.equals=feFpEquals,ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger,ECFieldElementFp.prototype.negate=feFpNegate,ECFieldElementFp.prototype.add=feFpAdd,ECFieldElementFp.prototype.subtract=feFpSubtract,ECFieldElementFp.prototype.multiply=feFpMultiply,ECFieldElementFp.prototype.square=feFpSquare,ECFieldElementFp.prototype.divide=feFpDivide,ECFieldElementFp.prototype.sqrt=function(){return new ECFieldElementFp(this.q,this.x.sqrt().mod(this.q))},ECPointFp.prototype.getX=pointFpGetX,ECPointFp.prototype.getY=pointFpGetY,ECPointFp.prototype.equals=pointFpEquals,ECPointFp.prototype.isInfinity=pointFpIsInfinity,ECPointFp.prototype.negate=pointFpNegate,ECPointFp.prototype.add=pointFpAdd,ECPointFp.prototype.twice=pointFpTwice,ECPointFp.prototype.multiply=pointFpMultiply,ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo,ECCurveFp.prototype.getQ=curveFpGetQ,ECCurveFp.prototype.getA=curveFpGetA,ECCurveFp.prototype.getB=curveFpGetB,ECCurveFp.prototype.equals=curveFpEquals,ECCurveFp.prototype.getInfinity=curveFpGetInfinity,ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger,ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex,
22
+ function ECFieldElementFp(e,t){this.x=t,this.q=e}function feFpEquals(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(e){return new ECFieldElementFp(this.q,this.x.add(e.toBigInteger()).mod(this.q))}function feFpSubtract(e){return new ECFieldElementFp(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))}function feFpMultiply(e){return new ECFieldElementFp(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(e){return new ECFieldElementFp(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))}function ECPointFp(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?BigInteger.ONE:n,this.zinv=null}function pointFpGetX(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpGetY(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpEquals(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(BigInteger.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(BigInteger.ZERO))}function pointFpIsInfinity(){return null==this.x&&null==this.y||this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),r=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(r))return BigInteger.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new BigInteger("3"),i=this.x.toBigInteger(),s=this.y.toBigInteger();e.x.toBigInteger(),e.y.toBigInteger();var o=r.square(),a=o.multiply(r),d=i.multiply(o),c=t.square().multiply(this.z),l=c.subtract(d.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),u=d.multiply(n).multiply(t).subtract(s.multiply(a)).subtract(c.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),h=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(l),this.curve.fromBigInteger(u),h)}function pointFpTwice(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new BigInteger("3"),t=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),s=this.curve.a.toBigInteger(),o=t.square().multiply(e);BigInteger.ZERO.equals(s)||(o=o.add(this.z.square().multiply(s)));var a=(o=o.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),d=o.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(o.square().multiply(o)).mod(this.curve.q),c=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(d),c)}function pointFpMultiply(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new BigInteger("3")),i=this.negate(),s=this,o=this.curve.q.subtract(e),a=o.multiply(new BigInteger("3")),d=new ECPointFp(this.curve,this.x,this.y),c=d.negate();for(t=n.bitLength()-2;t>0;--t){s=s.twice();var l=n.testBit(t);l!=r.testBit(t)&&(s=s.add(l?this:i))}for(t=a.bitLength()-2;t>0;--t){d=d.twice();var u=a.testBit(t);u!=o.testBit(t)&&(d=d.add(u?d:c))}return s}function pointFpMultiplyTwo(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),s=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(s):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i}function ECCurveFp(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(e){return new ECFieldElementFp(this.q,e)}function curveFpDecodePointHex(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:var t=e.substr(0,2);e.substr(2);var r=this.fromBigInteger(new BigInteger(a,16)),n=this.getA(),i=this.getB(),s=r.square().add(n).multiply(r).add(i).sqrt();return"03"==t&&(s=s.negate()),new ECPointFp(this,r,s);case 4:case 6:case 7:var o=(e.length-2)/2,a=e.substr(2,o),d=e.substr(o+2,o);return new ECPointFp(this,this.fromBigInteger(new BigInteger(a,16)),this.fromBigInteger(new BigInteger(d,16)));default:return null}}SecureRandom.prototype.nextBytes=rng_get_bytes,RSAKey.prototype.doPublic=RSADoPublic,RSAKey.prototype.setPublic=RSASetPublic,RSAKey.prototype.type="RSA",RSAKey.prototype.doPrivate=RSADoPrivate,RSAKey.prototype.setPrivate=RSASetPrivate,RSAKey.prototype.setPrivateEx=RSASetPrivateEx,RSAKey.prototype.generate=RSAGenerate,ECFieldElementFp.prototype.equals=feFpEquals,ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger,ECFieldElementFp.prototype.negate=feFpNegate,ECFieldElementFp.prototype.add=feFpAdd,ECFieldElementFp.prototype.subtract=feFpSubtract,ECFieldElementFp.prototype.multiply=feFpMultiply,ECFieldElementFp.prototype.square=feFpSquare,ECFieldElementFp.prototype.divide=feFpDivide,ECFieldElementFp.prototype.sqrt=function(){return new ECFieldElementFp(this.q,this.x.sqrt().mod(this.q))},ECPointFp.prototype.getX=pointFpGetX,ECPointFp.prototype.getY=pointFpGetY,ECPointFp.prototype.equals=pointFpEquals,ECPointFp.prototype.isInfinity=pointFpIsInfinity,ECPointFp.prototype.negate=pointFpNegate,ECPointFp.prototype.add=pointFpAdd,ECPointFp.prototype.twice=pointFpTwice,ECPointFp.prototype.multiply=pointFpMultiply,ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo,ECCurveFp.prototype.getQ=curveFpGetQ,ECCurveFp.prototype.getA=curveFpGetA,ECCurveFp.prototype.getB=curveFpGetB,ECCurveFp.prototype.equals=curveFpEquals,ECCurveFp.prototype.getInfinity=curveFpGetInfinity,ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger,ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex,
26
23
  /*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib
27
24
  */
28
25
  ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},ECPointFp.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(t<r.length)r=r.slice(r.length-t);else for(;t>r.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},ECPointFp.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var s=new BigInteger(n),o=new BigInteger(i);return new ECPointFp(e,e.fromBigInteger(s),e.fromBigInteger(o))},ECPointFp.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),s=new BigInteger(n,16),o=new BigInteger(i,16);return new ECPointFp(e,e.fromBigInteger(s),e.fromBigInteger(o))},ECPointFp.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),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(BigInteger.valueOf(2)),t=this.curve.fromBigInteger(BigInteger.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new BigInteger("3")),i=this.negate(),s=this;for(t=n.bitLength()-2;t>0;--t){s=s.twice();var o=n.testBit(t);o!=r.testBit(t)&&(s=s.add2D(o?this:i))}return s},ECPointFp.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),s=t.multiply(t).mod(i),o=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return s.equals(o)},ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},ECPointFp.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(BigInteger.ONE)<0||t.compareTo(e.subtract(BigInteger.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(BigInteger.ONE)<0||r.compareTo(e.subtract(BigInteger.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};
29
26
  /*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval
30
27
  */
31
- var jsonParse=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"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),s=Object.hasOwnProperty;return function(r,o){var a,d,c=r.match(e),l=c[0],u=!1;"{"===l?a={}:"["===l?a=[]:(a=[],u=!0);for(var h=[a],g=1-u,p=c.length;g<p;++g){var m;switch((l=c[g]).charCodeAt(0)){default:(m=h[0])[d||m.length]=+l,d=void 0;break;case 34:if(-1!==(l=l.substring(1,l.length-1)).indexOf("\\")&&(l=l.replace(t,n)),m=h[0],!d){if(!(m instanceof Array)){d=l||i;break}d=m.length}m[d]=l,d=void 0;break;case 91:m=h[0],h.unshift(m[d||m.length]=[]),d=void 0;break;case 93:case 125:h.shift();break;case 102:(m=h[0])[d||m.length]=!1,d=void 0;break;case 110:(m=h[0])[d||m.length]=null,d=void 0;break;case 116:(m=h[0])[d||m.length]=!0,d=void 0;break;case 123:m=h[0],h.unshift(m[d||m.length]={}),d=void 0}}if(u){if(1!==h.length)throw new Error;a=a[0]}else if(h.length)throw new Error;if(o){var f=function(e,t){var r=e[t];if(r&&"object"==typeof r){var n=null;for(var i in r)if(s.call(r,i)&&r!==e){var a=f(r,i);void 0!==a?r[i]=a:(n||(n=[]),n.push(i))}if(n)for(var d=n.length;--d>=0;)delete r[n[d]]}return o.call(e,t,r)};a=f({"":a},"")}return a}}();void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.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){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i<r;i++)n+="f";t=new BigInteger(n,16).xor(e).add(BigInteger.ONE).toString(16).replace(/^-/,"")}return t},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,s=t.DERBitString,o=t.DEROctetString,a=t.DERNull,d=t.DERObjectIdentifier,c=t.DEREnumerated,l=t.DERUTF8String,u=t.DERNumericString,h=t.DERPrintableString,g=t.DERTeletexString,p=t.DERIA5String,m=t.DERUTCTime,f=t.DERGeneralizedTime,S=t.DERVisibleString,y=t.DERBMPString,b=t.DERSequence,E=t.DERSet,v=t.DERTaggedObject,_=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var T=Object.keys(e);if(1!=T.length)throw new Error("key of param shall be only one.");var R=T[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+R+":"))throw new Error("undefined key: "+R);if("bool"==R)return new n(e[R]);if("int"==R)return new i(e[R]);if("bitstr"==R)return new s(e[R]);if("octstr"==R)return new o(e[R]);if("null"==R)return new a(e[R]);if("oid"==R)return new d(e[R]);if("enum"==R)return new c(e[R]);if("utf8str"==R)return new l(e[R]);if("numstr"==R)return new u(e[R]);if("prnstr"==R)return new h(e[R]);if("telstr"==R)return new g(e[R]);if("ia5str"==R)return new p(e[R]);if("utctime"==R)return new m(e[R]);if("gentime"==R)return new f(e[R]);if("visstr"==R)return new S(e[R]);if("bmpstr"==R)return new y(e[R]);if("asn1"==R)return new r(e[R]);if("seq"==R){for(var $=e[R],C=[],A=0;A<$.length;A++){var N=_($[A]);C.push(N)}return new b({array:C})}if("set"==R){for($=e[R],C=[],A=0;A<$.length;A++){N=_($[A]);C.push(N)}return new E({array:C})}if("tag"==R){var I=e[R];if("[object Array]"===Object.prototype.toString.call(I)&&3==I.length){var w=_(I[2]);return new v({tag:I[0],explicit:I[1],obj:w})}return new v(I)}},this.jsonToASN1HEX=function(e){return this.newObject(e).tohex()}},KJUR.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",r=parseInt(e.substr(0,2),16),n=(t=Math.floor(r/40)+"."+r%40,""),i=2;i<e.length;i+=2){var s=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);if(n+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new BigInteger(n,2).toString(10),n=""}return t},KJUR.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=new BigInteger(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";n=s+n;for(o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n},KJUR.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 r=t.length/2;if(r>15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+r).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)},KJUR.asn1.DERAbstractString=function(e){KJUR.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=utf8tohex(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))},extendClass(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.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,r){var n=this.zeroPadding,i=this.localDateToUTC(e),s=String(i.getFullYear());"utc"==t&&(s=s.substr(2,2));var o=s+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var d=n(String(a),3);o=o+"."+(d=d.replace(/[0]+$/,""))}}return o+"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,r,n,i,s){var o=new Date(Date.UTC(e,t-1,r,n,i,s,0));this.setByDate(o)},this.getFreshValueHex=function(){return this.hV}},extendClass(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.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)},extendClass(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(e){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},extendClass(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex;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,r=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)r=new BigInteger(String(e),10);else if(null!=e.int)r=new BigInteger(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");r=e.bigint}return this.hV=t(r),this.hV},null!=e&&(this.params=e)},extendClass(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}KJUR.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 r="0"+e;this.hTLV=null,this.isModified=!0,this.hV=r+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 r="",n=0;n<e.length-1;n+=8){var i=e.substr(n,8),s=parseInt(i,2).toString(16);1==s.length&&(s="0"+s),r+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+r},this.setByBooleanArray=function(e){for(var t="",r=0;r<e.length;r++)1==e[r]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),r=0;r<e;r++)t[r]=!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))},extendClass(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object),KJUR.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex=t.tohex()}KJUR.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},extendClass(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},extendClass(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object),KJUR.asn1.DERObjectIdentifier=function(e){KJUR.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=oidtohex(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=KJUR.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)},extendClass(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.DEREnumerated=function(e){KJUR.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new BigInteger(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))},extendClass(KJUR.asn1.DEREnumerated,KJUR.asn1.ASN1Object),KJUR.asn1.DERUTF8String=function(e){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},extendClass(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNumericString=function(e){KJUR.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},extendClass(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERPrintableString=function(e){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},extendClass(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERTeletexString=function(e){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},extendClass(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERIA5String=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},extendClass(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERVisibleString=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},extendClass(KJUR.asn1.DERVisibleString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERBMPString=function(e){KJUR.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},extendClass(KJUR.asn1.DERBMPString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERUTCTime=function(e){KJUR.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=stohex(e)}else if(null!=e.str)this.hV=stohex(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=stohex(this.formatDate(t,"utc",!0))}else if(null!=e.date&&e.date instanceof Date){var r=!0===e.millis;this.hV=stohex(this.formatDate(e.date,"utc",r))}else e instanceof Date&&(this.hV=stohex(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)},extendClass(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERGeneralizedTime=function(e){KJUR.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=stohex(e)}else if(null!=e.str)this.hV=stohex(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=stohex(this.formatDate(t,"gen",!0))}else if(null!=e.date&&e.date instanceof Date){var r=!0===e.millis;this.hV=stohex(this.formatDate(e.date,"gen",r))}else e instanceof Date&&(this.hV=stohex(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)},extendClass(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERSequence=function(e){KJUR.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}},extendClass(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERSet=function(e){KJUR.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 r=this.asn1Array[t];e.push(r.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)},extendClass(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERTaggedObject=function(e){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);var t=KJUR.asn1,r=ASN1HEX,n=r.getV;r.isASN1HEX;var i=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,r){this.params={tag:t,explicit:e,obj:r}},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=utf8tohex(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 r;e.obj instanceof t.ASN1Object?r=e.obj.tohex():"object"==typeof e.obj&&(r=i(e.obj).tohex()),e.explicit?this.hV=r:this.hV=n(r,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)},extendClass(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);var ASN1HEX=new function(){},KJUR,utf8tob64u,b64utoutf8;function stoBA(e){for(var t=new Array,r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function BAtohex(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function stohex(e){return BAtohex(stoBA(e))}function b64tob64u(e){return e=(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function b64utob64(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),e=(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function hextob64u(e){return e.length%2==1&&(e="0"+e),b64tob64u(hex2b64(e))}function b64utohex(e){return b64tohex(b64utob64(e))}function utf8tohex(e){return uricmptohex(encodeURIComponentAll(e)).toLowerCase()}function hextoutf8(e){try{return decodeURIComponent(hextouricmp(e))}catch(e){return null}}function iso88591hextoutf8(e){return hextoutf8(iso88591hextoutf8hex(e))}function iso88591hextoutf8hex(e){for(var t=e.match(/.{1,2}/g),r=[],n=0;n<t.length;n++){var i=parseInt(t[n],16);161<=i&&i<=191?(r.push("c2"),r.push(t[n])):192<=i&&i<=255?(r.push("c3"),r.push((i-64).toString(16))):r.push(t[n])}return r.join("")}function hextorstr(e){for(var t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t}function rstrtohex(e){for(var t="",r=0;r<e.length;r++)t+=("0"+e.charCodeAt(r).toString(16)).slice(-2);return t}function hextob64(e){return hex2b64(e)}function foldnl(e,t){return e=(e=e.replace(new RegExp("(.{"+t+"})","g"),"$1\r\n")).replace(/\s+$/,"")}function b64nltohex(e){return b64tohex(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}function hextopem(e,t){return"-----BEGIN "+t+"-----\r\n"+foldnl(hextob64(e),64)+"\r\n-----END "+t+"-----\r\n"}function pemtohex(e,t){if(-1==e.indexOf("-----BEGIN "))throw new Error("can't find PEM header");return b64nltohex(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function zulutomsec(e){var t,r,n,i,s,o,a,d,c,l;if(l=(e=timetogen(e)).match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return t=parseInt(l[1]),r=parseInt(l[2])-1,n=parseInt(l[3]),i=parseInt(l[4]),s=parseInt(l[5]),o=parseInt(l[6]),a=0,""!==(d=l[7])&&(c=(d.substr(1)+"00").substr(0,3),a=parseInt(c)),Date.UTC(t,r,n,i,s,o,a);throw new Error("unsupported zulu format: "+e)}function zulutosec(e){return Math.round(zulutomsec(e)/1e3)}function timetogen(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}function uricmptohex(e){return e.replace(/%/g,"")}function hextouricmp(e){return e.replace(/(..)/g,"%$1")}function ipv6tohex(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var r=(e=e.toLowerCase()).split(":").length-1;if(r<2)throw t;var n=":".repeat(7-r+2),i=(e=e.replace("::",n)).split(":");if(8!=i.length)throw t;for(var s=0;s<8;s++)i[s]=("0000"+i[s]).slice(-4);return i.join("")}function hextoipv6(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 r=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null==r)return e.slice(1,-1);var n=r.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 hextoip(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 hextoipv6(e);if(64==e.length){try{return hextoipv6(e.substr(0,32))+"/"+ipprefixlen(e.substr(32))}catch(e){throw t}return}return e}try{return hextoip(e.substr(0,8))+"/"+ipprefixlen(e.substr(8))}catch(e){throw t}}}function ipprefixlen(e){var t,r=new Error("malformed mask");try{t=new BigInteger(e,16).toString(2)}catch(e){throw r}if(!t.match(/^1*0*$/))throw r;return t.replace(/0+$/,"").length}function iptohex(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 r;if(e.match(/^[0-9.]+\/[0-9]+$/))return iptohex((r=e.split("/"))[0])+ipnetmask(parseInt(r[1]),32);if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return ipv6tohex(e);if(e.match(/^[0-9a-f:]+\/[0-9]+$/)&&-1!==e.indexOf(":"))return ipv6tohex((r=e.split("/"))[0])+ipnetmask(parseInt(r[1]),128);throw t}var n=e.split(".");if(4!==n.length)throw t;var i="";try{for(var s=0;s<4;s++){i+=("0"+parseInt(n[s]).toString(16)).slice(-2)}return i}catch(e){throw t}}function ipnetmask(e,t){return 32==t&&0==e?"00000000":128==t&&0==e?"00000000000000000000000000000000":new BigInteger(Array(e+1).join("1")+Array(t-e+1).join("0"),2).toString(16)}function ucs2hextoutf8(e){var t=e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),r=parseInt(e.substr(2),16);if(0==t&r<128)return String.fromCharCode(r);if(t<8){var n=128|63&r;return hextoutf8((192|(7&t)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return hextoutf8((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))}));return t.join("")}function encodeURIComponentAll(e){for(var t=encodeURIComponent(e),r="",n=0;n<t.length;n++)"%"==t[n]?(r+=t.substr(n,3),n+=2):r=r+"%"+stohex(t[n]);return r}function ishex(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function isBase64URLDot(e){return!!e.match(/^[0-9A-Za-z-_.]+$/)}function hextoposhex(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}function oidtohex(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";n=s+n;for(o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};try{if(!e.match(/^[0-9.]+$/))return null;var n="",i=e.split("."),s=40*parseInt(i[0],10)+parseInt(i[1],10);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n}catch(e){return null}}function hextooid(e){if(!ishex(e))return null;try{var t=[],r=e.substr(0,2),n=parseInt(r,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var i=e.substr(2),s=[],o=0;o<i.length/2;o++)s.push(parseInt(i.substr(2*o,2),16));var a=[],d="";for(o=0;o<s.length;o++)128&s[o]?d+=strpad((127&s[o]).toString(2),7):(d+=strpad((127&s[o]).toString(2),7),a.push(new String(parseInt(d,2))),d="");var c=t.join(".");return a.length>0&&(c=c+"."+a.join(".")),c}catch(e){return null}}ASN1HEX.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var r=parseInt(e.substr(t+3,1));return 0==r?-1:0<r&&r<10?r+1:-2},ASN1HEX.getL=function(e,t){var r=ASN1HEX.getLblen(e,t);return r<1?"":e.substr(t+2,2*r)},ASN1HEX.getVblen=function(e,t){var r;return""==(r=ASN1HEX.getL(e,t))?-1:("8"===r.substr(0,1)?new BigInteger(r.substr(2),16):new BigInteger(r,16)).intValue()},ASN1HEX.getVidx=function(e,t){var r=ASN1HEX.getLblen(e,t);return r<0?r:t+2*(r+1)},ASN1HEX.getV=function(e,t){var r=ASN1HEX.getVidx(e,t),n=ASN1HEX.getVblen(e,t);return e.substr(r,2*n)},ASN1HEX.getTLV=function(e,t){return e.substr(t,2)+ASN1HEX.getL(e,t)+ASN1HEX.getV(e,t)},ASN1HEX.getTLVblen=function(e,t){return 2+2*ASN1HEX.getLblen(e,t)+2*ASN1HEX.getVblen(e,t)},ASN1HEX.getNextSiblingIdx=function(e,t){return ASN1HEX.getVidx(e,t)+2*ASN1HEX.getVblen(e,t)},ASN1HEX.getChildIdx=function(e,t){var r,n,i,s=ASN1HEX,o=[];r=s.getVidx(e,t),n=2*s.getVblen(e,t),"03"==e.substr(t,2)&&(r+=2,n-=2),i=0;for(var a=r;i<=n;){var d=s.getTLVblen(e,a);if((i+=d)<=n&&o.push(a),a+=d,i>=n)break}return o},ASN1HEX.getNthChildIdx=function(e,t,r){return ASN1HEX.getChildIdx(e,t)[r]},ASN1HEX.getIdxbyList=function(e,t,r,n){var i,s,o=ASN1HEX;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(s=o.getChildIdx(e,t)).length?-1:o.getIdxbyList(e,s[i],r,n)},ASN1HEX.getIdxbyListEx=function(e,t,r,n){var i,s,o=ASN1HEX;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),s=o.getChildIdx(e,t);for(var a=0,d=0;d<s.length;d++){var c=e.substr(s[d],2);if("number"==typeof i&&!o.isContextTag(c)&&a==i||"string"==typeof i&&o.isContextTag(c,i))return o.getIdxbyListEx(e,s[d],r,n);o.isContextTag(c)||a++}return-1},ASN1HEX.getTLVbyList=function(e,t,r,n){var i=ASN1HEX,s=i.getIdxbyList(e,t,r,n);return-1==s||s>=e.length?null:i.getTLV(e,s)},ASN1HEX.getTLVbyListEx=function(e,t,r,n){var i=ASN1HEX,s=i.getIdxbyListEx(e,t,r,n);return-1==s?null:i.getTLV(e,s)},ASN1HEX.getVbyList=function(e,t,r,n,i){var s,o,a=ASN1HEX;return-1==(s=a.getIdxbyList(e,t,r,n))||s>=e.length?null:(o=a.getV(e,s),!0===i&&(o=o.substr(2)),o)},ASN1HEX.getVbyListEx=function(e,t,r,n,i){var s,o,a=ASN1HEX;return-1==(s=a.getIdxbyListEx(e,t,r,n))?null:(o=a.getV(e,s),"03"==e.substr(s,2)&&!1!==i&&(o=o.substr(2)),o)},ASN1HEX.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=ASN1HEX.getV(e,t);return"02"==n?parseInt(i,16):bitstrtoint(i)}catch(e){return r}},ASN1HEX.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:hextooid(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=ASN1HEX.getOID(e,t,r);if(n==r)return r;var i=KJUR.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},ASN1HEX.getString=function(e,t,r){null==r&&(r=null);try{return hextorstr(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var s=e.substr(2),o=[],a=0;a<s.length/2;a++)o.push(parseInt(s.substr(2*a,2),16));var d=[],c="";for(a=0;a<o.length;a++)128&o[a]?c+=t((127&o[a]).toString(2),7):(c+=t((127&o[a]).toString(2),7),d.push(new String(parseInt(c,2))),c="");var l=r.join(".");return d.length>0&&(l=l+"."+d.join(".")),l},ASN1HEX.dump=function(e,t,r,n){var i=ASN1HEX,s=i.getV,o=i.dump,a=i.getChildIdx,d=e;e instanceof KJUR.asn1.ASN1Object&&(d=e.tohex());var c=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===r&&(r=0),void 0===n&&(n="");var l,u=t.ommit_long_octet;if("01"==(l=d.substr(r,2)))return"00"==(h=s(d,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==l)return n+"INTEGER "+c(h=s(d,r),u)+"\n";if("03"==l){var h=s(d,r);if(i.isASN1HEX(h.substr(2))){var g=n+"BITSTRING, encapsulates\n";return g+=o(h.substr(2),t,0,n+" ")}return n+"BITSTRING "+c(h,u)+"\n"}if("04"==l){h=s(d,r);if(i.isASN1HEX(h)){g=n+"OCTETSTRING, encapsulates\n";return g+=o(h,t,0,n+" ")}return n+"OCTETSTRING "+c(h,u)+"\n"}if("05"==l)return n+"NULL\n";if("06"==l){var p=s(d,r),m=KJUR.asn1.ASN1Util.oidHexToInt(p),f=KJUR.asn1.x509.OID.oid2name(m),S=m.replace(/\./g," ");return""!=f?n+"ObjectIdentifier "+f+" ("+S+")\n":n+"ObjectIdentifier ("+S+")\n"}if("0a"==l)return n+"ENUMERATED "+parseInt(s(d,r))+"\n";if("0c"==l)return n+"UTF8String '"+hextoutf8(s(d,r))+"'\n";if("13"==l)return n+"PrintableString '"+hextoutf8(s(d,r))+"'\n";if("14"==l)return n+"TeletexString '"+hextoutf8(s(d,r))+"'\n";if("16"==l)return n+"IA5String '"+hextoutf8(s(d,r))+"'\n";if("17"==l)return n+"UTCTime "+hextoutf8(s(d,r))+"\n";if("18"==l)return n+"GeneralizedTime "+hextoutf8(s(d,r))+"\n";if("1a"==l)return n+"VisualString '"+hextoutf8(s(d,r))+"'\n";if("1e"==l)return n+"BMPString '"+ucs2hextoutf8(s(d,r))+"'\n";if("30"==l){if("3000"==d.substr(r,4))return n+"SEQUENCE {}\n";g=n+"SEQUENCE\n";var y=t;if((2==(v=a(d,r)).length||3==v.length)&&"06"==d.substr(v[0],2)&&"04"==d.substr(v[v.length-1],2)){f=i.oidname(s(d,v[0]));var b=JSON.parse(JSON.stringify(t));b.x509ExtName=f,y=b}for(var E=0;E<v.length;E++)g+=o(d,y,v[E],n+" ");return g}if("31"==l){g=n+"SET\n";var v=a(d,r);for(E=0;E<v.length;E++)g+=o(d,t,v[E],n+" ");return g}if(0!=(128&(l=parseInt(l,16)))){var _=31&l;if(0!=(32&l)){for(g=n+"["+_+"]\n",v=a(d,r),E=0;E<v.length;E++)g+=o(d,t,v[E],n+" ");return g}h=s(d,r);if(ASN1HEX.isASN1HEX(h)){var g=n+"["+_+"]\n";return g+=o(h,t,0,n+" ")}return("68747470"==h.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==_)&&(h=hextoutf8(h)),g=n+"["+_+"] "+h+"\n"}return n+"UNKNOWN("+l+") "+s(d,r)+"\n"},ASN1HEX.parse=function(e){var t=ASN1HEX,r=t.parse,n=t.isASN1HEX,i=t.getV,s=t.getTLV,o=t.getChildIdx,a=KJUR.asn1,d=a.ASN1Util.oidHexToInt,c=a.x509.OID.oid2name,l=hextoutf8,u=ucs2hextoutf8,h=iso88591hextoutf8,g={"0c":"utf8str",12:"numstr",13:"prnstr",14:"telstr",16:"ia5str",17:"utctime",18:"gentime","1a":"visstr","1e":"bmpstr",30:"seq",31:"set"},p=e.substr(0,2),m={},f=i(e,0);if("01"==p)return"0101ff"==e?{bool:!0}:{bool:!1};if("02"==p)return{int:{hex:f}};if("03"==p)try{if("00"!=f.substr(0,2))throw"not encap";var S=f.substr(2);if(!n(S))throw"not encap";return{bitstr:{obj:r(S)}}}catch(e){var y=null;return f.length<=10&&(y=bitstrtobinstr(f)),null==y?{bitstr:{hex:f}}:{bitstr:{bin:y}}}else if("04"==p)try{if(!n(f))throw"not encap";return{octstr:{obj:r(f)}}}catch(e){return{octstr:{hex:f}}}else{if("05"==p)return{null:""};if("06"==p){var b=d(f),E=c(b);return""==E?{oid:b}:{oid:E}}if("0a"==p)return f.length>4?{enum:{hex:f}}:{enum:parseInt(f,16)};if("30"==p||"31"==p)return m[g[p]]=function(e){for(var t=[],n=o(e,0),i=0;i<n.length;i++){var a=n[i],d=s(e,a),c=r(d);t.push(c)}return t}(e),m;if("14"==p){var v=h(f);return m[g[p]]={str:v},m}if("1e"==p){v=u(f);return m[g[p]]={str:v},m}if(-1!=":0c:12:13:16:17:18:1a:".indexOf(p)){v=l(f);return m[g[p]]={str:v},m}if(p.match(/^8[0-9]$/))return null==(v=l(f))|""==v||null!=v.match(/[\x00-\x1F\x7F-\x9F]/)||null!=v.match(/[\u0000-\u001F\u0080–\u009F]/)?{tag:{tag:p,explicit:!1,hex:f}}:{tag:{tag:p,explicit:!1,str:v}};if(!p.match(/^a[0-9]$/)){var _=new KJUR.asn1.ASN1Object;return _.hV=f,{asn1:{tlv:p+_.getLengthHexFromValue()+f}}}try{if(!n(f))throw new Error("not encap");return{tag:{tag:p,explicit:!0,obj:r(f)}}}catch(e){return{tag:{tag:p,explicit:!0,hex:f}}}}},ASN1HEX.isContextTag=function(e,t){var r,n;e=e.toLowerCase();try{r=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&r);try{return null!=t.match(/^\[[0-9]+\]$/)&&(!((n=parseInt(t.substr(1,t.length-1),10))>31)&&(128==(192&r)&&(31&r)==n))}catch(e){return!1}},ASN1HEX.isASN1HEX=function(e){var t=ASN1HEX;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},ASN1HEX.checkStrictDER=function(e,t,r,n,i){var s=ASN1HEX;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!KJUR.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(s.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var o=s.getVblen(e,t);if(o>n)throw new Error("value of L too long than hex: idx="+t);var a=s.getTLV(e,t),d=a.length-2-s.getL(e,t).length;if(d!==2*o)throw new Error("V string length and L's value not the same:"+d+"/"+2*o);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var c=e.substr(t,2);if("02"===c){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(c,16)){for(var u=s.getVblen(e,t),h=0,g=s.getChildIdx(e,t),p=0;p<g.length;p++){h+=s.getTLV(e,g[p]).length,s.checkStrictDER(e,g[p],r,n,i)}if(2*u!=h)throw new Error("sum of children's TLV length and L unmatch: "+2*u+"!="+h)}},ASN1HEX.oidname=function(e){var t=KJUR.asn1;KJUR.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var r=t.x509.OID.oid2name(e);return""===r&&(r=e),r},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.x509&&KJUR.asn1.x509||(KJUR.asn1.x509={}),KJUR.asn1.x509.Certificate=function(e){KJUR.asn1.x509.Certificate.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERBitString,n=t.DERSequence,i=t.x509,s=i.TBSCertificate,o=i.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 r=e.tbsobj.tohex(),n=new KJUR.crypto.Signature({alg:t});n.init(e.cakey),n.updateHex(r),e.sighex=n.sign()},this.getPEM=function(){return hextopem(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 o({name:e.sigalg})),t.push(new r({hex:"00"+e.sighex})),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.Certificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.TBSCertificate=function(e){KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=t.DERTaggedObject,i=t.DERInteger,s=t.DERSequence,o=r.AlgorithmIdentifier,a=r.Time,d=r.X500Name,c=r.Extensions,l=r.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 r=2;null!=t.version&&(r=t.version-1);var u=new n({obj:new i({int:r})});e.push(u)}return e.push(new i(t.serial)),e.push(new o({name:t.sigalg})),e.push(new d(t.issuer)),e.push(new s({array:[new a(t.notbefore),new a(t.notafter)]})),e.push(new d(t.subject)),e.push(new l(KEYUTIL.getKey(t.sbjpubkey))),void 0!==t.ext&&t.ext.length>0&&e.push(new n({tag:"a3",obj:new c(t.ext)})),new KJUR.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extensions=function(e){KJUR.asn1.x509.Extensions.superclass.constructor.call(this);var t=KJUR.asn1,r=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 i=this.aParam[t],s=i.extname,o=null;if(null!=i.extn)o=new n.PrivateExtension(i);else if("subjectKeyIdentifier"==s)o=new n.SubjectKeyIdentifier(i);else if("keyUsage"==s)o=new n.KeyUsage(i);else if("subjectAltName"==s)o=new n.SubjectAltName(i);else if("issuerAltName"==s)o=new n.IssuerAltName(i);else if("basicConstraints"==s)o=new n.BasicConstraints(i);else if("nameConstraints"==s)o=new n.NameConstraints(i);else if("cRLDistributionPoints"==s)o=new n.CRLDistributionPoints(i);else if("certificatePolicies"==s)o=new n.CertificatePolicies(i);else if("policyMappings"==s)o=new n.PolicyMappings(i);else if("policyConstraints"==s)o=new n.PolicyConstraints(i);else if("inhibitAnyPolicy"==s)o=new n.InhibitAnyPolicy(i);else if("authorityKeyIdentifier"==s)o=new n.AuthorityKeyIdentifier(i);else if("extKeyUsage"==s)o=new n.ExtKeyUsage(i);else if("authorityInfoAccess"==s)o=new n.AuthorityInfoAccess(i);else if("cRLNumber"==s)o=new n.CRLNumber(i);else if("cRLReason"==s)o=new n.CRLReason(i);else if("ocspNonce"==s)o=new n.OCSPNonce(i);else if("ocspNoCheck"==s)o=new n.OCSPNoCheck(i);else if("adobeTimeStamp"==s)o=new n.AdobeTimeStamp(i);else{if("subjectDirectoryAttributes"!=s)throw new Error("extension not supported:"+JSON.stringify(i));o=new n.SubjectDirectoryAttributes(i)}null!=o&&e.push(o)}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.Extensions,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extension=function(e){KJUR.asn1.x509.Extension.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERObjectIdentifier,n=t.DEROctetString;t.DERBitString;var i=t.DERBoolean,s=t.DERSequence;this.tohex=function(){var e=new r({oid:this.oid}),t=new n({hex:this.getExtnValueHex()}),o=new Array;return o.push(e),this.critical&&o.push(new i),o.push(t),new s({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.critical=!1,void 0!==e&&void 0!==e.critical&&(this.critical=e.critical)},extendClass(KJUR.asn1.x509.Extension,KJUR.asn1.ASN1Object),KJUR.asn1.x509.KeyUsage=function(e){KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this,e);var t=Error,r={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 KJUR.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 namearraytobinstr(e.names,r);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)},extendClass(KJUR.asn1.x509.KeyUsage,KJUR.asn1.x509.Extension),KJUR.asn1.x509.BasicConstraints=function(e){KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERBoolean,n=t.DERInteger,i=t.DERSequence;this.getExtnValueHex=function(){var e=new Array;this.cA&&e.push(new r),this.pathLen>-1&&e.push(new n({int:this.pathLen}));var t=new i({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))},extendClass(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLDistributionPoints=function(e){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],i=0;i<e.length;i++)if(e[i]instanceof KJUR.asn1.ASN1Object)n.push(e[i]);else{var s=new r.DistributionPoint(e[i]);n.push(s)}this.asn1ExtnValue=new t.DERSequence({array:n})},this.setByOneURI=function(e){var t=new r.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))},extendClass(KJUR.asn1.x509.CRLDistributionPoints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.DistributionPoint=function(e){KJUR.asn1.x509.DistributionPoint.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509.DistributionPointName;this.tohex=function(){var e=new t.DERSequence;if(null!=this.asn1DP){var r=new t.DERTaggedObject({explicit:!0,tag:"a0",obj:this.asn1DP});e.appendASN1Object(r)}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 r(e.dpname):void 0!==e.fulluri&&(this.asn1DP=new r({full:[{uri:e.fulluri}]})))},extendClass(KJUR.asn1.x509.DistributionPoint,KJUR.asn1.ASN1Object),KJUR.asn1.x509.DistributionPointName=function(e){KJUR.asn1.x509.DistributionPointName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERTaggedObject;if(this.tohex=function(){if("full"!=this.type)throw new Error("currently type shall be 'full': "+this.type);return this.asn1Obj=new r({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)}},extendClass(KJUR.asn1.x509.DistributionPointName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CertificatePolicies=function(e){KJUR.asn1.x509.CertificatePolicies.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509,n=t.DERSequence,i=r.PolicyInformation;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++)e.push(new i(this.params.array[t]));var r=new n({array:e});return this.asn1ExtnValue=r,this.asn1ExtnValue.tohex()},this.oid="2.5.29.32",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.CertificatePolicies,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PolicyInformation=function(e){KJUR.asn1.x509.PolicyInformation.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier,i=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 i(this.params.array[s]));t.length>0&&e.push(new r({array:t}))}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyInformation,KJUR.asn1.ASN1Object),KJUR.asn1.x509.PolicyQualifierInfo=function(e){KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERIA5String,i=t.DERObjectIdentifier,s=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new r({array:[new i({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)},extendClass(KJUR.asn1.x509.PolicyQualifierInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.UserNotice=function(e){KJUR.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence;KJUR.asn1.DERInteger;var r=KJUR.asn1.x509.DisplayText,n=KJUR.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 r(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.UserNotice,KJUR.asn1.ASN1Object),KJUR.asn1.x509.NoticeReference=function(e){KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence,r=KJUR.asn1.DERInteger,n=KJUR.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 i=[],s=this.params.noticenum,o=0;o<s.length;o++)i.push(new r(s[o]));e.push(new t({array:i}))}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)},extendClass(KJUR.asn1.x509.NoticeReference,KJUR.asn1.ASN1Object),KJUR.asn1.x509.DisplayText=function(e){KJUR.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"))},extendClass(KJUR.asn1.x509.DisplayText,KJUR.asn1.DERAbstractString),KJUR.asn1.x509.PolicyMappings=function(e){KJUR.asn1.x509.PolicyMappings.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){for(var e=this.params,t=[],n=0;n<e.array.length;n++){var i=e.array[n];t.push({seq:[{oid:i[0]},{oid:i[1]}]})}return this.asn1ExtnValue=r({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.33",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyMappings,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PolicyConstraints=function(e){KJUR.asn1.x509.PolicyConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=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=r({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.36",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.InhibitAnyPolicy=function(e){KJUR.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=r({int:this.params.skip}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.54",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.InhibitAnyPolicy,KJUR.asn1.x509.Extension),KJUR.asn1.x509.NameConstraints=function(e){KJUR.asn1.x509.NameConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509,n=t.ASN1Util.newObject,i=r.GeneralSubtree;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];if(null!=e.permit&&null!=e.permit.length){for(var r=[],s=0;s<e.permit.length;s++)r.push(new i(e.permit[s]));t.push({tag:{tagi:"a0",obj:{seq:r}}})}if(null!=e.exclude&&null!=e.exclude.length){var o=[];for(s=0;s<e.exclude.length;s++)o.push(new i(e.exclude[s]));t.push({tag:{tagi:"a1",obj:{seq:o}}})}return this.asn1ExtnValue=n({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.30",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.NameConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.GeneralSubtree=function(e){KJUR.asn1.x509.GeneralSubtree.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(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)},extendClass(KJUR.asn1.x509.GeneralSubtree,KJUR.asn1.ASN1Object),KJUR.asn1.x509.ExtKeyUsage=function(e){KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,e);var t=KJUR.asn1;this.setPurposeArray=function(e){this.asn1ExtnValue=new t.DERSequence;for(var r=0;r<e.length;r++){var n=new t.DERObjectIdentifier(e[r]);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)},extendClass(KJUR.asn1.x509.ExtKeyUsage,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AuthorityKeyIdentifier=function(e){KJUR.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,e);var t=KJUR,r=t.asn1,n=r.DERTaggedObject,i=r.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 i([{dn:this.asn1CertIssuer}])})),this.asn1CertSN&&e.push(new n({explicit:!1,tag:"82",obj:this.asn1CertSN}));var t=new r.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 KJUR.asn1.DEROctetString(e);else if("object"==typeof e&&KJUR.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN ")){var t=e;"string"==typeof e&&(t=KEYUTIL.getKey(e));var r=KEYUTIL.getKeyID(t);this.asn1KID=new KJUR.asn1.DEROctetString({hex:r})}},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 KJUR.asn1.x509.X500Name(e):"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&-1!=e.indexOf("CERTIFICATE")&&(this.asn1CertIssuer=new KJUR.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 KJUR.asn1.DERInteger(e);else if("string"==typeof e&&-1!=e.indexOf("BEGIN ")&&e.indexOf("CERTIFICATE")){var t=new X509;t.readCertPEM(e);var r=t.getSerialNumberHex();this.asn1CertSN=new KJUR.asn1.DERInteger({hex:r})}},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)))},extendClass(KJUR.asn1.x509.AuthorityKeyIdentifier,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectKeyIdentifier=function(e){KJUR.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this,e);var t=KJUR.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&&KJUR.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN")){var r=e;"string"==typeof e&&(r=KEYUTIL.getKey(e));var n=KEYUTIL.getKeyID(r);this.asn1KID=new KJUR.asn1.DEROctetString({hex:n})}},this.oid="2.5.29.14",void 0!==e&&void 0!==e.kid&&this.setKIDByParam(e.kid)},extendClass(KJUR.asn1.x509.SubjectKeyIdentifier,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AuthorityInfoAccess=function(e){KJUR.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,e),this.setAccessDescriptionArray=function(e){for(var t=new Array,r=KJUR.asn1,n=r.DERSequence,i=r.DERObjectIdentifier,s=r.x509.GeneralName,o=0;o<e.length;o++){var a,d=e[o];if(void 0!==d.ocsp)a=new n({array:[new i({oid:"1.3.6.1.5.5.7.48.1"}),new s({uri:d.ocsp})]});else{if(void 0===d.caissuer)throw new Error("unknown AccessMethod parameter: "+JSON.stringify(d));a=new n({array:[new i({oid:"1.3.6.1.5.5.7.48.2"}),new s({uri:d.caissuer})]})}t.push(a)}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)},extendClass(KJUR.asn1.x509.AuthorityInfoAccess,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectAltName=function(e){KJUR.asn1.x509.SubjectAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new KJUR.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)},extendClass(KJUR.asn1.x509.SubjectAltName,KJUR.asn1.x509.Extension),KJUR.asn1.x509.IssuerAltName=function(e){KJUR.asn1.x509.IssuerAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new KJUR.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)},extendClass(KJUR.asn1.x509.IssuerAltName,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectDirectoryAttributes=function(e){KJUR.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.ASN1Util.newObject,i=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 o={seq:[{oid:"1.2.3.4"},{set:[{utf8str:"DE"}]}]};if("dateOfBirth"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={gentime:s.str};else if("placeOfBirth"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={utf8str:s.str};else if("gender"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str};else if("countryOfCitizenship"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str};else{if("countryOfResidence"!=s.attr)throw new Error("unsupported attribute: "+s.attr);o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str}}e.push(new n(o))}else{var a={seq:[{oid:s.attr},{set:s.array}]};e.push(n(a))}}var d=new r({array:e});return this.asn1ExtnValue=d,this.asn1ExtnValue.tohex()},this.oid="2.5.29.9",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.SubjectDirectoryAttributes,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PrivateExtension=function(e){KJUR.asn1.x509.PrivateExtension.superclass.constructor.call(this,e);var t=KJUR,r=t.lang.String.isHex,n=t.asn1,i=n.x509.OID.name2oid,s=n.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.oid=i(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&&r(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)},extendClass(KJUR.asn1.x509.PrivateExtension,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRL=function(e){KJUR.asn1.x509.CRL.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERBitString,i=t.x509,s=i.AlgorithmIdentifier,o=i.TBSCertList;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=new o(this.params).tohex(),t=new KJUR.crypto.Signature({alg:this.params.sigalg});t.init(this.params.cakey),t.updateHex(e);var r=t.sign();this.params.sighex=r},this.getPEM=function(){return hextopem(this.tohex(),"X509 CRL")},this.tohex=function(){var e=this.params;if(null==e.tbsobj&&(e.tbsobj=new o(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 r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRL,KJUR.asn1.ASN1Object),KJUR.asn1.x509.TBSCertList=function(e){KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERInteger,n=t.DERSequence,i=t.DERTaggedObject;t.DERObjectIdentifier;var s=t.x509,o=s.AlgorithmIdentifier,a=s.Time,d=s.Extensions,c=s.X500Name;this.params=null,this.setByParam=function(e){this.params=e},this.getRevCertSequence=function(){for(var e=[],t=this.params.revcert,i=0;i<t.length;i++){var s=[new r(t[i].sn),new a(t[i].date)];null!=t[i].ext&&s.push(new d(t[i].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 r({int:s});e.push(l)}if(e.push(new o({name:t.sigalg})),e.push(new c(t.issuer)),e.push(new a(t.thisupdate)),null!=t.nextupdate&&e.push(new a(t.nextupdate)),null!=t.revcert&&e.push(this.getRevCertSequence()),null!=t.ext){var u=new d(t.ext);e.push(new i({tag:"a0",explicit:!0,obj:u}))}return new n({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertList,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CRLEntry=function(e){KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);var t=KJUR.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))},extendClass(KJUR.asn1.x509.CRLEntry,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CRLNumber=function(e){KJUR.asn1.x509.CRLNumber.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DERInteger(this.params.num),this.asn1ExtnValue.tohex()},this.oid="2.5.29.20",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRLNumber,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLReason=function(e){KJUR.asn1.x509.CRLReason.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DEREnumerated(this.params.code),this.asn1ExtnValue.tohex()},this.oid="2.5.29.21",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRLReason,KJUR.asn1.x509.Extension),KJUR.asn1.x509.OCSPNonce=function(e){KJUR.asn1.x509.OCSPNonce.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DEROctetString(this.params),this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.2",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.OCSPNonce,KJUR.asn1.x509.Extension),KJUR.asn1.x509.OCSPNoCheck=function(e){KJUR.asn1.x509.OCSPNoCheck.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DERNull,this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.5",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.OCSPNoCheck,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AdobeTimeStamp=function(e){KJUR.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERInteger,n=t.DERBoolean,i=t.DERSequence,s=t.x509.GeneralName;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[new r(1)];return t.push(new s({uri:e.uri})),null!=e.reqauth&&t.push(new n(e.reqauth)),this.asn1ExtnValue=new i({array:t}),this.asn1ExtnValue.tohex()},this.oid="1.2.840.113583.1.1.9.1",void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AdobeTimeStamp,KJUR.asn1.x509.Extension),KJUR.asn1.x509.X500Name=function(e){KJUR.asn1.x509.X500Name.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.asn1,r=t.x509,n=r.RDN;this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var r=e.split("/");r.shift();for(var i=[],s=0;s<r.length;s++)if(r[s].match(/^[^=]+=.+$/))i.push(r[s]);else{var o=i.length-1;i[o]=i[o]+"/"+r[s]}for(s=0;s<i.length;s++)this.asn1Array.push(new n({str:i[s],rule:this.sRule}))},this.setByLdapString=function(e,t){void 0!==t&&(this.sRule=t);var n=r.X500Name.ldapToCompat(e);this.setByString(n,t)},this.setByObject=function(e,t){for(var r in void 0!==t&&(this.sRule=t),e)if(e.hasOwnProperty(r)){var i=new n({str:r+"="+e[r],rule:this.sRule});this.asn1Array?this.asn1Array.push(i):this.asn1Array=[i]}},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 X509).readCertPEM(e.certissuer),this.hTLV=t.getIssuerHex()):void 0!==e.certsubject?((t=new X509).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 r={array:this.paramArray[e]};"utf8"!=this.sRule&&(r.rule=this.sRule);var i=new n(r);this.asn1Array.push(i)}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)},extendClass(KJUR.asn1.x509.X500Name,KJUR.asn1.ASN1Object),KJUR.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(",")},KJUR.asn1.x509.X500Name.onelineToLDAP=function(e){return KJUR.asn1.x509.X500Name.compatToLDAP(e)},KJUR.asn1.x509.X500Name.ldapToCompat=function(e){for(var t=e.split(","),r=!1,n=[],i=0;t.length>0;i++){var s=t.shift();if(!0===r){var o=(n.pop()+","+s).replace(/\\,/g,",");n.push(o),r=!1}else n.push(s);"\\"===s.substr(-1,1)&&(r=!0)}return n=n.map((function(e){return e.replace("/","\\/")})),n.reverse(),"/"+n.join("/")},KJUR.asn1.x509.X500Name.ldapToOneline=function(e){return KJUR.asn1.x509.X500Name.ldapToCompat(e)},KJUR.asn1.x509.RDN=function(e){KJUR.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.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 KJUR.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=KJUR.asn1.x509.RDN.parseString(e),r=0;r<t.length;r++)this.addByString(t[r])},this.tohex=function(){if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var r=this.paramArray[e];void 0!==r.rule&&"utf8"!=this.sRule&&(r.rule=this.sRule);var n=new t(r);this.asn1Array.push(n)}var i=new KJUR.asn1.DERSet({array:this.asn1Array});return this.TLV=i.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.RDN,KJUR.asn1.ASN1Object),KJUR.asn1.x509.RDN.parseString=function(e){for(var t=e.split(/\+/),r=!1,n=[],i=0;t.length>0;i++){var s=t.shift();if(!0===r){var o=(n.pop()+"+"+s).replace(/\\\+/g,"+");n.push(o),r=!1}else n.push(s);"\\"===s.substr(-1,1)&&(r=!0)}var a=!1,d=[];for(i=0;n.length>0;i++){s=n.shift();if(!0===a){var c=d.pop();if(s.match(/"$/)){o=(c+"+"+s).replace(/^([^=]+)="(.*)"$/,"$1=$2");d.push(o),a=!1}else d.push(c+"+"+s)}else d.push(s);s.match(/^[^=]+="/)&&(a=!0)}return d},KJUR.asn1.x509.AttributeTypeAndValue=function(e){KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=KJUR,r=t.asn1,n=r.DERSequence,i=r.DERUTF8String,s=r.DERPrintableString,o=r.DERTeletexString,a=r.DERIA5String,d=r.DERVisibleString,c=r.DERBMPString,l=t.lang.String.isMail,u=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 r=e.match(/^([^=]+)=(.+)$/);if(!r)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(r[1],r[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,r=this.sRule;return"prn"===r?"CN"==e&&l(t)?"ia5":u(t)?"prn":"utf8":"utf8"===r?"CN"==e&&l(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,r){void 0!==r&&(this.sRule=r),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new i({str:t});if("prn"==e)return new s({str:t});if("tel"==e)return new o({str:t});if("ia5"==e)return new a({str:t});if("vis"==e)return new d({str:t});if("bmp"==e)return new c({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=KJUR.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),r=new n({array:[e,t]});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AttributeTypeAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.x509.SubjectPublicKeyInfo=function(e){KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.DERInteger,i=r.DERBitString,s=r.DERObjectIdentifier,o=r.DERSequence,a=r.ASN1Util.newObject,d=r.x509.AlgorithmIdentifier,c=t.crypto;c.ECDSA,c.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new o({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 RSAKey){var t=a({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new d({name:"rsaEncryption"}),this.asn1SubjPKey=new i({hex:"00"+t})}}catch(e){}try{if(e instanceof KJUR.crypto.ECDSA){var r=new s({name:e.curveName});this.asn1AlgId=new d({name:"ecPublicKey",asn1params:r}),this.asn1SubjPKey=new i({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof KJUR.crypto.DSA){r=new a({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new d({name:"dsa",asn1params:r});var o=new n({bigint:e.y});this.asn1SubjPKey=new i({hex:"00"+o.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Time=function(e){KJUR.asn1.x509.Time.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new r,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)},KJUR.asn1.x509.Time_bak=function(e){KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(this.timeParams):new n(this.timeParams):"utc"==this.type?new r: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)},extendClass(KJUR.asn1.x509.Time,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier=function(e){KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=KJUR.asn1,r=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 r)n===this.nameAlg&&(e=r[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 i=[this.asn1Alg];null!==this.asn1Params&&i.push(this.asn1Params);var s=new t.DERSequence({array:i});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)}},extendClass(KJUR.asn1.x509.AlgorithmIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},KJUR.asn1.x509.GeneralName=function(e){KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=r.X500Name,i=r.OtherName,s=t.DERIA5String;t.DERPrintableString;var o=t.DEROctetString,a=t.DERTaggedObject,d=t.ASN1Object,c=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,r=this.params,l=!1;if(void 0!==r.other)e="a0",t=new i(r.other);else if(void 0!==r.rfc822)e="81",t=new s({str:r.rfc822});else if(void 0!==r.dns)e="82",t=new s({str:r.dns});else if(void 0!==r.dn)e="a4",l=!0,t="string"==typeof r.dn?new n({str:r.dn}):r.dn instanceof KJUR.asn1.x509.X500Name?r.dn:new n(r.dn);else if(void 0!==r.ldapdn)e="a4",l=!0,t=new n({ldapstr:r.ldapdn});else if(void 0!==r.certissuer||void 0!==r.certsubj){var u,h;e="a4",l=!0;var g=null;if(void 0!==r.certsubj?(u=!1,h=r.certsubj):(u=!0,h=r.certissuer),h.match(/^[0-9A-Fa-f]+$/),-1!=h.indexOf("-----BEGIN ")&&(g=pemtohex(h)),null==g)throw new Error("certsubj/certissuer not cert");var p,m=new X509;m.hex=g,p=u?m.getIssuerHex():m.getSubjectHex(),(t=new d).hTLV=p}else if(void 0!==r.uri)e="86",t=new s({str:r.uri});else{if(void 0===r.ip)throw new c("improper params");var f;e="87";var S=r.ip;try{if(S.match(/^[0-9a-f]+$/)){var y=S.length;if(8!=y&&16!=y&&32!=y&&64!=y)throw"err";f=S}else f=iptohex(S)}catch(e){throw new c("malformed IP address: "+r.ip+":"+e.message)}t=new o({hex:f})}return new a({tag:e,explicit:l,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.GeneralName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.GeneralNames=function(e){KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=KJUR.asn1;this.setByParamArray=function(e){for(var r=0;r<e.length;r++){var n=new t.x509.GeneralName(e[r]);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)},extendClass(KJUR.asn1.x509.GeneralNames,KJUR.asn1.ASN1Object),KJUR.asn1.x509.OtherName=function(e){KJUR.asn1.x509.OtherName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERObjectIdentifier,n=t.DERSequence,i=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 r({oid:e.oid}),s=i({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)},extendClass(KJUR.asn1.x509.OtherName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.OID=new function(){var e=KJUR.asn1.DERObjectIdentifier;this.name2oidList={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",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 r=this.name2oidList[t],n=new e({oid:r});return this.objCache[t]=n,n},this.atype2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];var r;if(t.match(/^\d+\.\d+\.[0-9.]+$/))r=t;else if(void 0!==this.atype2oidList[t])r=this.atype2oidList[t];else{if(void 0===this.name2oidList[t])throw new Error("AttributeType name undefined: "+t);r=this.name2oidList[t]}var n=new e({oid:r});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,r){if(!this[e].match(/^[0-2]\.[0-9.]+$/))throw new Error("value is not OID")}),e),!0)}catch(e){return!1}}},KJUR.asn1.x509.OID.oid2name=function(e){var t=KJUR.asn1.x509.OID.name2oidList;for(var r in t)if(t[r]==e)return r;return""},KJUR.asn1.x509.OID.oid2atype=function(e){var t=KJUR.asn1.x509.OID.atype2oidList;for(var r in t)if(t[r]==e)return r;return e},KJUR.asn1.x509.OID.name2oid=function(e){if(e.match(/^[0-9.]+$/))return e;var t=KJUR.asn1.x509.OID.name2oidList;return void 0===t[e]?"":t[e]},KJUR.asn1.x509.X509Util={},KJUR.asn1.x509.X509Util.newCertPEM=function(e){var t=KJUR.asn1.x509;return t.TBSCertificate,new(0,t.Certificate)(e).getPEM()},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.cms&&KJUR.asn1.cms||(KJUR.asn1.cms={}),KJUR.asn1.cms.Attribute=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERSet,s=r.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 i({array:this.getValueArray()});return new n({array:[e,t]}).tohex()},this.getEncodedHex=function(){return this.tohex()}},extendClass(KJUR.asn1.cms.Attribute,KJUR.asn1.ASN1Object),KJUR.asn1.cms.ContentType=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.cms.ContentType,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.MessageDigest=function(e){var t=KJUR.asn1,r=t.DEROctetString;t.cms.MessageDigest.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.4",this.getValueArray=function(){return[new r(this.params)]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.MessageDigest,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.SigningTime=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.cms.SigningTime,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.SigningCertificate=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence,s=n.cms,o=s.ESSCertID;r.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 r=this.params.array,n=[],s=0;s<r.length;s++){var a=r[s];0!=e.hasis||"string"!=typeof a||-1==a.indexOf("-----BEGIN")&&!ASN1HEX.isASN1HEX(a)||(a={cert:a}),0!=a.hasis&&0==e.hasis&&(a.hasis=!1),n.push(new o(a))}var d=new i({array:n});return[new i({array:[d]})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SigningCertificate,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.ESSCertID=function(e){KJUR.asn1.cms.ESSCertID.superclass.constructor.call(this);var t=Error,r=KJUR,n=r.asn1,i=n.DEROctetString,s=n.DERSequence,o=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")&&!ASN1HEX.isASN1HEX(e))return e;var i,s,o;if("string"==typeof e)i=e;else{if(null==e.cert)throw new t("hash nor cert unspecified");i=e.cert}if(s=-1!=i.indexOf("-----BEGIN")?pemtohex(i):i,"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?s=pemtohex(e):ASN1HEX.isASN1HEX(e)&&(s=e)),null!=e.alg)o=e.alg;else{if(null==n)throw new t("hash alg unspecified");o=n}return r.crypto.Util.hashHex(s,o)},this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha1"),r=[];return r.push(new i({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&r.push(new o(e)),new s({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.ESSCertID,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SigningCertificateV2=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence;n.x509;var s=n.cms,o=s.ESSCertIDv2;r.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 r=this.params.array,n=[],s=0;s<r.length;s++){var a=r[s];null==e.alg&&0!=e.hasis||"string"!=typeof a||-1==a.indexOf("-----BEGIN")&&!ASN1HEX.isASN1HEX(a)||(a={cert:a}),null==a.alg&&null!=e.alg&&(a.alg=e.alg),0!=a.hasis&&0==e.hasis&&(a.hasis=!1),n.push(new o(a))}var d=new i({array:n});return[new i({array:[d]})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SigningCertificateV2,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.ESSCertIDv2=function(e){KJUR.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DEROctetString,n=t.DERSequence,i=t.cms.IssuerSerial,s=t.x509.AlgorithmIdentifier;this.params=null,this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha256"),o=[];return null!=e.alg&&"sha256"!=e.alg&&o.push(new s({name:e.alg})),o.push(new r({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&o.push(new i(e)),new n({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.ESSCertIDv2,KJUR.asn1.cms.ESSCertID),KJUR.asn1.cms.IssuerSerial=function(e){var t=Error,r=KJUR.asn1,n=r.DERInteger,i=r.DERSequence,s=r.cms,o=r.x509.GeneralNames,a=X509;s.IssuerSerial.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.tohex=function(){var e,r,s=this.params;if("string"==typeof s&&-1!=s.indexOf("-----BEGIN")||null!=s.cert){var d;d=null!=s.cert?s.cert:s;var c=new a;c.readCertPEM(d),e=c.getIssuer(),r={hex:c.getSerialNumberHex()}}else{if(null==s.issuer||!s.serial)throw new t("cert or issuer and serial parameter not specified");e=s.issuer,r=s.serial}var l=new o([{dn:e}]),u=new n(r);return new i({array:[l,u]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.IssuerSerial,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignerIdentifier=function(e){var t=KJUR.asn1;t.DERInteger,t.DERSequence;var r=t.cms,n=r.IssuerAndSerialNumber,i=r.SubjectKeyIdentifier;t.x509.X500Name,r.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 i(e).tohex();throw new Error("wrong property for isssn or skid")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignerIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.cms.IssuerAndSerialNumber=function(e){var t=KJUR.asn1,r=t.DERInteger,n=t.DERSequence,i=t.cms,s=t.x509.X500Name,o=X509,a=Error;i.IssuerAndSerialNumber.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e,t,i=this.params;if("string"==typeof i&&-1!=i.indexOf("-----BEGIN")||null!=i.cert){var d;d=null!=i.cert?i.cert:i;var c=new o;c.readCertPEM(d),e=c.getIssuer(),t={hex:c.getSerialNumberHex()}}else{if(null==i.issuer||!i.serial)throw new a("cert or issuer and serial parameter not specified");e=i.issuer,t=i.serial}var l=new s(e),u=new r(t);return new n({array:[l,u]}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.IssuerAndSerialNumber,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SubjectKeyIdentifier=function(e){var t=KJUR.asn1;t.DERInteger,t.DERSequence;var r=t.ASN1Util.newObject,n=t.cms;n.IssuerAndSerialName,n.SubjectKeyIdentifier,t.x509.X500Name;var i=X509,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 i(t.cert).getExtSubjectKeyIdentifier().kid.hex:null!=t.skid&&(e=t.skid);return r({tag:{tage:"a0",obj:{octstr:{hex:e}}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SubjectKeyIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.cms.AttributeList=function(e){var t=Error,r=KJUR.asn1,n=r.DERSet,i=r.cms;i.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 r=!0;null!=e.sortflag&&(r=e.sortflag);for(var s=e.array,o=[],a=0;a<s.length;a++){var d=s[a],c=d.attr;if("contentType"==c)o.push(new i.ContentType(d));else if("messageDigest"==c)o.push(new i.MessageDigest(d));else if("signingTime"==c)o.push(new i.SigningTime(d));else if("signingCertificate"==c)o.push(new i.SigningCertificate(d));else if("signingCertificateV2"==c)o.push(new i.SigningCertificateV2(d));else if("signaturePolicyIdentifier"==c)o.push(new KJUR.asn1.cades.SignaturePolicyIdentifier(d));else{if("signatureTimeStamp"!=c&&"timeStampToken"!=c)throw new t("unknown attr: "+c);o.push(new KJUR.asn1.cades.SignatureTimeStamp(d))}}var l=new n({array:o,sortflag:r});return this.hTLV=l.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.AttributeList,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignerInfo=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERInteger,s=n.DEROctetString,o=n.DERSequence,a=n.DERTaggedObject,d=n.cms,c=d.SignerIdentifier,l=d.AttributeList;d.ContentType,d.EncapsulatedContentInfo,d.MessageDigest,d.SignedData;var u=n.x509.AlgorithmIdentifier,h=r.crypto,g=KEYUTIL;d.SignerInfo.superclass.constructor.call(this),this.params=null,this.sign=function(){var e=this.params,t=e.sigalg,r=new l(e.sattrs).tohex(),n=g.getKey(e.signkey),i=new h.Signature({alg:t});i.init(n),i.updateHex(r);var s=i.sign();e.sighex=s},this.tohex=function(){var e=this.params,r=[];if(r.push(new i({int:e.version})),r.push(new c(e.id)),r.push(new u({name:e.hashalg})),null!=e.sattrs){var n=new l(e.sattrs);try{r.push(new a({tag:"a0",explicit:!1,obj:n}))}catch(e){throw new t("si sattr error: "+e)}}if(null!=e.sigalgfield?r.push(new u({name:e.sigalgfield})):r.push(new u({name:e.sigalg})),null==e.sighex&&null!=e.signkey&&this.sign(),r.push(new s({hex:e.sighex})),null!=e.uattrs){n=new l(e.uattrs);try{r.push(new a({tag:"a1",explicit:!1,obj:n}))}catch(e){throw new t("si uattr error: "+e)}}return new o({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignerInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.EncapsulatedContentInfo=function(e){var t=KJUR.asn1,r=t.DERTaggedObject,n=t.DERSequence,i=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 i(e.type)),null!=e.content&&(null!=e.content.hex||null!=e.content.str)&&1!=e.isDetached){var o=new s(e.content),a=new r({tag:"a0",explicit:!0,obj:o});t.push(a)}return new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.EncapsulatedContentInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.ContentInfo=function(e){var t=KJUR.asn1,r=t.DERTaggedObject,n=t.DERSequence,i=t.DERObjectIdentifier;t.x509.OID.name2obj,KJUR.asn1.cms.ContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];t.push(new i(e.type));var s=new r({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)},extendClass(KJUR.asn1.cms.ContentInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignedData=function(e){var t=KJUR.asn1;t.ASN1Object;var r=t.DERInteger,n=t.DERSet,i=t.DERSequence;t.DERTaggedObject;var s=t.cms,o=s.EncapsulatedContentInfo,a=s.SignerInfo,d=s.ContentInfo,c=s.CertificateSet,l=s.RevocationInfoChoices,u=t.x509.AlgorithmIdentifier;KJUR.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={},r=e.sinfos,n=0;n<r.length;n++){t[r[n].hashalg]=1}e.hashalgs=Object.keys(t).sort()},this._setContentTypeByEContent=function(e){for(var t=e.econtent.type,r=e.sinfos,n=0;n<r.length;n++){var i=r[n];this._getAttrParamByName(i,"contentType").type=t}},this._setMessageDigestByEContent=function(e){var t=e.econtent;e.econtent.type;var r=t.content.hex;null==r&&"data"==t.type&&null!=t.content.str&&(r=rstrtohex(t.content.str));for(var n=e.sinfos,i=0;i<n.length;i++){var s=n[i],o=s.hashalg,a=this._getAttrParamByName(s,"messageDigest"),d=KJUR.crypto.Util.hashHex(r,o);a.hex=d}},this._getAttrParamByName=function(e,t){for(var r=e.sattrs.array,n=0;n<r.length;n++)if(r[n].attr==t)return r[n]},this._setSignerInfoVersion=function(e){for(var t=e.sinfos,r=0;r<t.length;r++){var n=t[r],i=1;"skid"==n.id.type&&(i=3),n.version=i}},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,r=0;r<t.length;r++){if(null!=t[r].ocsp)return 5}var n=e.sinfos;for(r=0;r<n.length;r++){if(3==e.sinfos[r].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 r({int:e.version}));for(var s=[],d=0;d<e.hashalgs.length;d++){var h=e.hashalgs[d];s.push(new u({name:h}))}t.push(new n({array:s})),t.push(new o(e.econtent)),null!=e.certs&&t.push(new c(e.certs)),null!=e.revinfos&&t.push(new l(e.revinfos));var g=[];for(d=0;d<e.sinfos.length;d++){var p=e.sinfos[d];g.push(new a(p))}return t.push(new n({array:g})),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.getContentInfo=function(){return new d({type:"signed-data",obj:this})},this.getContentInfoEncodedHex=function(){return this.getContentInfo().tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignedData,KJUR.asn1.ASN1Object),KJUR.asn1.cms.CertificateSet=function(e){KJUR.asn1.cms.CertificateSet.superclass.constructor.call(this);var t=Error,r=KJUR.asn1,n=r.DERTaggedObject,i=r.DERSet,s=r.ASN1Object;this.params=null,this.tohex=function(){var e,r=this.params,o=[];if(r instanceof Array)e=r;else{if(null==r.array)throw new t("cert array not specified");e=r.array}for(var a=0;a<e.length;a++){var d=pemtohex(e[a]),c=new s;c.hTLV=d,o.push(c)}var l={array:o};0==r.sortflag&&(l.sortflag=!1);var u=new i(l);return new n({tag:"a0",explicit:!1,obj:u}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.CertificateSet,KJUR.asn1.ASN1Object),KJUR.asn1.cms.RevocationInfoChoices=function(e){KJUR.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=[],r=0;r<e.length;r++)t.push(new KJUR.asn1.cms.RevocationInfoChoice(e[r]));return KJUR.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:{set:t}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.RevocationInfoChoices,KJUR.asn1.ASN1Object),KJUR.asn1.cms.RevocationInfoChoice=function(e){KJUR.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=pemtohex(e.crl)),t}if(null!=e.ocsp)return KJUR.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:new KJUR.asn1.cms.OtherRevocationFormat(e)}}).tohex();throw new Error("property crl or ocsp undefined")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.RevocationInfoChoice,KJUR.asn1.ASN1Object),KJUR.asn1.cms.OtherRevocationFormat=function(e){KJUR.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);var t=Error,r=KJUR,n=r.asn1.ASN1Util.newObject,i=r.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(!i(e.ocsp)||!ASN1HEX.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)},extendClass(KJUR.asn1.cms.OtherRevocationFormat,KJUR.asn1.ASN1Object),KJUR.asn1.cms.CMSUtil=new function(){},KJUR.asn1.cms.CMSUtil.newSignedData=function(e){return new KJUR.asn1.cms.SignedData(e)},KJUR.asn1.cms.CMSUtil.verifySignedData=function(e){var t=KJUR,r=t.asn1,n=r.cms;n.SignerInfo,n.SignedData,n.SigningTime,n.SigningCertificate,n.SigningCertificateV2,r.cades.SignaturePolicyIdentifier;var i=t.lang.String.isHex,s=ASN1HEX,o=s.getVbyList,a=s.getTLVbyList,d=s.getIdxbyList,c=s.getChildIdx,l=s.getTLV,u=s.oidname,h=t.crypto.Util.hashHex;void 0===e.cms&&i(e.cms);var g=e.cms,p=function(e,t){var r=t.idx;t.signerid_issuer1=a(e,r,[1,0],"30"),t.signerid_serial1=o(e,r,[1,1],"02"),t.hashalg=u(o(e,r,[2,0],"06"));var n=d(e,r,[3],"a0");t.idxSignedAttrs=n,m(e,t,n);var i=c(e,r).length;if(i<6)throw"malformed SignerInfo";t.sigalg=u(o(e,r,[i-2,0],"06")),t.sigval=o(e,r,[i-1],"04")},m=function(e,t,r){var n=c(e,r);t.signedAttrIdxList=n;for(var i=0;i<n.length;i++){var s,a=n[i],d=o(e,a,[0],"06");"2a864886f70d010905"===d?(s=hextoutf8(o(e,a,[1,0])),t.saSigningTime=s):"2a864886f70d010904"===d&&(s=o(e,a,[1,0],"04"),t.saMessageDigest=s)}},f=function(e,t,r,n){r.verifyDetail={};var i=r.verifyDetail,s=t.parse.econtent,o=r.hashalg,a=r.saMessageDigest;i.validMessageDigest=!1,h(s,o)===a&&(i.validMessageDigest=!0),function(e,t,r,n){var i,s=t.parse.certsIdx;if(void 0===t.certs){i=[],t.certkeys=[];for(var o=c(e,s),a=0;a<o.length;a++){var d=l(e,o[a]),u=new X509;u.readCertHex(d),i[a]=u,t.certkeys[a]=u.getPublicKey()}t.certs=i}else i=t.certs;for(t.cccc=i.length,t.cccci=o.length,a=0;a<i.length;a++){var h=u.getIssuerHex(),g=u.getSerialNumberHex();r.signerid_issuer1===h&&r.signerid_serial1===g&&(r.certkey_idx=a)}}(e,t,r),i.validSignatureValue=!1;var d=r.sigalg,u="31"+l(e,r.idxSignedAttrs).substr(2);r.signedattrshex=u;var g=t.certs[r.certkey_idx].getPublicKey(),p=new KJUR.crypto.Signature({alg:d});p.init(g),p.updateHex(u);var m=p.verify(r.sigval);i.validSignatureValue_isValid=m,!0===m&&(i.validSignatureValue=!0),r.isValid=!1,i.validMessageDigest&&i.validSignatureValue&&(r.isValid=!0)},S={isValid:!1,parse:{}};return function(e,t){if("2a864886f70d010702"!==o(e,0,[0],"06"))return t;t.cmsType="signedData",t.econtent=o(e,0,[1,0,2,1,0]),function(e,t){for(var r,n=3;n<6;n++)if(void 0!==(r=d(e,0,[1,0,n]))){var i=e.substr(r,2);"a0"===i&&(t.certsIdx=r),"a1"===i&&(t.revinfosIdx=r),"31"===i&&(t.signerinfosIdx=r)}}(e,t),t.signerInfos=[],function(e,t){var r=t.signerinfosIdx;if(void 0!==r){var n=c(e,r);t.signerInfoIdxList=n;for(var i=0;i<n.length;i++){var s={idx:n[i]};p(e,s),t.signerInfos.push(s)}}}(e,t)}(g,S.parse),function(e,t){for(var r=t.parse.signerInfos,n=r.length,i=!0,s=0;s<n;s++){var o=r[s];f(e,t,o),o.isValid||(i=!1)}t.isValid=i}(g,S),S},KJUR.asn1.cms.CMSParser=function(){var e=Error,t=X509,r=new t,n=ASN1HEX,i=n.getV,s=n.getTLV;n.getIdxbyList;var o=n.getTLVbyList,a=n.getTLVbyListEx,d=n.getVbyList,c=n.getVbyListEx,l=n.getChildIdx;this.getCMSSignedData=function(e){var t=o(e,0,[1,0]);return this.getSignedData(t)},this.getSignedData=function(e){var t=l(e,0),r={},n=i(e,t[0]),o=parseInt(n,16);r.version=o;var d=s(e,t[1]);r.hashalgs=this.getHashAlgArray(d);var c=s(e,t[2]);r.econtent=this.getEContent(c);var u=a(e,0,["[0]"]);null!=u&&(r.certs=this.getCertificateSet(u)),a(e,0,["[1]"]);var h=a(e,0,[3]);return r.sinfos=this.getSignerInfos(h),r},this.getHashAlgArray=function(e){for(var r=l(e,0),n=new t,i=[],o=0;o<r.length;o++){var a=s(e,r[o]),d=n.getAlgorithmIdentifierName(a);i.push(d)}return i},this.getEContent=function(e){var t={},r=d(e,0,[0]),n=d(e,0,[1,0]);return t.type=KJUR.asn1.x509.OID.oid2name(ASN1HEX.hextooidstr(r)),t.content={hex:n},t},this.getSignerInfos=function(e){for(var t=[],r=l(e,0),n=0;n<r.length;n++){var i=s(e,r[n]),o=this.getSignerInfo(i);t.push(o)}return t},this.getSignerInfo=function(e){var t={},i=l(e,0),o=n.getInt(e,i[0],-1);-1!=o&&(t.version=o);var d=s(e,i[1]),u=this.getIssuerAndSerialNumber(d);t.id=u;var h=s(e,i[2]),g=r.getAlgorithmIdentifierName(h);t.hashalg=g;var p=a(e,0,["[0]"]);if(null!=p){var m=this.getAttributeList(p);t.sattrs=m}var f=a(e,0,[3]),S=r.getAlgorithmIdentifierName(f);t.sigalg=S;var y=c(e,0,[4]);t.sighex=y;var b=a(e,0,["[1]"]);if(null!=b){var E=this.getAttributeList(b);t.uattrs=E}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),o=s(e,n[0]);t.issuer=r.getX500Name(o);var a=i(e,n[1]);return t.serial={hex:a},t},this.getAttributeList=function(e){for(var t=[],r=l(e,0),n=0;n<r.length;n++){var i=s(e,r[n]),o=this.getAttribute(i);t.push(o)}return{array:t}},this.getAttribute=function(e){var t={},r=l(e,0),i=n.getOID(e,r[0]),o=KJUR.asn1.x509.OID.oid2name(i);t.attr=o;var a=s(e,r[1]),d=l(a,0);if(1==d.length)t.valhex=s(a,d[0]);else{for(var c=[],u=0;u<d.length;u++)c.push(s(a,d[u]));t.valhex=c}return"contentType"==o?this.setContentType(t):"messageDigest"==o?this.setMessageDigest(t):"signingTime"==o?this.setSigningTime(t):"signingCertificate"==o?this.setSigningCertificate(t):"signingCertificateV2"==o?this.setSigningCertificateV2(t):"signaturePolicyIdentifier"==o&&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=hextoutf8(i(e.valhex,0));e.str=t,delete e.valhex},this.setMessageDigest=function(e){var t=i(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 r=s(e.valhex,t[0]),n=l(r,0),i=[],o=0;o<n.length;o++){var a=s(r,n[o]),d=this.getESSCertID(a);i.push(d)}e.array=i}if(t.length>1){var c=s(e.valhex,t[1]);e.polhex=c}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var r=l(e.valhex,0);if(r.length>0){var o=n.getOID(e.valhex,r[0]);e.oid=o}if(r.length>1){var a=new t,d=l(e.valhex,r[1]),c=s(e.valhex,d[0]),u=a.getAlgorithmIdentifierName(c);e.alg=u;var h=i(e.valhex,d[1]);e.hash=h}delete e.valhex},this.setSigningCertificateV2=function(e){var t=l(e.valhex,0);if(t.length>0){for(var r=s(e.valhex,t[0]),n=l(r,0),i=[],o=0;o<n.length;o++){var a=s(r,n[o]),d=this.getESSCertIDv2(a);i.push(d)}e.array=i}if(t.length>1){var c=s(e.valhex,t[1]);e.polhex=c}delete e.valhex},this.getESSCertID=function(e){var t={},r=l(e,0);if(r.length>0){var n=i(e,r[0]);t.hash=n}if(r.length>1){var o=s(e,r[1]),a=this.getIssuerSerial(o);null!=a.serial&&(t.serial=a.serial),null!=a.issuer&&(t.issuer=a.issuer)}return t},this.getESSCertIDv2=function(t){var n={},o=l(t,0);if(o.length<1||3<o.length)throw new e("wrong number of elements");var a=0;if("30"==t.substr(o[0],2)){var d=s(t,o[0]);n.alg=r.getAlgorithmIdentifierName(d),a++}else n.alg="sha256";var c=i(t,o[a]);if(n.hash=c,o.length>a+1){var u=s(t,o[a+1]),h=this.getIssuerSerial(u);n.issuer=h.issuer,n.serial=h.serial}return n},this.getIssuerSerial=function(e){var t={},n=l(e,0),o=s(e,n[0]),a=r.getGeneralNames(o)[0].dn;t.issuer=a;var d=i(e,n[1]);return t.serial={hex:d},t},this.getCertificateSet=function(e){for(var t=l(e,0),r=[],n=0;n<t.length;n++){var i=s(e,t[n]);if("30"==i.substr(0,2)){var o=hextopem(i,"CERTIFICATE");r.push(o)}}return{array:r,sortflag:!1}}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.tsp&&KJUR.asn1.tsp||(KJUR.asn1.tsp={}),KJUR.asn1.tsp.TimeStampToken=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.tsp.TimeStampToken,KJUR.asn1.cms.SignedData),KJUR.asn1.tsp.TSTInfo=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERInteger,i=t.DERBoolean,s=t.DERGeneralizedTime,o=t.DERObjectIdentifier,a=t.DERTaggedObject,d=t.tsp,c=d.MessageImprint,l=d.Accuracy;t.x509.X500Name;var u=t.x509.GeneralName;if(d.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 r({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 o({oid:e.policy})}void 0!==e.messageImprint&&(this.dMessageImprint=new c(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 i),void 0!==e.nonce&&(this.dNonce=new n(e.nonce)),void 0!==e.tsa&&(this.dTsa=new a({tag:"a0",explicit:!0,obj:new u({dn:e.tsa})}))}},extendClass(KJUR.asn1.tsp.TSTInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.Accuracy=function(e){var t=KJUR.asn1,r=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}}}),r({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.Accuracy,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.MessageImprint=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DEROctetString,i=t.x509.AlgorithmIdentifier;t.tsp.MessageImprint.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=new i({name:e.alg}),s=new n({hex:e.hash});return new r({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.MessageImprint,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.TimeStampReq=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERInteger,i=t.DERBoolean;t.ASN1Object;var s=t.DERObjectIdentifier,o=t.tsp,a=o.MessageImprint;o.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 KJUR.asn1.ASN1Object?t.push(e.messageImprint):t.push(new a(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 i),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.TimeStampReq,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.TimeStampResp=function(e){var t=KJUR.asn1,r=t.DERSequence;t.ASN1Object;var n=t.tsp,i=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 i(e.statusinfo)):s.push(new i("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 i(e.statusinfo))}return new r({array:s}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.TimeStampResp,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIStatusInfo=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.tsp,s=i.PKIStatus,o=i.PKIFreeText,a=i.PKIFailureInfo;i.PKIStatusInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,r=[];if("string"==typeof e)r.push(new s(e));else{if(null==e.status)throw new t("property 'status' unspecified");r.push(new s(e.status)),null!=e.statusstr&&r.push(new o(e.statusstr)),null!=e.failinfo&&r.push(new a(e.failinfo))}return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIStatusInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIStatus=function(e){var t=Error,r=KJUR.asn1,n=r.DERInteger;r.tsp.PKIStatus.superclass.constructor.call(this);var i={granted:0,grantedWithMods:1,rejection:2,waiting:3,revocationWarning:4,revocationNotification:5};this.params=null,this.tohex=function(){var e,r=this.params;if("string"==typeof r)try{e=i[r]}catch(e){throw new t("undefined name: "+r)}else{if("number"!=typeof r)throw new t("unsupported params");e=r}return new n({int:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIStatus,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIFreeText=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERUTF8String;r.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 r=[],s=0;s<e.length;s++)r.push(new i({str:e[s]}));return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIFreeText,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIFailureInfo=function(e){var t=Error,r=KJUR.asn1,n=r.DERBitString,i=r.tsp.PKIFailureInfo,s={badAlg:0,badRequest:2,badDataFormat:5,timeNotAvailable:14,unacceptedPolicy:15,unacceptedExtension:16,addInfoNotAvailable:17,systemFailure:25};i.superclass.constructor.call(this),this.params=null,this.getBinValue=function(){var e=this.params,r=0;if("number"==typeof e&&0<=e&&e<=25){for(var n=(r|=1<<e).toString(2),i="",o=n.length-1;o>=0;o--)i+=n[o];return i}if("string"==typeof e&&null!=s[e])return namearraytobinstr([e],s);if("object"==typeof e&&null!=e.length)return namearraytobinstr(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)},extendClass(KJUR.asn1.tsp.PKIFailureInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},KJUR.asn1.tsp.SimpleTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var i=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:i},this.params.econtent.content.serial={int:this.serial++};var s=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:s},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.SimpleTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.FixedTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var i=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:i},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.FixedTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.TSPUtil=new function(){},KJUR.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new KJUR.asn1.tsp.TimeStampToken(e)},KJUR.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new KJUR.asn1.tsp.TSPParser).getTimeStampReq(e)},KJUR.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new KJUR.asn1.tsp.TSPParser).getMessageImprint(e)},KJUR.asn1.tsp.TSPParser=function(){var e=new X509,t=ASN1HEX,r=t.getV,n=t.getTLV,i=t.getIdxbyList;t.getTLVbyListEx;var s=t.getChildIdx,o=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],a={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 r=this.getPKIStatusInfo(n(e,t[0])),i=n(e,t[1]),o=this.getToken(i);return o.statusinfo=r,o}},this.getToken=function(e){var t=(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var r=t.content.hex,n=this.getTSTInfo(r);t.content=n}},this.getTSTInfo=function(t){var i={},o=s(t,0),a=r(t,o[1]);i.policy=hextooid(a);var d=n(t,o[2]);i.messageImprint=this.getMessageImprint(d);var c=r(t,o[3]);i.serial={hex:c};var l=r(t,o[4]);i.genTime={str:hextoutf8(l)};var u=0;if(o.length>5&&"30"==t.substr(o[5],2)){var h=n(t,o[5]);i.accuracy=this.getAccuracy(h),u++}o.length>5+u&&"01"==t.substr(o[5+u],2)&&("ff"==r(t,o[5+u])&&(i.ordering=!0),u++);if(o.length>5+u&&"02"==t.substr(o[5+u],2)){var g=r(t,o[5+u]);i.nonce={hex:g},u++}if(o.length>5+u&&"a0"==t.substr(o[5+u],2)){var p=n(t,o[5+u]);p="30"+p.substr(2),pGeneralNames=e.getGeneralNames(p);var m=pGeneralNames[0].dn;i.tsa=m,u++}if(o.length>5+u&&"a1"==t.substr(o[5+u],2)){var f=n(t,o[5+u]);f="30"+f.substr(2);var S=e.getExtParamArray(f);i.ext=S,u++}return i},this.getAccuracy=function(e){for(var t={},n=s(e,0),i=0;i<n.length;i++){var o=e.substr(n[i],2),a=r(e,n[i]),d=parseInt(a,16);"02"==o?t.seconds=d:"80"==o?t.millis=d:"81"==o&&(t.micros=d)}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 o=i(e,0,[0,0]),a=r(e,o),d=t.hextooidstr(a),c=KJUR.asn1.x509.OID.oid2name(d);if(""==c)throw new Error("hashAlg name undefined: "+d);var l=c,u=i(e,0,[1]);return n.alg=l,n.hash=r(e,u),n},this.getPKIStatusInfo=function(e){var t={},i=s(e,0),a=0;try{var d=r(e,i[0]),c=parseInt(d,16);t.status=o[c]}catch(e){}if(i.length>1&&"30"==e.substr(i[1],2)){var l=n(e,i[1]);t.statusstr=this.getPKIFreeText(l),a++}if(i.length>a&&"03"==e.substr(i[1+a],2)){var u=n(e,i[1+a]);t.failinfo=this.getPKIFailureInfo(u)}return t},this.getPKIFreeText=function(e){for(var r=[],n=s(e,0),i=0;i<n.length;i++)r.push(t.getString(e,n[i]));return r},this.getPKIFailureInfo=function(e){var r=t.getInt(e,0);return null!=a[r]?a[r]:r},this.getTimeStampReq=function(e){var i={certreq:!1},o=s(e,0);if(o.length<2)throw new Error("TimeStampReq must have at least 2 items");var a=n(e,o[1]);i.messageImprint=KJUR.asn1.tsp.TSPUtil.parseMessageImprint(a);for(var d=2;d<o.length;d++){var c=o[d],l=e.substr(c,2);if("06"==l){var u=r(e,c);i.policy=t.hextooidstr(u)}"02"==l&&(i.nonce=r(e,c)),"01"==l&&(i.certreq=!0)}return i}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.cades&&KJUR.asn1.cades||(KJUR.asn1.cades={}),KJUR.asn1.cades.SignaturePolicyIdentifier=function(e){var t=KJUR.asn1.cades,r=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 r(this.params)]},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignaturePolicyIdentifier,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.SignaturePolicyId=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier;t.x509.AlgorithmIdentifier;var i=t.cades,s=i.SignaturePolicyId,o=i.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 o(e)),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignaturePolicyId,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHashAlgAndValue=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DEROctetString,s=r.x509.AlgorithmIdentifier;r.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 r=null;if(null!=e.hash)r=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var o=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(o=pemtohex(e.cert)),r=KJUR.crypto.Util.hashHex(o,e.alg)}var a=[];return a.push(new s({name:e.alg})),a.push(new i({hex:r})),new n({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHashAlgAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHashValue=function(e){KJUR.asn1.cades.OtherHashValue.superclass.constructor.call(this);var t=Error,r=KJUR;r.lang.String.isHex;var n=r.asn1.DEROctetString;r.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 r=null;if(null!=e.hash)r=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var i=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(i=pemtohex(e.cert)),r=KJUR.crypto.Util.hashHex(i,"sha1")}return new n({hex:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHashValue,KJUR.asn1.ASN1Object),KJUR.asn1.cades.SignatureTimeStamp=function(e){var t=Error,r=KJUR,n=r.lang.String.isHex,i=r.asn1,s=i.ASN1Object;i.x509,i.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(r=new s).hTLV=e.tst,[r];if(e.tst instanceof s)return[e.tst];throw new t("params.tst has wrong value")}if(null!=e.res){var r,i=e.res;if(i instanceof s&&(i=i.tohex()),"string"!=typeof i||!n(i))throw new t("params.res has wrong value");return ASN1HEX.getTLVbyList(i,0,[1]),(r=new s).hTLV=e.tst,[r]}},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignatureTimeStamp,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.CompleteCertificateRefs=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence,s=n.cades,o=s.OtherCertID,a=r.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,r=[],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(!a(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 d=new o(s);r.push(d)}return[new i({array:r})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.CompleteCertificateRefs,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.OtherCertID=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.cms.IssuerSerial,i=t.cades,s=i.OtherHashValue,o=i.OtherHashAlgAndValue;i.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=[],i=null;if(i=null!=e.alg?new o(e):new s(e),t.push(i),null!=e.cert&&1==e.hasis||null!=e.issuer&&null!=e.serial){var a=new n(e);t.push(a)}return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherCertID,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHash=function(e){var t=KJUR,r=t.asn1;r.cms;var n=r.cades,i=n.OtherHashAlgAndValue,s=n.OtherHashValue;t.crypto.Util.hashHex;var o=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}:o(e)&&(e={hash:e}));return(null!=e.alg?new i(e):new s(e)).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHash,KJUR.asn1.ASN1Object),KJUR.asn1.cades.CAdESUtil=new function(){},KJUR.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned=function(e){return(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e)},KJUR.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned=function(e,t,r){var n=ASN1HEX,i=n.getChildIdx,s=n.getTLV,o=n.getV,a=KJUR.asn1,d=a.ASN1Object,c=a.cms,l=c.AttributeList,u=c.SignerInfo,h={},g=i(e,t);if(6!=g.length)throw"not supported items for SignerInfo (!=6)";var p=g.shift();h.version=s(e,p);var m=g.shift();h.si=s(e,m);var f=g.shift();h.digalg=s(e,f);var S=g.shift();h.sattrs=s(e,S);var y=g.shift();h.sigalg=s(e,y);var b=g.shift();h.sig=s(e,b),h.sigval=o(e,b);var E=null;return h.obj=new u,(E=new d).hTLV=h.version,h.obj.dCMSVersion=E,(E=new d).hTLV=h.si,h.obj.dSignerIdentifier=E,(E=new d).hTLV=h.digalg,h.obj.dDigestAlgorithm=E,(E=new d).hTLV=h.sattrs,h.obj.dSignedAttrs=E,(E=new d).hTLV=h.sigalg,h.obj.dSigAlg=E,(E=new d).hTLV=h.sig,h.obj.dSig=E,h.obj.dUnsignedAttrs=new l,h},void 0!==KJUR.asn1.csr&&KJUR.asn1.csr||(KJUR.asn1.csr={}),KJUR.asn1.csr.CertificationRequest=function(e){var t=KJUR.asn1,r=t.DERBitString,n=t.DERSequence,i=t.csr;t.x509;var s=i.CertificationRequestInfo;i.CertificationRequest.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.sign=function(){var e=new s(this.params).tohex(),t=new KJUR.crypto.Signature({alg:this.params.sigalg});t.init(this.params.sbjprvkey),t.updateHex(e);var r=t.sign();this.params.sighex=r},this.getPEM=function(){return hextopem(this.tohex(),"CERTIFICATE REQUEST")},this.tohex=function(){var e=this.params,t=new KJUR.asn1.csr.CertificationRequestInfo(this.params),i=new KJUR.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 r({hex:"00"+e.sighex});return new n({array:[t,i,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.csr.CertificationRequest,KJUR.asn1.ASN1Object),KJUR.asn1.csr.CertificationRequestInfo=function(e){var t=KJUR.asn1;t.DERBitString;var r=t.DERSequence,n=t.DERInteger,i=t.DERUTF8String,s=t.DERTaggedObject,o=t.ASN1Util.newObject,a=t.csr,d=t.x509,c=d.X500Name,l=d.Extensions,u=d.SubjectPublicKeyInfo;a.AttributeList,a.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 c(e.subject)),t.push(new u(KEYUTIL.getKey(e.sbjpubkey))),null!=e.attrs){var a=function(e){for(var t=Error,r=KJUR.asn1.x509.Extensions,n=[],i=0;i<e.length;i++){var s=e[i],o=s.attr;if("extensionRequest"==o){var a={seq:[{oid:"1.2.840.113549.1.9.14"},{set:[new r(s.ext)]}]};n.push(a)}else if("unstructuredName"==o){a={seq:[{oid:"1.2.840.113549.1.9.2"},{set:s.names}]};n.push(a)}else{if("challengePassword"!=o)throw new t("unknown CSR attribute");a={seq:[{oid:"1.2.840.113549.1.9.7"},{set:[{utf8str:s.password}]}]};n.push(a)}}return{set:n}}(e.attrs),d=o({tag:{tage:"a0",obj:a}});t.push(d)}else if(null!=e.extreq){var h=new l(e.extreq);d=o({tag:{tage:"a0",obj:{seq:[{oid:"1.2.840.113549.1.9.14"},{set:[h]}]}}});t.push(d)}else t.push(new s({tag:"a0",explicit:!1,obj:new i({str:""})}));return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.csr.CertificationRequestInfo,KJUR.asn1.ASN1Object),KJUR.asn1.csr.AttributeList=function(e){},extendClass(KJUR.asn1.csr.AttributeList,KJUR.asn1.ASN1Object),KJUR.asn1.csr.CSRUtil=new function(){},KJUR.asn1.csr.CSRUtil.newCSRPEM=function(e){return new KJUR.asn1.csr.CertificationRequest(e).getPEM()},KJUR.asn1.csr.CSRUtil.getParam=function(e,t){var r=ASN1HEX,n=r.getV,i=r.getIdxbyList,s=r.getTLVbyList,o=r.getTLVbyListEx,a=r.getVbyListEx,d={};if(-1==e.indexOf("-----BEGIN CERTIFICATE REQUEST"))throw new Error("argument is not PEM file");var c=pemtohex(e,"CERTIFICATE REQUEST");t&&(d.tbs=s(c,0,[0]));try{var l=o(c,0,[0,1]);if("3000"==l)d.subject={};else{var u=new X509;d.subject=u.getX500Name(l)}}catch(e){}var h=o(c,0,[0,2]),g=KEYUTIL.getKey(h,null,"pkcs8pub");d.sbjpubkey=KEYUTIL.getPEM(g,"PKCS8PUB");var p=function(e){var t=i(e,0,[0,3,0,0],"06");return"2a864886f70d01090e"!=n(e,t)?null:s(e,0,[0,3,0,1,0],"30")}(c);u=new X509;null!=p&&(d.extreq=u.getExtParamArray(p));try{var m=o(c,0,[1],"30");u=new X509;d.sigalg=u.getAlgorithmIdentifierName(m)}catch(e){}try{var f=a(c,0,[2]);d.sighex=f}catch(e){}return d},KJUR.asn1.csr.CSRUtil.verifySignature=function(e){try{var t=null;if("string"==typeof e&&-1!=e.indexOf("-----BEGIN CERTIFICATE REQUEST")?t=KJUR.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 r=new KJUR.crypto.Signature({alg:t.sigalg});return r.init(t.sbjpubkey),r.updateHex(t.tbs),r.verify(t.sighex)}catch(e){return alert(e),!1}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.ocsp&&KJUR.asn1.ocsp||(KJUR.asn1.ocsp={}),KJUR.asn1.ocsp.DEFAULT_HASH="sha1",KJUR.asn1.ocsp.OCSPResponse=function(e){KJUR.asn1.ocsp.OCSPResponse.superclass.constructor.call(this),KJUR.asn1.DEREnumerated;var t=KJUR.asn1.ASN1Util.newObject,r=KJUR.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 i=new r(e);return t({seq:[{enum:{int:0}},{tag:{tag:"a0",explicit:!0,obj:i}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.OCSPResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponseBytes=function(e){KJUR.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier,i=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),o=[];return o.push(new n({name:"ocspBasic"})),o.push(new i({hex:t.tohex()})),new r({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponseBytes,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.BasicOCSPResponse=function(e){KJUR.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);var t=Error,r=KJUR.asn1,n=r.ASN1Object,i=r.DERSequence;r.DERGeneralizedTime;var s=r.DERTaggedObject,o=r.DERBitString;r.x509.Extensions;var a=r.x509.AlgorithmIdentifier,d=r.ocsp;d.ResponderID,_SingleResponseList=d.SingleResponseList,_ResponseData=d.ResponseData,this.params=null,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.tbsresp.tohex(),r=new KJUR.crypto.Signature({alg:e.sigalg});r.init(e.reskey),r.updateHex(t),e.sighex=r.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 r=[];if(r.push(e.tbsresp),r.push(new a({name:e.sigalg})),r.push(new o({hex:"00"+e.sighex})),null!=e.certs&&null!=e.certs.length){for(var d=[],c=0;c<e.certs.length;c++){var l=e.certs[c],u=null;if(ASN1HEX.isASN1HEX(l))u=l;else{if(!l.match(/-----BEGIN/))throw new t("certs["+c+"] not hex or PEM");u=pemtohex(l)}d.push(new n({tlv:u}))}var h=new i({array:d});r.push(new s({tag:"a0",explicit:!0,obj:h}))}return new i({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.BasicOCSPResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponseData=function(e){KJUR.asn1.ocsp.ResponseData.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERGeneralizedTime,i=t.DERTaggedObject,s=t.x509.Extensions,o=t.ocsp,a=o.ResponderID;_SingleResponseList=o.SingleResponseList,this.params=null,this.tohex=function(){var e=this.params;e.respid,e.prodat,e.array;var t=[];if(t.push(new a(e.respid)),t.push(new n(e.prodat)),t.push(new _SingleResponseList(e.array)),null!=e.ext){var o=new s(e.ext);t.push(new i({tag:"a1",explicit:!0,obj:o}))}return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponseData,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponderID=function(e){KJUR.asn1.ocsp.ResponderID.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.ASN1Util.newObject,i=r.x509.X500Name,s=t.lang.String.isHex,o=Error;this.params=null,this.tohex=function(){var e=this.params;if(null!=e.key){var t,r=null;if("string"==typeof e.key){if(s(e.key)&&(r=e.key),e.key.match(/-----BEGIN CERTIFICATE/))null!=(t=new X509(e.key).getExtSubjectKeyIdentifier())&&(r=t.kid.hex)}else if(e.key instanceof X509)null!=(t=e.key.getExtSubjectKeyIdentifier())&&(r=t.kid.hex);if(null==r)throw new o("wrong key member value");return n({tag:{tag:"a2",explicit:!0,obj:{octstr:{hex:r}}}}).tohex()}if(null!=e.name){var a=null;if("string"==typeof e.name&&e.name.match(/-----BEGIN CERTIFICATE/))a=new X509(e.name).getSubject();else e.name instanceof X509?a=e.name.getSubject():"object"!=typeof e.name||null==e.name.array&&null==e.name.str||(a=e.name);if(null==a)throw new o("wrong name member value");return n({tag:{tag:"a1",explicit:!0,obj:new i(a)}}).tohex()}throw new o("key or name not specified")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponderID,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.SingleResponseList=function(e){KJUR.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);var t=KJUR.asn1,r=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=[],i=0;i<e.length;i++)t.push(new n(e[i]));return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.SingleResponseList,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.SingleResponse=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERGeneralizedTime,s=r.DERTaggedObject,o=r.ocsp,a=o.CertID,d=o.CertStatus,c=r.x509.Extensions;o.SingleResponse.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,r=[];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(r.push(new a(e.certid)),r.push(new d(e.status)),r.push(new i(e.thisupdate)),null!=e.nextupdate){var o=new i(e.nextupdate);r.push(new s({tag:"a0",explicit:!0,obj:o}))}if(null!=e.ext){var l=new c(e.ext);r.push(new s({tag:"a1",explicit:!0,obj:l}))}return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.SingleResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.CertID=function(e){var t=KJUR,r=t.asn1,n=r.DEROctetString,i=r.DERInteger,s=r.DERSequence,o=r.x509.AlgorithmIdentifier,a=r.ocsp;a.DEFAULT_HASH;var d=t.crypto.Util.hashHex,c=X509,l=ASN1HEX.getVbyList;a.CertID.superclass.constructor.call(this),this.DEFAULT_HASH="sha1",this.params=null,this.setByValue=function(e,t,r,n){null==n&&(n=this.DEFAULT_HASH),this.params={alg:n,issname:e,isskey:t,sbjsn:r}},this.setByCert=function(e,t,r){null==r&&(r=this.DEFAULT_HASH),this.params={alg:r,issuerCert:e,subjectCert:t}},this.getParamByCerts=function(e,t,r){null==r&&(r=this.DEFAULT_HASH);var n=new c(e),i=new c(t),s=d(n.getSubjectHex(),r),o=n.getPublicKeyHex();return{alg:r,issname:s,isskey:d(l(o,0,[1],"03",!0),r),sbjsn:i.getSerialNumberHex()}},this.tohex=function(){if("object"!=typeof this.params)throw new Error("params not set");var e,t,r,a,d=this.params;if(a=null==d.alg?this.DEFAULT_HASH:d.alg,null!=d.issuerCert&&null!=d.subjectCert){var c=this.getParamByCerts(d.issuerCert,d.subjectCert,a);e=c.issname,t=c.isskey,r=c.sbjsn}else{if(null==d.issname||null==d.isskey||null==d.sbjsn)throw new Error("required param members not defined");e=d.issname,t=d.isskey,r=d.sbjsn}var l=new o({name:a}),u=new n({hex:e}),h=new n({hex:t}),g=new i({hex:r}),p=new s({array:[l,u,h,g]});return this.hTLV=p.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.CertID,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.CertStatus=function(e){KJUR.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 r={tag:"a1",explicit:!1,obj:{seq:t}};return KJUR.asn1.ASN1Util.newObject({tag:r}).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)},extendClass(KJUR.asn1.ocsp.CertStatus,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.Request=function(e){var t=KJUR.asn1,r=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 r({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){var i=new n.CertID(e);this.dReqCert=i}},extendClass(KJUR.asn1.ocsp.Request,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.TBSRequest=function(e){var t=KJUR.asn1,r=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=[],r=0;r<e.length;r++){var i=new n.Request(e[0]);t.push(i)}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 r({array:this.dRequestList});if(e.push(t),null!==this.dRequestExt)throw"requestExtensions not supported";var n=new r({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)},extendClass(KJUR.asn1.ocsp.TBSRequest,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.OCSPRequest=function(e){var t=KJUR.asn1,r=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 r({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList){var i=new n.TBSRequest(e);this.dTbsRequest=i}},extendClass(KJUR.asn1.ocsp.OCSPRequest,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.OCSPUtil={},KJUR.asn1.ocsp.OCSPUtil.getRequestHex=function(e,t,r){var n=KJUR.asn1.ocsp;void 0===r&&(r=n.DEFAULT_HASH);var i={alg:r,issuerCert:e,subjectCert:t};return new n.OCSPRequest({reqList:[i]}).tohex()},KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo=function(e){var t=ASN1HEX,r=t.getVbyList,n=t.getVbyListEx,i=t.getIdxbyList;t.getIdxbyListEx;var s=t.getV,o={};try{var a=n(e,0,[0],"0a");o.responseStatus=parseInt(a,16)}catch(e){}if(0!==o.responseStatus)return o;try{var d=i(e,0,[1,0,1,0,0,2,0,1]);"80"===e.substr(d,2)?o.certStatus="good":"a1"===e.substr(d,2)?(o.certStatus="revoked",o.revocationTime=hextoutf8(r(e,d,[0]))):"82"===e.substr(d,2)&&(o.certStatus="unknown")}catch(e){}try{var c=i(e,0,[1,0,1,0,0,2,0,2]);o.thisUpdate=hextoutf8(s(e,c))}catch(e){}try{var l=i(e,0,[1,0,1,0,0,2,0,3]);"a0"===e.substr(l,2)&&(o.nextUpdate=hextoutf8(r(e,l,[0])))}catch(e){}return o},KJUR.asn1.ocsp.OCSPParser=function(){var e=Error,t=X509,r=new t,n=ASN1HEX,i=n.getV,s=n.getTLV,o=n.getIdxbyList,a=n.getVbyList,d=n.getTLVbyList,c=n.getVbyListEx,l=n.getTLVbyListEx,u=n.getChildIdx;this.getOCSPRequest=function(t){var r=u(t,0);if(1!=r.length&&2!=r.length)throw new e("wrong number elements: "+r.length);return this.getTBSRequest(s(t,r[0]))},this.getTBSRequest=function(e){var t={},n=l(e,0,[0],"30");t.array=this.getRequestList(n);var i=l(e,0,["[2]",0],"30");return null!=i&&(t.ext=r.getExtParamArray(i)),t},this.getRequestList=function(e){for(var t=[],r=u(e,0),n=0;n<r.length;n++){e=s(e,r[n]);t.push(this.getRequest(e))}return t},this.getRequest=function(t){var n=u(t,0);if(1!=n.length&&2!=n.length)throw new e("wrong number elements: "+n.length);var i=this.getCertID(s(t,n[0]));if(2==n.length){var a=o(t,0,[1,0]);i.ext=r.getExtParamArray(s(t,a))}return i},this.getCertID=function(r){var n=u(r,0);if(4!=n.length)throw new e("wrong number elements: "+n.length);var o=new t,a={};return a.alg=o.getAlgorithmIdentifierName(s(r,n[0])),a.issname=i(r,n[1]),a.isskey=i(r,n[2]),a.sbjsn=i(r,n[3]),a},this.getOCSPResponse=function(e){var t,r=u(e,0),n=i(e,r[0]),s=parseInt(n);if(1==r.length)return{resstatus:s};var o=d(e,0,[1,0]);return(t=this.getResponseBytes(o)).resstatus=s,t},this.getResponseBytes=function(e){var t,r=u(e,0),n=d(e,0,[1,0]);t=this.getBasicOCSPResponse(n);var s=i(e,r[0]);return t.restype=KJUR.asn1.x509.OID.oid2name(hextooid(s)),t},this.getBasicOCSPResponse=function(e){var t,r=u(e,0);t=this.getResponseData(s(e,r[0]));var n=new X509;t.alg=n.getAlgorithmIdentifierName(s(e,r[1]));var o=i(e,r[2]);t.sighex=o.substr(2);var a=c(e,0,["[0]"]);if(null!=a){for(var d=u(a,0),l=[],h=0;h<d.length;h++){var g=s(a,d[h]);l.push(g)}t.certs=l}return t},this.getResponseData=function(e){var t=u(e,0),r=t.length,n={},o=0;"a0"==e.substr(t[0],2)&&o++,n.respid=this.getResponderID(s(e,t[o++]));var a=i(e,t[o++]);if(n.prodat=hextoutf8(a),n.array=this.getSingleResponseList(s(e,t[o++])),"a1"==e.substr(t[r-1],2)){var c=d(e,t[r-1],[0]),l=new X509;n.ext=l.getExtParamArray(c)}return n},this.getResponderID=function(e){var t={};if("a2"==e.substr(0,2)){var r=a(e,0,[0]);t.key=r}if("a1"==e.substr(0,2)){var n=d(e,0,[0]),i=new X509;t.name=i.getX500Name(n)}return t},this.getSingleResponseList=function(e){for(var t=u(e,0),r=[],n=0;n<t.length;n++){var i=this.getSingleResponse(s(e,t[n]));r.push(i)}return r},this.getSingleResponse=function(e){var t=u(e,0),r={},n=this.getCertID(s(e,t[0]));r.certid=n;var o=this.getCertStatus(s(e,t[1]));if(r.status=o,"18"==e.substr(t[2],2)){var c=i(e,t[2]);r.thisupdate=hextoutf8(c)}for(var l=3;l<t.length;l++){if("a0"==e.substr(t[l],2)){var h=a(e,t[l],[0],"18");r.nextupdate=hextoutf8(h)}if("a1"==e.substr(t[l],2)){var g=new X509,p=d(e,0,[l,0]);r.ext=g.getExtParamArray(p)}}return r},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 r=hextoutf8(a(e,0,[0]));t.time=r}return t}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.lang&&KJUR.lang||(KJUR.lang={}),KJUR.lang.String=function(){},"function"==typeof Buffer?(utf8tob64u=function(e){return b64tob64u(Buffer.from(e,"utf8").toString("base64"))},b64utoutf8=function(e){return Buffer.from(b64utob64(e),"base64").toString("utf8")}):(utf8tob64u=function(e){return hextob64u(uricmptohex(encodeURIComponentAll(e)))},b64utoutf8=function(e){return decodeURIComponent(hextouricmp(b64utohex(e)))}),KJUR.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},KJUR.lang.String.isHex=function(e){return ishex(e)},KJUR.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},KJUR.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=b64utob64(e),KJUR.lang.String.isBase64(e))},KJUR.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},KJUR.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},KJUR.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},KJUR.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 strpad=function(e,t,r){return null==r&&(r="0"),e.length>=t?e:new Array(t-e.length+1).join(r)+e};function bitstrtoint(e){if(e.length%2!=0)return-1;if(null==(e=e.toLowerCase()).match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16);if(r>7)return-1;var n=e.substr(2),i=parseInt(n,16).toString(2);"0"==i&&(i="00000000"),i=i.slice(0,0-r);var s=parseInt(i,2);return NaN==s?-1:s}catch(e){return-1}}function bitstrtobinstr(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 r=e.substr(2),n="",i=0;i<r.length;i+=2){var s=r.substr(i,2),o=parseInt(s,16).toString(2);n+=o=("0000000"+o).slice(-8)}return n.substr(0,n.length-t)}catch(e){return null}}function namearraytobinstr(e,t){for(var r=0,n=0;n<e.length;n++)r|=1<<t[e[n]];var i=r.toString(2),s="";for(n=i.length-1;n>=0;n--)s+=i[n];return s}function aryval(e,t,r){if("object"==typeof e){t=String(t).split(".");for(var n=0;n<t.length&&e;n++){var i=t[n];i.match(/^[0-9]+$/)&&(i=parseInt(i)),e=e[i]}return e||!1===e?e:r}}function extendClass(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.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:CryptoJS.algo.MD5,sha1:CryptoJS.algo.SHA1,sha224:CryptoJS.algo.SHA224,sha256:CryptoJS.algo.SHA256,sha384:CryptoJS.algo.SHA384,sha512:CryptoJS.algo.SHA512,ripemd160:CryptoJS.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,r){var n=this.getDigestInfoHex(e,t),i=r/4;if(n.length+22>i)throw"key is too short for SigAlg: keylen="+r+","+t;for(var s="0001",o="00"+n,a="",d=i-4-o.length,c=0;c<d;c+=2)a+="ff";return s+a+o},this.hashString=function(e,t){return new KJUR.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new KJUR.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 RSAKey||e instanceof KJUR.crypto.DSA||e instanceof KJUR.crypto.ECDSA}},KJUR.crypto.Util.md5=function(e){return new KJUR.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},KJUR.crypto.Util.ripemd160=function(e){return new KJUR.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},KJUR.crypto.Util.SECURERANDOMGEN=new SecureRandom,KJUR.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(t),BAtohex(t)},KJUR.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(e),16)},KJUR.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,r=new Array((e-t)/8+1);return KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(r),r[0]=(255<<t&255^255)&r[0],BAtohex(r)},KJUR.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(e),16)},KJUR.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var r=KJUR.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(r))return r}},KJUR.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var r=e.compareTo(t);if(1==r)throw"biMin is greater than biMax";if(0==r)return e;var n=t.subtract(e);return KJUR.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},KJUR.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=KJUR.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=KJUR.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=KJUR.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=CryptoJS.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(CryptoJS.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=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},KJUR.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},KJUR.crypto.MessageDigest.getHashLength=function(e){var t=KJUR.crypto.MessageDigest,r=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[r])throw"not supported algorithm: "+e;return t.HASHLENGTH[r]},KJUR.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},KJUR.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=KJUR.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var r=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(r)&&"cryptojs"==t){try{var n=KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[r];this.mac=CryptoJS.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+r+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=CryptoJS.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(CryptoJS.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=rstrtohex(e)),void(this.pass=CryptoJS.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=utf8tohex(e.utf8)),void 0!==e.rstr&&(t=rstrtohex(e.rstr)),void 0!==e.b64&&(t=b64tohex(e.b64)),void 0!==e.b64u&&(t=b64utohex(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=CryptoJS.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=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},KJUR.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 r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+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 KJUR.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 r=null;try{r=void 0===t?KEYUTIL.getKey(e):KEYUTIL.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===r.isPrivate)this.prvKey=r,this.state="SIGN";else{if(!0!==r.isPublic)throw"init failed.:"+r;this.pubKey=r,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!==KJUR.crypto.ECDSA&&(this.prvKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof RSAKey&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof RSAKey&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof KJUR.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof KJUR.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!==KJUR.crypto.ECDSA&&(this.pubKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof RSAKey&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof RSAKey&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==KJUR.crypto.ECDSA&&this.pubKey instanceof KJUR.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==KJUR.crypto.DSA&&this.pubKey instanceof KJUR.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=KJUR.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=KEYUTIL.getKey(e.prvkeypem);this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},KJUR.crypto.Cipher=function(e){},KJUR.crypto.Cipher.encrypt=function(e,t,r){if(t instanceof RSAKey&&t.isPublic){var n=KJUR.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.encrypt(e);if("RSAOAEP"===n)return t.encryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.encryptOAEP(e,"sha"+i[1]);throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.encrypt: unsupported key or algorithm"},KJUR.crypto.Cipher.decrypt=function(e,t,r){if(t instanceof RSAKey&&t.isPrivate){var n=KJUR.crypto.Cipher.getAlgByKeyAndName(t,r);if("RSA"===n)return t.decrypt(e);if("RSAOAEP"===n)return t.decryptOAEP(e,"sha1");var i=n.match(/^RSAOAEP(\d+)$/);if(null!==i)return t.decryptOAEP(e,"sha"+i[1]);throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+r}throw"Cipher.decrypt: unsupported key or algorithm"},KJUR.crypto.Cipher.getAlgByKeyAndName=function(e,t){if(e instanceof RSAKey){if(-1!=":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(t))return t;if(null==t)return"RSA";throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+t}throw"getAlgByKeyAndName: not supported algorithm name: "+t},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECDSA=function(e){var t=Error,r=BigInteger,n=ECPointFp,i=KJUR.crypto.ECDSA,s=KJUR.crypto.ECParameterDB,o=i.getName,a=ASN1HEX,d=a.getVbyListEx,c=a.isASN1HEX,l=new SecureRandom;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new r(e.bitLength(),l).mod(e.subtract(r.ONE)).add(r.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 r={};return r.x=e.substr(2,t),r.y=e.substr(2+t),r},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),r=this.ecparams.keycharlen,n=("0000000000"+t.toString(16)).slice(-r);return this.setPrivateKeyHex(n),{ecprvhex:n,ecpubhex:this.generatePublicKeyHex()}},this.generatePublicKeyHex=function(){var e=new r(this.prvKeyHex,16),t=this.ecparams.G.multiply(e),n=t.getX().toBigInteger(),i=t.getY().toBigInteger(),s=this.ecparams.keycharlen,o="04"+("0000000000"+n.toString(16)).slice(-s)+("0000000000"+i.toString(16)).slice(-s);return this.setPublicKeyHex(o),o},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new r(t,16),s=this.ecparams.n,o=new r(e.substring(0,this.ecparams.keycharlen),16);do{var a=this.getBigRandom(s),d=this.ecparams.G.multiply(a).getX().toBigInteger().mod(s)}while(d.compareTo(r.ZERO)<=0);var c=a.modInverse(s).multiply(o.add(n.multiply(d))).mod(s);return i.biRSSigToASN1Sig(d,c)},this.sign=function(e,t){var n=t,i=this.ecparams.n,s=r.fromByteArrayUnsigned(e);do{var o=this.getBigRandom(i),a=this.ecparams.G.multiply(o).getX().toBigInteger().mod(i)}while(a.compareTo(BigInteger.ZERO)<=0);var d=o.modInverse(i).multiply(s.add(n.multiply(a))).mod(i);return this.serializeSig(a,d)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,s){try{var o,a,d=i.parseSigHex(t);o=d.r,a=d.s;var c=n.decodeFromHex(this.ecparams.curve,s),l=new r(e.substring(0,this.ecparams.keycharlen),16);return this.verifyRaw(l,o,a,c)}catch(e){return!1}},this.verify=function(e,t,i){var s,o,a;if(Bitcoin.Util.isArray(t)){var d=this.parseSig(t);s=d.r,o=d.s}else{if("object"!=typeof t||!t.r||!t.s)throw"Invalid value for signature";s=t.r,o=t.s}if(i instanceof ECPointFp)a=i;else{if(!Bitcoin.Util.isArray(i))throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=n.decodeFrom(this.ecparams.curve,i)}var c=r.fromByteArrayUnsigned(e);return this.verifyRaw(c,s,o,a)},this.verifyRaw=function(e,t,n,i){var s=this.ecparams.n,o=this.ecparams.G;if(t.compareTo(r.ONE)<0||t.compareTo(s)>=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(s)>=0)return!1;var a=n.modInverse(s),d=e.multiply(a).mod(s),c=t.multiply(a).mod(s);return o.multiply(d).add(i.multiply(c)).getX().toBigInteger().mod(s).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},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 i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},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:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===c(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=d(e,0,["[0]",0],"06"),r=d(e,0,[1],"04");try{n=d(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=o(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===c(e))throw new t("not ASN.1 hex string");var r,n,i;try{d(e,0,[1,0],"06"),r=d(e,0,[1,1],"06"),n=d(e,0,[2,0,1],"04");try{i=d(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=o(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===c(e))throw new t("not ASN.1 hex string");var r,n;try{d(e,0,[0,0],"06"),r=d(e,0,[0,1],"06"),n=d(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=o(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===c(e))throw new t("not ASN.1 hex string");var n,i;try{n=d(e,0,[0,5,0,1],"06"),i=d(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=o(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},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))},KJUR.crypto.ECDSA.parseSigHex=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new BigInteger(t.r,16),s:new BigInteger(t.s,16)}},KJUR.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=ASN1HEX,r=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 i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var s=i[0],o=i[1];if("02"!=e.substr(s,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(o,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,s),s:n(e,o)}},KJUR.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if(r.length>=130&&r.length<=134){if(r.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"==r.substr(0,2)&&(r=r.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var i=Math.max(r.length,n.length);return(r=("000000"+r).slice(-i))+(n=("000000"+n).slice(-i))}if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.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 r+n},KJUR.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),r=e.substr(e.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new BigInteger(e,16),n=new BigInteger(t,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(r,n)},KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=KJUR.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).tohex()},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new BigInteger(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,s,o,a,d,c,l,u,h,g,p){e[n]={};var m=r(s),f=r(o),S=r(a),y=r(d),b=r(c),E=new ECCurveFp(m,f,S),v=E.decodePointHex("04"+l+u);e[n].name=n,e[n].keylen=i,e[n].keycharlen=2*Math.ceil(i/8),e[n].curve=E,e[n].G=v,e[n].n=y,e[n].h=b,e[n].oid=g,e[n].info=p;for(var _=0;_<h.length;_++)t[h[_]]=n}},KJUR.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),KJUR.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),KJUR.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),KJUR.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),KJUR.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),KJUR.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),KJUR.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]),void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.DSA=function(){var e=ASN1HEX;e.getVbyList;var t=e.getVbyListEx,r=e.isASN1HEX,n=BigInteger;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,r,n,i){this.isPrivate=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=i},this.setPrivateHex=function(e,t,r,n,i){var s,o,a,d,c;s=new BigInteger(e,16),o=new BigInteger(t,16),a=new BigInteger(r,16),d="string"==typeof n&&n.length>1?new BigInteger(n,16):null,c=new BigInteger(i,16),this.setPrivate(s,o,a,d,c)},this.setPublic=function(e,t,r,n){this.isPublic=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=null},this.setPublicHex=function(e,t,r,n){var i,s,o,a;i=new BigInteger(e,16),s=new BigInteger(t,16),o=new BigInteger(r,16),a=new BigInteger(n,16),this.setPublic(i,s,o,a)},this.signWithMessageHash=function(e){var t=this.p,r=this.q,n=this.g;this.y;var i=this.x,s=KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE),r.subtract(BigInteger.ONE)),o=new BigInteger(e.substr(0,r.bitLength()/4),16),a=n.modPow(s,t).mod(r),d=s.modInverse(r).multiply(o.add(i.multiply(a))).mod(r);return KJUR.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:a}},{int:{bigint:d}}]})},this.verifyWithMessageHash=function(e,t){var r=this.p,n=this.q,i=this.g,s=this.y,o=this.parseASN1Signature(t),a=o[0],d=o[1],c=new BigInteger(e.substr(0,n.bitLength()/4),16);if(BigInteger.ZERO.compareTo(a)>0||a.compareTo(n)>0)throw"invalid DSA signature";if(BigInteger.ZERO.compareTo(d)>=0||d.compareTo(n)>0)throw"invalid DSA signature";var l=d.modInverse(n),u=c.multiply(l).mod(n),h=a.multiply(l).mod(n);return 0==i.modPow(u,r).multiply(s.modPow(h,r)).mod(r).mod(n).compareTo(a)},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,i,s,o,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),i=t(e,0,[2],"02"),s=t(e,0,[3],"02"),o=t(e,0,[4],"02"),a=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,i,s,o,a)},this.readPKCS8PrvKeyHex=function(e){var n,i,s,o;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),i=t(e,0,[1,1,1],"02"),s=t(e,0,[1,1,2],"02"),o=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,i,s,null,o)},this.readPKCS8PubKeyHex=function(e){var n,i,s,o;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),i=t(e,0,[0,1,1],"02"),s=t(e,0,[0,1,2],"02"),o=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,i,s,o)},this.readCertPubKeyHex=function(e,n){var i,s,o,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{i=t(e,0,[0,5,0,1,0],"02"),s=t(e,0,[0,5,0,1,1],"02"),o=t(e,0,[0,5,0,1,2],"02"),a=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(i,s,o,a)}};var KEYUTIL=function(){var e=function(e,r,n){return t(CryptoJS.AES,e,r,n)},t=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),s=CryptoJS.enc.Hex.parse(r),o=CryptoJS.enc.Hex.parse(n),a={};a.key=s,a.iv=o,a.ciphertext=i;var d=e.decrypt(a,s,{iv:o});return CryptoJS.enc.Hex.stringify(d)},r=function(e,t,r){return n(CryptoJS.AES,e,t,r)},n=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),s=CryptoJS.enc.Hex.parse(r),o=CryptoJS.enc.Hex.parse(n),a=e.encrypt(i,s,{iv:o}),d=CryptoJS.enc.Hex.parse(a.toString());return CryptoJS.enc.Base64.stringify(d)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(CryptoJS.TripleDES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(CryptoJS.DES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.DES,e,t,r)},keylen:8,ivlen:8}},s=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,s=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),s=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),s=1);var o=e.indexOf("-----END");if(-1!=i&&-1!=o){var a=e.substring(i+2*s,o-s);a=a.replace(/\s+/g,""),t.data=a}return t},o=function(e,t,r){for(var n=r.substring(0,16),s=CryptoJS.enc.Hex.parse(n),o=CryptoJS.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,d="",c=null;;){var l=CryptoJS.algo.MD5.create();if(null!=c&&l.update(c),l.update(o),l.update(s),c=l.finalize(),(d+=CryptoJS.enc.Hex.stringify(c)).length>=2*a)break}var u={};return u.keyhex=d.substr(0,2*i[e].keylen),u.ivhex=d.substr(2*i[e].keylen,2*i[e].ivlen),u},a=function(e,t,r,n){var s=CryptoJS.enc.Base64.parse(e),o=CryptoJS.enc.Hex.stringify(s);return(0,i[t].proc)(o,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return s(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return o(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=s(e),n=r.cipher,i=r.ivsalt,d=r.data,c=o(n,t,i).keyhex;return a(d,n,c,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,s){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===s||null==s){var d=function(e){var t=CryptoJS.lib.WordArray.random(e);return CryptoJS.enc.Hex.stringify(t)}(i[n].ivlen);s=d.toUpperCase()}var c=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,o(n,r,s).keyhex,s);a="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+s+"\r\n",a+="\r\n",a+=c.replace(/(.{64})/g,"$1\r\n"),a+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={},s=r(e,0);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+s.length);i.ciphertext=n(e,s[1]);var o=r(e,s[0]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+o.length);if("2a864886f70d01050d"!=n(e,o[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,o[1]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var d=r(e,a[1]);if(2!=d.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+d.length);if("2a864886f70d0307"!=n(e,d[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,d[1]);var c=r(e,a[0]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+c.length);if("2a864886f70d01050c"!=n(e,c[0]))throw new Error("this only supports pkcs5PBKDF2");var l=r(e,c[1]);if(l.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+l.length);i.pbkdf2Salt=n(e,l[0]);var u=n(e,l[1]);try{i.pbkdf2Iter=parseInt(u,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+u)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=CryptoJS.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=CryptoJS.PBKDF2(t,r,{keySize:6,iterations:n});return CryptoJS.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=pemtohex(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=KEYUTIL.getPBKDF2KeyHexFromParam(n,t),s={};s.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var o=CryptoJS.enc.Hex.parse(i),a=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV),d=CryptoJS.TripleDES.decrypt(s,o,{iv:a});return CryptoJS.enc.Hex.stringify(d)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var s=r(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 o=r(e,s[1]);if(2!=o.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(o[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,o[0]),"06"==e.substr(o[1],2)&&(i.algparam=n(e,o[1])),"04"!=e.substr(s[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,s[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=pemtohex(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new RSAKey;else if("2a8648ce380401"==r.algoid)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new KJUR.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=ASN1HEX.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new RSAKey;else if("2a8648ce380401"===r)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new KJUR.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var s=r(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(i.n=n(e,s[0]),"02"!=e.substr(s[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,s[1]),i},parsePublicPKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null},s=r(e,0);if(2!=s.length)throw new Error("outer DERSequence shall have 2 elements: "+s.length);var o=s[0];if("30"!=e.substr(o,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,o);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(s[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,s[1]).substr(2),i}}}();function _zeroPaddingOfSignature(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e}function pss_mgf1_str(e,t,r){for(var n="",i=0;n.length<t;)n+=hextorstr(r(rstrtohex(e+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(e){for(var t in KJUR.crypto.Util.DIGESTINFOHEAD){var r=KJUR.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function X509(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;t.dump;var i,s=t.parse,o=t.getTLV,a=t.getVbyList,d=t.getVbyListEx,c=t.getTLVbyList,l=t.getTLVbyListEx,u=t.getIdxbyList,h=t.getIdxbyListEx,g=t.getVidx,p=t.getInt,m=t.oidname,f=t.hextooidstr,S=pemtohex,y=Error;try{i=KJUR.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=c(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=c(e,0,[0]),r=p(t,0);if(r<0||2<r)throw new Error("malformed version field");return this.version=r+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return d(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 i)if(e===i[t])return t;return m(d(e,0,[0],"06"))},this.getIssuer=function(e,t){return this.getX500Name(this.getIssuerHex(),e,t)},this.getIssuerHex=function(){return c(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 c(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=a(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getNotAfter=function(){var e=a(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 c(this.hex,0,[0,6+this.foffset],"30")},this.getSPKIValue=function(){var e=this.getSPKI();return null==e?null:a(e,0,[1],"03",!0)},this.getPublicKeyIdx=function(){return u(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return u(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return KEYUTIL.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=c(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return a(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),r=this.getSignatureValueHex(),n=c(this.hex,0,[0],"30"),i=new KJUR.crypto.Signature({alg:t});return i.init(e),i.updateHex(n),i.verify(r)},this.parseExt=function(e){var i,s,o;if(void 0===e){if(o=this.hex,3!==this.version)return-1;i=u(o,0,[0,7,0],"30"),s=r(o,i)}else{o=pemtohex(e);var d=u(o,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=n(o,d))return void(this.aExtInfo=new Array);i=u(o,0,[0,3,0,1,0],"30"),s=r(o,i),this.hex=o}this.aExtInfo=new Array;for(var c=0;c<s.length;c++){var l={critical:!1},h=0;3===r(o,s[c]).length&&(l.critical=!0,h=1),l.oid=t.hextooidstr(a(o,s[c],[0],"06"));var p=u(o,s[c],[1+h]);l.vidx=g(o,p),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,r=e;if(e.match(/^[0-9.]+$/)||(r=KJUR.asn1.x509.OID.name2oid(e)),""!==r)for(var n=0;n<t.length;n++)if(t[n].oid===r)return t[n]},this.getCriticalExtV=function(e,t,r){if(null!=t)return[t,r];var n=this.getExtInfo(e);return null==n?[null,null]:[o(this.hex,n.vidx),n.critical]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("basicConstraints");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"basicConstraints"};if(t&&(i.critical=!0),"3000"===e)return i;if("30030101ff"===e)return i.cA=!0,i;if("30060101ff02"===e.substr(0,12)){var s=n(e,10),a=parseInt(s,16);return i.cA=!0,i.pathLen=a,i}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 i={extname:"nameConstraints"};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){for(var d=[],c=r(e,s[a]),l=0;l<c.length;l++){var u=o(e,c[l]),h=this.getGeneralSubtree(u);d.push(h)}var g=e.substr(s[a],2);"a0"==g?i.permit=d:"a1"==g&&(i.exclude=d)}return i}},this.getGeneralSubtree=function(e){var t=r(e,0),i=t.length;if(i<1||2<i)throw new Error("wrong num elements");for(var s=this.getGeneralName(o(e,t[0])),a=1;a<i;a++){var d=e.substr(t[a],2),c=n(e,t[a]),l=parseInt(c,16);"80"==d&&(s.min=l),"81"==d&&(s.max=l)}return s},this.getExtKeyUsage=function(e,t){var r=this.getCriticalExtV("keyUsage",e,t);if(e=r[0],t=r[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=o(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var r="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(r=r.slice(-8)),10==e.length&&(r=r.slice(-16)),""==(r=r.replace(/0+$/,""))&&(r="0"),r},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),r=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&r.push(X509.KEYUSAGE_NAME[n]);return r.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectKeyIdentifier");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"subjectKeyIdentifier"};t&&(i.critical=!0);var s=n(e,0);return i.kid={hex:s},i},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("authorityKeyIdentifier");if(void 0===i)return;e=o(this.hex,i.vidx),t=i.critical}var s={extname:"authorityKeyIdentifier"};t&&(s.critical=!0);for(var a=r(e,0),d=0;d<a.length;d++){var c=e.substr(a[d],2);if("80"===c&&(s.kid={hex:n(e,a[d])}),"a1"===c){var l=o(e,a[d]),u=this.getGeneralNames(l);s.issuer=u[0].dn}"82"===c&&(s.sn={hex:n(e,a[d])})}return s},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("extKeyUsage");if(void 0===i)return;e=o(this.hex,i.vidx),t=i.critical}var s={extname:"extKeyUsage",array:[]};t&&(s.critical=!0);for(var a=r(e,0),d=0;d<a.length;d++)s.array.push(m(n(e,a[d])));return s},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,i=o(this.hex,e.vidx);if(""===i)return t;for(var s=r(i,0),a=0;a<s.length;a++)t.push(m(n(i,s[a])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.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 r=this.getExtInfo("issuerAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=r(e,0),n=[],i=0;i<t.length;i++){var s=this.getGeneralName(o(e,t[i]));void 0!==s&&n.push(s)}return n},this.getGeneralName=function(e){var t=e.substr(0,2),r=n(e,0),i=hextorstr(r);return"81"==t?{rfc822:i}:"82"==t?{dns:i}:"86"==t?{uri:i}:"87"==t?{ip:hextoip(r)}:"a4"==t?{dn:this.getX500Name(r)}:"a0"==t?{other:this.getOtherName(e)}:void 0},this.getExtSubjectAltName2=function(){var e,t,i,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var a=new Array,d=o(this.hex,s.vidx),c=r(d,0),l=0;l<c.length;l++)i=d.substr(c[l],2),e=n(d,c[l]),"81"===i&&(t=hextoutf8(e),a.push(["MAIL",t])),"82"===i&&(t=hextoutf8(e),a.push(["DNS",t])),"84"===i&&(t=X509.hex2dn(e,0),a.push(["DN",t])),"86"===i&&(t=hextoutf8(e),a.push(["URI",t])),"87"===i&&(t=hextoip(e),a.push(["IP",t]));return a},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("cRLDistributionPoints");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"cRLDistributionPoints",array:[]};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){var d=o(e,s[a]);i.array.push(this.getDistributionPoint(d))}return i},this.getDistributionPoint=function(e){for(var t={},n=r(e,0),i=0;i<n.length;i++){var s=e.substr(n[i],2),a=o(e,n[i]);"a0"==s&&(t.dpname=this.getDistributionPointName(a))}return t},this.getDistributionPointName=function(e){for(var t={},n=r(e,0),i=0;i<n.length;i++){var s=e.substr(n[i],2),a=o(e,n[i]);"a0"==s&&(t.full=this.getGeneralNames(a))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtCRLDistributionPoints();if(null==e)return e;for(var t=e.array,r=[],n=0;n<t.length;n++)try{null!=t[n].dpname.full[0].uri&&r.push(t[n].dpname.full[0].uri)}catch(e){}return r},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},n=r(this.hex,e.vidx),i=0;i<n.length;i++){var s=a(this.hex,n[i],[0],"06"),o=a(this.hex,n[i],[1],"86");"2b06010505073001"===s&&t.ocsp.push(hextoutf8(o)),"2b06010505073002"===s&&t.caissuer.push(hextoutf8(o))}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=o(this.hex,n.vidx),t=n.critical}var i={extname:"authorityInfoAccess",array:[]};t&&(i.critical=!0);for(var s=r(e,0),c=0;c<s.length;c++){var l=d(e,s[c],[0],"06"),u=hextoutf8(a(e,s[c],[1],"86"));if("2b06010505073001"==l)i.array.push({ocsp:u});else{if("2b06010505073002"!=l)throw new Error("unknown method: "+l);i.array.push({caissuer:u})}}return i},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("certificatePolicies");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"certificatePolicies",array:[]};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){var d=o(e,s[a]),c=this.getPolicyInformation(d);i.array.push(c)}return i},this.getPolicyInformation=function(e){var t={},n=a(e,0,[0],"06");t.policyoid=m(n);var i=h(e,0,[1],"30");if(-1!=i){t.array=[];for(var s=r(e,i),d=0;d<s.length;d++){var c=o(e,s[d]),l=this.getPolicyQualifierInfo(c);t.array.push(l)}}return t},this.getOtherName=function(e){var t={},n=r(e,0),i=a(e,n[0],[],"06"),o=a(e,n[1],[]);return t.oid=m(i),t.value=s(o),t},this.getPolicyQualifierInfo=function(e){var t={},r=a(e,0,[0],"06");if("2b06010505070201"===r){var n=d(e,0,[1],"16");t.cps=hextorstr(n)}else if("2b06010505070202"===r){var i=c(e,0,[1],"30");t.unotice=this.getUserNotice(i)}return t},this.getUserNotice=function(e){var r=null;try{return r=t.parse(e),this._asn1ToUnotice(r)}catch(e){return}},this._asn1ToUnotice=function(e){try{for(var t={},r=aryval(e,"seq"),n=0;n<r.length;n++){var i=this._asn1ToNoticeRef(r[n]);null!=i&&(t.noticeref=i);var s=this.asn1ToDisplayText(r[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={},r=aryval(e,"seq"),n=0;n<r.length;n++){var i=this._asn1ToNoticeNum(r[n]);null!=i&&(t.noticenum=i);var s=this.asn1ToDisplayText(r[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=aryval(e,"seq"),r=[],n=0;n<t.length;n++){var i=t[n];r.push(parseInt(aryval(i,"int.hex"),16))}return r}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=hextorstr(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 r=this.getCriticalExtV("policyMappings",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"policyMappings"};t&&(n.critical=!0);try{for(var i=s(e).seq,o=[],a=0;a<i.length;a++){var d=i[a].seq;o.push([d[0].oid,d[1].oid])}n.array=o}catch(e){throw new y("malformed policyMappings")}return n}},this.getExtPolicyConstraints=function(e,t){var r=this.getCriticalExtV("policyConstraints",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"policyConstraints"};t&&(n.critical=!0);var i=s(e);try{for(var o=i.seq,a=0;a<o.length;a++){var d=o[a].tag;0==d.explicit&&("80"==d.tag&&(n.reqexp=parseInt(d.hex,16)),"81"==d.tag&&(n.inhibit=parseInt(d.hex,16)))}}catch(e){return new y("malformed policyConstraints value")}return n}},this.getExtInhibitAnyPolicy=function(e,t){var r=this.getCriticalExtV("inhibitAnyPolicy",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"inhibitAnyPolicy"};t&&(n.critical=!0);var i=p(e,0);return-1==i?new y("wrong value"):(n.skip=i,n)}},this.getExtCRLNumber=function(e,t){var r={extname:"cRLNumber"};if(t&&(r.critical=!0),"02"==e.substr(0,2))return r.num={hex:n(e,0)},r;throw new y("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var r={extname:"cRLReason"};if(t&&(r.critical=!0),"0a"==e.substr(0,2))return r.code=parseInt(n(e,0),16),r;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var r={extname:"ocspNonce"};t&&(r.critical=!0);var i=n(e,0);return r.hex=i,r},this.getExtOcspNoCheck=function(e,t){var r={extname:"ocspNoCheck"};return t&&(r.critical=!0),r},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("adobeTimeStamp");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"adobeTimeStamp"};t&&(i.critical=!0);var s=r(e,0);if(s.length>1){var a=o(e,s[1]),d=this.getGeneralName(a);null!=d.uri&&(i.uri=d.uri)}if(s.length>2){var c=o(e,s[2]);"0101ff"==c&&(i.reqauth=!0),"010100"==c&&(i.reqauth=!1)}return i},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectDirectoryAttributes");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var i=s(e),a=[],d=0;d<i.seq.length;d++){var c=i.seq[d],l=aryval(c,"seq.0.oid"),u=aryval(c,"seq.1.set");if(null==l||null==u)throw"error";a.push({attr:l,array:u})}return n.array=a,n}catch(e){throw new Error("malformed subjectDirectoryAttributes extension value")}};var b=function(e){var t={};try{var r=e.seq[0].oid,n=KJUR.asn1.x509.OID.name2oid(r);t.type=KJUR.asn1.x509.OID.oid2atype(n);var i=e.seq[1];if(null!=i.utf8str)t.ds="utf8",t.value=i.utf8str.str;else if(null!=i.numstr)t.ds="num",t.value=i.numstr.str;else if(null!=i.telstr)t.ds="tel",t.value=i.telstr.str;else if(null!=i.prnstr)t.ds="prn",t.value=i.prnstr.str;else if(null!=i.ia5str)t.ds="ia5",t.value=i.ia5str.str;else if(null!=i.visstr)t.ds="vis",t.value=i.visstr.str;else{if(null==i.bmpstr)throw"error";t.ds="bmp",t.value=i.bmpstr.str}return t}catch(e){throw new Erorr("improper ASN.1 parsed AttrTypeAndValue")}},E=function(e){try{return e.set.map((function(e){return b(e)}))}catch(e){throw new Error("improper ASN.1 parsed RDN: "+e)}};this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n<e.length;n++)for(var i=e[n],s=0;s<i.length;s++)r.push(i[s]);for(n=0;n<r.length;n++){var o=r[n],a=o.ds,d=o.value,c=o.type;if("prn"!=a&&"utf8"!=a&&"ia5"!=a)return"mixed";if("ia5"==a){if("CN"!=c)return"mixed";if(KJUR.lang.String.isMail(d))continue;return"mixed"}if("C"==c){if("prn"==a)continue;return"mixed"}if(null==t)t=a;else if(t!==a)return"mixed"}return null==t?"prn":t},this.getAttrTypeAndValue=function(e){var t=s(e);return b(t)},this.getRDN=function(e){var t=s(e);return E(t)},this.getX500NameArray=function(e){return function(e){try{return e.seq.map((function(e){return E(e)}))}catch(e){throw new Error("improper ASN.1 parsed X500Name: "+e)}}(s(e))},this.getX500Name=function(e,t,r){var n=this.getX500NameArray(e),i={str:this.dnarraytostr(n)};return i.array=n,1==r&&(i.hex=e),1==t&&(i.canon=this.c14nRDNArray(n)),i},this.readCertPEM=function(e){this.readCertHex(S(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{u(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=hextopem(this.getPublicKeyHex(),"PUBLIC KEY"),null!=this.aExtInfo&&this.aExtInfo.length>0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=c(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=h(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=r(e,0),i=0;i<n.length;i++){var s=o(e,n[i]),a=this.getExtParam(s);null!=a&&t.push(a)}return t},this.getExtParam=function(e){var t=r(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var n=f(a(e,0,[0],"06")),i=!1;3==t&&"0101ff"==c(e,0,[1])&&(i=!0);var o=c(e,0,[t-1,0]),d=void 0;if("2.5.29.14"==n?d=this.getExtSubjectKeyIdentifier(o,i):"2.5.29.15"==n?d=this.getExtKeyUsage(o,i):"2.5.29.17"==n?d=this.getExtSubjectAltName(o,i):"2.5.29.18"==n?d=this.getExtIssuerAltName(o,i):"2.5.29.19"==n?d=this.getExtBasicConstraints(o,i):"2.5.29.30"==n?d=this.getExtNameConstraints(o,i):"2.5.29.31"==n?d=this.getExtCRLDistributionPoints(o,i):"2.5.29.32"==n?d=this.getExtCertificatePolicies(o,i):"2.5.29.33"==n?d=this.getExtPolicyMappings(o,i):"2.5.29.35"==n?d=this.getExtAuthorityKeyIdentifier(o,i):"2.5.29.36"==n?d=this.getExtPolicyConstraints(o,i):"2.5.29.37"==n?d=this.getExtExtKeyUsage(o,i):"2.5.29.54"==n?d=this.getExtInhibitAnyPolicy(o,i):"1.3.6.1.5.5.7.1.1"==n?d=this.getExtAuthorityInfoAccess(o,i):"2.5.29.20"==n?d=this.getExtCRLNumber(o,i):"2.5.29.21"==n?d=this.getExtCRLReason(o,i):"2.5.29.9"==n?d=this.getExtSubjectDirectoryAttributes(o,i):"1.3.6.1.5.5.7.48.1.2"==n?d=this.getExtOcspNonce(o,i):"1.3.6.1.5.5.7.48.1.5"==n?d=this.getExtOcspNoCheck(o,i):"1.2.840.113583.1.1.9.1"==n?d=this.getExtAdobeTimeStamp(o,i):null!=X509.EXT_PARSER[n]&&(d=X509.EXT_PARSER[n](n,i,o)),null!=d)return d;var l={extname:n,extn:o};try{l.extn=s(o)}catch(e){}return i&&(l.critical=!0),l},this.findExt=function(e,t){for(var r=0;r<e.length;r++)if(e[r].extname==t)return e[r];return null},this.updateExtCDPFullURI=function(e,t){var r=this.findExt(e,"cRLDistributionPoints");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)if(null!=n[i].dpname&&null!=n[i].dpname.full)for(var s=n[i].dpname.full,o=0;o<s.length;o++){var a=s[i];null!=a.uri&&(a.uri=t)}},this.updateExtAIAOCSP=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].ocsp&&(n[i].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].caissuer&&(n[i].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 r=new KJUR.asn1.x509.X500Name({str:e.str}).tohex();t=this.getX500NameArray(r)}else t=e.array;null==e.canon&&(e.canon=this.c14nRDNArray(t))},this.c14nRDNArray=function(e){for(var t=[],r=0;r<e.length;r++){for(var n=e[r],i=[],s=0;s<n.length;s++){var o=n[s],a=o.value;a=(a=(a=(a=a.replace(/^\s*/,"")).replace(/\s*$/,"")).replace(/\s+/g," ")).toLowerCase(),i.push(o.type.toLowerCase()+"="+a)}t.push(i.join("+"))}return"/"+t.join("/")},this.getInfo=function(){var e,t,r,n=function(e){for(var t="",r=" ",n="\n",i=e.array,s=0;s<i.length;s++){var o=i[s];if(null!=o.dn&&(t+=r+"dn: "+o.dn.str+n),null!=o.ip&&(t+=r+"ip: "+o.ip+n),null!=o.rfc822&&(t+=r+"rfc822: "+o.rfc822+n),null!=o.dns&&(t+=r+"dns: "+o.dns+n),null!=o.uri&&(t+=r+"uri: "+o.uri+n),null!=o.other)t+=r+"other: "+o.other.oid+"="+JSON.stringify(o.other.value).replace(/\"/g,"")+n}return t=t.replace(/\n$/,"")},i=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];if(t+=" policy oid: "+i.policyoid+"\n",void 0!==i.array)for(var s=0;s<i.array.length;s++){var o=i.array[s];void 0!==o.cps&&(t+=" cps: "+o.cps+"\n")}}return t},s=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];try{void 0!==i.dpname.full[0].uri&&(t+=" "+i.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==i.dname.full[0].dn.hex&&(t+=" "+X509.hex2dn(i.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},o=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];void 0!==i.caissuer&&(t+=" caissuer: "+i.caissuer+"\n"),void 0!==i.ocsp&&(t+=" ocsp: "+i.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="+hextoposhex(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+hextoposhex(t.e.toString(16))+"\n"),null!=(r=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var a=0;a<r.length;a++){var d=r[a],c=KJUR.asn1.x509.OID.oid2name(d.oid);""===c&&(c=d.oid);var l="";if(!0===d.critical&&(l="CRITICAL"),e+=" "+c+" "+l+":\n","basicConstraints"===c){var u=this.getExtBasicConstraints();void 0===u.cA?e+=" {}\n":(e+=" cA=true",void 0!==u.pathLen&&(e+=", pathLen="+u.pathLen),e+="\n")}else{var h;if("policyMappings"==c)e+=" "+this.getExtPolicyMappings().array.map((function(e){var t=e;return t[0]+":"+t[1]})).join(", ")+"\n";else if("policyConstraints"==c)e+=" ",null!=(h=this.getExtPolicyConstraints()).reqexp&&(e+=" reqexp="+h.reqexp),null!=h.inhibit&&(e+=" inhibit="+h.inhibit),e+="\n";else if("inhibitAnyPolicy"==c)e+=" skip="+(h=this.getExtInhibitAnyPolicy()).skip+"\n";else if("keyUsage"==c)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"==c)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"==c){var g=this.getExtAuthorityKeyIdentifier();void 0!==g.kid&&(e+=" kid="+g.kid.hex+"\n")}else{if("extKeyUsage"==c)e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n";else if("subjectAltName"==c)e+=n(this.getExtSubjectAltName())+"\n";else if("cRLDistributionPoints"==c)e+=s(this.getExtCRLDistributionPoints());else if("authorityInfoAccess"==c)e+=o(this.getExtAuthorityInfoAccess());else"certificatePolicies"==c&&(e+=i(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):KJUR.lang.String.isHex(e)&&this.readCertHex(e))}KEYUTIL.getKey=function(e,t,r){var n=(f=ASN1HEX).getChildIdx;f.getV;var i=f.getVbyList,s=KJUR.crypto,o=s.ECDSA,a=s.DSA,d=RSAKey,c=pemtohex,l=KEYUTIL;if(void 0!==d&&e instanceof d)return e;if(void 0!==o&&e instanceof o)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new o({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new o({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(A=new d).setPublic(e.n,e.e),A;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(A=new d).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),A;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(A=new d).setPrivate(e.n,e.e,e.d),A;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(A=new a).setPublic(e.p,e.q,e.g,e.y),A;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(A=new a).setPrivate(e.p,e.q,e.g,e.y,e.x),A;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(A=new d).setPublic(b64utohex(e.n),b64utohex(e.e)),A;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(A=new d).setPrivateEx(b64utohex(e.n),b64utohex(e.e),b64utohex(e.d),b64utohex(e.p),b64utohex(e.q),b64utohex(e.dp),b64utohex(e.dq),b64utohex(e.qi)),A;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(A=new d).setPrivate(b64utohex(e.n),b64utohex(e.e),b64utohex(e.d)),A;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var u=(C=new o({curve:e.crv})).ecparams.keycharlen,h="04"+("0000000000"+b64utohex(e.x)).slice(-u)+("0000000000"+b64utohex(e.y)).slice(-u);return C.setPublicKeyHex(h),C}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){u=(C=new o({curve:e.crv})).ecparams.keycharlen,h="04"+("0000000000"+b64utohex(e.x)).slice(-u)+("0000000000"+b64utohex(e.y)).slice(-u);var g=("0000000000"+b64utohex(e.d)).slice(-u);return C.setPublicKeyHex(h),C.setPrivateKeyHex(g),C}if("pkcs5prv"===r){var p,m=e,f=ASN1HEX;if(9===(p=n(m,0)).length)(A=new d).readPKCS5PrvKeyHex(m);else if(6===p.length)(A=new a).readPKCS5PrvKeyHex(m);else{if(!(p.length>2&&"04"===m.substr(p[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(A=new o).readPKCS5PrvKeyHex(m)}return A}if("pkcs8prv"===r)return A=l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return X509.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return X509.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var S=pemtohex(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(S)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var y=c(e,"RSA PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=i(w=c(e,"DSA PRIVATE KEY"),0,[1],"02"),E=i(w,0,[2],"02"),v=i(w,0,[3],"02"),_=i(w,0,[4],"02"),T=i(w,0,[5],"02");return(A=new a).setPrivate(new BigInteger(b,16),new BigInteger(E,16),new BigInteger(v,16),new BigInteger(_,16),new BigInteger(T,16)),A}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){y=c(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 R=l.getDecryptedKeyHex(e,t),$=new RSAKey;return $.readPKCS5PrvKeyHex(R),$}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var C,A=i(w=l.getDecryptedKeyHex(e,t),0,[1],"04"),N=i(w,0,[2,0],"06"),I=i(w,0,[3,0],"03").substr(2);if(void 0===KJUR.crypto.OID.oidhex2name[N])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+N);return(C=new o({curve:KJUR.crypto.OID.oidhex2name[N]})).setPublicKeyHex(I),C.setPrivateKeyHex(A),C.isPublic=!1,C}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var w;b=i(w=l.getDecryptedKeyHex(e,t),0,[1],"02"),E=i(w,0,[2],"02"),v=i(w,0,[3],"02"),_=i(w,0,[4],"02"),T=i(w,0,[5],"02");return(A=new a).setPrivate(new BigInteger(b,16),new BigInteger(E,16),new BigInteger(v,16),new BigInteger(_,16),new BigInteger(T,16)),A}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},KEYUTIL.generateKeypair=function(e,t){if("RSA"==e){var r=t;(o=new RSAKey).generate(r,"10001"),o.isPrivate=!0,o.isPublic=!0;var n=new RSAKey,i=o.n.toString(16),s=o.e.toString(16);return n.setPublic(i,s),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}if("EC"==e){var o,a,d=t,c=new KJUR.crypto.ECDSA({curve:d}).generateKeyPairHex();return(o=new KJUR.crypto.ECDSA({curve:d})).setPublicKeyHex(c.ecpubhex),o.setPrivateKeyHex(c.ecprvhex),o.isPrivate=!0,o.isPublic=!1,(n=new KJUR.crypto.ECDSA({curve:d})).setPublicKeyHex(c.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},KEYUTIL.getPEM=function(e,t,r,n,i,s){var o=KJUR,a=o.asn1,d=a.DERObjectIdentifier,c=a.DERInteger,l=a.ASN1Util.newObject,u=a.x509.SubjectPublicKeyInfo,h=o.crypto,g=h.DSA,p=h.ECDSA,m=RSAKey;function f(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 S(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!==m&&e instanceof m||void 0!==g&&e instanceof g||void 0!==p&&e instanceof p)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return hextopem(_=new u(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==m&&e instanceof m&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(_=f(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var b=new d({name:e.curveName}).tohex(),E=S(e).tohex(),v="";return v+=hextopem(b,"EC PARAMETERS"),v+=hextopem(E,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(_=y(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==m&&e instanceof m&&void 0!==r&&null!=r&&1==e.isPrivate){var _=f(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",_,r,n,s)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate){_=S(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",_,r,n,s)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){_=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",_,r,n,s)}var T=function(e,t){var r=R(e,t);return new l({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:r.pbkdf2Salt}},{int:r.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:r.encryptionSchemeIV}}]}]}]},{octstr:{hex:r.ciphertext}}]}).tohex()},R=function(e,t){var r=CryptoJS.lib.WordArray.random(8),n=CryptoJS.lib.WordArray.random(8),i=CryptoJS.PBKDF2(t,r,{keySize:6,iterations:100}),s=CryptoJS.enc.Hex.parse(e),o=CryptoJS.TripleDES.encrypt(s,i,{iv:n})+"",a={};return a.ciphertext=o,a.pbkdf2Salt=CryptoJS.enc.Hex.stringify(r),a.pbkdf2Iter=100,a.encryptionSchemeAlg="DES-EDE3-CBC",a.encryptionSchemeIV=CryptoJS.enc.Hex.stringify(n),a};if("PKCS8PRV"==t&&null!=m&&e instanceof m&&1==e.isPrivate){var $=f(e).tohex();_=l({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:$}}]}).tohex();return void 0===r||null==r?hextopem(_,"PRIVATE KEY"):hextopem(E=T(_,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){var C={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&C.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});$=new l(C).tohex(),_=l({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:$}}]}).tohex();return void 0===r||null==r?hextopem(_,"PRIVATE KEY"):hextopem(E=T(_,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){$=new c({bigint:e.x}).tohex(),_=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===r||null==r?hextopem(_,"PRIVATE KEY"):hextopem(E=T(_,r),"ENCRYPTED PRIVATE KEY")}throw new Error("unsupported object nor format")},KEYUTIL.getKeyFromCSRPEM=function(e){var t=pemtohex(e,"CERTIFICATE REQUEST");return KEYUTIL.getKeyFromCSRHex(t)},KEYUTIL.getKeyFromCSRHex=function(e){var t=KEYUTIL.parseCSRHex(e);return KEYUTIL.getKey(t.p8pubkeyhex,null,"pkcs8pub")},KEYUTIL.parseCSRHex=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getTLV,i={},s=e;if("30"!=s.substr(0,2))throw new Error("malformed CSR(code:001)");var o=r(s,0);if(o.length<1)throw new Error("malformed CSR(code:002)");if("30"!=s.substr(o[0],2))throw new Error("malformed CSR(code:003)");var a=r(s,o[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(s,a[2]),i},KEYUTIL.getKeyID=function(e){var t=KEYUTIL,r=ASN1HEX;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=pemtohex(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),s=r.getV(n,i).substring(2);return KJUR.crypto.Util.hashHex(s,"sha1")},KEYUTIL.getJWK=function(e,t,r,n,i){var s,o,a={},d=KJUR.crypto.Util.hashHex;if("string"==typeof e)s=KEYUTIL.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(o=pemtohex(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof X509?(s=e.getPublicKey(),o=e.hex):s=e}if(s instanceof RSAKey&&s.isPrivate)a.kty="RSA",a.n=hextob64u(s.n.toString(16)),a.e=hextob64u(s.e.toString(16)),a.d=hextob64u(s.d.toString(16)),a.p=hextob64u(s.p.toString(16)),a.q=hextob64u(s.q.toString(16)),a.dp=hextob64u(s.dmp1.toString(16)),a.dq=hextob64u(s.dmq1.toString(16)),a.qi=hextob64u(s.coeff.toString(16));else if(s instanceof RSAKey&&s.isPublic)a.kty="RSA",a.n=hextob64u(s.n.toString(16)),a.e=hextob64u(s.e.toString(16));else if(s instanceof KJUR.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 c=s.getPublicKeyXYHex();a.kty="EC",a.crv=l,a.x=hextob64u(c.x),a.y=hextob64u(c.y),a.d=hextob64u(s.prvKeyHex)}else if(s instanceof KJUR.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);c=s.getPublicKeyXYHex();a.kty="EC",a.crv=l,a.x=hextob64u(c.x),a.y=hextob64u(c.y)}if(null==a.kty)throw new Error("unsupported keyinfo");return s.isPrivate||1==t||(a.kid=KJUR.jws.JWS.getJWKthumbprint(a)),null!=o&&1!=r&&(a.x5c=[hex2b64(o)]),null!=o&&1!=n&&(a.x5t=b64tob64u(hex2b64(d(o,"sha1")))),null!=o&&1!=i&&(a["x5t#S256"]=b64tob64u(hex2b64(d(o,"sha256")))),a},KEYUTIL.getJWKFromKey=function(e){return KEYUTIL.getJWK(e,!0,!0,!0,!0)},RSAKey.getPosArrayOfChildrenFromHex=function(e){return ASN1HEX.getChildIdx(e,0)},RSAKey.getHexValueArrayOfChildrenFromHex=function(e){var t,r=ASN1HEX.getV,n=r(e,(t=RSAKey.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),s=r(e,t[2]),o=r(e,t[3]),a=r(e,t[4]),d=r(e,t[5]),c=r(e,t[6]),l=r(e,t[7]),u=r(e,t[8]);return(t=new Array).push(n,i,s,o,a,d,c,l,u),t},RSAKey.prototype.readPrivateKeyFromPEMString=function(e){var t=pemtohex(e),r=RSAKey.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},RSAKey.prototype.readPKCS5PrvKeyHex=function(e){var t=RSAKey.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},RSAKey.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,s,o,a,d,c=ASN1HEX,l=c.getVbyListEx;if(!1===c.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=l(e,0,[2,0,1],"02"),r=l(e,0,[2,0,2],"02"),n=l(e,0,[2,0,3],"02"),i=l(e,0,[2,0,4],"02"),s=l(e,0,[2,0,5],"02"),o=l(e,0,[2,0,6],"02"),a=l(e,0,[2,0,7],"02"),d=l(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,s,o,a,d)},RSAKey.prototype.readPKCS5PubKeyHex=function(e){var t=ASN1HEX,r=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 i=r(e,n[0]),s=r(e,n[1]);this.setPublic(i,s)},RSAKey.prototype.readPKCS8PubKeyHex=function(e){var t=ASN1HEX;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 r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},RSAKey.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new X509).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},RSAKey.prototype.sign=function(e,t){var r=function(e){return KJUR.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},RSAKey.prototype.signWithMessageHash=function(e,t){var r=parseBigInt(KJUR.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return _zeroPaddingOfSignature(this.doPrivate(r).toString(16),this.n.bitLength())},RSAKey.prototype.signPSS=function(e,t,r){var n=function(e){return KJUR.crypto.Util.hashHex(e,t)}(rstrtohex(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},RSAKey.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=hextorstr(e),s=i.length,o=this.n.bitLength()-1,a=Math.ceil(o/8),d=function(e){return KJUR.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=s;else if(-2===r)r=a-s-2;else if(r<-2)throw new Error("invalid salt length");if(a<s+r+2)throw new Error("data too long");var c="";r>0&&(c=new Array(r),(new SecureRandom).nextBytes(c),c=String.fromCharCode.apply(String,c));var l=hextorstr(d(rstrtohex("\0\0\0\0\0\0\0\0"+i+c))),u=[];for(n=0;n<a-r-s-2;n+=1)u[n]=0;var h=String.fromCharCode.apply(String,u)+""+c,g=pss_mgf1_str(l,h.length,d),p=[];for(n=0;n<h.length;n+=1)p[n]=h.charCodeAt(n)^g.charCodeAt(n);var m=65280>>8*a-o&255;for(p[0]&=~m,n=0;n<s;n++)p.push(l.charCodeAt(n));return p.push(188),_zeroPaddingOfSignature(this.doPrivate(new BigInteger(p)).toString(16),this.n.bitLength())},RSAKey.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var r=parseBigInt(t,16),n=this.n.bitLength();if(r.bitLength()>n)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var s=_rsasign_getAlgNameAndHashFromHexDisgestInfo(i.replace(/^1f+00/,""));if(0==s.length)return!1;var o=s[0],a=s[1],d=function(e){return KJUR.crypto.Util.hashString(e,o)}(e);return a==d},RSAKey.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=parseBigInt(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=_rsasign_getAlgNameAndHashFromHexDisgestInfo(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},RSAKey.prototype.verifyPSS=function(e,t,r,n){var i,s=(i=rstrtohex(e),KJUR.crypto.Util.hashHex(i,r));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(s,t,r,n)},RSAKey.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,s=new BigInteger(t,16),o=function(e){return KJUR.crypto.Util.hashHex(e,r)},a=hextorstr(e),d=a.length,c=this.n.bitLength()-1,l=Math.ceil(c/8);if(-1===n||void 0===n)n=d;else if(-2===n)n=l-d-2;else if(n<-2)throw new Error("invalid salt length");if(l<d+n+2)throw new Error("data too long");var u=this.doPublic(s).toByteArray();for(i=0;i<u.length;i+=1)u[i]&=255;for(;u.length<l;)u.unshift(0);if(188!==u[l-1])throw new Error("encoded message does not end in 0xbc");var h=(u=String.fromCharCode.apply(String,u)).substr(0,l-d-1),g=u.substr(h.length,d),p=65280>>8*l-c&255;if(0!=(h.charCodeAt(0)&p))throw new Error("bits beyond keysize not zero");var m=pss_mgf1_str(g,h.length,o),f=[];for(i=0;i<h.length;i+=1)f[i]=h.charCodeAt(i)^m.charCodeAt(i);f[0]&=~p;var S=l-d-n-2;for(i=0;i<S;i+=1)if(0!==f[i])throw new Error("leftmost octets not zero");if(1!==f[S])throw new Error("0x01 marker not found");return g===hextorstr(o(rstrtohex("\0\0\0\0\0\0\0\0"+a+String.fromCharCode.apply(String,f.slice(-n)))))},RSAKey.SALT_LEN_HLEN=-1,RSAKey.SALT_LEN_MAX=-2,RSAKey.SALT_LEN_RECOVER=-2,X509.EXT_PARSER={},X509.registExtParser=function(e,t){X509.EXT_PARSER[e]=t},X509.hex2dn=function(e,t){void 0===t&&(t=0);var r=new X509;return ASN1HEX.getTLV(e,t),r.getX500Name(e).str},X509.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var r=new Array,n=ASN1HEX.getChildIdx(e,t),i=0;i<n.length;i++)r.push(X509.hex2attrTypeValue(e,n[i]));return r=r.map((function(e){return e.replace("+","\\+")})),r.join("+")},X509.hex2attrTypeValue=function(e,t){var r=ASN1HEX,n=r.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var i=r.getChildIdx(e,t);2!==i.length||e.substr(i[0],2);var s=n(e,i[0]),o=KJUR.asn1.ASN1Util.oidHexToInt(s);return KJUR.asn1.x509.OID.oid2atype(o)+"="+hextorstr(n(e,i[1]))},X509.getPublicKeyFromCertHex=function(e){var t=new X509;return t.readCertHex(e),t.getPublicKey()},X509.getPublicKeyFromCertPEM=function(e){var t=new X509;return t.readCertPEM(e),t.getPublicKey()},X509.getPublicKeyInfoPropOfCertPEM=function(e){var t,r,n=ASN1HEX.getVbyList,i={};return i.algparam=null,(t=new X509).readCertPEM(e),r=t.getPublicKeyHex(),i.keyhex=n(r,0,[1],"03").substr(2),i.algoid=n(r,0,[0,0],"06"),"2a8648ce3d0201"===i.algoid&&(i.algparam=n(r,0,[0,1],"06")),i},X509.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.jws&&KJUR.jws||(KJUR.jws={}),KJUR.jws.JWS=function(){var e=KJUR.jws.JWS.isSafeJSONString;this.parseJWS=function(t,r){if(void 0===this.parsedJWS||!r&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var i=n[1],s=n[2],o=n[3],a=i+"."+s;if(this.parsedJWS={},this.parsedJWS.headB64U=i,this.parsedJWS.payloadB64U=s,this.parsedJWS.sigvalB64U=o,this.parsedJWS.si=a,!r){var d=b64utohex(o),c=parseBigInt(d,16);this.parsedJWS.sigvalH=d,this.parsedJWS.sigvalBI=c}var l=b64utoutf8(i),u=b64utoutf8(s);if(this.parsedJWS.headS=l,this.parsedJWS.payloadS=u,!e(l,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+l}}},KJUR.jws.JWS.sign=function(e,t,r,n,i){var s=KJUR,o=s.jws.JWS,a=o.readSafeJSONString,d=o.isSafeJSONString,c=s.crypto;c.ECDSA;var l,u,h,g=c.Mac,p=c.Signature,m=JSON;if("string"!=typeof t&&"object"!=typeof t)throw"spHeader must be JSON string or object: "+t;if("object"==typeof t&&(u=t,l=m.stringify(u)),"string"==typeof t){if(!d(l=t))throw"JWS Head is not safe JSON string: "+l;u=a(l)}if(h=r,"object"==typeof r&&(h=m.stringify(r)),""!=e&&null!=e||void 0===u.alg||(e=u.alg),""!=e&&null!=e&&void 0===u.alg&&(u.alg=e,l=m.stringify(u)),e!==u.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+u.alg;var f=null;if(void 0===o.jwsalg2sigalg[e])throw"unsupported alg name: "+e;f=o.jwsalg2sigalg[e];var S=utf8tob64u(l)+"."+utf8tob64u(h),y="";if("Hmac"==f.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var b=new g({alg:f,prov:"cryptojs",pass:n});b.updateString(S),y=b.doFinal()}else if(-1!=f.indexOf("withECDSA")){(v=new p({alg:f})).init(n,i),v.updateString(S);var E=v.sign();y=KJUR.crypto.ECDSA.asn1SigToConcatSig(E)}else{var v;if("none"!=f)(v=new p({alg:f})).init(n,i),v.updateString(S),y=v.sign()}return S+"."+hextob64u(y)},KJUR.jws.JWS.verify=function(e,t,r){var n,i=KJUR,s=i.jws.JWS,o=s.readSafeJSONString,a=i.crypto,d=a.ECDSA,c=a.Mac,l=a.Signature;if(void 0!==typeof RSAKey&&(n=RSAKey),!isBase64URLDot(e))return!1;var u=e.split(".");if(3!==u.length)return!1;var h=u[0]+"."+u[1],g=b64utohex(u[2]),p=o(b64utoutf8(u[0])),m=null,f=null;if(void 0===p.alg)throw"algorithm not specified in header";if((f=(m=p.alg).substr(0,2),null!=r&&"[object Array]"===Object.prototype.toString.call(r)&&r.length>0)&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=KEYUTIL.getKey(t)),!("RS"!=f&&"PS"!=f||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==f&&!(t instanceof d))throw"key shall be a ECDSA obj for ES* algs";var S=null;if(void 0===s.jwsalg2sigalg[p.alg])throw"unsupported alg name: "+m;if("none"==(S=s.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==S.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var y=new c({alg:S,pass:t});return y.updateString(h),g==y.doFinal()}if(-1!=S.indexOf("withECDSA")){var b,E=null;try{E=d.concatSigToASN1Sig(g)}catch(e){return!1}return(b=new l({alg:S})).init(t),b.updateString(h),b.verify(E)}return(b=new l({alg:S})).init(t),b.updateString(h),b.verify(g)},KJUR.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),s={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),s.headerObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(t)),s.payloadObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(r)),s.headerPP=JSON.stringify(s.headerObj,null," "),null==s.payloadObj?s.payloadPP=b64utoutf8(r):s.payloadPP=JSON.stringify(s.payloadObj,null," "),void 0!==n&&(s.sigHex=b64utohex(n)),s},KJUR.jws.JWS.verifyJWT=function(e,t,r){var n=KJUR.jws,i=n.JWS,s=i.readSafeJSONString,o=i.inArray,a=i.includedArray;if(!isBase64URLDot(e))return!1;var d=e.split(".");if(3!=d.length)return!1;var c=d[0],l=d[1];b64utohex(d[2]);var u=s(b64utoutf8(c)),h=s(b64utoutf8(l));if(void 0===u.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!o(u.alg,r.alg))return!1;if(void 0!==h.iss&&"object"==typeof r.iss&&!o(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"==typeof r.sub&&!o(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"==typeof r.aud)if("string"==typeof h.aud){if(!o(h.aud,r.aud))return!1}else if("object"==typeof h.aud&&!a(h.aud,r.aud))return!1;var g=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(g=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriod<g)&&(!(void 0!==h.nbf&&"number"==typeof h.nbf&&g<h.nbf-r.gracePeriod)&&(!(void 0!==h.iat&&"number"==typeof h.iat&&g<h.iat-r.gracePeriod)&&((void 0===h.jti||void 0===r.jti||h.jti===r.jti)&&!!i.verify(e,t,r.alg))))},KJUR.jws.JWS.includedArray=function(e,t){var r=KJUR.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(!r(e[n],t))return!1;return!0},KJUR.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 r=0;r<t.length;r++)if(t[r]==e)return!0;return!1},KJUR.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"},KJUR.jws.JWS.isSafeJSONString=function(e,t,r){var n=null;try{return"object"!=typeof(n=jsonParse(e))||n.constructor===Array?0:(t&&(t[r]=n),1)}catch(e){return 0}},KJUR.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=typeof(t=jsonParse(e))||t.constructor===Array?null:t}catch(e){return null}},KJUR.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]},KJUR.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 r=rstrtohex(t);return hextob64u(KJUR.crypto.Util.hashHex(r,"sha256"))},KJUR.jws.IntDate={},KJUR.jws.IntDate.get=function(e){var t=KJUR.jws.IntDate,r=t.getNow,n=t.getZulu;if("now"==e)return r();if("now + 1hour"==e)return r()+3600;if("now + 1day"==e)return r()+86400;if("now + 1month"==e)return r()+2592e3;if("now + 1year"==e)return r()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},KJUR.jws.IntDate.getZulu=function(e){return zulutosec(e)},KJUR.jws.IntDate.getNow=function(){return~~(new Date/1e3)},KJUR.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.jws&&KJUR.jws||(KJUR.jws={}),KJUR.jws.JWSJS=function(){var e=KJUR.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,r,n){if(void 0===this.sPayload||null===this.sPayload)throw"there's no JSON-JS signature to add.";var i=this.aHeader.length;if(this.aHeader.length!=this.aSignature.length)throw"aHeader.length != aSignature.length";try{var s=KJUR.jws.JWS.sign(e,t,this.sPayload,r,n).split(".");s[0],s[2];this.aHeader.push(s[0]),this.aSignature.push(s[2])}catch(e){throw this.aHeader.length>i&&this.aHeader.pop(),this.aSignature.length>i&&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 r=e[t];if(2!==r.length)return!1;if(!1===this.verifyNth(t,r[0],r[1]))return!1}return!0},this.verifyNth=function(t,r,n){if(this.aHeader.length<=t||this.aSignature.length<=t)return!1;var i=this.aHeader[t],s=this.aSignature[t],o=i+"."+this.sPayload+"."+s,a=!1;try{a=e.verify(o,r,n)}catch(e){return!1}return a},this.readJWSJS=function(e){if("string"==typeof e){var r=t(e);if(null==r)throw"argument is not safe JSON object string";this.aHeader=r.headers,this.sPayload=r.payload,this.aSignature=r.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}},KJUR.crypto.ECDSA,KJUR.crypto.DSA,KJUR.crypto.Signature,KJUR.crypto.MessageDigest,KJUR.crypto.Mac,KJUR.crypto.Cipher;var KEYUTIL_1=KEYUTIL,b64utoutf8_1=b64utoutf8,KJUR_1=KJUR;KJUR.crypto,KJUR.asn1,KJUR.jws,KJUR.lang;const swarmPublicKey="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmkXOuNfY8u5xoTiIhkb8\ndjnbIwG/Wrz3vpo8BZir8L5e1a1nSy740qBjP7ZINBQoALDhFfmdOfJnCyEGiHuz\nZW6jbG6C3PryE3Bu6GKwqSmD6k3q4Zk27fpwYAnNl+rWhYYM563rJZBda/INyHNN\npK7M1mixWi7gNdjjXwoEXSSBx+VpYMkY6LiAB2mvHXTY9M1qI14dvgGoQISZQoKi\nNMTRCg5UP2ic0Dd9nSz/XpcOxGfa+0fwIl1F7RC1tJXOqvkGGPTOV4LLfg/Yta3h\nnUPX9EZZDIX6vO/0IBV1LzjSl2A1bYFYAjJfowv3i1CpvONBOClHjSY5t9Y8MH6p\nBwIDAQAB\n-----END PUBLIC KEY-----";var newFrom=(e,t)=>{const r={};return Object.getOwnPropertyNames(e).forEach((t=>{r[t]=e[t]})),new t(r)};class Line{type;id;extensions;endpointCustom;endpointSccp;endpointSip;static parse(e){return new Line({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 newFrom(e,Line)}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:r,endpointSccp:n,endpointSip:i}={}){this.id=e,this.extensions=t,this.endpointCustom=r||null,this.endpointSccp=n||null,this.endpointSip=i||null,this.type="Line"}}const FORWARD_KEYS={BUSY:"busy",NO_ANSWER:"noanswer",UNCONDITIONAL:"unconditional"};class ForwardOption{destination;enabled;key;static parse(e,t){return new ForwardOption({destination:e.destination||"",enabled:e.enabled,key:t})}static newFrom(e){return newFrom(e,ForwardOption)}constructor({destination:e,enabled:t,key:r}={}){this.destination=e,this.enabled=t,this.key=r}setDestination(e){return this.destination=e,this}setEnabled(e){return this.enabled=e,this}is(e){return this.key===e.key}}const STATE={AVAILABLE:"available",UNAVAILABLE:"unavailable",INVISIBLE:"invisible",DISCONNECTED:"disconnected",AWAY:"away"},LINE_STATE={AVAILABLE:"available",HOLDING:"holding",RINGING:"ringing",TALKING:"talking",UNAVAILABLE:"unavailable",PROGRESSING:"progressing"};class Profile{id;firstName;lastName;email;lines;sipLines;username;mobileNumber;forwards;doNotDisturb;onlineCallRecordEnabled;state;ringSeconds;voicemail;status;subscriptionType;agent;switchboards;callPickupTargetUsers;static parse(e){return new Profile({id:e.uuid,firstName:e.firstName||e.firstname||"",lastName:e.lastName||e.lastname||"",email:e.email,lines:e.lines.map((e=>Line.parse(e))),username:e.username,mobileNumber:e.mobile_phone_number||"",ringSeconds:e.ring_seconds,forwards:[ForwardOption.parse(e.forwards.unconditional,FORWARD_KEYS.UNCONDITIONAL),ForwardOption.parse(e.forwards.noanswer,FORWARD_KEYS.NO_ANSWER),ForwardOption.parse(e.forwards.busy,FORWARD_KEYS.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 newFrom(e,Profile)}constructor({id:e,firstName:t,lastName:r,email:n,lines:i,username:s,mobileNumber:o,forwards:a,doNotDisturb:d,state:c,subscriptionType:l,voicemail:u,switchboards:h,agent:g,status:p,ringSeconds:m,sipLines:f,callPickupTargetUsers:S,onlineCallRecordEnabled:y}){this.id=e,this.firstName=t,this.lastName=r,this.email=n,this.lines=i,this.username=s,this.mobileNumber=o,this.forwards=a,this.doNotDisturb=d,this.state=c,this.voicemail=u,this.subscriptionType=l,this.switchboards=h,this.agent=g,this.status=p,this.callPickupTargetUsers=S,this.onlineCallRecordEnabled=y,this.ringSeconds=m,this.sipLines=f||[]}static getLinesState(e){let t=LINE_STATE.UNAVAILABLE;for(const r of e){if(r.state===LINE_STATE.RINGING){t=LINE_STATE.RINGING;break}if(r.state===LINE_STATE.TALKING){t=LINE_STATE.TALKING;break}r.state===LINE_STATE.AVAILABLE&&(t=LINE_STATE.AVAILABLE)}return t}hasId(e){return e===this.id}setMobileNumber(e){return this.mobileNumber=e,this}setForwardOption(e){const t=this.forwards.slice(),r=t.findIndex((t=>t.is(e)));return t.splice(r,1,e),this.forwards=t,this}setDoNotDisturb(e){return this.doNotDisturb=e,this}setState(e){return this.state=e,this}}const BACKEND={OFFICE365:"office365",PERSONAL:"personal",GOOGLE:"google",WAZO:"wazo",CONFERENCE:"conference",PHONEBOOK:"phonebook"},SOURCE_MOBILE="mobile";class Contact{static BACKEND=BACKEND;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 r=e.find((e=>e&&e.is(t)));return r?t.merge(r):t}))}static sortContacts(e,t){const r=e.separateName(),n=t.separateName(),i=r.lastName,s=n.lastName;return i===s?r.firstName.localeCompare(n.firstName):i.localeCompare(s)}static parseMany(e,t=0,r=null){if(!e||!e.results||0===r)return[];return(null!==r&&r>0?e.results.slice(t,r):t>0?e.results.slice(t):e.results).map((t=>Contact.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,r)=>{if(!t.node)return null;const{email:n}=t.node,i=t.node.firstname&&t.node.lastname?`${t.node.firstname||""} ${t.node.lastname||""}`:t.node.wazoReverse;return new Contact({name:i,number:e[r],numbers:[{label:"primary",number:e[r]}],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 r=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)=>r.some((e=>e===t))&&null!==e))}static parse(e,t){const r=Contact.fetchNumbers(e,t),n=e.column_values[t.indexOf("email")];return new Contact({name:e.column_values[t.indexOf("name")],number:r.length?r[0]:"",numbers:r.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=>Contact.parsePersonal(e)))}static parsePersonal(e){return new Contact({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||BACKEND.PERSONAL})}static parseMobile(e){let t="";if(e.postalAddresses.length){const r=e.postalAddresses[0];t=`${r.street} ${r.city} ${r.postCode} ${r.country}`}const r=e.givenName||"",n=e.familyName||"",i=e.company||"";return new Contact({name:!r&&!n?i:`${r} ${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:SOURCE_MOBILE,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=>Contact.parseOffice365(e,t)))}static parseOffice365(e,t){const r=[],n=[];return e.emailAddresses&&e.emailAddresses.map((e=>r.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 Contact({sourceId:e.id||"",name:e.displayName||"",number:n.length?n[0].number:"",numbers:n,emails:r,source:t.name,backend:BACKEND.OFFICE365})}static parseManyGoogle(e,t){return e.map((e=>Contact.parseGoogle(e,t)))}static parseGoogle(e,t){const r=[];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=>r.push({label:t,number:e.numbers_by_label[t]}))):e.numbers&&e.numbers.forEach((e=>r.push({number:e}))),new Contact({sourceId:e.id||"",name:e.name||"",number:r.length?r[0].number:"",numbers:r,emails:[],source:t.name,backend:BACKEND.GOOGLE})}static parseManyWazo(e,t){return e.map((e=>Contact.parseWazo(e,t)))}static parseWazo(e,t){const r=[],n=[];return e.email&&r.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 Contact({uuid:e.uuid,sourceId:String(e.id)||"",name:`${e.firstname}${e.lastname?` ${e.lastname}`:""}`,number:n.length?n[0].number:"",numbers:n,emails:r,source:t.name,backend:BACKEND.WAZO})}static parseManyConference(e,t){return e.map((e=>Contact.parseConference(e,t)))}static parseConference(e,t){const r=[];let n="";return e&&e.extensions&&e.extensions.length>0&&e.extensions[0].exten&&(n=e.extensions[0].exten,r.push({label:"exten",number:n})),new Contact({sourceId:String(e.id),name:e.name,number:n,numbers:r,source:t.name,backend:BACKEND.CONFERENCE})}static newFrom(e){return newFrom(e,Contact)}constructor({id:e,uuid:t,name:r,number:n,numbers:i,email:s,emails:o,source:a,sourceId:d,entreprise:c,birthday:l,address:u,note:h,state:g,lineState:p,lastActivity:m,mobile:f,status:S,endpointId:y,personal:b,favorited:E,backend:v,personalStatus:_,sessions:T,connected:R,doNotDisturb:$,ringing:C,previousPresential:A,lines:N}={}){this.id=e,this.uuid=t,this.name=r||"",this.number=n,this.numbers=i,this.email=s,this.emails=o,this.source=a,this.sourceId=d,this.entreprise=c,this.birthday=l,this.address=u,this.note=h,this.state=g,this.lineState=p,this.lastActivity=m,this.mobile=f,this.status=S,this.endpointId=y,this.personal=b,this.favorited=E,this.backend=v,this.personalStatus=_||"",this.sessions=T||[],this.connected=R,this.doNotDisturb=$,this.ringing=C,this.previousPresential=A,this.lines=N||[],this.type="Contact"}setFavorite(e){return this.favorited=e,this}is(e){const t=null!==this.sourceId&&null!==e.sourceId&&this.sourceId===e.sourceId,r=!!this.uuid&&!!e.uuid&&this.uuid===e.uuid,n=t||r,i=!!this.backend&&!!e.backend&&this.backend===e.backend,s=!!this.source&&!!e.source&&this.source===e.source;return!!e&&n&&i&&s}hasId(e){return this.uuid===e}hasNumber(e){return this.number===e}hasEndpointId(e){return this.endpointId===e}isAvailable(){return this.state===STATE.AVAILABLE}isAway(){return this.state===STATE.AWAY}isUnavailable(){return this.state===STATE.UNAVAILABLE}isInvisible(){return this.state===STATE.INVISIBLE}isInCall(){return this.lineState===LINE_STATE.TALKING||this.lineState===LINE_STATE.HOLDING}isRinging(){return this.ringing}isInUseOrRinging(){return this.lineState===LINE_STATE.TALKING||this.lineState===LINE_STATE.RINGING}isProgressing(){return this.lineState===LINE_STATE.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===SOURCE_MOBILE}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 compareVersions=(e,t)=>{let r,n;const i=/(\.0+)+$/,s=e.replace(i,"").split("."),o=t.replace(i,"").split("."),a=Math.min(s.length,o.length);for(r=0;r<a;r++)if(n=parseInt(s[r],10)-parseInt(o[r],10),n)return n;return s.length-o.length},{jws:jws}=KJUR_1,swarmKey=KEYUTIL_1.getKey(swarmPublicKey),MINIMUM_WAZO_ENGINE_VERSION_FOR_DEFAULT_CONTEXT="19.08";let Session$1=class e{acl;contact;token;refreshToken;uuid;tenantUuid;stackUuid;sessionUuid;engineVersion;_stackHostFromHeader;profile;expiresAt;authorizations;static parse(t){const r=t.data.metadata?t.data.metadata.jwt:null;let n=[];if(r){if(jws.JWS.verifyJWT(r,swarmKey,{alg:["RS256"],verifyAt:new Date})){const e=jws.JWS.readSafeJSONString(b64utoutf8_1(r.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:moment.utc(t.data.utc_expires_at).toDate(),stackUuid:t.data.xivo_uuid,stackHostFromHeader:t._headers?.get?.("wazo-stack-host")})}static newFrom(t){return newFrom(t,e)}constructor({token:e,uuid:t,tenantUuid:r,profile:n,expiresAt:i,authorizations:s,acl:o,engineVersion:a,refreshToken:d,sessionUuid:c,stackUuid:l,stackHostFromHeader:u}){this.token=e,this.uuid=t,this.tenantUuid=r||null,this.profile=n,this.expiresAt=i,this.authorizations=s||[],this.acl=o||[],this.engineVersion=a,this.refreshToken=d,this.sessionUuid=c,this.stackUuid=l,this._stackHostFromHeader=u}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:r,mobileNumber:n,state:i,status:s}=this.profile||{},o=this.primaryNumber()||"",a=[{label:"primary",number:o}];return n&&a.push({label:"mobile",number:n}),new Contact({uuid:this.uuid||"",email:e,name:`${t} ${r}`,number:o,numbers:a,state:i||"",status:s,backend:"wazo",source:"default"})}primaryContext(){if(this.engineVersion&&this.hasEngineVersionGte(MINIMUM_WAZO_ENGINE_VERSION_FOR_DEFAULT_CONTEXT))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&&compareVersions(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 DEFAULT_BACKEND_USER="wazo_user",BACKEND_LDAP_USER="ldap_user",DETAULT_EXPIRATION=3600;var authMethods=(e,t)=>({checkToken:r=>e.head(`${t}/token/${r}`,null,{}),authenticate:r=>e.get(`${t}/token/${r}`,null,{}).then((e=>Session$1.parse(e))),logIn(r){const n={backend:r.backend||DEFAULT_BACKEND_USER,expiration:r.expiration||DETAULT_EXPIRATION},i={Authorization:`Basic ${ApiRequester.base64Encode(`${r.username}:${r.password}`)}`,"Content-Type":"application/json"};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),r.mobile&&(i["Wazo-Session-Type"]="mobile"),r.tenantId&&(console.warn("Use of `tenantId` is deprecated when calling logIn() method, use `domainName` instead."),n.tenant_id=r.tenantId),r.domainName&&(n.domain_name=r.domainName),e.post(`${t}/token`,n,i).then((e=>Session$1.parse(e)))},logOut:r=>e.delete(`${t}/token/${r}`,null,{},ApiRequester.successResponseParser),refreshToken:(r,n,i,s,o,a)=>{const d={backend:n||DEFAULT_BACKEND_USER,expiration:i||DETAULT_EXPIRATION,refresh_token:r,client_id:e.clientId};o&&(console.warn("Use of `tenantId` is deprecated when calling refreshToken() method, use `domainName` instead."),d.tenant_id=o),a&&(d.domain_name=a);const c={"Content-Type":"application/json",...s?{"Wazo-Session-Type":"mobile"}:{}};return e.post(`${t}/token`,d,c,ApiRequester.defaultParser,!1).then(Session$1.parse)},deleteRefreshToken:r=>e.delete(`${t}/users/me/tokens/${r}`,null,null,ApiRequester.successResponseParser),updatePassword:(r,n,i)=>{const s={new_password:i,old_password:n};return e.put(`${t}/users/${r}/password`,s,null,ApiRequester.successResponseParser)},sendDeviceToken:(r,n,i,s)=>{const o={token:n};return i&&(o.apns_token=i,o.apns_voip_token=i),s&&(o.apns_notification_token=s),e.post(`${t}/users/${r}/external/mobile`,o)},getPushNotificationSenderId:r=>e.get(`${t}/users/${r}/external/mobile/sender_id`,null).then((e=>e.sender_id)),sendResetPasswordEmail:({username:r,email:n})=>{const i={};return r&&(i.username=r),n&&(i.email=n),e.get(`${t}/users/password/reset`,i,{},ApiRequester.successResponseParser)},resetPassword:(r,n)=>{const i={password:n};return e.post(`${t}/users/password/reset?user_uuid=${r}`,i,null,ApiRequester.successResponseParser)},removeDeviceToken:r=>e.delete(`${t}/users/${r}/external/mobile`),createUser:(r,n,i,s)=>{const o={username:r,password:n,firstname:i,lastname:s};return e.post(`${t}/users`,o)},addUserEmail:(r,n,i)=>{const s={emails:[{address:n,main:i}]};return e.put(`${t}/users/${r}/emails`,s)},addUserPolicy:(r,n)=>e.put(`${t}/users/${r}/policies/${n}`),getRestrictionPolicies:r=>e.post(`${t}/token/${e.token}/scopes/check`,{scopes:r}),deleteUserPolicy:(r,n)=>e.delete(`${t}/users/${r}/policies/${n}`),addUserGroup:(r,n)=>e.put(`${t}/groups/${n}/users/${r}`),listUsersGroup:r=>e.get(`${t}/groups/${r}/users`),deleteUserGroup:(r,n)=>e.delete(`${t}/groups/${n}/users/${r}`),getUser:r=>e.get(`${t}/users/${r}`),getUserSession:r=>e.get(`${t}/users/${r}/sessions`),deleteUserSession:(r,n)=>e.delete(`${t}/users/${r}/sessions/${n}`),listUsers:()=>e.get(`${t}/users`),deleteUser:r=>e.delete(`${t}/users/${r}`),listTenants:()=>e.get(`${t}/tenants`),getTenant:r=>e.get(`${t}/tenants/${r}`),createTenant:r=>e.post(`${t}/tenants`,{name:r}),updateTenant:(r,n,i,s,o)=>{const a={name:n,contact:i,phone:s,address:o};return e.put(`${t}/tenants/${r}`,a)},deleteTenant:r=>e.delete(`${t}/tenants/${r}`),createGroup:r=>e.post(`${t}/groups`,{name:r}),listGroups:()=>e.get(`${t}/groups`),deleteGroup:r=>e.delete(`${t}/groups/${r}`),createPolicy:(r,n,i)=>{const s={name:r,description:n,acl_templates:i,acl:i};return e.post(`${t}/policies`,s)},listPolicies:()=>e.get(`${t}/policies`),deletePolicy:r=>e.delete(`${t}/policies/${r}`),getProviders:r=>e.get(`${t}/users/${r}/external`),getProviderToken:(r,n)=>e.get(`${t}/users/${r}/external/${n}`),getProviderAuthUrl:(r,n)=>e.post(`${t}/users/${r}/external/${n}`,{}),deleteProviderToken:(r,n)=>e.delete(`${t}/users/${r}/external/${n}`)}),applicationMethods=(e,t)=>({bridgeCall(r,n,i,s,o,a){const d=`${t}/${r}/nodes`,c={calls:[{id:n}]};return e.post(d,c,null,(e=>e.json().then((e=>e.uuid)))).then((t=>e.post(`${d}/${t}/calls`,{context:i,exten:s,autoanswer:o,displayed_caller_id_number:a}).then((e=>({nodeUuid:t,data:e})))))},answerCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/answer`,{},null,ApiRequester.successResponseParser),calls:r=>e.get(`${t}/${r}/calls`),hangupCall:(r,n)=>e.delete(`${t}/${r}/calls/${n}`),startPlaybackCall:(r,n,i,s)=>e.post(`${t}/${r}/calls/${n}/playbacks`,{language:i,uri:s}),stopPlaybackCall:(r,n)=>e.delete(`${t}/${r}/playbacks/${n}`),startProgressCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/progress/start`,{},null,ApiRequester.successResponseParser),stopProgressCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/progress/stop`,{},null,ApiRequester.successResponseParser),startMohCall:(r,n,i)=>e.put(`${t}/${r}/calls/${n}/moh/${i}/start`,{},null,ApiRequester.successResponseParser),stopMohCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/moh/stop`,{},null,ApiRequester.successResponseParser),startHoldCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/hold/start`,{},null,ApiRequester.successResponseParser),stopHoldCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/hold/stop`,{},null,ApiRequester.successResponseParser),startMuteCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/mute/start`,{},null,ApiRequester.successResponseParser),stopMuteCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/mute/stop`,{},null,ApiRequester.successResponseParser),sendDTMFCall:(r,n,i)=>e.put(`${t}/${r}/calls/${n}/dtmf`,{digits:i},null,ApiRequester.successResponseParser),addCallNodes:(r,n,i)=>e.put(`${t}/${r}/nodes/${n}/calls/${i}`,{},null,ApiRequester.successResponseParser),createNewNodeWithCall:(r,n)=>e.post(`${t}/${r}/nodes`,{calls:n}),addNewCallNodes:(r,n,i,s,o)=>e.post(`${t}/${r}/nodes/${n}/calls`,{context:i,exten:s,autoanswer:o}),listCallsNodes:(r,n)=>e.get(`${t}/${r}/nodes/${n}`),listNodes:r=>e.get(`${t}/${r}/nodes`),removeNode:(r,n)=>e.delete(`${t}/${r}/nodes/${n}`),removeCallNodes:(r,n,i)=>e.delete(`${t}/${r}/nodes/${n}/calls/${i}`),listSnoop:r=>e.get(`${t}/${r}/snoops`),removeSnoop:(r,n)=>e.delete(`${t}/${r}/snoops/${n}`),viewSnoop:(r,n)=>e.get(`${t}/${r}/snoops/${n}`),createSnoop:(r,n,i,s)=>e.post(`${t}/${r}/calls/${n}/snoops`,{snooping_call_id:i,whisper_mode:s}),updateSnoop:(r,n,i)=>e.put(`${t}/${r}/snoops/${n}`,{whisper_mode:i},null,ApiRequester.successResponseParser)});const availableCodecs=["vp8","vp9","h264"];class SipLine{id;uuid;tenantUuid;username;secret;type;host;options;endpointSectionOptions;links;trunk;line;static parse(e){let{username:t,secret:r,host:n}=e;if(e.auth_section_options){const i=(e,t)=>e.find((e=>e[0]===t)),s=i(e.auth_section_options,"username"),o=i(e.auth_section_options,"password"),a=i(e.endpoint_section_options,"media_address");t=s?s[1]:"",r=o?o[1]:"",n=a?a[1]:""}return new SipLine({id:e.id,uuid:e.uuid,tenantUuid:e.tenant_uuid,username:t,secret:r,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 newFrom(e,SipLine)}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=>availableCodecs.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:r,username:n,secret:i,type:s,host:o,options:a,endpointSectionOptions:d,links:c,trunk:l,line:u}){this.id=e,this.uuid=t,this.tenantUuid=r,this.username=n,this.secret=i,this.type=s,this.host=o,this.options=a,this.endpointSectionOptions=d,this.links=c,this.trunk=l,this.line=u,this.type="SipLine"}}class ExternalApp{name;type;configuration;static parse(e){return new ExternalApp({name:e.name,configuration:e.configuration})}static parseMany(e){return e.items.map((e=>ExternalApp.parse(e)))}static newFrom(e){return newFrom(e,ExternalApp)}constructor({name:e,configuration:t}={}){this.name=e,this.configuration=t,this.type="ExternalApp"}}class Meeting{type;guestSipAuthorization;uri;uuid;name;port;extension;persistent;ownerUuids;creationTime;pendingAuthorizations;requireAuthorization;static parse(e){return new Meeting({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:moment(e.creation_time).toDate(),requireAuthorization:e.require_authorization})}static parseMany(e){return e?e.map((e=>Meeting.parse(e))):[]}static newFrom(e){return newFrom(e,Meeting)}constructor({uuid:e,name:t,guestSipAuthorization:r,ownerUuids:n,port:i,uri:s,extension:o,persistent:a,creationTime:d,requireAuthorization:c}={}){this.guestSipAuthorization=r,this.uri=s,this.name=t,this.ownerUuids=n,this.port=i,this.uuid=e,this.extension=o,this.persistent=a,this.creationTime=d,this.requireAuthorization=c,this.type="Meeting"}getGuestSipCredentials(){const[e,t]=Buffer.from(this.guestSipAuthorization,"base64").toString("ascii").split(":");return{username:e,secret:t}}}const PENDING="pending",ACCEPTED$1="accepted",REJECTED$1="rejected",POST_PROCESSING="post_processing",POST_PROCESSED_SUCCESS="post_processed_success",POST_PROCESSED_ERROR="post_processed_error";class MeetingAuthorization{static PENDING=PENDING;static ACCEPTED=ACCEPTED$1;static REJECTED=REJECTED$1;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:r,userName:n}={}){this.meetingUuid=e,this.uuid=t,this.userUuid=r,this.userName=n}setStatus(e){this.status=e}getStatus(){return this.status}static parse(e){const{meeting_uuid:t,uuid:r,guest_uuid:n,guest_name:i}=e;return new MeetingAuthorization({meetingUuid:t,uuid:r,userUuid:n,userName:i})}static parseMany(e){return e?e.map(MeetingAuthorization.parse):[]}}const convertKeysFromCamelToUnderscore=e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Input is not an object");return Object.keys(e).reduce(((t,r)=>(t[camelToUnderscore(r)]="object"!=typeof e[r]||Array.isArray(e[r])?e[r]:convertKeysFromCamelToUnderscore(e[r]),t)),{})};var confdMethods=(e,t)=>({listUsers:()=>e.get(`${t}/users`,null),getUser:r=>e.get(`${t}/users/${r}`,null).then(Profile.parse),updateUser:(r,n)=>{const i={firstname:n.firstName,lastname:n.lastName,email:n.email,mobile_phone_number:n.mobileNumber};return e.put(`${t}/users/${r}`,i,null,ApiRequester.successResponseParser)},updateForwardOption:(r,n,i,s)=>{const o=`${t}/users/${r}/forwards/${n}`;return e.put(o,{destination:i,enabled:s},null,ApiRequester.successResponseParser)},updateDoNotDisturb:(r,n)=>e.put(`${t}/users/${r}/services/dnd`,{enabled:n},null,ApiRequester.successResponseParser),getUserLineSip:(r,n)=>e.get(`${t}/users/${r}/lines/${n}/associated/endpoints/sip?view=merged`).then(SipLine.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 r=t.lines[0];return this.getUserLineSip(e,r.uuid||r.id)}))},listApplications:()=>e.get(`${t}/applications`,null),getInfos:()=>e.get(`${t}/infos`,null),getExternalApps:r=>e.get(`${t}/users/${r}/external/apps`).then(ExternalApp.parseMany),getExternalApp:async(r,n)=>{const i=`${t}/users/${r}/external/apps/${n}?view=fallback`;try{return await e.get(i).then(ExternalApp.parse)}catch(e){return null}},getMyMeetings:()=>e.get(`${t}/users/me/meetings`).then((e=>Meeting.parseMany(e.items))),createMyMeeting:r=>e.post(`${t}/users/me/meetings`,convertKeysFromCamelToUnderscore(r)).then(Meeting.parse),updateMyMeeting:(r,n)=>e.put(`${t}/users/me/meetings/${r}`,convertKeysFromCamelToUnderscore(n),null,ApiRequester.successResponseParser),deleteMyMeeting:r=>e.delete(`${t}/users/me/meetings/${r}`,null),getMeeting:r=>e.get(`${t}/meetings/${r}`,null).then(Meeting.parse),meetingAuthorizations:r=>e.get(`${t}/users/me/meetings/${r}/authorizations`,null).then((e=>MeetingAuthorization.parseMany(e.items))),meetingAuthorizationReject:(r,n)=>e.put(`${t}/users/me/meetings/${r}/authorizations/${n}/reject`,{},null,ApiRequester.successResponseParser),meetingAuthorizationAccept:(r,n)=>e.put(`${t}/users/me/meetings/${r}/authorizations/${n}/accept`,{},null,ApiRequester.successResponseParser),guestGetMeeting:r=>e.get(`${t}/guests/me/meetings/${r}`,null).then(Meeting.parse),guestAuthorizationRequest:(r,n,i)=>e.post(`${t}/guests/${r}/meetings/${n}/authorizations`,{guest_name:i}).then(MeetingAuthorization.parse),guestAuthorizationCheck:(r,n,i)=>e.get(`${t}/guests/${r}/meetings/${n}/authorizations/${i}`,null)});class Relocation{static MIN_ENGINE_VERSION_REQUIRED;relocatedCall;initiatorCall;recipientCall;static parse(e){return new Relocation({initiatorCall:e.initiator_call,recipientCall:e.recipient_call,relocatedCall:e.relocated_call})}constructor({relocatedCall:e,initiatorCall:t,recipientCall:r}){this.initiatorCall=t||"",this.relocatedCall=e||"",this.recipientCall=r||""}}Relocation.MIN_ENGINE_VERSION_REQUIRED="19.09";class ChatMessage{type;uuid;content;date;alias;userUuid;roomUuid;read;static parseMany(e){return e&&e.items?e.items.map((e=>ChatMessage.parse(e))):[]}static parse(e){return new ChatMessage({uuid:e.uuid,date:moment(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 newFrom(e,ChatMessage)}constructor({uuid:e,date:t,content:r,userUuid:n,alias:i,roomUuid:s,read:o}={}){this.uuid=e,this.date=t,this.content=r,this.userUuid=n,this.alias=i,this.roomUuid=s,this.read=o,this.type="ChatMessage"}is(e){return this.uuid===e.uuid}isIncoming(e){return this.userUuid!==e}acknowledge(){return this.read=!0,this}}class Voicemail{type;id;date;duration;unread;caller;static parse(e){return new Voicemail({id:e.id,date:moment(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,r=e.folders.filter((e=>"old"===e.type))[0].messages;return[...t.map((e=>Voicemail.parse(e))).map((e=>e.makeAsUnRead())),...r.map((e=>Voicemail.parse(e))).map((e=>e.acknowledge()))]}static newFrom(e){return newFrom(e,Voicemail)}constructor({id:e,date:t,duration:r,caller:n,unread:i}){this.id=e,this.date=t,this.duration=r,this.caller=n,this.unread=i,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))}}const RECORD_STATE_ACTIVE="active";class Call{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=>Call.parse(e))):[]}static parse(e){return new Call({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:moment(e.creation_time).toDate(),talkingToIds:Object.keys(e.talking_to||{}),recording:e.record_state===RECORD_STATE_ACTIVE})}static newFrom(e){return newFrom(e,Call)}constructor({id:e,sipCallId:t,callerName:r,callerNumber:n,calleeName:i,calleeNumber:s,dialedExtension:o,isCaller:a,isVideo:d,lineId:c,muted:l,onHold:u,status:h,startingTime:g,talkingToIds:p,recording:m}){this.id=e,this.sipCallId=t,this.callerName=r,this.callerNumber=n,this.calleeName=i,this.calleeNumber=s,this.dialedExtension=o,this.muted=l,this.onHold=u,this.isCaller=a,this.lineId=c,this.status=h,this.startingTime=g,this.talkingToIds=p||[],this.recording=m,this.isVideo=!!d,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 SessionState$1;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(SessionState$1=SessionState$1||(SessionState$1={}));var updateFrom=(e,t)=>{Object.keys(t).forEach((r=>{(!e[r]&&t[r]||void 0!==e[r]&&void 0!==t[r]&&e[r]!==t[r])&&(e[r]=t[r])}))};class CallSession{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:r,displayName:n,callId:i,muted:s,videoMuted:o,number:a,paused:d,ringing:c,startTime:l,creationTime:u,endTime:h,cameraEnabled:g,dialedExtension:p,sipCallId:m,sipStatus:f,callerNumber:S,call:y,autoAnswer:b,ignored:E,screensharing:v,recording:_,recordingPaused:T,videoRemotelyDowngraded:R,sipSession:$,answerTime:C,conference:A}){this.callId=i,this.sipCallId=m,this.displayName=n,this.number=a,this.creationTime=u,this.startTime=l,this.endTime=h,this.isCaller=r,this.answered=e,this.answeredBySystem=t,this.ringing=c,this.paused=d,this.muted=s,this.videoMuted=o,this.callerNumber=S,this.cameraEnabled=g,this.dialedExtension=p||"",this.call=y,this.sipStatus=f,this.autoAnswer=b||!1,this.ignored=E||!1,this.screensharing=v||!1,this.recording=_||!1,this.recordingPaused=T||!1,this.videoRemotelyDowngraded=R,this.sipSession=$,this.answerTime=C||this.answerTime,this.conference=A,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===SessionState$1.Established}isTerminating(){return this.sipStatus===SessionState$1.Terminating}isTerminated(){return this.sipStatus===SessionState$1.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){updateFrom(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 newFrom(e,CallSession)}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 CallSession({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})}}class Emitter{eventEmitter;constructor(){this.eventEmitter=new EventEmitter$2}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 CallApi{static async fetchCallLogs(e,t){return getApiClient().callLogd.listCallLogs(e,t)}static async fetchDistinctCallLogs(e,t,r="peer_exten"){return getApiClient().callLogd.listDistinctCallLogs(e,t,r)}static async fetchActiveCalls(){return getApiClient().calld.listCalls()}static async fetchCallLogsFromDate(e,t){return getApiClient().callLogd.listCallLogsFromDate(e,t)}static async search(e,t){return getApiClient().callLogd.search(e,t)}static async searchBy(e,t,r){return getApiClient().callLogd.searchBy(e,t,r)}static async fetchSIP(e,t){const r=t||e.primaryLine();return getApiClient().confd.getUserLineSip(e.uuid,r?r.id:"")}static async cancelCall(e){return getApiClient().calld.cancelCall(e.callId)}static async makeCall(e,t,r=!1,n=!1){const i=e?e.id:null,s=await getApiClient().calld.makeCall(t,r,i,n);return Call.parse(s)}static async relocateCall(e,t,r){return getApiClient().calld.relocateCall(e,"line",t,r)}static async hold(e){return getApiClient().calld.hold(e)}static async resume(e){return getApiClient().calld.resume(e)}static async mute(e){return getApiClient().calld.mute(e)}static async sendDTMF(e,t){return getApiClient().calld.sendDTMF(e,t)}static async unmute(e){return getApiClient().calld.unmute(e)}static async transferCall(e,t,r){return getApiClient().calld.transferCall(e,t,r)}static async cancelCallTransfer(e){return getApiClient().calld.cancelCallTransfer(e)}static async confirmCallTransfer(e){return getApiClient().calld.confirmCallTransfer(e)}}const TRANSFER_FLOW_ATTENDED="attended",TRANSFER_FLOW_BLIND="blind",logger$b=IssueReporter$1?IssueReporter$1.loggerFor("cti-phone"):console;class CTIPhone extends Emitter{session;isMobile;callbackAllLines;currentCall;client=null;constructor(e,t=!1,r=!1){super(),logger$b.info("CTI Phone created"),this.session=e,this.isMobile=t,this.callbackAllLines=r}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(logger$b.info("make CTI call",{number:e}),!e)return null;try{this.currentCall=await CallApi.makeCall(t,e,this.isMobile,this.callbackAllLines)}catch(e){}if(!this.currentCall)return null;const r=CallSession.parseCall(this.currentCall);return this.eventEmitter.emit("onCallOutgoing",r),r}accept(e){return e?(logger$b.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&&(logger$b.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);logger$b.info("hangup CTI call",{callId:e.getId(),number:e.number});try{return await CallApi.cancelCall(e),this.currentCall&&e.callId===this.currentCall.id&&this.endCurrentCall(e),this.eventEmitter.emit("onCallEnded",e),!0}catch(t){return logger$b.error("hangup CTI call, error",t),this.eventEmitter.emit("onCallFailed",e),!1}}ignore(){}async reject(e){e&&(logger$b.info("reject CTI call",{callId:e.getId(),number:e.number}),await CallApi.cancelCall(e),this.eventEmitter.emit("onCallEnded",e))}async transfer(e,t){e&&(logger$b.info("transfer CTI call",{callId:e.getId(),number:e.number,to:t}),await CallApi.transferCall(e.callId,t,TRANSFER_FLOW_BLIND))}indirectTransfer(){return Promise.resolve(!1)}async initiateCTIIndirectTransfer(e,t){return e?(logger$b.info("indirect CTI transfer",{callId:e.getId(),number:e.number,to:t}),CallApi.transferCall(e.callId,t,TRANSFER_FLOW_ATTENDED)):Promise.resolve(null)}async cancelCTIIndirectTransfer(e){return logger$b.info("cancel CTI transfer",{transferId:e}),CallApi.cancelCallTransfer(e)}async confirmCTIIndirectTransfer(e){return logger$b.info("confirm CTI transfer",{transferId:e}),CallApi.confirmCallTransfer(e)}sendKey(e,t){e&&(logger$b.info("send CTI key",{callId:e.getId(),number:e.number,digits:t}),CallApi.sendDTMF(e.callId,t))}onConnectionMade(){logger$b.info("on CTI connection made"),this.eventEmitter.emit("onCallAccepted")}async close(){return logger$b.info("CTI close"),Promise.resolve()}async hold(e){return!!e&&(logger$b.info("CTI hold",{callId:e.getId(),number:e.number}),CallApi.hold(e.callId))}async resume(e){return!!e&&(logger$b.info("CTI resume",{callId:e.getId(),number:e.number}),CallApi.resume(e.callId))}async mute(e){e&&(logger$b.info("CTI mute",{callId:e.getId(),number:e.number}),await CallApi.mute(e.callId))}async unmute(e){e&&(logger$b.info("CTI unmute",{callId:e.getId(),number:e.number}),await CallApi.unmute(e.callId))}putOnSpeaker(){}putOffSpeaker(){}turnCameraOff(){}turnCameraOn(){}changeAudioInputDevice(){return Promise.resolve(null)}changeVideoInputDevice(){return Promise.resolve(null)}changeAudioDevice(){}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?CallSession.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 ctidNgMethods=(e,t)=>({updatePresence:r=>e.put(`${t}/users/me/presences`,{presence:r},null,ApiRequester.successResponseParser),listMessages:(r,n)=>{const i={};return r&&(i.participant_user_uuid=r),n&&(i.limit=n),e.get(`${t}/users/me/chats`,i).then(ChatMessage.parseMany)},sendMessage:(r,n,i)=>{const s={alias:r,msg:n,to:i};return e.post(`${t}/users/me/chats`,s,null,ApiRequester.successResponseParser)},makeCall:(r,n,i,s=!1)=>{const o={from_mobile:n,extension:r};return i&&(o.line_id=i),s&&(o.all_lines=!0),e.post(`${t}/users/me/calls`,o)},cancelCall:r=>e.delete(`${t}/users/me/calls/${r}`),listCalls:()=>e.get(`${t}/users/me/calls`).then((e=>Call.parseMany(e.items))),relocateCall(r,n,i,s){const o={completions:["answer"],destination:n,initiator_call:r,auto_answer:!0};return(i||s)&&(o.location={}),i&&(o.location.line_id=i),s&&(o.location.contact=s),e.post(`${t}/users/me/relocates`,o).then(Relocation.parse)},transferCall(r,n,i=TRANSFER_FLOW_BLIND){const s={exten:n,flow:i,initiator_call:r};return e.post(`${t}/users/me/transfers`,s)},cancelCallTransfer:r=>e.delete(`${t}/users/me/transfers/${r}`),confirmCallTransfer:r=>e.put(`${t}/users/me/transfers/${r}/complete`),listVoicemails:()=>e.get(`${t}/users/me/voicemails`,null).then((e=>Voicemail.parseMany(e))),deleteVoicemail:r=>e.delete(`${t}/users/me/voicemails/messages/${r}`,null),getPresence:r=>e.get(`${t}/users/${r}/presences`,null),getStatus:r=>e.get(`${t}/lines/${r}/presences`,null),fetchSwitchboardHeldCalls:r=>e.get(`${t}/switchboards/${r}/calls/held`,null),holdSwitchboardCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}`,null,null,ApiRequester.successResponseParser),answerSwitchboardHeldCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}/answer`,null),fetchSwitchboardQueuedCalls:r=>e.get(`${t}/switchboards/${r}/calls/queued`,null),answerSwitchboardQueuedCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/queued/${n}/answer`,null),sendFax:(r,n,i=null)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},o=ApiRequester.getQueryString({extension:r,caller_id:i});return e.post(`${t}/users/me/faxes?${o}`,n,s)}}),jsonToGraphQLQuery={},EnumType$1={};Object.defineProperty(EnumType$1,"__esModule",{value:!0}),EnumType$1.EnumType=void 0;var EnumType=function(e){this.value=e};EnumType$1.EnumType=EnumType;var VariableType$1={};Object.defineProperty(VariableType$1,"__esModule",{value:!0}),VariableType$1.VariableType=void 0;var VariableType=function(){function e(e){this.value=e}return e.prototype.toJSON=function(){return"$".concat(this.value)},e}();VariableType$1.VariableType=VariableType,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.jsonToGraphQLQuery=e.configFields=void 0;var t=EnumType$1,r=VariableType$1;function n(e){if(e instanceof t.EnumType)return e.value;if(e instanceof r.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 i=Object.keys(e).map((function(t){return"".concat(t,": ").concat(n(e[t]))})).join(", ");return"{".concat(i,"}")}function i(t,r){return-1==e.configFields.indexOf(t)&&-1==r.indexOf(t)}function s(e,t,r,o){Object.keys(e).filter((function(e){return i(e,o.ignoreFields)})).forEach((function(a){var d=e[a];if("object"==typeof d){if(Array.isArray(d)&&!(d=d.find((function(e){return e&&"object"==typeof e}))))return void r.push(["".concat(a),t]);if(d&&0===Object.keys(d).filter((function(e){return!1!==d[e]||o.includeFalsyKeys})).length)return;var c=Object.keys(d).filter((function(e){return i(e,o.ignoreFields)})).length>0,l="object"==typeof d.__args&&Object.keys(d.__args).length>0,u="object"==typeof d.__directives,h=d.__all_on instanceof Array,g="object"==typeof d.__on,p="".concat(a);if("string"==typeof d.__name&&(p="".concat(p," ").concat(d.__name)),"string"==typeof d.__aliasFor&&(p="".concat(p,": ").concat(d.__aliasFor)),"object"==typeof d.__variables&&Object.keys(d.__variables).length>0)p="".concat(p," (").concat(function(e){var t=[];for(var r in e)t.push("$".concat(r,": ").concat(e[r]));return t.join(", ")}(d.__variables),")");else if(l||u){var m="",f="";u&&(f=Object.entries(d.__directives).map((function(e){var t;return"@".concat(function(e){var t=Object.keys(e)[0],r=e[t];if("boolean"==typeof r||"object"==typeof r&&0===Object.keys(r).length)return t;if("object"==typeof r){var i=[];for(var s in r){var o=n(r[s]).replace(/"/g,"");i.push("".concat(s,": ").concat(o))}return"".concat(t,"(").concat(i.join(", "),")")}throw new Error("Unsupported type for directive: ".concat(typeof r,". Types allowed: object, boolean.\n")+"Offending object: ".concat(JSON.stringify(e)))}(((t={})[e[0]]=e[1],t)))})).join(" ")),l&&(m="(".concat(function(e){var t=[];for(var r in e)t.push("".concat(r,": ").concat(n(e[r])));return t.join(", ")}(d.__args),")"));var S=u&&l?" ":"";p="".concat(p," ").concat(m).concat(S).concat(f)}if(r.push([p+(c||g||h?" {":""),t]),s(d,t+1,r,o),h&&d.__all_on.forEach((function(e){r.push(["...".concat(e),t+1])})),g)(d.__on instanceof Array?d.__on:[d.__on]).forEach((function(e){var n=e.__typeName;r.push(["... on ".concat(n," {"),t+1]),s(e,t+2,r,o),r.push(["}",t+1])}));(c||g||h)&&r.push(["}",t])}else(!0===o.includeFalsyKeys||d)&&r.push(["".concat(a),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 r=[];s(e,0,r,t);var n="";return r.forEach((function(e){var r=e[0],i=e[1];t.pretty?(n&&(n+="\n"),n+=function(e){return Array(4*e+1).join(" ")}(i)+r):(n&&(n+=" "),n+=r)})),n}}(jsonToGraphQLQuery);const getContactPayload=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:""});var dirdMethods=(e,t)=>({search:(r,n,i=0,s=null)=>e.get(`${t}/directories/lookup/${r}`,{term:n}).then((e=>Contact.parseMany(e,i,s))),listPersonalContacts:r=>e.get(`${t}/personal`,r).then((e=>Contact.parseManyPersonal(e.items))),fetchPersonalContact:r=>e.get(`${t}/personal/${r}`).then(Contact.parsePersonal),addContact:r=>e.post(`${t}/personal`,getContactPayload(r)).then(Contact.parsePersonal),editContact:r=>e.put(`${t}/personal/${r.sourceId||r.id||""}`,getContactPayload(r)).then(Contact.parsePersonal),importContacts:async r=>{const n={"Content-Type":"text/csv; charset=utf-8","X-Auth-Token":e.token};return e.post(`${t}/personal/import`,r,n).then((e=>Contact.parseManyPersonal(e.created)))},deleteContact:r=>e.delete(`${t}/personal/${r}`),listFavorites:r=>e.get(`${t}/directories/favorites/${r}`).then(Contact.parseMany),markAsFavorite:(r,n)=>{const i=`${t}/directories/favorites/${r}/${n}`;return e.put(i,null,null,ApiRequester.successResponseParser)},removeFavorite:(r,n)=>e.delete(`${t}/directories/favorites/${r}/${n}`),fetchOffice365Source:r=>e.get(`${t}/directories/${r}/sources`,{backend:"office365"}),fetchOffice365Contacts:async(r,n)=>r?e.get(`${t}/backends/office365/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyOffice365(e.items,r))):Promise.resolve([]),fetchWazoSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"wazo"}),fetchWazoContacts:async(r,n)=>r?e.get(`${t}/backends/wazo/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyWazo(e.items,r))):Promise.resolve([]),fetchGoogleSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"google"}),fetchGoogleContacts:async(r,n)=>r?e.get(`${t}/backends/google/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyGoogle(e.items,r))):Promise.resolve([]),fetchConferenceSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"conference"}),fetchSourcesFor:(r,n)=>e.get(`${t}/directories/${r}/sources`,{backend:n}),fetchPhonebookContacts:async(r,n)=>r?e.get(`${t}/backends/phonebook/sources/${r.uuid}/contacts`,n):Promise.resolve({items:[],total:0}),fetchConferenceContacts:async(r,n)=>r?e.get(`${t}/backends/conference/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyConference(e.items,r))):Promise.resolve([]),findMultipleContactsByNumber:(r,n)=>{const i=jsonToGraphQLQuery.jsonToGraphQLQuery({me:{contacts:{__args:{profile:"default",extens:r},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:`{${i}}`}).then(Contact.manyGraphQlWithNumbersParser(r))}});class Recording{deleted;end;fileName;start;uuid;static parseMany(e=[]){return e?e.map((e=>Recording.parse(e))):[]}static parse(e){return new Recording({deleted:e.deleted,fileName:e.filename,end:e.end_time?moment(e.end_time).toDate():null,start:moment(e.start_time).toDate(),uuid:e.uuid})}constructor({deleted:e,end:t,fileName:r,start:n,uuid:i}){this.deleted=e,this.end=t,this.fileName=r,this.start=n,this.uuid=i}}class CallLog{type;answer;answered;newMissedCall;callDirection;destination;recordings;source;id;duration;start;end;static merge(e,t){const r=e.concat(t);return r.map((e=>e.id)).filter(((e,t,r)=>r.indexOf(e)===t)).map((e=>r.find((t=>t&&t.id===e))))}static parseMany(e){return e&&e.items?e.items.map((e=>CallLog.parse(e))):[]}static parse(e){return new CallLog({answer:e.answer?moment(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:moment(e.start).toDate(),end:e.end?moment(e.end).toDate():null,recordings:Recording.parseMany(e.recordings||[])})}static parseNew(e,t){const r=CallLog.parse(e);return r.newMissedCall=t&&t.hasExtension(e.requested_extension||e.destination_extension)&&!e.answered,r}static newFrom(e){return newFrom(e,CallLog)}constructor({answer:e,answered:t,callDirection:r,destination:n,source:i,id:s,duration:o,start:a,end:d,recordings:c}){this.answer=e,this.answered=t,this.callDirection=r,this.destination=n,this.source=i,this.id=s,this.duration=o,this.start=a,this.end=d,this.recordings=c||[],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}}var callLogdMethods=(e,t)=>({search:(r,n=5)=>e.get(`${t}/users/me/cdr`,{search:r,limit:n}).then(CallLog.parseMany),searchBy:(r,n,i=5)=>e.get(`${t}/users/me/cdr`,{[r]:n,limit:i}).then(CallLog.parseMany),listCallLogs:(r,n=5)=>e.get(`${t}/users/me/cdr`,{offset:r,limit:n}).then(CallLog.parseMany),listDistinctCallLogs:(r,n=5,i=void 0)=>e.get(`${t}/users/me/cdr`,{offset:r,limit:n,distinct:i}).then(CallLog.parseMany),listCallLogsFromDate:(r,n)=>e.get(`${t}/users/me/cdr`,{from:r.toISOString(),number:n}).then(CallLog.parseMany)});class ChatRoom{type;uuid;name;users;static parseMany(e){return e&&e.items?e.items.map((e=>ChatRoom.parse(e))):[]}static parse(e){return new ChatRoom({uuid:e.uuid,name:e.name,users:e.users})}static newFrom(e){return newFrom(e,ChatRoom)}constructor({uuid:e,name:t,users:r}={}){this.uuid=e,this.name=t,this.users=r,this.type="ChatRoom"}}const MAX_PRESENCE_FETCHED=30;var chatdMethods=(e,t)=>({updateState:(r,n)=>e.put(`${t}/users/${r}/presences`,{state:n},null,ApiRequester.successResponseParser),updateStatus:(r,n,i)=>{const s={state:n,status:i};return e.put(`${t}/users/${r}/presences`,s,null,ApiRequester.successResponseParser)},getState:async r=>e.get(`${t}/users/${r}/presences`).then((e=>e.state)),getContactStatusInfo:async r=>e.get(`${t}/users/${r}/presences`).then((e=>e)),getLineState:async r=>e.get(`${t}/users/${r}/presences`).then((e=>Profile.getLinesState(e.lines))),async getMultipleLineState(r){const n={},i=r||[];if(i.length>MAX_PRESENCE_FETCHED){const e=i.reduce(((e,t,r)=>(r%MAX_PRESENCE_FETCHED==0&&e.push(this.getMultipleLineState(i.slice(r,r+MAX_PRESENCE_FETCHED))),e)),[]);return(await Promise.all(e)).flat()}return i.length&&(n.user_uuid=i.join(",")),e.get(`${t}/users/presences`,n).then((e=>e.items))},getUserRooms:async()=>e.get(`${t}/users/me/rooms`).then(ChatRoom.parseMany),createRoom:async(r,n)=>e.post(`${t}/users/me/rooms`,{name:r,users:n}).then(ChatRoom.parse),getRoomMessages:async(r,n)=>{const i=ApiRequester.getQueryString(n||{});return e.get(`${t}/users/me/rooms/${r}/messages${i.length?`?${i}`:""}`).then((e=>ChatMessage.parseMany(e)))},sendRoomMessage:async(r,n)=>e.post(`${t}/users/me/rooms/${r}/messages`,n).then(ChatMessage.parse),getMessages:async r=>e.get(`${t}/users/me/rooms/messages`,r)});class IndirectTransfer{status;id;sourceId;destinationId;constructor({sourceId:e,destinationId:t,status:r,id:n}){this.sourceId=e,this.destinationId=t,this.status=r,this.id=n}static parseFromCallSession(e,t){return new IndirectTransfer({sourceId:e.getId(),destinationId:t.getId()})}static parseFromApi(e){return new IndirectTransfer({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){updateFrom(this,e)}static newFrom(e){return newFrom(e,IndirectTransfer)}}class MeetingStatus{type;full;constructor({full:e}={}){this.full=e,this.type="MeetingStatus"}static parse(e){return new MeetingStatus({full:e.full})}}var calldMethods=(e,t)=>({updatePresence:r=>e.put(`${t}/users/me/presences`,{presence:r},null,ApiRequester.successResponseParser),listMessages:(r,n)=>{const i={};return r&&(i.participant_user_uuid=r),n&&(i.limit=n),e.get(`${t}/users/me/chats`,i).then((e=>ChatMessage.parseMany(e)))},sendMessage:(r,n,i)=>{const s={alias:r,msg:n,to:i};return e.post(`${t}/users/me/chats`,s,null,ApiRequester.successResponseParser)},makeCall:(r,n,i,s=!1)=>{const o={from_mobile:n,extension:r};return i&&(o.line_id=i),s&&(o.all_lines=!0),e.post(`${t}/users/me/calls`,o)},cancelCall:r=>e.delete(`${t}/users/me/calls/${r}`,null),listCalls:()=>e.get(`${t}/users/me/calls`,null).then((e=>Call.parseMany(e.items))),relocateCall(r,n,i,s){const o={completions:["answer"],destination:n,initiator_call:r,auto_answer:!0};return(i||s)&&(o.location={}),i&&(o.location.line_id=i),s&&(o.location.contact=s),e.post(`${t}/users/me/relocates`,o).then((e=>Relocation.parse(e)))},listVoicemails:()=>e.get(`${t}/users/me/voicemails`).then((e=>Voicemail.parseMany(e))),deleteVoicemail:r=>e.delete(`${t}/users/me/voicemails/messages/${r}`),getVoicemailUrl:r=>{const n={token:e.token};return e.computeUrl("get",`${t}/users/me/voicemails/messages/${r.id}/recording`,n)},fetchSwitchboardHeldCalls:r=>e.get(`${t}/switchboards/${r}/calls/held`),holdSwitchboardCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}`,null,null,ApiRequester.successResponseParser),answerSwitchboardHeldCall:(r,n,i=null)=>e.put(`${t}/switchboards/${r}/calls/held/${n}/answer${i?`?line_id=${i}`:""}`),fetchSwitchboardQueuedCalls:r=>e.get(`${t}/switchboards/${r}/calls/queued`),answerSwitchboardQueuedCall:(r,n,i=null)=>e.put(`${t}/switchboards/${r}/calls/queued/${n}/answer${i?`?line_id=${i}`:""}`),sendFax:(r,n,i)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},o=ApiRequester.getQueryString({extension:r,caller_id:i});return e.post(`${t}/users/me/faxes?${o}`,n,s)},getConferenceParticipantsAsUser:async r=>e.get(`${t}/users/me/conferences/${r}/participants`),getMeetingParticipantsAsUser:async r=>e.get(`${t}/users/me/meetings/${r}/participants`),banMeetingParticipant:(r,n)=>e.delete(`${t}/users/me/meetings/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),listTrunks:()=>e.get(`${t}/trunks`),mute:r=>e.put(`${t}/users/me/calls/${r}/mute/start`,null,null,ApiRequester.successResponseParser),unmute:r=>e.put(`${t}/users/me/calls/${r}/mute/stop`,null,null,ApiRequester.successResponseParser),hold:r=>e.put(`${t}/users/me/calls/${r}/hold/start`,null,null,ApiRequester.successResponseParser),resume:r=>e.put(`${t}/users/me/calls/${r}/hold/stop`,null,null,ApiRequester.successResponseParser),transferCall:(r,n,i)=>e.post(`${t}/users/me/transfers`,{initiator_call:r,exten:n,flow:i}).then(IndirectTransfer.parseFromApi),confirmCallTransfer:r=>e.put(`${t}/users/me/transfers/${r}/complete`,null,null,ApiRequester.successResponseParser),cancelCallTransfer:r=>e.delete(`${t}/users/me/transfers/${r}`,null,null,ApiRequester.successResponseParser),sendDTMF:(r,n)=>e.put(`${t}/users/me/calls/${r}/dtmf?digits=${encodeURIComponent(n)}`,null,null,ApiRequester.successResponseParser),isAhHocConferenceAPIEnabled:()=>e.head(`${t}/users/me/conferences/adhoc`,null,null,ApiRequester.successResponseParser),createAdHocConference:(r,n)=>e.post(`${t}/users/me/conferences/adhoc`,{host_call_id:r,participant_call_ids:n}),addAdHocConferenceParticipant:(r,n)=>e.put(`${t}/users/me/conferences/adhoc/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),removeAdHocConferenceParticipant:(r,n)=>e.delete(`${t}/users/me/conferences/adhoc/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),deleteAdHocConference:r=>e.delete(`${t}/users/me/conferences/adhoc/${r}`,null,null,ApiRequester.successResponseParser),startRecording:r=>e.put(`${t}/users/me/calls/${r}/record/start`,null,null,ApiRequester.successResponseParser),stopRecording:r=>e.put(`${t}/users/me/calls/${r}/record/stop`,null,null,ApiRequester.successResponseParser),pauseRecording:r=>e.put(`${t}/users/me/calls/${r}/record/pause`,null,null,ApiRequester.successResponseParser),resumeRecording:r=>e.put(`${t}/users/me/calls/${r}/record/resume`,null,null,ApiRequester.successResponseParser),guestGetMeetingStatus:r=>e.get(`${t}/guests/me/meetings/${r}/status`).then(MeetingStatus.parse)});class Agent{context;extension;id;logged;number;paused;pausedReason;static parse(e){return new Agent({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:r,logged:n,number:i,paused:s,pausedReason:o}){this.context=e,this.extension=t,this.id=r,this.logged=n,this.number=i,this.paused=s,this.pausedReason=o}}var agentdMethods=(e,t)=>({getAgent:r=>e.get(`${t}/agents/by-id/${r}`,null).then(Agent.parse),login:(r,n,i)=>e.post(`${t}/agents/by-number/${r}/login`,{context:n,extension:i},null,ApiRequester.successResponseParser),loginWithLineId:r=>e.post(`${t}/users/me/agents/login`,{line_id:r},null,ApiRequester.successResponseParser),logout:r=>e.post(`${t}/agents/by-number/${r}/logoff`,null,null,ApiRequester.successResponseParser),pause:r=>e.post(`${t}/agents/by-number/${r}/pause`,{reason:"songbird_reason"},null,ApiRequester.successResponseParser),resume:r=>e.post(`${t}/agents/by-number/${r}/unpause`,null,null,ApiRequester.successResponseParser),getStatus:()=>e.get(`${t}/users/me/agents`,null).then(Agent.parse),staticLogout:()=>e.post(`${t}/users/me/agents/logoff`,null,null,ApiRequester.successResponseParser),staticPause:()=>e.post(`${t}/users/me/agents/pause`,{reason:"songbird_reason"},null,ApiRequester.successResponseParser),staticResume:()=>e.post(`${t}/users/me/agents/unpause`,null,null,ApiRequester.successResponseParser)});class Subscription{name;events;config;uuid;service;eventsUserUuid;eventsWazoUuid;metadata;ownerTenantUuid;ownerUserUuid;static parse(e){return new Subscription({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=>Subscription.parse(e)))}constructor({name:e,events:t,config:r,uuid:n,service:i,eventsUserUuid:s,eventsWazoUuid:o,metadata:a,ownerTenantUuid:d,ownerUserUuid:c}){this.name=e,this.events=t,this.config=r,this.uuid=n,this.service=i,this.eventsUserUuid=s,this.eventsWazoUuid=o,this.metadata=a,this.ownerTenantUuid=d,this.ownerUserUuid=c}}var webhookdMethods=(e,t)=>({getSubscriptions:()=>e.get(`${t}/users/me/subscriptions`).then(Subscription.parseMany),getSubscription:r=>e.get(`${t}/users/me/subscriptions/${r}`).then(Subscription.parse),createSubscription:r=>e.post(`${t}/users/me/subscriptions`,r),removeSubscription:r=>e.delete(`${t}/users/me/subscriptions/${r}`)}),amidMethods=(e,t)=>({action:(r,n={})=>e.post(`${t}/action/${r}`,n),getAors:async r=>{try{const n=await e.post(`${t}/action/PJSIPShowEndpoint`,{Endpoint:r})||[];return n?n.filter((e=>"ContactStatusDetail"===e.Event)):[]}catch{return[]}}});const AUTH_VERSION="0.1",APPLICATION_VERSION="1.0",CONFD_VERSION="1.1",CTIDNG_VERSION="1.0",DIRD_VERSION="0.1",CALL_LOGD_VERSION="1.0",CHATD_VERSION="1.0",CALLD_VERSION="1.0",AGENTD_VERSION="1.0",WEBHOOKD_VERSION="1.0",AMID_VERSION="1.0",logger$a=IssueReporter$1?IssueReporter$1.loggerFor("api"):console;class ApiClient{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:r,clientId:n,isMobile:i=!1,fetchOptions:s}){this.updateParameters({server:e,agent:t,clientId:n,fetchOptions:s}),this.refreshToken=r,this.isMobile=i||!1}initializeEndpoints(){this.auth=authMethods(this.client,`auth/${AUTH_VERSION}`),this.application=applicationMethods(this.client,`calld/${APPLICATION_VERSION}/applications`),this.confd=confdMethods(this.client,`confd/${CONFD_VERSION}`),this.ctidNg=ctidNgMethods(this.client,`ctid-ng/${CTIDNG_VERSION}`),this.dird=dirdMethods(this.client,`dird/${DIRD_VERSION}`),this.callLogd=callLogdMethods(this.client,`call-logd/${CALL_LOGD_VERSION}`),this.chatd=chatdMethods(this.client,`chatd/${CHATD_VERSION}`),this.calld=calldMethods(this.client,`calld/${CALLD_VERSION}`),this.agentd=agentdMethods(this.client,`agentd/${AGENTD_VERSION}`),this.webhookd=webhookdMethods(this.client,`webhookd/${WEBHOOKD_VERSION}`),this.amid=amidMethods(this.client,`amid/${AMID_VERSION}`)}updateParameters({server:e,agent:t,clientId:r,fetchOptions:n}){const i=this.refreshTokenCallback.bind(this);this.client=new ApiRequester({server:e,agent:t,refreshTokenCallback:i,clientId:r,fetchOptions:n}),this.initializeEndpoints()}async forceRefreshToken(){return logger$a.info("forcing refresh token, calling callback"),this.refreshTokenCallback()}async refreshTokenCallback(){if(logger$a.info("refresh token callback called",{refreshToken:obfuscateToken(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?(logger$a.info("token refreshed",{token:obfuscateToken(e.token)}),this.onRefreshToken&&this.onRefreshToken(e.token,e),this.setToken(e.token),e.token):null}catch(e){logger$a.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 setApiClientId=(e,t=null)=>{global.wazoClientId[String(t)]=e},setCurrentServer=e=>{global.wazoCurrentServer=e},setApiToken=(e,t=null)=>{global.wazoClientToken[String(t)]=e},setRefreshToken=(e,t=null)=>{global.wazoRefreshToken[String(t)]=e},setRefreshTenantId=(e,t=null)=>{console.warn("Use of `setRefreshTenantId` is deprecated, please use `setRefreshDomainName` instead"),global.wazoRefreshTenantId[String(t)]=e},setRefreshDomainName=(e,t=null)=>{global.wazoRefreshDomainName[String(t)]=e},setOnRefreshToken=(e,t=null)=>{global.wazoOnRefreshToken[String(t)]=e},setOnRefreshTokenError=(e,t=null)=>{global.wazoOnRefreshTokenError[String(t)]=e},setRefreshExpiration=(e,t=null)=>{global.wazoRefreshExpiration[String(t)]=e},setIsMobile=(e,t=null)=>{global.wazoIsMobile[String(t)]=e},setRequestTimeout=(e,t=null)=>{global.wazoRequestApiTimeout[String(t)]=e},setFetchOptions=(e,t=null)=>{global.wazoFetchOptions[String(t)]=e},getFetchOptions=(e=null)=>(e?global.wazoFetchOptions[e]:global.wazoFetchOptions.null)||global.wazoFetchOptions.null,fillClient=e=>{const{server:t,token:r,clientId:n}=e.client,i=global.wazoRefreshTenantId[t]||global.wazoRefreshTenantId.null||e.refreshTenantId,s=global.wazoRequestApiTimeout[t]||global.wazoRequestApiTimeout.null;return e.setToken(global.wazoClientToken[t]||global.wazoClientToken.null||r),e.setClientId(global.wazoClientId[t]||global.wazoClientId.null||n),e.setRefreshToken(global.wazoRefreshToken[t]||global.wazoRefreshToken.null||e.refreshToken),i&&e.setRefreshTenantId(i),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 getApiClient=(e=null)=>{const t=e||global.wazoCurrentServer||"";return t in global.wazoClients||(global.wazoClients[t]=new ApiClient({server:t})),fillClient(global.wazoClients[t])};class InvalidSubscription extends Error{}class InvalidAuthorization extends Error{}class NoTenantIdError extends Error{}class NoDomainNameError extends Error{}const logger$9=IssueReporter$1.loggerFor("simple-auth");class Auth{clientId;expiration;minSubscriptionType;authorizationName;host;session;onRefreshTokenCallback;onRefreshTokenCallbackError;onHostFromHeadersCallback;authenticated;mobile;BACKEND_WAZO;BACKEND_LDAP;shouldCheckUserUuidHeader;constructor(){this.expiration=DETAULT_EXPIRATION,this.authenticated=!1,this.minSubscriptionType=null,this.BACKEND_WAZO=DEFAULT_BACKEND_USER,this.BACKEND_LDAP=BACKEND_LDAP_USER,this.shouldCheckUserUuidHeader=!0}init(e,t,r,n,i){this.clientId=e,this.expiration=t,this.minSubscriptionType=void 0===r?null:r,this.authorizationName=n,this.host=null,this.session=null,this.mobile=i||!1,setApiClientId(this.clientId),setRefreshExpiration(this.expiration),setOnRefreshToken(((e,t)=>{logger$9.info("on refresh token done",{token:obfuscateToken(e)}),setApiToken(e),Wazo$1.Websocket.updateToken(e),this.onRefreshTokenCallback&&this.onRefreshTokenCallback(e,t)})),setOnRefreshTokenError((e=>{logger$9.error("on refresh token error",e),this.onRefreshTokenCallbackError&&this.onRefreshTokenCallbackError(e)}))}setFetchOptions(e){setFetchOptions(e)}async logIn(e,t,r,n){let i=null,s=null;if("string"==typeof n&&(i=n),n&&"object"==typeof n&&(s=n.domainName),r&&r!==this.BACKEND_WAZO&&!i&&!s){if(!i)throw new NoTenantIdError("No tenant id");if(!s)throw new NoDomainNameError("No domain name")}this.authenticated=!1,this.session=null;const o=await getApiClient().auth.logIn({username:e,password:t,backend:r,tenantId:i,domainName:s,expiration:this.expiration,mobile:this.mobile});if(o){const e=o.getHostFromHeader();e&&(this.setHost(e),this.onHostFromHeadersCallback&&this.onHostFromHeadersCallback(e))}return r&&getApiClient().setRefreshBackend(r),i&&getApiClient().setRefreshTenantId(i),s&&getApiClient().setRefreshDomainName(s),this._onAuthenticated(o)}async logInViaRefreshToken(e){const t=await getApiClient().auth.refreshToken(e,"",this.expiration,this.mobile);return this._onAuthenticated(t)}async validateToken(e,t){if(e){t&&setRefreshToken(t);try{const t=await getApiClient().auth.authenticate(e);return this._onAuthenticated(t)}catch(e){logger$9.error("on validate token error",e),console.warn(e)}}}async generateNewToken(e){return getApiClient().auth.refreshToken(e,"",this.expiration)}async logout(e=!0){try{Wazo$1.Websocket.close(!0),this.clientId&&e&&await getApiClient().auth.deleteRefreshToken(this.clientId)}catch(e){}try{this.session?.token&&await getApiClient().auth.logOut(this.session.token)}catch(e){}setApiToken(null),setRefreshToken(null),this.session=null,this.authenticated=!1,setFetchOptions({})}setOnHostFromHeaders(e){this.onHostFromHeadersCallback=e}setOnRefreshToken(e){this.onRefreshTokenCallback=e}setOnRefreshTokenError(e){this.onRefreshTokenCallbackError=e}checkAuthorizations(e,t){if(!t)return;const{authorizations:r}=e;if(!r.find((e=>e.rules.find((e=>e.name===t)))))throw new InvalidAuthorization(`No authorization '${t||""}' found for your account.`)}checkSubscription(e,t){const r=e.profile?.subscriptionType||null;if(null===r||r<=t){throw new InvalidSubscription(`Invalid subscription ${r||"n/a"}, required at least ${t}`)}}setHost(e){this.host=e,setCurrentServer(e)}setApiToken(e){setApiToken(e)}setRefreshToken(e){setRefreshToken(e)}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead."),setRefreshTenantId(e),getApiClient().setRefreshTenantId(e)}setRefreshDomainName(e){setRefreshDomainName(e),getApiClient().setRefreshDomainName(e)}setRequestTimeout(e){setRequestTimeout(e),getApiClient().setRequestTimeout(e)}forceRefreshToken(){return getApiClient().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,setApiClientId(this.clientId)}getName(){return`${this.getFirstName()} ${this.getLastName()}`}async setHttpUserUuidHeader(e){if(!e)return;const t={...getFetchOptions()?.headers||{},"X-User-UUID":e};try{this.shouldCheckUserUuidHeader&&await getApiClient().client.head("auth/0.1/status",null,t),setFetchOptions({...getFetchOptions(),headers:t})}catch(e){}}async _onAuthenticated(e){if(this.authenticated&&this.session)return this.session;const t=e;if(await this.setHttpUserUuidHeader(t.uuid),!t)return null;setApiToken(t.token),t.refreshToken&&setRefreshToken(t.refreshToken);try{const[e,{wazo_version:r}]=await Promise.all([getApiClient().confd.getUser(t.uuid),getApiClient().confd.getInfos()]);t.engineVersion=r,t.profile=e,this.checkAuthorizations(t,this.authorizationName),null!==this.minSubscriptionType&&this.checkSubscription(t,+this.minSubscriptionType)}catch(e){throw logger$9.error("on authenticated error",e),this.clientId&&await getApiClient().auth.deleteRefreshToken(this.clientId),t&&await getApiClient().auth.logOut(t.token),e}try{const e=t.profile?.lines.filter((e=>!e.endpointSccp)).map((e=>String(e.id))),r=await getApiClient().confd.getUserLinesSip(t.uuid,e);t.profile.sipLines=r.filter((e=>e instanceof SipLine))}catch(e){}return this.authenticated=!0,Wazo$1.Websocket.open(this.host,t),this.session=t,t}}global.wazoAuthInstance||(global.wazoAuthInstance=new Auth);var Auth$1=global.wazoAuthInstance;class AdHocAPIConference{phone;host;participants;started;finished;conferenceId;answerTime;muted;paused;constructor({phone:e,host:t,participants:r,started:n,finished:i,answerTime:s,conferenceId:o,muted:a,paused:d}){this.phone=e,this.host=t,this.participants=r||{},this.started=n||!1,this.finished=i||!1,this.answerTime=s,this.conferenceId=o||"",this.muted=a||!1,this.paused=d||!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 getApiClient().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],r={...this.participants,[t]:e};return await getApiClient().calld.addAdHocConferenceParticipant(this.conferenceId,t),new AdHocAPIConference({...this,participants:r})}participantHasLeft(e){return delete this.participants[e.getId()],new AdHocAPIConference({...this,participants:this.participants})}hasParticipants(){return Object.keys(this.participants).length>0}mute(){return this.muted=!0,this.phone.mute(this.host),new AdHocAPIConference({...this})}unmute(){return this.muted=!1,this.phone.unmute(this.host),new AdHocAPIConference({...this})}hold(){return this.paused=!0,this.phone.hold(this.host),new AdHocAPIConference({...this})}resume(){return this.paused=!1,this.phone.resume(this.host),new AdHocAPIConference({...this})}isOnHold(){return this.paused}isMuted(){return this.muted}async hangup(){return await getApiClient().calld.deleteAdHocConference(this.conferenceId),new AdHocAPIConference({...this,finished:!0,participant:[]})}async removeParticipant(e){const t=e.getTalkingToIds()[0];return delete this.participants[t],await getApiClient().calld.removeAdHocConferenceParticipant(this.conferenceId,t),new AdHocAPIConference({...this,participants:this.participants})}}class Exception extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class ContentTypeUnsupportedError extends Exception{constructor(e){super(e||"Unsupported content type.")}}class RequestPendingError extends Exception{constructor(e){super(e||"Request pending.")}}class SessionDescriptionHandlerError extends Exception{constructor(e){super(e||"Unspecified session description handler error.")}}class SessionTerminatedError extends Exception{constructor(){super("The session has terminated.")}}class StateTransitionError extends Exception{constructor(e){super(e||"An error occurred during state transition.")}}class Ack{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Bye{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 Cancel{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class EmitterImpl{constructor(){this.listeners=new Array}addListener(e,t){const r=t=>{this.removeListener(r),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(r):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 Info{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 Parameters{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 NameAddrHeader extends Parameters{constructor(e,t,r){super(r),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 NameAddrHeader(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 URI extends Parameters{constructor(e="sip",t,r,n,i,s){if(super(i||{}),this.headers={},!r)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:r,port:n},this.normal={scheme:e.toLowerCase(),user:t,host:r.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 URI(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 r=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&r.push(e+"="+this.headers[e][t]);return r.length>0&&(t+="?"+r.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"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length;let i="";for(let e=0;e<n;e++)0!==e&&(i+="-"),i+=r[e].charAt(0).toUpperCase()+r[e].substring(1);return t[i]&&(i=t[i]),i}}function equivalentURI(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 r=Object.keys(e.parameters),n=Object.keys(t.parameters);return!!r.filter((e=>n.includes(e))).every((r=>e.parameters[r]===t.parameters[r]))&&(!!["user","ttl","method","transport"].every((r=>e.hasParam(r)&&t.hasParam(r)||!e.hasParam(r)&&!t.hasParam(r)))&&!!["maddr"].every((r=>e.hasParam(r)&&t.hasParam(r)||!e.hasParam(r)&&!t.hasParam(r))))}(e,t))return!1;const r=Object.keys(e.headers),n=Object.keys(t.headers);if(0!==r.length||0!==n.length){if(r.length!==n.length)return!1;const i=r.filter((e=>n.includes(e)));if(i.length!==n.length)return!1;if(!i.every((r=>e.headers[r].length&&t.headers[r].length&&e.headers[r][0]===t.headers[r][0])))return!1}return!0}function peg$padEnd(e,t,r){return r=r||" ",e.length>t?e:(t-=e.length,e+(r+=r.repeat(t)).slice(0,t))}class SyntaxError extends Error{constructor(e,t,r,n){super(),this.message=e,this.expected=t,this.found=r,this.location=n,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,SyntaxError.prototype):this.__proto__=SyntaxError.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,SyntaxError)}static buildMessage(e,t){function r(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"+r(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+r(e)))}function i(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"+r(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+r(e)))}function s(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":const t=e.parts.map((e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(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 r,n;if(t.sort(),t.length>0){for(r=1,n=1;r<t.length;r++)t[r-1]!==t[r]&&(t[n]=t[r],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 "+(((o=t)?'"'+n(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let r,n=null;for(r=0;r<e.length;r++)if(e[r].source===this.location.source){n=e[r].text.split(/\r\n|\n|\r/g);break}let i=this.location.start,s=this.location.source+":"+i.line+":"+i.column;if(n){let e=this.location.end,r=peg$padEnd("",i.line.toString().length," "),o=n[i.line-1],a=i.line===e.line?e.column:o.length+1;t+="\n --\x3e "+s+"\n"+r+" |\n"+i.line+" | "+o+"\n"+r+" | "+peg$padEnd("",i.column-1," ")+peg$padEnd("",a-i.column,"^")}else t+="\n at "+s}return t}}function peg$parse(e,t){const r={},n=(t=void 0!==t?t:{}).grammarSource,i={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 o=["\r\n",S("\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)," ",S(" ",!1),"\t",S("\t",!1),/^[a-zA-Z0-9]/,y([["a","z"],["A","Z"],["0","9"]],!1,!1),";",S(";",!1),"/",S("/",!1),"?",S("?",!1),":",S(":",!1),"@",S("@",!1),"&",S("&",!1),"=",S("=",!1),"+",S("+",!1),"$",S("$",!1),",",S(",",!1),"-",S("-",!1),"_",S("_",!1),".",S(".",!1),"!",S("!",!1),"~",S("~",!1),"*",S("*",!1),"'",S("'",!1),"(",S("(",!1),")",S(")",!1),"%",S("%",!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),"`",S("`",!1),"<",S("<",!1),">",S(">",!1),"\\",S("\\",!1),"[",S("[",!1),"]",S("]",!1),"{",S("{",!1),"}",S("}",!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 URI(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 URI(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",S("sips",!0),"sip",S("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(m().slice(0,-1))},function(){(t=t||{data:{}}).data.password=m()},function(){return(t=t||{data:{}}).data.host=m(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",m()},/^[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",m()},"::",S("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},function(){return(t=t||{data:{}}).data.host_type="IPv4",m()},"25",S("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",S("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",S("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=",S("transport=",!0),"udp",S("udp",!0),"tcp",S("tcp",!0),"sctp",S("sctp",!0),"tls",S("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",S("user=",!0),"phone",S("phone",!0),"ip",S("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",S("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",S("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",S("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",S("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new URI(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)},"//",S("//",!1),function(){(t=t||{data:{}}).data.scheme=m()},S("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=m()},"INVITE",S("INVITE",!1),"ACK",S("ACK",!1),"VXACH",S("VXACH",!1),"OPTIONS",S("OPTIONS",!1),"BYE",S("BYE",!1),"CANCEL",S("CANCEL",!1),"REGISTER",S("REGISTER",!1),"SUBSCRIBE",S("SUBSCRIBE",!1),"NOTIFY",S("NOTIFY",!1),"REFER",S("REFER",!1),"PUBLISH",S("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=m(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=m()},function(){(t=t||{data:{}}).data=m()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e<r;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 NameAddrHeader(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:d,offset:f().start.offset,parsed:e})},function(e){'"'===(e=m().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",S("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",S("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",S("0",!1),function(){return parseFloat(m())},function(e,r){(t=t||{data:{}}).data.params||(t.data.params={}),r=null===r?void 0:r[1],t.data.params[e.toLowerCase()]=r},"render",S("render",!0),"session",S("session",!0),"icon",S("icon",!0),"alert",S("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=m().toLowerCase())},"handling",S("handling",!0),"optional",S("optional",!0),"required",S("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=m()},"text",S("text",!0),"image",S("image",!0),"audio",S("audio",!0),"video",S("video",!0),"application",S("application",!0),"message",S("message",!0),"multipart",S("multipart",!0),"x-",S("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 NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",S("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 NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},"digest",S("Digest",!0),"realm",S("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",S("domain",!0),"nonce",S("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",S("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",S("stale",!0),"true",S("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",S("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",S("algorithm",!0),"md5",S("MD5",!0),"md5-sess",S("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",S("qop",!0),"auth-int",S("auth-int",!0),"auth",S("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,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e<r;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 NameAddrHeader(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:d,offset:f().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new NameAddrHeader(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",S("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",S("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",S("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",S("active",!0),"pending",S("pending",!0),"terminated",S("terminated",!0),function(){(t=t||{data:{}}).data.state=m()},"reason",S("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",S("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",S("deactivated",!0),"probation",S("probation",!0),"rejected",S("rejected",!0),"timeout",S("timeout",!0),"giveup",S("giveup",!0),"noresource",S("noresource",!0),"invariant",S("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",S("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",S("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",S("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",S("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",S("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},S("UDP",!0),S("TCP",!0),S("TLS",!0),S("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=m()},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",S("refresher",!1),"uas",S("uas",!1),"uac",S("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",S("stuns",!0),"stun",S("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",S("?transport=",!1),"turns",S("turns",!0),"turn",S("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=m()},"Referred-By",S("Referred-By",!1),"b",S("b",!1),"cid",S("cid",!1)],a=[_('2 ""6 7!'),_('4"""5!7#'),_('4$""5!7%'),_('4&""5!7\''),_(";'.# &;("),_('4(""5!7)'),_('4*""5!7+'),_('2,""6,7-'),_('2.""6.7/'),_('40""5!71'),_('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'),_(";).# &;,"),_('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),_('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),_('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),_(';.." &"'),_("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),_('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_('4\\""5!7].# &;3'),_('4^""5!7_'),_('4`""5!7a'),_(';!.) &4b""5!7c'),_('%$;).• &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&&&#/"!&,)'),_('%$;).‰ &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&&&#/"!&,)'),_('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.) &;\'.# &;('),_('%$;).ī &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&&&#/"!&,)'),_("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),_("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),_("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),_("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),_("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),_('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),_('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),_("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),_("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),_("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),_("%;//0#;&/'$8\":~\" )(\"'#&'#"),_("%;&/0#;//'$8\":~\" )(\"'#&'#"),_("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),_('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),_("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),_("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),_(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),_('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),_("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),_("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),_('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),_('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),_("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),_('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'),_('%$;+._ &;-.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!:–! )'),_('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:—! )"),_('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),_('$4™""5!7š/,#0)*4™""5!7š&&&#'),_('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),_('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),_('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),_('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),_("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),_('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),_('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),_(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),_('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),_('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),_('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),_('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),_('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),_('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),_('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),_('%$;j/&#0#*;j&&&#/"!&,)'),_('%$;j/&#0#*;j&&&#/"!&,)'),_(";k.) &;+.# &;-"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),_('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),_('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),_("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),_("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),_(";‘.# &;r"),_("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),_(";M.# &;t"),_("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),_('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),_('%24""6475/,#;{/#$+")("\'#&\'#'),_("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),_(";*.) &;+.# &;-"),_(';+. &;-.‰ &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#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_("$;~0#*;~&"),_(';+.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'),_('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),_(";.# &;‚"),_('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),_('$;+.ƒ &;-.} &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&&&#'),_("$;y0#*;y&"),_('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),_('2Õ""6Õ7Ö'),_('2×""6×7Ø'),_('2Ù""6Ù7Ú'),_('2Û""6Û7Ü'),_('2Ý""6Ý7Þ'),_('2ß""6ß7à'),_('2á""6á7â'),_('2ã""6ã7ä'),_('2å""6å7æ'),_('2ç""6ç7è'),_('2é""6é7ê'),_("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),_("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%;“/' 8!:ì!! )"),_("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),_("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),_("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),_("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),_("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),_("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),_("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),_(";œ.) &;.# &; "),_("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),_("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),_('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),_('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),_(";6.) &;T.# &;H"),_("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),_(";¥.# &; "),_('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),_("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),_("%;©/& 8!:č! )"),_("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_(";«.# &;¬"),_('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),_('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),_(";6.# &;®"),_('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),_(";­.# &;6"),_("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),_(";6.# &;H"),_("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),_("%;ž/' 8!:ğ!! )"),_('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),_('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),_(";¹.# &; "),_("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),_("%;ž/' 8!:Ħ!! )"),_("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),_(";¾"),_("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),_("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),_(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),_("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),_("%;I/' 8!:Ĭ!! )"),_("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),_(";t.# &;w"),_("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),_("%;I/' 8!:ı!! )"),_("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),_('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),_('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),_('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),_('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),_("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),_("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),_("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),_('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),_("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),_("%;–/& 8!:Ő! )"),_('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),_('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),_("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),_("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),_("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),_('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'),_(';1." &"'),_('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),_("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),_(";¹.# &; "),_("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),_("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),_("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),_("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),_("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),_("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),_("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),_('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),_('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),_('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),_('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),_(";¾"),_('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),_(";ô.# &; "),_('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),_('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),_("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),_("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),_("$;%0#*;%&"),_("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),_('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),_('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),_(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),_('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?'),_('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),_('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),_("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),_("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),_("%;ă/,#;ă/#$+\")(\"'#&'#"),_("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),_("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),_('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),_(";™.# &;L"),_("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),_("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let d=0,c=0;const l=[{line:1,column:1}];let u,h=0,g=[],p=0;if(void 0!==t.startRule){if(!(t.startRule in i))throw new Error("Can't start parsing from rule \""+t.startRule+'".');s=i[t.startRule]}function m(){return e.substring(c,d)}function f(){return E(c,d)}function S(e,t){return{type:"literal",text:e,ignoreCase:t}}function y(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function b(t){let r,n=l[t];if(n)return n;for(r=t-1;!l[r];)r--;for(n=l[r],n={line:n.line,column:n.column};r<t;)10===e.charCodeAt(r)?(n.line++,n.column=1):n.column++,r++;return l[t]=n,n}function E(e,t){const r=b(e),i=b(t);return{source:n,start:{offset:e,line:r.line,column:r.column},end:{offset:t,line:i.line,column:i.column}}}function v(e){d<h||(d>h&&(h=d,g=[]),g.push(e))}function _(e){return e.split("").map((e=>e.charCodeAt(0)-32))}if(t.data={},u=function t(n){const i=a[n];let s=0;const l=[];let u=i.length;const h=[],g=[];let m;for(;;){for(;s<u;)switch(i[s]){case 0:g.push(o[i[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(r),s++;break;case 4:g.push([]),s++;break;case 5:g.push(d),s++;break;case 6:g.pop(),s++;break;case 7:d=g.pop(),s++;break;case 8:g.length-=i[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-i[s+1],i[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),d)),s++;break;case 13:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 14:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]===r?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 15:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]!==r?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 16:g[g.length-1]!==r?(h.push(u),l.push(s),u=s+2+i[s+1],s+=2):s+=2+i[s+1];break;case 17:h.push(u),l.push(s+3+i[s+1]+i[s+2]),e.length>d?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 18:h.push(u),l.push(s+4+i[s+2]+i[s+3]),e.substr(d,o[i[s+1]].length)===o[i[s+1]]?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 19:h.push(u),l.push(s+4+i[s+2]+i[s+3]),e.substr(d,o[i[s+1]].length).toLowerCase()===o[i[s+1]]?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 20:h.push(u),l.push(s+4+i[s+2]+i[s+3]),o[i[s+1]].test(e.charAt(d))?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 21:g.push(e.substr(d,i[s+1])),d+=i[s+1],s+=2;break;case 22:g.push(o[i[s+1]]),d+=o[i[s+1]].length,s+=2;break;case 23:g.push(r),0===p&&v(o[i[s+1]]),s+=2;break;case 24:c=g[g.length-1-i[s+1]],s+=2;break;case 25:c=d,s++;break;case 26:m=i.slice(s+4,s+4+i[s+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-i[s+2],i[s+2],o[i[s+1]].apply(null,m)),s+=4+i[s+3];break;case 27:g.push(t(i[s+1])),s+=2;break;case 28:p++,s++;break;case 29:p--,s++;break;default:throw new Error("Invalid opcode: "+i[s]+".")}if(!(h.length>0))break;u=h.pop(),s=l.pop()}return g[0]}(s),u!==r&&d===e.length)return u;throw u!==r&&d<e.length&&v({type:"end"}),T=g,R=h<e.length?e.charAt(h):null,$=h<e.length?E(h,h+1):E(h,h),new SyntaxError(SyntaxError.buildMessage(T,R),T,R,$);var T,R,$}const parse=peg$parse;var Grammar;!function(e){e.parse=function(e,t){const r={startRule:t};try{parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){const r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){const r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(Grammar=Grammar||(Grammar={}));const REASON_PHRASE={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 createRandomToken(e,t=32){let r="";for(let n=0;n<e;n++){r+=Math.floor(Math.random()*t).toString(t)}return r}function getReasonPhrase(e){return REASON_PHRASE[e]||""}function newTag(){return createRandomToken(10)}function headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length;let i="";for(let e=0;e<n;e++)0!==e&&(i+="-"),i+=r[e].charAt(0).toUpperCase()+r[e].substring(1);return t[i]&&(i=t[i]),i}function utf8Length(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class IncomingMessage{constructor(){this.headers={}}addHeader(e,t){const r={raw:t};e=headerize(e),this.headers[e]?this.headers[e].push(r):this.headers[e]=[r]}getHeader(e){const t=this.headers[headerize(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[headerize(e)],r=[];if(!t)return[];for(const e of t)r.push(e.raw);return r}hasHeader(e){return!!this.headers[headerize(e)]}parseHeader(e,t=0){if(e=headerize(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const r=this.headers[e][t],n=r.raw;if(r.parsed)return r.parsed;const i=Grammar.parse(n,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(r.parsed=i,i)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[headerize(e)]=[{raw:t}]}toString(){return this.data}}class IncomingRequestMessage extends IncomingMessage{constructor(){super()}}class IncomingResponseMessage extends IncomingMessage{constructor(){super()}}class OutgoingRequestMessage{constructor(e,t,r,n,i,s,o){this.headers={},this.extraHeaders=[],this.options=OutgoingRequestMessage.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),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()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=r.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:newTag(),this.from=OutgoingRequestMessage.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=n.clone(),this.toTag=this.options.toTag,this.to=OutgoingRequestMessage.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+createRandomToken(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,r){const n={};return r&&(n.tag=r),new NameAddrHeader(e,t,n)}getHeader(e){const t=this.headers[headerize(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=[],r=this.headers[headerize(e)];if(r)for(const e of r)t.push(e);else{const r=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)r.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[headerize(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[headerize(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let r="SIP/2.0/"+t;r+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(r+=";rport"),this.setHeader("via",r),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 r of this.headers[t])e+=t+": "+r+"\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: "+utf8Length(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: "+utf8Length(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 contentTypeToContentDisposition(e){return"application/sdp"===e?"session":"render"}function fromBodyLegacy(e){const t="string"==typeof e?e:e.body,r="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:contentTypeToContentDisposition(r),contentType:r,content:t}}function isBody(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function getBody(e){let t,r,n;if(e instanceof IncomingRequestMessage&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,r=e.parseHeader("Content-Type"),n=e.body}if(e instanceof IncomingResponseMessage&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,r=e.parseHeader("Content-Type"),n=e.body}if(e instanceof OutgoingRequestMessage&&e.body)if(t=e.getHeader("Content-Disposition"),r=e.getHeader("Content-Type"),"string"==typeof e.body){if(!r)throw new Error("Header content type header does not equal body content type.");n=e.body}else{if(r&&r!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");r=e.body.contentType,n=e.body.body}if(isBody(e)&&(t=e.contentDisposition,r=e.contentType,n=e.content),n){if(r&&!t&&(t=contentTypeToContentDisposition(r)),!t)throw new Error("Content disposition undefined.");if(!r)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:r,content:n}}}var SessionState,SignalingState;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(SessionState=SessionState||(SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(SignalingState=SignalingState||(SignalingState={}));const T1=500,T2=4e3,T4=5e3,Timers={T1:T1,T2:T2,T4:T4,TIMER_B:64*T1,TIMER_D:0*T1,TIMER_F:64*T1,TIMER_H:64*T1,TIMER_I:0*T4,TIMER_J:0*T1,TIMER_K:0*T4,TIMER_L:64*T1,TIMER_M:64*T1,TIMER_N:64*T1,PROVISIONAL_RESPONSE_INTERVAL:6e4};class TransactionStateError extends Exception{constructor(e){super(e||"Transaction state error.")}}var C;!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"}(C=C||(C={}));const AllowedMethods=[C.ACK,C.BYE,C.CANCEL,C.INFO,C.INVITE,C.MESSAGE,C.NOTIFY,C.OPTIONS,C.PRACK,C.REFER,C.REGISTER,C.SUBSCRIBE];class Message{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 Notification{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 Referral{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof NameAddrHeader))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 r=((e=e||{}).extraHeaders||[]).slice(),n=this.replaces;n&&r.push("Replaces: "+decodeURIComponent(n));const i=this.referredBy;return i&&r.push("Referred-By: "+i),e.extraHeaders=r,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}class Session{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=SessionState$1.Initial,this.delegate=t.delegate,this._stateEventEmitter=new EmitterImpl,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 SessionState$1.Initial:case SessionState$1.Establishing:break;case SessionState$1.Established:return new Promise((e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})}));case SessionState$1.Terminating:case SessionState$1.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 SessionState$1.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 SessionState$1.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 SessionState$1.Established:{const t=e.requestDelegate,r=this.copyRequestOptions(e.requestOptions);return this._bye(t,r)}case SessionState$1.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 SessionState$1.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!==SessionState$1.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,r=this.copyRequestOptions(e.requestOptions);return this._info(t,r)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==SessionState$1.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new RequestPendingError("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 r=getBody(t.message);if(!r)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(SessionState$1.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(r,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===SessionState$1.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(SessionState$1.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(r,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!==SessionState$1.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(SessionState$1.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!==SessionState$1.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(SessionState$1.Terminated)}})).then((()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)}))},onTrying:e=>{}},r=e.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+AllowedMethods.toString()),r.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,r))}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 r.body=e,this.dialog.invite(t,r)})).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!==SessionState$1.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,r=this.copyRequestOptions(e.requestOptions);return this._message(t,r)}refer(e,t={}){if(this.state!==SessionState$1.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 Session&&!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 r=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,r,n)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const r=this.dialog;switch(r.sessionState){case SessionState.Initial:case SessionState.Early:throw new Error(`Invalid dialog state ${r.sessionState}`);case SessionState.AckWait:return this.stateTransition(SessionState$1.Terminating),new Promise((n=>{r.delegate={onAck:()=>{const i=r.bye(e,t);return this.stateTransition(SessionState$1.Terminated),n(i),Promise.resolve()},onAckTimeout:()=>{const i=r.bye(e,t);this.stateTransition(SessionState$1.Terminated),n(i)}}}));case SessionState.Confirmed:{const n=r.bye(e,t);return this.stateTransition(SessionState$1.Terminated),Promise.resolve(n)}case SessionState.Terminated:throw new Error(`Invalid dialog state ${r.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,r){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,r))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,r){e.ack();const n=[];t&&n.push("Reason: "+this.getReasonHeaderValue(t,r)),e.session.bye(void 0,{extraHeaders:n})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==SessionState$1.Established&&this.state!==SessionState$1.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 r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new Ack(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.Stable:{const n=getBody(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,r).catch((e=>{this.logger.error(e.message);const r=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:r}),this.stateTransition(SessionState$1.Terminated)})):Promise.resolve()}case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===SessionState$1.Established){if(this.delegate&&this.delegate.onBye){const t=new Bye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(SessionState$1.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===SessionState$1.Established)if(this.delegate&&this.delegate.onInfo){const t=new Info(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!==SessionState$1.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=Grammar.nameAddrHeaderParse(t)}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r).then((r=>{const n=e.accept({statusCode:200,extraHeaders:t,body:r});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!==SignalingState.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 r=e.reject({statusCode:488});if(this.state!==SessionState$1.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(SessionState$1.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.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===SessionState$1.Established)if(this.delegate&&this.delegate.onMessage){const t=new Message(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===SessionState$1.Established)if(this.onNotify){const t=new Notification(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new Notification(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===SessionState$1.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!==SessionState$1.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 Referral(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 r=getBody(e.message);return r&&"session"===r.contentDisposition?this.setOfferAndGetAnswer(r,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case SignalingState.Initial:return this.getOffer(e);case SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case SignalingState.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 SignalingState.Stable:return this.state!==SessionState$1.Established?Promise.resolve(void 0):this.getOffer(e);case SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(r,n).then((e=>fromBodyLegacy(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 r=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}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 r.setDescription(e.content,n,i).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 r=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}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 r.setDescription(e.content,n,i).then((()=>r.getDescription(n,i))).then((e=>fromBodyLegacy(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 SessionState$1.Initial:e!==SessionState$1.Establishing&&e!==SessionState$1.Established&&e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Establishing:e!==SessionState$1.Established&&e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Established:e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Terminating:e!==SessionState$1.Terminated&&t();break;case SessionState$1.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===SessionState$1.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 r=e;let n=getReasonPhrase(e);return!n&&t&&(n=t),"SIP;cause="+r+';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 URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const r=e.remoteIdentity.friendlyName,n=e.dialog.remoteTarget.toString(),i=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${r}" <${n}?Replaces=${encodeURIComponent(`${i};to-tag=${s};from-tag=${o}`)}>`}return t}}var SIPExtension;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(SIPExtension=SIPExtension||(SIPExtension={}));const UserAgentRegisteredOptionTags={"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 Invitation extends Session{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 r=this.incomingInviteRequest.message,n=r.getHeader("require");n&&n.toLowerCase().includes("100rel")&&(this.rel100="required");const i=r.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),r.toTag=t.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout((()=>{t.reject({statusCode:480}),this.stateTransition(SessionState$1.Terminated)}),this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){const e=1e3*Number(r.getHeader("expires")||0);this.expiresTimer=setTimeout((()=>{this.state===SessionState$1.Initial&&(t.reject({statusCode:487}),this.stateTransition(SessionState$1.Terminated))}),e)}const s=this.request.getHeader("P-Asserted-Identity");s&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(s)),this._contact=this.userAgent.contact.toString();const o=r.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=r.body,this._rendertype=r.getHeader("Content-Type")),this._id=r.callId+r.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 SessionState$1.Initial:case SessionState$1.Establishing:return this.reject().then((()=>super.dispose()));case SessionState$1.Established:case SessionState$1.Terminating:case SessionState$1.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!==SessionState$1.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(SessionState$1.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(SessionState$1.Established),this._replacee&&this._replacee._bye()})).catch((e=>this.handleResponseError(e)))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==SessionState$1.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===SIPExtension.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!==SessionState$1.Initial&&this.state!==SessionState$1.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,r=e.reasonPhrase?e.reasonPhrase:getReasonPhrase(t),n=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const i=e.body?fromBodyLegacy(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:r,extraHeaders:n,body:i}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i}),this.stateTransition(SessionState$1.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===SessionState$1.Initial||this.state===SessionState$1.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new Cancel(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(SessionState$1.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=getBody(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case SignalingState.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case SignalingState.Stable:return this.setAnswer(t,r).then((()=>{}));case SignalingState.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,r);case SignalingState.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 ContentTypeUnsupportedError?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof SessionDescriptionHandlerError?this.logger.error("A session description handler occurred while sending response"):e instanceof SessionTerminatedError?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof TransactionStateError&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===SessionState$1.Initial||this.state===SessionState$1.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(SessionState$1.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(SessionState$1.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=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:r}))):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r}))))}sendProgress(e={}){const t=e.statusCode||180,r=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),i=e.body?fromBodyLegacy(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,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},r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let s;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise(((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>(s=e,this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:s})))).then((t=>{let a,d;this._dialog=t.session,t.session.delegate={onPrack:r=>{a=r,clearTimeout(c),clearTimeout(h),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then((r=>{try{d=a.accept({statusCode:200,body:r}),this.prackArrived(),e({prackRequest:a,prackResponse:d,progressResponse:t})}catch(e){o(e)}})).catch((e=>o(e))))}};const c=setTimeout((()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(h),this.reject({statusCode:504}).then((()=>o(new SessionTerminatedError))).catch((e=>o(e))))}),64*Timers.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:s})}catch(e){return this.waitingForPrack=!1,void o(e)}h=setTimeout(l,u*=2)};let u=Timers.T1,h=setTimeout(l,u)})).catch((e=>{this.waitingForPrack=!1,o(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 SessionTerminatedError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Inviter extends Session{constructor(e,t,r={}){super(e,r),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!==r.earlyMedia?r.earlyMedia:this.earlyMedia,this.fromTag=newTag(),this.inviteWithoutSdp=void 0!==r.inviteWithoutSdp?r.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},r);n.params=Object.assign({},r.params);const i=r.anonymous||!1,s=e.contact.toString({anonymous:i,outbound:i?!e.contact.tempGruu:!e.contact.pubGruu});i&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(o="string"==typeof n.params.fromUri?Grammar.URIParse(n.params.fromUri):n.params.fromUri),!o)throw new TypeError("Invalid from URI: "+n.params.fromUri);let a=t;if(n.params.toUri&&(a="string"==typeof n.params.toUri?Grammar.URIParse(n.params.toUri):n.params.toUri),!a)throw new TypeError("Invalid to URI: "+n.params.toUri);const d=Object.assign({},n.params);d.fromTag=this.fromTag;const c=(n.extraHeaders||[]).slice();i&&e.configuration.uri&&(c.push("P-Preferred-Identity: "+e.configuration.uri.toString()),c.push("Privacy: id")),c.push("Contact: "+s),c.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===SIPExtension.Required&&c.push("Require: 100rel"),e.configuration.sipExtensionReplaces===SIPExtension.Required&&c.push("Require: replaces"),n.extraHeaders=c;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(C.INVITE,t,o,a,d,c,undefined),this._contact=s,this._referralInviterOptions=n,this._renderbody=r.renderbody,this._rendertype=r.rendertype,r.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=r.sessionDescriptionHandlerModifiers),r.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=r.sessionDescriptionHandlerOptions),r.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=r.sessionDescriptionHandlerModifiersReInvite),r.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=r.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 SessionState$1.Initial:case SessionState$1.Establishing:return this.cancel().then((()=>super.dispose()));case SessionState$1.Established:case SessionState$1.Terminating:case SessionState$1.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!==SessionState$1.Initial&&this.state!==SessionState$1.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(SessionState$1.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="'+(getReasonPhrase(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(SessionState$1.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==SessionState$1.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(SessionState$1.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(SessionState$1.Establishing),this.sendInvite(e)))).catch((e=>{throw this.logger.log(e.message),this.state!==SessionState$1.Terminated&&this.stateTransition(SessionState$1.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(SessionState$1.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 Session))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!==SessionState$1.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,r=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),r.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=r,r.signalingState){case SignalingState.Initial:case SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(SessionState$1.Terminated),Promise.reject(new Error("Bad Media Description"));case SignalingState.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(SessionState$1.Established)})).catch((t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(SessionState$1.Terminated),t}))}case SignalingState.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(r.id),e.ack(),this.stateTransition(SessionState$1.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){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(SessionState$1.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(SessionState$1.Established),Promise.resolve()}const t=r.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(SessionState$1.Established)})).catch((t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(SessionState$1.Terminated),t}))}case SignalingState.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!==SessionState$1.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 r=e.message,n=e.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));const i=r.getHeader("require"),s=r.getHeader("rseq"),o=!!(i&&i.includes("100rel")&&s?Number(s):void 0),a=[];switch(o&&a.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),n.signalingState){case SignalingState.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case SignalingState.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case SignalingState.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(n.id,i),i.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then((()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers))).then((t=>{const r={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:r})})).catch((e=>{throw this.stateTransition(SessionState$1.Terminated),e}))}case SignalingState.Stable:if(o&&e.prack({extraHeaders:a}),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(SessionState$1.Terminated),e}))}return Promise.resolve();case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===SessionState$1.Establishing||this.state===SessionState$1.Terminating?this.stateTransition(SessionState$1.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===SessionState$1.Establishing||this.state===SessionState$1.Terminating?this.stateTransition(SessionState$1.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===SessionState$1.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class Messager{constructor(e,t,r,n="text/plain",i={}){this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};let s=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(s="string"==typeof i.params.fromUri?Grammar.URIParse(i.params.fromUri):i.params.fromUri),!s)throw new TypeError("Invalid from URI: "+i.params.fromUri);let o=t;if(i.params.toUri&&(o="string"==typeof i.params.toUri?Grammar.URIParse(i.params.toUri):i.params.toUri),!o)throw new TypeError("Invalid to URI: "+i.params.toUri);const a=i.params?Object.assign({},i.params):{},d=(i.extraHeaders||[]).slice(),c={contentDisposition:"render",contentType:n,content:r};this.request=e.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE,t,s,o,a,d,c),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var RegistererState,SubscriptionState,TransportState,UserAgentState,Levels,Parser,TransactionState;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(RegistererState=RegistererState||(RegistererState={}));class Registerer{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=RegistererState.Initial,this._waiting=!1,this._stateEventEmitter=new EmitterImpl,this._waitingEventEmitter=new EmitterImpl,this.userAgent=e;const r=e.configuration.uri.clone();if(r.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},Registerer.defaultOptions()),{registrar:r}),Registerer.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===Grammar.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,i=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,s=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(C.REGISTER,n,i,s,o,a,void 0),this.expires=this.options.expires||Registerer.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||Registerer.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:Registerer.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new URI("sip","anonymous","anonymous.invalid"),refreshFrequency:Registerer.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),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===RegistererState.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===RegistererState.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 RequestPendingError("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 r=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let r;t.message.hasHeader("expires")&&(r=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let n,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(n=t.message.parseHeader("contact",i),!n)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&equivalentURI(n.uri,this.userAgent.contact.pubGruu)){r=Number(n.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(n.uri.user===this.userAgent.contact.uri.user){r=Number(n.getParam("expires"));break}}else if(equivalentURI(n.uri,this.userAgent.contact.uri)){r=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===r)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=Grammar.URIParse(e.replace(/"/g,"")))}if(n.hasParam("pub-gruu")){const e=n.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Grammar.URIParse(e.replace(/"/g,"")))}this.registered(r),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 r=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(r=Number.parseInt(e,void 0))}this._retryAfter=isNaN(r)?void 0:r,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(r)}unregister(e={}){if(this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==RegistererState.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===RegistererState.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 r=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(r)}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!==RegistererState.Registered&&this.stateTransition(RegistererState.Registered)}unregistered(){this.clearTimers(),this._state!==RegistererState.Unregistered&&this.stateTransition(RegistererState.Unregistered)}terminated(){this.clearTimers(),this._state!==RegistererState.Terminated&&this.stateTransition(RegistererState.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case RegistererState.Initial:e!==RegistererState.Registered&&e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&t();break;case RegistererState.Registered:e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&t();break;case RegistererState.Unregistered:e!==RegistererState.Registered&&e!==RegistererState.Terminated&&t();break;case RegistererState.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===RegistererState.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===RegistererState.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)}}Registerer.defaultExpires=600,Registerer.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(SubscriptionState=SubscriptionState||(SubscriptionState={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(TransportState=TransportState||(TransportState={})),function(e){e.Started="Started",e.Stopped="Stopped"}(UserAgentState=UserAgentState||(UserAgentState={}));class Md5{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=Md5.hexChars,r=Md5.hexOut;let n,i,s,o;for(o=0;o<4;o+=1)for(i=8*o,n=e[o],s=0;s<8;s+=2)r[i+1+s]=t.charAt(15&n),n>>>=4,r[i+0+s]=t.charAt(15&n),n>>>=4;return r.join("")}static _md5cycle(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r+=(n&i|~n&s)+t[0]-680876936|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[1]-389564586|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[2]+606105819|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[3]-1044525330|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[4]-176418897|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[5]+1200080426|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[6]-1473231341|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[7]-45705983|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[8]+1770035416|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[9]-1958414417|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[10]-42063|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[11]-1990404162|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[12]+1804603682|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[13]-40341101|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[14]-1502002290|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[15]+1236535329|0,n=(n<<22|n>>>10)+i|0,r+=(n&s|i&~s)+t[1]-165796510|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[6]-1069501632|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[11]+643717713|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[0]-373897302|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[5]-701558691|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[10]+38016083|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[15]-660478335|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[4]-405537848|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[9]+568446438|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[14]-1019803690|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[3]-187363961|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[8]+1163531501|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[13]-1444681467|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[2]-51403784|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[7]+1735328473|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[12]-1926607734|0,n=(n<<20|n>>>12)+i|0,r+=(n^i^s)+t[5]-378558|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[8]-2022574463|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[11]+1839030562|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[14]-35309556|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[1]-1530992060|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[4]+1272893353|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[7]-155497632|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[10]-1094730640|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[13]+681279174|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[0]-358537222|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[3]-722521979|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[6]+76029189|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[9]-640364487|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[12]-421815835|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[15]+530742520|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[2]-995338651|0,n=(n<<23|n>>>9)+i|0,r+=(i^(n|~s))+t[0]-198630844|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[7]+1126891415|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[14]-1416354905|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[5]-57434055|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[12]+1700485571|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[3]-1894986606|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[10]-1051523|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[1]-2054922799|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[8]+1873313359|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[15]-30611744|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[6]-1560198380|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[13]+1309151649|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[4]-145523070|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[11]-1120210379|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[2]+718787259|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[9]-343485551|0,n=(n<<21|n>>>11)+i|0,e[0]=r+e[0]|0,e[1]=n+e[1]|0,e[2]=i+e[2]|0,e[3]=s+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Md5.stateIdentity),this}appendStr(e){const t=this._buffer8,r=this._buffer32;let n,i,s=this._bufferLength;for(i=0;i<e.length;i+=1){if(n=e.charCodeAt(i),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(++i)-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,Md5._md5cycle(this._state,r),s-=64,r[0]=r[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,r=this._buffer32;let n,i=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-i);n--;)t[i++]=e.charCodeAt(s++);if(i<64)break;this._dataLength+=64,Md5._md5cycle(this._state,r),i=0}return this._bufferLength=i,this}appendByteArray(e){const t=this._buffer8,r=this._buffer32;let n,i=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-i);n--;)t[i++]=e[s++];if(i<64)break;this._dataLength+=64,Md5._md5cycle(this._state,r),i=0}return this._bufferLength=i,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,r=e.state,n=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],i=0;i<t.length;i+=1)this._buffer8[i]=t.charCodeAt(i)}end(e=!1){const t=this._bufferLength,r=this._buffer8,n=this._buffer32,i=1+(t>>2);let s;if(this._dataLength+=t,r[t]=128,r[t+1]=r[t+2]=r[t+3]=0,n.set(Md5.buffer32Identity.subarray(i),i),t>55&&(Md5._md5cycle(this._state,n),n.set(Md5.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),r=parseInt(e[1],16)||0;n[14]=t,n[15]=r}return Md5._md5cycle(this._state,n),e?this._state:Md5._hex(this._state)}}function MD5(e){return Md5.hashStr(e)}Md5.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Md5.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Md5.hexChars="0123456789abcdef",Md5.hexOut=[],Md5.onePassHasher=new Md5,"5d41402abc4b2a76b9719d911017c592"!==Md5.hashStr("hello")&&console.error("Md5 self test failed.");class DigestAuthentication{constructor(e,t,r,n){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=r,this.password=n,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,r){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=createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!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,r;t=this.ha1,""!==t&&void 0!==t||(t=MD5(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(r=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+r)):"auth-int"===this.qop?(r=MD5(this.method+":"+this.uri+":"+MD5(e||"")),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+r)):void 0===this.qop&&(r=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+r))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Levels=Levels||(Levels={}));class Logger{constructor(e,t,r){this.logger=e,this.category=t,this.label=r}error(e){this.genericLog(Levels.error,e)}warn(e){this.genericLog(Levels.warn,e)}log(e){this.genericLog(Levels.log,e)}debug(e){this.genericLog(Levels.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 LoggerFactory{constructor(){this.builtinEnabled=!0,this._level=Levels.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:Levels.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 Logger(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Logger(this,e);return this.loggers[e]=t,t}}genericLog(e,t,r,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,n),this.connector&&this.connector(Levels[e],t,r,n)}print(e,t,r,n){if("string"==typeof n){const e=[new Date,t];r&&e.push(r),n=e.concat(n).join(" | ")}switch(e){case Levels.error:console.error(n);break;case Levels.warn:console.warn(n);break;case Levels.log:console.log(n);break;case Levels.debug:console.debug(n)}}}function constructOutgoingResponse(e,t){const r="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const n=t.reasonPhrase?t.reasonPhrase:getReasonPhrase(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+n+r;t.statusCode>=100&&t.statusCode,t.statusCode;const s="From: "+e.getHeader("From")+r,o="Call-ID: "+e.callId+r,a="CSeq: "+e.cseq+" "+e.method+r,d=e.getHeaders("via").reduce(((e,t)=>e+"Via: "+t+r),"");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=newTag()),c+=";tag="+e}c+=r;let l="";t.supported&&(l="Supported: "+t.supported.join(", ")+r);let u="";t.userAgent&&(u="User-Agent: "+t.userAgent+r);let h="";return t.extraHeaders&&(h=t.extraHeaders.reduce(((e,t)=>e+t.trim()+r),"")),i+=d,i+=s,i+=c,i+=a,i+=o,i+=l,i+=u,i+=h,t.body?(i+="Content-Type: "+t.body.contentType+r,i+="Content-Length: "+utf8Length(t.body.content)+r+r,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){let r=t,n=0,i=0;if(e.substring(r,r+2).match(/(^\r\n)/))return-2;for(;0===n;){if(i=e.indexOf("\r\n",r),-1===i)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?r=i+2:n=i}return n}function r(e,t,r,n){const i=t.indexOf(":",r),s=t.substring(r,i).trim(),o=t.substring(i+1,n).trim();let a;switch(s.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=Grammar.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach((t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=Grammar.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach((t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof IncomingResponseMessage&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(s.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+s+"'"}}e.getHeader=t,e.parseHeader=r,e.parseMessage=function(e,n){let i=0,s=e.indexOf("\r\n");if(-1===s)return void n.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,s),a=Grammar.parse(o,"Request_Response");let d,c;if(-1!==a){for(a.status_code?(d=new IncomingResponseMessage,d.statusCode=a.status_code,d.reasonPhrase=a.reason_phrase):(d=new IncomingRequestMessage,d.method=a.method,d.ruri=a.uri),d.data=e,i=s+2;;){if(s=t(e,i),-2===s){c=i+2;break}if(-1===s)return void n.error("malformed message");const o=r(d,e,i,s);if(o&&!0!==o)return void n.error(o.error);i=s+2}return d.hasHeader("content-length")?d.body=e.substr(c,Number(d.getHeader("content-length"))):d.body=e.substring(c),d}n.warn('error parsing first line of SIP message: "'+o+'"')}}(Parser=Parser||(Parser={}));class TransportError extends Exception{constructor(e){super(e||"Unspecified transport error.")}}class Transaction{constructor(e,t,r,n,i){this._transport=e,this._user=t,this._id=r,this._state=n,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,r),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 r=()=>{this.removeStateChangeListener(r),e()};!0===(null==t?void 0:t.once)?this.listeners.push(r):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 TransportError)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new TransportError(e.message):new TransportError,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 ServerTransaction extends Transaction{constructor(e,t,r,n,i){super(t,r,e.viaBranch,n,i),this._request=e,this.user=r}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"}(TransactionState=TransactionState||(TransactionState={}));class InviteServerTransaction extends ServerTransaction{constructor(e,t,r){super(e,t,r,TransactionState.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 TransactionState.Proceeding:if(e.method===C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case TransactionState.Accepted:if(e.method===C.INVITE)return;break;case TransactionState.Completed:if(e.method===C.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===C.ACK)return void this.stateTransition(TransactionState.Confirmed);break;case TransactionState.Confirmed:case TransactionState.Terminated:if(e.method===C.INVITE||e.method===C.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 TransactionState.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(TransactionState.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(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send non-2xx final response.")}));break;case TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));break;case TransactionState.Completed:case TransactionState.Confirmed:case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(r),new Error(r)}retransmitAcceptedResponse(){this.state===TransactionState.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 TransactionState.Proceeding:t();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Proceeding&&t();break;case TransactionState.Confirmed:this.state!==TransactionState.Completed&&t();break;case TransactionState.Terminated:this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&this.state!==TransactionState.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===TransactionState.Accepted&&(this.L=setTimeout((()=>this.timerL()),Timers.TIMER_L)),e===TransactionState.Completed&&(this.H=setTimeout((()=>this.timerH()),Timers.TIMER_H)),e===TransactionState.Confirmed&&(this.I=setTimeout((()=>this.timerI()),Timers.TIMER_I)),e===TransactionState.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.")}))}),Timers.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===TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(TransactionState.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(TransactionState.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)}}class ClientTransaction extends Transaction{constructor(e,t,r,n,i){super(t,r,ClientTransaction.makeId(e),n,i),this._request=e,this.user=r,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 NonInviteClientTransaction extends ClientTransaction{constructor(e,t,r){super(e,t,r,TransactionState.Trying,"sip.transaction.nict"),this.F=setTimeout((()=>this.timerF()),Timers.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 TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Completed:case TransactionState.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const r=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((()=>this.timerK()),Timers.TIMER_K)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))}timerK(){this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}}class Dialog{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const r=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const i=n.uri,s=e.cseq,o=e.callId,a=e.fromTag,d=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const c=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+d,early:t.statusCode<200,callId:o,localTag:a,remoteTag:d,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:c,remoteURI:l,remoteTarget:i,routeSet:r,secure:!1}}static initialDialogStateForUserAgentServer(e,t,r=!1){const n=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const s=i.uri,o=e.cseq,a=e.callId,d=t,c=e.fromTag,l=e.from.uri;return{id:a+d+c,early:r,callId:a,localTag:d,remoteTag:c,localSequenceNumber:undefined,remoteSequenceNumber:o,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!==C.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 r=this.remoteURI,n=this.remoteTag,i=this.localURI,s=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const d=this.remoteTarget,c=this.routeSet,l=t&&t.extraHeaders,u=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,d,i,r,{callId:o,cseq:a,fromTag:s,toTag:n,routeSet:c},l,u)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class InviteClientTransaction extends ClientTransaction{constructor(e,t,r){super(e,t,r,TransactionState.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout((()=>this.timerB()),Timers.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 r="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(r,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 TransactionState.Calling:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.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(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.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 TransactionState.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,r=this.request.callId,n=this.request.cseq,i=this.request.getHeader("from"),s=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let d=`ACK ${t} SIP/2.0\r\n`;a&&(d+=`Route: ${a}\r\n`),d+=`Via: ${o}\r\n`,d+=`To: ${s}\r\n`,d+=`From: ${i}\r\n`,d+=`Call-ID: ${r}\r\n`,d+=`CSeq: ${n} ACK\r\n`,d+="Max-Forwards: 70\r\n",d+="Content-Length: 0\r\n\r\n",this.send(d).catch((e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")}))}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Calling:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Calling&&r();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Calling&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Calling&&this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}this.B&&(clearTimeout(this.B),this.B=void 0),TransactionState.Proceeding,e===TransactionState.Completed&&(this.D=setTimeout((()=>this.timerD()),Timers.TIMER_D)),e===TransactionState.Accepted&&(this.M=setTimeout((()=>this.timerM()),Timers.TIMER_M)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)}}class UserAgentClient{constructor(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,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 r=this.core.makeOutgoingRequestMessage(C.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 r.branch=this.message.branch,this.message.headers.Route&&(r.headers.Route=this.message.headers.Route),e&&r.setHeader("Reason",e),this.transaction.state===TransactionState.Proceeding?new UserAgentClient(NonInviteClientTransaction,this.core,r):this.transaction.addStateChangeListener((()=>{this.transaction&&this.transaction.state===TransactionState.Proceeding&&new UserAgentClient(NonInviteClientTransaction,this.core,r)}),{once:!0}),r}authenticationGuard(e,t){const r=e.statusCode;if(!r)throw new Error("Response status code undefined.");if(401!==r&&407!==r)return!0;let n,i;if(401===r?(n=e.parseHeader("www-authenticate"),i="authorization"):(n=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!n)return this.logger.warn(r+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(r+" 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(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new IncomingResponseMessage;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 IncomingResponseMessage;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===TransactionState.Terminated&&(this.core.userAgentClients.delete(r),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 r=t.id+t.request.method;this.core.userAgentClients.set(r,this)}}class ByeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.BYE,r);super(NonInviteClientTransaction,e.userAgentCore,n,t),e.dispose()}}class NonInviteServerTransaction extends ServerTransaction{constructor(e,t,r){super(e,t,r,TransactionState.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 TransactionState.Trying:break;case TransactionState.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 TransactionState.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 TransactionState.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 TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(TransactionState.Proceeding),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case TransactionState.Completed:return;case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(r),new Error(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.J=setTimeout((()=>this.timerJ()),Timers.TIMER_J)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}}class UserAgentServer{constructor(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:newTag(),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 TransactionStateError(`${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 TransactionStateError(`${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 TransactionStateError(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const r=t.statusCode;if(r<300||r>399)throw new TypeError(`Invalid statusCode: ${r}`);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 TransactionStateError(`${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 TransactionStateError(`${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 InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding||this.transaction.state===TransactionState.Accepted;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.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=constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===TransactionState.Terminated&&(this.core.userAgentServers.delete(r),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 r=t.id;this.core.userAgentServers.set(t.id,this)}}class ByeUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r)}}class InfoUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.INFO,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}class InfoUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r)}}class MessageUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class MessageUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r)}}class NotifyUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.NOTIFY,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}function instanceOfDialog(e){return void 0!==e.userAgentCore}class NotifyUserAgentServer extends UserAgentServer{constructor(e,t,r){const n=instanceOfDialog(e)?e.userAgentCore:e;super(NonInviteServerTransaction,n,t,r)}}class PrackUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.PRACK,r);super(NonInviteClientTransaction,e.userAgentCore,n,t),e.signalingStateTransition(n)}}class PrackUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class ReInviteUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.INVITE,r);super(InviteClientTransaction,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 ReInviteUserAgentServer extends UserAgentServer{constructor(e,t,r){super(InviteServerTransaction,e.userAgentCore,t,r),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),r=this.dialog,n=Object.assign(Object.assign({},t),{session:r});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),n}progress(e={statusCode:180}){const t=super.progress(e),r=this.dialog,n=Object.assign(Object.assign({},t),{session:r});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 ReferUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.REFER,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}function instanceOfSessionDialog(e){return void 0!==e.userAgentCore}class ReferUserAgentServer extends UserAgentServer{constructor(e,t,r){const n=instanceOfSessionDialog(e)?e.userAgentCore:e;super(NonInviteServerTransaction,n,t,r)}}class SessionDialog extends Dialog{constructor(e,t,r,n){super(t,r),this.initialTransaction=e,this._signalingState=SignalingState.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=n,e instanceof InviteServerTransaction&&(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=SignalingState.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?SessionState.Early:this.ackWait?SessionState.AckWait:this._signalingState===SignalingState.Closed?SessionState.Terminated:SessionState.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 InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const r=this.createOutgoingRequestMessage(C.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(r),this.signalingStateTransition(r),{message:r}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==TransactionState.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 ByeUserAgentClient(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 InfoUserAgentClient(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 ReInviteUserAgentClient(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 r=this.createOutgoingRequestMessage(C.MESSAGE,t);return new MessageUserAgentClient(this.core,r,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 NotifyUserAgentClient(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new PrackUserAgentClient(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 ReferUserAgentClient(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==C.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===C.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.")},r=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:r}),void t();if(this.ackWait&&this.signalingState!==SignalingState.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:r}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:r});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===C.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case C.BYE:{const t=new ByeUserAgentServer(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case C.INFO:{const t=new InfoUserAgentServer(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case C.INVITE:{const t=new ReInviteUserAgentServer(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case C.MESSAGE:{const t=new MessageUserAgentServer(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case C.NOTIFY:{const t=new NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case C.PRACK:{const t=new PrackUserAgentServer(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case C.REFER:{const t=new ReferUserAgentServer(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 InviteClientTransaction)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"),r=e.getHeader("rseq"),n=t&&t.includes("100rel")&&r?Number(r):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!==SignalingState.HaveLocalOffer&&this.signalingState!==SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof IncomingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof IncomingResponseMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof OutgoingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(isBody(e))switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof InviteServerTransaction){const e=this.initialTransaction;let t=Timers.T1;const r=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Timers.T2),this.invite2xxTimer=setTimeout(r,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,t);const n=()=>{e.state===TransactionState.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 InviteServerTransaction){const e=this.reinviteUserAgentServer.transaction;let t=Timers.T1;const r=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Timers.T2),this.invite2xxTimer=setTimeout(r,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,t);const n=()=>{e.state===TransactionState.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(n)}}}class InviteUserAgentClient extends UserAgentClient{constructor(e,t,r){super(InviteClientTransaction,e,t,r),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=r}dispose(){this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===TransactionState.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=Dialog.initialDialogStateForUserAgentClient(this.message,e);let r=this.earlyDialogs.get(t.id);if(!r){const e=this.transaction;if(!(e instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");r=new SessionDialog(e,this.core,t),this.earlyDialogs.set(r.id,r)}if(!r.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");r.signalingState!==SignalingState.Initial&&r.signalingState!==SignalingState.HaveLocalOffer||r.signalingStateTransition(e);const n=r;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=Dialog.initialDialogStateForUserAgentClient(this.message,e);let r=this.confirmedDialogs.get(t.id);if(r){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(r=this.earlyDialogs.get(t.id),r)r.confirm(),r.recomputeRouteSet(e),this.earlyDialogs.delete(r.id),this.confirmedDialogs.set(r.id,r);else{const e=this.transaction;if(!(e instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");r=new SessionDialog(e,this.core,t),this.confirmedDialogs.set(r.id,r)}r.signalingState!==SignalingState.Initial&&r.signalingState!==SignalingState.HaveLocalOffer||r.signalingStateTransition(e);const n=r;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 InviteUserAgentServer extends UserAgentServer{constructor(e,t,r){super(InviteServerTransaction,e,t,r),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new TransactionStateError(`${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 InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new SessionDialog(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),r=`Contact: ${this.core.configuration.contact.toString()}`,n="Allow: "+AllowedMethods.toString();if(!e.body)if(this.confirmedDialog.signalingState===SignalingState.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===SignalingState.Initial||this.confirmedDialog.signalingState===SignalingState.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(r);const i=super.accept(e),s=this.confirmedDialog,o=Object.assign(Object.assign({},i),{session:s});return e.body&&this.confirmedDialog.signalingState!==SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new SessionDialog(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),r=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r);const n=super.progress(e),i=this.earlyDialog,s=Object.assign(Object.assign({},n),{session:i});return e.body&&this.earlyDialog.signalingState!==SignalingState.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 PublishUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class RegisterUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class RegisterUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r),this.core=e}}class ReSubscribeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.SUBSCRIBE,r);super(NonInviteClientTransaction,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 SubscriptionDialog extends Dialog{constructor(e,t,r,n,i,s){super(n,i),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=r,this.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const r=t.getHeaders("record-route"),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const i=n.uri,s=e.cseq,o=e.callId,a=e.fromTag,d=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+d,early:!1,callId:o,localTag:a,remoteTag:d,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:r,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===C.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: "+AllowedMethods.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 r;if(this.subscriptionState!==SubscriptionState.Pending&&this.subscriptionState!==SubscriptionState.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 ReSubscribeUserAgentClient(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(r=t.extraHeaders)||void 0===r?void 0:r.includes("Expires: 0"))||(this.N=setTimeout((()=>this.timerN()),Timers.TIMER_N)),n}terminate(){this.stateTransition(SubscriptionState.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+AllowedMethods.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 r=e.parseHeader("Subscription-State");if(!r||!r.state)return void this.core.replyStateless(e,{statusCode:489});const n=r.state,i=r.expires?Math.max(r.expires,0):void 0;switch(n){case"pending":this.stateTransition(SubscriptionState.Pending,i);break;case"active":this.stateTransition(SubscriptionState.Active,i);break;case"terminated":this.stateTransition(SubscriptionState.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const s=new NotifyUserAgentServer(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 r=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case SubscriptionState.Initial:case SubscriptionState.NotifyWait:return void r();case SubscriptionState.Pending:if(this.subscriptionState!==SubscriptionState.NotifyWait&&this.subscriptionState!==SubscriptionState.Pending)return void r();break;case SubscriptionState.Active:case SubscriptionState.Terminated:if(this.subscriptionState!==SubscriptionState.NotifyWait&&this.subscriptionState!==SubscriptionState.Pending&&this.subscriptionState!==SubscriptionState.Active)return void r();break;default:return void r()}e===SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==SubscriptionState.Terminated&&(this.stateTransition(SubscriptionState.Terminated),this.onTerminated())}}class SubscribeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=t.getHeader("Event");if(!n)throw new Error("Event undefined");const i=t.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(NonInviteClientTransaction,e,t,r),this.delegate=r,this.subscriberId=t.callId+t.fromTag+n,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=n,this.subscriptionState=SubscriptionState.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 r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=r.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=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=SubscriptionState.Pending;break;case"active":this.subscriptionState=SubscriptionState.Active;break;case"terminated":this.subscriptionState=SubscriptionState.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==SubscriptionState.Terminated){const t=SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,r=this.dialog;this.delegate.onNotify({request:t,subscription:r})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((()=>this.timerN()),Timers.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 SubscribeUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r),this.core=e}}const acceptedBodyTypes=["application/sdp","application/dtmf-relay"];class UserAgentCore{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 InviteUserAgentClient(this,e,t)}message(e,t){return new MessageUserAgentClient(this,e,t)}publish(e,t){return new PublishUserAgentClient(this,e,t)}register(e,t){return new RegisterUserAgentClient(this,e,t)}subscribe(e,t){return new SubscribeUserAgentClient(this,e,t)}request(e,t){return new UserAgentClient(NonInviteClientTransaction,this,e,t)}makeOutgoingRequestMessage(e,t,r,n,i,s,o){const a=this.configuration.sipjsId,d=this.configuration.displayName,c=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,u=this.configuration.supportedOptionTags.slice();e===C.REGISTER&&u.push("path","gruu"),e===C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&u.push("gruu");const h={callIdPrefix:a,forceRport:c,fromDisplayName:d,hackViaTcp:l,optionTags:u,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},h),i);return new OutgoingRequestMessage(e,t,r,n,g,s,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const r=this.configuration.userAgentHeaderFieldValue,n=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:r,supported:n});const i=constructOutgoingResponse(e,t);return this.transport.send(i.message).catch((t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)})),i}receiveRequestFromTransport(e){const t=e.viaBranch,r=this.userAgentServers.get(t);e.method===C.ACK&&r&&r.transaction.state===TransactionState.Accepted&&r instanceof InviteUserAgentServer?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof InviteServerTransaction&&r.transaction.state===TransactionState.Proceeding&&r instanceof InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!AllowedMethods.includes(e.method)){const t="Allow: "+AllowedMethods.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,r=e=>!!e&&e.user===t.user;if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==C.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===C.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const r=e.callId+e.toTag+t.event,n=this.subscribers.get(r);if(n){const t=new NotifyUserAgentServer(this,e);return void n.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,r=this.dialogs.get(t);if(r){if(e.method===C.OPTIONS){const t="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,r]})}r.receiveRequest(e)}else e.method!==C.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case C.ACK:break;case C.BYE:this.replyStateless(e,{statusCode:481});break;case C.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case C.INFO:this.replyStateless(e,{statusCode:405});break;case C.INVITE:{const t=new InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case C.MESSAGE:{const t=new MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case C.NOTIFY:{const t=new NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case C.OPTIONS:{const t="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,r]})}break;case C.REFER:{const t=new ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case C.REGISTER:{const t=new RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case C.SUBSCRIBE:{const t=new SubscribeUserAgentServer(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,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}function defaultMediaStreamFactory(){return 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)}function defaultPeerConnectionConfiguration(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}}class SessionDescriptionHandler{constructor(e,t,r){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=r,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==r?void 0:r.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 r,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 i=null===(r=null==e?void 0:e.offerOptions)||void 0===r?void 0:r.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(i,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 r=this._peerConnection.getSenders();if(0===r.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const n=r[0].dtmf;if(!n)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{n.insertDTMF(e,i,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,r){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},r))).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,r=this._localMediaStream,n=[],i=e=>{const i=e.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const s=t.getSenders().find((e=>e.track&&e.track.kind===i));s?n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),e()})).then((()=>s.replaceTrack(e).then((()=>{const t=r.getTracks().find((e=>e.kind===i));t&&(t.stop(),r.removeTrack(t),SessionDescriptionHandler.dispatchRemoveTrackEvent(r,t)),r.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(r,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),e}))))):n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),e()})).then((()=>{try{t.addTrack(e,r)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),e}r.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(r,e)})))},s=e.getAudioTracks();s.length&&i(s[0]);const o=e.getVideoTracks();return o.length&&i(o[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 r;switch(this._peerConnection.signalingState){case"stable":r="offer";break;case"have-local-offer":r="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:r}):(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),SessionDescriptionHandler.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),SessionDescriptionHandler.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),SessionDescriptionHandler.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),SessionDescriptionHandler.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 r=t(e.direction);e.direction!==r&&(e.direction=r)}}))}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"})(),r=(()=>{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!==r&&(e.direction=r)}))}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,r)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=r,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 r;const n=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.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 r;const n=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var r;const n=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${n}`),"complete"===n&&this.iceGatheringComplete(),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.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 r;const n=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const r=e.track.kind,n=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${r} ${n}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function defaultSessionDescriptionHandlerFactory(e){return(t,r)=>{void 0===e&&(e=defaultMediaStreamFactory());const n={iceGatheringTimeout:void 0!==(null==r?void 0:r.iceGatheringTimeout)?null==r?void 0:r.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},defaultPeerConnectionConfiguration()),null==r?void 0:r.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new SessionDescriptionHandler(i,e,n)}}class Transport{constructor(e,t){if(this._state=TransportState.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new EmitterImpl,this.logger=e,t){const e=t,r=null==e?void 0:e.wsServers,n=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==r){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)}r&&!t.server&&("string"==typeof r&&(t.server=r),r instanceof Array&&(t.server=r[0]))}this.configuration=Object.assign(Object.assign({},Transport.defaultOptions),t);const r=this.configuration.server,n=Grammar.parse(r,"absoluteURI");if(-1===n)throw this.logger.error(`Invalid WebSocket Server URL "${r}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(n.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${r}"`),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===TransportState.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case TransportState.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case TransportState.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case TransportState.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)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,r)=>{this.connectResolve=t,this.connectReject=r,this.transitionState(TransportState.Disconnected,e)}))}return this.connectPromise=new Promise(((t,r)=>{this.connectResolve=t,this.connectReject=r,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 TransportState.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case TransportState.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.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,r)=>{this.disconnectResolve=t,this.disconnectReject=r;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!==TransportState.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 r=`WebSocket closed ${this.server} (code: ${e.code})`,n=this.disconnectPromise?void 0:new Error(r);n&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(r),this._ws=void 0,this.transitionState(TransportState.Disconnected,n)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const r=e.data;let n;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{n=(new TextDecoder).decode(new Uint8Array(r))}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=r,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===TransportState.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===TransportState.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(TransportState.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 StateTransitionError("Loop detected.")}transitionState(e,t){const r=()=>{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 TransportState.Connecting:e!==TransportState.Connected&&e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Connected:e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnecting:e!==TransportState.Connecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnected:e!==TransportState.Connecting&&r();break;default:throw new Error("Unknown state.")}const n=this._state;this._state=e;const i=this.connectResolve,s=this.connectReject;n===TransportState.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(n===TransportState.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===TransportState.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===TransportState.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===TransportState.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!s)throw new Error("Connect reject undefined.");e===TransportState.Connected?i():s(t||new Error("Connect aborted."))}if(n===TransportState.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===TransportState.Disconnected?o():a(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}}Transport.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};const LIBRARY_VERSION="0.21.1";class UserAgent{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=UserAgentState.Stopped,this._stateEventEmitter=new EmitterImpl,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},UserAgent.defaultOptions()),{sipjsId:createRandomToken(5)}),{uri:new URI("sip","anonymous."+createRandomToken(6),"anonymous.invalid")}),{viaHost:createRandomToken(12)+".invalid"}),UserAgent.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,r=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+r}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new LoggerFactory,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=Levels.error;break;case"warn":this.loggerFactory.level=Levels.warn;break;case"log":this.loggerFactory.level=Levels.log;break;case"debug":this.loggerFactory.level=Levels.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,r=t.maxReconnectionAttempts,n=t.reconnectionTimeout;if(void 0!==r){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!==r&&(this.options.reconnectionAttempts=r)}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:UserAgent.newUUID(),-1===Grammar.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Grammar.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:defaultSessionDescriptionHandlerFactory(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:SIPExtension.Unsupported,sipExtensionReplaces:SIPExtension.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Transport,transportOptions:{},uri:new URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+LIBRARY_VERSION,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,r)=>(void 0!==e[r]&&(t[r]=e[r]),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===UserAgentState.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then((()=>this.transport.connect()))}start(){return this.state===UserAgentState.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(UserAgentState.Started),this.transport.connect())}async stop(){if(this.state===UserAgentState.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(UserAgentState.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),r=Object.assign({},this._sessions),n=Object.assign({},this._subscriptions),i=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 r)r[e]&&await r[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 i.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),s.dispose(),this.transitionState(UserAgentState.Stopped)}_makeInviter(e,t){return new Inviter(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,r=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((r=>{this.logger.error(r.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)}))}),1===e?0:1e3*r))}initContact(){const e=""!==this.options.contactName?this.options.contactName:createRandomToken(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new URI("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const r=e.anonymous||!1,n=e.outbound||!1,i=e.register||!1;let s="<";return s+=r?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:i?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===SIPExtension.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===SIPExtension.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter((e=>UserAgentRegisteredOptionTags[e]))),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const r={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,r=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new DigestAuthentication(this.getLoggerFactory(),r,e,t)},transportAccessor:()=>this.transport};return new UserAgentCore(r,{onInvite:e=>{var t;const r=new Invitation(this,e);if(e.delegate={onCancel:e=>{r._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==SIPExtension.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 i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const s=e+n+i,o=this.userAgentCore.dialogs.get(s);if(!o)return void r.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void r.reject({statusCode:486});const a=this._sessions[e+i]||this._sessions[e+n]||void 0;if(!a)throw new Error("Session does not exist.");r._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return r.autoSendAnInitialProvisionalResponse?void r.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(r)})):void this.delegate.onInvite(r);r.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new Message(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new Notification(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!==UserAgentState.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==UserAgentState.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=Parser.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===UserAgentState.Stopped&&t instanceof IncomingRequestMessage)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const r=()=>{const e=["from","to","call_id","cseq","via"];for(const r of e)if(!t.hasHeader(r))return this.logger.warn(`Missing mandatory header field : ${r}.`),!1;return!0};if(t instanceof IncomingRequestMessage){if(!r())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=utf8Length(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof IncomingResponseMessage){if(!r())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=utf8Length(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 IncomingRequestMessage)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof IncomingResponseMessage))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const r=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case UserAgentState.Started:e!==UserAgentState.Stopped&&r();break;case UserAgentState.Stopped:e!==UserAgentState.Started&&r();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 ON_USER_AGENT="onUserAgent",ON_REGISTERED="onRegistered",ON_UNREGISTERED="onUnRegistered",ON_PROGRESS$1="onProgress",ON_CALL_ACCEPTED="onCallAccepted",ON_CALL_ANSWERED="onCallAnswered",ON_CALL_INCOMING="onCallIncoming",ON_CALL_OUTGOING="onCallOutgoing",ON_CALL_MUTED="onCallMuted",ON_CALL_UNMUTED="onCallUnmuted",ON_CALL_RESUMED="onCallResumed",ON_CALL_HELD="onCallHeld",ON_CALL_UNHELD="onCallUnHeld",ON_CAMERA_DISABLED="onCameraDisabled",ON_CAMERA_RESUMED="onCameraResumed",ON_CALL_CANCELED="onCallCanceled",ON_CALL_FAILED="onCallFailed",ON_CALL_REJECTED="onCallRejected",ON_CALL_ENDED="onCallEnded",ON_CALL_ENDING="onCallEnding",ON_MESSAGE="onMessage",ON_REINVITE$1="reinvite",ON_TRACK$1="onTrack",ON_AUDIO_STREAM="onAudioStream",ON_VIDEO_STREAM="onVideoStream",ON_REMOVE_STREAM="onRemoveStream",ON_SHARE_SCREEN_STARTED="onScreenShareStarted",ON_SHARE_SCREEN_ENDING="onScreenShareEnding",ON_SHARE_SCREEN_ENDED="onScreenShareEnded",ON_TERMINATE_SOUND="terminateSound",ON_PLAY_RING_SOUND="playRingingSound",ON_PLAY_INBOUND_CALL_SIGNAL_SOUND="playInboundCallSignalSound",ON_PLAY_HANGUP_SOUND="playHangupSound",ON_PLAY_PROGRESS_SOUND="playProgressSound",ON_VIDEO_INPUT_CHANGE="videoInputChange",ON_CALL_ERROR="onCallError",ON_MESSAGE_TRACK_UPDATED="onTrackUpdated",ON_NETWORK_STATS$1="onNetworkStats",ON_CHAT="phone/ON_CHAT",ON_SIGNAL="phone/ON_SIGNAL",ON_DISCONNECTED$1="onDisconnected",ON_EARLY_MEDIA$1="onEarlyMedia",MESSAGE_TYPE_CHAT="message/TYPE_CHAT",MESSAGE_TYPE_SIGNAL="message/TYPE_SIGNAL",events$1=[ON_USER_AGENT,ON_REGISTERED,ON_UNREGISTERED,ON_PROGRESS$1,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_CALL_FAILED,ON_CALL_ENDED,ON_CALL_REJECTED,ON_MESSAGE,ON_REINVITE$1,ON_TRACK$1,ON_AUDIO_STREAM,ON_VIDEO_STREAM,ON_REMOVE_STREAM,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_SHARE_SCREEN_STARTED,ON_CALL_ERROR,ON_CHAT,ON_SIGNAL,ON_NETWORK_STATS$1,ON_DISCONNECTED$1,ON_EARLY_MEDIA$1],logger$8=IssueReporter$1.loggerFor("webrtc-phone");class WebRTCPhone extends Emitter{client;allowVideo;callSessions;incomingSessions;currentSipSession;currentCallSession;audioOutputDeviceId;audioRingDeviceId;audioOutputVolume;audioRingVolume;ringingEnabled;acceptedSessions;rejectedSessions;ignoredSessions;currentScreenShare;lastScreenShare;shouldSendReinvite;constructor(e,t,r=!1,n){super(),this.client=e,this.allowVideo=r,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 logger$8.info("WebRTC register",{client:!!this.client}),this.client?this.client.register().then((()=>(logger$8.info("WebRTC register, registered"),this.bindClientEvents()))).catch((e=>{console.error("register error",e,e.message,e.stack),logger$8.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&&(logger$8.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,r=!1,n=!1,i=!1){const s=this.findSipSession(e);if(logger$8.info("WebRTC phone - send reinvite",{sessionId:s?s.id:null,constraints:t,audioOnly:n,conference:r,iceRestart:i}),!s)return;const o=t?.screen,a=o||t?.video;if(!t||a){if(a){if(!await this._upgradeToVideo(e,t,r))return}return this.client.reinvite(s,t,r,n,i)}this._downgradeToAudio(e)}getUserAgent(){return this.client?.config?.userAgentString||"webrtc-phone"}startHeartbeat(){logger$8.info("WebRTC phone - start heartbeat",{client:!!this.client,hasHeartbeat:this.client.hasHeartbeat()}),this.client&&!this.client.hasHeartbeat()&&this.client.startHeartbeat()}stopHeartbeat(){logger$8.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(){logger$8.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 r=this.findSipSession(e);return!!r&&(logger$8.info("Downgrade to audio",{id:e?e.getId():null,withMessage:t}),this.client.downgradeToAudio(r),e&&(e.cameraEnabled=!1,this._updateCallSession(e)),t&&this._sendReinviteMessage(e,!1),!0)}async _upgradeToVideo(e,t,r){const n=this.findSipSession(e);if(!n)return Promise.resolve(!1);logger$8.info("Upgrade to video",{id:e?e.getId():null,constraints:t,isConference:r});const i=t&&!!t.screen,s=t&&t.desktop,o=n.sessionDescriptionHandlerOptionsReInvite,a=o?.audioOnly,d=await this.client.upgradeToVideo(n,t,r);return e&&(e.cameraEnabled=!0,this._updateCallSession(e)),!d||(this._sendReinviteMessage(e,!0),i&&this._onScreenSharing(d,n,e,!1,s),!(!r||!a))}_sendReinviteMessage(e,t){const r=this.findSipSession(e);logger$8.info("Sending reinvite message",{id:e?e.getId():null,isUpgrade:t}),setTimeout((()=>{this.sendMessage(r,JSON.stringify({type:MESSAGE_TYPE_SIGNAL,content:{type:ON_MESSAGE_TRACK_UPDATED,update:t?"upgrade":"downgrade",sipCallId:r&&this.getSipSessionId(r),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 Invitation){const r=e._onCancel.bind(e);e._onCancel=n=>{logger$8.trace("on sip session canceled",{callId:n.callId,sipSessionId:t}),r(n);const i=-1!==n.data.indexOf("cause=26")&&-1!==n.data.indexOf("completed elsewhere"),s=this._createCallSession(e);delete this.callSessions[t],this.eventEmitter.emit(ON_CALL_CANCELED,s,i)}}if(e.stateChange.addListener((t=>{switch(t){case SessionState$1.Terminating:logger$8.info("WebRTC phone - call terminating",{sipId:e.id}),this.eventEmitter.emit(ON_CALL_ENDING,this._createCallSession(e));break;case SessionState$1.Terminated:{logger$8.info("WebRTC phone - call terminated",{sipId:e.id});const t=this._createCallSession(e);t.endTime=new Date;const r=this._onCallTerminated(e);return this.eventEmitter.emit(ON_CALL_ENDED,t,r)}}})),!e.sessionDescriptionHandler)return;const r=e.sessionDescriptionHandler.peerConnection;r?(r.ontrack=t=>{const r=t,[n]=r.streams,i=r&&r.track&&r.track.kind;return logger$8.info("on track stream called on the peer connection",{callId:this.getSipSessionId(e),streamId:n?n.id:null,tracks:n?n.getTracks():null,kind:i}),"audio"===i?this.eventEmitter.emit(ON_AUDIO_STREAM,n):this.eventEmitter.emit(ON_VIDEO_STREAM,n,r.track.id,r,e)},r.onremovestream=e=>{logger$8.info("on remove stream called on the peer connection",{id:e.stream.id,tracks:e.stream.getTracks()}),this.eventEmitter.emit(ON_REMOVE_STREAM,e.stream)}):logger$8.info("null peer connection")}async startScreenSharing(e,t){logger$8.info("WebRTC - start screen sharing",{constraints:e,id:t?t.getId():null});const r=await this.client.getStreamFromConstraints(e);if(!r)throw new Error(`Can't create media stream for screensharing with: ${JSON.stringify(e)}`);const n=r.getVideoTracks()[0],i=this.currentSipSession,s=i&&this.client.getPeerConnection(this.getSipSessionId(i)),o=s&&s.getSenders&&s.getSenders().find((e=>e&&e.track&&"video"===e.track.kind)),a=i&&this.client.getLocalStream(this.getSipSessionId(i)),d=a?a.getTracks().find((e=>"video"===e.kind)):null,c=!!d;return d&&a&&(d.enabled=!1,d.stop(),a.removeTrack(d)),a&&a.addTrack(n),o&&o.replaceTrack(n),this._onScreenSharing(r,i,t,c,e.desktop),r}async stopScreenSharing(e=!0,t){if(!this.currentScreenShare)return;logger$8.info("WebRTC phone - stop screen sharing",{restoreLocalStream:e});let r=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),i={audio:!1,video:this.currentScreenShare.hadVideo};this._downgradeToAudio(e,!1),await new Promise((e=>setTimeout(e,500))),r=await this.sendReinvite(e,i,n)}}catch(e){console.warn(e)}const n=this.currentSipSession;return this.eventEmitter.emit(ON_SHARE_SCREEN_ENDED,t&&n?this._createCallSession(n,t,{screensharing:!1}):null),this.currentScreenShare=null,r}_onScreenSharing(e,t,r,n,i){const s=e.getVideoTracks()[0],o=this.getSipSessionId(t),a=this.client.getPeerConnection(o),d=a&&a.getSenders&&a.getSenders().find((e=>e&&e.track&&"video"===e.track.kind));logger$8.info("WebRTC phone - on screensharing",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),s&&(s.onended=()=>{logger$8.info("WebRTC phone - on screenshare ended",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),this.eventEmitter.emit(ON_SHARE_SCREEN_ENDING,this._createCallSession(t,r))}),this.currentScreenShare={stream:e,hadVideo:n,sender:d,sipSessionId:o,desktop:i},this.client.setLocalMediaStream(this.getSipSessionId(t),e),this.eventEmitter.emit(ON_SHARE_SCREEN_STARTED,this._createCallSession(t,r,{screensharing:!0}),e)}_onCallAccepted(e,t){logger$8.info("WebRTC phone - on call accepted",{sipId:e.id,cameraEnabled:t});const r=this._createAcceptedCallSession(e,t);this.currentSipSession&&!this.isCurrentCallSipSession(r)&&(logger$8.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=r,this.eventEmitter.emit(ON_TERMINATE_SOUND,r,"call accepted");const n=this.getSipSessionId(e);return n&&this.removeIncomingSessions(n),r.answerTime=new Date,this._updateCallSession(r),this.eventEmitter.emit(ON_CALL_ACCEPTED,r,t),r}changeAudioDevice(e){logger$8.info("WebRTC phone - change audio device",{deviceId:e}),this.audioOutputDeviceId=e,this.client.changeAudioOutputDevice(e)}createAudioElementFor(e){return this.client.createAudioElementFor(e)}changeRingDevice(e){logger$8.info("WebRTC phone - changing ring device",{id:e}),this.audioRingDeviceId=e}changeAudioVolume(e){logger$8.info("WebRTC phone - changing audio volume",{volume:e}),this.audioOutputVolume=e,this.client.changeAudioOutputVolume(e)}changeRingVolume(e){logger$8.info("WebRTC phone - changing ring volume",{volume:e}),this.audioRingVolume=e}changeAudioInputDevice(e,t){return logger$8.info("WebRTC phone - changeAudio input device",{deviceId:e}),this.client.changeAudioInputDevice(e,this.currentSipSession,t)}async changeVideoInputDevice(e){return logger$8.info("WebRTC phone - change video input device",{deviceId:e}),this.client.changeVideoInputDevice(e,this.currentSipSession)}changeSessionVideoInputDevice(e){return logger$8.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);logger$8.info("WebRTC phone - on call terminated",{sipId:e.id,sipSessionId:t,ids:Object.keys(this.callSessions)});const r=this._createCallSession(e),n=this.isCurrentCallSipSession(r),i=r.is(this.getIncomingCallSession()),s=n?this.incomingSessions.length:i;i&&setTimeout((()=>{this.eventEmitter.emit(ON_TERMINATE_SOUND,r,"call terminated")}),5),t&&this.removeIncomingSessions(t),delete this.callSessions[t],n&&(this.currentSipSession=void 0,this.currentCallSession=void 0);const o=this.hasIncomingCallSession();if(logger$8.info("WebRTC phone - check to re-trigger incoming call",{sipId:e.id,shouldRetrigger:s,hasIncomingCallSession:o}),this.client.onCallEnded(e),o&&s){const e=this.getIncomingCallSession();setTimeout((()=>{this.ringingEnabled&&(this.currentCallSession?this.eventEmitter.emit(ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,e):this.eventEmitter.emit(ON_PLAY_RING_SOUND,this.audioRingDeviceId,this.audioRingVolume,e)),this.eventEmitter.emit(ON_CALL_INCOMING,e,e?.cameraEnabled)}),100)}return!(r.getId()in this.ignoredSessions)&&(e.isCanceled||setTimeout((()=>{this.eventEmitter.emit(ON_PLAY_HANGUP_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,r)}),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 logger$8.warn("WebRTCPhone.getLocalStreamForCall is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}getRemoteStreamForCall(e){return logger$8.warn("WebRTCPhone.getRemoteStreamForCall is deprecated, use WebRTCPhone.getRemoteStream instead"),this.getRemoteVideoStream(e)}getRemoteStreamsForCall(e){return logger$8.warn("WebRTCPhone.getRemoteStreamsForCall is deprecated, use WebRTCPhone.getRemoteStreams instead"),this.getRemoteStream(e)}accept(e,t){if(logger$8.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 logger$8.warn("no CallSession to accept."),Promise.resolve(null);const r=this.getSipSessionIdFromCallSession(e);if(r&&!(r in this.callSessions))return logger$8.warn("Call session already ended or not found, can't accept it.",{sipSessionId:r}),Promise.resolve(null);if(e.getId()in this.acceptedSessions)return logger$8.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(ON_CALL_ANSWERED,e);const n=this.client.getSipSession(e.getId());if(n)return logger$8.info("accept call, session found",{sipId:n.id}),this.client.answer(n,!!this.allowVideo&&t).then((()=>e.sipCallId)).catch((t=>{throw logger$8.error(t),this.endCurrentCall(e),t}));const i="No CallSession found to accept.";return logger$8.warn(i,{id:e?e.getId():"n/a",ids:this.client.getSipSessionIds()}),e&&this.eventEmitter.emit(ON_CALL_ERROR,new Error(i),e),Promise.resolve(null)}isAccepted(e){return e&&e.getId()in this.acceptedSessions}async reject(e){if(logger$8.info("reject WebRTC called",{id:e.getId()}),this.eventEmitter.emit(ON_TERMINATE_SOUND,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&&(logger$8.info("WebRTC rejecting",{sipId:t.id}),this.client.hangup(t))}async ignore(e){logger$8.info("WebRTC ignore",{id:e.getId()}),this.eventEmitter.emit(ON_TERMINATE_SOUND,e,"ignoring call"),this.ignoredSessions[e.getId()]=!0,e.ignore()}atxfer(e){const t=this.findSipSession(e);if(t)return logger$8.info("WebRTC atxfer",{sipId:t.id}),this.client.atxfer(t)}hold(e,t=!0){logger$8.info("WebRTC hold",{id:e.getId()});const r=this.findSipSession(e);return r?this.holdSipSession(r,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){logger$8.info("WebRTC resume called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return new Promise(((e,t)=>t(new Error("No session to resume"))));logger$8.info("WebRTC resuming",{sipId:r.id}),this.currentSipSession&&this.currentSipSession.id!==r.id&&(logger$8.info("WebRTC hold call after resume",{id:this.currentSipSession.id}),this.holdSipSession(this.currentSipSession,this.currentCallSession,t));const n=this.unholdSipSession(r,e,t);return this.currentSipSession=r,e&&(this.currentCallSession=e),n}async holdSipSession(e,t,r=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to hold"))));const n=this.getSipSessionId(e),i=this.client.hasLocalVideo(n);logger$8.info("WebRTC hold sip session",{sipId:e.id,hasVideo:i}),this.currentScreenShare&&this.currentScreenShare.sipSessionId===n&&(this.lastScreenShare=this.currentScreenShare,await this.stopScreenSharing(!1,t)),i&&await this.client.downgradeToAudio(e);const s=!!t&&t.isConference(),o=this.client.hold(e,s,i);return r&&this.eventEmitter.emit(ON_CALL_HELD,this._createCallSession(e,t)),o}async unholdSipSession(e,t,r=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to unhold"))));const n=!!t&&t.isConference(),i=this.getSipSessionId(e);logger$8.info("WebRTC unhold sip session",{sessionId:i,isConference:n});const{hasVideo:s}=this.client.getHeldSession(i)||{},o=this.lastScreenShare&&this.lastScreenShare.sipSessionId===i,a=this.lastScreenShare&&this.lastScreenShare.desktop,d=this.client.unhold(e,n);if(s){const t={audio:!1,video:!0,screen:o,desktop:a};await this.client.upgradeToVideo(e,t,n)}const c=r=>{const n=this.lastScreenShare&&this.lastScreenShare.hadVideo;r&&this._onScreenSharing(r,e,t,n),this.lastScreenShare=null};if(r){t&&(t.muted=!1);const r=this._createCallSession(e,t);this.eventEmitter.emit(ON_CALL_UNHELD,r),this.eventEmitter.emit(ON_CALL_RESUMED,r)}return d.then((()=>{const e=t?this.getLocalVideoStream(t):null;return o&&c(e),e}))}mute(e,t=!0){logger$8.info("WebRTC mute called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return;logger$8.info("WebRTC muting",{sipId:r.id}),this.client.mute(r);const n=this._createCallSession(r,e,{muted:!0});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(ON_CALL_MUTED,n)}unmute(e,t=!0){logger$8.info("WebRTC unmute called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return;logger$8.info("WebRTC unmuting",{sipId:r.id}),this.client.unmute(r);const n=this._createCallSession(r,e,{muted:!1});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(ON_CALL_UNMUTED,n)}isAudioMuted(e){const t=this.findSipSession(e);return!t||this.client.isAudioMuted(t)}turnCameraOn(e){const t=this.findSipSession(e);t&&(logger$8.info("WebRTC turn camera on",{sipId:t.id}),this.client.toggleCameraOn(t),this.eventEmitter.emit(ON_CAMERA_RESUMED,this._createCameraResumedCallSession(t,e)))}turnCameraOff(e){const t=this.findSipSession(e);t&&(logger$8.info("WebRTC turn camera off",{sipId:t.id}),this.client.toggleCameraOff(t),this.eventEmitter.emit(ON_CAMERA_DISABLED,this._createCameraDisabledCallSession(t,e)))}sendKey(e,t){const r=this.findSipSession(e);r&&(logger$8.info("WebRTC send key",{sipId:r.id,tone:t}),this.client.sendDTMF(r,t))}async makeCall(e,t,r,n=!1,i=!1){if(logger$8.info("make WebRTC call",{number:e,lineId:t?t.id:null,cameraEnabled:r,audioOnly:n,conference:i}),!e)return Promise.resolve(null);let s;this.client.isRegistered()||await this.client.register(),this.currentSipSession&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0).catch((e=>{logger$8.warn("Unable to hold current session when making another call",e)}));try{s=this.client.call(e,!!this.allowVideo&&r,n,i),this._bindEvents(s)}catch(e){return logger$8.warn("make WebRTC call, error",{message:e.message,stack:e.stack}),Promise.resolve(null)}const o=this._createOutgoingCallSession(s,r||!1);return o.setIsConference(i),o.creationTime=new Date,this._updateCallSession(o),this.eventEmitter.emit(ON_PLAY_PROGRESS_SOUND,this.audioOutputDeviceId,this.audioOutputVolume),this.currentSipSession=s,this.currentCallSession=o,this.eventEmitter.emit(ON_CALL_OUTGOING,o),s.invitePromise&&s.invitePromise.catch((e=>{this.eventEmitter.emit(ON_CALL_ERROR,e,o)})),Promise.resolve(o)}transfer(e,t){const r=this.findSipSession(e);r&&(logger$8.info("WebRTC transfer",{sipId:r.id,target:t}),this.client.transfer(r,t))}async indirectTransfer(e,t){const r=this.client.getSipSession(e.sipCallId),n=this.client.getSipSession(t.sipCallId);return logger$8.info("WebRTC indirect transfer",{sipId:r?r.id:null,target:n?n.id:null}),n?new Promise((e=>{const i={requestDelegate:{onAccept:()=>{setTimeout((()=>{this.hangup(t).then(e)}),200)}}};return n.refer(r,i)})):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 r=this.getSipSessionId(t);return logger$8.info("WebRTC hangup",{sipId:t.id,sipSessionId:r}),await this.client.hangup(t),e?this.endCurrentCall(e):r&&delete this.callSessions[r],this.shouldSendReinvite=!1,!0}async getStats(e){const t=this.findSipSession(e);return t?this.client.getStats(t):null}startNetworkMonitoring(e,t=1e3){const r=this.findSipSession(e);return r?this.client.startNetworkMonitoring(r,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){logger$8.info("force cancel, error",e)}}endCurrentCall(e){const t=this.isCurrentCallSipSession(e);logger$8.info("Ending current call",{id:e?e.getId():null,isCurrent:t}),t&&(this.currentSipSession=void 0,this.currentCallSession=void 0),this.eventEmitter.emit(ON_TERMINATE_SOUND,e,"locally ended")}onConnectionMade(){}isConference(e){return!!e&&(this.client&&this.client.isConference(e.sipCallId))}async close(e=!1){logger$8.info("WebRTC close");try{await Promise.race([this.unregister(),new Promise(((e,t)=>setTimeout((()=>t(new Error("Unregister, timed out"))),3e3)))])}catch(e){logger$8.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(){logger$8.info("WebRTC enable ringing"),this.ringingEnabled=!0}disableRinging(){logger$8.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,r="text/plain"){return this.client.sendMessage(e,t,r)}getLocalStream(e){return e?this.client.getLocalStream(e.sipCallId):null}getLocalVideoStream(e){return e?this.client.getLocalVideoStream(e.sipCallId):null}getLocalMediaStream(e){return logger$8.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 r="Auto"===e.request.getHeader("Answer-Mode"),n=!!this.allowVideo&&t;logger$8.info("WebRTC invite received",{sipId:e.id,withVideo:n,autoAnswer:r});const i=this._createIncomingCallSession(e,n,null,r);this.incomingSessions.push(i.getId()),this._bindEvents(e),this.client.storeSipSession(e),this.currentSipSession?this.eventEmitter.emit(ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,i):this.ringingEnabled&&this.eventEmitter.emit(ON_PLAY_RING_SOUND,this.audioRingDeviceId,this.audioRingVolume,i),i.creationTime=new Date,this._updateCallSession(i),this.eventEmitter.emit(ON_CALL_INCOMING,i,t)})),this.client.on(this.client.ON_REINVITE,((...e)=>{logger$8.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,(e=>{const t=this.getSipSessionId(e),r=t in this.callSessions;logger$8.info("WebRTC call accepted",{sipId:t,hasSession:r}),r?(this._onCallAccepted(e,this.client.hasVideo(t)),this.audioOutputDeviceId&&this.client.changeAudioOutputDevice(this.audioOutputDeviceId)):logger$8.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=>{logger$8.error("WebRTC error",e),this.eventEmitter.emit(ON_CALL_ERROR,e)})),this.client.on(this.client.REJECTED,(e=>{logger$8.info("WebRTC call rejected",e.id);const t=this._createCallSession(e);delete this.callSessions[this.getSipSessionId(e)],t.endTime=new Date,this.eventEmitter.emit(ON_CALL_REJECTED,t)})),this.client.on(this.client.UNREGISTERED,(()=>{logger$8.info("WebRTC unregistered"),this.eventEmitter.emit(ON_UNREGISTERED)})),this.client.on(this.client.ON_DISCONNECTED,(()=>{logger$8.info("WebRTC disconnected"),this.eventEmitter.emit(ON_DISCONNECTED$1)})),this.client.on(this.client.ON_PROGRESS,(e=>{logger$8.info("WebRTC progess (180)"),this.eventEmitter.emit(ON_PROGRESS$1,this._createCallSession(e,null,{incoming:!1,ringing:!0}),this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.ON_EARLY_MEDIA,(e=>{logger$8.info("WebRTC early media");const t=this._createCallSession(e);this.eventEmitter.emit(ON_EARLY_MEDIA$1,t)})),this.client.on(this.client.REGISTERED,(()=>{if(logger$8.info("WebRTC registered",{shouldSendReinvite:this.shouldSendReinvite,state:this.currentSipSession?this.currentSipSession.state:null,currentSipSession:!!this.currentSipSession}),this.stopHeartbeat(),this.eventEmitter.emit(ON_REGISTERED),this.shouldSendReinvite&&this.currentSipSession&&this.currentSipSession.state===SessionState$1.Established){this.shouldSendReinvite=!1;const e=this.currentSipSession?.sessionDescriptionHandler?.peerConnection,t=!!e&&e.sfu,r=this.currentCallSession&&this.currentCallSession.cameraEnabled;try{this.sendReinvite(this.currentCallSession,null,t,!r,!0)}catch(e){logger$8.error("WebRTC reinvite after register, error",{message:e.message,stack:e.stack})}}})),this.client.on(this.client.CONNECTED,(()=>{logger$8.info("WebRTC client connected"),this.stopHeartbeat()})),this.client.on(this.client.DISCONNECTED,(()=>{logger$8.info("WebRTC client disconnected"),this.eventEmitter.emit(ON_UNREGISTERED),this.client.hasHeartbeat()||this.startHeartbeat(),this.shouldSendReinvite=!0})),this.client.on(this.client.ON_TRACK,((e,t)=>{this.eventEmitter.emit(ON_TRACK$1,e,t)})),this.client.on("onVideoInputChange",(e=>{this.eventEmitter.emit(ON_VIDEO_INPUT_CHANGE,e)})),this.client.on(this.client.MESSAGE,(e=>{this._onMessage(e),this.eventEmitter.emit(ON_MESSAGE,e)})),this.client.on(this.client.ON_NETWORK_STATS,((e,t,r)=>{const n=this.getCallSession(this.getSipSessionId(e));this.eventEmitter.emit(ON_NETWORK_STATS$1,n,t,r)})),this.client.on(this.client.ON_SCREEN_SHARING_REINVITE,((e,t,r)=>{const n=this.getSipSessionId(e),i=this.client.getLocalStream(n),s=this.callSessions[n];logger$8.info("Updrading directly in screensharing mode",{sipSessionId:n,tracks:i?.getTracks()||null}),this._onScreenSharing(i,e,s,!1,r)}))}findSipSession(e){const t=this.client.getSipSessionIds(),r=t.findIndex((t=>e&&e.isId(t)));if(-1===r){const e=this.currentSipSession?this.getSipSessionId(this.currentSipSession):this.client.getSipSessionIds()[0];return e?this.client.getSipSession(e):null}return this.client.getSipSession(t[r])}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:r,content:n}=t;switch(r){case MESSAGE_TYPE_CHAT:this.eventEmitter.emit(ON_CHAT,n);break;case MESSAGE_TYPE_SIGNAL:this.eventEmitter.emit(ON_SIGNAL,n)}}_createIncomingCallSession(e,t,r,n=!1){return this._createCallSession(e,r,{incoming:!0,ringing:!0,cameraEnabled:t,autoAnswer:n})}_createOutgoingCallSession(e,t,r){return this._createCallSession(e,r,{incoming:!1,ringing:!0,cameraEnabled:t})}_createAcceptedCallSession(e,t,r){return this._createCallSession(e,r,{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,r={}){const n=e?e.remoteIdentity||e.assertedIdentity:null,i=n?n.uri._normal.user:null,{state:s}=e||{},o=this.getSipSessionId(e);t=t||this.callSessions[o];const a=new CallSession({callId:t&&t.callId,sipCallId:o,sipStatus:s,displayName:n&&n.displayName||i,startTime:t?t.startTime:new Date,creationTime:t?t.creationTime:null,answerTime:t?t.answerTime:null,endTime:t?t.endTime:null,answered:s===SessionState$1.Established,paused:this.client.isCallHeld(e),isCaller:t?t.isCaller:"incoming"in r&&!r.incoming,cameraEnabled:t?t.isCameraEnabled():this.client.hasVideo(o),number:i,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(),...r});return this.callSessions[o]=a,a}}var PHONE_EVENTS=Object.freeze({__proto__:null,MESSAGE_TYPE_CHAT:MESSAGE_TYPE_CHAT,MESSAGE_TYPE_SIGNAL:MESSAGE_TYPE_SIGNAL,ON_AUDIO_STREAM:ON_AUDIO_STREAM,ON_CALL_ACCEPTED:ON_CALL_ACCEPTED,ON_CALL_ANSWERED:ON_CALL_ANSWERED,ON_CALL_CANCELED:ON_CALL_CANCELED,ON_CALL_ENDED:ON_CALL_ENDED,ON_CALL_ENDING:ON_CALL_ENDING,ON_CALL_ERROR:ON_CALL_ERROR,ON_CALL_FAILED:ON_CALL_FAILED,ON_CALL_HELD:ON_CALL_HELD,ON_CALL_INCOMING:ON_CALL_INCOMING,ON_CALL_MUTED:ON_CALL_MUTED,ON_CALL_OUTGOING:ON_CALL_OUTGOING,ON_CALL_REJECTED:ON_CALL_REJECTED,ON_CALL_RESUMED:ON_CALL_RESUMED,ON_CALL_UNHELD:ON_CALL_UNHELD,ON_CALL_UNMUTED:ON_CALL_UNMUTED,ON_CAMERA_DISABLED:ON_CAMERA_DISABLED,ON_CAMERA_RESUMED:ON_CAMERA_RESUMED,ON_CHAT:ON_CHAT,ON_DISCONNECTED:ON_DISCONNECTED$1,ON_EARLY_MEDIA:ON_EARLY_MEDIA$1,ON_MESSAGE:ON_MESSAGE,ON_MESSAGE_TRACK_UPDATED:ON_MESSAGE_TRACK_UPDATED,ON_NETWORK_STATS:ON_NETWORK_STATS$1,ON_PLAY_HANGUP_SOUND:ON_PLAY_HANGUP_SOUND,ON_PLAY_INBOUND_CALL_SIGNAL_SOUND:ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,ON_PLAY_PROGRESS_SOUND:ON_PLAY_PROGRESS_SOUND,ON_PLAY_RING_SOUND:ON_PLAY_RING_SOUND,ON_PROGRESS:ON_PROGRESS$1,ON_REGISTERED:ON_REGISTERED,ON_REINVITE:ON_REINVITE$1,ON_REMOVE_STREAM:ON_REMOVE_STREAM,ON_SHARE_SCREEN_ENDED:ON_SHARE_SCREEN_ENDED,ON_SHARE_SCREEN_ENDING:ON_SHARE_SCREEN_ENDING,ON_SHARE_SCREEN_STARTED:ON_SHARE_SCREEN_STARTED,ON_SIGNAL:ON_SIGNAL,ON_TERMINATE_SOUND:ON_TERMINATE_SOUND,ON_TRACK:ON_TRACK$1,ON_UNREGISTERED:ON_UNREGISTERED,ON_USER_AGENT:ON_USER_AGENT,ON_VIDEO_INPUT_CHANGE:ON_VIDEO_INPUT_CHANGE,ON_VIDEO_STREAM:ON_VIDEO_STREAM,default:WebRTCPhone,events:events$1});let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function wrapPeerConnectionEvent(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(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),i.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),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 disableLog(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(logDisabled_=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(deprecationWarnings_=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){deprecationWarnings_&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(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:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=extractVersion(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=extractVersion(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=extractVersion(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,r){const n=isObject(e[r]),i=n?compactObject(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function walkStats(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?walkStats(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach((t=>{walkStats(e,e.get(t),r)}))})))}function filterStats(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===n&&r.trackId===t.id&&walkStats(e,r,i)}))})),i}const logging=log;function shimGetUserMedia$2(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=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[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=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 o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){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 r.mediaDevices.enumerateDevices().then((r=>{r=r.filter((e=>"videoinput"===e.kind));let o=r.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),logging("chrome: "+JSON.stringify(e)),i(e)}))}e.video=n(e.video)}return logging("chrome: "+JSON.stringify(e)),i(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(r.getUserMedia=function(e,t,n){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(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 shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const n=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(r.video.mandatory.maxWidth=n),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(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",(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(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 r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};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 r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.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 shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,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 i=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){r(s(i(e)))};return t.apply(this,[n,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,n)}}function shimSenderReceiverGetStats(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(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}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(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,r,n;return this.getSenders().forEach((r=>{r.track===e&&(t?n=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?n=!0:r=t),t.track===e))),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(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,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};const r=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();r.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 i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),i.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.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 r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,r){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 i=this._streams[r.id];if(i)i.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.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((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var chromeShim=Object.freeze({__proto__:null,fixNegotiationNeeded:fixNegotiationNeeded,shimAddTrackRemoveTrack:shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative:shimAddTrackRemoveTrackWithNative,shimGetDisplayMedia:shimGetDisplayMedia$1,shimGetSendersWithDtmf:shimGetSendersWithDtmf,shimGetStats:shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream:shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats:shimSenderReceiverGetStats});function shimGetUserMedia$1(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}function shimOnTrack(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 shimPeerConnection(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 r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const r={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,i,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function shimSenderGetStats(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.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 shimReceiverGetStats(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}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(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 r=e.length>0;r&&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(r){const{sender:t}=n,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function shimGetParameters(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 shimCreateOffer(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 shimCreateAnswer(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 firefoxShim=Object.freeze({__proto__:null,shimAddTransceiver:shimAddTransceiver,shimCreateAnswer:shimCreateAnswer,shimCreateOffer:shimCreateOffer,shimGetDisplayMedia:shimGetDisplayMedia,shimGetParameters:shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack:shimOnTrack,shimPeerConnection:shimPeerConnection,shimRTCDataChannel:shimRTCDataChannel,shimReceiverGetStats:shimReceiverGetStats,shimRemoveStream:shimRemoveStream,shimSenderGetStats:shimSenderGetStats});function shimLocalStreamsAPI(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((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.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 r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function shimRemoteStreamsAPI(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 r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function shimGetUserMedia(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let n=e.iceServers[r];void 0===n.urls&&n.url?(deprecated("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function shimTrackEventTransceiver(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 shimCreateOfferLegacy(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 r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var safariShim=Object.freeze({__proto__:null,shimAudioContext:shimAudioContext,shimCallbacksAPI:shimCallbacksAPI,shimConstraints:shimConstraints,shimCreateOfferLegacy:shimCreateOfferLegacy,shimGetUserMedia:shimGetUserMedia,shimLocalStreamsAPI:shimLocalStreamsAPI,shimRTCIceServerUrls:shimRTCIceServerUrls,shimRemoteStreamsAPI:shimRemoteStreamsAPI,shimTrackEventTransceiver:shimTrackEventTransceiver}),sdp$1={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 r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={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":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),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 r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\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 r;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=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:"+r+" "+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="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},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 r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.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,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},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,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.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 r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{i.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.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",r.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let i=0;return r.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let d;const c=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));c.length>0&&c[0].length>1&&c[0][0]===a&&(d=c[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&d&&(t.rtx={ssrc:d}),r.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});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,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},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 r;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:i};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let r=[];return r="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&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){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 r?t.getDirection(r):"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 r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(sdp$1);var sdpExports=sdp$1.exports,SDPUtils=getDefaultExportFromCjs(sdpExports),sdp=_mergeNamespaces({__proto__:null,default:SDPUtils},[sdpExports]);function shimRTCIceCandidate(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 r=new t(e),n=SDPUtils.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,wrapPeerConnectionEvent(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimRTCIceCandidateRelayProtocol(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||wrapPeerConnectionEvent(e,"icecandidate",(e=>{if(e.candidate){const t=SDPUtils.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function shimMaxMessageSize(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 r=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=SDPUtils.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=SDPUtils.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 r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=SDPUtils.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function shimConnectionState(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 r=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 r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function removeExtmapAllowMixed(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=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:r}):t.sdp=r}return r.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.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 r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var commonShim=Object.freeze({__proto__:null,removeExtmapAllowMixed:removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty:shimAddIceCandidateNullOrEmpty,shimConnectionState:shimConnectionState,shimMaxMessageSize:shimMaxMessageSize,shimParameterlessSetLocalDescription:shimParameterlessSetLocalDescription,shimRTCIceCandidate:shimRTCIceCandidate,shimRTCIceCandidateRelayProtocol:shimRTCIceCandidateRelayProtocol,shimSendThrowTypeError:shimSendThrowTypeError});function adapterFactory({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=log,n=detectBrowser(e),i={browserDetails:n,commonShim:commonShim,extractVersion:extractVersion,disableLog:disableLog,disableWarnings:disableWarnings,sdp:sdp};switch(n.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,n),shimMediaStream(e),shimPeerConnection$1(e,n),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,n),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,n),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,n),shimPeerConnection(e,n),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e);break;case"safari":if(!safariShim||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;default:r("Unsupported browser!")}return i}adapterFactory({window:"undefined"==typeof window?void 0:window});const stripMediaDescription=(e,t)=>{const r=new RegExp("m="+t+".*$","gm"),n=new RegExp("^a=group:.*$","gm");if(r.test(e)){let r;const i=(e=e.split(/^m=/gm).filter((e=>{if(e.substr(0,t.length)===t){if(r=e.match(/^a=mid:.*$/gm),r){const e=r[0].match(/:.+$/g);e&&(r=e[0].substr(1))}return!1}return!0})).join("m=")).match(n);if(i&&1===i.length){let t=i[0];const s=new RegExp(" *"+r+"[^ ]*","g");t=t.replace(s,""),e=e.split(n).join(t)}}return e};function stripVideo(e){return e.sdp=stripMediaDescription(e.sdp||"","video"),Promise.resolve(e)}function holdModifier(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const r=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:r})}var getStats$1={exports:{}};!function(e){e.exports=function(e,t,r){var n;(n=void 0!==commonjsGlobal?commonjsGlobal:null)&&"undefined"==typeof window&&void 0!==commonjsGlobal&&(commonjsGlobal.navigator={userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45",getUserMedia:function(){}},commonjsGlobal.console||(commonjsGlobal.console={}),void 0!==commonjsGlobal.console.log&&void 0!==commonjsGlobal.console.error||(commonjsGlobal.console.error=commonjsGlobal.console.log=commonjsGlobal.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===i&&(n.RTCPeerConnection=function(){}),n.window=commonjsGlobal);var i=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 r=e.type.split("-")[0];t="outbound"===r?"send":"inbound"===r?"recv":null}return t}},nomore:function(){c=!0}},o={checkIfOfferer:function(e){"googLibjingleSession"===e.type&&(s.isOfferer=e.googInitiator)}},a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),d=this;if(!(arguments[0]instanceof i))throw"1st argument is not instance of RTCPeerConnection.";d=arguments[0],arguments[1]instanceof MediaStreamTrack&&(e=arguments[1],t=arguments[2],r=arguments[3]);var c=!1;o.datachannel=function(e){"datachannel"===e.type&&(s.datachannel={state:e.state})},o.googCertificate=function(e){"googCertificate"==e.type&&(s.encryption=e.googFingerprintAlgorithm),"certificate"==e.type&&(s.encryption=e.fingerprintAlgorithm)},o.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 r=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,r=n/1024,s.audio[t].availableBandwidth=r.toFixed(1),s.audio.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=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,r=n/1024,s.audio.bytesReceived=r.toFixed(1)),e.googTrackId&&-1===s.audio[t].tracks.indexOf(e.googTrackId)&&s.audio[t].tracks.push(e.googTrackId),e.googCurrentDelayMs&&(r=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&&(r=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))}}},o.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 r=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,r=n/1024,s.video[t].availableBandwidth=r.toFixed(1),s.video.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=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,r=n/1024,s.video.bytesReceived=r.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,r=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,r=n/1024,s.video[t].framerateMean=n.toFixed(1)),e.bitrateMean&&(s.bandwidth.bitrateMean=e.bitrateMean,r=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,r=n/1024,s.video[t].bitrateMean=n.toFixed(1)),e.googCurrentDelayMs&&(r=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&&(r=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))}}},o.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)},o.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 r=s.internal.candidates[t];-1!==r.ipAddress.indexOf(e.googLocalAddress)&&(s.connectionType.local.candidateType=r.candidateType,s.connectionType.local.ipAddress=r.ipAddress,s.connectionType.local.networkType=r.networkType,s.connectionType.local.transport=r.transport),-1!==r.ipAddress.indexOf(e.googRemoteAddress)&&(s.connectionType.remote.candidateType=r.candidateType,s.connectionType.remote.ipAddress=r.ipAddress,s.connectionType.remote.networkType=r.networkType,s.connectionType.remote.transport=r.transport)})),s.connectionType.transport=e.googTransportType,(t=s.internal.candidates[e.localCandidateId])&&t.ipAddress&&(s.connectionType.systemIpAddress=t.ipAddress),(r=s.internal.candidates[e.remoteCandidateId])&&r.ipAddress&&(s.connectionType.systemIpAddress=r.ipAddress)),"candidate-pair"===e.type&&!0===e.selected&&!0===e.nominated&&"succeeded"===e.state)var t=s.internal.candidates[e.remoteCandidateId],r=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),a){var n=e.localCandidateId?"send":"recv";if(!n)return;if(e.bytesSent){var i=0;s.internal.video[n].prevBytesSent||(s.internal.video[n].prevBytesSent=e.bytesSent);var o=e.bytesSent-s.internal.video[n].prevBytesSent;s.internal.video[n].prevBytesSent=e.bytesSent,i=o/1024,s.video[n].availableBandwidth=i.toFixed(1),s.video.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.video[n].prevBytesReceived||(s.internal.video[n].prevBytesReceived=e.bytesReceived),o=e.bytesReceived-s.internal.video[n].prevBytesReceived,s.internal.video[n].prevBytesReceived=e.bytesReceived,i=o/1024,s.video.bytesReceived=i.toFixed(1)),e.availableOutgoingBitrate&&(i=0,s.internal.video[n].prevAvailableOutgoingBitrate||(s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate),o=e.availableOutgoingBitrate-s.internal.video[n].prevAvailableOutgoingBitrate,s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate,i=o/1024,s.video.availableOutgoingBitrate=i.toFixed(1)),e.availableIncomingBitrate&&(i=0,s.internal.video[n].prevAvailableIncomingBitrate||(s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate),o=e.availableIncomingBitrate-s.internal.video[n].prevAvailableIncomingBitrate,s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate,i=o/1024,s.video.availableIncomingBitrate=i.toFixed(1))}}};var l={},u={},h={},g={};o.localcandidate=function(e){"localcandidate"!==e.type&&"local-candidate"!==e.type||e.id&&(l[e.id]||(l[e.id]=[]),u[e.id]||(u[e.id]=[]),h[e.id]||(h[e.id]=[]),g[e.id]||(g[e.id]=[]),e.candidateType&&-1===l[e.id].indexOf(e.candidateType)&&l[e.id].push(e.candidateType),e.transport&&-1===u[e.id].indexOf(e.transport)&&u[e.id].push(e.transport),e.ipAddress&&-1===h[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&h[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===g[e.id].indexOf(e.networkType)&&g[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:l[e.id],ipAddress:h[e.id],portNumber:e.portNumber,networkType:g[e.id],priority:e.priority,transport:u[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.local.candidateType=l[e.id],s.connectionType.local.ipAddress=h[e.id],s.connectionType.local.networkType=g[e.id],s.connectionType.local.transport=u[e.id])};var p={},m={},f={},S={};o.remotecandidate=function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||e.id&&(p[e.id]||(p[e.id]=[]),m[e.id]||(m[e.id]=[]),f[e.id]||(f[e.id]=[]),S[e.id]||(S[e.id]=[]),e.candidateType&&-1===p[e.id].indexOf(e.candidateType)&&p[e.id].push(e.candidateType),e.transport&&-1===m[e.id].indexOf(e.transport)&&m[e.id].push(e.transport),e.ipAddress&&-1===f[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&f[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===S[e.id].indexOf(e.networkType)&&S[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:p[e.id],ipAddress:f[e.id],portNumber:e.portNumber,networkType:S[e.id],priority:e.priority,transport:m[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.remote.candidateType=p[e.id],s.connectionType.remote.ipAddress=f[e.id],s.connectionType.remote.networkType=S[e.id],s.connectionType.remote.transport=m[e.id])},o.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)))},o.inboundrtp=function(e){if(a&&"inbound-rtp"===e.type){var t=e.mediaType||"audio",r=e.isRemote?"recv":"send";if(r){if(e.bytesSent){var n=0;s.internal[t][r].prevBytesSent||(s.internal[t][r].prevBytesSent=e.bytesSent);var i=e.bytesSent-s.internal[t][r].prevBytesSent;s.internal[t][r].prevBytesSent=e.bytesSent,n=i/1024,s[t][r].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][r].prevBytesReceived||(s.internal[t][r].prevBytesReceived=e.bytesReceived),i=e.bytesReceived-s.internal[t][r].prevBytesReceived,s.internal[t][r].prevBytesReceived=e.bytesReceived,n=i/1024,s[t].bytesReceived=n.toFixed(1))}}},o.outboundrtp=function(e){if(a&&"outbound-rtp"===e.type){var t=e.mediaType||"audio",r=e.isRemote?"recv":"send";if(r){if(e.bytesSent){var n=0;s.internal[t][r].prevBytesSent||(s.internal[t][r].prevBytesSent=e.bytesSent);var i=e.bytesSent-s.internal[t][r].prevBytesSent;s.internal[t][r].prevBytesSent=e.bytesSent,n=i/1024,s[t][r].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][r].prevBytesReceived||(s.internal[t][r].prevBytesReceived=e.bytesReceived),i=e.bytesReceived-s.internal[t][r].prevBytesReceived,s.internal[t][r].prevBytesReceived=e.bytesReceived,n=i/1024,s[t].bytesReceived=n.toFixed(1))}}},o.track=function(e){if(a&&"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:[]}};o.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(o).forEach((function(t){if("function"==typeof o[t])try{o[t](e)}catch(e){console.error(e.message,e.stack,e)}}))}));try{-1!==d.iceConnectionState.search(/failed|closed|disconnected/gi)&&(c=!0)}catch(e){c=!0}!0===c&&(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),c||null!=typeof r&&r&&setTimeout(e,r||1e3)}},d.getStats(window.mediaStreamTrack||null).then((function(e){var t=[];e.forEach((function(e){t.push(e)})),n(t)})).catch(n)}()}}(getStats$1);var getStatsExports=getStats$1.exports,getStats=getDefaultExportFromCjs(getStatsExports),lib={},parser$1={},grammar$2={exports:{}},grammar$1=grammar$2.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(grammar$1).forEach((function(e){grammar$1[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$2.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var d=n[t][a];if(d.reg.test(i))return r(d,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.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 r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},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 r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(parser$1);var grammar=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=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 r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach((function(t){grammar[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))})),e.media.forEach((function(e){i.push(makeLine("m",grammar.m[0],e)),n.forEach((function(t){grammar[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1;lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;const parseCandidate$1=e=>{if(!e)return null;const t=lib.parse(0===e.indexOf("a=")?e:`a=${e}`);return t.candidates?t.candidates[0]:null},getSrflxOrRelay=e=>e.filter((e=>e&&("srflx"===e.type||"relay"===e.type))),getVideoDirection=e=>{const t=lib.parse(e).media.find((e=>"video"===e.type));return t?t.direction:null},hasAnActiveVideo=e=>{if(!e)return!1;return!!lib.parse(e).media.find((e=>"video"===e.type&&e.port>10&&(!e.direction||"inactive"!==e.direction)))},fixSdp=(e,t,r=!0)=>{const n=lib.parse(e),i=getSrflxOrRelay(t)[0],s=i?i.ip:null;s&&(n.origin.address=s),n.media=n.media.map((e=>{const n=r&&i?i.port:e.port;return{...e,port:n,candidates:(e.candidates||[]).concat(t),direction:n<10?"inactive":e.direction}}));let o=lib.write(n);return s&&(o=o.replace(/IN IP4 0.0.0.0/g,`IN IP4 ${s}`)),o},addIcesInAllBundles=e=>{const t=lib.parse(e),r=t.media.find((e=>!!e.candidates));if(!r)return e;const{candidates:n}=r;return t.media=t.media.map((e=>({...e,candidates:e.candidates||n}))),lib.write(t)},wazoLogger=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-sdh"):console,wazoMediaStreamFactory=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 WazoSessionDescriptionHandler extends SessionDescriptionHandler{gatheredCandidates;eventEmitter;isWeb;session;constructor(e,t,r,n,i){super(e,t,r),this.eventEmitter=new EventEmitter$2,this.isWeb=n,this.session=i}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 r=!!e.offerOptions&&e.offerOptions.iceRestart,n=!!e&&!!e.conference,i=!!e&&!!e.audioOnly,s=!this.session.pendingReinviteAck&&(r||"constraints"in e),o=void 0===e.iceGatheringTimeout?this.sessionDescriptionHandlerConfiguration?.iceGatheringTimeout:e.iceGatheringTimeout;return wazoLogger.trace("getting SDP description",{iceRestart:r,shouldWaitForIce:s,iceTimeout:o}),this.gatheredCandidates=[],this.peerConnectionDelegate||(this.peerConnectionDelegate={}),this.peerConnectionDelegate.onicecandidate=e=>{wazoLogger.trace("onicecandidate",e.candidate?e.candidate.candidate:{done:!0}),e.candidate&&(this.gatheredCandidates.push(parseCandidate$1(e.candidate.candidate)),-1===e.candidate.candidate.indexOf("srflx")&&-1===e.candidate.candidate.indexOf("relay")||(wazoLogger.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,i))).then((()=>this.createDataChannel(e))).then((()=>{!n||!e.constraints||e.constraints.video||"hold"in e||i||this.peerConnection?.addTransceiver&&this.peerConnection.addTransceiver("video",{streams:[this._localMediaStream],direction:"sendrecv"})})).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(r,o))).then((()=>this.getLocalSessionDescription())).then((t=>{const{sdp:r}=t;return-1!==r.indexOf("a=candidate")?{type:t.type,sdp:addIcesInAllBundles(r)}:(wazoLogger.info("No ICE candidates found in SDP, fixing it with gathered ices",this.gatheredCandidates),{type:t.type,sdp:fixSdp(r,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 wazoLogger.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 r={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=${t.duration||1e3}`}};return this.session.info({requestOptions:r})}close(){if(wazoLogger.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,r=!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,i)=>{if(t)return r&&i.receiver.track&&"video"===i.receiver.track.kind||e&&e.hold?"sendonly":"sendrecv";switch(n){case"inactive":return e&&e.hold?"inactive":t&&!r?"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"})(),i=(()=>{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&&r&&n.track&&"video"===n.track.kind)return void(e.direction="inactive");"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()}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,{sfu:r}=t,n=this._localMediaStream,i=[],s=e=>{const{kind:s}=e;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const o=t.getSenders&&t.getSenders().find((e=>e.track&&e.track.kind===s));!o||r&&"audio"!==e.kind?i.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),SessionDescriptionHandler.dispatchAddTrackEvent(n,e)}))):(o.track&&(e.enabled=o.track.enabled),i.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e(null)})).then((()=>o.replaceTrack(e).then((()=>{const t=n.getTracks().find((e=>e.kind===s));t&&(t.stop(),n.removeTrack(t),SessionDescriptionHandler.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(n,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))))))},o=e.getAudioTracks();o.length&&s(o[0]);const a=e.getVideoTracks();return a.length&&s(a[0]),i.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)))}}const DEFAULT_HEARTBEAT_DELAY=2e3,DEFAULT_HEARTBEAT_TIMEOUT=5e3,DEFAULT_MAX_HEARTBEATS=3;class Heartbeat{heartbeatDelay;heartbeatTimeout;maxHeartbeats;hasHeartbeat;_heartbeatDelayTimeout;_heartbeatNotReceivedTimeout;_heartbeatTries;_sendHeartbeatCallback;_onTimeoutCallback;constructor(e=DEFAULT_HEARTBEAT_DELAY,t=DEFAULT_HEARTBEAT_TIMEOUT,r=DEFAULT_MAX_HEARTBEATS){this.heartbeatDelay=e,this.heartbeatTimeout=t,this.maxHeartbeats=r,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 lastIndexOf=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},replaceLocalIpModifier=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")}),SIP_ID_LENGTH=36,DEFAULT_ICE_TIMEOUT=3e3,SEND_STATS_DELAY=5e3,states=["STATUS_NULL","STATUS_NEW","STATUS_CONNECTING","STATUS_CONNECTED","STATUS_COMPLETED"],logger$7=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-client"):console,statsLogger=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-stats"):console,REGISTERED="registered",UNREGISTERED="unregistered",REGISTRATION_FAILED="registrationFailed",INVITE="invite",CONNECTED="connected",DISCONNECTED="disconnected",TRANSPORT_ERROR="transportError",MESSAGE="message",ACCEPTED="accepted",REJECTED="rejected",ON_TRACK="onTrack",ON_PROGRESS="onProgress",ON_EARLY_MEDIA="onEarlyMedia",ON_REINVITE="reinvite",ON_ERROR="onError",ON_SCREEN_SHARING_REINVITE="onScreenSharingReinvite",ON_NETWORK_STATS="onNetworkStats",ON_DISCONNECTED="onDisconnected",events=[REGISTERED,UNREGISTERED,REGISTRATION_FAILED,INVITE],transportEvents=[CONNECTED,DISCONNECTED,TRANSPORT_ERROR,MESSAGE];class CanceledCallError extends Error{}const MAX_REGISTER_TRIES=5,NO_ANSWER_TIMEOUT=86400;class WebRTCClient extends Emitter{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 WebRTCClient.isAPrivateIp(e)?[{urls:["stun:stun.l.google.com:19302","stun:stun4.l.google.com:19302"]}]:[]}constructor(e,t,r){super(),this.clientId=Math.ceil(1e3*Math.random()),logger$7.info("sdk webrtc constructor",{clientId:this.clientId}),this.uaConfigOverrides=r,this.config=e,this.skipRegister=e.skipRegister,this._buildConfig(e,t).then((e=>{this.config=e,this.userAgent=this.createUserAgent(r)})),this.audioOutputDeviceId=e.audioOutputDeviceId,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 Heartbeat(e.heartbeatDelay,e.heartbeatTimeout,e.maxHeartbeats),this.heartbeat.setSendHeartbeat(this.pingServer.bind(this)),this.heartbeat.setOnHeartbeatTimeout(this._onHeartbeatTimeout.bind(this)),this.REGISTERED=REGISTERED,this.UNREGISTERED=UNREGISTERED,this.REGISTRATION_FAILED=REGISTRATION_FAILED,this.INVITE=INVITE,this.CONNECTED=CONNECTED,this.DISCONNECTED=DISCONNECTED,this.TRANSPORT_ERROR=TRANSPORT_ERROR,this.MESSAGE=MESSAGE,this.ACCEPTED=ACCEPTED,this.REJECTED=REJECTED,this.ON_TRACK=ON_TRACK,this.ON_REINVITE=ON_REINVITE,this.ON_ERROR=ON_ERROR,this.ON_SCREEN_SHARING_REINVITE=ON_SCREEN_SHARING_REINVITE,this.ON_NETWORK_STATS=ON_NETWORK_STATS,this.ON_DISCONNECTED=ON_DISCONNECTED,this.ON_EARLY_MEDIA=ON_EARLY_MEDIA,this.ON_PROGRESS=ON_PROGRESS}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);logger$7.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=>{logger$7.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(INVITE,e,this.sessionWantsToDoVideo(e),t)}};const r=new UserAgent(t);return r.start(),r.transport&&r.transport.connectPromise&&r.transport.connectPromise.catch((e=>{logger$7.warn("Transport connect error",e)})),r.transport.onMessage=e=>{const t=Parser.parseMessage(e,r.transport.logger);r.onTransportMessage(e),this.eventEmitter.emit(MESSAGE,t),t&&t.method===C.MESSAGE&&r.userAgentCore.replyStateless(t,{statusCode:200})},r}isConnected(){return Boolean(this.userAgent?.isConnected())}isConnecting(){return this.userAgent?.transport?.state===TransportState.Connecting}isRegistered(){return Boolean(this.registerer&&this.registerer.state===RegistererState.Registered)}onConnect(){return logger$7.info("sdk webrtc connected",{method:"delegate.onConnect",clientId:this.clientId}),this.eventEmitter.emit(CONNECTED),!this.isRegistered()&&this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.register()}async onDisconnect(e){logger$7.info("sdk webrtc disconnected",{method:"delegate.onConnect",clientId:this.clientId,error:e}),this.connectionPromise=null,this.eventEmitter.emit(DISCONNECTED,e),this.isRegistered()&&(await this.unregister(),this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.eventEmitter.emit(UNREGISTERED))}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 logger$7.info("sdk webrtc skip register...",t),Promise.resolve();if(logger$7.info("sdk webrtc registering...",t),this.userAgent||(logger$7.info("sdk webrtc recreating User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),!this.userAgent||this.isRegistered())return logger$7.info("sdk webrtc registering aborted, already registered or no UA can be created"),Promise.resolve();if(this.connectionPromise||this.registerer?.waiting)return logger$7.info("sdk webrtc registering aborted due to a registration in progress.",{clientId:this.clientId}),Promise.resolve();const r=this._isWeb()?{}:{extraContactHeaderParams:["mobility=mobile"]},n=()=>{logger$7.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<=MAX_REGISTER_TRIES&&(logger$7.info("sdk webrtc registering, retrying...",{clientId:this.clientId,tries:e}),setTimeout((()=>this.register(e+1)),300)))};return this._connectIfNeeded().then((()=>{this.userAgent||(logger$7.info("sdk webrtc recreating User Agent after connection"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),logger$7.info("sdk webrtc registering, transport connected",{registerOptions:r,ua:!!this.userAgent,clientId:this.clientId}),this.registerer=new Registerer(this.userAgent,r),this.connectionPromise=null,this._monkeyPatchRegisterer(this.registerer),this.registerer.stateChange.addListener((e=>{logger$7.info("sdk webrtc registering, state changed",{newState:e,clientId:this.clientId}),e===RegistererState.Registered&&this.registerer&&this.registerer.state===RegistererState.Registered?this.eventEmitter.emit(REGISTERED):e===RegistererState.Unregistered&&this.eventEmitter.emit(UNREGISTERED)}));const e={requestDelegate:{onReject:e=>{logger$7.error("sdk webrtc registering, rejected",{clientId:this.clientId,response:e}),n()}}};return this.registerer.register(e).catch((e=>(logger$7.error("sdk webrtc registering, error",e),this.eventEmitter.emit(REGISTRATION_FAILED),e)))})).catch((e=>{logger$7.error("sdk webrtc registering, transport error",e),n()}))}_monkeyPatchRegisterer(e){if(!e)return;const t=e.waitingToggle.bind(e),r=e.unregistered.bind(e);e.waitingToggle=r=>{e&&e.waiting!==r&&t(r)},e.unregistered=()=>{e&&e.state!==RegistererState.Terminated&&r()}}async unregister(){logger$7.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 r=t=>{t===RegistererState.Unregistered&&(logger$7.info("sdk webrtc unregistered",{clientId:this.clientId}),this.registerer&&this.registerer.stateChange.addListener(r),this._cleanupRegister(),e())};this.registerer.stateChange.addListener(r),this.registerer.unregister().then().catch((e=>{logger$7.error("sdk webrtc unregistering, promise error",e),this._cleanupRegister(),t()}))}))}catch(e){logger$7.error("sdk webrtc unregistering, error",e),this._cleanupRegister()}}stop(){return logger$7.info("sdk webrtc stop",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent?this.userAgent.stop().then((()=>this._cleanupRegister())).catch((e=>{logger$7.warn("sdk webrtc stop, error",{message:e.message,stack:e.stack})})):Promise.resolve()}call(e,t,r=!1,n=!1){logger$7.info("sdk webrtc creating call",{clientId:this.clientId,number:e,enableVideo:t,audioOnly:r,conference:n});const i={sessionDescriptionHandlerOptionsReInvite:{conference:n,audioOnly:r},earlyMedia:!0};r&&(i.sessionDescriptionHandlerModifiersReInvite=[stripVideo]);const s=this._makeURI(e);let o=null;s?o=this.userAgent?new Inviter(this.userAgent,s,i):null:logger$7.error("Null URI"),o&&(this.storeSipSession(o),this._setupSession(o)),n&&(this.conferences[this.getSipSessionId(o)]=!0);const a={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=>{logger$7.info("on call rejected",{id:o?.id,fromTag:o?.fromTag}),this._stopSendingStats(o),this.stopNetworkMonitoring(o),this.eventEmitter.emit(REJECTED,o,e)}},sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1,n)};return a.sessionDescriptionHandlerOptions&&(a.sessionDescriptionHandlerOptions.audioOnly=r),a.sessionDescriptionHandlerModifiers=[replaceLocalIpModifier],r&&a.sessionDescriptionHandlerModifiers.push(stripVideo),o&&(o.invitePromise=o.invite(a).catch((e=>{logger$7.warn("sdk webrtc creating call, error",e)}))),o}answer(e,t){if(logger$7.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 logger$7.warn(e),Promise.reject(new Error(e))}const r={sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1)};return this._accept(e,r).then((()=>{if(e.isCanceled){const t="accepted a canceled session (or was canceled during the accept phase).";throw logger$7.error(t,{id:e.id}),this.onCallEnded(e),new CanceledCallError(t)}logger$7.info("sdk webrtc answer, accepted."),this._onAccepted(e)})).catch((t=>{throw logger$7.error(`answer call error for ${e?e.id:"n/a"}`,t),t}))}async hangup(e){const{state:t,id:r}=e;logger$7.info("sdk webrtc hangup call",{clientId:this.clientId,id:r,state:t});try{this._stopSendingStats(e),this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)];const r=e instanceof Inviter,n={[SessionState$1.Initial]:r?this._cancel.bind(this,e):this._reject.bind(this,e),[SessionState$1.Establishing]:r?this._cancel.bind(this,e):this._reject.bind(this,e),[SessionState$1.Established]:this._bye.bind(this,e)};return n[t]?await n[t]():await this._bye(e)}catch(e){logger$7.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 r=this.getSipSessionId(e);logger$7.info("starting network inspection",{id:r,clientId:this.clientId}),this.sessionNetworkStats[r]=[],this.networkMonitoringInterval[r]=setInterval((()=>this._fetchNetworkStats(r)),t)}stopNetworkMonitoring(e){const t=this.getSipSessionId(e),r=t in this.networkMonitoringInterval;logger$7.info("stopping network inspection",{clientId:this.clientId,id:t,exists:r}),r&&(clearInterval(this.networkMonitoringInterval[t]),delete this.networkMonitoringInterval[t],delete this.sessionNetworkStats[t])}async reject(e){logger$7.info("sdk webrtc reject call",{clientId:this.clientId,id:e.id});try{if(e instanceof Invitation)return this._reject(e);if(e instanceof Inviter)return this._cancel(e)}catch(e){logger$7.warn("Error when rejecting call",e.message,e.stack)}}async close(e=!1){if(logger$7.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,logger$7.info("sdk webrtc client closed",{clientId:this.clientId})}}getNumber(e){return e?e.remoteIdentity.uri._normal.user:null}mute(e){logger$7.info("sdk webrtc mute",{id:e.id}),this._toggleAudio(e,!0)}unmute(e){logger$7.info("sdk webrtc unmute",{id:e.id}),this._toggleAudio(e,!1)}isAudioMuted(e){if(!e||!e.sessionDescriptionHandler)return!1;let t=!0;const r=e.sessionDescriptionHandler.peerConnection;if(!r)return!1;if(r.getSenders){if(!r.getSenders().length)return!1;r.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(t=t&&!e.track.enabled)}))}else{if(!r.getLocalStreams().length)return!1;r.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{t=t&&!e.enabled}))}))}return t}toggleCameraOn(e){logger$7.info("sdk webrtc toggle camera on",{id:e.id}),this._toggleVideo(e,!1)}toggleCameraOff(e){logger$7.info("sdk webrtc toggle camera off",{id:e.id}),this._toggleVideo(e,!0)}hold(e,t=!1,r=!1){const n=this.getSipSessionId(e),i=r||this.hasLocalVideo(n);if(logger$7.info("sdk webrtc hold",{sessionId:n,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:i}),n in this.heldSessions)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();this.heldSessions[n]={hasVideo:i,isConference:t},this.mute(e),e.sessionDescriptionHandlerOptionsReInvite={hold:!0,conference:t};const s=this.getMediaConfiguration(!1,t);return this._isWeb()||(s.sessionDescriptionHandlerModifiers=[holdModifier]),s.sessionDescriptionHandlerOptions={constraints:s.constraints,hold:!0,conference:t},e.sessionDescriptionHandler&&(e.sessionDescriptionHandler.localMediaStreamConstraints=s.constraints),e.invite(s).catch((e=>{logger$7.warn("sdk webrtc re-invite during hold, error",e)}))}unhold(e,t=!1){const r=this.getSipSessionId(e),n=r in this.heldSessions&&this.heldSessions[r].hasVideo;if(logger$7.info("sdk webrtc unhold",{sessionId:r,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 i=this.getMediaConfiguration(!1,t);return this._isWeb()||(i.sessionDescriptionHandlerModifiers=[]),i.sessionDescriptionHandlerOptions={constraints:i.constraints,hold:!1,conference:t},e.invite(i).catch((e=>{logger$7.warn("sdk webrtc re-invite during resume, error",e)}))}async upgradeToVideo(e,t,r){const n=e.sessionDescriptionHandler?.peerConnection;let i;if(r){const e=n?.getTransceivers()||[],t=lastIndexOf(e,(e=>null===e.sender.track&&e.mid&&-1===e.mid.indexOf("video")));i=-1!==t?e[t].sender:null}else i=n&&n.getSenders&&n.getSenders().find((e=>null===e.track));if(!i)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,r=t.getTracks().find((e=>"audio"===e.kind));r&&s.addTrack(r)}const o=s.getVideoTracks()[0];return o&&i.replaceTrack(o),this.setLocalMediaStream(this.getSipSessionId(e),s),s}downgradeToAudio(e){const t=e.sessionDescriptionHandler,r=t?.localMediaStream,n=t?.peerConnection,i=r.getVideoTracks();n?.getSenders&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).forEach((e=>{e.replaceTrack(null)})),i.forEach((e=>{e.enabled=!1,e.stop(),r.removeTrack(e)}))}async getStreamFromConstraints(e,t=!1){const r=e&&e.video,{constraints:n}=this.getMediaConfiguration(r,t,e);let i=null;try{i=await wazoMediaStreamFactory(n)}catch(e){}return i?(i.local=!0,i):null}getHeldSession(e){return this.heldSessions[e]}isCallHeld(e){return this.getSipSessionId(e)in this.heldSessions}isVideoRemotelyHeld(e){const t=this.getPeerConnection(e),r=t&&t.remoteDescription?t.remoteDescription.sdp:null;if(!r)return!1;return"sendonly"===getVideoDirection(r)}sendDTMF(e,t){return!!e.sessionDescriptionHandler&&(logger$7.info("Sending DTMF",{id:this.getSipSessionId(e),tone:t}),e.sessionDescriptionHandler.sendDtmf(t))}message(e,t){const r=this._makeURI(e);if(!this.userAgent||!r)return void logger$7.warn("Null value on message",{uri:r,userAgent:this.userAgent});new Messager(this.userAgent,r,t).message()}transfer(e,t){this.hold(e),logger$7.info("Transfering a session",{id:this.getSipSessionId(e),target:t});const r={requestDelegate:{onAccept:()=>{this.hangup(e)}}};setTimeout((()=>{const n=this._makeURI(t);n?e.refer(n,r):logger$7.warn("transfer timeout: null URI")}),50)}atxfer(e){this.hold(e),logger$7.info("webrtc transfer started",{id:this.getSipSessionId(e)});const t={newSession:null,init:async r=>{logger$7.info("webrtc transfer initialized",{id:this.getSipSessionId(e),target:r}),t.newSession=await this.call(r)},complete:()=>{logger$7.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,r="text/plain"){if(e){logger$7.info("send WebRTC message",{sipId:e.id,contentType:r});try{e.message({requestOptions:{body:{content:t,contentType:r,contentDisposition:""}}})}catch(e){console.warn(e)}}}pingServer(){if(!this.isConnected())return;const e=this.userAgent?.userAgentCore,t=this._makeURI(this.config.authorizationUser||""),r=new URI("sip","",this.config.host);if(t){const n=e?.makeOutgoingRequestMessage("OPTIONS",r,t,r,{});if(n)return e?.request(n);logger$7.warn("pingServer: null message")}logger$7.warn("pingServer: null fromURI")}getState(){return this.userAgent?states[this.userAgent.state]:UserAgentState.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){logger$7.info("Changing audio output volume",{volume:e}),Object.values(this.audioElements).forEach((t=>{t instanceof HTMLAudioElement&&(t.volume=e)})),this.audioOutputVolume=e}changeAudioOutputDevice(e){logger$7.info("Changing audio output device",{id:e}),this.audioOutputDeviceId=e,Object.values(this.audioElements).forEach((t=>{t.setSinkId&&t.setSinkId(e)}))}async changeAudioInputDevice(e,t,r){const n=this.getAudioDeviceId();if(logger$7.info("setting audio input device",{id:e,currentId:n,session:!!t}),!r&&e===n)return null;let i=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 - ",""),o=e.find((e=>e.label===s));if(o&&(i=o.deviceId,!r&&i===n))return null}}if(this.audio&&(this.audio={deviceId:{exact:i}}),t&&navigator.mediaDevices){const e=t.sessionDescriptionHandler,r=e?.peerConnection,n={audio:{deviceId:{exact:i}}},s=await navigator.mediaDevices.getUserMedia(n),o=s.getAudioTracks()[0],a=r&&r.getSenders&&r.getSenders().find((e=>o&&e&&e.track&&e.track.kind===o.kind));return a&&(a.track&&(o.enabled=a.track.enabled),a.replaceTrack(o)),s}return null}async changeVideoInputDevice(e,t){if(this.setVideoInputDevice(e),t)return this.changeSessionVideoInputDevice(e,t)}setVideoInputDevice(e){const t=this.getVideoDeviceId();if(logger$7.info("setting video input device",{id:e,currentId:t}),e===t)return null;const r="object"==typeof this.video?this.video:{};this.video={...r,deviceId:{exact:e}}}changeSessionVideoInputDevice(e,t){if(!this.sessionWantsToDoVideo(t))return Promise.resolve();const r=t.sessionDescriptionHandler.peerConnection,n=this.getSipSessionId(t),i=this.getLocalStream(n);logger$7.info("changing video input device",{id:e,sessionId:n}),i&&i.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 i=r&&r.getSenders&&r.getSenders().find((e=>t&&e&&e.track&&e.track.kind===t.kind)),s=!1;return i||(i=r&&r.getSenders&&r.getSenders().find((e=>!e.track))),i&&(s=!!i.track&&i.track.enabled,t.enabled=s,s||t.stop(),i.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,r=!1,n=!1,i=!1){if(!e)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();const s=this.isAudioMuted(e),o=t?t.video:this.sessionWantsToDoVideo(e),a=t&&t.screen,d=t&&t.desktop;if(logger$7.info("Sending reinvite",{clientId:this.clientId,id:this.getSipSessionId(e),newConstraints:t,conference:r,audioOnly:n,wasMuted:s,shouldDoVideo:o,shouldDoScreenSharing:a,desktop:d}),t&&t.video){const t=e.sessionDescriptionHandlerModifiersReInvite;e.sessionDescriptionHandlerModifiersReInvite=t.filter((e=>e!==stripVideo))}e.sessionDescriptionHandlerOptionsReInvite={...e.sessionDescriptionHandlerOptionsReInvite,conference:r,audioOnly:n};const{constraints:c}=this.getMediaConfiguration(o,r,t);return e.invite({requestDelegate:{onAccept:t=>(e instanceof Inviter&&e.outgoingRequestMessage.body?e.outgoingRequestMessage.body.body=t.message.body:e instanceof Invitation&&(e.incomingInviteRequest.message.body=t.message.body),logger$7.info("on re-INVITE accepted",{id:this.getSipSessionId(e),wasMuted:s,shouldDoScreenSharing:a}),this.updateRemoteStream(this.getSipSessionId(e),!1),s&&this.mute(e),this._onAccepted(e,t.session,!1,!1),a&&this.eventEmitter.emit(ON_SCREEN_SHARING_REINVITE,e,t,d),this.eventEmitter.emit(ON_REINVITE,e,t))},sessionDescriptionHandlerModifiers:[replaceLocalIpModifier],requestOptions:{extraHeaders:["Subject: "+(a?"screenshare":"upgrade-video")]},sessionDescriptionHandlerOptions:{constraints:c,conference:r,audioOnly:n,offerOptions:{iceRestart:i}}})}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,SIP_ID_LENGTH):e instanceof Inviter&&e.outgoingRequestMessage?e.outgoingRequestMessage.callId.substring(0,SIP_ID_LENGTH):(e.id||"").substring(0,SIP_ID_LENGTH)}async waitForRegister(){return new Promise((e=>this.on(REGISTERED,e)))}sessionWantsToDoVideo(e){if(!e)return!1;const{body:t}=e.request||e,r="object"==typeof t&&t?t.body:t;return hasAnActiveVideo(r)}hasHeartbeat(){return this.heartbeat.hasHeartbeat}startHeartbeat(){logger$7.info("sdk webrtc start heartbeat",{userAgent:!!this.userAgent,clientId:this.clientId}),this.userAgent?(this.eventEmitter.off(MESSAGE,this._boundOnHeartbeat),this.eventEmitter.on(MESSAGE,this._boundOnHeartbeat),this.heartbeat.start()):this.heartbeat.stop()}stopHeartbeat(){logger$7.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(){logger$7.info("attempt reconnection",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent&&this.userAgent.attemptReconnection()}storeSipSession(e){const t=this.getSipSessionId(e);logger$7.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,SIP_ID_LENGTH)]:null}getSipSessionIds(){return Object.keys(this.sipSessions)}setLocalMediaStream(e,t){const r=this.sipSessions[e];r&&(logger$7.info("setting local media stream",{sipSessionId:e,tracks:t?t.getTracks():null}),r.sessionDescriptionHandler&&(r.sessionDescriptionHandler._localMediaStream=t))}updateLocalStream(e,t){const r=this.sipSessions[e];if(!r)return;const n=this.getLocalStream(e);logger$7.info("updating local stream",{sipSessionId:e,oldStream:!!n,tracks:t.getTracks()}),n&&this._cleanupStream(n),this.setLocalMediaStream(e,t),this._setupMedias(r,t)}updateRemoteStream(e,t=!0){const r=this.getRemoteStream(e),n=this.getPeerConnection(e);logger$7.info("Updating remote stream",{sessionId:e,tracks:r?r.getTracks():null,receiverTracks:n&&n.getReceivers?n.getReceivers().map((e=>e.track)):null}),n&&r&&(r.getTracks().forEach((e=>{(t||"video"===e.kind)&&r.removeTrack(e)})),n.getReceivers&&n.getReceivers().forEach((e=>{(t||"video"===e.track.kind)&&r.addTrack(e.track)})))}getMediaConfiguration(e,t=!1,r=null){const n=!(!r||!("screen"in r))&&r.screen,i=!(!r||!("desktop"in r))&&r.desktop,s=!r||!("audio"in r)||r.audio,o=r&&"object"==typeof r.video?r.video.mandatory:{};return logger$7.info("Retrieving media a configuration",{enableVideo:e,screenSharing:n,isDesktop:i,withAudio:s,constraints:r}),{constraints:{audio:n?!i:!!s&&this._getAudioConstraints(),video:n?i?{mandatory:{chromeMediaSource:"desktop",...o||{}}}:{cursor:"always"}:this._getVideoConstraints(e),screen:n,desktop:i,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}createAudioElementFor(e){const t=document.createElement("audio");return t.setAttribute("id",`audio-${e}`),logger$7.info("creating audio element",{sessionId:e,audioOutputDeviceId:this.audioOutputDeviceId}),t.setSinkId&&this.audioOutputDeviceId&&t.setSinkId(this.audioOutputDeviceId),document.body&&document.body.appendChild(t),this.audioElements[e]=t,t.volume=this.audioOutputVolume,t.autoplay=!0,t}_onTransportError(){logger$7.error("on transport error"),this.eventEmitter.emit(TRANSPORT_ERROR),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()&&(logger$7.info("on heartbeat received from Asterisk",{hasHeartbeat:this.hasHeartbeat()}),this.heartbeat.onHeartbeat(),this.heartbeatCb&&this.heartbeatCb())}async _onHeartbeatTimeout(){if(logger$7.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){logger$7.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 logger$7.info("connect if needed, checking",{connected:this.isConnected(),clientId:this.clientId}),this.userAgent||(logger$7.info("need to recreate User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),this.isConnected()?(logger$7.info("webrtc sdk, already connected"),Promise.resolve()):this.isConnecting()?(logger$7.info("webrtc sdk, already connecting..."),this.connectionPromise=this.userAgent.transport.connectPromise,Promise.resolve(this.connectionPromise)):this.connectionPromise?(logger$7.info("webrtc sdk, connection promise connecting..."),this.connectionPromise):(logger$7.info("WebRTC UA needs to connect"),this.userAgent&&this.userAgent.state!==UserAgentState.Stopped&&this.userAgent.transitionState(UserAgentState.Stopped),this.userAgent.transport&&this.userAgent.transport.state!==TransportState.Disconnected&&this.userAgent.transport.transitionState(TransportState.Disconnected),this.connectionPromise=this.userAgent.start().catch(console.error),this.connectionPromise)}_buildConfig(e,t){if(!t)return new Promise((t=>t(e)));const r=new ApiClient({server:`${e.host}:${String(e.port||443)}`});return r.setToken(t.token),r.setRefreshToken(t.refreshToken),r.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,r=this.config.port||443;if(this.config.websocketSip){const e=this.config.websocketSip.split(":");[t]=e,r=Number(e[1])}const{userUuid:n}=this.config,i={noAnswerTimeout:NO_ANSWER_TIMEOUT,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 r=e.userAgent.getLogger("sip.WazoSessionDescriptionHandler"),n=this._isWeb(),i="peerConnectionOptions"in t&&t.peerConnectionOptions.iceGatheringTimeout||DEFAULT_ICE_TIMEOUT,s={...t,iceGatheringTimeout:i,peerConnectionConfiguration:{...defaultPeerConnectionConfiguration(),...t.peerConnectionConfiguration||{}}};return new WazoSessionDescriptionHandler(r,wazoMediaStreamFactory,s,n,e)},transportOptions:{traceSip:e?.traceSip||!1,wsServers:`wss://${t}:${r}/api/asterisk/ws${n?`?userUuid=${n}`:""}`},sessionDescriptionHandlerFactoryOptions:{modifiers:[replaceLocalIpModifier],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:WebRTCClient.getIceServers(this.config.host),...this._getRtcOptions(),...e?.peerConnectionOptions||{}}},peerConnectionConfiguration:{rtcpMuxPolicy:"require",iceServers:WebRTCClient.getIceServers(this.config.host),...e?.peerConnectionOptions||{}}}};return delete e?.traceSip,{...i,...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(ON_ERROR,e)})),e.peerConnectionDelegate={onicecandidateerror:e=>{logger$7.error("on icecandidate error",{address:e.address,port:e.port,errorCode:e.errorCode,errorText:e.errorText,url:e.url})}}};const r=e.onInviteRequest.bind(e);let n=!1;e.onInviteRequest=e=>{n=this.hasARemoteVideoTrack(t),r(e)},e.delegate.onInvite=r=>{let i=null,s=null;return e.assertedIdentity&&(s=e.assertedIdentity.uri.normal.user,i=e.assertedIdentity.displayName||s),logger$7.info("re-invite received",{updatedCalleeName:i,updatedNumber:s,hadRemoteVideo:n}),e instanceof Invitation?e.incomingInviteRequest.message.body=r.body:e instanceof Inviter&&e.outgoingInviteRequest.message.body&&(e.outgoingInviteRequest.message.body.body=r.body),this.updateRemoteStream(t,!1),this._setupMedias(e),this.eventEmitter.emit(ON_REINVITE,e,r,i,s,n)}}_onProgress(e,t=!1){this._setupMedias(e);const r=this.getSipSessionId(e).substr(0,20);this.updateRemoteStream(r),logger$7.info("progress received",{sessionId:r,early:t}),this.eventEmitter.emit(t?ON_EARLY_MEDIA:ON_PROGRESS,e)}_onAccepted(e,t,r=!0,n=!0){logger$7.info("on call accepted",{id:e.id,clientId:this.clientId,remoteTag:e.remoteTag}),this.storeSipSession(e),this._setupMedias(e),this.updateRemoteStream(this.getSipSessionId(e),n);const i=e.sessionDescriptionHandler?.peerConnection,s=t=>{const r=this._isAudioOnly(e),{kind:n,label:i,readyState:s,id:o,muted:a}=t.track;logger$7.info("on track event",{isAudioOnly:r,kind:n,label:i,readyState:s,id:o,muted:a}),r&&"video"===n&&t.track.stop(),this.eventEmitter.emit(ON_TRACK,e,t)},o=e.sessionDescriptionHandler;o?.peerConnection&&o.peerConnection.addEventListener("track",s),o.remoteMediaStream.onaddtrack=s,i&&(i.oniceconnectionstatechange=()=>{logger$7.info("on ice connection state changed",{state:i.iceConnectionState}),"disconnected"===i.iceConnectionState&&this.eventEmitter.emit(ON_DISCONNECTED)}),r&&this.eventEmitter.emit(ACCEPTED,e,t),this._startSendingStats(e)}_isAudioOnly(e){return Boolean(e.sessionDescriptionHandlerModifiersReInvite.find((e=>e===stripVideo)))}_setupMedias(e,t=null){if(!this._isWeb())return void logger$7.info("Setup media on mobile, no need to setup html element, bailing");const r=this.getSipSessionId(e),n=this.isConference(r);if(r in this.audioElements)return void logger$7.info("html element already exists for session",{sessionId:r});this._hasAudio()&&this._isWeb()&&!(r in this.audioElements)&&this.createAudioElementFor(r);const i=this.audioElements[r],s=this.sipSessions[e.callId],o=this.getRemoteStream(r),a=s?.sessionDescriptionHandler,d=a?a.remoteMediaStream:null,c=t||o||d;if(!c)return void logger$7.info("Setup media no stream to attach, bailing");const l=i.currentTime>0&&!i.paused&&!i.ended&&i.readyState>2;logger$7.info("setting up media",{sessionId:r,streams:{new:!!t,remove:!!o,early:!!d},hasAudio:this._hasAudio(),isConference:n,shouldPause:l}),n||(l&&i.pause(),i.srcObject=c,i.volume=this.audioOutputVolume,i.play().catch((()=>{})))}_cleanupMedia(e){const t=this.getSipSessionId(e),r=this.getLocalStream(t);r&&this._cleanupStream(r);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 r=e.sessionDescriptionHandler,n=r?.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 r=e.sessionDescriptionHandler,n=r?.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:r}=e;r&&t&&t.addTrack(r)}))):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 r=this.getSipSessionId(e);getStats(t,(e=>{const{results:t,internal:n,nomore:i,...s}=e;this.statsIntervals[r]=i,statsLogger.trace("stats",{sessionId:r,...s})}),SEND_STATS_DELAY)}_stopSendingStats(e){const t=this.getSipSessionId(e);logger$7.trace("Check for stopping stats",{sessionId:t,ids:Object.keys(this.statsIntervals)}),t in this.statsIntervals&&(logger$7.trace("Stop sending stats for call",{sessionId:t}),this.statsIntervals[t](),delete this.statsIntervals[t])}_makeURI(e){return UserAgent.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){logger$7.error("WebRTC transport disconnect, error",e)}}async _fetchNetworkStats(e){const t=this.getSipSession(e),r=t?await this.getStats(t):null;if(!r||!(e in this.sessionNetworkStats))return Promise.resolve(null);const n={audioBytesSent:0,videoBytesSent:0,videoBytesReceived:0,audioBytesReceived:0},i=this.sessionNetworkStats[e].length,s=this.sessionNetworkStats[e][i-1],o=s?s.audioBytesSent:0,a=s?s.audioContentSent:0,d=s?s.videoBytesSent:0,c=s?s.audioBytesReceived:0,l=s?s.audioContentReceived:0,u=s?s.videoBytesReceived:0,h=s?s.transportSent:0,g=s?s.transportReceived:0;let p=0,m=0,f=0,S=0,y=0,b=0,E=0,v=0,_=0;r.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.kind&&(p+=Number(e.bytesSent)+Number(e.headerBytesSent),f+=Number(e.bytesSent)),"remote-outbound-rtp"===e.type&&"audio"===e.kind&&(p+=Number(e.bytesSent)),"outbound-rtp"===e.type&&"video"===e.kind&&(y+=Number(e.bytesSent)+Number(e.headerBytesSent)),"inbound-rtp"===e.type&&"audio"===e.kind&&(_+=Number(e.packetsLost),n.packetsReceived=Number(e.packetsReceived),m+=Number(e.bytesReceived)+Number(e.headerBytesReceived),S+=Number(e.bytesReceived)),"inbound-rtp"===e.type&&"video"===e.kind&&(b+=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&&(_+=Number(e.packetsLost),n.roundTripTime=Number(e.roundTripTime),n.jitter=Number(e.jitter)),"remote-inbound-rtp"===e.type&&"video"===e.kind&&(_+=Number(e.packetsLost)),"transport"===e.type&&(E+=Number(e.bytesSent),v+=Number(e.bytesReceived))})),n.packetsLost=_,n.totalAudioBytesSent=p,n.audioBytesSent=p-o,n.totalAudioBytesReceived=m-c,n.audioBytesReceived=m,n.totalAudioContentSent=f,n.audioContentSent=f-a,n.totalAudioBytesReceived=S-l,n.audioContentReceived=S,n.totalVideoBytesSent=y,n.videoBytesSent=y-d,n.totalVideoBytesReceived=b,n.videoBytesReceived=b-u,n.totalTransportSent=E-h,n.transportSent=E,n.totalTransportReceived=v,n.transportReceived=v-g,n.bandwidth=n.audioBytesSent+n.audioBytesReceived+n.videoBytesSent+n.videoBytesReceived+n.transportReceived+n.transportSent,this.sessionNetworkStats[e]&&(this.eventEmitter.emit(ON_NETWORK_STATS,t,n,this.sessionNetworkStats[e]),e in this.sessionNetworkStats&&this.sessionNetworkStats[e].push(n))}async _accept(e,t={}){if(e.state===SessionState$1.Terminated||e.state===SessionState$1.Terminating){const t="Trying to accept a terminated sipSession.";throw logger$7.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(e.state!==SessionState$1.Initial){const t="Trying to accept a non Initial sipSession.";throw logger$7.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 logger$7.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}try{return await e.accept(t)}catch(e){logger$7.warn("Session accept, error",e)}}async _reject(e,t={}){if(e.state===SessionState$1.Initial||e.state===SessionState$1.Establishing)if(e.incomingInviteRequest.rejectable)try{return await e.reject(t)}catch(e){logger$7.warn("Session reject, error",e)}else logger$7.warn("Trying to reject a non `rejectable` session",{state:e.state,sessionId:e.id});else logger$7.warn("Trying to reject a session in a wrong state",{state:e.state,sessionId:e.id})}async _cancel(e,t={}){if(e.state===SessionState$1.Initial||e.state===SessionState$1.Establishing)try{return await e.cancel(t)}catch(e){logger$7.warn("Session cancel, error",e)}else logger$7.warn("Trying to cancel a session in a wrong state",{state:e.state,sessionId:e.id})}async _bye(e,t={}){if(e.state!==SessionState$1.Established)return logger$7.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){logger$7.warn("Session bye, error",e)}return null}}class SFUNotAvailableError extends Error{constructor(e="Sorry your user is not configured to support video conference"){super(e),this.name="SFUNotAvailableError"}}const logger$6=IssueReporter$1.loggerFor("simple-phone"),sipLogger=IssueReporter$1.loggerFor("sip.js"),protocolLogger=IssueReporter$1.loggerFor("sip"),protocolDebugMessages=["Received WebSocket text message:","Sending WebSocket message:"];class Phone extends Emitter{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(PHONE_EVENTS).forEach((e=>{this[e]=PHONE_EVENTS[e]})),this.SessionState=SessionState$1}async connect(e={},t=null){const r=e;if(this.phone)return void(r.media&&this.phone.setMediaConstraints(r.media));const n=Wazo$1.Auth.getHost(),i=Wazo$1.Auth.getSession();if(!n||!i)throw new Error("Please connect to the server using `Wazo.Auth.logIn` or `Wazo.Auth.authenticate` before using Room.connect().");if(this.session=i,this.sipLine=t||this.getPrimaryWebRtcLine(),!this.sipLine)throw new Error("Sorry, no sip lines found for this user");r.userUuid=i.uuid||"",this.connectWithCredentials(n,this.sipLine,i.displayName(),r)}connectWithCredentials(e,t,r,n={}){if(this.phone)return;const[i,s=443]=e.split(":"),o=n;o.media=o.media||{audio:!0,video:!1},o.uaConfigOverrides=o.uaConfigOverrides||{},IssueReporter$1.enabled&&(o.uaConfigOverrides.traceSip=!0,o.log=o.log||{},o.log.builtinEnabled=!1,o.log.logLevel="debug",o.log.connector=this._logConnector),this.client=new WebRTCClient({host:i,port:"string"==typeof s?parseInt(s,10):s,displayName:r,authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e}`,...o},null,o.uaConfigOverrides),this.phone=new WebRTCPhone(this.client,o.audioDeviceOutput,!0,o.audioDeviceRing),this._transferEvents()}async disconnect(){this.phone&&(this.phone.hasAnActiveCall()&&(logger$6.info("hangup call on disconnect"),await this.phone.hangup()),await this.phone.close()),this.phone=null}async call(e,t=!1,r=null,n=!1,i=!1){if(!this.phone)return;const s=r||this.getPrimaryWebRtcLine();return this.phone.makeCall(e,s,t,n,i)}async hangup(e){return logger$6.info("hangup via simple phone",{callId:e.getId()}),!!this.phone&&this.phone.hangup(e)}async accept(e,t){return logger$6.info("accept via simple phone",{callId:e.getId(),cameraEnabled:t}),this.phone?this.phone.accept(e,t):null}async startConference(e,t){const r=[e,...t].reduce(((e,t)=>(e[t.getTalkingToIds()[0]]=t,e)),{});if(!this.phone)return Promise.reject();return new AdHocAPIConference({phone:this.phone,host:e,participants:r}).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&&Wazo$1.getApiClient().calld.mute(e.callId).catch((e=>{logger$6.error("Mute via API, error",e)}))}unmuteViaAPI(e){e&&e.callId&&Wazo$1.getApiClient().calld.unmute(e.callId).catch((e=>{logger$6.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,r=!1){return this.phone?this.phone.sendReinvite(e,t,r):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,r="text/plain"){const n=t||this.getCurrentSipSession();n&&this.phone&&this.phone.sendMessage(n,e,r)}sendChat(e,t){this.sendMessage(JSON.stringify({type:MESSAGE_TYPE_CHAT,content:e}),t,"application/json")}sendSignal(e,t){this.sendMessage(JSON.stringify({type:MESSAGE_TYPE_SIGNAL,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 logger$6.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 logger$6.warn("Phone.getRemoteStreamForCall is deprecated, use Phone.getRemoteStream instead"),this.getRemoteStream(e)||null}getRemoteStreamsForCall(e){return logger$6.warn("Phone.getRemoteStreamsForCall is deprecated, use Phone.getLocalStream instead"),this.getLocalStream(e)||null}getRemoteVideoStreamForCall(e){return logger$6.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=Wazo$1.Auth.getSession();return e?.primaryWebRtcLine()||null}getOutputDevice(){return this.phone?.audioOutputDeviceId||null}getPrimaryLine(){const e=Wazo$1.Auth.getSession();return e?.primarySipLine()||null}getLineById(e){return this.getSipLines().find((t=>t&&t.id===e))||null}getSipLines(){const e=Wazo$1.Auth.getSession();return e&&e.profile?.sipLines||[]}hasSfu(){return this.sipLine?.hasVideoConference()||!1}checkSfu(){if(!this.hasSfu())throw new SFUNotAvailableError}enableLogger(){this.client.enableLogger(this._logConnector)}_transferEvents(){this.unbind(),[...events,...transportEvents].forEach((e=>{this.client.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter.emit,[`client-${e}`,...t])))})),Object.values(PHONE_EVENTS).forEach((e=>{"string"==typeof e&&this.phone&&this.phone.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter,[e,...t])))}))}_logConnector(e,t,r,n){const i=n&&n.indexOf?protocolDebugMessages.findIndex((e=>-1!==n.indexOf(e))):-1;if("sip.Transport"===t&&-1!==i){const e=0===i?"receiving":"sending",r=n.replace(`${protocolDebugMessages[i]}\n\n`,"").replace("\r\n","\n");protocolLogger.trace(r,{className:t,direction:e})}else sipLogger.trace(n,{className:t})}}global.wazoTelephonyInstance||(global.wazoTelephonyInstance=new Phone);var Phone$1=global.wazoTelephonyInstance,extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},extendStatics(e,t)};
28
+ var jsonParse=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"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),s=Object.hasOwnProperty;return function(r,o){var a,d,c=r.match(e),l=c[0],u=!1;"{"===l?a={}:"["===l?a=[]:(a=[],u=!0);for(var h=[a],g=1-u,p=c.length;g<p;++g){var m;switch((l=c[g]).charCodeAt(0)){default:(m=h[0])[d||m.length]=+l,d=void 0;break;case 34:if(-1!==(l=l.substring(1,l.length-1)).indexOf("\\")&&(l=l.replace(t,n)),m=h[0],!d){if(!(m instanceof Array)){d=l||i;break}d=m.length}m[d]=l,d=void 0;break;case 91:m=h[0],h.unshift(m[d||m.length]=[]),d=void 0;break;case 93:case 125:h.shift();break;case 102:(m=h[0])[d||m.length]=!1,d=void 0;break;case 110:(m=h[0])[d||m.length]=null,d=void 0;break;case 116:(m=h[0])[d||m.length]=!0,d=void 0;break;case 123:m=h[0],h.unshift(m[d||m.length]={}),d=void 0}}if(u){if(1!==h.length)throw new Error;a=a[0]}else if(h.length)throw new Error;if(o){var f=function(e,t){var r=e[t];if(r&&"object"==typeof r){var n=null;for(var i in r)if(s.call(r,i)&&r!==e){var a=f(r,i);void 0!==a?r[i]=a:(n||(n=[]),n.push(i))}if(n)for(var d=n.length;--d>=0;)delete r[n[d]]}return o.call(e,t,r)};a=f({"":a},"")}return a}}();void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.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 twoscompl(e)},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,s=t.DERBitString,o=t.DEROctetString,a=t.DERNull,d=t.DERObjectIdentifier,c=t.DEREnumerated,l=t.DERUTF8String,u=t.DERNumericString,h=t.DERPrintableString,g=t.DERTeletexString,p=t.DERIA5String,m=t.DERUTCTime,f=t.DERGeneralizedTime,S=t.DERVisibleString,y=t.DERBMPString,b=t.DERSequence,E=t.DERSet,v=t.DERTaggedObject,_=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var T=Object.keys(e);if(1!=T.length)throw new Error("key of param shall be only one.");var R=T[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+R+":"))throw new Error("undefined key: "+R);if("bool"==R)return new n(e[R]);if("int"==R)return new i(e[R]);if("bitstr"==R)return new s(e[R]);if("octstr"==R)return new o(e[R]);if("null"==R)return new a(e[R]);if("oid"==R)return new d(e[R]);if("enum"==R)return new c(e[R]);if("utf8str"==R)return new l(e[R]);if("numstr"==R)return new u(e[R]);if("prnstr"==R)return new h(e[R]);if("telstr"==R)return new g(e[R]);if("ia5str"==R)return new p(e[R]);if("utctime"==R)return new m(e[R]);if("gentime"==R)return new f(e[R]);if("visstr"==R)return new S(e[R]);if("bmpstr"==R)return new y(e[R]);if("asn1"==R)return new r(e[R]);if("seq"==R){for(var $=e[R],C=[],A=0;A<$.length;A++){var N=_($[A]);C.push(N)}return new b({array:C})}if("set"==R){for($=e[R],C=[],A=0;A<$.length;A++){N=_($[A]);C.push(N)}return new E({array:C})}if("tag"==R){var I=e[R];if("[object Array]"===Object.prototype.toString.call(I)&&3==I.length){var w=_(I[2]);return new v({tag:I[0],explicit:I[1],obj:w})}return new v(I)}},this.jsonToASN1HEX=function(e){return this.newObject(e).tohex()}},KJUR.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",r=parseInt(e.substr(0,2),16),n=(t=Math.floor(r/40)+"."+r%40,""),i=2;i<e.length;i+=2){var s=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);if(n+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new BigInteger(n,2).toString(10),n=""}return t},KJUR.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=new BigInteger(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";n=s+n;for(o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var n="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n},KJUR.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 r=t.length/2;if(r>15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+r).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)},KJUR.asn1.DERAbstractString=function(e){KJUR.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=utf8tohex(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))},extendClass(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.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,r){var n=this.zeroPadding,i=this.localDateToUTC(e),s=String(i.getFullYear());"utc"==t&&(s=s.substr(2,2));var o=s+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var d=n(String(a),3);o=o+"."+(d=d.replace(/[0]+$/,""))}}return o+"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,r,n,i,s){var o=new Date(Date.UTC(e,t-1,r,n,i,s,0));this.setByDate(o)},this.getFreshValueHex=function(){return this.hV}},extendClass(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.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)},extendClass(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(e){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},extendClass(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=twoscompl;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,r=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)r=new BigInteger(String(e),10);else if(null!=e.int)r=new BigInteger(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");r=e.bigint}return this.hV=t(r),this.hV},null!=e&&(this.params=e)},extendClass(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}KJUR.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 r="0"+e;this.hTLV=null,this.isModified=!0,this.hV=r+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 r="",n=0;n<e.length-1;n+=8){var i=e.substr(n,8),s=parseInt(i,2).toString(16);1==s.length&&(s="0"+s),r+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+r},this.setByBooleanArray=function(e){for(var t="",r=0;r<e.length;r++)1==e[r]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),r=0;r<e;r++)t[r]=!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))},extendClass(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object),KJUR.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex=t.tohex()}KJUR.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},extendClass(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},extendClass(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object),KJUR.asn1.DERObjectIdentifier=function(e){KJUR.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=oidtohex(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=KJUR.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)},extendClass(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.DEREnumerated=function(e){KJUR.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=twoscompl(e)},this.setByInteger=function(e){var t=new BigInteger(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))},extendClass(KJUR.asn1.DEREnumerated,KJUR.asn1.ASN1Object),KJUR.asn1.DERUTF8String=function(e){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},extendClass(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNumericString=function(e){KJUR.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},extendClass(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERPrintableString=function(e){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},extendClass(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERTeletexString=function(e){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},extendClass(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERIA5String=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},extendClass(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERVisibleString=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="1a"},extendClass(KJUR.asn1.DERVisibleString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERBMPString=function(e){KJUR.asn1.DERBMPString.superclass.constructor.call(this,e),this.hT="1e"},extendClass(KJUR.asn1.DERBMPString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERUTCTime=function(e){KJUR.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=stohex(e)}else if(null!=e.str)this.hV=stohex(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=stohex(this.formatDate(t,"utc",!0))}else if(null!=e.date&&e.date instanceof Date){var r=!0===e.millis;this.hV=stohex(this.formatDate(e.date,"utc",r))}else e instanceof Date&&(this.hV=stohex(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)},extendClass(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERGeneralizedTime=function(e){KJUR.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=stohex(e)}else if(null!=e.str)this.hV=stohex(e.str);else if(null==e.date&&1==e.millis){var t=new Date;this.hV=stohex(this.formatDate(t,"gen",!0))}else if(null!=e.date&&e.date instanceof Date){var r=!0===e.millis;this.hV=stohex(this.formatDate(e.date,"gen",r))}else e instanceof Date&&(this.hV=stohex(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)},extendClass(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERSequence=function(e){KJUR.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}},extendClass(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERSet=function(e){KJUR.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 r=this.asn1Array[t];e.push(r.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)},extendClass(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERTaggedObject=function(e){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);var t=KJUR.asn1,r=ASN1HEX,n=r.getV;r.isASN1HEX;var i=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,r){this.params={tag:t,explicit:e,obj:r}},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=utf8tohex(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 r;e.obj instanceof t.ASN1Object?r=e.obj.tohex():"object"==typeof e.obj&&(r=i(e.obj).tohex()),e.explicit?this.hV=r:this.hV=n(r,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)},extendClass(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);var ASN1HEX=new function(){},KJUR,utf8tob64u,b64utoutf8;function stoBA(e){for(var t=new Array,r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function BAtohex(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);1==n.length&&(n="0"+n),t+=n}return t}function stohex(e){return BAtohex(stoBA(e))}function b64tob64u(e){return e=(e=(e=e.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function b64utob64(e){return e.length%4==2?e+="==":e.length%4==3&&(e+="="),e=(e=e.replace(/-/g,"+")).replace(/_/g,"/")}function hextob64u(e){return e.length%2==1&&(e="0"+e),b64tob64u(hex2b64(e))}function b64utohex(e){return b64tohex(b64utob64(e))}function utf8tohex(e){return uricmptohex(encodeURIComponentAll(e)).toLowerCase()}function hextoutf8(e){try{return decodeURIComponent(hextouricmp(e))}catch(e){return null}}function iso88591hextoutf8(e){return hextoutf8(iso88591hextoutf8hex(e))}function iso88591hextoutf8hex(e){for(var t=e.match(/.{1,2}/g),r=[],n=0;n<t.length;n++){var i=parseInt(t[n],16);161<=i&&i<=191?(r.push("c2"),r.push(t[n])):192<=i&&i<=255?(r.push("c3"),r.push((i-64).toString(16))):r.push(t[n])}return r.join("")}function hextorstr(e){for(var t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t}function rstrtohex(e){for(var t="",r=0;r<e.length;r++)t+=("0"+e.charCodeAt(r).toString(16)).slice(-2);return t}function hextob64(e){return hex2b64(e)}function foldnl(e,t){return e=(e=e.replace(new RegExp("(.{"+t+"})","g"),"$1\r\n")).replace(/\s+$/,"")}function b64nltohex(e){return b64tohex(e.replace(/[^0-9A-Za-z\/+=]*/g,""))}function hextopem(e,t){return"-----BEGIN "+t+"-----\r\n"+foldnl(hextob64(e),64)+"\r\n-----END "+t+"-----\r\n"}function pemtohex(e,t){if(-1==e.indexOf("-----BEGIN "))throw new Error("can't find PEM header");return b64nltohex(e=void 0!==t?(e=e.replace(new RegExp("^[^]*-----BEGIN "+t+"-----"),"")).replace(new RegExp("-----END "+t+"-----[^]*$"),""):(e=e.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function zulutomsec(e){var t,r,n,i,s,o,a,d,c,l;if(l=(e=timetogen(e)).match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return t=parseInt(l[1]),r=parseInt(l[2])-1,n=parseInt(l[3]),i=parseInt(l[4]),s=parseInt(l[5]),o=parseInt(l[6]),a=0,""!==(d=l[7])&&(c=(d.substr(1)+"00").substr(0,3),a=parseInt(c)),Date.UTC(t,r,n,i,s,o,a);throw new Error("unsupported zulu format: "+e)}function zulutosec(e){return Math.round(zulutomsec(e)/1e3)}function timetogen(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}function uricmptohex(e){return e.replace(/%/g,"")}function hextouricmp(e){return e.replace(/(..)/g,"%$1")}function ipv6tohex(e){var t="malformed IPv6 address";if(!e.match(/^[0-9A-Fa-f:]+$/))throw t;var r=(e=e.toLowerCase()).split(":").length-1;if(r<2)throw t;var n=":".repeat(7-r+2),i=(e=e.replace("::",n)).split(":");if(8!=i.length)throw t;for(var s=0;s<8;s++)i[s]=("0000"+i[s]).slice(-4);return i.join("")}function hextoipv6(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 r=(e=":"+t.join(":")+":").match(/:(0:){2,}/g);if(null==r)return e.slice(1,-1);var n=r.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 hextoip(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 hextoipv6(e);if(64==e.length){try{return hextoipv6(e.substr(0,32))+"/"+ipprefixlen(e.substr(32))}catch(e){throw t}return}return e}try{return hextoip(e.substr(0,8))+"/"+ipprefixlen(e.substr(8))}catch(e){throw t}}}function ipprefixlen(e){var t,r=new Error("malformed mask");try{t=new BigInteger(e,16).toString(2)}catch(e){throw r}if(!t.match(/^1*0*$/))throw r;return t.replace(/0+$/,"").length}function iptohex(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 r;if(e.match(/^[0-9.]+\/[0-9]+$/))return iptohex((r=e.split("/"))[0])+ipnetmask(parseInt(r[1]),32);if(e.match(/^[0-9a-f:]+$/)&&-1!==e.indexOf(":"))return ipv6tohex(e);if(e.match(/^[0-9a-f:]+\/[0-9]+$/)&&-1!==e.indexOf(":"))return ipv6tohex((r=e.split("/"))[0])+ipnetmask(parseInt(r[1]),128);throw t}var n=e.split(".");if(4!==n.length)throw t;var i="";try{for(var s=0;s<4;s++){i+=("0"+parseInt(n[s]).toString(16)).slice(-2)}return i}catch(e){throw t}}function ipnetmask(e,t){return 32==t&&0==e?"00000000":128==t&&0==e?"00000000000000000000000000000000":new BigInteger(Array(e+1).join("1")+Array(t-e+1).join("0"),2).toString(16)}function ucs2hextoutf8(e){var t=e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),r=parseInt(e.substr(2),16);if(0==t&r<128)return String.fromCharCode(r);if(t<8){var n=128|63&r;return hextoutf8((192|(7&t)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return hextoutf8((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))}));return t.join("")}function encodeURIComponentAll(e){for(var t=encodeURIComponent(e),r="",n=0;n<t.length;n++)"%"==t[n]?(r+=t.substr(n,3),n+=2):r=r+"%"+stohex(t[n]);return r}function ishex(e){return!(e.length%2!=0||!e.match(/^[0-9a-f]+$/)&&!e.match(/^[0-9A-F]+$/))}function isBase64URLDot(e){return!!e.match(/^[0-9A-Za-z-_.]+$/)}function hextoposhex(e){return e.length%2==1?"0"+e:e.substr(0,1)>"7"?"00"+e:e}function oidtohex(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";n=s+n;for(o=0;o<n.length-1;o+=7){var a=n.substr(o,7);o!=n.length-7&&(a="1"+a),r+=t(parseInt(a,2))}return r};try{if(!e.match(/^[0-9.]+$/))return null;var n="",i=e.split("."),s=40*parseInt(i[0],10)+parseInt(i[1],10);n+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)n+=r(i[o]);return n}catch(e){return null}}function hextooid(e){if(!ishex(e))return null;try{var t=[],r=e.substr(0,2),n=parseInt(r,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var i=e.substr(2),s=[],o=0;o<i.length/2;o++)s.push(parseInt(i.substr(2*o,2),16));var a=[],d="";for(o=0;o<s.length;o++)128&s[o]?d+=strpad((127&s[o]).toString(2),7):(d+=strpad((127&s[o]).toString(2),7),a.push(new String(parseInt(d,2))),d="");var c=t.join(".");return a.length>0&&(c=c+"."+a.join(".")),c}catch(e){return null}}function inttohex(e){return twoscompl(new BigInteger(String(e),10))}function twoscompl(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 r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i<r;i++)n+="f";return t=new BigInteger(n,16).xor(e).add(BigInteger.ONE).toString(16).replace(/^-/,"")}ASN1HEX.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var r=parseInt(e.substr(t+3,1));return 0==r?-1:0<r&&r<10?r+1:-2},ASN1HEX.getL=function(e,t){var r=ASN1HEX.getLblen(e,t);return r<1?"":e.substr(t+2,2*r)},ASN1HEX.getVblen=function(e,t){var r;return""==(r=ASN1HEX.getL(e,t))?-1:("8"===r.substr(0,1)?new BigInteger(r.substr(2),16):new BigInteger(r,16)).intValue()},ASN1HEX.getVidx=function(e,t){var r=ASN1HEX.getLblen(e,t);return r<0?r:t+2*(r+1)},ASN1HEX.getV=function(e,t){var r=ASN1HEX.getVidx(e,t),n=ASN1HEX.getVblen(e,t);return e.substr(r,2*n)},ASN1HEX.getTLV=function(e,t){return e.substr(t,2)+ASN1HEX.getL(e,t)+ASN1HEX.getV(e,t)},ASN1HEX.getTLVblen=function(e,t){return 2+2*ASN1HEX.getLblen(e,t)+2*ASN1HEX.getVblen(e,t)},ASN1HEX.getNextSiblingIdx=function(e,t){return ASN1HEX.getVidx(e,t)+2*ASN1HEX.getVblen(e,t)},ASN1HEX.getChildIdx=function(e,t){var r,n,i,s=ASN1HEX,o=[];r=s.getVidx(e,t),n=2*s.getVblen(e,t),"03"==e.substr(t,2)&&(r+=2,n-=2),i=0;for(var a=r;i<=n;){var d=s.getTLVblen(e,a);if((i+=d)<=n&&o.push(a),a+=d,i>=n)break}return o},ASN1HEX.getNthChildIdx=function(e,t,r){return ASN1HEX.getChildIdx(e,t)[r]},ASN1HEX.getIdxbyList=function(e,t,r,n){var i,s,o=ASN1HEX;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(s=o.getChildIdx(e,t)).length?-1:o.getIdxbyList(e,s[i],r,n)},ASN1HEX.getIdxbyListEx=function(e,t,r,n){var i,s,o=ASN1HEX;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),s=o.getChildIdx(e,t);for(var a=0,d=0;d<s.length;d++){var c=e.substr(s[d],2);if("number"==typeof i&&!o.isContextTag(c)&&a==i||"string"==typeof i&&o.isContextTag(c,i))return o.getIdxbyListEx(e,s[d],r,n);o.isContextTag(c)||a++}return-1},ASN1HEX.getTLVbyList=function(e,t,r,n){var i=ASN1HEX,s=i.getIdxbyList(e,t,r,n);return-1==s||s>=e.length?null:i.getTLV(e,s)},ASN1HEX.getTLVbyListEx=function(e,t,r,n){var i=ASN1HEX,s=i.getIdxbyListEx(e,t,r,n);return-1==s?null:i.getTLV(e,s)},ASN1HEX.getVbyList=function(e,t,r,n,i){var s,o,a=ASN1HEX;return-1==(s=a.getIdxbyList(e,t,r,n))||s>=e.length?null:(o=a.getV(e,s),!0===i&&(o=o.substr(2)),o)},ASN1HEX.getVbyListEx=function(e,t,r,n,i){var s,o,a=ASN1HEX;return-1==(s=a.getIdxbyListEx(e,t,r,n))?null:(o=a.getV(e,s),"03"==e.substr(s,2)&&!1!==i&&(o=o.substr(2)),o)},ASN1HEX.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=ASN1HEX.getV(e,t);return"02"==n?parseInt(i,16):bitstrtoint(i)}catch(e){return r}},ASN1HEX.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:hextooid(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=ASN1HEX.getOID(e,t,r);if(n==r)return r;var i=KJUR.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},ASN1HEX.getString=function(e,t,r){null==r&&(r=null);try{return hextorstr(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var s=e.substr(2),o=[],a=0;a<s.length/2;a++)o.push(parseInt(s.substr(2*a,2),16));var d=[],c="";for(a=0;a<o.length;a++)128&o[a]?c+=t((127&o[a]).toString(2),7):(c+=t((127&o[a]).toString(2),7),d.push(new String(parseInt(c,2))),c="");var l=r.join(".");return d.length>0&&(l=l+"."+d.join(".")),l},ASN1HEX.dump=function(e,t,r,n){var i=ASN1HEX,s=i.getV,o=i.dump,a=i.getChildIdx,d=e;e instanceof KJUR.asn1.ASN1Object&&(d=e.tohex());var c=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===r&&(r=0),void 0===n&&(n="");var l,u=t.ommit_long_octet;if("01"==(l=d.substr(r,2)))return"00"==(h=s(d,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==l)return n+"INTEGER "+c(h=s(d,r),u)+"\n";if("03"==l){var h=s(d,r);if(i.isASN1HEX(h.substr(2))){var g=n+"BITSTRING, encapsulates\n";return g+=o(h.substr(2),t,0,n+" ")}return n+"BITSTRING "+c(h,u)+"\n"}if("04"==l){h=s(d,r);if(i.isASN1HEX(h)){g=n+"OCTETSTRING, encapsulates\n";return g+=o(h,t,0,n+" ")}return n+"OCTETSTRING "+c(h,u)+"\n"}if("05"==l)return n+"NULL\n";if("06"==l){var p=s(d,r),m=KJUR.asn1.ASN1Util.oidHexToInt(p),f=KJUR.asn1.x509.OID.oid2name(m),S=m.replace(/\./g," ");return""!=f?n+"ObjectIdentifier "+f+" ("+S+")\n":n+"ObjectIdentifier ("+S+")\n"}if("0a"==l)return n+"ENUMERATED "+parseInt(s(d,r))+"\n";if("0c"==l)return n+"UTF8String '"+hextoutf8(s(d,r))+"'\n";if("13"==l)return n+"PrintableString '"+hextoutf8(s(d,r))+"'\n";if("14"==l)return n+"TeletexString '"+hextoutf8(s(d,r))+"'\n";if("16"==l)return n+"IA5String '"+hextoutf8(s(d,r))+"'\n";if("17"==l)return n+"UTCTime "+hextoutf8(s(d,r))+"\n";if("18"==l)return n+"GeneralizedTime "+hextoutf8(s(d,r))+"\n";if("1a"==l)return n+"VisualString '"+hextoutf8(s(d,r))+"'\n";if("1e"==l)return n+"BMPString '"+ucs2hextoutf8(s(d,r))+"'\n";if("30"==l){if("3000"==d.substr(r,4))return n+"SEQUENCE {}\n";g=n+"SEQUENCE\n";var y=t;if((2==(v=a(d,r)).length||3==v.length)&&"06"==d.substr(v[0],2)&&"04"==d.substr(v[v.length-1],2)){f=i.oidname(s(d,v[0]));var b=JSON.parse(JSON.stringify(t));b.x509ExtName=f,y=b}for(var E=0;E<v.length;E++)g+=o(d,y,v[E],n+" ");return g}if("31"==l){g=n+"SET\n";var v=a(d,r);for(E=0;E<v.length;E++)g+=o(d,t,v[E],n+" ");return g}if(0!=(128&(l=parseInt(l,16)))){var _=31&l;if(0!=(32&l)){for(g=n+"["+_+"]\n",v=a(d,r),E=0;E<v.length;E++)g+=o(d,t,v[E],n+" ");return g}h=s(d,r);if(ASN1HEX.isASN1HEX(h)){var g=n+"["+_+"]\n";return g+=o(h,t,0,n+" ")}return("68747470"==h.substr(0,8)||"subjectAltName"===t.x509ExtName&&2==_)&&(h=hextoutf8(h)),g=n+"["+_+"] "+h+"\n"}return n+"UNKNOWN("+l+") "+s(d,r)+"\n"},ASN1HEX.parse=function(e){var t=ASN1HEX,r=t.parse,n=t.isASN1HEX,i=t.getV,s=t.getTLV,o=t.getChildIdx,a=KJUR.asn1,d=a.ASN1Util.oidHexToInt,c=a.x509.OID.oid2name,l=hextoutf8,u=ucs2hextoutf8,h=iso88591hextoutf8,g={"0c":"utf8str",12:"numstr",13:"prnstr",14:"telstr",16:"ia5str",17:"utctime",18:"gentime","1a":"visstr","1e":"bmpstr",30:"seq",31:"set"},p=e.substr(0,2),m={},f=i(e,0);if("01"==p)return"0101ff"==e?{bool:!0}:{bool:!1};if("02"==p)return{int:{hex:f}};if("03"==p)try{if("00"!=f.substr(0,2))throw"not encap";var S=f.substr(2);if(!n(S))throw"not encap";return{bitstr:{obj:r(S)}}}catch(e){var y=null;return f.length<=10&&(y=bitstrtobinstr(f)),null==y?{bitstr:{hex:f}}:{bitstr:{bin:y}}}else if("04"==p)try{if(!n(f))throw"not encap";return{octstr:{obj:r(f)}}}catch(e){return{octstr:{hex:f}}}else{if("05"==p)return{null:""};if("06"==p){var b=d(f),E=c(b);return""==E?{oid:b}:{oid:E}}if("0a"==p)return f.length>4?{enum:{hex:f}}:{enum:parseInt(f,16)};if("30"==p||"31"==p)return m[g[p]]=function(e){for(var t=[],n=o(e,0),i=0;i<n.length;i++){var a=n[i],d=s(e,a),c=r(d);t.push(c)}return t}(e),m;if("14"==p){var v=h(f);return m[g[p]]={str:v},m}if("1e"==p){v=u(f);return m[g[p]]={str:v},m}if(-1!=":0c:12:13:16:17:18:1a:".indexOf(p)){v=l(f);return m[g[p]]={str:v},m}if(p.match(/^8[0-9]$/))return null==(v=l(f))|""==v||null!=v.match(/[\x00-\x1F\x7F-\x9F]/)||null!=v.match(/[\u0000-\u001F\u0080–\u009F]/)?{tag:{tag:p,explicit:!1,hex:f}}:{tag:{tag:p,explicit:!1,str:v}};if(!p.match(/^a[0-9]$/)){var _=new KJUR.asn1.ASN1Object;return _.hV=f,{asn1:{tlv:p+_.getLengthHexFromValue()+f}}}try{if(!n(f))throw new Error("not encap");return{tag:{tag:p,explicit:!0,obj:r(f)}}}catch(e){return{tag:{tag:p,explicit:!0,hex:f}}}}},ASN1HEX.isContextTag=function(e,t){var r,n;e=e.toLowerCase();try{r=parseInt(e,16)}catch(e){return-1}if(void 0===t)return 128==(192&r);try{return null!=t.match(/^\[[0-9]+\]$/)&&(!((n=parseInt(t.substr(1,t.length-1),10))>31)&&(128==(192&r)&&(31&r)==n))}catch(e){return!1}},ASN1HEX.isASN1HEX=function(e){var t=ASN1HEX;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},ASN1HEX.checkStrictDER=function(e,t,r,n,i){var s=ASN1HEX;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!KJUR.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(s.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var o=s.getVblen(e,t);if(o>n)throw new Error("value of L too long than hex: idx="+t);var a=s.getTLV(e,t),d=a.length-2-s.getL(e,t).length;if(d!==2*o)throw new Error("V string length and L's value not the same:"+d+"/"+2*o);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var c=e.substr(t,2);if("02"===c){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(c,16)){for(var u=s.getVblen(e,t),h=0,g=s.getChildIdx(e,t),p=0;p<g.length;p++){h+=s.getTLV(e,g[p]).length,s.checkStrictDER(e,g[p],r,n,i)}if(2*u!=h)throw new Error("sum of children's TLV length and L unmatch: "+2*u+"!="+h)}},ASN1HEX.oidname=function(e){var t=KJUR.asn1;KJUR.lang.String.isHex(e)&&(e=t.ASN1Util.oidHexToInt(e));var r=t.x509.OID.oid2name(e);return""===r&&(r=e),r},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.x509&&KJUR.asn1.x509||(KJUR.asn1.x509={}),KJUR.asn1.x509.Certificate=function(e){KJUR.asn1.x509.Certificate.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERBitString,n=t.DERSequence,i=t.x509,s=i.TBSCertificate,o=i.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 r=e.tbsobj.tohex(),n=new KJUR.crypto.Signature({alg:t});n.init(e.cakey),n.updateHex(r),e.sighex=n.sign()},this.getPEM=function(){return hextopem(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 o({name:e.sigalg})),t.push(new r({hex:"00"+e.sighex})),new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.Certificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.TBSCertificate=function(e){KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=t.DERTaggedObject,i=t.DERInteger,s=t.DERSequence,o=r.AlgorithmIdentifier,a=r.Time,d=r.X500Name,c=r.Extensions,l=r.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 r=2;null!=t.version&&(r=t.version-1);var u=new n({obj:new i({int:r})});e.push(u)}return e.push(new i(t.serial)),e.push(new o({name:t.sigalg})),e.push(new d(t.issuer)),e.push(new s({array:[new a(t.notbefore),new a(t.notafter)]})),e.push(new d(t.subject)),e.push(new l(KEYUTIL.getKey(t.sbjpubkey))),void 0!==t.ext&&t.ext.length>0&&e.push(new n({tag:"a3",obj:new c(t.ext)})),new KJUR.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extensions=function(e){KJUR.asn1.x509.Extensions.superclass.constructor.call(this);var t=KJUR.asn1,r=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 i=this.aParam[t],s=i.extname,o=null;if(null!=i.extn)o=new n.PrivateExtension(i);else if("subjectKeyIdentifier"==s)o=new n.SubjectKeyIdentifier(i);else if("keyUsage"==s)o=new n.KeyUsage(i);else if("subjectAltName"==s)o=new n.SubjectAltName(i);else if("issuerAltName"==s)o=new n.IssuerAltName(i);else if("basicConstraints"==s)o=new n.BasicConstraints(i);else if("nameConstraints"==s)o=new n.NameConstraints(i);else if("cRLDistributionPoints"==s)o=new n.CRLDistributionPoints(i);else if("certificatePolicies"==s)o=new n.CertificatePolicies(i);else if("policyMappings"==s)o=new n.PolicyMappings(i);else if("policyConstraints"==s)o=new n.PolicyConstraints(i);else if("inhibitAnyPolicy"==s)o=new n.InhibitAnyPolicy(i);else if("authorityKeyIdentifier"==s)o=new n.AuthorityKeyIdentifier(i);else if("extKeyUsage"==s)o=new n.ExtKeyUsage(i);else if("authorityInfoAccess"==s)o=new n.AuthorityInfoAccess(i);else if("cRLNumber"==s)o=new n.CRLNumber(i);else if("cRLReason"==s)o=new n.CRLReason(i);else if("ocspNonce"==s)o=new n.OCSPNonce(i);else if("ocspNoCheck"==s)o=new n.OCSPNoCheck(i);else if("adobeTimeStamp"==s)o=new n.AdobeTimeStamp(i);else{if("subjectDirectoryAttributes"!=s)throw new Error("extension not supported:"+JSON.stringify(i));o=new n.SubjectDirectoryAttributes(i)}null!=o&&e.push(o)}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.Extensions,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extension=function(e){KJUR.asn1.x509.Extension.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERObjectIdentifier,n=t.DEROctetString;t.DERBitString;var i=t.DERBoolean,s=t.DERSequence;this.tohex=function(){var e=new r({oid:this.oid}),t=new n({hex:this.getExtnValueHex()}),o=new Array;return o.push(e),this.critical&&o.push(new i),o.push(t),new s({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.critical=!1,void 0!==e&&void 0!==e.critical&&(this.critical=e.critical)},extendClass(KJUR.asn1.x509.Extension,KJUR.asn1.ASN1Object),KJUR.asn1.x509.KeyUsage=function(e){KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this,e);var t=Error,r={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 KJUR.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 namearraytobinstr(e.names,r);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)},extendClass(KJUR.asn1.x509.KeyUsage,KJUR.asn1.x509.Extension),KJUR.asn1.x509.BasicConstraints=function(e){KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERBoolean,n=t.DERInteger,i=t.DERSequence;this.getExtnValueHex=function(){var e=new Array;this.cA&&e.push(new r),this.pathLen>-1&&e.push(new n({int:this.pathLen}));var t=new i({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))},extendClass(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLDistributionPoints=function(e){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],i=0;i<e.length;i++)if(e[i]instanceof KJUR.asn1.ASN1Object)n.push(e[i]);else{var s=new r.DistributionPoint(e[i]);n.push(s)}this.asn1ExtnValue=new t.DERSequence({array:n})},this.setByOneURI=function(e){var t=new r.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))},extendClass(KJUR.asn1.x509.CRLDistributionPoints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.DistributionPoint=function(e){KJUR.asn1.x509.DistributionPoint.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509.DistributionPointName;this.tohex=function(){var e=new t.DERSequence;if(null!=this.asn1DP){var r=new t.DERTaggedObject({explicit:!0,tag:"a0",obj:this.asn1DP});e.appendASN1Object(r)}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 r(e.dpname):void 0!==e.fulluri&&(this.asn1DP=new r({full:[{uri:e.fulluri}]})))},extendClass(KJUR.asn1.x509.DistributionPoint,KJUR.asn1.ASN1Object),KJUR.asn1.x509.DistributionPointName=function(e){KJUR.asn1.x509.DistributionPointName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERTaggedObject;if(this.tohex=function(){if("full"!=this.type)throw new Error("currently type shall be 'full': "+this.type);return this.asn1Obj=new r({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)}},extendClass(KJUR.asn1.x509.DistributionPointName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CertificatePolicies=function(e){KJUR.asn1.x509.CertificatePolicies.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509,n=t.DERSequence,i=r.PolicyInformation;this.params=null,this.getExtnValueHex=function(){for(var e=[],t=0;t<this.params.array.length;t++)e.push(new i(this.params.array[t]));var r=new n({array:e});return this.asn1ExtnValue=r,this.asn1ExtnValue.tohex()},this.oid="2.5.29.32",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.CertificatePolicies,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PolicyInformation=function(e){KJUR.asn1.x509.PolicyInformation.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier,i=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 i(this.params.array[s]));t.length>0&&e.push(new r({array:t}))}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyInformation,KJUR.asn1.ASN1Object),KJUR.asn1.x509.PolicyQualifierInfo=function(e){KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERIA5String,i=t.DERObjectIdentifier,s=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new r({array:[new i({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)},extendClass(KJUR.asn1.x509.PolicyQualifierInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.UserNotice=function(e){KJUR.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence;KJUR.asn1.DERInteger;var r=KJUR.asn1.x509.DisplayText,n=KJUR.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 r(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.UserNotice,KJUR.asn1.ASN1Object),KJUR.asn1.x509.NoticeReference=function(e){KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence,r=KJUR.asn1.DERInteger,n=KJUR.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 i=[],s=this.params.noticenum,o=0;o<s.length;o++)i.push(new r(s[o]));e.push(new t({array:i}))}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)},extendClass(KJUR.asn1.x509.NoticeReference,KJUR.asn1.ASN1Object),KJUR.asn1.x509.DisplayText=function(e){KJUR.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"))},extendClass(KJUR.asn1.x509.DisplayText,KJUR.asn1.DERAbstractString),KJUR.asn1.x509.PolicyMappings=function(e){KJUR.asn1.x509.PolicyMappings.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){for(var e=this.params,t=[],n=0;n<e.array.length;n++){var i=e.array[n];t.push({seq:[{oid:i[0]},{oid:i[1]}]})}return this.asn1ExtnValue=r({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.33",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyMappings,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PolicyConstraints=function(e){KJUR.asn1.x509.PolicyConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=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=r({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.36",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.InhibitAnyPolicy=function(e){KJUR.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this,e);var t=KJUR.asn1;t.x509;var r=t.ASN1Util.newObject;this.params=null,this.getExtnValueHex=function(){return this.asn1ExtnValue=r({int:this.params.skip}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.54",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.InhibitAnyPolicy,KJUR.asn1.x509.Extension),KJUR.asn1.x509.NameConstraints=function(e){KJUR.asn1.x509.NameConstraints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509,n=t.ASN1Util.newObject,i=r.GeneralSubtree;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[];if(null!=e.permit&&null!=e.permit.length){for(var r=[],s=0;s<e.permit.length;s++)r.push(new i(e.permit[s]));t.push({tag:{tagi:"a0",obj:{seq:r}}})}if(null!=e.exclude&&null!=e.exclude.length){var o=[];for(s=0;s<e.exclude.length;s++)o.push(new i(e.exclude[s]));t.push({tag:{tagi:"a1",obj:{seq:o}}})}return this.asn1ExtnValue=n({seq:t}),this.asn1ExtnValue.tohex()},this.oid="2.5.29.30",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.NameConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.GeneralSubtree=function(e){KJUR.asn1.x509.GeneralSubtree.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(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)},extendClass(KJUR.asn1.x509.GeneralSubtree,KJUR.asn1.ASN1Object),KJUR.asn1.x509.ExtKeyUsage=function(e){KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,e);var t=KJUR.asn1;this.setPurposeArray=function(e){this.asn1ExtnValue=new t.DERSequence;for(var r=0;r<e.length;r++){var n=new t.DERObjectIdentifier(e[r]);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)},extendClass(KJUR.asn1.x509.ExtKeyUsage,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AuthorityKeyIdentifier=function(e){KJUR.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,e);var t=KJUR,r=t.asn1,n=r.DERTaggedObject,i=r.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 i([{dn:this.asn1CertIssuer}])})),this.asn1CertSN&&e.push(new n({explicit:!1,tag:"82",obj:this.asn1CertSN}));var t=new r.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 KJUR.asn1.DEROctetString(e);else if("object"==typeof e&&KJUR.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN ")){var t=e;"string"==typeof e&&(t=KEYUTIL.getKey(e));var r=KEYUTIL.getKeyID(t);this.asn1KID=new KJUR.asn1.DEROctetString({hex:r})}},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 KJUR.asn1.x509.X500Name(e):"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&-1!=e.indexOf("CERTIFICATE")&&(this.asn1CertIssuer=new KJUR.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 KJUR.asn1.DERInteger(e);else if("string"==typeof e&&-1!=e.indexOf("BEGIN ")&&e.indexOf("CERTIFICATE")){var t=new X509;t.readCertPEM(e);var r=t.getSerialNumberHex();this.asn1CertSN=new KJUR.asn1.DERInteger({hex:r})}},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)))},extendClass(KJUR.asn1.x509.AuthorityKeyIdentifier,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectKeyIdentifier=function(e){KJUR.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this,e);var t=KJUR.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&&KJUR.crypto.Util.isKey(e)||"string"==typeof e&&-1!=e.indexOf("BEGIN")){var r=e;"string"==typeof e&&(r=KEYUTIL.getKey(e));var n=KEYUTIL.getKeyID(r);this.asn1KID=new KJUR.asn1.DEROctetString({hex:n})}},this.oid="2.5.29.14",void 0!==e&&void 0!==e.kid&&this.setKIDByParam(e.kid)},extendClass(KJUR.asn1.x509.SubjectKeyIdentifier,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AuthorityInfoAccess=function(e){KJUR.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,e),this.setAccessDescriptionArray=function(e){for(var t=new Array,r=KJUR.asn1,n=r.DERSequence,i=r.DERObjectIdentifier,s=r.x509.GeneralName,o=0;o<e.length;o++){var a,d=e[o];if(void 0!==d.ocsp)a=new n({array:[new i({oid:"1.3.6.1.5.5.7.48.1"}),new s({uri:d.ocsp})]});else{if(void 0===d.caissuer)throw new Error("unknown AccessMethod parameter: "+JSON.stringify(d));a=new n({array:[new i({oid:"1.3.6.1.5.5.7.48.2"}),new s({uri:d.caissuer})]})}t.push(a)}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)},extendClass(KJUR.asn1.x509.AuthorityInfoAccess,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectAltName=function(e){KJUR.asn1.x509.SubjectAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new KJUR.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)},extendClass(KJUR.asn1.x509.SubjectAltName,KJUR.asn1.x509.Extension),KJUR.asn1.x509.IssuerAltName=function(e){KJUR.asn1.x509.IssuerAltName.superclass.constructor.call(this,e),this.setNameArray=function(e){this.asn1ExtnValue=new KJUR.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)},extendClass(KJUR.asn1.x509.IssuerAltName,KJUR.asn1.x509.Extension),KJUR.asn1.x509.SubjectDirectoryAttributes=function(e){KJUR.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.ASN1Util.newObject,i=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 o={seq:[{oid:"1.2.3.4"},{set:[{utf8str:"DE"}]}]};if("dateOfBirth"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={gentime:s.str};else if("placeOfBirth"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={utf8str:s.str};else if("gender"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str};else if("countryOfCitizenship"==s.attr)o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str};else{if("countryOfResidence"!=s.attr)throw new Error("unsupported attribute: "+s.attr);o.seq[0].oid=i(s.attr),o.seq[1].set[0]={prnstr:s.str}}e.push(new n(o))}else{var a={seq:[{oid:s.attr},{set:s.array}]};e.push(n(a))}}var d=new r({array:e});return this.asn1ExtnValue=d,this.asn1ExtnValue.tohex()},this.oid="2.5.29.9",void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.SubjectDirectoryAttributes,KJUR.asn1.x509.Extension),KJUR.asn1.x509.PrivateExtension=function(e){KJUR.asn1.x509.PrivateExtension.superclass.constructor.call(this,e);var t=KJUR,r=t.lang.String.isHex,n=t.asn1,i=n.x509.OID.name2oid,s=n.ASN1Util.newObject;this.params=null,this.setByParam=function(e){this.oid=i(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&&r(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)},extendClass(KJUR.asn1.x509.PrivateExtension,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRL=function(e){KJUR.asn1.x509.CRL.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERBitString,i=t.x509,s=i.AlgorithmIdentifier,o=i.TBSCertList;this.params=void 0,this.setByParam=function(e){this.params=e},this.sign=function(){var e=new o(this.params).tohex(),t=new KJUR.crypto.Signature({alg:this.params.sigalg});t.init(this.params.cakey),t.updateHex(e);var r=t.sign();this.params.sighex=r},this.getPEM=function(){return hextopem(this.tohex(),"X509 CRL")},this.tohex=function(){var e=this.params;if(null==e.tbsobj&&(e.tbsobj=new o(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 r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRL,KJUR.asn1.ASN1Object),KJUR.asn1.x509.TBSCertList=function(e){KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERInteger,n=t.DERSequence,i=t.DERTaggedObject;t.DERObjectIdentifier;var s=t.x509,o=s.AlgorithmIdentifier,a=s.Time,d=s.Extensions,c=s.X500Name;this.params=null,this.setByParam=function(e){this.params=e},this.getRevCertSequence=function(){for(var e=[],t=this.params.revcert,i=0;i<t.length;i++){var s=[new r(t[i].sn),new a(t[i].date)];null!=t[i].ext&&s.push(new d(t[i].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 r({int:s});e.push(l)}if(e.push(new o({name:t.sigalg})),e.push(new c(t.issuer)),e.push(new a(t.thisupdate)),null!=t.nextupdate&&e.push(new a(t.nextupdate)),null!=t.revcert&&e.push(this.getRevCertSequence()),null!=t.ext){var u=new d(t.ext);e.push(new i({tag:"a0",explicit:!0,obj:u}))}return new n({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertList,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CRLEntry=function(e){KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);var t=KJUR.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))},extendClass(KJUR.asn1.x509.CRLEntry,KJUR.asn1.ASN1Object),KJUR.asn1.x509.CRLNumber=function(e){KJUR.asn1.x509.CRLNumber.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DERInteger(this.params.num),this.asn1ExtnValue.tohex()},this.oid="2.5.29.20",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRLNumber,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLReason=function(e){KJUR.asn1.x509.CRLReason.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DEREnumerated(this.params.code),this.asn1ExtnValue.tohex()},this.oid="2.5.29.21",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.CRLReason,KJUR.asn1.x509.Extension),KJUR.asn1.x509.OCSPNonce=function(e){KJUR.asn1.x509.OCSPNonce.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DEROctetString(this.params),this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.2",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.OCSPNonce,KJUR.asn1.x509.Extension),KJUR.asn1.x509.OCSPNoCheck=function(e){KJUR.asn1.x509.OCSPNoCheck.superclass.constructor.call(this,e),this.params=void 0,this.getExtnValueHex=function(){return this.asn1ExtnValue=new KJUR.asn1.DERNull,this.asn1ExtnValue.tohex()},this.oid="1.3.6.1.5.5.7.48.1.5",null!=e&&(this.params=e)},extendClass(KJUR.asn1.x509.OCSPNoCheck,KJUR.asn1.x509.Extension),KJUR.asn1.x509.AdobeTimeStamp=function(e){KJUR.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERInteger,n=t.DERBoolean,i=t.DERSequence,s=t.x509.GeneralName;this.params=null,this.getExtnValueHex=function(){var e=this.params,t=[new r(1)];return t.push(new s({uri:e.uri})),null!=e.reqauth&&t.push(new n(e.reqauth)),this.asn1ExtnValue=new i({array:t}),this.asn1ExtnValue.tohex()},this.oid="1.2.840.113583.1.1.9.1",void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AdobeTimeStamp,KJUR.asn1.x509.Extension),KJUR.asn1.x509.X500Name=function(e){KJUR.asn1.x509.X500Name.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.asn1,r=t.x509,n=r.RDN;this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var r=e.split("/");r.shift();for(var i=[],s=0;s<r.length;s++)if(r[s].match(/^[^=]+=.+$/))i.push(r[s]);else{var o=i.length-1;i[o]=i[o]+"/"+r[s]}for(s=0;s<i.length;s++)this.asn1Array.push(new n({str:i[s],rule:this.sRule}))},this.setByLdapString=function(e,t){void 0!==t&&(this.sRule=t);var n=r.X500Name.ldapToCompat(e);this.setByString(n,t)},this.setByObject=function(e,t){for(var r in void 0!==t&&(this.sRule=t),e)if(e.hasOwnProperty(r)){var i=new n({str:r+"="+e[r],rule:this.sRule});this.asn1Array?this.asn1Array.push(i):this.asn1Array=[i]}},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 X509).readCertPEM(e.certissuer),this.hTLV=t.getIssuerHex()):void 0!==e.certsubject?((t=new X509).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 r={array:this.paramArray[e]};"utf8"!=this.sRule&&(r.rule=this.sRule);var i=new n(r);this.asn1Array.push(i)}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)},extendClass(KJUR.asn1.x509.X500Name,KJUR.asn1.ASN1Object),KJUR.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(",")},KJUR.asn1.x509.X500Name.onelineToLDAP=function(e){return KJUR.asn1.x509.X500Name.compatToLDAP(e)},KJUR.asn1.x509.X500Name.ldapToCompat=function(e){for(var t=e.split(","),r=!1,n=[],i=0;t.length>0;i++){var s=t.shift();if(!0===r){var o=(n.pop()+","+s).replace(/\\,/g,",");n.push(o),r=!1}else n.push(s);"\\"===s.substr(-1,1)&&(r=!0)}return n=n.map((function(e){return e.replace("/","\\/")})),n.reverse(),"/"+n.join("/")},KJUR.asn1.x509.X500Name.ldapToOneline=function(e){return KJUR.asn1.x509.X500Name.ldapToCompat(e)},KJUR.asn1.x509.RDN=function(e){KJUR.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.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 KJUR.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=KJUR.asn1.x509.RDN.parseString(e),r=0;r<t.length;r++)this.addByString(t[r])},this.tohex=function(){if(0==this.asn1Array.length&&this.paramArray.length>0)for(var e=0;e<this.paramArray.length;e++){var r=this.paramArray[e];void 0!==r.rule&&"utf8"!=this.sRule&&(r.rule=this.sRule);var n=new t(r);this.asn1Array.push(n)}var i=new KJUR.asn1.DERSet({array:this.asn1Array});return this.TLV=i.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.RDN,KJUR.asn1.ASN1Object),KJUR.asn1.x509.RDN.parseString=function(e){for(var t=e.split(/\+/),r=!1,n=[],i=0;t.length>0;i++){var s=t.shift();if(!0===r){var o=(n.pop()+"+"+s).replace(/\\\+/g,"+");n.push(o),r=!1}else n.push(s);"\\"===s.substr(-1,1)&&(r=!0)}var a=!1,d=[];for(i=0;n.length>0;i++){s=n.shift();if(!0===a){var c=d.pop();if(s.match(/"$/)){o=(c+"+"+s).replace(/^([^=]+)="(.*)"$/,"$1=$2");d.push(o),a=!1}else d.push(c+"+"+s)}else d.push(s);s.match(/^[^=]+="/)&&(a=!0)}return d},KJUR.asn1.x509.AttributeTypeAndValue=function(e){KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=KJUR,r=t.asn1,n=r.DERSequence,i=r.DERUTF8String,s=r.DERPrintableString,o=r.DERTeletexString,a=r.DERIA5String,d=r.DERVisibleString,c=r.DERBMPString,l=t.lang.String.isMail,u=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 r=e.match(/^([^=]+)=(.+)$/);if(!r)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(r[1],r[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,r=this.sRule;return"prn"===r?"CN"==e&&l(t)?"ia5":u(t)?"prn":"utf8":"utf8"===r?"CN"==e&&l(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,r){void 0!==r&&(this.sRule=r),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new i({str:t});if("prn"==e)return new s({str:t});if("tel"==e)return new o({str:t});if("ia5"==e)return new a({str:t});if("vis"==e)return new d({str:t});if("bmp"==e)return new c({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=KJUR.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),r=new n({array:[e,t]});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AttributeTypeAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.x509.SubjectPublicKeyInfo=function(e){KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.DERInteger,i=r.DERBitString,s=r.DERObjectIdentifier,o=r.DERSequence,a=r.ASN1Util.newObject,d=r.x509.AlgorithmIdentifier,c=t.crypto;c.ECDSA,c.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new o({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 RSAKey){var t=a({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new d({name:"rsaEncryption"}),this.asn1SubjPKey=new i({hex:"00"+t})}}catch(e){}try{if(e instanceof KJUR.crypto.ECDSA){var r=new s({name:e.curveName});this.asn1AlgId=new d({name:"ecPublicKey",asn1params:r}),this.asn1SubjPKey=new i({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof KJUR.crypto.DSA){r=new a({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new d({name:"dsa",asn1params:r});var o=new n({bigint:e.y});this.asn1SubjPKey=new i({hex:"00"+o.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Time=function(e){KJUR.asn1.x509.Time.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new r,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)},KJUR.asn1.x509.Time_bak=function(e){KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);var t=KJUR.asn1,r=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 r(this.timeParams):new n(this.timeParams):"utc"==this.type?new r: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)},extendClass(KJUR.asn1.x509.Time,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier=function(e){KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=KJUR.asn1,r=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 r)n===this.nameAlg&&(e=r[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 i=[this.asn1Alg];null!==this.asn1Params&&i.push(this.asn1Params);var s=new t.DERSequence({array:i});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)}},extendClass(KJUR.asn1.x509.AlgorithmIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},KJUR.asn1.x509.GeneralName=function(e){KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=r.X500Name,i=r.OtherName,s=t.DERIA5String;t.DERPrintableString;var o=t.DEROctetString,a=t.DERTaggedObject,d=t.ASN1Object,c=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,r=this.params,l=!1;if(void 0!==r.other)e="a0",t=new i(r.other);else if(void 0!==r.rfc822)e="81",t=new s({str:r.rfc822});else if(void 0!==r.dns)e="82",t=new s({str:r.dns});else if(void 0!==r.dn)e="a4",l=!0,t="string"==typeof r.dn?new n({str:r.dn}):r.dn instanceof KJUR.asn1.x509.X500Name?r.dn:new n(r.dn);else if(void 0!==r.ldapdn)e="a4",l=!0,t=new n({ldapstr:r.ldapdn});else if(void 0!==r.certissuer||void 0!==r.certsubj){var u,h;e="a4",l=!0;var g=null;if(void 0!==r.certsubj?(u=!1,h=r.certsubj):(u=!0,h=r.certissuer),h.match(/^[0-9A-Fa-f]+$/),-1!=h.indexOf("-----BEGIN ")&&(g=pemtohex(h)),null==g)throw new Error("certsubj/certissuer not cert");var p,m=new X509;m.hex=g,p=u?m.getIssuerHex():m.getSubjectHex(),(t=new d).hTLV=p}else if(void 0!==r.uri)e="86",t=new s({str:r.uri});else{if(void 0===r.ip)throw new c("improper params");var f;e="87";var S=r.ip;try{if(S.match(/^[0-9a-f]+$/)){var y=S.length;if(8!=y&&16!=y&&32!=y&&64!=y)throw"err";f=S}else f=iptohex(S)}catch(e){throw new c("malformed IP address: "+r.ip+":"+e.message)}t=new o({hex:f})}return new a({tag:e,explicit:l,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.GeneralName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.GeneralNames=function(e){KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=KJUR.asn1;this.setByParamArray=function(e){for(var r=0;r<e.length;r++){var n=new t.x509.GeneralName(e[r]);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)},extendClass(KJUR.asn1.x509.GeneralNames,KJUR.asn1.ASN1Object),KJUR.asn1.x509.OtherName=function(e){KJUR.asn1.x509.OtherName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERObjectIdentifier,n=t.DERSequence,i=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 r({oid:e.oid}),s=i({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)},extendClass(KJUR.asn1.x509.OtherName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.OID=new function(){var e=KJUR.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 r=this.name2oidList[t],n=new e({oid:r});return this.objCache[t]=n,n},this.atype2obj=function(t){if(void 0!==this.objCache[t])return this.objCache[t];var r;if(t.match(/^\d+\.\d+\.[0-9.]+$/))r=t;else if(void 0!==this.atype2oidList[t])r=this.atype2oidList[t];else{if(void 0===this.name2oidList[t])throw new Error("AttributeType name undefined: "+t);r=this.name2oidList[t]}var n=new e({oid:r});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,r){if(!this[e].match(/^[0-2]\.[0-9.]+$/))throw new Error("value is not OID")}),e),!0)}catch(e){return!1}}},KJUR.asn1.x509.OID.oid2name=function(e){var t=KJUR.asn1.x509.OID.name2oidList;for(var r in t)if(t[r]==e)return r;return""},KJUR.asn1.x509.OID.oid2atype=function(e){var t=KJUR.asn1.x509.OID.atype2oidList;for(var r in t)if(t[r]==e)return r;return e},KJUR.asn1.x509.OID.name2oid=function(e){if(e.match(/^[0-9.]+$/))return e;var t=KJUR.asn1.x509.OID.name2oidList;return void 0===t[e]?"":t[e]},KJUR.asn1.x509.X509Util={},KJUR.asn1.x509.X509Util.newCertPEM=function(e){var t=KJUR.asn1.x509;return t.TBSCertificate,new(0,t.Certificate)(e).getPEM()},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.cms&&KJUR.asn1.cms||(KJUR.asn1.cms={}),KJUR.asn1.cms.Attribute=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERSet,s=r.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 i({array:this.getValueArray()});return new n({array:[e,t]}).tohex()},this.getEncodedHex=function(){return this.tohex()}},extendClass(KJUR.asn1.cms.Attribute,KJUR.asn1.ASN1Object),KJUR.asn1.cms.ContentType=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.cms.ContentType,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.MessageDigest=function(e){var t=KJUR.asn1,r=t.DEROctetString;t.cms.MessageDigest.superclass.constructor.call(this),this.typeOid="1.2.840.113549.1.9.4",this.getValueArray=function(){return[new r(this.params)]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.MessageDigest,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.SigningTime=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.cms.SigningTime,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.SigningCertificate=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence,s=n.cms,o=s.ESSCertID;r.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 r=this.params.array,n=[],s=0;s<r.length;s++){var a=r[s];0!=e.hasis||"string"!=typeof a||-1==a.indexOf("-----BEGIN")&&!ASN1HEX.isASN1HEX(a)||(a={cert:a}),0!=a.hasis&&0==e.hasis&&(a.hasis=!1),n.push(new o(a))}var d=new i({array:n});return[new i({array:[d]})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SigningCertificate,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.ESSCertID=function(e){KJUR.asn1.cms.ESSCertID.superclass.constructor.call(this);var t=Error,r=KJUR,n=r.asn1,i=n.DEROctetString,s=n.DERSequence,o=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")&&!ASN1HEX.isASN1HEX(e))return e;var i,s,o;if("string"==typeof e)i=e;else{if(null==e.cert)throw new t("hash nor cert unspecified");i=e.cert}if(s=-1!=i.indexOf("-----BEGIN")?pemtohex(i):i,"string"==typeof e&&(-1!=e.indexOf("-----BEGIN")?s=pemtohex(e):ASN1HEX.isASN1HEX(e)&&(s=e)),null!=e.alg)o=e.alg;else{if(null==n)throw new t("hash alg unspecified");o=n}return r.crypto.Util.hashHex(s,o)},this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha1"),r=[];return r.push(new i({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&r.push(new o(e)),new s({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.ESSCertID,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SigningCertificateV2=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence;n.x509;var s=n.cms,o=s.ESSCertIDv2;r.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 r=this.params.array,n=[],s=0;s<r.length;s++){var a=r[s];null==e.alg&&0!=e.hasis||"string"!=typeof a||-1==a.indexOf("-----BEGIN")&&!ASN1HEX.isASN1HEX(a)||(a={cert:a}),null==a.alg&&null!=e.alg&&(a.alg=e.alg),0!=a.hasis&&0==e.hasis&&(a.hasis=!1),n.push(new o(a))}var d=new i({array:n});return[new i({array:[d]})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SigningCertificateV2,KJUR.asn1.cms.Attribute),KJUR.asn1.cms.ESSCertIDv2=function(e){KJUR.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DEROctetString,n=t.DERSequence,i=t.cms.IssuerSerial,s=t.x509.AlgorithmIdentifier;this.params=null,this.tohex=function(){var e=this.params,t=this.getCertHash(e,"sha256"),o=[];return null!=e.alg&&"sha256"!=e.alg&&o.push(new s({name:e.alg})),o.push(new r({hex:t})),("string"==typeof e&&-1!=e.indexOf("-----BEGIN")||null!=e.cert&&0!=e.hasis||null!=e.issuer&&null!=e.serial)&&o.push(new i(e)),new n({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.ESSCertIDv2,KJUR.asn1.cms.ESSCertID),KJUR.asn1.cms.IssuerSerial=function(e){var t=Error,r=KJUR.asn1,n=r.DERInteger,i=r.DERSequence,s=r.cms,o=r.x509.GeneralNames,a=X509;s.IssuerSerial.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.tohex=function(){var e,r,s=this.params;if("string"==typeof s&&-1!=s.indexOf("-----BEGIN")||null!=s.cert){var d;d=null!=s.cert?s.cert:s;var c=new a;c.readCertPEM(d),e=c.getIssuer(),r={hex:c.getSerialNumberHex()}}else{if(null==s.issuer||!s.serial)throw new t("cert or issuer and serial parameter not specified");e=s.issuer,r=s.serial}var l=new o([{dn:e}]),u=new n(r);return new i({array:[l,u]}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.IssuerSerial,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignerIdentifier=function(e){var t=KJUR.asn1;t.DERInteger,t.DERSequence;var r=t.cms,n=r.IssuerAndSerialNumber,i=r.SubjectKeyIdentifier;t.x509.X500Name,r.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 i(e).tohex();throw new Error("wrong property for isssn or skid")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignerIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.cms.IssuerAndSerialNumber=function(e){var t=KJUR.asn1,r=t.DERInteger,n=t.DERSequence,i=t.cms,s=t.x509.X500Name,o=X509,a=Error;i.IssuerAndSerialNumber.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e,t,i=this.params;if("string"==typeof i&&-1!=i.indexOf("-----BEGIN")||null!=i.cert){var d;d=null!=i.cert?i.cert:i;var c=new o;c.readCertPEM(d),e=c.getIssuer(),t={hex:c.getSerialNumberHex()}}else{if(null==i.issuer||!i.serial)throw new a("cert or issuer and serial parameter not specified");e=i.issuer,t=i.serial}var l=new s(e),u=new r(t);return new n({array:[l,u]}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.IssuerAndSerialNumber,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SubjectKeyIdentifier=function(e){var t=KJUR.asn1;t.DERInteger,t.DERSequence;var r=t.ASN1Util.newObject,n=t.cms;n.IssuerAndSerialName,n.SubjectKeyIdentifier,t.x509.X500Name;var i=X509,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 i(t.cert).getExtSubjectKeyIdentifier().kid.hex:null!=t.skid&&(e=t.skid);return r({tag:{tage:"a0",obj:{octstr:{hex:e}}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SubjectKeyIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.cms.AttributeList=function(e){var t=Error,r=KJUR.asn1,n=r.DERSet,i=r.cms;i.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 r=!0;null!=e.sortflag&&(r=e.sortflag);for(var s=e.array,o=[],a=0;a<s.length;a++){var d=s[a],c=d.attr;if("contentType"==c)o.push(new i.ContentType(d));else if("messageDigest"==c)o.push(new i.MessageDigest(d));else if("signingTime"==c)o.push(new i.SigningTime(d));else if("signingCertificate"==c)o.push(new i.SigningCertificate(d));else if("signingCertificateV2"==c)o.push(new i.SigningCertificateV2(d));else if("signaturePolicyIdentifier"==c)o.push(new KJUR.asn1.cades.SignaturePolicyIdentifier(d));else{if("signatureTimeStamp"!=c&&"timeStampToken"!=c)throw new t("unknown attr: "+c);o.push(new KJUR.asn1.cades.SignatureTimeStamp(d))}}var l=new n({array:o,sortflag:r});return this.hTLV=l.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.AttributeList,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignerInfo=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERInteger,s=n.DEROctetString,o=n.DERSequence,a=n.DERTaggedObject,d=n.cms,c=d.SignerIdentifier,l=d.AttributeList;d.ContentType,d.EncapsulatedContentInfo,d.MessageDigest,d.SignedData;var u=n.x509.AlgorithmIdentifier,h=r.crypto,g=KEYUTIL;d.SignerInfo.superclass.constructor.call(this),this.params=null,this.sign=function(){var e=this.params,t=e.sigalg,r=new l(e.sattrs).tohex(),n=g.getKey(e.signkey),i=new h.Signature({alg:t});i.init(n),i.updateHex(r);var s=i.sign();e.sighex=s},this.tohex=function(){var e=this.params,r=[];if(r.push(new i({int:e.version})),r.push(new c(e.id)),r.push(new u({name:e.hashalg})),null!=e.sattrs){var n=new l(e.sattrs);try{r.push(new a({tag:"a0",explicit:!1,obj:n}))}catch(e){throw new t("si sattr error: "+e)}}if(null!=e.sigalgfield?r.push(new u({name:e.sigalgfield})):r.push(new u({name:e.sigalg})),null==e.sighex&&null!=e.signkey&&this.sign(),r.push(new s({hex:e.sighex})),null!=e.uattrs){n=new l(e.uattrs);try{r.push(new a({tag:"a1",explicit:!1,obj:n}))}catch(e){throw new t("si uattr error: "+e)}}return new o({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignerInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.EncapsulatedContentInfo=function(e){var t=KJUR.asn1,r=t.DERTaggedObject,n=t.DERSequence,i=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 i(e.type)),null!=e.content&&(null!=e.content.hex||null!=e.content.str)&&1!=e.isDetached){var o=new s(e.content),a=new r({tag:"a0",explicit:!0,obj:o});t.push(a)}return new n({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.EncapsulatedContentInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.ContentInfo=function(e){var t=KJUR.asn1,r=t.DERTaggedObject,n=t.DERSequence,i=t.DERObjectIdentifier;t.x509.OID.name2obj,KJUR.asn1.cms.ContentInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=[];t.push(new i(e.type));var s=new r({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)},extendClass(KJUR.asn1.cms.ContentInfo,KJUR.asn1.ASN1Object),KJUR.asn1.cms.SignedData=function(e){var t=KJUR.asn1;t.ASN1Object;var r=t.DERInteger,n=t.DERSet,i=t.DERSequence;t.DERTaggedObject;var s=t.cms,o=s.EncapsulatedContentInfo,a=s.SignerInfo,d=s.ContentInfo,c=s.CertificateSet,l=s.RevocationInfoChoices,u=t.x509.AlgorithmIdentifier;KJUR.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={},r=e.sinfos,n=0;n<r.length;n++){t[r[n].hashalg]=1}e.hashalgs=Object.keys(t).sort()},this._setContentTypeByEContent=function(e){for(var t=e.econtent.type,r=e.sinfos,n=0;n<r.length;n++){var i=r[n];this._getAttrParamByName(i,"contentType").type=t}},this._setMessageDigestByEContent=function(e){var t=e.econtent;e.econtent.type;var r=t.content.hex;null==r&&"data"==t.type&&null!=t.content.str&&(r=rstrtohex(t.content.str));for(var n=e.sinfos,i=0;i<n.length;i++){var s=n[i],o=s.hashalg,a=this._getAttrParamByName(s,"messageDigest"),d=KJUR.crypto.Util.hashHex(r,o);a.hex=d}},this._getAttrParamByName=function(e,t){for(var r=e.sattrs.array,n=0;n<r.length;n++)if(r[n].attr==t)return r[n]},this._setSignerInfoVersion=function(e){for(var t=e.sinfos,r=0;r<t.length;r++){var n=t[r],i=1;"skid"==n.id.type&&(i=3),n.version=i}},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,r=0;r<t.length;r++){if(null!=t[r].ocsp)return 5}var n=e.sinfos;for(r=0;r<n.length;r++){if(3==e.sinfos[r].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 r({int:e.version}));for(var s=[],d=0;d<e.hashalgs.length;d++){var h=e.hashalgs[d];s.push(new u({name:h}))}t.push(new n({array:s})),t.push(new o(e.econtent)),null!=e.certs&&t.push(new c(e.certs)),null!=e.revinfos&&t.push(new l(e.revinfos));var g=[];for(d=0;d<e.sinfos.length;d++){var p=e.sinfos[d];g.push(new a(p))}return t.push(new n({array:g})),new i({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.getContentInfo=function(){return new d({type:"signed-data",obj:this})},this.getContentInfoEncodedHex=function(){return this.getContentInfo().tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.SignedData,KJUR.asn1.ASN1Object),KJUR.asn1.cms.CertificateSet=function(e){KJUR.asn1.cms.CertificateSet.superclass.constructor.call(this);var t=Error,r=KJUR.asn1,n=r.DERTaggedObject,i=r.DERSet,s=r.ASN1Object;this.params=null,this.tohex=function(){var e,r=this.params,o=[];if(r instanceof Array)e=r;else{if(null==r.array)throw new t("cert array not specified");e=r.array}for(var a=0;a<e.length;a++){var d=pemtohex(e[a]),c=new s;c.hTLV=d,o.push(c)}var l={array:o};0==r.sortflag&&(l.sortflag=!1);var u=new i(l);return new n({tag:"a0",explicit:!1,obj:u}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.CertificateSet,KJUR.asn1.ASN1Object),KJUR.asn1.cms.RevocationInfoChoices=function(e){KJUR.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=[],r=0;r<e.length;r++)t.push(new KJUR.asn1.cms.RevocationInfoChoice(e[r]));return KJUR.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:{set:t}}}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.RevocationInfoChoices,KJUR.asn1.ASN1Object),KJUR.asn1.cms.RevocationInfoChoice=function(e){KJUR.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=pemtohex(e.crl)),t}if(null!=e.ocsp)return KJUR.asn1.ASN1Util.newObject({tag:{tagi:"a1",obj:new KJUR.asn1.cms.OtherRevocationFormat(e)}}).tohex();throw new Error("property crl or ocsp undefined")},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cms.RevocationInfoChoice,KJUR.asn1.ASN1Object),KJUR.asn1.cms.OtherRevocationFormat=function(e){KJUR.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);var t=Error,r=KJUR,n=r.asn1.ASN1Util.newObject,i=r.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(!i(e.ocsp)||!ASN1HEX.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)},extendClass(KJUR.asn1.cms.OtherRevocationFormat,KJUR.asn1.ASN1Object),KJUR.asn1.cms.CMSUtil=new function(){},KJUR.asn1.cms.CMSUtil.newSignedData=function(e){return new KJUR.asn1.cms.SignedData(e)},KJUR.asn1.cms.CMSUtil.verifySignedData=function(e){var t=KJUR,r=t.asn1,n=r.cms;n.SignerInfo,n.SignedData,n.SigningTime,n.SigningCertificate,n.SigningCertificateV2,r.cades.SignaturePolicyIdentifier;var i=t.lang.String.isHex,s=ASN1HEX,o=s.getVbyList,a=s.getTLVbyList,d=s.getIdxbyList,c=s.getChildIdx,l=s.getTLV,u=s.oidname,h=t.crypto.Util.hashHex;void 0===e.cms&&i(e.cms);var g=e.cms,p=function(e,t){var r=t.idx;t.signerid_issuer1=a(e,r,[1,0],"30"),t.signerid_serial1=o(e,r,[1,1],"02"),t.hashalg=u(o(e,r,[2,0],"06"));var n=d(e,r,[3],"a0");t.idxSignedAttrs=n,m(e,t,n);var i=c(e,r).length;if(i<6)throw"malformed SignerInfo";t.sigalg=u(o(e,r,[i-2,0],"06")),t.sigval=o(e,r,[i-1],"04")},m=function(e,t,r){var n=c(e,r);t.signedAttrIdxList=n;for(var i=0;i<n.length;i++){var s,a=n[i],d=o(e,a,[0],"06");"2a864886f70d010905"===d?(s=hextoutf8(o(e,a,[1,0])),t.saSigningTime=s):"2a864886f70d010904"===d&&(s=o(e,a,[1,0],"04"),t.saMessageDigest=s)}},f=function(e,t,r,n){r.verifyDetail={};var i=r.verifyDetail,s=t.parse.econtent,o=r.hashalg,a=r.saMessageDigest;i.validMessageDigest=!1,h(s,o)===a&&(i.validMessageDigest=!0),function(e,t,r,n){var i,s=t.parse.certsIdx;if(void 0===t.certs){i=[],t.certkeys=[];for(var o=c(e,s),a=0;a<o.length;a++){var d=l(e,o[a]),u=new X509;u.readCertHex(d),i[a]=u,t.certkeys[a]=u.getPublicKey()}t.certs=i}else i=t.certs;for(t.cccc=i.length,t.cccci=o.length,a=0;a<i.length;a++){var h=u.getIssuerHex(),g=u.getSerialNumberHex();r.signerid_issuer1===h&&r.signerid_serial1===g&&(r.certkey_idx=a)}}(e,t,r),i.validSignatureValue=!1;var d=r.sigalg,u="31"+l(e,r.idxSignedAttrs).substr(2);r.signedattrshex=u;var g=t.certs[r.certkey_idx].getPublicKey(),p=new KJUR.crypto.Signature({alg:d});p.init(g),p.updateHex(u);var m=p.verify(r.sigval);i.validSignatureValue_isValid=m,!0===m&&(i.validSignatureValue=!0),r.isValid=!1,i.validMessageDigest&&i.validSignatureValue&&(r.isValid=!0)},S={isValid:!1,parse:{}};return function(e,t){if("2a864886f70d010702"!==o(e,0,[0],"06"))return t;t.cmsType="signedData",t.econtent=o(e,0,[1,0,2,1,0]),function(e,t){for(var r,n=3;n<6;n++)if(void 0!==(r=d(e,0,[1,0,n]))){var i=e.substr(r,2);"a0"===i&&(t.certsIdx=r),"a1"===i&&(t.revinfosIdx=r),"31"===i&&(t.signerinfosIdx=r)}}(e,t),t.signerInfos=[],function(e,t){var r=t.signerinfosIdx;if(void 0!==r){var n=c(e,r);t.signerInfoIdxList=n;for(var i=0;i<n.length;i++){var s={idx:n[i]};p(e,s),t.signerInfos.push(s)}}}(e,t)}(g,S.parse),function(e,t){for(var r=t.parse.signerInfos,n=r.length,i=!0,s=0;s<n;s++){var o=r[s];f(e,t,o),o.isValid||(i=!1)}t.isValid=i}(g,S),S},KJUR.asn1.cms.CMSParser=function(){var e=Error,t=X509,r=new t,n=ASN1HEX,i=n.getV,s=n.getTLV;n.getIdxbyList;var o=n.getTLVbyList,a=n.getTLVbyListEx,d=n.getVbyList,c=n.getVbyListEx,l=n.getChildIdx;this.getCMSSignedData=function(e){var t=o(e,0,[1,0]);return this.getSignedData(t)},this.getSignedData=function(e){var t=l(e,0),r={},n=i(e,t[0]),o=parseInt(n,16);r.version=o;var d=s(e,t[1]);r.hashalgs=this.getHashAlgArray(d);var c=s(e,t[2]);r.econtent=this.getEContent(c);var u=a(e,0,["[0]"]);null!=u&&(r.certs=this.getCertificateSet(u)),a(e,0,["[1]"]);var h=a(e,0,[3]);return r.sinfos=this.getSignerInfos(h),r},this.getHashAlgArray=function(e){for(var r=l(e,0),n=new t,i=[],o=0;o<r.length;o++){var a=s(e,r[o]),d=n.getAlgorithmIdentifierName(a);i.push(d)}return i},this.getEContent=function(e){var t={},r=d(e,0,[0]),n=d(e,0,[1,0]);return t.type=KJUR.asn1.x509.OID.oid2name(ASN1HEX.hextooidstr(r)),t.content={hex:n},t},this.getSignerInfos=function(e){for(var t=[],r=l(e,0),n=0;n<r.length;n++){var i=s(e,r[n]),o=this.getSignerInfo(i);t.push(o)}return t},this.getSignerInfo=function(e){var t={},i=l(e,0),o=n.getInt(e,i[0],-1);-1!=o&&(t.version=o);var d=s(e,i[1]),u=this.getIssuerAndSerialNumber(d);t.id=u;var h=s(e,i[2]),g=r.getAlgorithmIdentifierName(h);t.hashalg=g;var p=a(e,0,["[0]"]);if(null!=p){var m=this.getAttributeList(p);t.sattrs=m}var f=a(e,0,[3]),S=r.getAlgorithmIdentifierName(f);t.sigalg=S;var y=c(e,0,[4]);t.sighex=y;var b=a(e,0,["[1]"]);if(null!=b){var E=this.getAttributeList(b);t.uattrs=E}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),o=s(e,n[0]);t.issuer=r.getX500Name(o);var a=i(e,n[1]);return t.serial={hex:a},t},this.getAttributeList=function(e){for(var t=[],r=l(e,0),n=0;n<r.length;n++){var i=s(e,r[n]),o=this.getAttribute(i);t.push(o)}return{array:t}},this.getAttribute=function(e){var t={},r=l(e,0),i=n.getOID(e,r[0]),o=KJUR.asn1.x509.OID.oid2name(i);t.attr=o;var a=s(e,r[1]),d=l(a,0);if(1==d.length)t.valhex=s(a,d[0]);else{for(var c=[],u=0;u<d.length;u++)c.push(s(a,d[u]));t.valhex=c}return"contentType"==o?this.setContentType(t):"messageDigest"==o?this.setMessageDigest(t):"signingTime"==o?this.setSigningTime(t):"signingCertificate"==o?this.setSigningCertificate(t):"signingCertificateV2"==o?this.setSigningCertificateV2(t):"signaturePolicyIdentifier"==o&&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=hextoutf8(i(e.valhex,0));e.str=t,delete e.valhex},this.setMessageDigest=function(e){var t=i(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 r=s(e.valhex,t[0]),n=l(r,0),i=[],o=0;o<n.length;o++){var a=s(r,n[o]),d=this.getESSCertID(a);i.push(d)}e.array=i}if(t.length>1){var c=s(e.valhex,t[1]);e.polhex=c}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var r=l(e.valhex,0);if(r.length>0){var o=n.getOID(e.valhex,r[0]);e.oid=o}if(r.length>1){var a=new t,d=l(e.valhex,r[1]),c=s(e.valhex,d[0]),u=a.getAlgorithmIdentifierName(c);e.alg=u;var h=i(e.valhex,d[1]);e.hash=h}delete e.valhex},this.setSigningCertificateV2=function(e){var t=l(e.valhex,0);if(t.length>0){for(var r=s(e.valhex,t[0]),n=l(r,0),i=[],o=0;o<n.length;o++){var a=s(r,n[o]),d=this.getESSCertIDv2(a);i.push(d)}e.array=i}if(t.length>1){var c=s(e.valhex,t[1]);e.polhex=c}delete e.valhex},this.getESSCertID=function(e){var t={},r=l(e,0);if(r.length>0){var n=i(e,r[0]);t.hash=n}if(r.length>1){var o=s(e,r[1]),a=this.getIssuerSerial(o);null!=a.serial&&(t.serial=a.serial),null!=a.issuer&&(t.issuer=a.issuer)}return t},this.getESSCertIDv2=function(t){var n={},o=l(t,0);if(o.length<1||3<o.length)throw new e("wrong number of elements");var a=0;if("30"==t.substr(o[0],2)){var d=s(t,o[0]);n.alg=r.getAlgorithmIdentifierName(d),a++}else n.alg="sha256";var c=i(t,o[a]);if(n.hash=c,o.length>a+1){var u=s(t,o[a+1]),h=this.getIssuerSerial(u);n.issuer=h.issuer,n.serial=h.serial}return n},this.getIssuerSerial=function(e){var t={},n=l(e,0),o=s(e,n[0]),a=r.getGeneralNames(o)[0].dn;t.issuer=a;var d=i(e,n[1]);return t.serial={hex:d},t},this.getCertificateSet=function(e){for(var t=l(e,0),r=[],n=0;n<t.length;n++){var i=s(e,t[n]);if("30"==i.substr(0,2)){var o=hextopem(i,"CERTIFICATE");r.push(o)}}return{array:r,sortflag:!1}}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.tsp&&KJUR.asn1.tsp||(KJUR.asn1.tsp={}),KJUR.asn1.tsp.TimeStampToken=function(e){var t=KJUR.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)},extendClass(KJUR.asn1.tsp.TimeStampToken,KJUR.asn1.cms.SignedData),KJUR.asn1.tsp.TSTInfo=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERInteger,i=t.DERBoolean,s=t.DERGeneralizedTime,o=t.DERObjectIdentifier,a=t.DERTaggedObject,d=t.tsp,c=d.MessageImprint,l=d.Accuracy;t.x509.X500Name;var u=t.x509.GeneralName;if(d.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 r({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 o({oid:e.policy})}void 0!==e.messageImprint&&(this.dMessageImprint=new c(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 i),void 0!==e.nonce&&(this.dNonce=new n(e.nonce)),void 0!==e.tsa&&(this.dTsa=new a({tag:"a0",explicit:!0,obj:new u({dn:e.tsa})}))}},extendClass(KJUR.asn1.tsp.TSTInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.Accuracy=function(e){var t=KJUR.asn1,r=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}}}),r({seq:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.Accuracy,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.MessageImprint=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DEROctetString,i=t.x509.AlgorithmIdentifier;t.tsp.MessageImprint.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,t=new i({name:e.alg}),s=new n({hex:e.hash});return new r({array:[t,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.MessageImprint,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.TimeStampReq=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERInteger,i=t.DERBoolean;t.ASN1Object;var s=t.DERObjectIdentifier,o=t.tsp,a=o.MessageImprint;o.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 KJUR.asn1.ASN1Object?t.push(e.messageImprint):t.push(new a(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 i),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.TimeStampReq,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.TimeStampResp=function(e){var t=KJUR.asn1,r=t.DERSequence;t.ASN1Object;var n=t.tsp,i=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 i(e.statusinfo)):s.push(new i("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 i(e.statusinfo))}return new r({array:s}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.TimeStampResp,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIStatusInfo=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.tsp,s=i.PKIStatus,o=i.PKIFreeText,a=i.PKIFailureInfo;i.PKIStatusInfo.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,r=[];if("string"==typeof e)r.push(new s(e));else{if(null==e.status)throw new t("property 'status' unspecified");r.push(new s(e.status)),null!=e.statusstr&&r.push(new o(e.statusstr)),null!=e.failinfo&&r.push(new a(e.failinfo))}return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIStatusInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIStatus=function(e){var t=Error,r=KJUR.asn1,n=r.DERInteger;r.tsp.PKIStatus.superclass.constructor.call(this);var i={granted:0,grantedWithMods:1,rejection:2,waiting:3,revocationWarning:4,revocationNotification:5};this.params=null,this.tohex=function(){var e,r=this.params;if("string"==typeof r)try{e=i[r]}catch(e){throw new t("undefined name: "+r)}else{if("number"!=typeof r)throw new t("unsupported params");e=r}return new n({int:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIStatus,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIFreeText=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERUTF8String;r.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 r=[],s=0;s<e.length;s++)r.push(new i({str:e[s]}));return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIFreeText,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.PKIFailureInfo=function(e){var t=Error,r=KJUR.asn1,n=r.DERBitString,i=r.tsp.PKIFailureInfo,s={badAlg:0,badRequest:2,badDataFormat:5,timeNotAvailable:14,unacceptedPolicy:15,unacceptedExtension:16,addInfoNotAvailable:17,systemFailure:25};i.superclass.constructor.call(this),this.params=null,this.getBinValue=function(){var e=this.params,r=0;if("number"==typeof e&&0<=e&&e<=25){for(var n=(r|=1<<e).toString(2),i="",o=n.length-1;o>=0;o--)i+=n[o];return i}if("string"==typeof e&&null!=s[e])return namearraytobinstr([e],s);if("object"==typeof e&&null!=e.length)return namearraytobinstr(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)},extendClass(KJUR.asn1.tsp.PKIFailureInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},KJUR.asn1.tsp.SimpleTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var i=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:i},this.params.econtent.content.serial={int:this.serial++};var s=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:s},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.SimpleTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.FixedTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var i=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:i},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.FixedTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.TSPUtil=new function(){},KJUR.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new KJUR.asn1.tsp.TimeStampToken(e)},KJUR.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new KJUR.asn1.tsp.TSPParser).getTimeStampReq(e)},KJUR.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new KJUR.asn1.tsp.TSPParser).getMessageImprint(e)},KJUR.asn1.tsp.TSPParser=function(){var e=new X509,t=ASN1HEX,r=t.getV,n=t.getTLV,i=t.getIdxbyList;t.getTLVbyListEx;var s=t.getChildIdx,o=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],a={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 r=this.getPKIStatusInfo(n(e,t[0])),i=n(e,t[1]),o=this.getToken(i);return o.statusinfo=r,o}},this.getToken=function(e){var t=(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var r=t.content.hex,n=this.getTSTInfo(r);t.content=n}},this.getTSTInfo=function(t){var i={},o=s(t,0),a=r(t,o[1]);i.policy=hextooid(a);var d=n(t,o[2]);i.messageImprint=this.getMessageImprint(d);var c=r(t,o[3]);i.serial={hex:c};var l=r(t,o[4]);i.genTime={str:hextoutf8(l)};var u=0;if(o.length>5&&"30"==t.substr(o[5],2)){var h=n(t,o[5]);i.accuracy=this.getAccuracy(h),u++}o.length>5+u&&"01"==t.substr(o[5+u],2)&&("ff"==r(t,o[5+u])&&(i.ordering=!0),u++);if(o.length>5+u&&"02"==t.substr(o[5+u],2)){var g=r(t,o[5+u]);i.nonce={hex:g},u++}if(o.length>5+u&&"a0"==t.substr(o[5+u],2)){var p=n(t,o[5+u]);p="30"+p.substr(2),pGeneralNames=e.getGeneralNames(p);var m=pGeneralNames[0].dn;i.tsa=m,u++}if(o.length>5+u&&"a1"==t.substr(o[5+u],2)){var f=n(t,o[5+u]);f="30"+f.substr(2);var S=e.getExtParamArray(f);i.ext=S,u++}return i},this.getAccuracy=function(e){for(var t={},n=s(e,0),i=0;i<n.length;i++){var o=e.substr(n[i],2),a=r(e,n[i]),d=parseInt(a,16);"02"==o?t.seconds=d:"80"==o?t.millis=d:"81"==o&&(t.micros=d)}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 o=i(e,0,[0,0]),a=r(e,o),d=t.hextooidstr(a),c=KJUR.asn1.x509.OID.oid2name(d);if(""==c)throw new Error("hashAlg name undefined: "+d);var l=c,u=i(e,0,[1]);return n.alg=l,n.hash=r(e,u),n},this.getPKIStatusInfo=function(e){var t={},i=s(e,0),a=0;try{var d=r(e,i[0]),c=parseInt(d,16);t.status=o[c]}catch(e){}if(i.length>1&&"30"==e.substr(i[1],2)){var l=n(e,i[1]);t.statusstr=this.getPKIFreeText(l),a++}if(i.length>a&&"03"==e.substr(i[1+a],2)){var u=n(e,i[1+a]);t.failinfo=this.getPKIFailureInfo(u)}return t},this.getPKIFreeText=function(e){for(var r=[],n=s(e,0),i=0;i<n.length;i++)r.push(t.getString(e,n[i]));return r},this.getPKIFailureInfo=function(e){var r=t.getInt(e,0);return null!=a[r]?a[r]:r},this.getTimeStampReq=function(e){var i={certreq:!1},o=s(e,0);if(o.length<2)throw new Error("TimeStampReq must have at least 2 items");var a=n(e,o[1]);i.messageImprint=KJUR.asn1.tsp.TSPUtil.parseMessageImprint(a);for(var d=2;d<o.length;d++){var c=o[d],l=e.substr(c,2);if("06"==l){var u=r(e,c);i.policy=t.hextooidstr(u)}"02"==l&&(i.nonce=r(e,c)),"01"==l&&(i.certreq=!0)}return i}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.cades&&KJUR.asn1.cades||(KJUR.asn1.cades={}),KJUR.asn1.cades.SignaturePolicyIdentifier=function(e){var t=KJUR.asn1.cades,r=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 r(this.params)]},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignaturePolicyIdentifier,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.SignaturePolicyId=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier;t.x509.AlgorithmIdentifier;var i=t.cades,s=i.SignaturePolicyId,o=i.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 o(e)),new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignaturePolicyId,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHashAlgAndValue=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DEROctetString,s=r.x509.AlgorithmIdentifier;r.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 r=null;if(null!=e.hash)r=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var o=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(o=pemtohex(e.cert)),r=KJUR.crypto.Util.hashHex(o,e.alg)}var a=[];return a.push(new s({name:e.alg})),a.push(new i({hex:r})),new n({array:a}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHashAlgAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHashValue=function(e){KJUR.asn1.cades.OtherHashValue.superclass.constructor.call(this);var t=Error,r=KJUR;r.lang.String.isHex;var n=r.asn1.DEROctetString;r.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 r=null;if(null!=e.hash)r=e.hash;else if(null!=e.cert){if("string"!=typeof e.cert)throw new t("cert not string");var i=e.cert;-1!=e.cert.indexOf("-----BEGIN")&&(i=pemtohex(e.cert)),r=KJUR.crypto.Util.hashHex(i,"sha1")}return new n({hex:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHashValue,KJUR.asn1.ASN1Object),KJUR.asn1.cades.SignatureTimeStamp=function(e){var t=Error,r=KJUR,n=r.lang.String.isHex,i=r.asn1,s=i.ASN1Object;i.x509,i.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(r=new s).hTLV=e.tst,[r];if(e.tst instanceof s)return[e.tst];throw new t("params.tst has wrong value")}if(null!=e.res){var r,i=e.res;if(i instanceof s&&(i=i.tohex()),"string"!=typeof i||!n(i))throw new t("params.res has wrong value");return ASN1HEX.getTLVbyList(i,0,[1]),(r=new s).hTLV=e.tst,[r]}},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.SignatureTimeStamp,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.CompleteCertificateRefs=function(e){var t=Error,r=KJUR,n=r.asn1,i=n.DERSequence,s=n.cades,o=s.OtherCertID,a=r.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,r=[],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(!a(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 d=new o(s);r.push(d)}return[new i({array:r})]},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.CompleteCertificateRefs,KJUR.asn1.cms.Attribute),KJUR.asn1.cades.OtherCertID=function(e){var t=KJUR.asn1,r=t.DERSequence,n=t.cms.IssuerSerial,i=t.cades,s=i.OtherHashValue,o=i.OtherHashAlgAndValue;i.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=[],i=null;if(i=null!=e.alg?new o(e):new s(e),t.push(i),null!=e.cert&&1==e.hasis||null!=e.issuer&&null!=e.serial){var a=new n(e);t.push(a)}return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherCertID,KJUR.asn1.ASN1Object),KJUR.asn1.cades.OtherHash=function(e){var t=KJUR,r=t.asn1;r.cms;var n=r.cades,i=n.OtherHashAlgAndValue,s=n.OtherHashValue;t.crypto.Util.hashHex;var o=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}:o(e)&&(e={hash:e}));return(null!=e.alg?new i(e):new s(e)).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.cades.OtherHash,KJUR.asn1.ASN1Object),KJUR.asn1.cades.CAdESUtil=new function(){},KJUR.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned=function(e){return(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e)},KJUR.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned=function(e,t,r){var n=ASN1HEX,i=n.getChildIdx,s=n.getTLV,o=n.getV,a=KJUR.asn1,d=a.ASN1Object,c=a.cms,l=c.AttributeList,u=c.SignerInfo,h={},g=i(e,t);if(6!=g.length)throw"not supported items for SignerInfo (!=6)";var p=g.shift();h.version=s(e,p);var m=g.shift();h.si=s(e,m);var f=g.shift();h.digalg=s(e,f);var S=g.shift();h.sattrs=s(e,S);var y=g.shift();h.sigalg=s(e,y);var b=g.shift();h.sig=s(e,b),h.sigval=o(e,b);var E=null;return h.obj=new u,(E=new d).hTLV=h.version,h.obj.dCMSVersion=E,(E=new d).hTLV=h.si,h.obj.dSignerIdentifier=E,(E=new d).hTLV=h.digalg,h.obj.dDigestAlgorithm=E,(E=new d).hTLV=h.sattrs,h.obj.dSignedAttrs=E,(E=new d).hTLV=h.sigalg,h.obj.dSigAlg=E,(E=new d).hTLV=h.sig,h.obj.dSig=E,h.obj.dUnsignedAttrs=new l,h},void 0!==KJUR.asn1.csr&&KJUR.asn1.csr||(KJUR.asn1.csr={}),KJUR.asn1.csr.CertificationRequest=function(e){var t=KJUR.asn1,r=t.DERBitString,n=t.DERSequence,i=t.csr;t.x509;var s=i.CertificationRequestInfo;i.CertificationRequest.superclass.constructor.call(this),this.setByParam=function(e){this.params=e},this.sign=function(){var e=new s(this.params).tohex(),t=new KJUR.crypto.Signature({alg:this.params.sigalg});t.init(this.params.sbjprvkey),t.updateHex(e);var r=t.sign();this.params.sighex=r},this.getPEM=function(){return hextopem(this.tohex(),"CERTIFICATE REQUEST")},this.tohex=function(){var e=this.params,t=new KJUR.asn1.csr.CertificationRequestInfo(this.params),i=new KJUR.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 r({hex:"00"+e.sighex});return new n({array:[t,i,s]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.csr.CertificationRequest,KJUR.asn1.ASN1Object),KJUR.asn1.csr.CertificationRequestInfo=function(e){var t=KJUR.asn1;t.DERBitString;var r=t.DERSequence,n=t.DERInteger,i=t.DERUTF8String,s=t.DERTaggedObject,o=t.ASN1Util.newObject,a=t.csr,d=t.x509,c=d.X500Name,l=d.Extensions,u=d.SubjectPublicKeyInfo;a.AttributeList,a.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 c(e.subject)),t.push(new u(KEYUTIL.getKey(e.sbjpubkey))),null!=e.attrs){var a=function(e){for(var t=Error,r=KJUR.asn1.x509.Extensions,n=[],i=0;i<e.length;i++){var s=e[i],o=s.attr;if("extensionRequest"==o){var a={seq:[{oid:"1.2.840.113549.1.9.14"},{set:[new r(s.ext)]}]};n.push(a)}else if("unstructuredName"==o){a={seq:[{oid:"1.2.840.113549.1.9.2"},{set:s.names}]};n.push(a)}else{if("challengePassword"!=o)throw new t("unknown CSR attribute");a={seq:[{oid:"1.2.840.113549.1.9.7"},{set:[{utf8str:s.password}]}]};n.push(a)}}return{set:n}}(e.attrs),d=o({tag:{tage:"a0",obj:a}});t.push(d)}else if(null!=e.extreq){var h=new l(e.extreq);d=o({tag:{tage:"a0",obj:{seq:[{oid:"1.2.840.113549.1.9.14"},{set:[h]}]}}});t.push(d)}else t.push(new s({tag:"a0",explicit:!1,obj:new i({str:""})}));return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.csr.CertificationRequestInfo,KJUR.asn1.ASN1Object),KJUR.asn1.csr.AttributeList=function(e){},extendClass(KJUR.asn1.csr.AttributeList,KJUR.asn1.ASN1Object),KJUR.asn1.csr.CSRUtil=new function(){},KJUR.asn1.csr.CSRUtil.newCSRPEM=function(e){return new KJUR.asn1.csr.CertificationRequest(e).getPEM()},KJUR.asn1.csr.CSRUtil.getParam=function(e,t){var r=ASN1HEX,n=r.getV,i=r.getIdxbyList,s=r.getTLVbyList,o=r.getTLVbyListEx,a=r.getVbyListEx,d={};if(-1==e.indexOf("-----BEGIN CERTIFICATE REQUEST"))throw new Error("argument is not PEM file");var c=pemtohex(e,"CERTIFICATE REQUEST");t&&(d.tbs=s(c,0,[0]));try{var l=o(c,0,[0,1]);if("3000"==l)d.subject={};else{var u=new X509;d.subject=u.getX500Name(l)}}catch(e){}var h=o(c,0,[0,2]),g=KEYUTIL.getKey(h,null,"pkcs8pub");d.sbjpubkey=KEYUTIL.getPEM(g,"PKCS8PUB");var p=function(e){var t=i(e,0,[0,3,0,0],"06");return"2a864886f70d01090e"!=n(e,t)?null:s(e,0,[0,3,0,1,0],"30")}(c);u=new X509;null!=p&&(d.extreq=u.getExtParamArray(p));try{var m=o(c,0,[1],"30");u=new X509;d.sigalg=u.getAlgorithmIdentifierName(m)}catch(e){}try{var f=a(c,0,[2]);d.sighex=f}catch(e){}return d},KJUR.asn1.csr.CSRUtil.verifySignature=function(e){try{var t=null;if("string"==typeof e&&-1!=e.indexOf("-----BEGIN CERTIFICATE REQUEST")?t=KJUR.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 r=new KJUR.crypto.Signature({alg:t.sigalg});return r.init(t.sbjpubkey),r.updateHex(t.tbs),r.verify(t.sighex)}catch(e){return alert(e),!1}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),void 0!==KJUR.asn1.ocsp&&KJUR.asn1.ocsp||(KJUR.asn1.ocsp={}),KJUR.asn1.ocsp.DEFAULT_HASH="sha1",KJUR.asn1.ocsp.OCSPResponse=function(e){KJUR.asn1.ocsp.OCSPResponse.superclass.constructor.call(this),KJUR.asn1.DEREnumerated;var t=KJUR.asn1.ASN1Util.newObject,r=KJUR.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 i=new r(e);return t({seq:[{enum:{int:0}},{tag:{tag:"a0",explicit:!0,obj:i}}]}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.OCSPResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponseBytes=function(e){KJUR.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERObjectIdentifier,i=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),o=[];return o.push(new n({name:"ocspBasic"})),o.push(new i({hex:t.tohex()})),new r({array:o}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponseBytes,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.BasicOCSPResponse=function(e){KJUR.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);var t=Error,r=KJUR.asn1,n=r.ASN1Object,i=r.DERSequence;r.DERGeneralizedTime;var s=r.DERTaggedObject,o=r.DERBitString;r.x509.Extensions;var a=r.x509.AlgorithmIdentifier,d=r.ocsp;d.ResponderID,_SingleResponseList=d.SingleResponseList,_ResponseData=d.ResponseData,this.params=null,this.setByParam=function(e){this.params=e},this.sign=function(){var e=this.params,t=e.tbsresp.tohex(),r=new KJUR.crypto.Signature({alg:e.sigalg});r.init(e.reskey),r.updateHex(t),e.sighex=r.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 r=[];if(r.push(e.tbsresp),r.push(new a({name:e.sigalg})),r.push(new o({hex:"00"+e.sighex})),null!=e.certs&&null!=e.certs.length){for(var d=[],c=0;c<e.certs.length;c++){var l=e.certs[c],u=null;if(ASN1HEX.isASN1HEX(l))u=l;else{if(!l.match(/-----BEGIN/))throw new t("certs["+c+"] not hex or PEM");u=pemtohex(l)}d.push(new n({tlv:u}))}var h=new i({array:d});r.push(new s({tag:"a0",explicit:!0,obj:h}))}return new i({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.BasicOCSPResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponseData=function(e){KJUR.asn1.ocsp.ResponseData.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.DERGeneralizedTime,i=t.DERTaggedObject,s=t.x509.Extensions,o=t.ocsp,a=o.ResponderID;_SingleResponseList=o.SingleResponseList,this.params=null,this.tohex=function(){var e=this.params;e.respid,e.prodat,e.array;var t=[];if(t.push(new a(e.respid)),t.push(new n(e.prodat)),t.push(new _SingleResponseList(e.array)),null!=e.ext){var o=new s(e.ext);t.push(new i({tag:"a1",explicit:!0,obj:o}))}return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponseData,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.ResponderID=function(e){KJUR.asn1.ocsp.ResponderID.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.ASN1Util.newObject,i=r.x509.X500Name,s=t.lang.String.isHex,o=Error;this.params=null,this.tohex=function(){var e=this.params;if(null!=e.key){var t,r=null;if("string"==typeof e.key){if(s(e.key)&&(r=e.key),e.key.match(/-----BEGIN CERTIFICATE/))null!=(t=new X509(e.key).getExtSubjectKeyIdentifier())&&(r=t.kid.hex)}else if(e.key instanceof X509)null!=(t=e.key.getExtSubjectKeyIdentifier())&&(r=t.kid.hex);if(null==r)throw new o("wrong key member value");return n({tag:{tag:"a2",explicit:!0,obj:{octstr:{hex:r}}}}).tohex()}if(null!=e.name){var a=null;if("string"==typeof e.name&&e.name.match(/-----BEGIN CERTIFICATE/))a=new X509(e.name).getSubject();else e.name instanceof X509?a=e.name.getSubject():"object"!=typeof e.name||null==e.name.array&&null==e.name.str||(a=e.name);if(null==a)throw new o("wrong name member value");return n({tag:{tag:"a1",explicit:!0,obj:new i(a)}}).tohex()}throw new o("key or name not specified")},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.ResponderID,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.SingleResponseList=function(e){KJUR.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);var t=KJUR.asn1,r=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=[],i=0;i<e.length;i++)t.push(new n(e[i]));return new r({array:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.SingleResponseList,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.SingleResponse=function(e){var t=Error,r=KJUR.asn1,n=r.DERSequence,i=r.DERGeneralizedTime,s=r.DERTaggedObject,o=r.ocsp,a=o.CertID,d=o.CertStatus,c=r.x509.Extensions;o.SingleResponse.superclass.constructor.call(this),this.params=null,this.tohex=function(){var e=this.params,r=[];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(r.push(new a(e.certid)),r.push(new d(e.status)),r.push(new i(e.thisupdate)),null!=e.nextupdate){var o=new i(e.nextupdate);r.push(new s({tag:"a0",explicit:!0,obj:o}))}if(null!=e.ext){var l=new c(e.ext);r.push(new s({tag:"a1",explicit:!0,obj:l}))}return new n({array:r}).tohex()},this.getEncodedHex=function(){return this.tohex()},this.setByParam=function(e){this.params=e},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.SingleResponse,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.CertID=function(e){var t=KJUR,r=t.asn1,n=r.DEROctetString,i=r.DERInteger,s=r.DERSequence,o=r.x509.AlgorithmIdentifier,a=r.ocsp;a.DEFAULT_HASH;var d=t.crypto.Util.hashHex,c=X509,l=ASN1HEX.getVbyList;a.CertID.superclass.constructor.call(this),this.DEFAULT_HASH="sha1",this.params=null,this.setByValue=function(e,t,r,n){null==n&&(n=this.DEFAULT_HASH),this.params={alg:n,issname:e,isskey:t,sbjsn:r}},this.setByCert=function(e,t,r){null==r&&(r=this.DEFAULT_HASH),this.params={alg:r,issuerCert:e,subjectCert:t}},this.getParamByCerts=function(e,t,r){null==r&&(r=this.DEFAULT_HASH);var n=new c(e),i=new c(t),s=d(n.getSubjectHex(),r),o=n.getPublicKeyHex();return{alg:r,issname:s,isskey:d(l(o,0,[1],"03",!0),r),sbjsn:i.getSerialNumberHex()}},this.tohex=function(){if("object"!=typeof this.params)throw new Error("params not set");var e,t,r,a,d=this.params;if(a=null==d.alg?this.DEFAULT_HASH:d.alg,null!=d.issuerCert&&null!=d.subjectCert){var c=this.getParamByCerts(d.issuerCert,d.subjectCert,a);e=c.issname,t=c.isskey,r=c.sbjsn}else{if(null==d.issname||null==d.isskey||null==d.sbjsn)throw new Error("required param members not defined");e=d.issname,t=d.isskey,r=d.sbjsn}var l=new o({name:a}),u=new n({hex:e}),h=new n({hex:t}),g=new i({hex:r}),p=new s({array:[l,u,h,g]});return this.hTLV=p.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.ocsp.CertID,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.CertStatus=function(e){KJUR.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 r={tag:"a1",explicit:!1,obj:{seq:t}};return KJUR.asn1.ASN1Util.newObject({tag:r}).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)},extendClass(KJUR.asn1.ocsp.CertStatus,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.Request=function(e){var t=KJUR.asn1,r=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 r({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e){var i=new n.CertID(e);this.dReqCert=i}},extendClass(KJUR.asn1.ocsp.Request,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.TBSRequest=function(e){var t=KJUR.asn1,r=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=[],r=0;r<e.length;r++){var i=new n.Request(e[0]);t.push(i)}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 r({array:this.dRequestList});if(e.push(t),null!==this.dRequestExt)throw"requestExtensions not supported";var n=new r({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)},extendClass(KJUR.asn1.ocsp.TBSRequest,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.OCSPRequest=function(e){var t=KJUR.asn1,r=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 r({array:e});return this.hTLV=t.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&void 0!==e.reqList){var i=new n.TBSRequest(e);this.dTbsRequest=i}},extendClass(KJUR.asn1.ocsp.OCSPRequest,KJUR.asn1.ASN1Object),KJUR.asn1.ocsp.OCSPUtil={},KJUR.asn1.ocsp.OCSPUtil.getRequestHex=function(e,t,r){var n=KJUR.asn1.ocsp;void 0===r&&(r=n.DEFAULT_HASH);var i={alg:r,issuerCert:e,subjectCert:t};return new n.OCSPRequest({reqList:[i]}).tohex()},KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo=function(e){var t=ASN1HEX,r=t.getVbyList,n=t.getVbyListEx,i=t.getIdxbyList;t.getIdxbyListEx;var s=t.getV,o={};try{var a=n(e,0,[0],"0a");o.responseStatus=parseInt(a,16)}catch(e){}if(0!==o.responseStatus)return o;try{var d=i(e,0,[1,0,1,0,0,2,0,1]);"80"===e.substr(d,2)?o.certStatus="good":"a1"===e.substr(d,2)?(o.certStatus="revoked",o.revocationTime=hextoutf8(r(e,d,[0]))):"82"===e.substr(d,2)&&(o.certStatus="unknown")}catch(e){}try{var c=i(e,0,[1,0,1,0,0,2,0,2]);o.thisUpdate=hextoutf8(s(e,c))}catch(e){}try{var l=i(e,0,[1,0,1,0,0,2,0,3]);"a0"===e.substr(l,2)&&(o.nextUpdate=hextoutf8(r(e,l,[0])))}catch(e){}return o},KJUR.asn1.ocsp.OCSPParser=function(){var e=Error,t=X509,r=new t,n=ASN1HEX,i=n.getV,s=n.getTLV,o=n.getIdxbyList,a=n.getVbyList,d=n.getTLVbyList,c=n.getVbyListEx,l=n.getTLVbyListEx,u=n.getChildIdx;this.getOCSPRequest=function(t){var r=u(t,0);if(1!=r.length&&2!=r.length)throw new e("wrong number elements: "+r.length);return this.getTBSRequest(s(t,r[0]))},this.getTBSRequest=function(e){var t={},n=l(e,0,[0],"30");t.array=this.getRequestList(n);var i=l(e,0,["[2]",0],"30");return null!=i&&(t.ext=r.getExtParamArray(i)),t},this.getRequestList=function(e){for(var t=[],r=u(e,0),n=0;n<r.length;n++){e=s(e,r[n]);t.push(this.getRequest(e))}return t},this.getRequest=function(t){var n=u(t,0);if(1!=n.length&&2!=n.length)throw new e("wrong number elements: "+n.length);var i=this.getCertID(s(t,n[0]));if(2==n.length){var a=o(t,0,[1,0]);i.ext=r.getExtParamArray(s(t,a))}return i},this.getCertID=function(r){var n=u(r,0);if(4!=n.length)throw new e("wrong number elements: "+n.length);var o=new t,a={};return a.alg=o.getAlgorithmIdentifierName(s(r,n[0])),a.issname=i(r,n[1]),a.isskey=i(r,n[2]),a.sbjsn=i(r,n[3]),a},this.getOCSPResponse=function(e){var t,r=u(e,0),n=i(e,r[0]),s=parseInt(n);if(1==r.length)return{resstatus:s};var o=d(e,0,[1,0]);return(t=this.getResponseBytes(o)).resstatus=s,t},this.getResponseBytes=function(e){var t,r=u(e,0),n=d(e,0,[1,0]);t=this.getBasicOCSPResponse(n);var s=i(e,r[0]);return t.restype=KJUR.asn1.x509.OID.oid2name(hextooid(s)),t},this.getBasicOCSPResponse=function(e){var t,r=u(e,0);t=this.getResponseData(s(e,r[0]));var n=new X509;t.alg=n.getAlgorithmIdentifierName(s(e,r[1]));var o=i(e,r[2]);t.sighex=o.substr(2);var a=c(e,0,["[0]"]);if(null!=a){for(var d=u(a,0),l=[],h=0;h<d.length;h++){var g=s(a,d[h]);l.push(g)}t.certs=l}return t},this.getResponseData=function(e){var t=u(e,0),r=t.length,n={},o=0;"a0"==e.substr(t[0],2)&&o++,n.respid=this.getResponderID(s(e,t[o++]));var a=i(e,t[o++]);if(n.prodat=hextoutf8(a),n.array=this.getSingleResponseList(s(e,t[o++])),"a1"==e.substr(t[r-1],2)){var c=d(e,t[r-1],[0]),l=new X509;n.ext=l.getExtParamArray(c)}return n},this.getResponderID=function(e){var t={};if("a2"==e.substr(0,2)){var r=a(e,0,[0]);t.key=r}if("a1"==e.substr(0,2)){var n=d(e,0,[0]),i=new X509;t.name=i.getX500Name(n)}return t},this.getSingleResponseList=function(e){for(var t=u(e,0),r=[],n=0;n<t.length;n++){var i=this.getSingleResponse(s(e,t[n]));r.push(i)}return r},this.getSingleResponse=function(e){var t=u(e,0),r={},n=this.getCertID(s(e,t[0]));r.certid=n;var o=this.getCertStatus(s(e,t[1]));if(r.status=o,"18"==e.substr(t[2],2)){var c=i(e,t[2]);r.thisupdate=hextoutf8(c)}for(var l=3;l<t.length;l++){if("a0"==e.substr(t[l],2)){var h=a(e,t[l],[0],"18");r.nextupdate=hextoutf8(h)}if("a1"==e.substr(t[l],2)){var g=new X509,p=d(e,0,[l,0]);r.ext=g.getExtParamArray(p)}}return r},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 r=hextoutf8(a(e,0,[0]));t.time=r}return t}},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.lang&&KJUR.lang||(KJUR.lang={}),KJUR.lang.String=function(){},"function"==typeof Buffer?(utf8tob64u=function(e){return b64tob64u(Buffer.from(e,"utf8").toString("base64"))},b64utoutf8=function(e){return Buffer.from(b64utob64(e),"base64").toString("utf8")}):(utf8tob64u=function(e){return hextob64u(uricmptohex(encodeURIComponentAll(e)))},b64utoutf8=function(e){return decodeURIComponent(hextouricmp(b64utohex(e)))}),KJUR.lang.String.isInteger=function(e){return!!e.match(/^[0-9]+$/)||!!e.match(/^-[0-9]+$/)},KJUR.lang.String.isHex=function(e){return ishex(e)},KJUR.lang.String.isBase64=function(e){return!(!(e=e.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||e.length%4!=0)},KJUR.lang.String.isBase64URL=function(e){return!e.match(/[+/=]/)&&(e=b64utob64(e),KJUR.lang.String.isBase64(e))},KJUR.lang.String.isIntegerArray=function(e){return!!(e=e.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},KJUR.lang.String.isPrintable=function(e){return null!==e.match(/^[0-9A-Za-z '()+,-./:=?]*$/)},KJUR.lang.String.isIA5=function(e){return null!==e.match(/^[\x20-\x21\x23-\x7f]*$/)},KJUR.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 strpad=function(e,t,r){return null==r&&(r="0"),e.length>=t?e:new Array(t-e.length+1).join(r)+e};function bitstrtoint(e){if(e.length%2!=0)return-1;if(null==(e=e.toLowerCase()).match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16);if(r>7)return-1;var n=e.substr(2),i=parseInt(n,16).toString(2);"0"==i&&(i="00000000"),i=i.slice(0,0-r);var s=parseInt(i,2);return NaN==s?-1:s}catch(e){return-1}}function bitstrtobinstr(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 r=e.substr(2),n="",i=0;i<r.length;i+=2){var s=r.substr(i,2),o=parseInt(s,16).toString(2);n+=o=("0000000"+o).slice(-8)}return n.substr(0,n.length-t)}catch(e){return null}}function namearraytobinstr(e,t){for(var r=0,n=0;n<e.length;n++)r|=1<<t[e[n]];var i=r.toString(2),s="";for(n=i.length-1;n>=0;n--)s+=i[n];return s}function aryval(e,t,r){if("object"==typeof e){t=String(t).split(".");for(var n=0;n<t.length&&e;n++){var i=t[n];i.match(/^[0-9]+$/)&&(i=parseInt(i)),e=e[i]}return e||!1===e?e:r}}function extendClass(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.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:CryptoJS.algo.MD5,sha1:CryptoJS.algo.SHA1,sha224:CryptoJS.algo.SHA224,sha256:CryptoJS.algo.SHA256,sha384:CryptoJS.algo.SHA384,sha512:CryptoJS.algo.SHA512,ripemd160:CryptoJS.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,r){var n=this.getDigestInfoHex(e,t),i=r/4;if(n.length+22>i)throw"key is too short for SigAlg: keylen="+r+","+t;for(var s="0001",o="00"+n,a="",d=i-4-o.length,c=0;c<d;c+=2)a+="ff";return s+a+o},this.hashString=function(e,t){return new KJUR.crypto.MessageDigest({alg:t}).digestString(e)},this.hashHex=function(e,t){return new KJUR.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 RSAKey||e instanceof KJUR.crypto.DSA||e instanceof KJUR.crypto.ECDSA}},KJUR.crypto.Util.md5=function(e){return new KJUR.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(e)},KJUR.crypto.Util.ripemd160=function(e){return new KJUR.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(e)},KJUR.crypto.Util.SECURERANDOMGEN=new SecureRandom,KJUR.crypto.Util.getRandomHexOfNbytes=function(e){var t=new Array(e);return KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(t),BAtohex(t)},KJUR.crypto.Util.getRandomBigIntegerOfNbytes=function(e){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(e),16)},KJUR.crypto.Util.getRandomHexOfNbits=function(e){var t=e%8,r=new Array((e-t)/8+1);return KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(r),r[0]=(255<<t&255^255)&r[0],BAtohex(r)},KJUR.crypto.Util.getRandomBigIntegerOfNbits=function(e){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(e),16)},KJUR.crypto.Util.getRandomBigIntegerZeroToMax=function(e){for(var t=e.bitLength();;){var r=KJUR.crypto.Util.getRandomBigIntegerOfNbits(t);if(-1!=e.compareTo(r))return r}},KJUR.crypto.Util.getRandomBigIntegerMinToMax=function(e,t){var r=e.compareTo(t);if(1==r)throw"biMin is greater than biMax";if(0==r)return e;var n=t.subtract(e);return KJUR.crypto.Util.getRandomBigIntegerZeroToMax(n).add(e)},KJUR.crypto.MessageDigest=function(e){this.setAlgAndProvider=function(e,t){if(null!==(e=KJUR.crypto.MessageDigest.getCanonicalAlgName(e))&&void 0===t&&(t=KJUR.crypto.Util.DEFAULTPROVIDER[e]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(e)&&"cryptojs"==t){try{this.md=KJUR.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=CryptoJS.enc.Hex.parse(e);this.md.update(t)},this.digest=function(){return this.md.finalize().toString(CryptoJS.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=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},KJUR.crypto.MessageDigest.getCanonicalAlgName=function(e){return"string"==typeof e&&(e=(e=e.toLowerCase()).replace(/-/,"")),e},KJUR.crypto.MessageDigest.getHashLength=function(e){var t=KJUR.crypto.MessageDigest,r=t.getCanonicalAlgName(e);if(void 0===t.HASHLENGTH[r])throw"not supported algorithm: "+e;return t.HASHLENGTH[r]},KJUR.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},KJUR.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=KJUR.crypto.Util.DEFAULTPROVIDER[e]),this.algProv=e+"/"+t;var r=e.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(r)&&"cryptojs"==t){try{var n=KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[r];this.mac=CryptoJS.algo.HMAC.create(n,this.pass)}catch(e){throw"setAlgAndProvider hash alg set fail hashAlg="+r+"/"+e}this.updateString=function(e){this.mac.update(e)},this.updateHex=function(e){var t=CryptoJS.enc.Hex.parse(e);this.mac.update(t)},this.doFinal=function(){return this.mac.finalize().toString(CryptoJS.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=rstrtohex(e)),void(this.pass=CryptoJS.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=utf8tohex(e.utf8)),void 0!==e.rstr&&(t=rstrtohex(e.rstr)),void 0!==e.b64&&(t=b64tohex(e.b64)),void 0!==e.b64u&&(t=b64utohex(e.b64u)),null==t)throw"KJUR.crypto.Mac unsupported password type: "+e;this.pass=CryptoJS.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=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},KJUR.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 r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+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 KJUR.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 r=null;try{r=void 0===t?KEYUTIL.getKey(e):KEYUTIL.getKey(e,t)}catch(e){throw"init failed:"+e}if(!0===r.isPrivate)this.prvKey=r,this.state="SIGN";else{if(!0!==r.isPublic)throw"init failed.:"+r;this.pubKey=r,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!==KJUR.crypto.ECDSA&&(this.prvKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof RSAKey&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof RSAKey&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof KJUR.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof KJUR.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!==KJUR.crypto.ECDSA&&(this.pubKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof RSAKey&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,e,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof RSAKey&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==KJUR.crypto.ECDSA&&this.pubKey instanceof KJUR.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,e);if(void 0!==KJUR.crypto.DSA&&this.pubKey instanceof KJUR.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=KJUR.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=KEYUTIL.getKey(e.prvkeypem);this.init(t)}catch(e){throw"fatal error to load pem private key: "+e}}},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECDSA=function(e){var t=Error,r=BigInteger,n=ECPointFp,i=KJUR.crypto.ECDSA,s=KJUR.crypto.ECParameterDB,o=i.getName,a=ASN1HEX,d=a.getVbyListEx,c=a.isASN1HEX,l=new SecureRandom;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(e){return new r(e.bitLength(),l).mod(e.subtract(r.ONE)).add(r.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 r={};return r.x=e.substr(2,t),r.y=e.substr(2+t),r},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),r=this.ecparams.keycharlen,n=("0000000000"+t.toString(16)).slice(-r);return this.setPrivateKeyHex(n),{ecprvhex:n,ecpubhex:this.generatePublicKeyHex()}},this.generatePublicKeyHex=function(){var e=new r(this.prvKeyHex,16),t=this.ecparams.G.multiply(e),n=t.getX().toBigInteger(),i=t.getY().toBigInteger(),s=this.ecparams.keycharlen,o="04"+("0000000000"+n.toString(16)).slice(-s)+("0000000000"+i.toString(16)).slice(-s);return this.setPublicKeyHex(o),o},this.signWithMessageHash=function(e){return this.signHex(e,this.prvKeyHex)},this.signHex=function(e,t){var n=new r(t,16),s=this.ecparams.n,o=new r(e.substring(0,this.ecparams.keycharlen),16);do{var a=this.getBigRandom(s),d=this.ecparams.G.multiply(a).getX().toBigInteger().mod(s)}while(d.compareTo(r.ZERO)<=0);var c=a.modInverse(s).multiply(o.add(n.multiply(d))).mod(s);return i.biRSSigToASN1Sig(d,c)},this.sign=function(e,t){var n=t,i=this.ecparams.n,s=r.fromByteArrayUnsigned(e);do{var o=this.getBigRandom(i),a=this.ecparams.G.multiply(o).getX().toBigInteger().mod(i)}while(a.compareTo(BigInteger.ZERO)<=0);var d=o.modInverse(i).multiply(s.add(n.multiply(a))).mod(i);return this.serializeSig(a,d)},this.verifyWithMessageHash=function(e,t){return this.verifyHex(e,t,this.pubKeyHex)},this.verifyHex=function(e,t,s){try{var o,a,d=i.parseSigHex(t);o=d.r,a=d.s;var c=n.decodeFromHex(this.ecparams.curve,s),l=new r(e.substring(0,this.ecparams.keycharlen),16);return this.verifyRaw(l,o,a,c)}catch(e){return!1}},this.verify=function(e,t,i){var s,o,a;if(Bitcoin.Util.isArray(t)){var d=this.parseSig(t);s=d.r,o=d.s}else{if("object"!=typeof t||!t.r||!t.s)throw"Invalid value for signature";s=t.r,o=t.s}if(i instanceof ECPointFp)a=i;else{if(!Bitcoin.Util.isArray(i))throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=n.decodeFrom(this.ecparams.curve,i)}var c=r.fromByteArrayUnsigned(e);return this.verifyRaw(c,s,o,a)},this.verifyRaw=function(e,t,n,i){var s=this.ecparams.n,o=this.ecparams.G;if(t.compareTo(r.ONE)<0||t.compareTo(s)>=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(s)>=0)return!1;var a=n.modInverse(s),d=e.multiply(a).mod(s),c=t.multiply(a).mod(s);return o.multiply(d).add(i.multiply(c)).getX().toBigInteger().mod(s).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},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 i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},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:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===c(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=d(e,0,["[0]",0],"06"),r=d(e,0,[1],"04");try{n=d(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=o(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===c(e))throw new t("not ASN.1 hex string");var r,n,i;try{d(e,0,[1,0],"06"),r=d(e,0,[1,1],"06"),n=d(e,0,[2,0,1],"04");try{i=d(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=o(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===c(e))throw new t("not ASN.1 hex string");var r,n;try{d(e,0,[0,0],"06"),r=d(e,0,[0,1],"06"),n=d(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=o(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===c(e))throw new t("not ASN.1 hex string");var n,i;try{n=d(e,0,[0,5,0,1],"06"),i=d(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=o(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},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))},KJUR.crypto.ECDSA.parseSigHex=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new BigInteger(t.r,16),s:new BigInteger(t.s,16)}},KJUR.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=ASN1HEX,r=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 i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var s=i[0],o=i[1];if("02"!=e.substr(s,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(o,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,s),s:n(e,o)}},KJUR.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if(r.length>=130&&r.length<=134){if(r.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"==r.substr(0,2)&&(r=r.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var i=Math.max(r.length,n.length);return(r=("000000"+r).slice(-i))+(n=("000000"+n).slice(-i))}if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.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 r+n},KJUR.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),r=e.substr(e.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new BigInteger(e,16),n=new BigInteger(t,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(r,n)},KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=KJUR.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).tohex()},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new BigInteger(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,s,o,a,d,c,l,u,h,g,p){e[n]={};var m=r(s),f=r(o),S=r(a),y=r(d),b=r(c),E=new ECCurveFp(m,f,S),v=E.decodePointHex("04"+l+u);e[n].name=n,e[n].keylen=i,e[n].keycharlen=2*Math.ceil(i/8),e[n].curve=E,e[n].G=v,e[n].n=y,e[n].h=b,e[n].oid=g,e[n].info=p;for(var _=0;_<h.length;_++)t[h[_]]=n}},KJUR.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),KJUR.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),KJUR.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),KJUR.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),KJUR.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),KJUR.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),KJUR.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),KJUR.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]),void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.DSA=function(){var e=ASN1HEX;e.getVbyList;var t=e.getVbyListEx,r=e.isASN1HEX,n=BigInteger;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,r,n,i){this.isPrivate=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=i},this.setPrivateHex=function(e,t,r,n,i){var s,o,a,d,c;s=new BigInteger(e,16),o=new BigInteger(t,16),a=new BigInteger(r,16),d="string"==typeof n&&n.length>1?new BigInteger(n,16):null,c=new BigInteger(i,16),this.setPrivate(s,o,a,d,c)},this.setPublic=function(e,t,r,n){this.isPublic=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=null},this.setPublicHex=function(e,t,r,n){var i,s,o,a;i=new BigInteger(e,16),s=new BigInteger(t,16),o=new BigInteger(r,16),a=new BigInteger(n,16),this.setPublic(i,s,o,a)},this.signWithMessageHash=function(e){var t=this.p,r=this.q,n=this.g;this.y;var i=this.x,s=KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE),r.subtract(BigInteger.ONE)),o=new BigInteger(e.substr(0,r.bitLength()/4),16),a=n.modPow(s,t).mod(r),d=s.modInverse(r).multiply(o.add(i.multiply(a))).mod(r);return KJUR.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:a}},{int:{bigint:d}}]})},this.verifyWithMessageHash=function(e,t){var r=this.p,n=this.q,i=this.g,s=this.y,o=this.parseASN1Signature(t),a=o[0],d=o[1],c=new BigInteger(e.substr(0,n.bitLength()/4),16);if(BigInteger.ZERO.compareTo(a)>0||a.compareTo(n)>0)throw"invalid DSA signature";if(BigInteger.ZERO.compareTo(d)>=0||d.compareTo(n)>0)throw"invalid DSA signature";var l=d.modInverse(n),u=c.multiply(l).mod(n),h=a.multiply(l).mod(n);return 0==i.modPow(u,r).multiply(s.modPow(h,r)).mod(r).mod(n).compareTo(a)},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,i,s,o,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),i=t(e,0,[2],"02"),s=t(e,0,[3],"02"),o=t(e,0,[4],"02"),a=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,i,s,o,a)},this.readPKCS8PrvKeyHex=function(e){var n,i,s,o;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),i=t(e,0,[1,1,1],"02"),s=t(e,0,[1,1,2],"02"),o=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,i,s,null,o)},this.readPKCS8PubKeyHex=function(e){var n,i,s,o;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),i=t(e,0,[0,1,1],"02"),s=t(e,0,[0,1,2],"02"),o=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,i,s,o)},this.readCertPubKeyHex=function(e,n){var i,s,o,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{i=t(e,0,[0,5,0,1,0],"02"),s=t(e,0,[0,5,0,1,1],"02"),o=t(e,0,[0,5,0,1,2],"02"),a=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(i,s,o,a)}};var KEYUTIL=function(){var e=function(e,r,n){return t(CryptoJS.AES,e,r,n)},t=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),s=CryptoJS.enc.Hex.parse(r),o=CryptoJS.enc.Hex.parse(n),a={};a.key=s,a.iv=o,a.ciphertext=i;var d=e.decrypt(a,s,{iv:o});return CryptoJS.enc.Hex.stringify(d)},r=function(e,t,r){return n(CryptoJS.AES,e,t,r)},n=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),s=CryptoJS.enc.Hex.parse(r),o=CryptoJS.enc.Hex.parse(n),a=e.encrypt(i,s,{iv:o}),d=CryptoJS.enc.Hex.parse(a.toString());return CryptoJS.enc.Base64.stringify(d)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(CryptoJS.TripleDES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(CryptoJS.DES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.DES,e,t,r)},keylen:8,ivlen:8}},s=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,s=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),s=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),s=1);var o=e.indexOf("-----END");if(-1!=i&&-1!=o){var a=e.substring(i+2*s,o-s);a=a.replace(/\s+/g,""),t.data=a}return t},o=function(e,t,r){for(var n=r.substring(0,16),s=CryptoJS.enc.Hex.parse(n),o=CryptoJS.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,d="",c=null;;){var l=CryptoJS.algo.MD5.create();if(null!=c&&l.update(c),l.update(o),l.update(s),c=l.finalize(),(d+=CryptoJS.enc.Hex.stringify(c)).length>=2*a)break}var u={};return u.keyhex=d.substr(0,2*i[e].keylen),u.ivhex=d.substr(2*i[e].keylen,2*i[e].ivlen),u},a=function(e,t,r,n){var s=CryptoJS.enc.Base64.parse(e),o=CryptoJS.enc.Hex.stringify(s);return(0,i[t].proc)(o,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return s(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return o(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=s(e),n=r.cipher,i=r.ivsalt,d=r.data,c=o(n,t,i).keyhex;return a(d,n,c,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,s){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===s||null==s){var d=function(e){var t=CryptoJS.lib.WordArray.random(e);return CryptoJS.enc.Hex.stringify(t)}(i[n].ivlen);s=d.toUpperCase()}var c=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,o(n,r,s).keyhex,s);a="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+s+"\r\n",a+="\r\n",a+=c.replace(/(.{64})/g,"$1\r\n"),a+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},getEncryptedPKCS8PEM:function(e,t,r){return hextopem(this.getEncryptedPKCS8Hex(e,t,r),"ENCRYPTED PRIVATE KEY")},getEncryptedPKCS8Hex:function(e,t,r){var n;(n=null==r||null==r?{}:JSON.parse(JSON.stringify(r))).plain=e,this.initPBES2Param(n),this.encryptPBES2Param(n,t);var i=this.generatePBES2ASN1Param(n);return KJUR.asn1.ASN1Util.newObject(i).tohex()},initPBES2Param:function(e){var t;(null==aryval(e,"encalg")&&(e.encalg="aes256-CBC"),null==aryval(e,"iter")&&(e.iter=2048),null==aryval(e,"prf")&&(e.prf="hmacWithSHA256"),null==aryval(e,"salt")&&(e.salt=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8))),null==aryval(e,"enciv"))&&("des-EDE3-CBC"==e.encalg&&(t=8),"aes128-CBC"==e.encalg&&(t=16),"aes256-CBC"==e.encalg&&(t=16),e.enciv=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(t)))},encryptPBES2Param:function(e,t){var r=KEYUTIL.getDKFromPBES2Param(e,t);try{var n=KJUR.crypto.Cipher.encrypt(e.plain,r,e.encalg,{iv:e.enciv})}catch(t){throw new Error("encrypt error: "+e.plain+" "+r+" "+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:inttohex(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=ASN1HEX,r=t.getChildIdx,n=t.getV,i={},s=r(e,0);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+s.length);i.ciphertext=n(e,s[1]);var o=r(e,s[0]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+o.length);if("2a864886f70d01050d"!=n(e,o[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,o[1]);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var d=r(e,a[1]);if(2!=d.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+d.length);if("2a864886f70d0307"!=n(e,d[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,d[1]);var c=r(e,a[0]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+c.length);if("2a864886f70d01050c"!=n(e,c[0]))throw new Error("this only supports pkcs5PBKDF2");var l=r(e,c[1]);if(l.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+l.length);i.pbkdf2Salt=n(e,l[0]);var u=n(e,l[1]);try{i.pbkdf2Iter=parseInt(u,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+u)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=CryptoJS.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=CryptoJS.PBKDF2(t,r,{keySize:6,iterations:n});return CryptoJS.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=pemtohex(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=KEYUTIL.getPBKDF2KeyHexFromParam(n,t),s={};s.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var o=CryptoJS.enc.Hex.parse(i),a=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV),d=CryptoJS.TripleDES.decrypt(s,o,{iv:a});return CryptoJS.enc.Hex.stringify(d)},parsePBES2:function(e){var t=ASN1HEX.parse(e);if("pkcs5PBES2"!=aryval(t,"seq.0.seq.0.oid")||"pkcs5PBKDF2"!=aryval(t,"seq.0.seq.1.seq.0.seq.0.oid"))throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");var r=aryval(t,"seq.0.seq.1.seq.0.seq.1.seq");if(null==r)throw new Error("PBKDF2 parameter not found");var n=aryval(r,"0.octstr.hex"),i=aryval(r,"1.int.hex"),s=aryval(r,"2.seq.0.oid","hmacWithSHA1"),o=-1;try{o=parseInt(i,16)}catch(e){throw new Error("iter not proper value")}var a=aryval(t,"seq.0.seq.1.seq.1.seq.0.oid"),d=aryval(t,"seq.0.seq.1.seq.1.seq.1.octstr.hex"),c=aryval(t,"seq.1.octstr.hex");if(null==a||null==d||null==c)throw new Error("encalg, enciv or enc is undefined");return{salt:n,iter:o,prf:s,encalg:a,enciv:d,enc:c}},getDKFromPBES2Param:function(e,t){var r={hmacWithSHA1:CryptoJS.algo.SHA1,hmacWithSHA224:CryptoJS.algo.SHA224,hmacWithSHA256:CryptoJS.algo.SHA256,hmacWithSHA384:CryptoJS.algo.SHA384,hmacWithSHA512:CryptoJS.algo.SHA512}[e.prf];if(null==r)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 i=CryptoJS.enc.Hex.parse(e.salt),s=e.iter;try{var o=CryptoJS.PBKDF2(t,i,{keySize:n,iterations:s,hasher:r});return CryptoJS.enc.Hex.stringify(o)}catch(r){throw new Error("PBKDF2 error: "+r+" "+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 r,n=pemtohex(e);try{r=KEYUTIL.parsePBES2(n)}catch(e){throw new Error("malformed PBES2 format: "+e.message)}var i=KEYUTIL.getDKFromPBES2Param(r,t);return KJUR.crypto.Cipher.decrypt(r.enc,i,r.encalg,{iv:r.enciv})},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this.getPlainHexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var s=r(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 o=r(e,s[1]);if(2!=o.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(o[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,o[0]),"06"==e.substr(o[1],2)&&(i.algparam=n(e,o[1])),"04"!=e.substr(s[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,s[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=pemtohex(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new RSAKey;else if("2a8648ce380401"==r.algoid)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new KJUR.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=ASN1HEX.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new RSAKey;else if("2a8648ce380401"===r)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new KJUR.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var s=r(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(i.n=n(e,s[0]),"02"!=e.substr(s[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,s[1]),i},parsePublicPKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null},s=r(e,0);if(2!=s.length)throw new Error("outer DERSequence shall have 2 elements: "+s.length);var o=s[0];if("30"!=e.substr(o,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,o);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(s[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,s[1]).substr(2),i}}}();function _zeroPaddingOfSignature(e,t){for(var r="",n=t/4-e.length,i=0;i<n;i++)r+="0";return r+e}function pss_mgf1_str(e,t,r){for(var n="",i=0;n.length<t;)n+=hextorstr(r(rstrtohex(e+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(e){for(var t in KJUR.crypto.Util.DIGESTINFOHEAD){var r=KJUR.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function X509(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;t.dump;var i,s=t.parse,o=t.getTLV,a=t.getVbyList,d=t.getVbyListEx,c=t.getTLVbyList,l=t.getTLVbyListEx,u=t.getIdxbyList,h=t.getIdxbyListEx,g=t.getVidx,p=t.getInt,m=t.oidname,f=t.hextooidstr,S=pemtohex,y=Error;try{i=KJUR.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=c(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=c(e,0,[0]),r=p(t,0);if(r<0||2<r)throw new Error("malformed version field");return this.version=r+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return d(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 i)if(e===i[t])return t;return m(d(e,0,[0],"06"))},this.getIssuer=function(e,t){return this.getX500Name(this.getIssuerHex(),e,t)},this.getIssuerHex=function(){return c(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 c(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var e=a(this.hex,0,[0,4+this.foffset,0]);return e=e.replace(/(..)/g,"%$1"),e=decodeURIComponent(e)},this.getNotAfter=function(){var e=a(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 c(this.hex,0,[0,6+this.foffset],"30")},this.getSPKIValue=function(){var e=this.getSPKI();return null==e?null:a(e,0,[1],"03",!0)},this.getPublicKeyIdx=function(){return u(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var e=this.getPublicKeyIdx();return u(this.hex,e,[1,0],"30")},this.getPublicKey=function(){return KEYUTIL.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var e=c(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(e)},this.getSignatureValueHex=function(){return a(this.hex,0,[2],"03",!0)},this.verifySignature=function(e){var t=this.getSignatureAlgorithmField(),r=this.getSignatureValueHex(),n=c(this.hex,0,[0],"30"),i=new KJUR.crypto.Signature({alg:t});return i.init(e),i.updateHex(n),i.verify(r)},this.parseExt=function(e){var i,s,o;if(void 0===e){if(o=this.hex,3!==this.version)return-1;i=u(o,0,[0,7,0],"30"),s=r(o,i)}else{o=pemtohex(e);var d=u(o,0,[0,3,0,0],"06");if("2a864886f70d01090e"!=n(o,d))return void(this.aExtInfo=new Array);i=u(o,0,[0,3,0,1,0],"30"),s=r(o,i),this.hex=o}this.aExtInfo=new Array;for(var c=0;c<s.length;c++){var l={critical:!1},h=0;3===r(o,s[c]).length&&(l.critical=!0,h=1),l.oid=t.hextooidstr(a(o,s[c],[0],"06"));var p=u(o,s[c],[1+h]);l.vidx=g(o,p),this.aExtInfo.push(l)}},this.getExtInfo=function(e){var t=this.aExtInfo,r=e;if(e.match(/^[0-9.]+$/)||(r=KJUR.asn1.x509.OID.name2oid(e)),""!==r)for(var n=0;n<t.length;n++)if(t[n].oid===r)return t[n]},this.getCriticalExtV=function(e,t,r){if(null!=t)return[t,r];var n=this.getExtInfo(e);return null==n?[null,null]:[o(this.hex,n.vidx),n.critical]},this.getExtBasicConstraints=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("basicConstraints");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"basicConstraints"};if(t&&(i.critical=!0),"3000"===e)return i;if("30030101ff"===e)return i.cA=!0,i;if("30060101ff02"===e.substr(0,12)){var s=n(e,10),a=parseInt(s,16);return i.cA=!0,i.pathLen=a,i}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 i={extname:"nameConstraints"};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){for(var d=[],c=r(e,s[a]),l=0;l<c.length;l++){var u=o(e,c[l]),h=this.getGeneralSubtree(u);d.push(h)}var g=e.substr(s[a],2);"a0"==g?i.permit=d:"a1"==g&&(i.exclude=d)}return i}},this.getGeneralSubtree=function(e){var t=r(e,0),i=t.length;if(i<1||2<i)throw new Error("wrong num elements");for(var s=this.getGeneralName(o(e,t[0])),a=1;a<i;a++){var d=e.substr(t[a],2),c=n(e,t[a]),l=parseInt(c,16);"80"==d&&(s.min=l),"81"==d&&(s.max=l)}return s},this.getExtKeyUsage=function(e,t){var r=this.getCriticalExtV("keyUsage",e,t);if(e=r[0],t=r[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=o(this.hex,t.vidx)}if(8!=e.length&&10!=e.length)throw new Error("malformed key usage value: "+e);var r="000000000000000"+parseInt(e.substr(6),16).toString(2);return 8==e.length&&(r=r.slice(-8)),10==e.length&&(r=r.slice(-16)),""==(r=r.replace(/0+$/,""))&&(r="0"),r},this.getExtKeyUsageString=function(e){for(var t=this.getExtKeyUsageBin(e),r=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&r.push(X509.KEYUSAGE_NAME[n]);return r.join(",")},this.getExtSubjectKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectKeyIdentifier");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var i={extname:"subjectKeyIdentifier"};t&&(i.critical=!0);var s=n(e,0);return i.kid={hex:s},i},this.getExtAuthorityKeyIdentifier=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("authorityKeyIdentifier");if(void 0===i)return;e=o(this.hex,i.vidx),t=i.critical}var s={extname:"authorityKeyIdentifier"};t&&(s.critical=!0);for(var a=r(e,0),d=0;d<a.length;d++){var c=e.substr(a[d],2);if("80"===c&&(s.kid={hex:n(e,a[d])}),"a1"===c){var l=o(e,a[d]),u=this.getGeneralNames(l);s.issuer=u[0].dn}"82"===c&&(s.sn={hex:n(e,a[d])})}return s},this.getExtExtKeyUsage=function(e,t){if(void 0===e&&void 0===t){var i=this.getExtInfo("extKeyUsage");if(void 0===i)return;e=o(this.hex,i.vidx),t=i.critical}var s={extname:"extKeyUsage",array:[]};t&&(s.critical=!0);for(var a=r(e,0),d=0;d<a.length;d++)s.array.push(m(n(e,a[d])));return s},this.getExtExtKeyUsageName=function(){var e=this.getExtInfo("extKeyUsage");if(void 0===e)return e;var t=new Array,i=o(this.hex,e.vidx);if(""===i)return t;for(var s=r(i,0),a=0;a<s.length;a++)t.push(m(n(i,s[a])));return t},this.getExtSubjectAltName=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.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 r=this.getExtInfo("issuerAltName");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"issuerAltName",array:[]};return t&&(n.critical=!0),n.array=this.getGeneralNames(e),n},this.getGeneralNames=function(e){for(var t=r(e,0),n=[],i=0;i<t.length;i++){var s=this.getGeneralName(o(e,t[i]));void 0!==s&&n.push(s)}return n},this.getGeneralName=function(e){var t=e.substr(0,2),r=n(e,0),i=hextorstr(r);return"81"==t?{rfc822:i}:"82"==t?{dns:i}:"86"==t?{uri:i}:"87"==t?{ip:hextoip(r)}:"a4"==t?{dn:this.getX500Name(r)}:"a0"==t?{other:this.getOtherName(e)}:void 0},this.getExtSubjectAltName2=function(){var e,t,i,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var a=new Array,d=o(this.hex,s.vidx),c=r(d,0),l=0;l<c.length;l++)i=d.substr(c[l],2),e=n(d,c[l]),"81"===i&&(t=hextoutf8(e),a.push(["MAIL",t])),"82"===i&&(t=hextoutf8(e),a.push(["DNS",t])),"84"===i&&(t=X509.hex2dn(e,0),a.push(["DN",t])),"86"===i&&(t=hextoutf8(e),a.push(["URI",t])),"87"===i&&(t=hextoip(e),a.push(["IP",t]));return a},this.getExtCRLDistributionPoints=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("cRLDistributionPoints");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"cRLDistributionPoints",array:[]};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){var d=o(e,s[a]);i.array.push(this.getDistributionPoint(d))}return i},this.getDistributionPoint=function(e){for(var t={},n=r(e,0),i=0;i<n.length;i++){var s=e.substr(n[i],2),a=o(e,n[i]);"a0"==s&&(t.dpname=this.getDistributionPointName(a))}return t},this.getDistributionPointName=function(e){for(var t={},n=r(e,0),i=0;i<n.length;i++){var s=e.substr(n[i],2),a=o(e,n[i]);"a0"==s&&(t.full=this.getGeneralNames(a))}return t},this.getExtCRLDistributionPointsURI=function(){var e=this.getExtCRLDistributionPoints();if(null==e)return e;for(var t=e.array,r=[],n=0;n<t.length;n++)try{null!=t[n].dpname.full[0].uri&&r.push(t[n].dpname.full[0].uri)}catch(e){}return r},this.getExtAIAInfo=function(){var e=this.getExtInfo("authorityInfoAccess");if(void 0===e)return e;for(var t={ocsp:[],caissuer:[]},n=r(this.hex,e.vidx),i=0;i<n.length;i++){var s=a(this.hex,n[i],[0],"06"),o=a(this.hex,n[i],[1],"86");"2b06010505073001"===s&&t.ocsp.push(hextoutf8(o)),"2b06010505073002"===s&&t.caissuer.push(hextoutf8(o))}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=o(this.hex,n.vidx),t=n.critical}var i={extname:"authorityInfoAccess",array:[]};t&&(i.critical=!0);for(var s=r(e,0),c=0;c<s.length;c++){var l=d(e,s[c],[0],"06"),u=hextoutf8(a(e,s[c],[1],"86"));if("2b06010505073001"==l)i.array.push({ocsp:u});else{if("2b06010505073002"!=l)throw new Error("unknown method: "+l);i.array.push({caissuer:u})}}return i},this.getExtCertificatePolicies=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("certificatePolicies");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"certificatePolicies",array:[]};t&&(i.critical=!0);for(var s=r(e,0),a=0;a<s.length;a++){var d=o(e,s[a]),c=this.getPolicyInformation(d);i.array.push(c)}return i},this.getPolicyInformation=function(e){var t={},n=a(e,0,[0],"06");t.policyoid=m(n);var i=h(e,0,[1],"30");if(-1!=i){t.array=[];for(var s=r(e,i),d=0;d<s.length;d++){var c=o(e,s[d]),l=this.getPolicyQualifierInfo(c);t.array.push(l)}}return t},this.getOtherName=function(e){var t={},n=r(e,0),i=a(e,n[0],[],"06"),o=a(e,n[1],[]);return t.oid=m(i),t.value=s(o),t},this.getPolicyQualifierInfo=function(e){var t={},r=a(e,0,[0],"06");if("2b06010505070201"===r){var n=d(e,0,[1],"16");t.cps=hextorstr(n)}else if("2b06010505070202"===r){var i=c(e,0,[1],"30");t.unotice=this.getUserNotice(i)}return t},this.getUserNotice=function(e){var r=null;try{return r=t.parse(e),this._asn1ToUnotice(r)}catch(e){return}},this._asn1ToUnotice=function(e){try{for(var t={},r=aryval(e,"seq"),n=0;n<r.length;n++){var i=this._asn1ToNoticeRef(r[n]);null!=i&&(t.noticeref=i);var s=this.asn1ToDisplayText(r[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={},r=aryval(e,"seq"),n=0;n<r.length;n++){var i=this._asn1ToNoticeNum(r[n]);null!=i&&(t.noticenum=i);var s=this.asn1ToDisplayText(r[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=aryval(e,"seq"),r=[],n=0;n<t.length;n++){var i=t[n];r.push(parseInt(aryval(i,"int.hex"),16))}return r}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=hextorstr(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 r=this.getCriticalExtV("policyMappings",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"policyMappings"};t&&(n.critical=!0);try{for(var i=s(e).seq,o=[],a=0;a<i.length;a++){var d=i[a].seq;o.push([d[0].oid,d[1].oid])}n.array=o}catch(e){throw new y("malformed policyMappings")}return n}},this.getExtPolicyConstraints=function(e,t){var r=this.getCriticalExtV("policyConstraints",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"policyConstraints"};t&&(n.critical=!0);var i=s(e);try{for(var o=i.seq,a=0;a<o.length;a++){var d=o[a].tag;0==d.explicit&&("80"==d.tag&&(n.reqexp=parseInt(d.hex,16)),"81"==d.tag&&(n.inhibit=parseInt(d.hex,16)))}}catch(e){return new y("malformed policyConstraints value")}return n}},this.getExtInhibitAnyPolicy=function(e,t){var r=this.getCriticalExtV("inhibitAnyPolicy",e,t);if(e=r[0],t=r[1],null!=e){var n={extname:"inhibitAnyPolicy"};t&&(n.critical=!0);var i=p(e,0);return-1==i?new y("wrong value"):(n.skip=i,n)}},this.getExtCRLNumber=function(e,t){var r={extname:"cRLNumber"};if(t&&(r.critical=!0),"02"==e.substr(0,2))return r.num={hex:n(e,0)},r;throw new y("hExtV parse error: "+e)},this.getExtCRLReason=function(e,t){var r={extname:"cRLReason"};if(t&&(r.critical=!0),"0a"==e.substr(0,2))return r.code=parseInt(n(e,0),16),r;throw new Error("hExtV parse error: "+e)},this.getExtOcspNonce=function(e,t){var r={extname:"ocspNonce"};t&&(r.critical=!0);var i=n(e,0);return r.hex=i,r},this.getExtOcspNoCheck=function(e,t){var r={extname:"ocspNoCheck"};return t&&(r.critical=!0),r},this.getExtAdobeTimeStamp=function(e,t){if(void 0===e&&void 0===t){var n=this.getExtInfo("adobeTimeStamp");if(void 0===n)return;e=o(this.hex,n.vidx),t=n.critical}var i={extname:"adobeTimeStamp"};t&&(i.critical=!0);var s=r(e,0);if(s.length>1){var a=o(e,s[1]),d=this.getGeneralName(a);null!=d.uri&&(i.uri=d.uri)}if(s.length>2){var c=o(e,s[2]);"0101ff"==c&&(i.reqauth=!0),"010100"==c&&(i.reqauth=!1)}return i},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectDirectoryAttributes");if(void 0===r)return;e=o(this.hex,r.vidx),t=r.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var i=s(e),a=[],d=0;d<i.seq.length;d++){var c=i.seq[d],l=aryval(c,"seq.0.oid"),u=aryval(c,"seq.1.set");if(null==l||null==u)throw"error";a.push({attr:l,array:u})}return n.array=a,n}catch(e){throw new Error("malformed subjectDirectoryAttributes extension value")}};var b=function(e){var t={};try{var r=e.seq[0].oid,n=KJUR.asn1.x509.OID.name2oid(r);t.type=KJUR.asn1.x509.OID.oid2atype(n);var i=e.seq[1];if(null!=i.utf8str)t.ds="utf8",t.value=i.utf8str.str;else if(null!=i.numstr)t.ds="num",t.value=i.numstr.str;else if(null!=i.telstr)t.ds="tel",t.value=i.telstr.str;else if(null!=i.prnstr)t.ds="prn",t.value=i.prnstr.str;else if(null!=i.ia5str)t.ds="ia5",t.value=i.ia5str.str;else if(null!=i.visstr)t.ds="vis",t.value=i.visstr.str;else{if(null==i.bmpstr)throw"error";t.ds="bmp",t.value=i.bmpstr.str}return t}catch(e){throw new Erorr("improper ASN.1 parsed AttrTypeAndValue")}},E=function(e){try{return e.set.map((function(e){return b(e)}))}catch(e){throw new Error("improper ASN.1 parsed RDN: "+e)}};this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n<e.length;n++)for(var i=e[n],s=0;s<i.length;s++)r.push(i[s]);for(n=0;n<r.length;n++){var o=r[n],a=o.ds,d=o.value,c=o.type;if("prn"!=a&&"utf8"!=a&&"ia5"!=a)return"mixed";if("ia5"==a){if("CN"!=c)return"mixed";if(KJUR.lang.String.isMail(d))continue;return"mixed"}if("C"==c){if("prn"==a)continue;return"mixed"}if(null==t)t=a;else if(t!==a)return"mixed"}return null==t?"prn":t},this.getAttrTypeAndValue=function(e){var t=s(e);return b(t)},this.getRDN=function(e){var t=s(e);return E(t)},this.getX500NameArray=function(e){return function(e){try{return e.seq.map((function(e){return E(e)}))}catch(e){throw new Error("improper ASN.1 parsed X500Name: "+e)}}(s(e))},this.getX500Name=function(e,t,r){var n=this.getX500NameArray(e),i={str:this.dnarraytostr(n)};return i.array=n,1==r&&(i.hex=e),1==t&&(i.canon=this.c14nRDNArray(n)),i},this.readCertPEM=function(e){this.readCertHex(S(e))},this.readCertHex=function(e){this.hex=e,this.getVersion();try{u(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=hextopem(this.getPublicKeyHex(),"PUBLIC KEY"),null!=this.aExtInfo&&this.aExtInfo.length>0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=c(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=h(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=r(e,0),i=0;i<n.length;i++){var s=o(e,n[i]),a=this.getExtParam(s);null!=a&&t.push(a)}return t},this.getExtParam=function(e){var t=r(e,0).length;if(2!=t&&3!=t)throw new Error("wrong number elements in Extension: "+t+" "+e);var n=f(a(e,0,[0],"06")),i=!1;3==t&&"0101ff"==c(e,0,[1])&&(i=!0);var o=c(e,0,[t-1,0]),d=void 0;if("2.5.29.14"==n?d=this.getExtSubjectKeyIdentifier(o,i):"2.5.29.15"==n?d=this.getExtKeyUsage(o,i):"2.5.29.17"==n?d=this.getExtSubjectAltName(o,i):"2.5.29.18"==n?d=this.getExtIssuerAltName(o,i):"2.5.29.19"==n?d=this.getExtBasicConstraints(o,i):"2.5.29.30"==n?d=this.getExtNameConstraints(o,i):"2.5.29.31"==n?d=this.getExtCRLDistributionPoints(o,i):"2.5.29.32"==n?d=this.getExtCertificatePolicies(o,i):"2.5.29.33"==n?d=this.getExtPolicyMappings(o,i):"2.5.29.35"==n?d=this.getExtAuthorityKeyIdentifier(o,i):"2.5.29.36"==n?d=this.getExtPolicyConstraints(o,i):"2.5.29.37"==n?d=this.getExtExtKeyUsage(o,i):"2.5.29.54"==n?d=this.getExtInhibitAnyPolicy(o,i):"1.3.6.1.5.5.7.1.1"==n?d=this.getExtAuthorityInfoAccess(o,i):"2.5.29.20"==n?d=this.getExtCRLNumber(o,i):"2.5.29.21"==n?d=this.getExtCRLReason(o,i):"2.5.29.9"==n?d=this.getExtSubjectDirectoryAttributes(o,i):"1.3.6.1.5.5.7.48.1.2"==n?d=this.getExtOcspNonce(o,i):"1.3.6.1.5.5.7.48.1.5"==n?d=this.getExtOcspNoCheck(o,i):"1.2.840.113583.1.1.9.1"==n?d=this.getExtAdobeTimeStamp(o,i):null!=X509.EXT_PARSER[n]&&(d=X509.EXT_PARSER[n](n,i,o)),null!=d)return d;var l={extname:n,extn:o};try{l.extn=s(o)}catch(e){}return i&&(l.critical=!0),l},this.findExt=function(e,t){for(var r=0;r<e.length;r++)if(e[r].extname==t)return e[r];return null},this.updateExtCDPFullURI=function(e,t){var r=this.findExt(e,"cRLDistributionPoints");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)if(null!=n[i].dpname&&null!=n[i].dpname.full)for(var s=n[i].dpname.full,o=0;o<s.length;o++){var a=s[i];null!=a.uri&&(a.uri=t)}},this.updateExtAIAOCSP=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].ocsp&&(n[i].ocsp=t)},this.updateExtAIACAIssuer=function(e,t){var r=this.findExt(e,"authorityInfoAccess");if(null!=r&&null!=r.array)for(var n=r.array,i=0;i<n.length;i++)null!=n[i].caissuer&&(n[i].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 r=new KJUR.asn1.x509.X500Name({str:e.str}).tohex();t=this.getX500NameArray(r)}else t=e.array;null==e.canon&&(e.canon=this.c14nRDNArray(t))},this.c14nRDNArray=function(e){for(var t=[],r=0;r<e.length;r++){for(var n=e[r],i=[],s=0;s<n.length;s++){var o=n[s],a=o.value;a=(a=(a=(a=a.replace(/^\s*/,"")).replace(/\s*$/,"")).replace(/\s+/g," ")).toLowerCase(),i.push(o.type.toLowerCase()+"="+a)}t.push(i.join("+"))}return"/"+t.join("/")},this.getInfo=function(){var e,t,r,n=function(e){for(var t="",r=" ",n="\n",i=e.array,s=0;s<i.length;s++){var o=i[s];if(null!=o.dn&&(t+=r+"dn: "+o.dn.str+n),null!=o.ip&&(t+=r+"ip: "+o.ip+n),null!=o.rfc822&&(t+=r+"rfc822: "+o.rfc822+n),null!=o.dns&&(t+=r+"dns: "+o.dns+n),null!=o.uri&&(t+=r+"uri: "+o.uri+n),null!=o.other)t+=r+"other: "+o.other.oid+"="+JSON.stringify(o.other.value).replace(/\"/g,"")+n}return t=t.replace(/\n$/,"")},i=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];if(t+=" policy oid: "+i.policyoid+"\n",void 0!==i.array)for(var s=0;s<i.array.length;s++){var o=i.array[s];void 0!==o.cps&&(t+=" cps: "+o.cps+"\n")}}return t},s=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];try{void 0!==i.dpname.full[0].uri&&(t+=" "+i.dpname.full[0].uri+"\n")}catch(e){}try{void 0!==i.dname.full[0].dn.hex&&(t+=" "+X509.hex2dn(i.dpname.full[0].dn.hex)+"\n")}catch(e){}}return t},o=function(e){for(var t="",r=e.array,n=0;n<r.length;n++){var i=r[n];void 0!==i.caissuer&&(t+=" caissuer: "+i.caissuer+"\n"),void 0!==i.ocsp&&(t+=" ocsp: "+i.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="+hextoposhex(t.n.toString(16)).substr(0,16)+"...\n",e+=" e="+hextoposhex(t.e.toString(16))+"\n"),null!=(r=this.aExtInfo)){e+="X509v3 Extensions:\n";for(var a=0;a<r.length;a++){var d=r[a],c=KJUR.asn1.x509.OID.oid2name(d.oid);""===c&&(c=d.oid);var l="";if(!0===d.critical&&(l="CRITICAL"),e+=" "+c+" "+l+":\n","basicConstraints"===c){var u=this.getExtBasicConstraints();void 0===u.cA?e+=" {}\n":(e+=" cA=true",void 0!==u.pathLen&&(e+=", pathLen="+u.pathLen),e+="\n")}else{var h;if("policyMappings"==c)e+=" "+this.getExtPolicyMappings().array.map((function(e){var t=e;return t[0]+":"+t[1]})).join(", ")+"\n";else if("policyConstraints"==c)e+=" ",null!=(h=this.getExtPolicyConstraints()).reqexp&&(e+=" reqexp="+h.reqexp),null!=h.inhibit&&(e+=" inhibit="+h.inhibit),e+="\n";else if("inhibitAnyPolicy"==c)e+=" skip="+(h=this.getExtInhibitAnyPolicy()).skip+"\n";else if("keyUsage"==c)e+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"==c)e+=" "+this.getExtSubjectKeyIdentifier().kid.hex+"\n";else if("authorityKeyIdentifier"==c){var g=this.getExtAuthorityKeyIdentifier();void 0!==g.kid&&(e+=" kid="+g.kid.hex+"\n")}else{if("extKeyUsage"==c)e+=" "+this.getExtExtKeyUsage().array.join(", ")+"\n";else if("subjectAltName"==c)e+=n(this.getExtSubjectAltName())+"\n";else if("cRLDistributionPoints"==c)e+=s(this.getExtCRLDistributionPoints());else if("authorityInfoAccess"==c)e+=o(this.getExtAuthorityInfoAccess());else"certificatePolicies"==c&&(e+=i(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):KJUR.lang.String.isHex(e)&&this.readCertHex(e))}KEYUTIL.getKey=function(e,t,r){var n=(f=ASN1HEX).getChildIdx;f.getV;var i=f.getVbyList,s=KJUR.crypto,o=s.ECDSA,a=s.DSA,d=RSAKey,c=pemtohex,l=KEYUTIL;if(void 0!==d&&e instanceof d)return e;if(void 0!==o&&e instanceof o)return e;if(void 0!==a&&e instanceof a)return e;if(void 0!==e.curve&&void 0!==e.xy&&void 0===e.d)return new o({pub:e.xy,curve:e.curve});if(void 0!==e.curve&&void 0!==e.d)return new o({prv:e.d,curve:e.curve});if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(A=new d).setPublic(e.n,e.e),A;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(A=new d).setPrivateEx(e.n,e.e,e.d,e.p,e.q,e.dp,e.dq,e.co),A;if(void 0===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d&&void 0===e.p)return(A=new d).setPrivate(e.n,e.e,e.d),A;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0===e.x)return(A=new a).setPublic(e.p,e.q,e.g,e.y),A;if(void 0!==e.p&&void 0!==e.q&&void 0!==e.g&&void 0!==e.y&&void 0!==e.x)return(A=new a).setPrivate(e.p,e.q,e.g,e.y,e.x),A;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0===e.d)return(A=new d).setPublic(b64utohex(e.n),b64utohex(e.e)),A;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(A=new d).setPrivateEx(b64utohex(e.n),b64utohex(e.e),b64utohex(e.d),b64utohex(e.p),b64utohex(e.q),b64utohex(e.dp),b64utohex(e.dq),b64utohex(e.qi)),A;if("RSA"===e.kty&&void 0!==e.n&&void 0!==e.e&&void 0!==e.d)return(A=new d).setPrivate(b64utohex(e.n),b64utohex(e.e),b64utohex(e.d)),A;if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0===e.d){var u=(C=new o({curve:e.crv})).ecparams.keycharlen,h="04"+("0000000000"+b64utohex(e.x)).slice(-u)+("0000000000"+b64utohex(e.y)).slice(-u);return C.setPublicKeyHex(h),C}if("EC"===e.kty&&void 0!==e.crv&&void 0!==e.x&&void 0!==e.y&&void 0!==e.d){u=(C=new o({curve:e.crv})).ecparams.keycharlen,h="04"+("0000000000"+b64utohex(e.x)).slice(-u)+("0000000000"+b64utohex(e.y)).slice(-u);var g=("0000000000"+b64utohex(e.d)).slice(-u);return C.setPublicKeyHex(h),C.setPrivateKeyHex(g),C}if("pkcs5prv"===r){var p,m=e,f=ASN1HEX;if(9===(p=n(m,0)).length)(A=new d).readPKCS5PrvKeyHex(m);else if(6===p.length)(A=new a).readPKCS5PrvKeyHex(m);else{if(!(p.length>2&&"04"===m.substr(p[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(A=new o).readPKCS5PrvKeyHex(m)}return A}if("pkcs8prv"===r)return A=l.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return l._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return X509.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return X509.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var S=pemtohex(e,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(S)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var y=c(e,"RSA PRIVATE KEY");return l.getKey(y,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=i(w=c(e,"DSA PRIVATE KEY"),0,[1],"02"),E=i(w,0,[2],"02"),v=i(w,0,[3],"02"),_=i(w,0,[4],"02"),T=i(w,0,[5],"02");return(A=new a).setPrivate(new BigInteger(b,16),new BigInteger(E,16),new BigInteger(v,16),new BigInteger(_,16),new BigInteger(T,16)),A}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){y=c(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 R=l.getDecryptedKeyHex(e,t),$=new RSAKey;return $.readPKCS5PrvKeyHex(R),$}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var C,A=i(w=l.getDecryptedKeyHex(e,t),0,[1],"04"),N=i(w,0,[2,0],"06"),I=i(w,0,[3,0],"03").substr(2);if(void 0===KJUR.crypto.OID.oidhex2name[N])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+N);return(C=new o({curve:KJUR.crypto.OID.oidhex2name[N]})).setPublicKeyHex(I),C.setPrivateKeyHex(A),C.isPublic=!1,C}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var w;b=i(w=l.getDecryptedKeyHex(e,t),0,[1],"02"),E=i(w,0,[2],"02"),v=i(w,0,[3],"02"),_=i(w,0,[4],"02"),T=i(w,0,[5],"02");return(A=new a).setPrivate(new BigInteger(b,16),new BigInteger(E,16),new BigInteger(v,16),new BigInteger(_,16),new BigInteger(T,16)),A}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return l.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},KEYUTIL.generateKeypair=function(e,t){if("RSA"==e){var r=t;(o=new RSAKey).generate(r,"10001"),o.isPrivate=!0,o.isPublic=!0;var n=new RSAKey,i=o.n.toString(16),s=o.e.toString(16);return n.setPublic(i,s),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}if("EC"==e){var o,a,d=t,c=new KJUR.crypto.ECDSA({curve:d}).generateKeyPairHex();return(o=new KJUR.crypto.ECDSA({curve:d})).setPublicKeyHex(c.ecpubhex),o.setPrivateKeyHex(c.ecprvhex),o.isPrivate=!0,o.isPublic=!1,(n=new KJUR.crypto.ECDSA({curve:d})).setPublicKeyHex(c.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=o,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},KEYUTIL.getPEM=function(e,t,r,n,i,s){var o=KJUR,a=o.asn1,d=a.DERObjectIdentifier,c=a.DERInteger,l=a.ASN1Util.newObject,u=a.x509.SubjectPublicKeyInfo,h=o.crypto,g=h.DSA,p=h.ECDSA,m=RSAKey;function f(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 S(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!==m&&e instanceof m||void 0!==g&&e instanceof g||void 0!==p&&e instanceof p)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return hextopem(_=new u(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==m&&e instanceof m&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(_=f(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var b=new d({name:e.curveName}).tohex(),E=S(e).tohex(),v="";return v+=hextopem(b,"EC PARAMETERS"),v+=hextopem(E,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(_=y(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==m&&e instanceof m&&void 0!==r&&null!=r&&1==e.isPrivate){var _=f(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",_,r,n,s)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate){_=S(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",_,r,n,s)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){_=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",_,r,n,s)}var T=function(e,t){if("string"==typeof t)return KEYUTIL.getEncryptedPKCS8PEM(e,t);if("object"==typeof t&&null!=aryval(t,"passcode")){var r=JSON.parse(JSON.stringify(t)),n=r.passcode;return delete r.passcode,KEYUTIL.getEncryptedPKCS8PEM(e,n,r)}};if("PKCS8PRV"==t&&null!=m&&e instanceof m&&1==e.isPrivate){var R=f(e).tohex();_=l({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:R}}]}).tohex();return void 0===r||null==r?hextopem(_,"PRIVATE KEY"):T(_,r)}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){var $={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&$.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});R=new l($).tohex(),_=l({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:R}}]}).tohex();return void 0===r||null==r?hextopem(_,"PRIVATE KEY"):T(_,r)}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){R=new c({bigint:e.x}).tohex(),_=l({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:R}}]}).tohex();return void 0===r||null==r?hextopem(_,"PRIVATE KEY"):T(_,r)}throw new Error("unsupported object nor format")},KEYUTIL.getKeyFromCSRPEM=function(e){var t=pemtohex(e,"CERTIFICATE REQUEST");return KEYUTIL.getKeyFromCSRHex(t)},KEYUTIL.getKeyFromCSRHex=function(e){var t=KEYUTIL.parseCSRHex(e);return KEYUTIL.getKey(t.p8pubkeyhex,null,"pkcs8pub")},KEYUTIL.parseCSRHex=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getTLV,i={},s=e;if("30"!=s.substr(0,2))throw new Error("malformed CSR(code:001)");var o=r(s,0);if(o.length<1)throw new Error("malformed CSR(code:002)");if("30"!=s.substr(o[0],2))throw new Error("malformed CSR(code:003)");var a=r(s,o[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(s,a[2]),i},KEYUTIL.getKeyID=function(e){var t=KEYUTIL,r=ASN1HEX;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=pemtohex(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),s=r.getV(n,i).substring(2);return KJUR.crypto.Util.hashHex(s,"sha1")},KEYUTIL.getJWK=function(e,t,r,n,i){var s,o,a={},d=KJUR.crypto.Util.hashHex;if("string"==typeof e)s=KEYUTIL.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(o=pemtohex(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof X509?(s=e.getPublicKey(),o=e.hex):s=e}if(s instanceof RSAKey&&s.isPrivate)a.kty="RSA",a.n=hextob64u(s.n.toString(16)),a.e=hextob64u(s.e.toString(16)),a.d=hextob64u(s.d.toString(16)),a.p=hextob64u(s.p.toString(16)),a.q=hextob64u(s.q.toString(16)),a.dp=hextob64u(s.dmp1.toString(16)),a.dq=hextob64u(s.dmq1.toString(16)),a.qi=hextob64u(s.coeff.toString(16));else if(s instanceof RSAKey&&s.isPublic)a.kty="RSA",a.n=hextob64u(s.n.toString(16)),a.e=hextob64u(s.e.toString(16));else if(s instanceof KJUR.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 c=s.getPublicKeyXYHex();a.kty="EC",a.crv=l,a.x=hextob64u(c.x),a.y=hextob64u(c.y),a.d=hextob64u(s.prvKeyHex)}else if(s instanceof KJUR.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);c=s.getPublicKeyXYHex();a.kty="EC",a.crv=l,a.x=hextob64u(c.x),a.y=hextob64u(c.y)}if(null==a.kty)throw new Error("unsupported keyinfo");return s.isPrivate||1==t||(a.kid=KJUR.jws.JWS.getJWKthumbprint(a)),null!=o&&1!=r&&(a.x5c=[hex2b64(o)]),null!=o&&1!=n&&(a.x5t=b64tob64u(hex2b64(d(o,"sha1")))),null!=o&&1!=i&&(a["x5t#S256"]=b64tob64u(hex2b64(d(o,"sha256")))),a},KEYUTIL.getJWKFromKey=function(e){return KEYUTIL.getJWK(e,!0,!0,!0,!0)},RSAKey.getPosArrayOfChildrenFromHex=function(e){return ASN1HEX.getChildIdx(e,0)},RSAKey.getHexValueArrayOfChildrenFromHex=function(e){var t,r=ASN1HEX.getV,n=r(e,(t=RSAKey.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),s=r(e,t[2]),o=r(e,t[3]),a=r(e,t[4]),d=r(e,t[5]),c=r(e,t[6]),l=r(e,t[7]),u=r(e,t[8]);return(t=new Array).push(n,i,s,o,a,d,c,l,u),t},RSAKey.prototype.readPrivateKeyFromPEMString=function(e){var t=pemtohex(e),r=RSAKey.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},RSAKey.prototype.readPKCS5PrvKeyHex=function(e){var t=RSAKey.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},RSAKey.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,s,o,a,d,c=ASN1HEX,l=c.getVbyListEx;if(!1===c.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=l(e,0,[2,0,1],"02"),r=l(e,0,[2,0,2],"02"),n=l(e,0,[2,0,3],"02"),i=l(e,0,[2,0,4],"02"),s=l(e,0,[2,0,5],"02"),o=l(e,0,[2,0,6],"02"),a=l(e,0,[2,0,7],"02"),d=l(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,s,o,a,d)},RSAKey.prototype.readPKCS5PubKeyHex=function(e){var t=ASN1HEX,r=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 i=r(e,n[0]),s=r(e,n[1]);this.setPublic(i,s)},RSAKey.prototype.readPKCS8PubKeyHex=function(e){var t=ASN1HEX;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 r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},RSAKey.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new X509).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},RSAKey.prototype.sign=function(e,t){var r=function(e){return KJUR.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},RSAKey.prototype.signWithMessageHash=function(e,t){var r=parseBigInt(KJUR.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return _zeroPaddingOfSignature(this.doPrivate(r).toString(16),this.n.bitLength())},RSAKey.prototype.signPSS=function(e,t,r){var n=function(e){return KJUR.crypto.Util.hashHex(e,t)}(rstrtohex(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},RSAKey.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=hextorstr(e),s=i.length,o=this.n.bitLength()-1,a=Math.ceil(o/8),d=function(e){return KJUR.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=s;else if(-2===r)r=a-s-2;else if(r<-2)throw new Error("invalid salt length");if(a<s+r+2)throw new Error("data too long");var c="";r>0&&(c=new Array(r),(new SecureRandom).nextBytes(c),c=String.fromCharCode.apply(String,c));var l=hextorstr(d(rstrtohex("\0\0\0\0\0\0\0\0"+i+c))),u=[];for(n=0;n<a-r-s-2;n+=1)u[n]=0;var h=String.fromCharCode.apply(String,u)+""+c,g=pss_mgf1_str(l,h.length,d),p=[];for(n=0;n<h.length;n+=1)p[n]=h.charCodeAt(n)^g.charCodeAt(n);var m=65280>>8*a-o&255;for(p[0]&=~m,n=0;n<s;n++)p.push(l.charCodeAt(n));return p.push(188),_zeroPaddingOfSignature(this.doPrivate(new BigInteger(p)).toString(16),this.n.bitLength())},RSAKey.prototype.verify=function(e,t){if(null==(t=t.toLowerCase()).match(/^[0-9a-f]+$/))return!1;var r=parseBigInt(t,16),n=this.n.bitLength();if(r.bitLength()>n)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var s=_rsasign_getAlgNameAndHashFromHexDisgestInfo(i.replace(/^1f+00/,""));if(0==s.length)return!1;var o=s[0],a=s[1],d=function(e){return KJUR.crypto.Util.hashString(e,o)}(e);return a==d},RSAKey.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=parseBigInt(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=_rsasign_getAlgNameAndHashFromHexDisgestInfo(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},RSAKey.prototype.verifyPSS=function(e,t,r,n){var i,s=(i=rstrtohex(e),KJUR.crypto.Util.hashHex(i,r));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(s,t,r,n)},RSAKey.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,s=new BigInteger(t,16),o=function(e){return KJUR.crypto.Util.hashHex(e,r)},a=hextorstr(e),d=a.length,c=this.n.bitLength()-1,l=Math.ceil(c/8);if(-1===n||void 0===n)n=d;else if(-2===n)n=l-d-2;else if(n<-2)throw new Error("invalid salt length");if(l<d+n+2)throw new Error("data too long");var u=this.doPublic(s).toByteArray();for(i=0;i<u.length;i+=1)u[i]&=255;for(;u.length<l;)u.unshift(0);if(188!==u[l-1])throw new Error("encoded message does not end in 0xbc");var h=(u=String.fromCharCode.apply(String,u)).substr(0,l-d-1),g=u.substr(h.length,d),p=65280>>8*l-c&255;if(0!=(h.charCodeAt(0)&p))throw new Error("bits beyond keysize not zero");var m=pss_mgf1_str(g,h.length,o),f=[];for(i=0;i<h.length;i+=1)f[i]=h.charCodeAt(i)^m.charCodeAt(i);f[0]&=~p;var S=l-d-n-2;for(i=0;i<S;i+=1)if(0!==f[i])throw new Error("leftmost octets not zero");if(1!==f[S])throw new Error("0x01 marker not found");return g===hextorstr(o(rstrtohex("\0\0\0\0\0\0\0\0"+a+String.fromCharCode.apply(String,f.slice(-n)))))},RSAKey.SALT_LEN_HLEN=-1,RSAKey.SALT_LEN_MAX=-2,RSAKey.SALT_LEN_RECOVER=-2,X509.EXT_PARSER={},X509.registExtParser=function(e,t){X509.EXT_PARSER[e]=t},X509.hex2dn=function(e,t){void 0===t&&(t=0);var r=new X509;return ASN1HEX.getTLV(e,t),r.getX500Name(e).str},X509.hex2rdn=function(e,t){if(void 0===t&&(t=0),"31"!==e.substr(t,2))throw new Error("malformed RDN");for(var r=new Array,n=ASN1HEX.getChildIdx(e,t),i=0;i<n.length;i++)r.push(X509.hex2attrTypeValue(e,n[i]));return r=r.map((function(e){return e.replace("+","\\+")})),r.join("+")},X509.hex2attrTypeValue=function(e,t){var r=ASN1HEX,n=r.getV;if(void 0===t&&(t=0),"30"!==e.substr(t,2))throw new Error("malformed attribute type and value");var i=r.getChildIdx(e,t);2!==i.length||e.substr(i[0],2);var s=n(e,i[0]),o=KJUR.asn1.ASN1Util.oidHexToInt(s);return KJUR.asn1.x509.OID.oid2atype(o)+"="+hextorstr(n(e,i[1]))},X509.getPublicKeyFromCertHex=function(e){var t=new X509;return t.readCertHex(e),t.getPublicKey()},X509.getPublicKeyFromCertPEM=function(e){var t=new X509;return t.readCertPEM(e),t.getPublicKey()},X509.getPublicKeyInfoPropOfCertPEM=function(e){var t,r,n=ASN1HEX.getVbyList,i={};return i.algparam=null,(t=new X509).readCertPEM(e),r=t.getPublicKeyHex(),i.keyhex=n(r,0,[1],"03").substr(2),i.algoid=n(r,0,[0,0],"06"),"2a8648ce3d0201"===i.algoid&&(i.algparam=n(r,0,[0,1],"06")),i},X509.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.jws&&KJUR.jws||(KJUR.jws={}),KJUR.jws.JWS=function(){var e=KJUR.jws.JWS.isSafeJSONString;this.parseJWS=function(t,r){if(void 0===this.parsedJWS||!r&&void 0===this.parsedJWS.sigvalH){var n=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==n)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var i=n[1],s=n[2],o=n[3],a=i+"."+s;if(this.parsedJWS={},this.parsedJWS.headB64U=i,this.parsedJWS.payloadB64U=s,this.parsedJWS.sigvalB64U=o,this.parsedJWS.si=a,!r){var d=b64utohex(o),c=parseBigInt(d,16);this.parsedJWS.sigvalH=d,this.parsedJWS.sigvalBI=c}var l=b64utoutf8(i),u=b64utoutf8(s);if(this.parsedJWS.headS=l,this.parsedJWS.payloadS=u,!e(l,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+l}}},KJUR.jws.JWS.sign=function(e,t,r,n,i){var s=KJUR,o=s.jws.JWS,a=o.readSafeJSONString,d=o.isSafeJSONString,c=s.crypto;c.ECDSA;var l,u,h,g=c.Mac,p=c.Signature,m=JSON;if("string"!=typeof t&&"object"!=typeof t)throw"spHeader must be JSON string or object: "+t;if("object"==typeof t&&(u=t,l=m.stringify(u)),"string"==typeof t){if(!d(l=t))throw"JWS Head is not safe JSON string: "+l;u=a(l)}if(h=r,"object"==typeof r&&(h=m.stringify(r)),""!=e&&null!=e||void 0===u.alg||(e=u.alg),""!=e&&null!=e&&void 0===u.alg&&(u.alg=e,l=m.stringify(u)),e!==u.alg)throw"alg and sHeader.alg doesn't match: "+e+"!="+u.alg;var f=null;if(void 0===o.jwsalg2sigalg[e])throw"unsupported alg name: "+e;f=o.jwsalg2sigalg[e];var S=utf8tob64u(l)+"."+utf8tob64u(h),y="";if("Hmac"==f.substr(0,4)){if(void 0===n)throw"mac key shall be specified for HS* alg";var b=new g({alg:f,prov:"cryptojs",pass:n});b.updateString(S),y=b.doFinal()}else if(-1!=f.indexOf("withECDSA")){(v=new p({alg:f})).init(n,i),v.updateString(S);var E=v.sign();y=KJUR.crypto.ECDSA.asn1SigToConcatSig(E)}else{var v;if("none"!=f)(v=new p({alg:f})).init(n,i),v.updateString(S),y=v.sign()}return S+"."+hextob64u(y)},KJUR.jws.JWS.verify=function(e,t,r){var n,i=KJUR,s=i.jws.JWS,o=s.readSafeJSONString,a=i.crypto,d=a.ECDSA,c=a.Mac,l=a.Signature;if(void 0!==typeof RSAKey&&(n=RSAKey),!isBase64URLDot(e))return!1;var u=e.split(".");if(3!==u.length)return!1;var h=u[0]+"."+u[1],g=b64utohex(u[2]),p=o(b64utoutf8(u[0])),m=null,f=null;if(void 0===p.alg)throw"algorithm not specified in header";if((f=(m=p.alg).substr(0,2),null!=r&&"[object Array]"===Object.prototype.toString.call(r)&&r.length>0)&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=KEYUTIL.getKey(t)),!("RS"!=f&&"PS"!=f||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==f&&!(t instanceof d))throw"key shall be a ECDSA obj for ES* algs";var S=null;if(void 0===s.jwsalg2sigalg[p.alg])throw"unsupported alg name: "+m;if("none"==(S=s.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==S.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var y=new c({alg:S,pass:t});return y.updateString(h),g==y.doFinal()}if(-1!=S.indexOf("withECDSA")){var b,E=null;try{E=d.concatSigToASN1Sig(g)}catch(e){return!1}return(b=new l({alg:S})).init(t),b.updateString(h),b.verify(E)}return(b=new l({alg:S})).init(t),b.updateString(h),b.verify(g)},KJUR.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),s={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),s.headerObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(t)),s.payloadObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(r)),s.headerPP=JSON.stringify(s.headerObj,null," "),null==s.payloadObj?s.payloadPP=b64utoutf8(r):s.payloadPP=JSON.stringify(s.payloadObj,null," "),void 0!==n&&(s.sigHex=b64utohex(n)),s},KJUR.jws.JWS.verifyJWT=function(e,t,r){var n=KJUR.jws,i=n.JWS,s=i.readSafeJSONString,o=i.inArray,a=i.includedArray;if(!isBase64URLDot(e))return!1;var d=e.split(".");if(3!=d.length)return!1;var c=d[0],l=d[1];b64utohex(d[2]);var u=s(b64utoutf8(c)),h=s(b64utoutf8(l));if(void 0===u.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!o(u.alg,r.alg))return!1;if(void 0!==h.iss&&"object"==typeof r.iss&&!o(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"==typeof r.sub&&!o(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"==typeof r.aud)if("string"==typeof h.aud){if(!o(h.aud,r.aud))return!1}else if("object"==typeof h.aud&&!a(h.aud,r.aud))return!1;var g=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(g=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriod<g)&&(!(void 0!==h.nbf&&"number"==typeof h.nbf&&g<h.nbf-r.gracePeriod)&&(!(void 0!==h.iat&&"number"==typeof h.iat&&g<h.iat-r.gracePeriod)&&((void 0===h.jti||void 0===r.jti||h.jti===r.jti)&&!!i.verify(e,t,r.alg))))},KJUR.jws.JWS.includedArray=function(e,t){var r=KJUR.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(!r(e[n],t))return!1;return!0},KJUR.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 r=0;r<t.length;r++)if(t[r]==e)return!0;return!1},KJUR.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"},KJUR.jws.JWS.isSafeJSONString=function(e,t,r){var n=null;try{return"object"!=typeof(n=jsonParse(e))||n.constructor===Array?0:(t&&(t[r]=n),1)}catch(e){return 0}},KJUR.jws.JWS.readSafeJSONString=function(e){var t=null;try{return"object"!=typeof(t=jsonParse(e))||t.constructor===Array?null:t}catch(e){return null}},KJUR.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]},KJUR.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 r=rstrtohex(t);return hextob64u(KJUR.crypto.Util.hashHex(r,"sha256"))},KJUR.jws.IntDate={},KJUR.jws.IntDate.get=function(e){var t=KJUR.jws.IntDate,r=t.getNow,n=t.getZulu;if("now"==e)return r();if("now + 1hour"==e)return r()+3600;if("now + 1day"==e)return r()+86400;if("now + 1month"==e)return r()+2592e3;if("now + 1year"==e)return r()+31536e3;if(e.match(/Z$/))return n(e);if(e.match(/^[0-9]+$/))return parseInt(e);throw"unsupported format: "+e},KJUR.jws.IntDate.getZulu=function(e){return zulutosec(e)},KJUR.jws.IntDate.getNow=function(){return~~(new Date/1e3)},KJUR.jws.IntDate.intDate2UTCString=function(e){return new Date(1e3*e).toUTCString()},KJUR.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!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.jws&&KJUR.jws||(KJUR.jws={}),KJUR.jws.JWSJS=function(){var e=KJUR.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,r,n){if(void 0===this.sPayload||null===this.sPayload)throw"there's no JSON-JS signature to add.";var i=this.aHeader.length;if(this.aHeader.length!=this.aSignature.length)throw"aHeader.length != aSignature.length";try{var s=KJUR.jws.JWS.sign(e,t,this.sPayload,r,n).split(".");s[0],s[2];this.aHeader.push(s[0]),this.aSignature.push(s[2])}catch(e){throw this.aHeader.length>i&&this.aHeader.pop(),this.aSignature.length>i&&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 r=e[t];if(2!==r.length)return!1;if(!1===this.verifyNth(t,r[0],r[1]))return!1}return!0},this.verifyNth=function(t,r,n){if(this.aHeader.length<=t||this.aSignature.length<=t)return!1;var i=this.aHeader[t],s=this.aSignature[t],o=i+"."+this.sPayload+"."+s,a=!1;try{a=e.verify(o,r,n)}catch(e){return!1}return a},this.readJWSJS=function(e){if("string"==typeof e){var r=t(e);if(null==r)throw"argument is not safe JSON object string";this.aHeader=r.headers,this.sPayload=r.payload,this.aSignature=r.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}},KJUR.crypto.ECDSA,KJUR.crypto.DSA,KJUR.crypto.Signature,KJUR.crypto.MessageDigest,KJUR.crypto.Mac;var KEYUTIL_1=KEYUTIL,b64utoutf8_1=b64utoutf8,KJUR_1=KJUR;KJUR.crypto,KJUR.asn1,KJUR.jws,KJUR.lang;const swarmPublicKey="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmkXOuNfY8u5xoTiIhkb8\ndjnbIwG/Wrz3vpo8BZir8L5e1a1nSy740qBjP7ZINBQoALDhFfmdOfJnCyEGiHuz\nZW6jbG6C3PryE3Bu6GKwqSmD6k3q4Zk27fpwYAnNl+rWhYYM563rJZBda/INyHNN\npK7M1mixWi7gNdjjXwoEXSSBx+VpYMkY6LiAB2mvHXTY9M1qI14dvgGoQISZQoKi\nNMTRCg5UP2ic0Dd9nSz/XpcOxGfa+0fwIl1F7RC1tJXOqvkGGPTOV4LLfg/Yta3h\nnUPX9EZZDIX6vO/0IBV1LzjSl2A1bYFYAjJfowv3i1CpvONBOClHjSY5t9Y8MH6p\nBwIDAQAB\n-----END PUBLIC KEY-----";var newFrom=(e,t)=>{const r={};return Object.getOwnPropertyNames(e).forEach((t=>{r[t]=e[t]})),new t(r)};class Line{type;id;extensions;endpointCustom;endpointSccp;endpointSip;static parse(e){return new Line({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 newFrom(e,Line)}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:r,endpointSccp:n,endpointSip:i}={}){this.id=e,this.extensions=t,this.endpointCustom=r||null,this.endpointSccp=n||null,this.endpointSip=i||null,this.type="Line"}}const FORWARD_KEYS={BUSY:"busy",NO_ANSWER:"noanswer",UNCONDITIONAL:"unconditional"};class ForwardOption{destination;enabled;key;static parse(e,t){return new ForwardOption({destination:e.destination||"",enabled:e.enabled,key:t})}static newFrom(e){return newFrom(e,ForwardOption)}constructor({destination:e,enabled:t,key:r}={}){this.destination=e,this.enabled=t,this.key=r}setDestination(e){return this.destination=e,this}setEnabled(e){return this.enabled=e,this}is(e){return this.key===e.key}}const STATE={AVAILABLE:"available",UNAVAILABLE:"unavailable",INVISIBLE:"invisible",DISCONNECTED:"disconnected",AWAY:"away"},LINE_STATE={AVAILABLE:"available",HOLDING:"holding",RINGING:"ringing",TALKING:"talking",UNAVAILABLE:"unavailable",PROGRESSING:"progressing"};class Profile{id;firstName;lastName;email;lines;sipLines;username;mobileNumber;forwards;doNotDisturb;onlineCallRecordEnabled;state;ringSeconds;voicemail;status;subscriptionType;agent;switchboards;callPickupTargetUsers;static parse(e){return new Profile({id:e.uuid,firstName:e.firstName||e.firstname||"",lastName:e.lastName||e.lastname||"",email:e.email,lines:e.lines.map((e=>Line.parse(e))),username:e.username,mobileNumber:e.mobile_phone_number||"",ringSeconds:e.ring_seconds,forwards:[ForwardOption.parse(e.forwards.unconditional,FORWARD_KEYS.UNCONDITIONAL),ForwardOption.parse(e.forwards.noanswer,FORWARD_KEYS.NO_ANSWER),ForwardOption.parse(e.forwards.busy,FORWARD_KEYS.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 newFrom(e,Profile)}constructor({id:e,firstName:t,lastName:r,email:n,lines:i,username:s,mobileNumber:o,forwards:a,doNotDisturb:d,state:c,subscriptionType:l,voicemail:u,switchboards:h,agent:g,status:p,ringSeconds:m,sipLines:f,callPickupTargetUsers:S,onlineCallRecordEnabled:y}){this.id=e,this.firstName=t,this.lastName=r,this.email=n,this.lines=i,this.username=s,this.mobileNumber=o,this.forwards=a,this.doNotDisturb=d,this.state=c,this.voicemail=u,this.subscriptionType=l,this.switchboards=h,this.agent=g,this.status=p,this.callPickupTargetUsers=S,this.onlineCallRecordEnabled=y,this.ringSeconds=m,this.sipLines=f||[]}static getLinesState(e){let t=LINE_STATE.UNAVAILABLE;for(const r of e){if(r.state===LINE_STATE.RINGING){t=LINE_STATE.RINGING;break}if(r.state===LINE_STATE.TALKING){t=LINE_STATE.TALKING;break}r.state===LINE_STATE.AVAILABLE&&(t=LINE_STATE.AVAILABLE)}return t}hasId(e){return e===this.id}setMobileNumber(e){return this.mobileNumber=e,this}setForwardOption(e){const t=this.forwards.slice(),r=t.findIndex((t=>t.is(e)));return t.splice(r,1,e),this.forwards=t,this}setDoNotDisturb(e){return this.doNotDisturb=e,this}setState(e){return this.state=e,this}}const BACKEND={OFFICE365:"office365",PERSONAL:"personal",GOOGLE:"google",WAZO:"wazo",CONFERENCE:"conference",PHONEBOOK:"phonebook"},SOURCE_MOBILE="mobile";class Contact{static BACKEND=BACKEND;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 r=e.find((e=>e&&e.is(t)));return r?t.merge(r):t}))}static sortContacts(e,t){const r=e.separateName(),n=t.separateName(),i=r.lastName,s=n.lastName;return i===s?r.firstName.localeCompare(n.firstName):i.localeCompare(s)}static parseMany(e,t=0,r=null){if(!e||!e.results||0===r)return[];return(null!==r&&r>0?e.results.slice(t,r):t>0?e.results.slice(t):e.results).map((t=>Contact.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,r)=>{if(!t.node)return null;const{email:n}=t.node,i=t.node.firstname&&t.node.lastname?`${t.node.firstname||""} ${t.node.lastname||""}`:t.node.wazoReverse;return new Contact({name:i,number:e[r],numbers:[{label:"primary",number:e[r]}],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 r=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)=>r.some((e=>e===t))&&null!==e))}static parse(e,t){const r=Contact.fetchNumbers(e,t),n=e.column_values[t.indexOf("email")];return new Contact({name:e.column_values[t.indexOf("name")],number:r.length?r[0]:"",numbers:r.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=>Contact.parsePersonal(e)))}static parsePersonal(e){return new Contact({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||BACKEND.PERSONAL})}static parseMobile(e){let t="";if(e.postalAddresses.length){const r=e.postalAddresses[0];t=`${r.street} ${r.city} ${r.postCode} ${r.country}`}const r=e.givenName||"",n=e.familyName||"",i=e.company||"";return new Contact({name:!r&&!n?i:`${r} ${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:SOURCE_MOBILE,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=>Contact.parseOffice365(e,t)))}static parseOffice365(e,t){const r=[],n=[];return e.emailAddresses&&e.emailAddresses.map((e=>r.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 Contact({sourceId:e.id||"",name:e.displayName||"",number:n.length?n[0].number:"",numbers:n,emails:r,source:t.name,backend:BACKEND.OFFICE365})}static parseManyGoogle(e,t){return e.map((e=>Contact.parseGoogle(e,t)))}static parseGoogle(e,t){const r=[];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=>r.push({label:t,number:e.numbers_by_label[t]}))):e.numbers&&e.numbers.forEach((e=>r.push({number:e}))),new Contact({sourceId:e.id||"",name:e.name||"",number:r.length?r[0].number:"",numbers:r,emails:[],source:t.name,backend:BACKEND.GOOGLE})}static parseManyWazo(e,t){return e.map((e=>Contact.parseWazo(e,t)))}static parseWazo(e,t){const r=[],n=[];return e.email&&r.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 Contact({uuid:e.uuid,sourceId:String(e.id)||"",name:`${e.firstname}${e.lastname?` ${e.lastname}`:""}`,number:n.length?n[0].number:"",numbers:n,emails:r,source:t.name,backend:BACKEND.WAZO})}static parseManyConference(e,t){return e.map((e=>Contact.parseConference(e,t)))}static parseConference(e,t){const r=[];let n="";return e&&e.extensions&&e.extensions.length>0&&e.extensions[0].exten&&(n=e.extensions[0].exten,r.push({label:"exten",number:n})),new Contact({sourceId:String(e.id),name:e.name,number:n,numbers:r,source:t.name,backend:BACKEND.CONFERENCE})}static newFrom(e){return newFrom(e,Contact)}constructor({id:e,uuid:t,name:r,number:n,numbers:i,email:s,emails:o,source:a,sourceId:d,entreprise:c,birthday:l,address:u,note:h,state:g,lineState:p,lastActivity:m,mobile:f,status:S,endpointId:y,personal:b,favorited:E,backend:v,personalStatus:_,sessions:T,connected:R,doNotDisturb:$,ringing:C,previousPresential:A,lines:N}={}){this.id=e,this.uuid=t,this.name=r||"",this.number=n,this.numbers=i,this.email=s,this.emails=o,this.source=a,this.sourceId=d,this.entreprise=c,this.birthday=l,this.address=u,this.note=h,this.state=g,this.lineState=p,this.lastActivity=m,this.mobile=f,this.status=S,this.endpointId=y,this.personal=b,this.favorited=E,this.backend=v,this.personalStatus=_||"",this.sessions=T||[],this.connected=R,this.doNotDisturb=$,this.ringing=C,this.previousPresential=A,this.lines=N||[],this.type="Contact"}setFavorite(e){return this.favorited=e,this}is(e){const t=null!==this.sourceId&&null!==e.sourceId&&this.sourceId===e.sourceId,r=!!this.uuid&&!!e.uuid&&this.uuid===e.uuid,n=t||r,i=!!this.backend&&!!e.backend&&this.backend===e.backend,s=!!this.source&&!!e.source&&this.source===e.source;return!!e&&n&&i&&s}hasId(e){return this.uuid===e}hasNumber(e){return this.number===e}hasEndpointId(e){return this.endpointId===e}isAvailable(){return this.state===STATE.AVAILABLE}isAway(){return this.state===STATE.AWAY}isUnavailable(){return this.state===STATE.UNAVAILABLE}isInvisible(){return this.state===STATE.INVISIBLE}isInCall(){return this.lineState===LINE_STATE.TALKING||this.lineState===LINE_STATE.HOLDING}isRinging(){return this.ringing}isInUseOrRinging(){return this.lineState===LINE_STATE.TALKING||this.lineState===LINE_STATE.RINGING}isProgressing(){return this.lineState===LINE_STATE.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===SOURCE_MOBILE}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 compareVersions=(e,t)=>{let r,n;const i=/(\.0+)+$/,s=e.replace(i,"").split("."),o=t.replace(i,"").split("."),a=Math.min(s.length,o.length);for(r=0;r<a;r++)if(n=parseInt(s[r],10)-parseInt(o[r],10),n)return n;return s.length-o.length},{jws:jws}=KJUR_1,swarmKey=KEYUTIL_1.getKey(swarmPublicKey),MINIMUM_WAZO_ENGINE_VERSION_FOR_DEFAULT_CONTEXT="19.08";let Session$1=class e{acl;contact;token;refreshToken;uuid;tenantUuid;stackUuid;sessionUuid;engineVersion;_stackHostFromHeader;profile;expiresAt;authorizations;static parse(t){const r=t.data.metadata?t.data.metadata.jwt:null;let n=[];if(r){if(jws.JWS.verifyJWT(r,swarmKey,{alg:["RS256"],verifyAt:new Date})){const e=jws.JWS.readSafeJSONString(b64utoutf8_1(r.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:moment.utc(t.data.utc_expires_at).toDate(),stackUuid:t.data.xivo_uuid,stackHostFromHeader:t._headers?.get?.("wazo-stack-host")})}static newFrom(t){return newFrom(t,e)}constructor({token:e,uuid:t,tenantUuid:r,profile:n,expiresAt:i,authorizations:s,acl:o,engineVersion:a,refreshToken:d,sessionUuid:c,stackUuid:l,stackHostFromHeader:u}){this.token=e,this.uuid=t,this.tenantUuid=r||null,this.profile=n,this.expiresAt=i,this.authorizations=s||[],this.acl=o||[],this.engineVersion=a,this.refreshToken=d,this.sessionUuid=c,this.stackUuid=l,this._stackHostFromHeader=u}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:r,mobileNumber:n,state:i,status:s}=this.profile||{},o=this.primaryNumber()||"",a=[{label:"primary",number:o}];return n&&a.push({label:"mobile",number:n}),new Contact({uuid:this.uuid||"",email:e,name:`${t} ${r}`,number:o,numbers:a,state:i||"",status:s,backend:"wazo",source:"default"})}primaryContext(){if(this.engineVersion&&this.hasEngineVersionGte(MINIMUM_WAZO_ENGINE_VERSION_FOR_DEFAULT_CONTEXT))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&&compareVersions(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 DEFAULT_BACKEND_USER="wazo_user",BACKEND_LDAP_USER="ldap_user",DETAULT_EXPIRATION=3600;var authMethods=(e,t)=>({checkToken:r=>e.head(`${t}/token/${r}`,null,{}),authenticate:r=>e.get(`${t}/token/${r}`,null,{}).then((e=>Session$1.parse(e))),logIn(r){const n={backend:r.backend||DEFAULT_BACKEND_USER,expiration:r.expiration||DETAULT_EXPIRATION},i={Authorization:`Basic ${ApiRequester.base64Encode(`${r.username}:${r.password}`)}`,"Content-Type":"application/json"};return e.clientId&&(n.access_type="offline",n.client_id=e.clientId),r.mobile&&(i["Wazo-Session-Type"]="mobile"),r.tenantId&&(console.warn("Use of `tenantId` is deprecated when calling logIn() method, use `domainName` instead."),n.tenant_id=r.tenantId),r.domainName&&(n.domain_name=r.domainName),e.post(`${t}/token`,n,i).then((e=>Session$1.parse(e)))},logOut:r=>e.delete(`${t}/token/${r}`,null,{},ApiRequester.successResponseParser),refreshToken:(r,n,i,s,o,a)=>{const d={backend:n||DEFAULT_BACKEND_USER,expiration:i||DETAULT_EXPIRATION,refresh_token:r,client_id:e.clientId};o&&(console.warn("Use of `tenantId` is deprecated when calling refreshToken() method, use `domainName` instead."),d.tenant_id=o),a&&(d.domain_name=a);const c={"Content-Type":"application/json",...s?{"Wazo-Session-Type":"mobile"}:{}};return e.post(`${t}/token`,d,c,ApiRequester.defaultParser,!1).then(Session$1.parse)},deleteRefreshToken:r=>e.delete(`${t}/users/me/tokens/${r}`,null,null,ApiRequester.successResponseParser),updatePassword:(r,n,i)=>{const s={new_password:i,old_password:n};return e.put(`${t}/users/${r}/password`,s,null,ApiRequester.successResponseParser)},sendDeviceToken:(r,n,i,s)=>{const o={token:n};return i&&(o.apns_token=i,o.apns_voip_token=i),s&&(o.apns_notification_token=s),e.post(`${t}/users/${r}/external/mobile`,o)},getPushNotificationSenderId:r=>e.get(`${t}/users/${r}/external/mobile/sender_id`,null).then((e=>e.sender_id)),sendResetPasswordEmail:({username:r,email:n})=>{const i={};return r&&(i.username=r),n&&(i.email=n),e.get(`${t}/users/password/reset`,i,{},ApiRequester.successResponseParser)},resetPassword:(r,n)=>{const i={password:n};return e.post(`${t}/users/password/reset?user_uuid=${r}`,i,null,ApiRequester.successResponseParser)},removeDeviceToken:r=>e.delete(`${t}/users/${r}/external/mobile`),createUser:(r,n,i,s)=>{const o={username:r,password:n,firstname:i,lastname:s};return e.post(`${t}/users`,o)},addUserEmail:(r,n,i)=>{const s={emails:[{address:n,main:i}]};return e.put(`${t}/users/${r}/emails`,s)},addUserPolicy:(r,n)=>e.put(`${t}/users/${r}/policies/${n}`),getRestrictionPolicies:r=>e.post(`${t}/token/${e.token}/scopes/check`,{scopes:r}),deleteUserPolicy:(r,n)=>e.delete(`${t}/users/${r}/policies/${n}`),addUserGroup:(r,n)=>e.put(`${t}/groups/${n}/users/${r}`),listUsersGroup:r=>e.get(`${t}/groups/${r}/users`),deleteUserGroup:(r,n)=>e.delete(`${t}/groups/${n}/users/${r}`),getUser:r=>e.get(`${t}/users/${r}`),getUserSession:r=>e.get(`${t}/users/${r}/sessions`),deleteUserSession:(r,n)=>e.delete(`${t}/users/${r}/sessions/${n}`),listUsers:()=>e.get(`${t}/users`),deleteUser:r=>e.delete(`${t}/users/${r}`),listTenants:()=>e.get(`${t}/tenants`),getTenant:r=>e.get(`${t}/tenants/${r}`),createTenant:r=>e.post(`${t}/tenants`,{name:r}),updateTenant:(r,n,i,s,o)=>{const a={name:n,contact:i,phone:s,address:o};return e.put(`${t}/tenants/${r}`,a)},deleteTenant:r=>e.delete(`${t}/tenants/${r}`),createGroup:r=>e.post(`${t}/groups`,{name:r}),listGroups:()=>e.get(`${t}/groups`),deleteGroup:r=>e.delete(`${t}/groups/${r}`),createPolicy:(r,n,i)=>{const s={name:r,description:n,acl_templates:i,acl:i};return e.post(`${t}/policies`,s)},listPolicies:()=>e.get(`${t}/policies`),deletePolicy:r=>e.delete(`${t}/policies/${r}`),getProviders:r=>e.get(`${t}/users/${r}/external`),getProviderToken:(r,n)=>e.get(`${t}/users/${r}/external/${n}`),getProviderAuthUrl:(r,n)=>e.post(`${t}/users/${r}/external/${n}`,{}),deleteProviderToken:(r,n)=>e.delete(`${t}/users/${r}/external/${n}`)}),applicationMethods=(e,t)=>({bridgeCall(r,n,i,s,o,a){const d=`${t}/${r}/nodes`,c={calls:[{id:n}]};return e.post(d,c,null,(e=>e.json().then((e=>e.uuid)))).then((t=>e.post(`${d}/${t}/calls`,{context:i,exten:s,autoanswer:o,displayed_caller_id_number:a}).then((e=>({nodeUuid:t,data:e})))))},answerCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/answer`,{},null,ApiRequester.successResponseParser),calls:r=>e.get(`${t}/${r}/calls`),hangupCall:(r,n)=>e.delete(`${t}/${r}/calls/${n}`),startPlaybackCall:(r,n,i,s)=>e.post(`${t}/${r}/calls/${n}/playbacks`,{language:i,uri:s}),stopPlaybackCall:(r,n)=>e.delete(`${t}/${r}/playbacks/${n}`),startProgressCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/progress/start`,{},null,ApiRequester.successResponseParser),stopProgressCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/progress/stop`,{},null,ApiRequester.successResponseParser),startMohCall:(r,n,i)=>e.put(`${t}/${r}/calls/${n}/moh/${i}/start`,{},null,ApiRequester.successResponseParser),stopMohCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/moh/stop`,{},null,ApiRequester.successResponseParser),startHoldCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/hold/start`,{},null,ApiRequester.successResponseParser),stopHoldCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/hold/stop`,{},null,ApiRequester.successResponseParser),startMuteCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/mute/start`,{},null,ApiRequester.successResponseParser),stopMuteCall:(r,n)=>e.put(`${t}/${r}/calls/${n}/mute/stop`,{},null,ApiRequester.successResponseParser),sendDTMFCall:(r,n,i)=>e.put(`${t}/${r}/calls/${n}/dtmf`,{digits:i},null,ApiRequester.successResponseParser),addCallNodes:(r,n,i)=>e.put(`${t}/${r}/nodes/${n}/calls/${i}`,{},null,ApiRequester.successResponseParser),createNewNodeWithCall:(r,n)=>e.post(`${t}/${r}/nodes`,{calls:n}),addNewCallNodes:(r,n,i,s,o)=>e.post(`${t}/${r}/nodes/${n}/calls`,{context:i,exten:s,autoanswer:o}),listCallsNodes:(r,n)=>e.get(`${t}/${r}/nodes/${n}`),listNodes:r=>e.get(`${t}/${r}/nodes`),removeNode:(r,n)=>e.delete(`${t}/${r}/nodes/${n}`),removeCallNodes:(r,n,i)=>e.delete(`${t}/${r}/nodes/${n}/calls/${i}`),listSnoop:r=>e.get(`${t}/${r}/snoops`),removeSnoop:(r,n)=>e.delete(`${t}/${r}/snoops/${n}`),viewSnoop:(r,n)=>e.get(`${t}/${r}/snoops/${n}`),createSnoop:(r,n,i,s)=>e.post(`${t}/${r}/calls/${n}/snoops`,{snooping_call_id:i,whisper_mode:s}),updateSnoop:(r,n,i)=>e.put(`${t}/${r}/snoops/${n}`,{whisper_mode:i},null,ApiRequester.successResponseParser)});const availableCodecs=["vp8","vp9","h264"];class SipLine{id;uuid;tenantUuid;username;secret;type;host;options;endpointSectionOptions;links;trunk;line;static parse(e){let{username:t,secret:r,host:n}=e;if(e.auth_section_options){const i=(e,t)=>e.find((e=>e[0]===t)),s=i(e.auth_section_options,"username"),o=i(e.auth_section_options,"password"),a=i(e.endpoint_section_options,"media_address");t=s?s[1]:"",r=o?o[1]:"",n=a?a[1]:""}return new SipLine({id:e.id,uuid:e.uuid,tenantUuid:e.tenant_uuid,username:t,secret:r,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 newFrom(e,SipLine)}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=>availableCodecs.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:r,username:n,secret:i,type:s,host:o,options:a,endpointSectionOptions:d,links:c,trunk:l,line:u}){this.id=e,this.uuid=t,this.tenantUuid=r,this.username=n,this.secret=i,this.type=s,this.host=o,this.options=a,this.endpointSectionOptions=d,this.links=c,this.trunk=l,this.line=u,this.type="SipLine"}}class ExternalApp{name;type;configuration;static parse(e){return new ExternalApp({name:e.name,configuration:e.configuration})}static parseMany(e){return e.items.map((e=>ExternalApp.parse(e)))}static newFrom(e){return newFrom(e,ExternalApp)}constructor({name:e,configuration:t}={}){this.name=e,this.configuration=t,this.type="ExternalApp"}}class Meeting{type;guestSipAuthorization;uri;uuid;name;port;extension;persistent;ownerUuids;creationTime;pendingAuthorizations;requireAuthorization;static parse(e){return new Meeting({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:moment(e.creation_time).toDate(),requireAuthorization:e.require_authorization})}static parseMany(e){return e?e.map((e=>Meeting.parse(e))):[]}static newFrom(e){return newFrom(e,Meeting)}constructor({uuid:e,name:t,guestSipAuthorization:r,ownerUuids:n,port:i,uri:s,extension:o,persistent:a,creationTime:d,requireAuthorization:c}={}){this.guestSipAuthorization=r,this.uri=s,this.name=t,this.ownerUuids=n,this.port=i,this.uuid=e,this.extension=o,this.persistent=a,this.creationTime=d,this.requireAuthorization=c,this.type="Meeting"}getGuestSipCredentials(){const[e,t]=Buffer.from(this.guestSipAuthorization,"base64").toString("ascii").split(":");return{username:e,secret:t}}}const PENDING="pending",ACCEPTED$1="accepted",REJECTED$1="rejected",POST_PROCESSING="post_processing",POST_PROCESSED_SUCCESS="post_processed_success",POST_PROCESSED_ERROR="post_processed_error";class MeetingAuthorization{static PENDING=PENDING;static ACCEPTED=ACCEPTED$1;static REJECTED=REJECTED$1;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:r,userName:n}={}){this.meetingUuid=e,this.uuid=t,this.userUuid=r,this.userName=n}setStatus(e){this.status=e}getStatus(){return this.status}static parse(e){const{meeting_uuid:t,uuid:r,guest_uuid:n,guest_name:i}=e;return new MeetingAuthorization({meetingUuid:t,uuid:r,userUuid:n,userName:i})}static parseMany(e){return e?e.map(MeetingAuthorization.parse):[]}}const convertKeysFromCamelToUnderscore=e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Input is not an object");return Object.keys(e).reduce(((t,r)=>(t[camelToUnderscore(r)]="object"!=typeof e[r]||Array.isArray(e[r])?e[r]:convertKeysFromCamelToUnderscore(e[r]),t)),{})};var confdMethods=(e,t)=>({listUsers:()=>e.get(`${t}/users`,null),getUser:r=>e.get(`${t}/users/${r}`,null).then(Profile.parse),updateUser:(r,n)=>{const i={firstname:n.firstName,lastname:n.lastName,email:n.email,mobile_phone_number:n.mobileNumber};return e.put(`${t}/users/${r}`,i,null,ApiRequester.successResponseParser)},updateForwardOption:(r,n,i,s)=>{const o=`${t}/users/${r}/forwards/${n}`;return e.put(o,{destination:i,enabled:s},null,ApiRequester.successResponseParser)},updateDoNotDisturb:(r,n)=>e.put(`${t}/users/${r}/services/dnd`,{enabled:n},null,ApiRequester.successResponseParser),getUserLineSip:(r,n)=>e.get(`${t}/users/${r}/lines/${n}/associated/endpoints/sip?view=merged`).then(SipLine.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 r=t.lines[0];return this.getUserLineSip(e,r.uuid||r.id)}))},listApplications:()=>e.get(`${t}/applications`,null),getInfos:()=>e.get(`${t}/infos`,null),getExternalApps:r=>e.get(`${t}/users/${r}/external/apps`).then(ExternalApp.parseMany),getExternalApp:async(r,n)=>{const i=`${t}/users/${r}/external/apps/${n}?view=fallback`;try{return await e.get(i).then(ExternalApp.parse)}catch(e){return null}},getMyMeetings:()=>e.get(`${t}/users/me/meetings`).then((e=>Meeting.parseMany(e.items))),createMyMeeting:r=>e.post(`${t}/users/me/meetings`,convertKeysFromCamelToUnderscore(r)).then(Meeting.parse),updateMyMeeting:(r,n)=>e.put(`${t}/users/me/meetings/${r}`,convertKeysFromCamelToUnderscore(n),null,ApiRequester.successResponseParser),deleteMyMeeting:r=>e.delete(`${t}/users/me/meetings/${r}`,null),getMeeting:r=>e.get(`${t}/meetings/${r}`,null).then(Meeting.parse),meetingAuthorizations:r=>e.get(`${t}/users/me/meetings/${r}/authorizations`,null).then((e=>MeetingAuthorization.parseMany(e.items))),meetingAuthorizationReject:(r,n)=>e.put(`${t}/users/me/meetings/${r}/authorizations/${n}/reject`,{},null,ApiRequester.successResponseParser),meetingAuthorizationAccept:(r,n)=>e.put(`${t}/users/me/meetings/${r}/authorizations/${n}/accept`,{},null,ApiRequester.successResponseParser),guestGetMeeting:r=>e.get(`${t}/guests/me/meetings/${r}`,null).then(Meeting.parse),guestAuthorizationRequest:(r,n,i)=>e.post(`${t}/guests/${r}/meetings/${n}/authorizations`,{guest_name:i}).then(MeetingAuthorization.parse),guestAuthorizationCheck:(r,n,i)=>e.get(`${t}/guests/${r}/meetings/${n}/authorizations/${i}`,null)});class Relocation{static MIN_ENGINE_VERSION_REQUIRED;relocatedCall;initiatorCall;recipientCall;static parse(e){return new Relocation({initiatorCall:e.initiator_call,recipientCall:e.recipient_call,relocatedCall:e.relocated_call})}constructor({relocatedCall:e,initiatorCall:t,recipientCall:r}){this.initiatorCall=t||"",this.relocatedCall=e||"",this.recipientCall=r||""}}Relocation.MIN_ENGINE_VERSION_REQUIRED="19.09";class ChatMessage{type;uuid;content;date;alias;userUuid;roomUuid;read;static parseMany(e){return e&&e.items?e.items.map((e=>ChatMessage.parse(e))):[]}static parse(e){return new ChatMessage({uuid:e.uuid,date:moment(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 newFrom(e,ChatMessage)}constructor({uuid:e,date:t,content:r,userUuid:n,alias:i,roomUuid:s,read:o}={}){this.uuid=e,this.date=t,this.content=r,this.userUuid=n,this.alias=i,this.roomUuid=s,this.read=o,this.type="ChatMessage"}is(e){return this.uuid===e.uuid}isIncoming(e){return this.userUuid!==e}acknowledge(){return this.read=!0,this}}class Voicemail{type;id;date;duration;unread;caller;static parse(e){return new Voicemail({id:e.id,date:moment(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,r=e.folders.filter((e=>"old"===e.type))[0].messages;return[...t.map((e=>Voicemail.parse(e))).map((e=>e.makeAsUnRead())),...r.map((e=>Voicemail.parse(e))).map((e=>e.acknowledge()))]}static newFrom(e){return newFrom(e,Voicemail)}constructor({id:e,date:t,duration:r,caller:n,unread:i}){this.id=e,this.date=t,this.duration=r,this.caller=n,this.unread=i,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))}}const RECORD_STATE_ACTIVE="active";class Call{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=>Call.parse(e))):[]}static parse(e){return new Call({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:moment(e.creation_time).toDate(),talkingToIds:Object.keys(e.talking_to||{}),recording:e.record_state===RECORD_STATE_ACTIVE})}static newFrom(e){return newFrom(e,Call)}constructor({id:e,sipCallId:t,callerName:r,callerNumber:n,calleeName:i,calleeNumber:s,dialedExtension:o,isCaller:a,isVideo:d,lineId:c,muted:l,onHold:u,status:h,startingTime:g,talkingToIds:p,recording:m}){this.id=e,this.sipCallId=t,this.callerName=r,this.callerNumber=n,this.calleeName=i,this.calleeNumber=s,this.dialedExtension=o,this.muted=l,this.onHold=u,this.isCaller=a,this.lineId=c,this.status=h,this.startingTime=g,this.talkingToIds=p||[],this.recording=m,this.isVideo=!!d,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 SessionState$1;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(SessionState$1=SessionState$1||(SessionState$1={}));var updateFrom=(e,t)=>{Object.keys(t).forEach((r=>{(!e[r]&&t[r]||void 0!==e[r]&&void 0!==t[r]&&e[r]!==t[r])&&(e[r]=t[r])}))};class CallSession{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:r,displayName:n,callId:i,muted:s,videoMuted:o,number:a,paused:d,ringing:c,startTime:l,creationTime:u,endTime:h,cameraEnabled:g,dialedExtension:p,sipCallId:m,sipStatus:f,callerNumber:S,call:y,autoAnswer:b,ignored:E,screensharing:v,recording:_,recordingPaused:T,videoRemotelyDowngraded:R,sipSession:$,answerTime:C,conference:A}){this.callId=i,this.sipCallId=m,this.displayName=n,this.number=a,this.creationTime=u,this.startTime=l,this.endTime=h,this.isCaller=r,this.answered=e,this.answeredBySystem=t,this.ringing=c,this.paused=d,this.muted=s,this.videoMuted=o,this.callerNumber=S,this.cameraEnabled=g,this.dialedExtension=p||"",this.call=y,this.sipStatus=f,this.autoAnswer=b||!1,this.ignored=E||!1,this.screensharing=v||!1,this.recording=_||!1,this.recordingPaused=T||!1,this.videoRemotelyDowngraded=R,this.sipSession=$,this.answerTime=C||this.answerTime,this.conference=A,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===SessionState$1.Established}isTerminating(){return this.sipStatus===SessionState$1.Terminating}isTerminated(){return this.sipStatus===SessionState$1.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){updateFrom(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 newFrom(e,CallSession)}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 CallSession({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})}}class Emitter{eventEmitter;constructor(){this.eventEmitter=new EventEmitter$2}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 CallApi{static async fetchCallLogs(e,t){return getApiClient().callLogd.listCallLogs(e,t)}static async fetchDistinctCallLogs(e,t,r="peer_exten"){return getApiClient().callLogd.listDistinctCallLogs(e,t,r)}static async fetchActiveCalls(){return getApiClient().calld.listCalls()}static async fetchCallLogsFromDate(e,t){return getApiClient().callLogd.listCallLogsFromDate(e,t)}static async search(e,t){return getApiClient().callLogd.search(e,t)}static async searchBy(e,t,r){return getApiClient().callLogd.searchBy(e,t,r)}static async fetchSIP(e,t){const r=t||e.primaryLine();return getApiClient().confd.getUserLineSip(e.uuid,r?r.id:"")}static async cancelCall(e){return getApiClient().calld.cancelCall(e.callId)}static async makeCall(e,t,r=!1,n=!1){const i=e?e.id:null,s=await getApiClient().calld.makeCall(t,r,i,n);return Call.parse(s)}static async relocateCall(e,t,r){return getApiClient().calld.relocateCall(e,"line",t,r)}static async hold(e){return getApiClient().calld.hold(e)}static async resume(e){return getApiClient().calld.resume(e)}static async mute(e){return getApiClient().calld.mute(e)}static async sendDTMF(e,t){return getApiClient().calld.sendDTMF(e,t)}static async unmute(e){return getApiClient().calld.unmute(e)}static async transferCall(e,t,r){return getApiClient().calld.transferCall(e,t,r)}static async cancelCallTransfer(e){return getApiClient().calld.cancelCallTransfer(e)}static async confirmCallTransfer(e){return getApiClient().calld.confirmCallTransfer(e)}}const TRANSFER_FLOW_ATTENDED="attended",TRANSFER_FLOW_BLIND="blind",logger$b=IssueReporter$1?IssueReporter$1.loggerFor("cti-phone"):console;class CTIPhone extends Emitter{session;isMobile;callbackAllLines;currentCall;client=null;constructor(e,t=!1,r=!1){super(),logger$b.info("CTI Phone created"),this.session=e,this.isMobile=t,this.callbackAllLines=r}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(logger$b.info("make CTI call",{number:e}),!e)return null;try{this.currentCall=await CallApi.makeCall(t,e,this.isMobile,this.callbackAllLines)}catch(e){}if(!this.currentCall)return null;const r=CallSession.parseCall(this.currentCall);return this.eventEmitter.emit("onCallOutgoing",r),r}accept(e){return e?(logger$b.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&&(logger$b.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);logger$b.info("hangup CTI call",{callId:e.getId(),number:e.number});try{return await CallApi.cancelCall(e),this.currentCall&&e.callId===this.currentCall.id&&this.endCurrentCall(e),this.eventEmitter.emit("onCallEnded",e),!0}catch(t){return logger$b.error("hangup CTI call, error",t),this.eventEmitter.emit("onCallFailed",e),!1}}ignore(){}async reject(e){e&&(logger$b.info("reject CTI call",{callId:e.getId(),number:e.number}),await CallApi.cancelCall(e),this.eventEmitter.emit("onCallEnded",e))}async transfer(e,t){e&&(logger$b.info("transfer CTI call",{callId:e.getId(),number:e.number,to:t}),await CallApi.transferCall(e.callId,t,TRANSFER_FLOW_BLIND))}indirectTransfer(){return Promise.resolve(!1)}async initiateCTIIndirectTransfer(e,t){return e?(logger$b.info("indirect CTI transfer",{callId:e.getId(),number:e.number,to:t}),CallApi.transferCall(e.callId,t,TRANSFER_FLOW_ATTENDED)):Promise.resolve(null)}async cancelCTIIndirectTransfer(e){return logger$b.info("cancel CTI transfer",{transferId:e}),CallApi.cancelCallTransfer(e)}async confirmCTIIndirectTransfer(e){return logger$b.info("confirm CTI transfer",{transferId:e}),CallApi.confirmCallTransfer(e)}sendKey(e,t){e&&(logger$b.info("send CTI key",{callId:e.getId(),number:e.number,digits:t}),CallApi.sendDTMF(e.callId,t))}onConnectionMade(){logger$b.info("on CTI connection made"),this.eventEmitter.emit("onCallAccepted")}async close(){return logger$b.info("CTI close"),Promise.resolve()}async hold(e){return!!e&&(logger$b.info("CTI hold",{callId:e.getId(),number:e.number}),CallApi.hold(e.callId))}async resume(e){return!!e&&(logger$b.info("CTI resume",{callId:e.getId(),number:e.number}),CallApi.resume(e.callId))}async mute(e){e&&(logger$b.info("CTI mute",{callId:e.getId(),number:e.number}),await CallApi.mute(e.callId))}async unmute(e){e&&(logger$b.info("CTI unmute",{callId:e.getId(),number:e.number}),await CallApi.unmute(e.callId))}putOnSpeaker(){}putOffSpeaker(){}turnCameraOff(){}turnCameraOn(){}changeAudioInputDevice(){return Promise.resolve(null)}changeVideoInputDevice(){return Promise.resolve(null)}changeAudioDevice(){}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?CallSession.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 ctidNgMethods=(e,t)=>({updatePresence:r=>e.put(`${t}/users/me/presences`,{presence:r},null,ApiRequester.successResponseParser),listMessages:(r,n)=>{const i={};return r&&(i.participant_user_uuid=r),n&&(i.limit=n),e.get(`${t}/users/me/chats`,i).then(ChatMessage.parseMany)},sendMessage:(r,n,i)=>{const s={alias:r,msg:n,to:i};return e.post(`${t}/users/me/chats`,s,null,ApiRequester.successResponseParser)},makeCall:(r,n,i,s=!1)=>{const o={from_mobile:n,extension:r};return i&&(o.line_id=i),s&&(o.all_lines=!0),e.post(`${t}/users/me/calls`,o)},cancelCall:r=>e.delete(`${t}/users/me/calls/${r}`),listCalls:()=>e.get(`${t}/users/me/calls`).then((e=>Call.parseMany(e.items))),relocateCall(r,n,i,s){const o={completions:["answer"],destination:n,initiator_call:r,auto_answer:!0};return(i||s)&&(o.location={}),i&&(o.location.line_id=i),s&&(o.location.contact=s),e.post(`${t}/users/me/relocates`,o).then(Relocation.parse)},transferCall(r,n,i=TRANSFER_FLOW_BLIND){const s={exten:n,flow:i,initiator_call:r};return e.post(`${t}/users/me/transfers`,s)},cancelCallTransfer:r=>e.delete(`${t}/users/me/transfers/${r}`),confirmCallTransfer:r=>e.put(`${t}/users/me/transfers/${r}/complete`),listVoicemails:()=>e.get(`${t}/users/me/voicemails`,null).then((e=>Voicemail.parseMany(e))),deleteVoicemail:r=>e.delete(`${t}/users/me/voicemails/messages/${r}`,null),getPresence:r=>e.get(`${t}/users/${r}/presences`,null),getStatus:r=>e.get(`${t}/lines/${r}/presences`,null),fetchSwitchboardHeldCalls:r=>e.get(`${t}/switchboards/${r}/calls/held`,null),holdSwitchboardCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}`,null,null,ApiRequester.successResponseParser),answerSwitchboardHeldCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}/answer`,null),fetchSwitchboardQueuedCalls:r=>e.get(`${t}/switchboards/${r}/calls/queued`,null),answerSwitchboardQueuedCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/queued/${n}/answer`,null),sendFax:(r,n,i=null)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},o=ApiRequester.getQueryString({extension:r,caller_id:i});return e.post(`${t}/users/me/faxes?${o}`,n,s)}}),jsonToGraphQLQuery={},EnumType$1={};Object.defineProperty(EnumType$1,"__esModule",{value:!0}),EnumType$1.EnumType=void 0;var EnumType=function(e){this.value=e};EnumType$1.EnumType=EnumType;var VariableType$1={};Object.defineProperty(VariableType$1,"__esModule",{value:!0}),VariableType$1.VariableType=void 0;var VariableType=function(){function e(e){this.value=e}return e.prototype.toJSON=function(){return"$".concat(this.value)},e}();VariableType$1.VariableType=VariableType,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.jsonToGraphQLQuery=e.configFields=void 0;var t=EnumType$1,r=VariableType$1;function n(e){if(e instanceof t.EnumType)return e.value;if(e instanceof r.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 i=Object.keys(e).map((function(t){return"".concat(t,": ").concat(n(e[t]))})).join(", ");return"{".concat(i,"}")}function i(t,r){return-1==e.configFields.indexOf(t)&&-1==r.indexOf(t)}function s(e,t,r,o){Object.keys(e).filter((function(e){return i(e,o.ignoreFields)})).forEach((function(a){var d=e[a];if("object"==typeof d){if(Array.isArray(d)&&!(d=d.find((function(e){return e&&"object"==typeof e}))))return void r.push(["".concat(a),t]);if(d&&0===Object.keys(d).filter((function(e){return!1!==d[e]||o.includeFalsyKeys})).length)return;var c=Object.keys(d).filter((function(e){return i(e,o.ignoreFields)})).length>0,l="object"==typeof d.__args&&Object.keys(d.__args).length>0,u="object"==typeof d.__directives,h=d.__all_on instanceof Array,g="object"==typeof d.__on,p="".concat(a);if("string"==typeof d.__name&&(p="".concat(p," ").concat(d.__name)),"string"==typeof d.__aliasFor&&(p="".concat(p,": ").concat(d.__aliasFor)),"object"==typeof d.__variables&&Object.keys(d.__variables).length>0)p="".concat(p," (").concat(function(e){var t=[];for(var r in e)t.push("$".concat(r,": ").concat(e[r]));return t.join(", ")}(d.__variables),")");else if(l||u){var m="",f="";u&&(f=Object.entries(d.__directives).map((function(e){var t;return"@".concat(function(e){var t=Object.keys(e)[0],r=e[t];if("boolean"==typeof r||"object"==typeof r&&0===Object.keys(r).length)return t;if("object"==typeof r){var i=[];for(var s in r){var o=n(r[s]).replace(/"/g,"");i.push("".concat(s,": ").concat(o))}return"".concat(t,"(").concat(i.join(", "),")")}throw new Error("Unsupported type for directive: ".concat(typeof r,". Types allowed: object, boolean.\n")+"Offending object: ".concat(JSON.stringify(e)))}(((t={})[e[0]]=e[1],t)))})).join(" ")),l&&(m="(".concat(function(e){var t=[];for(var r in e)t.push("".concat(r,": ").concat(n(e[r])));return t.join(", ")}(d.__args),")"));var S=u&&l?" ":"";p="".concat(p," ").concat(m).concat(S).concat(f)}if(r.push([p+(c||g||h?" {":""),t]),s(d,t+1,r,o),h&&d.__all_on.forEach((function(e){r.push(["...".concat(e),t+1])})),g)(d.__on instanceof Array?d.__on:[d.__on]).forEach((function(e){var n=e.__typeName;r.push(["... on ".concat(n," {"),t+1]),s(e,t+2,r,o),r.push(["}",t+1])}));(c||g||h)&&r.push(["}",t])}else(!0===o.includeFalsyKeys||d)&&r.push(["".concat(a),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 r=[];s(e,0,r,t);var n="";return r.forEach((function(e){var r=e[0],i=e[1];t.pretty?(n&&(n+="\n"),n+=function(e){return Array(4*e+1).join(" ")}(i)+r):(n&&(n+=" "),n+=r)})),n}}(jsonToGraphQLQuery);const getContactPayload=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:""});var dirdMethods=(e,t)=>({search:(r,n,i=0,s=null)=>e.get(`${t}/directories/lookup/${r}`,{term:n}).then((e=>Contact.parseMany(e,i,s))),listPersonalContacts:r=>e.get(`${t}/personal`,r).then((e=>Contact.parseManyPersonal(e.items))),fetchPersonalContact:r=>e.get(`${t}/personal/${r}`).then(Contact.parsePersonal),addContact:r=>e.post(`${t}/personal`,getContactPayload(r)).then(Contact.parsePersonal),editContact:r=>e.put(`${t}/personal/${r.sourceId||r.id||""}`,getContactPayload(r)).then(Contact.parsePersonal),importContacts:async r=>{const n={"Content-Type":"text/csv; charset=utf-8","X-Auth-Token":e.token};return e.post(`${t}/personal/import`,r,n).then((e=>Contact.parseManyPersonal(e.created)))},deleteContact:r=>e.delete(`${t}/personal/${r}`),listFavorites:r=>e.get(`${t}/directories/favorites/${r}`).then(Contact.parseMany),markAsFavorite:(r,n)=>{const i=`${t}/directories/favorites/${r}/${n}`;return e.put(i,null,null,ApiRequester.successResponseParser)},removeFavorite:(r,n)=>e.delete(`${t}/directories/favorites/${r}/${n}`),fetchOffice365Source:r=>e.get(`${t}/directories/${r}/sources`,{backend:"office365"}),fetchOffice365Contacts:async(r,n)=>r?e.get(`${t}/backends/office365/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyOffice365(e.items,r))):Promise.resolve([]),fetchWazoSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"wazo"}),fetchWazoContacts:async(r,n)=>r?e.get(`${t}/backends/wazo/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyWazo(e.items,r))):Promise.resolve([]),fetchGoogleSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"google"}),fetchGoogleContacts:async(r,n)=>r?e.get(`${t}/backends/google/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyGoogle(e.items,r))):Promise.resolve([]),fetchConferenceSource:r=>e.get(`${t}/directories/${r}/sources`,{backend:"conference"}),fetchSourcesFor:(r,n)=>e.get(`${t}/directories/${r}/sources`,{backend:n}),fetchPhonebookContacts:async(r,n)=>r?e.get(`${t}/backends/phonebook/sources/${r.uuid}/contacts`,n):Promise.resolve({items:[],total:0}),fetchConferenceContacts:async(r,n)=>r?e.get(`${t}/backends/conference/sources/${r.uuid}/contacts`,n).then((e=>Contact.parseManyConference(e.items,r))):Promise.resolve([]),findMultipleContactsByNumber:(r,n)=>{const i=jsonToGraphQLQuery.jsonToGraphQLQuery({me:{contacts:{__args:{profile:"default",extens:r},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:`{${i}}`}).then(Contact.manyGraphQlWithNumbersParser(r))}});class Recording{deleted;end;fileName;start;uuid;static parseMany(e=[]){return e?e.map((e=>Recording.parse(e))):[]}static parse(e){return new Recording({deleted:e.deleted,fileName:e.filename,end:e.end_time?moment(e.end_time).toDate():null,start:moment(e.start_time).toDate(),uuid:e.uuid})}constructor({deleted:e,end:t,fileName:r,start:n,uuid:i}){this.deleted=e,this.end=t,this.fileName=r,this.start=n,this.uuid=i}}class CallLog{type;answer;answered;newMissedCall;callDirection;destination;recordings;source;id;duration;start;end;static merge(e,t){const r=e.concat(t);return r.map((e=>e.id)).filter(((e,t,r)=>r.indexOf(e)===t)).map((e=>r.find((t=>t&&t.id===e))))}static parseMany(e){return e&&e.items?e.items.map((e=>CallLog.parse(e))):[]}static parse(e){return new CallLog({answer:e.answer?moment(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:moment(e.start).toDate(),end:e.end?moment(e.end).toDate():null,recordings:Recording.parseMany(e.recordings||[])})}static parseNew(e,t){const r=CallLog.parse(e);return r.newMissedCall=t&&t.hasExtension(e.requested_extension||e.destination_extension)&&!e.answered,r}static newFrom(e){return newFrom(e,CallLog)}constructor({answer:e,answered:t,callDirection:r,destination:n,source:i,id:s,duration:o,start:a,end:d,recordings:c}){this.answer=e,this.answered=t,this.callDirection=r,this.destination=n,this.source=i,this.id=s,this.duration=o,this.start=a,this.end=d,this.recordings=c||[],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}}var callLogdMethods=(e,t)=>({search:(r,n=5)=>e.get(`${t}/users/me/cdr`,{search:r,limit:n}).then(CallLog.parseMany),searchBy:(r,n,i=5)=>e.get(`${t}/users/me/cdr`,{[r]:n,limit:i}).then(CallLog.parseMany),listCallLogs:(r,n=5)=>e.get(`${t}/users/me/cdr`,{offset:r,limit:n}).then(CallLog.parseMany),listDistinctCallLogs:(r,n=5,i=void 0)=>e.get(`${t}/users/me/cdr`,{offset:r,limit:n,distinct:i}).then(CallLog.parseMany),listCallLogsFromDate:(r,n)=>e.get(`${t}/users/me/cdr`,{from:r.toISOString(),number:n}).then(CallLog.parseMany)});class ChatRoom{type;uuid;name;users;static parseMany(e){return e&&e.items?e.items.map((e=>ChatRoom.parse(e))):[]}static parse(e){return new ChatRoom({uuid:e.uuid,name:e.name,users:e.users})}static newFrom(e){return newFrom(e,ChatRoom)}constructor({uuid:e,name:t,users:r}={}){this.uuid=e,this.name=t,this.users=r,this.type="ChatRoom"}}const MAX_PRESENCE_FETCHED=30;var chatdMethods=(e,t)=>({updateState:(r,n)=>e.put(`${t}/users/${r}/presences`,{state:n},null,ApiRequester.successResponseParser),updateStatus:(r,n,i)=>{const s={state:n,status:i};return e.put(`${t}/users/${r}/presences`,s,null,ApiRequester.successResponseParser)},getState:async r=>e.get(`${t}/users/${r}/presences`).then((e=>e.state)),getContactStatusInfo:async r=>e.get(`${t}/users/${r}/presences`).then((e=>e)),getLineState:async r=>e.get(`${t}/users/${r}/presences`).then((e=>Profile.getLinesState(e.lines))),async getMultipleLineState(r){const n={},i=r||[];if(i.length>MAX_PRESENCE_FETCHED){const e=i.reduce(((e,t,r)=>(r%MAX_PRESENCE_FETCHED==0&&e.push(this.getMultipleLineState(i.slice(r,r+MAX_PRESENCE_FETCHED))),e)),[]);return(await Promise.all(e)).flat()}return i.length&&(n.user_uuid=i.join(",")),e.get(`${t}/users/presences`,n).then((e=>e.items))},getUserRooms:async()=>e.get(`${t}/users/me/rooms`).then(ChatRoom.parseMany),createRoom:async(r,n)=>e.post(`${t}/users/me/rooms`,{name:r,users:n}).then(ChatRoom.parse),getRoomMessages:async(r,n)=>{const i=ApiRequester.getQueryString(n||{});return e.get(`${t}/users/me/rooms/${r}/messages${i.length?`?${i}`:""}`).then((e=>ChatMessage.parseMany(e)))},sendRoomMessage:async(r,n)=>e.post(`${t}/users/me/rooms/${r}/messages`,n).then(ChatMessage.parse),getMessages:async r=>e.get(`${t}/users/me/rooms/messages`,r)});class IndirectTransfer{status;id;sourceId;destinationId;constructor({sourceId:e,destinationId:t,status:r,id:n}){this.sourceId=e,this.destinationId=t,this.status=r,this.id=n}static parseFromCallSession(e,t){return new IndirectTransfer({sourceId:e.getId(),destinationId:t.getId()})}static parseFromApi(e){return new IndirectTransfer({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){updateFrom(this,e)}static newFrom(e){return newFrom(e,IndirectTransfer)}}class MeetingStatus{type;full;constructor({full:e}={}){this.full=e,this.type="MeetingStatus"}static parse(e){return new MeetingStatus({full:e.full})}}var calldMethods=(e,t)=>({updatePresence:r=>e.put(`${t}/users/me/presences`,{presence:r},null,ApiRequester.successResponseParser),listMessages:(r,n)=>{const i={};return r&&(i.participant_user_uuid=r),n&&(i.limit=n),e.get(`${t}/users/me/chats`,i).then((e=>ChatMessage.parseMany(e)))},sendMessage:(r,n,i)=>{const s={alias:r,msg:n,to:i};return e.post(`${t}/users/me/chats`,s,null,ApiRequester.successResponseParser)},makeCall:(r,n,i,s=!1)=>{const o={from_mobile:n,extension:r};return i&&(o.line_id=i),s&&(o.all_lines=!0),e.post(`${t}/users/me/calls`,o)},cancelCall:r=>e.delete(`${t}/users/me/calls/${r}`,null),listCalls:()=>e.get(`${t}/users/me/calls`,null).then((e=>Call.parseMany(e.items))),relocateCall(r,n,i,s){const o={completions:["answer"],destination:n,initiator_call:r,auto_answer:!0};return(i||s)&&(o.location={}),i&&(o.location.line_id=i),s&&(o.location.contact=s),e.post(`${t}/users/me/relocates`,o).then((e=>Relocation.parse(e)))},listVoicemails:()=>e.get(`${t}/users/me/voicemails`).then((e=>Voicemail.parseMany(e))),deleteVoicemail:r=>e.delete(`${t}/users/me/voicemails/messages/${r}`),getVoicemailUrl:r=>{const n={token:e.token};return e.computeUrl("get",`${t}/users/me/voicemails/messages/${r.id}/recording`,n)},fetchSwitchboardHeldCalls:r=>e.get(`${t}/switchboards/${r}/calls/held`),holdSwitchboardCall:(r,n)=>e.put(`${t}/switchboards/${r}/calls/held/${n}`,null,null,ApiRequester.successResponseParser),answerSwitchboardHeldCall:(r,n,i=null)=>e.put(`${t}/switchboards/${r}/calls/held/${n}/answer${i?`?line_id=${i}`:""}`),fetchSwitchboardQueuedCalls:r=>e.get(`${t}/switchboards/${r}/calls/queued`),answerSwitchboardQueuedCall:(r,n,i=null)=>e.put(`${t}/switchboards/${r}/calls/queued/${n}/answer${i?`?line_id=${i}`:""}`),sendFax:(r,n,i)=>{const s={"Content-type":"application/pdf","X-Auth-Token":e.token},o=ApiRequester.getQueryString({extension:r,caller_id:i});return e.post(`${t}/users/me/faxes?${o}`,n,s)},getConferenceParticipantsAsUser:async r=>e.get(`${t}/users/me/conferences/${r}/participants`),getMeetingParticipantsAsUser:async r=>e.get(`${t}/users/me/meetings/${r}/participants`),banMeetingParticipant:(r,n)=>e.delete(`${t}/users/me/meetings/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),listTrunks:()=>e.get(`${t}/trunks`),mute:r=>e.put(`${t}/users/me/calls/${r}/mute/start`,null,null,ApiRequester.successResponseParser),unmute:r=>e.put(`${t}/users/me/calls/${r}/mute/stop`,null,null,ApiRequester.successResponseParser),hold:r=>e.put(`${t}/users/me/calls/${r}/hold/start`,null,null,ApiRequester.successResponseParser),resume:r=>e.put(`${t}/users/me/calls/${r}/hold/stop`,null,null,ApiRequester.successResponseParser),transferCall:(r,n,i)=>e.post(`${t}/users/me/transfers`,{initiator_call:r,exten:n,flow:i}).then(IndirectTransfer.parseFromApi),confirmCallTransfer:r=>e.put(`${t}/users/me/transfers/${r}/complete`,null,null,ApiRequester.successResponseParser),cancelCallTransfer:r=>e.delete(`${t}/users/me/transfers/${r}`,null,null,ApiRequester.successResponseParser),sendDTMF:(r,n)=>e.put(`${t}/users/me/calls/${r}/dtmf?digits=${encodeURIComponent(n)}`,null,null,ApiRequester.successResponseParser),isAhHocConferenceAPIEnabled:()=>e.head(`${t}/users/me/conferences/adhoc`,null,null,ApiRequester.successResponseParser),createAdHocConference:(r,n)=>e.post(`${t}/users/me/conferences/adhoc`,{host_call_id:r,participant_call_ids:n}),addAdHocConferenceParticipant:(r,n)=>e.put(`${t}/users/me/conferences/adhoc/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),removeAdHocConferenceParticipant:(r,n)=>e.delete(`${t}/users/me/conferences/adhoc/${r}/participants/${n}`,null,null,ApiRequester.successResponseParser),deleteAdHocConference:r=>e.delete(`${t}/users/me/conferences/adhoc/${r}`,null,null,ApiRequester.successResponseParser),startRecording:r=>e.put(`${t}/users/me/calls/${r}/record/start`,null,null,ApiRequester.successResponseParser),stopRecording:r=>e.put(`${t}/users/me/calls/${r}/record/stop`,null,null,ApiRequester.successResponseParser),pauseRecording:r=>e.put(`${t}/users/me/calls/${r}/record/pause`,null,null,ApiRequester.successResponseParser),resumeRecording:r=>e.put(`${t}/users/me/calls/${r}/record/resume`,null,null,ApiRequester.successResponseParser),guestGetMeetingStatus:r=>e.get(`${t}/guests/me/meetings/${r}/status`).then(MeetingStatus.parse)});class Agent{context;extension;id;logged;number;paused;pausedReason;static parse(e){return new Agent({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:r,logged:n,number:i,paused:s,pausedReason:o}){this.context=e,this.extension=t,this.id=r,this.logged=n,this.number=i,this.paused=s,this.pausedReason=o}}var agentdMethods=(e,t)=>({getAgent:r=>e.get(`${t}/agents/by-id/${r}`,null).then(Agent.parse),login:(r,n,i)=>e.post(`${t}/agents/by-number/${r}/login`,{context:n,extension:i},null,ApiRequester.successResponseParser),loginWithLineId:r=>e.post(`${t}/users/me/agents/login`,{line_id:r},null,ApiRequester.successResponseParser),logout:r=>e.post(`${t}/agents/by-number/${r}/logoff`,null,null,ApiRequester.successResponseParser),pause:r=>e.post(`${t}/agents/by-number/${r}/pause`,{reason:"songbird_reason"},null,ApiRequester.successResponseParser),resume:r=>e.post(`${t}/agents/by-number/${r}/unpause`,null,null,ApiRequester.successResponseParser),getStatus:()=>e.get(`${t}/users/me/agents`,null).then(Agent.parse),staticLogout:()=>e.post(`${t}/users/me/agents/logoff`,null,null,ApiRequester.successResponseParser),staticPause:()=>e.post(`${t}/users/me/agents/pause`,{reason:"songbird_reason"},null,ApiRequester.successResponseParser),staticResume:()=>e.post(`${t}/users/me/agents/unpause`,null,null,ApiRequester.successResponseParser)});class Subscription{name;events;config;uuid;service;eventsUserUuid;eventsWazoUuid;metadata;ownerTenantUuid;ownerUserUuid;static parse(e){return new Subscription({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=>Subscription.parse(e)))}constructor({name:e,events:t,config:r,uuid:n,service:i,eventsUserUuid:s,eventsWazoUuid:o,metadata:a,ownerTenantUuid:d,ownerUserUuid:c}){this.name=e,this.events=t,this.config=r,this.uuid=n,this.service=i,this.eventsUserUuid=s,this.eventsWazoUuid=o,this.metadata=a,this.ownerTenantUuid=d,this.ownerUserUuid=c}}var webhookdMethods=(e,t)=>({getSubscriptions:()=>e.get(`${t}/users/me/subscriptions`).then(Subscription.parseMany),getSubscription:r=>e.get(`${t}/users/me/subscriptions/${r}`).then(Subscription.parse),createSubscription:r=>e.post(`${t}/users/me/subscriptions`,r),removeSubscription:r=>e.delete(`${t}/users/me/subscriptions/${r}`)}),amidMethods=(e,t)=>({action:(r,n={})=>e.post(`${t}/action/${r}`,n),getAors:async r=>{try{const n=await e.post(`${t}/action/PJSIPShowEndpoint`,{Endpoint:r})||[];return n?n.filter((e=>"ContactStatusDetail"===e.Event)):[]}catch{return[]}}});const AUTH_VERSION="0.1",APPLICATION_VERSION="1.0",CONFD_VERSION="1.1",CTIDNG_VERSION="1.0",DIRD_VERSION="0.1",CALL_LOGD_VERSION="1.0",CHATD_VERSION="1.0",CALLD_VERSION="1.0",AGENTD_VERSION="1.0",WEBHOOKD_VERSION="1.0",AMID_VERSION="1.0",logger$a=IssueReporter$1?IssueReporter$1.loggerFor("api"):console;class ApiClient{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:r,clientId:n,isMobile:i=!1,fetchOptions:s}){this.updateParameters({server:e,agent:t,clientId:n,fetchOptions:s}),this.refreshToken=r,this.isMobile=i||!1}initializeEndpoints(){this.auth=authMethods(this.client,`auth/${AUTH_VERSION}`),this.application=applicationMethods(this.client,`calld/${APPLICATION_VERSION}/applications`),this.confd=confdMethods(this.client,`confd/${CONFD_VERSION}`),this.ctidNg=ctidNgMethods(this.client,`ctid-ng/${CTIDNG_VERSION}`),this.dird=dirdMethods(this.client,`dird/${DIRD_VERSION}`),this.callLogd=callLogdMethods(this.client,`call-logd/${CALL_LOGD_VERSION}`),this.chatd=chatdMethods(this.client,`chatd/${CHATD_VERSION}`),this.calld=calldMethods(this.client,`calld/${CALLD_VERSION}`),this.agentd=agentdMethods(this.client,`agentd/${AGENTD_VERSION}`),this.webhookd=webhookdMethods(this.client,`webhookd/${WEBHOOKD_VERSION}`),this.amid=amidMethods(this.client,`amid/${AMID_VERSION}`)}updateParameters({server:e,agent:t,clientId:r,fetchOptions:n}){const i=this.refreshTokenCallback.bind(this);this.client=new ApiRequester({server:e,agent:t,refreshTokenCallback:i,clientId:r,fetchOptions:n}),this.initializeEndpoints()}async forceRefreshToken(){return logger$a.info("forcing refresh token, calling callback"),this.refreshTokenCallback()}async refreshTokenCallback(){if(logger$a.info("refresh token callback called",{refreshToken:obfuscateToken(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?(logger$a.info("token refreshed",{token:obfuscateToken(e.token)}),this.onRefreshToken&&this.onRefreshToken(e.token,e),this.setToken(e.token),e.token):null}catch(e){logger$a.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 setApiClientId=(e,t=null)=>{global.wazoClientId[String(t)]=e},setCurrentServer=e=>{global.wazoCurrentServer=e},setApiToken=(e,t=null)=>{global.wazoClientToken[String(t)]=e},setRefreshToken=(e,t=null)=>{global.wazoRefreshToken[String(t)]=e},setRefreshTenantId=(e,t=null)=>{console.warn("Use of `setRefreshTenantId` is deprecated, please use `setRefreshDomainName` instead"),global.wazoRefreshTenantId[String(t)]=e},setRefreshDomainName=(e,t=null)=>{global.wazoRefreshDomainName[String(t)]=e},setOnRefreshToken=(e,t=null)=>{global.wazoOnRefreshToken[String(t)]=e},setOnRefreshTokenError=(e,t=null)=>{global.wazoOnRefreshTokenError[String(t)]=e},setRefreshExpiration=(e,t=null)=>{global.wazoRefreshExpiration[String(t)]=e},setIsMobile=(e,t=null)=>{global.wazoIsMobile[String(t)]=e},setRequestTimeout=(e,t=null)=>{global.wazoRequestApiTimeout[String(t)]=e},setFetchOptions=(e,t=null)=>{global.wazoFetchOptions[String(t)]=e},getFetchOptions=(e=null)=>(e?global.wazoFetchOptions[e]:global.wazoFetchOptions.null)||global.wazoFetchOptions.null,fillClient=e=>{const{server:t,token:r,clientId:n}=e.client,i=global.wazoRefreshTenantId[t]||global.wazoRefreshTenantId.null||e.refreshTenantId,s=global.wazoRequestApiTimeout[t]||global.wazoRequestApiTimeout.null;return e.setToken(global.wazoClientToken[t]||global.wazoClientToken.null||r),e.setClientId(global.wazoClientId[t]||global.wazoClientId.null||n),e.setRefreshToken(global.wazoRefreshToken[t]||global.wazoRefreshToken.null||e.refreshToken),i&&e.setRefreshTenantId(i),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 getApiClient=(e=null)=>{const t=e||global.wazoCurrentServer||"";return t in global.wazoClients||(global.wazoClients[t]=new ApiClient({server:t})),fillClient(global.wazoClients[t])};class InvalidSubscription extends Error{}class InvalidAuthorization extends Error{}class NoTenantIdError extends Error{}class NoDomainNameError extends Error{}const logger$9=IssueReporter$1.loggerFor("simple-auth");class Auth{clientId;expiration;minSubscriptionType;authorizationName;host;session;onRefreshTokenCallback;onRefreshTokenCallbackError;onHostFromHeadersCallback;authenticated;mobile;BACKEND_WAZO;BACKEND_LDAP;shouldCheckUserUuidHeader;constructor(){this.expiration=DETAULT_EXPIRATION,this.authenticated=!1,this.minSubscriptionType=null,this.BACKEND_WAZO=DEFAULT_BACKEND_USER,this.BACKEND_LDAP=BACKEND_LDAP_USER,this.shouldCheckUserUuidHeader=!0}init(e,t,r,n,i){this.clientId=e,this.expiration=t,this.minSubscriptionType=void 0===r?null:r,this.authorizationName=n,this.host=null,this.session=null,this.mobile=i||!1,setApiClientId(this.clientId),setRefreshExpiration(this.expiration),setOnRefreshToken(((e,t)=>{logger$9.info("on refresh token done",{token:obfuscateToken(e)}),setApiToken(e),Wazo$1.Websocket.updateToken(e),this.onRefreshTokenCallback&&this.onRefreshTokenCallback(e,t)})),setOnRefreshTokenError((e=>{logger$9.error("on refresh token error",e),this.onRefreshTokenCallbackError&&this.onRefreshTokenCallbackError(e)}))}setFetchOptions(e){setFetchOptions(e)}async logIn(e,t,r,n){let i=null,s=null;if("string"==typeof n&&(i=n),n&&"object"==typeof n&&(s=n.domainName),r&&r!==this.BACKEND_WAZO&&!i&&!s){if(!i)throw new NoTenantIdError("No tenant id");if(!s)throw new NoDomainNameError("No domain name")}this.authenticated=!1,this.session=null;const o=await getApiClient().auth.logIn({username:e,password:t,backend:r,tenantId:i,domainName:s,expiration:this.expiration,mobile:this.mobile});if(o){const e=o.getHostFromHeader();e&&(this.setHost(e),this.onHostFromHeadersCallback&&this.onHostFromHeadersCallback(e))}return r&&getApiClient().setRefreshBackend(r),i&&getApiClient().setRefreshTenantId(i),s&&getApiClient().setRefreshDomainName(s),this._onAuthenticated(o)}async logInViaRefreshToken(e){const t=await getApiClient().auth.refreshToken(e,"",this.expiration,this.mobile);return this._onAuthenticated(t)}async validateToken(e,t){if(e){t&&setRefreshToken(t);try{const t=await getApiClient().auth.authenticate(e);return this._onAuthenticated(t)}catch(e){logger$9.error("on validate token error",e),console.warn(e)}}}async generateNewToken(e){return getApiClient().auth.refreshToken(e,"",this.expiration)}async logout(e=!0){try{Wazo$1.Websocket.close(!0),this.clientId&&e&&await getApiClient().auth.deleteRefreshToken(this.clientId)}catch(e){}try{this.session?.token&&await getApiClient().auth.logOut(this.session.token)}catch(e){}setApiToken(null),setRefreshToken(null),this.session=null,this.authenticated=!1,setFetchOptions({})}setOnHostFromHeaders(e){this.onHostFromHeadersCallback=e}setOnRefreshToken(e){this.onRefreshTokenCallback=e}setOnRefreshTokenError(e){this.onRefreshTokenCallbackError=e}checkAuthorizations(e,t){if(!t)return;const{authorizations:r}=e;if(!r.find((e=>e.rules.find((e=>e.name===t)))))throw new InvalidAuthorization(`No authorization '${t||""}' found for your account.`)}checkSubscription(e,t){const r=e.profile?.subscriptionType||null;if(null===r||r<=t){throw new InvalidSubscription(`Invalid subscription ${r||"n/a"}, required at least ${t}`)}}setHost(e){this.host=e,setCurrentServer(e)}setApiToken(e){setApiToken(e)}setRefreshToken(e){setRefreshToken(e)}setRefreshTenantId(e){console.warn("Use of `setRefreshTenantId` is deprecated, use `setRefreshDomainName` instead."),setRefreshTenantId(e),getApiClient().setRefreshTenantId(e)}setRefreshDomainName(e){setRefreshDomainName(e),getApiClient().setRefreshDomainName(e)}setRequestTimeout(e){setRequestTimeout(e),getApiClient().setRequestTimeout(e)}forceRefreshToken(){return getApiClient().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,setApiClientId(this.clientId)}getName(){return`${this.getFirstName()} ${this.getLastName()}`}async setHttpUserUuidHeader(e){if(!e)return;const t={...getFetchOptions()?.headers||{},"X-User-UUID":e};try{this.shouldCheckUserUuidHeader&&await getApiClient().client.head("auth/0.1/status",null,t),setFetchOptions({...getFetchOptions(),headers:t})}catch(e){}}async _onAuthenticated(e){if(this.authenticated&&this.session)return this.session;const t=e;if(await this.setHttpUserUuidHeader(t.uuid),!t)return null;setApiToken(t.token),t.refreshToken&&setRefreshToken(t.refreshToken);try{const[e,{wazo_version:r}]=await Promise.all([getApiClient().confd.getUser(t.uuid),getApiClient().confd.getInfos()]);t.engineVersion=r,t.profile=e,this.checkAuthorizations(t,this.authorizationName),null!==this.minSubscriptionType&&this.checkSubscription(t,+this.minSubscriptionType)}catch(e){throw logger$9.error("on authenticated error",e),this.clientId&&await getApiClient().auth.deleteRefreshToken(this.clientId),t&&await getApiClient().auth.logOut(t.token),e}try{const e=t.profile?.lines.filter((e=>!e.endpointSccp)).map((e=>String(e.id))),r=await getApiClient().confd.getUserLinesSip(t.uuid,e);t.profile.sipLines=r.filter((e=>e instanceof SipLine))}catch(e){}return this.authenticated=!0,Wazo$1.Websocket.open(this.host,t),this.session=t,t}}global.wazoAuthInstance||(global.wazoAuthInstance=new Auth);var Auth$1=global.wazoAuthInstance;class AdHocAPIConference{phone;host;participants;started;finished;conferenceId;answerTime;muted;paused;constructor({phone:e,host:t,participants:r,started:n,finished:i,answerTime:s,conferenceId:o,muted:a,paused:d}){this.phone=e,this.host=t,this.participants=r||{},this.started=n||!1,this.finished=i||!1,this.answerTime=s,this.conferenceId=o||"",this.muted=a||!1,this.paused=d||!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 getApiClient().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],r={...this.participants,[t]:e};return await getApiClient().calld.addAdHocConferenceParticipant(this.conferenceId,t),new AdHocAPIConference({...this,participants:r})}participantHasLeft(e){return delete this.participants[e.getId()],new AdHocAPIConference({...this,participants:this.participants})}hasParticipants(){return Object.keys(this.participants).length>0}mute(){return this.muted=!0,this.phone.mute(this.host),new AdHocAPIConference({...this})}unmute(){return this.muted=!1,this.phone.unmute(this.host),new AdHocAPIConference({...this})}hold(){return this.paused=!0,this.phone.hold(this.host),new AdHocAPIConference({...this})}resume(){return this.paused=!1,this.phone.resume(this.host),new AdHocAPIConference({...this})}isOnHold(){return this.paused}isMuted(){return this.muted}async hangup(){return await getApiClient().calld.deleteAdHocConference(this.conferenceId),new AdHocAPIConference({...this,finished:!0,participant:[]})}async removeParticipant(e){const t=e.getTalkingToIds()[0];return delete this.participants[t],await getApiClient().calld.removeAdHocConferenceParticipant(this.conferenceId,t),new AdHocAPIConference({...this,participants:this.participants})}}class Exception extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class ContentTypeUnsupportedError extends Exception{constructor(e){super(e||"Unsupported content type.")}}class RequestPendingError extends Exception{constructor(e){super(e||"Request pending.")}}class SessionDescriptionHandlerError extends Exception{constructor(e){super(e||"Unspecified session description handler error.")}}class SessionTerminatedError extends Exception{constructor(){super("The session has terminated.")}}class StateTransitionError extends Exception{constructor(e){super(e||"An error occurred during state transition.")}}class Ack{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class Bye{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 Cancel{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class EmitterImpl{constructor(){this.listeners=new Array}addListener(e,t){const r=t=>{this.removeListener(r),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(r):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 Info{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 Parameters{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 NameAddrHeader extends Parameters{constructor(e,t,r){super(r),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 NameAddrHeader(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 URI extends Parameters{constructor(e="sip",t,r,n,i,s){if(super(i||{}),this.headers={},!r)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:r,port:n},this.normal={scheme:e.toLowerCase(),user:t,host:r.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 URI(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 r=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&r.push(e+"="+this.headers[e][t]);return r.length>0&&(t+="?"+r.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"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length;let i="";for(let e=0;e<n;e++)0!==e&&(i+="-"),i+=r[e].charAt(0).toUpperCase()+r[e].substring(1);return t[i]&&(i=t[i]),i}}function equivalentURI(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 r=Object.keys(e.parameters),n=Object.keys(t.parameters);return!!r.filter((e=>n.includes(e))).every((r=>e.parameters[r]===t.parameters[r]))&&(!!["user","ttl","method","transport"].every((r=>e.hasParam(r)&&t.hasParam(r)||!e.hasParam(r)&&!t.hasParam(r)))&&!!["maddr"].every((r=>e.hasParam(r)&&t.hasParam(r)||!e.hasParam(r)&&!t.hasParam(r))))}(e,t))return!1;const r=Object.keys(e.headers),n=Object.keys(t.headers);if(0!==r.length||0!==n.length){if(r.length!==n.length)return!1;const i=r.filter((e=>n.includes(e)));if(i.length!==n.length)return!1;if(!i.every((r=>e.headers[r].length&&t.headers[r].length&&e.headers[r][0]===t.headers[r][0])))return!1}return!0}function peg$padEnd(e,t,r){return r=r||" ",e.length>t?e:(t-=e.length,e+(r+=r.repeat(t)).slice(0,t))}class SyntaxError extends Error{constructor(e,t,r,n){super(),this.message=e,this.expected=t,this.found=r,this.location=n,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,SyntaxError.prototype):this.__proto__=SyntaxError.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,SyntaxError)}static buildMessage(e,t){function r(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"+r(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+r(e)))}function i(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"+r(e))).replace(/[\x10-\x1F\x7F-\x9F]/g,(e=>"\\x"+r(e)))}function s(e){switch(e.type){case"literal":return'"'+n(e.text)+'"';case"class":const t=e.parts.map((e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(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 r,n;if(t.sort(),t.length>0){for(r=1,n=1;r<t.length;r++)t[r-1]!==t[r]&&(t[n]=t[r],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 "+(((o=t)?'"'+n(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let r,n=null;for(r=0;r<e.length;r++)if(e[r].source===this.location.source){n=e[r].text.split(/\r\n|\n|\r/g);break}let i=this.location.start,s=this.location.source+":"+i.line+":"+i.column;if(n){let e=this.location.end,r=peg$padEnd("",i.line.toString().length," "),o=n[i.line-1],a=i.line===e.line?e.column:o.length+1;t+="\n --\x3e "+s+"\n"+r+" |\n"+i.line+" | "+o+"\n"+r+" | "+peg$padEnd("",i.column-1," ")+peg$padEnd("",a-i.column,"^")}else t+="\n at "+s}return t}}function peg$parse(e,t){const r={},n=(t=void 0!==t?t:{}).grammarSource,i={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 o=["\r\n",S("\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)," ",S(" ",!1),"\t",S("\t",!1),/^[a-zA-Z0-9]/,y([["a","z"],["A","Z"],["0","9"]],!1,!1),";",S(";",!1),"/",S("/",!1),"?",S("?",!1),":",S(":",!1),"@",S("@",!1),"&",S("&",!1),"=",S("=",!1),"+",S("+",!1),"$",S("$",!1),",",S(",",!1),"-",S("-",!1),"_",S("_",!1),".",S(".",!1),"!",S("!",!1),"~",S("~",!1),"*",S("*",!1),"'",S("'",!1),"(",S("(",!1),")",S(")",!1),"%",S("%",!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),"`",S("`",!1),"<",S("<",!1),">",S(">",!1),"\\",S("\\",!1),"[",S("[",!1),"]",S("]",!1),"{",S("{",!1),"}",S("}",!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 URI(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 URI(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",S("sips",!0),"sip",S("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(m().slice(0,-1))},function(){(t=t||{data:{}}).data.password=m()},function(){return(t=t||{data:{}}).data.host=m(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",m()},/^[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",m()},"::",S("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",m()},function(){return(t=t||{data:{}}).data.host_type="IPv4",m()},"25",S("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",S("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",S("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=",S("transport=",!0),"udp",S("udp",!0),"tcp",S("tcp",!0),"sctp",S("sctp",!0),"tls",S("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",S("user=",!0),"phone",S("phone",!0),"ip",S("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",S("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",S("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",S("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",S("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,r){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),r=null===r?void 0:r[1],t.data.uri_params[e.toLowerCase()]=r},function(e,r){e=e.join("").toLowerCase(),r=r.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(r):t.data.uri_headers[e]=[r]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new URI(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)},"//",S("//",!1),function(){(t=t||{data:{}}).data.scheme=m()},S("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=m()},"INVITE",S("INVITE",!1),"ACK",S("ACK",!1),"VXACH",S("VXACH",!1),"OPTIONS",S("OPTIONS",!1),"BYE",S("BYE",!1),"CANCEL",S("CANCEL",!1),"REGISTER",S("REGISTER",!1),"SUBSCRIBE",S("SUBSCRIBE",!1),"NOTIFY",S("NOTIFY",!1),"REFER",S("REFER",!1),"PUBLISH",S("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=m(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=m()},function(){(t=t||{data:{}}).data=m()},function(){var e,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e<r;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 NameAddrHeader(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:d,offset:f().start.offset,parsed:e})},function(e){'"'===(e=m().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",S("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",S("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",S("0",!1),function(){return parseFloat(m())},function(e,r){(t=t||{data:{}}).data.params||(t.data.params={}),r=null===r?void 0:r[1],t.data.params[e.toLowerCase()]=r},"render",S("render",!0),"session",S("session",!0),"icon",S("icon",!0),"alert",S("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=m().toLowerCase())},"handling",S("handling",!0),"optional",S("optional",!0),"required",S("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=m()},"text",S("text",!0),"image",S("image",!0),"audio",S("audio",!0),"video",S("video",!0),"application",S("application",!0),"message",S("message",!0),"multipart",S("multipart",!0),"x-",S("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 NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",S("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 NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},"digest",S("Digest",!0),"realm",S("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",S("domain",!0),"nonce",S("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",S("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",S("stale",!0),"true",S("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",S("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",S("algorithm",!0),"md5",S("MD5",!0),"md5-sess",S("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",S("qop",!0),"auth-int",S("auth-int",!0),"auth",S("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,r;for(r=(t=t||{data:{}}).data.multi_header.length,e=0;e<r;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 NameAddrHeader(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:d,offset:f().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new NameAddrHeader(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",S("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",S("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",S("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",S("active",!0),"pending",S("pending",!0),"terminated",S("terminated",!0),function(){(t=t||{data:{}}).data.state=m()},"reason",S("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",S("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",S("deactivated",!0),"probation",S("probation",!0),"rejected",S("rejected",!0),"timeout",S("timeout",!0),"giveup",S("giveup",!0),"noresource",S("noresource",!0),"invariant",S("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",S("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",S("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",S("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",S("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",S("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},S("UDP",!0),S("TCP",!0),S("TLS",!0),S("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=m()},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",S("refresher",!1),"uas",S("uas",!1),"uac",S("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",S("stuns",!0),"stun",S("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",S("?transport=",!1),"turns",S("turns",!0),"turn",S("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=m()},"Referred-By",S("Referred-By",!1),"b",S("b",!1),"cid",S("cid",!1)],a=[_('2 ""6 7!'),_('4"""5!7#'),_('4$""5!7%'),_('4&""5!7\''),_(";'.# &;("),_('4(""5!7)'),_('4*""5!7+'),_('2,""6,7-'),_('2.""6.7/'),_('40""5!71'),_('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'),_(";).# &;,"),_('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),_('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),_('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),_(';.." &"'),_("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),_('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_('4\\""5!7].# &;3'),_('4^""5!7_'),_('4`""5!7a'),_(';!.) &4b""5!7c'),_('%$;).• &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&&&#/"!&,)'),_('%$;).‰ &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&&&#/"!&,)'),_('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.) &;\'.# &;('),_('%$;).ī &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&&&#/"!&,)'),_("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),_("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),_("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),_("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),_("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),_('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),_('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),_("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),_("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),_("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),_("%;//0#;&/'$8\":~\" )(\"'#&'#"),_("%;&/0#;//'$8\":~\" )(\"'#&'#"),_("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),_('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),_("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),_("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),_(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),_('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),_("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),_("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),_('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),_('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),_("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),_('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'),_('%$;+._ &;-.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!:–! )'),_('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:—! )"),_('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),_('$4™""5!7š/,#0)*4™""5!7š&&&#'),_('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),_('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),_('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),_('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),_("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),_('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),_('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),_(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),_('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),_('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),_('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),_('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),_('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),_('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),_('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),_('%$;j/&#0#*;j&&&#/"!&,)'),_('%$;j/&#0#*;j&&&#/"!&,)'),_(";k.) &;+.# &;-"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),_('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),_('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),_("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),_("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),_('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),_(";‘.# &;r"),_("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),_(";M.# &;t"),_("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),_('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),_('%24""6475/,#;{/#$+")("\'#&\'#'),_("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),_(";*.) &;+.# &;-"),_(';+. &;-.‰ &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#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),_("$;~0#*;~&"),_(';+.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'),_('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),_(";.# &;‚"),_('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),_('$;+.ƒ &;-.} &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&&&#'),_("$;y0#*;y&"),_('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),_('2Õ""6Õ7Ö'),_('2×""6×7Ø'),_('2Ù""6Ù7Ú'),_('2Û""6Û7Ü'),_('2Ý""6Ý7Þ'),_('2ß""6ß7à'),_('2á""6á7â'),_('2ã""6ã7ä'),_('2å""6å7æ'),_('2ç""6ç7è'),_('2é""6é7ê'),_("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),_("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%;“/' 8!:ì!! )"),_("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),_("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),_("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),_("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),_("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),_("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),_("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),_(";œ.) &;.# &; "),_("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),_("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),_('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),_('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),_(";6.) &;T.# &;H"),_("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),_(";¥.# &; "),_('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),_("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),_("%;©/& 8!:č! )"),_("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_(";«.# &;¬"),_('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),_('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),_(";6.# &;®"),_('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),_(";­.# &;6"),_("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),_(";6.# &;H"),_("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),_("%;ž/' 8!:ğ!! )"),_('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),_('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),_("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),_(";¹.# &; "),_("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),_("%;ž/' 8!:Ħ!! )"),_("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),_(";¾"),_("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),_("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),_(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),_("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),_("%;I/' 8!:Ĭ!! )"),_("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),_(";t.# &;w"),_("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),_("%;I/' 8!:ı!! )"),_("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),_('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),_('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),_('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),_('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),_("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),_("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),_("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),_('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),_("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),_("%;–/& 8!:Ő! )"),_('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),_('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),_("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),_("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),_("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),_('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'),_(';1." &"'),_('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),_("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),_(";¹.# &; "),_("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),_("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),_(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),_("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),_("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),_("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),_("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),_("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),_("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),_('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),_('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),_('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),_('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),_('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),_(";¾"),_('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),_(";ô.# &; "),_('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),_('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),_("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),_("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),_("$;%0#*;%&"),_("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),_('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),_('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),_("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),_(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),_('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?'),_('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),_('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),_('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),_("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),_("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),_("%;ă/,#;ă/#$+\")(\"'#&'#"),_("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),_("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),_('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),_(";™.# &;L"),_("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),_("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let d=0,c=0;const l=[{line:1,column:1}];let u,h=0,g=[],p=0;if(void 0!==t.startRule){if(!(t.startRule in i))throw new Error("Can't start parsing from rule \""+t.startRule+'".');s=i[t.startRule]}function m(){return e.substring(c,d)}function f(){return E(c,d)}function S(e,t){return{type:"literal",text:e,ignoreCase:t}}function y(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function b(t){let r,n=l[t];if(n)return n;for(r=t-1;!l[r];)r--;for(n=l[r],n={line:n.line,column:n.column};r<t;)10===e.charCodeAt(r)?(n.line++,n.column=1):n.column++,r++;return l[t]=n,n}function E(e,t){const r=b(e),i=b(t);return{source:n,start:{offset:e,line:r.line,column:r.column},end:{offset:t,line:i.line,column:i.column}}}function v(e){d<h||(d>h&&(h=d,g=[]),g.push(e))}function _(e){return e.split("").map((e=>e.charCodeAt(0)-32))}if(t.data={},u=function t(n){const i=a[n];let s=0;const l=[];let u=i.length;const h=[],g=[];let m;for(;;){for(;s<u;)switch(i[s]){case 0:g.push(o[i[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(r),s++;break;case 4:g.push([]),s++;break;case 5:g.push(d),s++;break;case 6:g.pop(),s++;break;case 7:d=g.pop(),s++;break;case 8:g.length-=i[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-i[s+1],i[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),d)),s++;break;case 13:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 14:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]===r?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 15:h.push(u),l.push(s+3+i[s+1]+i[s+2]),g[g.length-1]!==r?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 16:g[g.length-1]!==r?(h.push(u),l.push(s),u=s+2+i[s+1],s+=2):s+=2+i[s+1];break;case 17:h.push(u),l.push(s+3+i[s+1]+i[s+2]),e.length>d?(u=s+3+i[s+1],s+=3):(u=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 18:h.push(u),l.push(s+4+i[s+2]+i[s+3]),e.substr(d,o[i[s+1]].length)===o[i[s+1]]?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 19:h.push(u),l.push(s+4+i[s+2]+i[s+3]),e.substr(d,o[i[s+1]].length).toLowerCase()===o[i[s+1]]?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 20:h.push(u),l.push(s+4+i[s+2]+i[s+3]),o[i[s+1]].test(e.charAt(d))?(u=s+4+i[s+2],s+=4):(u=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 21:g.push(e.substr(d,i[s+1])),d+=i[s+1],s+=2;break;case 22:g.push(o[i[s+1]]),d+=o[i[s+1]].length,s+=2;break;case 23:g.push(r),0===p&&v(o[i[s+1]]),s+=2;break;case 24:c=g[g.length-1-i[s+1]],s+=2;break;case 25:c=d,s++;break;case 26:m=i.slice(s+4,s+4+i[s+3]).map((function(e){return g[g.length-1-e]})),g.splice(g.length-i[s+2],i[s+2],o[i[s+1]].apply(null,m)),s+=4+i[s+3];break;case 27:g.push(t(i[s+1])),s+=2;break;case 28:p++,s++;break;case 29:p--,s++;break;default:throw new Error("Invalid opcode: "+i[s]+".")}if(!(h.length>0))break;u=h.pop(),s=l.pop()}return g[0]}(s),u!==r&&d===e.length)return u;throw u!==r&&d<e.length&&v({type:"end"}),T=g,R=h<e.length?e.charAt(h):null,$=h<e.length?E(h,h+1):E(h,h),new SyntaxError(SyntaxError.buildMessage(T,R),T,R,$);var T,R,$}const parse=peg$parse;var Grammar;!function(e){e.parse=function(e,t){const r={startRule:t};try{parse(e,r)}catch(e){r.data=-1}return r.data},e.nameAddrHeaderParse=function(t){const r=e.parse(t,"Name_Addr_Header");return-1!==r?r:void 0},e.URIParse=function(t){const r=e.parse(t,"SIP_URI");return-1!==r?r:void 0}}(Grammar=Grammar||(Grammar={}));const REASON_PHRASE={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 createRandomToken(e,t=32){let r="";for(let n=0;n<e;n++){r+=Math.floor(Math.random()*t).toString(t)}return r}function getReasonPhrase(e){return REASON_PHRASE[e]||""}function newTag(){return createRandomToken(10)}function headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},r=e.toLowerCase().replace(/_/g,"-").split("-"),n=r.length;let i="";for(let e=0;e<n;e++)0!==e&&(i+="-"),i+=r[e].charAt(0).toUpperCase()+r[e].substring(1);return t[i]&&(i=t[i]),i}function utf8Length(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class IncomingMessage{constructor(){this.headers={}}addHeader(e,t){const r={raw:t};e=headerize(e),this.headers[e]?this.headers[e].push(r):this.headers[e]=[r]}getHeader(e){const t=this.headers[headerize(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[headerize(e)],r=[];if(!t)return[];for(const e of t)r.push(e.raw);return r}hasHeader(e){return!!this.headers[headerize(e)]}parseHeader(e,t=0){if(e=headerize(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const r=this.headers[e][t],n=r.raw;if(r.parsed)return r.parsed;const i=Grammar.parse(n,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(r.parsed=i,i)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[headerize(e)]=[{raw:t}]}toString(){return this.data}}class IncomingRequestMessage extends IncomingMessage{constructor(){super()}}class IncomingResponseMessage extends IncomingMessage{constructor(){super()}}class OutgoingRequestMessage{constructor(e,t,r,n,i,s,o){this.headers={},this.extraHeaders=[],this.options=OutgoingRequestMessage.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),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()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=r.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:newTag(),this.from=OutgoingRequestMessage.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=n.clone(),this.toTag=this.options.toTag,this.to=OutgoingRequestMessage.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+createRandomToken(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,r){const n={};return r&&(n.tag=r),new NameAddrHeader(e,t,n)}getHeader(e){const t=this.headers[headerize(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=[],r=this.headers[headerize(e)];if(r)for(const e of r)t.push(e);else{const r=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)r.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[headerize(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[headerize(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let r="SIP/2.0/"+t;r+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(r+=";rport"),this.setHeader("via",r),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 r of this.headers[t])e+=t+": "+r+"\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: "+utf8Length(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: "+utf8Length(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 contentTypeToContentDisposition(e){return"application/sdp"===e?"session":"render"}function fromBodyLegacy(e){const t="string"==typeof e?e:e.body,r="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:contentTypeToContentDisposition(r),contentType:r,content:t}}function isBody(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function getBody(e){let t,r,n;if(e instanceof IncomingRequestMessage&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,r=e.parseHeader("Content-Type"),n=e.body}if(e instanceof IncomingResponseMessage&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,r=e.parseHeader("Content-Type"),n=e.body}if(e instanceof OutgoingRequestMessage&&e.body)if(t=e.getHeader("Content-Disposition"),r=e.getHeader("Content-Type"),"string"==typeof e.body){if(!r)throw new Error("Header content type header does not equal body content type.");n=e.body}else{if(r&&r!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");r=e.body.contentType,n=e.body.body}if(isBody(e)&&(t=e.contentDisposition,r=e.contentType,n=e.content),n){if(r&&!t&&(t=contentTypeToContentDisposition(r)),!t)throw new Error("Content disposition undefined.");if(!r)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:r,content:n}}}var SessionState,SignalingState;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(SessionState=SessionState||(SessionState={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(SignalingState=SignalingState||(SignalingState={}));const T1=500,T2=4e3,T4=5e3,Timers={T1:T1,T2:T2,T4:T4,TIMER_B:64*T1,TIMER_D:0*T1,TIMER_F:64*T1,TIMER_H:64*T1,TIMER_I:0*T4,TIMER_J:0*T1,TIMER_K:0*T4,TIMER_L:64*T1,TIMER_M:64*T1,TIMER_N:64*T1,PROVISIONAL_RESPONSE_INTERVAL:6e4};class TransactionStateError extends Exception{constructor(e){super(e||"Transaction state error.")}}var C;!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"}(C=C||(C={}));const AllowedMethods=[C.ACK,C.BYE,C.CANCEL,C.INFO,C.INVITE,C.MESSAGE,C.NOTIFY,C.OPTIONS,C.PRACK,C.REFER,C.REGISTER,C.SUBSCRIBE];class Message{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 Notification{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 Referral{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof NameAddrHeader))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 r=((e=e||{}).extraHeaders||[]).slice(),n=this.replaces;n&&r.push("Replaces: "+decodeURIComponent(n));const i=this.referredBy;return i&&r.push("Referred-By: "+i),e.extraHeaders=r,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}class Session{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=SessionState$1.Initial,this.delegate=t.delegate,this._stateEventEmitter=new EmitterImpl,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 SessionState$1.Initial:case SessionState$1.Establishing:break;case SessionState$1.Established:return new Promise((e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})}));case SessionState$1.Terminating:case SessionState$1.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 SessionState$1.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 SessionState$1.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 SessionState$1.Established:{const t=e.requestDelegate,r=this.copyRequestOptions(e.requestOptions);return this._bye(t,r)}case SessionState$1.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 SessionState$1.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!==SessionState$1.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,r=this.copyRequestOptions(e.requestOptions);return this._info(t,r)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==SessionState$1.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new RequestPendingError("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 r=getBody(t.message);if(!r)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(SessionState$1.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(r,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===SessionState$1.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(SessionState$1.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(r,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!==SessionState$1.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(SessionState$1.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!==SessionState$1.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(SessionState$1.Terminated)}})).then((()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)}))},onTrying:e=>{}},r=e.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+AllowedMethods.toString()),r.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,r))}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 r.body=e,this.dialog.invite(t,r)})).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!==SessionState$1.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,r=this.copyRequestOptions(e.requestOptions);return this._message(t,r)}refer(e,t={}){if(this.state!==SessionState$1.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 Session&&!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 r=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,r,n)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const r=this.dialog;switch(r.sessionState){case SessionState.Initial:case SessionState.Early:throw new Error(`Invalid dialog state ${r.sessionState}`);case SessionState.AckWait:return this.stateTransition(SessionState$1.Terminating),new Promise((n=>{r.delegate={onAck:()=>{const i=r.bye(e,t);return this.stateTransition(SessionState$1.Terminated),n(i),Promise.resolve()},onAckTimeout:()=>{const i=r.bye(e,t);this.stateTransition(SessionState$1.Terminated),n(i)}}}));case SessionState.Confirmed:{const n=r.bye(e,t);return this.stateTransition(SessionState$1.Terminated),Promise.resolve(n)}case SessionState.Terminated:throw new Error(`Invalid dialog state ${r.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,r){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,r))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,r){e.ack();const n=[];t&&n.push("Reason: "+this.getReasonHeaderValue(t,r)),e.session.bye(void 0,{extraHeaders:n})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==SessionState$1.Established&&this.state!==SessionState$1.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 r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new Ack(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.Stable:{const n=getBody(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,r).catch((e=>{this.logger.error(e.message);const r=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:r}),this.stateTransition(SessionState$1.Terminated)})):Promise.resolve()}case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.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(SessionState$1.Terminated),Promise.resolve()}case SignalingState.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===SessionState$1.Established){if(this.delegate&&this.delegate.onBye){const t=new Bye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(SessionState$1.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===SessionState$1.Established)if(this.delegate&&this.delegate.onInfo){const t=new Info(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!==SessionState$1.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=Grammar.nameAddrHeaderParse(t)}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r).then((r=>{const n=e.accept({statusCode:200,extraHeaders:t,body:r});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!==SignalingState.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 r=e.reject({statusCode:488});if(this.state!==SessionState$1.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(SessionState$1.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.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===SessionState$1.Established)if(this.delegate&&this.delegate.onMessage){const t=new Message(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===SessionState$1.Established)if(this.onNotify){const t=new Notification(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){const t=new Notification(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===SessionState$1.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!==SessionState$1.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 Referral(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 r=getBody(e.message);return r&&"session"===r.contentDisposition?this.setOfferAndGetAnswer(r,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case SignalingState.Initial:return this.getOffer(e);case SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case SignalingState.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 SignalingState.Stable:return this.state!==SessionState$1.Established?Promise.resolve(void 0):this.getOffer(e);case SignalingState.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(r,n).then((e=>fromBodyLegacy(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 r=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}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 r.setDescription(e.content,n,i).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 r=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}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 r.setDescription(e.content,n,i).then((()=>r.getDescription(n,i))).then((e=>fromBodyLegacy(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 SessionState$1.Initial:e!==SessionState$1.Establishing&&e!==SessionState$1.Established&&e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Establishing:e!==SessionState$1.Established&&e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Established:e!==SessionState$1.Terminating&&e!==SessionState$1.Terminated&&t();break;case SessionState$1.Terminating:e!==SessionState$1.Terminated&&t();break;case SessionState$1.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===SessionState$1.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 r=e;let n=getReasonPhrase(e);return!n&&t&&(n=t),"SIP;cause="+r+';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 URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const r=e.remoteIdentity.friendlyName,n=e.dialog.remoteTarget.toString(),i=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${r}" <${n}?Replaces=${encodeURIComponent(`${i};to-tag=${s};from-tag=${o}`)}>`}return t}}var SIPExtension;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(SIPExtension=SIPExtension||(SIPExtension={}));const UserAgentRegisteredOptionTags={"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 Invitation extends Session{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 r=this.incomingInviteRequest.message,n=r.getHeader("require");n&&n.toLowerCase().includes("100rel")&&(this.rel100="required");const i=r.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),r.toTag=t.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout((()=>{t.reject({statusCode:480}),this.stateTransition(SessionState$1.Terminated)}),this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){const e=1e3*Number(r.getHeader("expires")||0);this.expiresTimer=setTimeout((()=>{this.state===SessionState$1.Initial&&(t.reject({statusCode:487}),this.stateTransition(SessionState$1.Terminated))}),e)}const s=this.request.getHeader("P-Asserted-Identity");s&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(s)),this._contact=this.userAgent.contact.toString();const o=r.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=r.body,this._rendertype=r.getHeader("Content-Type")),this._id=r.callId+r.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 SessionState$1.Initial:case SessionState$1.Establishing:return this.reject().then((()=>super.dispose()));case SessionState$1.Established:case SessionState$1.Terminating:case SessionState$1.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!==SessionState$1.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(SessionState$1.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(SessionState$1.Established),this._replacee&&this._replacee._bye()})).catch((e=>this.handleResponseError(e)))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==SessionState$1.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===SIPExtension.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!==SessionState$1.Initial&&this.state!==SessionState$1.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,r=e.reasonPhrase?e.reasonPhrase:getReasonPhrase(t),n=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const i=e.body?fromBodyLegacy(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:r,extraHeaders:n,body:i}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i}),this.stateTransition(SessionState$1.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===SessionState$1.Initial||this.state===SessionState$1.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new Cancel(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(SessionState$1.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=getBody(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case SignalingState.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case SignalingState.Stable:return this.setAnswer(t,r).then((()=>{}));case SignalingState.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,r);case SignalingState.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 ContentTypeUnsupportedError?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof SessionDescriptionHandlerError?this.logger.error("A session description handler occurred while sending response"):e instanceof SessionTerminatedError?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof TransactionStateError&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===SessionState$1.Initial||this.state===SessionState$1.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(SessionState$1.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(SessionState$1.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=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:r}))):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r}))))}sendProgress(e={}){const t=e.statusCode||180,r=e.reasonPhrase,n=(e.extraHeaders||[]).slice(),i=e.body?fromBodyLegacy(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:r,extraHeaders:n,body:i});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,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},r=e.statusCode||183,n=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let s;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise(((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then((e=>(s=e,this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:s})))).then((t=>{let a,d;this._dialog=t.session,t.session.delegate={onPrack:r=>{a=r,clearTimeout(c),clearTimeout(h),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then((r=>{try{d=a.accept({statusCode:200,body:r}),this.prackArrived(),e({prackRequest:a,prackResponse:d,progressResponse:t})}catch(e){o(e)}})).catch((e=>o(e))))}};const c=setTimeout((()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(h),this.reject({statusCode:504}).then((()=>o(new SessionTerminatedError))).catch((e=>o(e))))}),64*Timers.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:r,reasonPhrase:n,extraHeaders:i,body:s})}catch(e){return this.waitingForPrack=!1,void o(e)}h=setTimeout(l,u*=2)};let u=Timers.T1,h=setTimeout(l,u)})).catch((e=>{this.waitingForPrack=!1,o(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 SessionTerminatedError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Inviter extends Session{constructor(e,t,r={}){super(e,r),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!==r.earlyMedia?r.earlyMedia:this.earlyMedia,this.fromTag=newTag(),this.inviteWithoutSdp=void 0!==r.inviteWithoutSdp?r.inviteWithoutSdp:this.inviteWithoutSdp;const n=Object.assign({},r);n.params=Object.assign({},r.params);const i=r.anonymous||!1,s=e.contact.toString({anonymous:i,outbound:i?!e.contact.tempGruu:!e.contact.pubGruu});i&&e.configuration.uri&&(n.params.fromDisplayName="Anonymous",n.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(n.params.fromUri&&(o="string"==typeof n.params.fromUri?Grammar.URIParse(n.params.fromUri):n.params.fromUri),!o)throw new TypeError("Invalid from URI: "+n.params.fromUri);let a=t;if(n.params.toUri&&(a="string"==typeof n.params.toUri?Grammar.URIParse(n.params.toUri):n.params.toUri),!a)throw new TypeError("Invalid to URI: "+n.params.toUri);const d=Object.assign({},n.params);d.fromTag=this.fromTag;const c=(n.extraHeaders||[]).slice();i&&e.configuration.uri&&(c.push("P-Preferred-Identity: "+e.configuration.uri.toString()),c.push("Privacy: id")),c.push("Contact: "+s),c.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===SIPExtension.Required&&c.push("Require: 100rel"),e.configuration.sipExtensionReplaces===SIPExtension.Required&&c.push("Require: replaces"),n.extraHeaders=c;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(C.INVITE,t,o,a,d,c,undefined),this._contact=s,this._referralInviterOptions=n,this._renderbody=r.renderbody,this._rendertype=r.rendertype,r.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=r.sessionDescriptionHandlerModifiers),r.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=r.sessionDescriptionHandlerOptions),r.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=r.sessionDescriptionHandlerModifiersReInvite),r.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=r.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 SessionState$1.Initial:case SessionState$1.Establishing:return this.cancel().then((()=>super.dispose()));case SessionState$1.Established:case SessionState$1.Terminating:case SessionState$1.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!==SessionState$1.Initial&&this.state!==SessionState$1.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(SessionState$1.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="'+(getReasonPhrase(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(SessionState$1.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==SessionState$1.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(SessionState$1.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(SessionState$1.Establishing),this.sendInvite(e)))).catch((e=>{throw this.logger.log(e.message),this.state!==SessionState$1.Terminated&&this.stateTransition(SessionState$1.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(SessionState$1.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 Session))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!==SessionState$1.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,r=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),r.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=r,r.signalingState){case SignalingState.Initial:case SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(SessionState$1.Terminated),Promise.reject(new Error("Bad Media Description"));case SignalingState.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(SessionState$1.Established)})).catch((t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(SessionState$1.Terminated),t}))}case SignalingState.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(r.id),e.ack(),this.stateTransition(SessionState$1.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){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(SessionState$1.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(SessionState$1.Established),Promise.resolve()}const t=r.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(SessionState$1.Established)})).catch((t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(SessionState$1.Terminated),t}))}case SignalingState.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!==SessionState$1.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 r=e.message,n=e.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));const i=r.getHeader("require"),s=r.getHeader("rseq"),o=!!(i&&i.includes("100rel")&&s?Number(s):void 0),a=[];switch(o&&a.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),n.signalingState){case SignalingState.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case SignalingState.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case SignalingState.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(n.id,i),i.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then((()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers))).then((t=>{const r={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:r})})).catch((e=>{throw this.stateTransition(SessionState$1.Terminated),e}))}case SignalingState.Stable:if(o&&e.prack({extraHeaders:a}),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(SessionState$1.Terminated),e}))}return Promise.resolve();case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===SessionState$1.Establishing||this.state===SessionState$1.Terminating?this.stateTransition(SessionState$1.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===SessionState$1.Establishing||this.state===SessionState$1.Terminating?this.stateTransition(SessionState$1.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===SessionState$1.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class Messager{constructor(e,t,r,n="text/plain",i={}){this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};let s=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(s="string"==typeof i.params.fromUri?Grammar.URIParse(i.params.fromUri):i.params.fromUri),!s)throw new TypeError("Invalid from URI: "+i.params.fromUri);let o=t;if(i.params.toUri&&(o="string"==typeof i.params.toUri?Grammar.URIParse(i.params.toUri):i.params.toUri),!o)throw new TypeError("Invalid to URI: "+i.params.toUri);const a=i.params?Object.assign({},i.params):{},d=(i.extraHeaders||[]).slice(),c={contentDisposition:"render",contentType:n,content:r};this.request=e.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE,t,s,o,a,d,c),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var RegistererState,SubscriptionState,TransportState,UserAgentState,Levels,Parser,TransactionState;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(RegistererState=RegistererState||(RegistererState={}));class Registerer{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=RegistererState.Initial,this._waiting=!1,this._stateEventEmitter=new EmitterImpl,this._waitingEventEmitter=new EmitterImpl,this.userAgent=e;const r=e.configuration.uri.clone();if(r.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},Registerer.defaultOptions()),{registrar:r}),Registerer.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===Grammar.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,i=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,s=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(C.REGISTER,n,i,s,o,a,void 0),this.expires=this.options.expires||Registerer.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||Registerer.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:Registerer.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new URI("sip","anonymous","anonymous.invalid"),refreshFrequency:Registerer.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),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===RegistererState.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===RegistererState.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 RequestPendingError("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 r=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let r;t.message.hasHeader("expires")&&(r=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let n,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(n=t.message.parseHeader("contact",i),!n)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&equivalentURI(n.uri,this.userAgent.contact.pubGruu)){r=Number(n.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(n.uri.user===this.userAgent.contact.uri.user){r=Number(n.getParam("expires"));break}}else if(equivalentURI(n.uri,this.userAgent.contact.uri)){r=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===r)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=Grammar.URIParse(e.replace(/"/g,"")))}if(n.hasParam("pub-gruu")){const e=n.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=Grammar.URIParse(e.replace(/"/g,"")))}this.registered(r),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 r=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(r=Number.parseInt(e,void 0))}this._retryAfter=isNaN(r)?void 0:r,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(r)}unregister(e={}){if(this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==RegistererState.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===RegistererState.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 r=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(r)}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!==RegistererState.Registered&&this.stateTransition(RegistererState.Registered)}unregistered(){this.clearTimers(),this._state!==RegistererState.Unregistered&&this.stateTransition(RegistererState.Unregistered)}terminated(){this.clearTimers(),this._state!==RegistererState.Terminated&&this.stateTransition(RegistererState.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case RegistererState.Initial:e!==RegistererState.Registered&&e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&t();break;case RegistererState.Registered:e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&t();break;case RegistererState.Unregistered:e!==RegistererState.Registered&&e!==RegistererState.Terminated&&t();break;case RegistererState.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===RegistererState.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===RegistererState.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)}}Registerer.defaultExpires=600,Registerer.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(SubscriptionState=SubscriptionState||(SubscriptionState={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(TransportState=TransportState||(TransportState={})),function(e){e.Started="Started",e.Stopped="Stopped"}(UserAgentState=UserAgentState||(UserAgentState={}));class Md5{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=Md5.hexChars,r=Md5.hexOut;let n,i,s,o;for(o=0;o<4;o+=1)for(i=8*o,n=e[o],s=0;s<8;s+=2)r[i+1+s]=t.charAt(15&n),n>>>=4,r[i+0+s]=t.charAt(15&n),n>>>=4;return r.join("")}static _md5cycle(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r+=(n&i|~n&s)+t[0]-680876936|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[1]-389564586|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[2]+606105819|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[3]-1044525330|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[4]-176418897|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[5]+1200080426|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[6]-1473231341|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[7]-45705983|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[8]+1770035416|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[9]-1958414417|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[10]-42063|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[11]-1990404162|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&s)+t[12]+1804603682|0,r=(r<<7|r>>>25)+n|0,s+=(r&n|~r&i)+t[13]-40341101|0,s=(s<<12|s>>>20)+r|0,i+=(s&r|~s&n)+t[14]-1502002290|0,i=(i<<17|i>>>15)+s|0,n+=(i&s|~i&r)+t[15]+1236535329|0,n=(n<<22|n>>>10)+i|0,r+=(n&s|i&~s)+t[1]-165796510|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[6]-1069501632|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[11]+643717713|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[0]-373897302|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[5]-701558691|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[10]+38016083|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[15]-660478335|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[4]-405537848|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[9]+568446438|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[14]-1019803690|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[3]-187363961|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[8]+1163531501|0,n=(n<<20|n>>>12)+i|0,r+=(n&s|i&~s)+t[13]-1444681467|0,r=(r<<5|r>>>27)+n|0,s+=(r&i|n&~i)+t[2]-51403784|0,s=(s<<9|s>>>23)+r|0,i+=(s&n|r&~n)+t[7]+1735328473|0,i=(i<<14|i>>>18)+s|0,n+=(i&r|s&~r)+t[12]-1926607734|0,n=(n<<20|n>>>12)+i|0,r+=(n^i^s)+t[5]-378558|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[8]-2022574463|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[11]+1839030562|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[14]-35309556|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[1]-1530992060|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[4]+1272893353|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[7]-155497632|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[10]-1094730640|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[13]+681279174|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[0]-358537222|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[3]-722521979|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[6]+76029189|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^s)+t[9]-640364487|0,r=(r<<4|r>>>28)+n|0,s+=(r^n^i)+t[12]-421815835|0,s=(s<<11|s>>>21)+r|0,i+=(s^r^n)+t[15]+530742520|0,i=(i<<16|i>>>16)+s|0,n+=(i^s^r)+t[2]-995338651|0,n=(n<<23|n>>>9)+i|0,r+=(i^(n|~s))+t[0]-198630844|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[7]+1126891415|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[14]-1416354905|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[5]-57434055|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[12]+1700485571|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[3]-1894986606|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[10]-1051523|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[1]-2054922799|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[8]+1873313359|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[15]-30611744|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[6]-1560198380|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[13]+1309151649|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~s))+t[4]-145523070|0,r=(r<<6|r>>>26)+n|0,s+=(n^(r|~i))+t[11]-1120210379|0,s=(s<<10|s>>>22)+r|0,i+=(r^(s|~n))+t[2]+718787259|0,i=(i<<15|i>>>17)+s|0,n+=(s^(i|~r))+t[9]-343485551|0,n=(n<<21|n>>>11)+i|0,e[0]=r+e[0]|0,e[1]=n+e[1]|0,e[2]=i+e[2]|0,e[3]=s+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Md5.stateIdentity),this}appendStr(e){const t=this._buffer8,r=this._buffer32;let n,i,s=this._bufferLength;for(i=0;i<e.length;i+=1){if(n=e.charCodeAt(i),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(++i)-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,Md5._md5cycle(this._state,r),s-=64,r[0]=r[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,r=this._buffer32;let n,i=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-i);n--;)t[i++]=e.charCodeAt(s++);if(i<64)break;this._dataLength+=64,Md5._md5cycle(this._state,r),i=0}return this._bufferLength=i,this}appendByteArray(e){const t=this._buffer8,r=this._buffer32;let n,i=this._bufferLength,s=0;for(;;){for(n=Math.min(e.length-s,64-i);n--;)t[i++]=e[s++];if(i<64)break;this._dataLength+=64,Md5._md5cycle(this._state,r),i=0}return this._bufferLength=i,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,r=e.state,n=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],i=0;i<t.length;i+=1)this._buffer8[i]=t.charCodeAt(i)}end(e=!1){const t=this._bufferLength,r=this._buffer8,n=this._buffer32,i=1+(t>>2);let s;if(this._dataLength+=t,r[t]=128,r[t+1]=r[t+2]=r[t+3]=0,n.set(Md5.buffer32Identity.subarray(i),i),t>55&&(Md5._md5cycle(this._state,n),n.set(Md5.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),r=parseInt(e[1],16)||0;n[14]=t,n[15]=r}return Md5._md5cycle(this._state,n),e?this._state:Md5._hex(this._state)}}function MD5(e){return Md5.hashStr(e)}Md5.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Md5.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Md5.hexChars="0123456789abcdef",Md5.hexOut=[],Md5.onePassHasher=new Md5,"5d41402abc4b2a76b9719d911017c592"!==Md5.hashStr("hello")&&console.error("Md5 self test failed.");class DigestAuthentication{constructor(e,t,r,n){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=r,this.password=n,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,r){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=createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(r),!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,r;t=this.ha1,""!==t&&void 0!==t||(t=MD5(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(r=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+r)):"auth-int"===this.qop?(r=MD5(this.method+":"+this.uri+":"+MD5(e||"")),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+r)):void 0===this.qop&&(r=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+r))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Levels=Levels||(Levels={}));class Logger{constructor(e,t,r){this.logger=e,this.category=t,this.label=r}error(e){this.genericLog(Levels.error,e)}warn(e){this.genericLog(Levels.warn,e)}log(e){this.genericLog(Levels.log,e)}debug(e){this.genericLog(Levels.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 LoggerFactory{constructor(){this.builtinEnabled=!0,this._level=Levels.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:Levels.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 Logger(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new Logger(this,e);return this.loggers[e]=t,t}}genericLog(e,t,r,n){this.level>=e&&this.builtinEnabled&&this.print(e,t,r,n),this.connector&&this.connector(Levels[e],t,r,n)}print(e,t,r,n){if("string"==typeof n){const e=[new Date,t];r&&e.push(r),n=e.concat(n).join(" | ")}switch(e){case Levels.error:console.error(n);break;case Levels.warn:console.warn(n);break;case Levels.log:console.log(n);break;case Levels.debug:console.debug(n)}}}function constructOutgoingResponse(e,t){const r="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const n=t.reasonPhrase?t.reasonPhrase:getReasonPhrase(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+n+r;t.statusCode>=100&&t.statusCode,t.statusCode;const s="From: "+e.getHeader("From")+r,o="Call-ID: "+e.callId+r,a="CSeq: "+e.cseq+" "+e.method+r,d=e.getHeaders("via").reduce(((e,t)=>e+"Via: "+t+r),"");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=newTag()),c+=";tag="+e}c+=r;let l="";t.supported&&(l="Supported: "+t.supported.join(", ")+r);let u="";t.userAgent&&(u="User-Agent: "+t.userAgent+r);let h="";return t.extraHeaders&&(h=t.extraHeaders.reduce(((e,t)=>e+t.trim()+r),"")),i+=d,i+=s,i+=c,i+=a,i+=o,i+=l,i+=u,i+=h,t.body?(i+="Content-Type: "+t.body.contentType+r,i+="Content-Length: "+utf8Length(t.body.content)+r+r,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){let r=t,n=0,i=0;if(e.substring(r,r+2).match(/(^\r\n)/))return-2;for(;0===n;){if(i=e.indexOf("\r\n",r),-1===i)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?r=i+2:n=i}return n}function r(e,t,r,n){const i=t.indexOf(":",r),s=t.substring(r,i).trim(),o=t.substring(i+1,n).trim();let a;switch(s.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=Grammar.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach((t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=Grammar.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach((t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof IncomingResponseMessage&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(s.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+s+"'"}}e.getHeader=t,e.parseHeader=r,e.parseMessage=function(e,n){let i=0,s=e.indexOf("\r\n");if(-1===s)return void n.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,s),a=Grammar.parse(o,"Request_Response");let d,c;if(-1!==a){for(a.status_code?(d=new IncomingResponseMessage,d.statusCode=a.status_code,d.reasonPhrase=a.reason_phrase):(d=new IncomingRequestMessage,d.method=a.method,d.ruri=a.uri),d.data=e,i=s+2;;){if(s=t(e,i),-2===s){c=i+2;break}if(-1===s)return void n.error("malformed message");const o=r(d,e,i,s);if(o&&!0!==o)return void n.error(o.error);i=s+2}return d.hasHeader("content-length")?d.body=e.substr(c,Number(d.getHeader("content-length"))):d.body=e.substring(c),d}n.warn('error parsing first line of SIP message: "'+o+'"')}}(Parser=Parser||(Parser={}));class TransportError extends Exception{constructor(e){super(e||"Unspecified transport error.")}}class Transaction{constructor(e,t,r,n,i){this._transport=e,this._user=t,this._id=r,this._state=n,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,r),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 r=()=>{this.removeStateChangeListener(r),e()};!0===(null==t?void 0:t.once)?this.listeners.push(r):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 TransportError)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new TransportError(e.message):new TransportError,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 ServerTransaction extends Transaction{constructor(e,t,r,n,i){super(t,r,e.viaBranch,n,i),this._request=e,this.user=r}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"}(TransactionState=TransactionState||(TransactionState={}));class InviteServerTransaction extends ServerTransaction{constructor(e,t,r){super(e,t,r,TransactionState.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 TransactionState.Proceeding:if(e.method===C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch((e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})));break;case TransactionState.Accepted:if(e.method===C.INVITE)return;break;case TransactionState.Completed:if(e.method===C.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===C.ACK)return void this.stateTransition(TransactionState.Confirmed);break;case TransactionState.Confirmed:case TransactionState.Terminated:if(e.method===C.INVITE||e.method===C.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 TransactionState.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(TransactionState.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(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send non-2xx final response.")}));break;case TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send 2xx response.")}));break;case TransactionState.Completed:case TransactionState.Confirmed:case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(r),new Error(r)}retransmitAcceptedResponse(){this.state===TransactionState.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 TransactionState.Proceeding:t();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Proceeding&&t();break;case TransactionState.Confirmed:this.state!==TransactionState.Completed&&t();break;case TransactionState.Terminated:this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&this.state!==TransactionState.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===TransactionState.Accepted&&(this.L=setTimeout((()=>this.timerL()),Timers.TIMER_L)),e===TransactionState.Completed&&(this.H=setTimeout((()=>this.timerH()),Timers.TIMER_H)),e===TransactionState.Confirmed&&(this.I=setTimeout((()=>this.timerI()),Timers.TIMER_I)),e===TransactionState.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.")}))}),Timers.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===TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(TransactionState.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(TransactionState.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)}}class ClientTransaction extends Transaction{constructor(e,t,r,n,i){super(t,r,ClientTransaction.makeId(e),n,i),this._request=e,this.user=r,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 NonInviteClientTransaction extends ClientTransaction{constructor(e,t,r){super(e,t,r,TransactionState.Trying,"sip.transaction.nict"),this.F=setTimeout((()=>this.timerF()),Timers.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 TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Completed:case TransactionState.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const r=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout((()=>this.timerK()),Timers.TIMER_K)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))}timerK(){this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}}class Dialog{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const r=t.getHeaders("record-route").reverse(),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const i=n.uri,s=e.cseq,o=e.callId,a=e.fromTag,d=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const c=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+d,early:t.statusCode<200,callId:o,localTag:a,remoteTag:d,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:c,remoteURI:l,remoteTarget:i,routeSet:r,secure:!1}}static initialDialogStateForUserAgentServer(e,t,r=!1){const n=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const s=i.uri,o=e.cseq,a=e.callId,d=t,c=e.fromTag,l=e.from.uri;return{id:a+d+c,early:r,callId:a,localTag:d,remoteTag:c,localSequenceNumber:undefined,remoteSequenceNumber:o,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!==C.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 r=this.remoteURI,n=this.remoteTag,i=this.localURI,s=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const d=this.remoteTarget,c=this.routeSet,l=t&&t.extraHeaders,u=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,d,i,r,{callId:o,cseq:a,fromTag:s,toTag:n,routeSet:c},l,u)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class InviteClientTransaction extends ClientTransaction{constructor(e,t,r){super(e,t,r,TransactionState.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout((()=>this.timerB()),Timers.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 r="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(r,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 TransactionState.Calling:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.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(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.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 TransactionState.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,r=this.request.callId,n=this.request.cseq,i=this.request.getHeader("from"),s=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!s)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let d=`ACK ${t} SIP/2.0\r\n`;a&&(d+=`Route: ${a}\r\n`),d+=`Via: ${o}\r\n`,d+=`To: ${s}\r\n`,d+=`From: ${i}\r\n`,d+=`Call-ID: ${r}\r\n`,d+=`CSeq: ${n} ACK\r\n`,d+="Max-Forwards: 70\r\n",d+="Content-Length: 0\r\n\r\n",this.send(d).catch((e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")}))}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Calling:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Calling&&r();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Calling&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Calling&&this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}this.B&&(clearTimeout(this.B),this.B=void 0),TransactionState.Proceeding,e===TransactionState.Completed&&(this.D=setTimeout((()=>this.timerD()),Timers.TIMER_D)),e===TransactionState.Accepted&&(this.M=setTimeout((()=>this.timerM()),Timers.TIMER_M)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)}}class UserAgentClient{constructor(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,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 r=this.core.makeOutgoingRequestMessage(C.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 r.branch=this.message.branch,this.message.headers.Route&&(r.headers.Route=this.message.headers.Route),e&&r.setHeader("Reason",e),this.transaction.state===TransactionState.Proceeding?new UserAgentClient(NonInviteClientTransaction,this.core,r):this.transaction.addStateChangeListener((()=>{this.transaction&&this.transaction.state===TransactionState.Proceeding&&new UserAgentClient(NonInviteClientTransaction,this.core,r)}),{once:!0}),r}authenticationGuard(e,t){const r=e.statusCode;if(!r)throw new Error("Response status code undefined.");if(401!==r&&407!==r)return!0;let n,i;if(401===r?(n=e.parseHeader("www-authenticate"),i="authorization"):(n=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!n)return this.logger.warn(r+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(r+" 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(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new IncomingResponseMessage;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 IncomingResponseMessage;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===TransactionState.Terminated&&(this.core.userAgentClients.delete(r),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 r=t.id+t.request.method;this.core.userAgentClients.set(r,this)}}class ByeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.BYE,r);super(NonInviteClientTransaction,e.userAgentCore,n,t),e.dispose()}}class NonInviteServerTransaction extends ServerTransaction{constructor(e,t,r){super(e,t,r,TransactionState.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 TransactionState.Trying:break;case TransactionState.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 TransactionState.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 TransactionState.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 TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(TransactionState.Proceeding),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send provisional response.")}));if(e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch((e=>{this.logTransportError(e,"Failed to send final response.")}));break;case TransactionState.Completed:return;case TransactionState.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const r=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(r),new Error(r)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const r=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.J=setTimeout((()=>this.timerJ()),Timers.TIMER_J)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)}}class UserAgentServer{constructor(e,t,r,n){this.transactionConstructor=e,this.core=t,this.message=r,this.delegate=n,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=r.toTag?r.toTag:newTag(),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 TransactionStateError(`${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 TransactionStateError(`${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 TransactionStateError(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const r=t.statusCode;if(r<300||r>399)throw new TypeError(`Invalid statusCode: ${r}`);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 TransactionStateError(`${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 TransactionStateError(`${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 InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding||this.transaction.state===TransactionState.Accepted;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.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=constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===TransactionState.Terminated&&(this.core.userAgentServers.delete(r),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 r=t.id;this.core.userAgentServers.set(t.id,this)}}class ByeUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r)}}class InfoUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.INFO,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}class InfoUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r)}}class MessageUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class MessageUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r)}}class NotifyUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.NOTIFY,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}function instanceOfDialog(e){return void 0!==e.userAgentCore}class NotifyUserAgentServer extends UserAgentServer{constructor(e,t,r){const n=instanceOfDialog(e)?e.userAgentCore:e;super(NonInviteServerTransaction,n,t,r)}}class PrackUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.PRACK,r);super(NonInviteClientTransaction,e.userAgentCore,n,t),e.signalingStateTransition(n)}}class PrackUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e.userAgentCore,t,r),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class ReInviteUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.INVITE,r);super(InviteClientTransaction,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 ReInviteUserAgentServer extends UserAgentServer{constructor(e,t,r){super(InviteServerTransaction,e.userAgentCore,t,r),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),r=this.dialog,n=Object.assign(Object.assign({},t),{session:r});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),n}progress(e={statusCode:180}){const t=super.progress(e),r=this.dialog,n=Object.assign(Object.assign({},t),{session:r});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 ReferUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.REFER,r);super(NonInviteClientTransaction,e.userAgentCore,n,t)}}function instanceOfSessionDialog(e){return void 0!==e.userAgentCore}class ReferUserAgentServer extends UserAgentServer{constructor(e,t,r){const n=instanceOfSessionDialog(e)?e.userAgentCore:e;super(NonInviteServerTransaction,n,t,r)}}class SessionDialog extends Dialog{constructor(e,t,r,n){super(t,r),this.initialTransaction=e,this._signalingState=SignalingState.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=n,e instanceof InviteServerTransaction&&(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=SignalingState.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?SessionState.Early:this.ackWait?SessionState.AckWait:this._signalingState===SignalingState.Closed?SessionState.Terminated:SessionState.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 InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const r=this.createOutgoingRequestMessage(C.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(r),this.signalingStateTransition(r),{message:r}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==TransactionState.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 ByeUserAgentClient(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 InfoUserAgentClient(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 ReInviteUserAgentClient(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 r=this.createOutgoingRequestMessage(C.MESSAGE,t);return new MessageUserAgentClient(this.core,r,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 NotifyUserAgentClient(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new PrackUserAgentClient(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 ReferUserAgentClient(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==C.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===C.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.")},r=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:r}),void t();if(this.ackWait&&this.signalingState!==SignalingState.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:r}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:r});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===C.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case C.BYE:{const t=new ByeUserAgentServer(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case C.INFO:{const t=new InfoUserAgentServer(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case C.INVITE:{const t=new ReInviteUserAgentServer(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case C.MESSAGE:{const t=new MessageUserAgentServer(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case C.NOTIFY:{const t=new NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case C.PRACK:{const t=new PrackUserAgentServer(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case C.REFER:{const t=new ReferUserAgentServer(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 InviteClientTransaction)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"),r=e.getHeader("rseq"),n=t&&t.includes("100rel")&&r?Number(r):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!==SignalingState.HaveLocalOffer&&this.signalingState!==SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof IncomingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof IncomingResponseMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof OutgoingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(isBody(e))switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof InviteServerTransaction){const e=this.initialTransaction;let t=Timers.T1;const r=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Timers.T2),this.invite2xxTimer=setTimeout(r,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,t);const n=()=>{e.state===TransactionState.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 InviteServerTransaction){const e=this.reinviteUserAgentServer.transaction;let t=Timers.T1;const r=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Timers.T2),this.invite2xxTimer=setTimeout(r,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,t);const n=()=>{e.state===TransactionState.Terminated&&(e.removeStateChangeListener(n),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(n)}}}class InviteUserAgentClient extends UserAgentClient{constructor(e,t,r){super(InviteClientTransaction,e,t,r),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=r}dispose(){this.earlyDialogs.forEach((e=>e.dispose())),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===TransactionState.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=Dialog.initialDialogStateForUserAgentClient(this.message,e);let r=this.earlyDialogs.get(t.id);if(!r){const e=this.transaction;if(!(e instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");r=new SessionDialog(e,this.core,t),this.earlyDialogs.set(r.id,r)}if(!r.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");r.signalingState!==SignalingState.Initial&&r.signalingState!==SignalingState.HaveLocalOffer||r.signalingStateTransition(e);const n=r;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=Dialog.initialDialogStateForUserAgentClient(this.message,e);let r=this.confirmedDialogs.get(t.id);if(r){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(r=this.earlyDialogs.get(t.id),r)r.confirm(),r.recomputeRouteSet(e),this.earlyDialogs.delete(r.id),this.confirmedDialogs.set(r.id,r);else{const e=this.transaction;if(!(e instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");r=new SessionDialog(e,this.core,t),this.confirmedDialogs.set(r.id,r)}r.signalingState!==SignalingState.Initial&&r.signalingState!==SignalingState.HaveLocalOffer||r.signalingStateTransition(e);const n=r;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 InviteUserAgentServer extends UserAgentServer{constructor(e,t,r){super(InviteServerTransaction,e,t,r),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new TransactionStateError(`${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 InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new SessionDialog(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),r=`Contact: ${this.core.configuration.contact.toString()}`,n="Allow: "+AllowedMethods.toString();if(!e.body)if(this.confirmedDialog.signalingState===SignalingState.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===SignalingState.Initial||this.confirmedDialog.signalingState===SignalingState.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(r);const i=super.accept(e),s=this.confirmedDialog,o=Object.assign(Object.assign({},i),{session:s});return e.body&&this.confirmedDialog.signalingState!==SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new TransactionStateError(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new SessionDialog(e,this.core,t)}const t=this.message.getHeaders("record-route").map((e=>`Record-Route: ${e}`)),r=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r);const n=super.progress(e),i=this.earlyDialog,s=Object.assign(Object.assign({},n),{session:i});return e.body&&this.earlyDialog.signalingState!==SignalingState.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 PublishUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class RegisterUserAgentClient extends UserAgentClient{constructor(e,t,r){super(NonInviteClientTransaction,e,t,r)}}class RegisterUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r),this.core=e}}class ReSubscribeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=e.createOutgoingRequestMessage(C.SUBSCRIBE,r);super(NonInviteClientTransaction,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 SubscriptionDialog extends Dialog{constructor(e,t,r,n,i,s){super(n,i),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=r,this.logger=n.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const r=t.getHeaders("record-route"),n=t.parseHeader("contact");if(!n)throw new Error("Contact undefined.");if(!(n instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");const i=n.uri,s=e.cseq,o=e.callId,a=e.fromTag,d=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!d)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+d,early:!1,callId:o,localTag:a,remoteTag:d,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:r,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===C.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: "+AllowedMethods.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 r;if(this.subscriptionState!==SubscriptionState.Pending&&this.subscriptionState!==SubscriptionState.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 ReSubscribeUserAgentClient(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(r=t.extraHeaders)||void 0===r?void 0:r.includes("Expires: 0"))||(this.N=setTimeout((()=>this.timerN()),Timers.TIMER_N)),n}terminate(){this.stateTransition(SubscriptionState.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+AllowedMethods.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 r=e.parseHeader("Subscription-State");if(!r||!r.state)return void this.core.replyStateless(e,{statusCode:489});const n=r.state,i=r.expires?Math.max(r.expires,0):void 0;switch(n){case"pending":this.stateTransition(SubscriptionState.Pending,i);break;case"active":this.stateTransition(SubscriptionState.Active,i);break;case"terminated":this.stateTransition(SubscriptionState.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const s=new NotifyUserAgentServer(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 r=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case SubscriptionState.Initial:case SubscriptionState.NotifyWait:return void r();case SubscriptionState.Pending:if(this.subscriptionState!==SubscriptionState.NotifyWait&&this.subscriptionState!==SubscriptionState.Pending)return void r();break;case SubscriptionState.Active:case SubscriptionState.Terminated:if(this.subscriptionState!==SubscriptionState.NotifyWait&&this.subscriptionState!==SubscriptionState.Pending&&this.subscriptionState!==SubscriptionState.Active)return void r();break;default:return void r()}e===SubscriptionState.Pending&&t&&(this.subscriptionExpires=t),e===SubscriptionState.Active&&t&&(this.subscriptionExpires=t),e===SubscriptionState.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==SubscriptionState.Terminated&&(this.stateTransition(SubscriptionState.Terminated),this.onTerminated())}}class SubscribeUserAgentClient extends UserAgentClient{constructor(e,t,r){const n=t.getHeader("Event");if(!n)throw new Error("Event undefined");const i=t.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(NonInviteClientTransaction,e,t,r),this.delegate=r,this.subscriberId=t.callId+t.fromTag+n,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=n,this.subscriptionState=SubscriptionState.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 r=e.message.parseHeader("Subscription-State");if(!r||!r.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const n=r.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=r.expires?Math.min(this.subscriptionExpires,Math.max(r.expires,0)):this.subscriptionExpires,n){case"pending":this.subscriptionState=SubscriptionState.Pending;break;case"active":this.subscriptionState=SubscriptionState.Active;break;case"terminated":this.subscriptionState=SubscriptionState.Terminated;break;default:throw new Error(`Unrecognized state ${n}.`)}if(this.subscriptionState!==SubscriptionState.Terminated){const t=SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,r=this.dialog;this.delegate.onNotify({request:t,subscription:r})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout((()=>this.timerN()),Timers.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 SubscribeUserAgentServer extends UserAgentServer{constructor(e,t,r){super(NonInviteServerTransaction,e,t,r),this.core=e}}const acceptedBodyTypes=["application/sdp","application/dtmf-relay"];class UserAgentCore{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 InviteUserAgentClient(this,e,t)}message(e,t){return new MessageUserAgentClient(this,e,t)}publish(e,t){return new PublishUserAgentClient(this,e,t)}register(e,t){return new RegisterUserAgentClient(this,e,t)}subscribe(e,t){return new SubscribeUserAgentClient(this,e,t)}request(e,t){return new UserAgentClient(NonInviteClientTransaction,this,e,t)}makeOutgoingRequestMessage(e,t,r,n,i,s,o){const a=this.configuration.sipjsId,d=this.configuration.displayName,c=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,u=this.configuration.supportedOptionTags.slice();e===C.REGISTER&&u.push("path","gruu"),e===C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&u.push("gruu");const h={callIdPrefix:a,forceRport:c,fromDisplayName:d,hackViaTcp:l,optionTags:u,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},h),i);return new OutgoingRequestMessage(e,t,r,n,g,s,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const r=this.configuration.userAgentHeaderFieldValue,n=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:r,supported:n});const i=constructOutgoingResponse(e,t);return this.transport.send(i.message).catch((t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)})),i}receiveRequestFromTransport(e){const t=e.viaBranch,r=this.userAgentServers.get(t);e.method===C.ACK&&r&&r.transaction.state===TransactionState.Accepted&&r instanceof InviteUserAgentServer?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==C.CANCEL?r?r.transaction.receiveRequest(e):this.receiveRequest(e):r?(this.replyStateless(e,{statusCode:200}),r.transaction instanceof InviteServerTransaction&&r.transaction.state===TransactionState.Proceeding&&r instanceof InviteUserAgentServer&&r.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!AllowedMethods.includes(e.method)){const t="Allow: "+AllowedMethods.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,r=e=>!!e&&e.user===t.user;if(!r(this.configuration.aor)&&!(r(this.configuration.contact.uri)||r(this.configuration.contact.pubGruu)||r(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==C.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===C.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const r=e.callId+e.toTag+t.event,n=this.subscribers.get(r);if(n){const t=new NotifyUserAgentServer(this,e);return void n.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,r=this.dialogs.get(t);if(r){if(e.method===C.OPTIONS){const t="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,r]})}r.receiveRequest(e)}else e.method!==C.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case C.ACK:break;case C.BYE:this.replyStateless(e,{statusCode:481});break;case C.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case C.INFO:this.replyStateless(e,{statusCode:405});break;case C.INVITE:{const t=new InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case C.MESSAGE:{const t=new MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case C.NOTIFY:{const t=new NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case C.OPTIONS:{const t="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,r]})}break;case C.REFER:{const t=new ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case C.REGISTER:{const t=new RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case C.SUBSCRIBE:{const t=new SubscribeUserAgentServer(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,r=this.userAgentClients.get(t);r?r.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}function defaultMediaStreamFactory(){return 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)}function defaultPeerConnectionConfiguration(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}}class SessionDescriptionHandler{constructor(e,t,r){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=r,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==r?void 0:r.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 r,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 i=null===(r=null==e?void 0:e.offerOptions)||void 0===r?void 0:r.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(i,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 r=this._peerConnection.getSenders();if(0===r.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const n=r[0].dtmf;if(!n)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{n.insertDTMF(e,i,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,r){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},r))).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,r=this._localMediaStream,n=[],i=e=>{const i=e.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const s=t.getSenders().find((e=>e.track&&e.track.kind===i));s?n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),e()})).then((()=>s.replaceTrack(e).then((()=>{const t=r.getTracks().find((e=>e.kind===i));t&&(t.stop(),r.removeTrack(t),SessionDescriptionHandler.dispatchRemoveTrackEvent(r,t)),r.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(r,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),e}))))):n.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),e()})).then((()=>{try{t.addTrack(e,r)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),e}r.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(r,e)})))},s=e.getAudioTracks();s.length&&i(s[0]);const o=e.getVideoTracks();return o.length&&i(o[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 r;switch(this._peerConnection.signalingState){case"stable":r="offer";break;case"have-local-offer":r="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:r}):(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),SessionDescriptionHandler.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),SessionDescriptionHandler.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),SessionDescriptionHandler.dispatchRemoveTrackEvent(t,e)})),t.addTrack(e),SessionDescriptionHandler.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 r=t(e.direction);e.direction!==r&&(e.direction=r)}}))}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"})(),r=(()=>{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!==r&&(e.direction=r)}))}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,r)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=r,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 r;const n=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.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 r;const n=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var r;const n=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${n}`),"complete"===n&&this.iceGatheringComplete(),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.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 r;const n=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${n}`),(null===(r=this._peerConnectionDelegate)||void 0===r?void 0:r.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const r=e.track.kind,n=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${r} ${n}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function defaultSessionDescriptionHandlerFactory(e){return(t,r)=>{void 0===e&&(e=defaultMediaStreamFactory());const n={iceGatheringTimeout:void 0!==(null==r?void 0:r.iceGatheringTimeout)?null==r?void 0:r.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},defaultPeerConnectionConfiguration()),null==r?void 0:r.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new SessionDescriptionHandler(i,e,n)}}class Transport{constructor(e,t){if(this._state=TransportState.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new EmitterImpl,this.logger=e,t){const e=t,r=null==e?void 0:e.wsServers,n=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==r){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)}r&&!t.server&&("string"==typeof r&&(t.server=r),r instanceof Array&&(t.server=r[0]))}this.configuration=Object.assign(Object.assign({},Transport.defaultOptions),t);const r=this.configuration.server,n=Grammar.parse(r,"absoluteURI");if(-1===n)throw this.logger.error(`Invalid WebSocket Server URL "${r}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(n.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${r}"`),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===TransportState.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case TransportState.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case TransportState.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case TransportState.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)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,r)=>{this.connectResolve=t,this.connectReject=r,this.transitionState(TransportState.Disconnected,e)}))}return this.connectPromise=new Promise(((t,r)=>{this.connectResolve=t,this.connectReject=r,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 TransportState.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case TransportState.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.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,r)=>{this.disconnectResolve=t,this.disconnectReject=r;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!==TransportState.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 r=`WebSocket closed ${this.server} (code: ${e.code})`,n=this.disconnectPromise?void 0:new Error(r);n&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(r),this._ws=void 0,this.transitionState(TransportState.Disconnected,n)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const r=e.data;let n;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{n=(new TextDecoder).decode(new Uint8Array(r))}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=r,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===TransportState.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===TransportState.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(TransportState.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 StateTransitionError("Loop detected.")}transitionState(e,t){const r=()=>{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 TransportState.Connecting:e!==TransportState.Connected&&e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Connected:e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnecting:e!==TransportState.Connecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnected:e!==TransportState.Connecting&&r();break;default:throw new Error("Unknown state.")}const n=this._state;this._state=e;const i=this.connectResolve,s=this.connectReject;n===TransportState.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(n===TransportState.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===TransportState.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===TransportState.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===TransportState.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!s)throw new Error("Connect reject undefined.");e===TransportState.Connected?i():s(t||new Error("Connect aborted."))}if(n===TransportState.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===TransportState.Disconnected?o():a(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}}Transport.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};const LIBRARY_VERSION="0.21.1";class UserAgent{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=UserAgentState.Stopped,this._stateEventEmitter=new EmitterImpl,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},UserAgent.defaultOptions()),{sipjsId:createRandomToken(5)}),{uri:new URI("sip","anonymous."+createRandomToken(6),"anonymous.invalid")}),{viaHost:createRandomToken(12)+".invalid"}),UserAgent.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,r=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+r}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new LoggerFactory,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=Levels.error;break;case"warn":this.loggerFactory.level=Levels.warn;break;case"log":this.loggerFactory.level=Levels.log;break;case"debug":this.loggerFactory.level=Levels.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,r=t.maxReconnectionAttempts,n=t.reconnectionTimeout;if(void 0!==r){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!==r&&(this.options.reconnectionAttempts=r)}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:UserAgent.newUUID(),-1===Grammar.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return Grammar.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:defaultSessionDescriptionHandlerFactory(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:SIPExtension.Unsupported,sipExtensionReplaces:SIPExtension.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Transport,transportOptions:{},uri:new URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+LIBRARY_VERSION,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,r)=>(void 0!==e[r]&&(t[r]=e[r]),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===UserAgentState.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then((()=>this.transport.connect()))}start(){return this.state===UserAgentState.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(UserAgentState.Started),this.transport.connect())}async stop(){if(this.state===UserAgentState.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(UserAgentState.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),r=Object.assign({},this._sessions),n=Object.assign({},this._subscriptions),i=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 r)r[e]&&await r[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 i.dispose().catch((e=>{throw this.logger.error(e.message),e})),this.logger.log("Dispose of core"),s.dispose(),this.transitionState(UserAgentState.Stopped)}_makeInviter(e,t){return new Inviter(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,r=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((r=>{this.logger.error(r.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)}))}),1===e?0:1e3*r))}initContact(){const e=""!==this.options.contactName?this.options.contactName:createRandomToken(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new URI("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const r=e.anonymous||!1,n=e.outbound||!1,i=e.register||!1;let s="<";return s+=r?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:i?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===SIPExtension.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===SIPExtension.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter((e=>UserAgentRegisteredOptionTags[e]))),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const r={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,r=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new DigestAuthentication(this.getLoggerFactory(),r,e,t)},transportAccessor:()=>this.transport};return new UserAgentCore(r,{onInvite:e=>{var t;const r=new Invitation(this,e);if(e.delegate={onCancel:e=>{r._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==SIPExtension.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 i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const s=e+n+i,o=this.userAgentCore.dialogs.get(s);if(!o)return void r.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void r.reject({statusCode:486});const a=this._sessions[e+i]||this._sessions[e+n]||void 0;if(!a)throw new Error("Session does not exist.");r._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return r.autoSendAnInitialProvisionalResponse?void r.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(r)})):void this.delegate.onInvite(r);r.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new Message(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new Notification(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!==UserAgentState.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==UserAgentState.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=Parser.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===UserAgentState.Stopped&&t instanceof IncomingRequestMessage)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const r=()=>{const e=["from","to","call_id","cseq","via"];for(const r of e)if(!t.hasHeader(r))return this.logger.warn(`Missing mandatory header field : ${r}.`),!1;return!0};if(t instanceof IncomingRequestMessage){if(!r())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=utf8Length(t.body),n=t.getHeader("content-length");if(n&&e<Number(n))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof IncomingResponseMessage){if(!r())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=utf8Length(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 IncomingRequestMessage)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof IncomingResponseMessage))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const r=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case UserAgentState.Started:e!==UserAgentState.Stopped&&r();break;case UserAgentState.Stopped:e!==UserAgentState.Started&&r();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 ON_USER_AGENT="onUserAgent",ON_REGISTERED="onRegistered",ON_UNREGISTERED="onUnRegistered",ON_PROGRESS$1="onProgress",ON_CALL_ACCEPTED="onCallAccepted",ON_CALL_ANSWERED="onCallAnswered",ON_CALL_INCOMING="onCallIncoming",ON_CALL_OUTGOING="onCallOutgoing",ON_CALL_MUTED="onCallMuted",ON_CALL_UNMUTED="onCallUnmuted",ON_CALL_RESUMED="onCallResumed",ON_CALL_HELD="onCallHeld",ON_CALL_UNHELD="onCallUnHeld",ON_CAMERA_DISABLED="onCameraDisabled",ON_CAMERA_RESUMED="onCameraResumed",ON_CALL_CANCELED="onCallCanceled",ON_CALL_FAILED="onCallFailed",ON_CALL_REJECTED="onCallRejected",ON_CALL_ENDED="onCallEnded",ON_CALL_ENDING="onCallEnding",ON_MESSAGE="onMessage",ON_REINVITE$1="reinvite",ON_TRACK$1="onTrack",ON_AUDIO_STREAM="onAudioStream",ON_VIDEO_STREAM="onVideoStream",ON_REMOVE_STREAM="onRemoveStream",ON_SHARE_SCREEN_STARTED="onScreenShareStarted",ON_SHARE_SCREEN_ENDING="onScreenShareEnding",ON_SHARE_SCREEN_ENDED="onScreenShareEnded",ON_TERMINATE_SOUND="terminateSound",ON_PLAY_RING_SOUND="playRingingSound",ON_PLAY_INBOUND_CALL_SIGNAL_SOUND="playInboundCallSignalSound",ON_PLAY_HANGUP_SOUND="playHangupSound",ON_PLAY_PROGRESS_SOUND="playProgressSound",ON_VIDEO_INPUT_CHANGE="videoInputChange",ON_CALL_ERROR="onCallError",ON_MESSAGE_TRACK_UPDATED="onTrackUpdated",ON_NETWORK_STATS$1="onNetworkStats",ON_CHAT="phone/ON_CHAT",ON_SIGNAL="phone/ON_SIGNAL",ON_DISCONNECTED$1="onDisconnected",ON_EARLY_MEDIA$1="onEarlyMedia",MESSAGE_TYPE_CHAT="message/TYPE_CHAT",MESSAGE_TYPE_SIGNAL="message/TYPE_SIGNAL",events$1=[ON_USER_AGENT,ON_REGISTERED,ON_UNREGISTERED,ON_PROGRESS$1,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_CALL_FAILED,ON_CALL_ENDED,ON_CALL_REJECTED,ON_MESSAGE,ON_REINVITE$1,ON_TRACK$1,ON_AUDIO_STREAM,ON_VIDEO_STREAM,ON_REMOVE_STREAM,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_SHARE_SCREEN_STARTED,ON_CALL_ERROR,ON_CHAT,ON_SIGNAL,ON_NETWORK_STATS$1,ON_DISCONNECTED$1,ON_EARLY_MEDIA$1],logger$8=IssueReporter$1.loggerFor("webrtc-phone");class WebRTCPhone extends Emitter{client;allowVideo;callSessions;incomingSessions;currentSipSession;currentCallSession;audioOutputDeviceId;audioRingDeviceId;audioOutputVolume;audioRingVolume;ringingEnabled;acceptedSessions;rejectedSessions;ignoredSessions;currentScreenShare;lastScreenShare;shouldSendReinvite;constructor(e,t,r=!1,n){super(),this.client=e,this.allowVideo=r,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 logger$8.info("WebRTC register",{client:!!this.client}),this.client?this.client.register().then((()=>(logger$8.info("WebRTC register, registered"),this.bindClientEvents()))).catch((e=>{console.error("register error",e,e.message,e.stack),logger$8.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&&(logger$8.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,r=!1,n=!1,i=!1){const s=this.findSipSession(e);if(logger$8.info("WebRTC phone - send reinvite",{sessionId:s?s.id:null,constraints:t,audioOnly:n,conference:r,iceRestart:i}),!s)return;const o=t?.screen,a=o||t?.video;if(!t||a){if(a){if(!await this._upgradeToVideo(e,t,r))return}return this.client.reinvite(s,t,r,n,i)}this._downgradeToAudio(e)}getUserAgent(){return this.client?.config?.userAgentString||"webrtc-phone"}startHeartbeat(){logger$8.info("WebRTC phone - start heartbeat",{client:!!this.client,hasHeartbeat:this.client.hasHeartbeat()}),this.client&&!this.client.hasHeartbeat()&&this.client.startHeartbeat()}stopHeartbeat(){logger$8.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(){logger$8.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 r=this.findSipSession(e);return!!r&&(logger$8.info("Downgrade to audio",{id:e?e.getId():null,withMessage:t}),this.client.downgradeToAudio(r),e&&(e.cameraEnabled=!1,this._updateCallSession(e)),t&&this._sendReinviteMessage(e,!1),!0)}async _upgradeToVideo(e,t,r){const n=this.findSipSession(e);if(!n)return Promise.resolve(!1);logger$8.info("Upgrade to video",{id:e?e.getId():null,constraints:t,isConference:r});const i=t&&!!t.screen,s=t&&t.desktop,o=n.sessionDescriptionHandlerOptionsReInvite,a=o?.audioOnly,d=await this.client.upgradeToVideo(n,t,r);return e&&(e.cameraEnabled=!0,this._updateCallSession(e)),!d||(this._sendReinviteMessage(e,!0),i&&this._onScreenSharing(d,n,e,!1,s),!(!r||!a))}_sendReinviteMessage(e,t){const r=this.findSipSession(e);logger$8.info("Sending reinvite message",{id:e?e.getId():null,isUpgrade:t}),setTimeout((()=>{this.sendMessage(r,JSON.stringify({type:MESSAGE_TYPE_SIGNAL,content:{type:ON_MESSAGE_TRACK_UPDATED,update:t?"upgrade":"downgrade",sipCallId:r&&this.getSipSessionId(r),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 Invitation){const r=e._onCancel.bind(e);e._onCancel=n=>{logger$8.trace("on sip session canceled",{callId:n.callId,sipSessionId:t}),r(n);const i=-1!==n.data.indexOf("cause=26")&&-1!==n.data.indexOf("completed elsewhere"),s=this._createCallSession(e);delete this.callSessions[t],this.eventEmitter.emit(ON_CALL_CANCELED,s,i)}}if(e.stateChange.addListener((t=>{switch(t){case SessionState$1.Terminating:logger$8.info("WebRTC phone - call terminating",{sipId:e.id}),this.eventEmitter.emit(ON_CALL_ENDING,this._createCallSession(e));break;case SessionState$1.Terminated:{logger$8.info("WebRTC phone - call terminated",{sipId:e.id});const t=this._createCallSession(e);t.endTime=new Date;const r=this._onCallTerminated(e);return this.eventEmitter.emit(ON_CALL_ENDED,t,r)}}})),!e.sessionDescriptionHandler)return;const r=e.sessionDescriptionHandler.peerConnection;r?(r.ontrack=t=>{const r=t,[n]=r.streams,i=r&&r.track&&r.track.kind;return logger$8.info("on track stream called on the peer connection",{callId:this.getSipSessionId(e),streamId:n?n.id:null,tracks:n?n.getTracks():null,kind:i}),"audio"===i?this.eventEmitter.emit(ON_AUDIO_STREAM,n):this.eventEmitter.emit(ON_VIDEO_STREAM,n,r.track.id,r,e)},r.onremovestream=e=>{logger$8.info("on remove stream called on the peer connection",{id:e.stream.id,tracks:e.stream.getTracks()}),this.eventEmitter.emit(ON_REMOVE_STREAM,e.stream)}):logger$8.info("null peer connection")}async startScreenSharing(e,t){logger$8.info("WebRTC - start screen sharing",{constraints:e,id:t?t.getId():null});const r=await this.client.getStreamFromConstraints(e);if(!r)throw new Error(`Can't create media stream for screensharing with: ${JSON.stringify(e)}`);const n=r.getVideoTracks()[0],i=this.currentSipSession,s=i&&this.client.getPeerConnection(this.getSipSessionId(i)),o=s&&s.getSenders&&s.getSenders().find((e=>e&&e.track&&"video"===e.track.kind)),a=i&&this.client.getLocalStream(this.getSipSessionId(i)),d=a?a.getTracks().find((e=>"video"===e.kind)):null,c=!!d;return d&&a&&(d.enabled=!1,d.stop(),a.removeTrack(d)),a&&a.addTrack(n),o&&o.replaceTrack(n),this._onScreenSharing(r,i,t,c,e.desktop),r}async stopScreenSharing(e=!0,t){if(!this.currentScreenShare)return;logger$8.info("WebRTC phone - stop screen sharing",{restoreLocalStream:e});let r=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),i={audio:!1,video:this.currentScreenShare.hadVideo};this._downgradeToAudio(e,!1),await new Promise((e=>setTimeout(e,500))),r=await this.sendReinvite(e,i,n)}}catch(e){console.warn(e)}const n=this.currentSipSession;return this.eventEmitter.emit(ON_SHARE_SCREEN_ENDED,t&&n?this._createCallSession(n,t,{screensharing:!1}):null),this.currentScreenShare=null,r}_onScreenSharing(e,t,r,n,i){const s=e.getVideoTracks()[0],o=this.getSipSessionId(t),a=this.client.getPeerConnection(o),d=a&&a.getSenders&&a.getSenders().find((e=>e&&e.track&&"video"===e.track.kind));logger$8.info("WebRTC phone - on screensharing",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),s&&(s.onended=()=>{logger$8.info("WebRTC phone - on screenshare ended",{hadVideo:n,id:this.getSipSessionId(t),screenTrack:s}),this.eventEmitter.emit(ON_SHARE_SCREEN_ENDING,this._createCallSession(t,r))}),this.currentScreenShare={stream:e,hadVideo:n,sender:d,sipSessionId:o,desktop:i},this.client.setLocalMediaStream(this.getSipSessionId(t),e),this.eventEmitter.emit(ON_SHARE_SCREEN_STARTED,this._createCallSession(t,r,{screensharing:!0}),e)}_onCallAccepted(e,t){logger$8.info("WebRTC phone - on call accepted",{sipId:e.id,cameraEnabled:t});const r=this._createAcceptedCallSession(e,t);this.currentSipSession&&!this.isCurrentCallSipSession(r)&&(logger$8.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=r,this.eventEmitter.emit(ON_TERMINATE_SOUND,r,"call accepted");const n=this.getSipSessionId(e);return n&&this.removeIncomingSessions(n),r.answerTime=new Date,this._updateCallSession(r),this.eventEmitter.emit(ON_CALL_ACCEPTED,r,t),r}changeAudioDevice(e){logger$8.info("WebRTC phone - change audio device",{deviceId:e}),this.audioOutputDeviceId=e,this.client.changeAudioOutputDevice(e)}createAudioElementFor(e){return this.client.createAudioElementFor(e)}changeRingDevice(e){logger$8.info("WebRTC phone - changing ring device",{id:e}),this.audioRingDeviceId=e}changeAudioVolume(e){logger$8.info("WebRTC phone - changing audio volume",{volume:e}),this.audioOutputVolume=e,this.client.changeAudioOutputVolume(e)}changeRingVolume(e){logger$8.info("WebRTC phone - changing ring volume",{volume:e}),this.audioRingVolume=e}changeAudioInputDevice(e,t){return logger$8.info("WebRTC phone - changeAudio input device",{deviceId:e}),this.client.changeAudioInputDevice(e,this.currentSipSession,t)}async changeVideoInputDevice(e){return logger$8.info("WebRTC phone - change video input device",{deviceId:e}),this.client.changeVideoInputDevice(e,this.currentSipSession)}changeSessionVideoInputDevice(e){return logger$8.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);logger$8.info("WebRTC phone - on call terminated",{sipId:e.id,sipSessionId:t,ids:Object.keys(this.callSessions)});const r=this._createCallSession(e),n=this.isCurrentCallSipSession(r),i=r.is(this.getIncomingCallSession()),s=n?this.incomingSessions.length:i;i&&setTimeout((()=>{this.eventEmitter.emit(ON_TERMINATE_SOUND,r,"call terminated")}),5),t&&this.removeIncomingSessions(t),delete this.callSessions[t],n&&(this.currentSipSession=void 0,this.currentCallSession=void 0);const o=this.hasIncomingCallSession();if(logger$8.info("WebRTC phone - check to re-trigger incoming call",{sipId:e.id,shouldRetrigger:s,hasIncomingCallSession:o}),this.client.onCallEnded(e),o&&s){const e=this.getIncomingCallSession();setTimeout((()=>{this.ringingEnabled&&(this.currentCallSession?this.eventEmitter.emit(ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,e):this.eventEmitter.emit(ON_PLAY_RING_SOUND,this.audioRingDeviceId,this.audioRingVolume,e)),this.eventEmitter.emit(ON_CALL_INCOMING,e,e?.cameraEnabled)}),100)}return!(r.getId()in this.ignoredSessions)&&(e.isCanceled||setTimeout((()=>{this.eventEmitter.emit(ON_PLAY_HANGUP_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,r)}),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 logger$8.warn("WebRTCPhone.getLocalStreamForCall is deprecated, use WebRTCPhone.getLocalStream instead"),this.getLocalStream(e)}getRemoteStreamForCall(e){return logger$8.warn("WebRTCPhone.getRemoteStreamForCall is deprecated, use WebRTCPhone.getRemoteStream instead"),this.getRemoteVideoStream(e)}getRemoteStreamsForCall(e){return logger$8.warn("WebRTCPhone.getRemoteStreamsForCall is deprecated, use WebRTCPhone.getRemoteStreams instead"),this.getRemoteStream(e)}accept(e,t){if(logger$8.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 logger$8.warn("no CallSession to accept."),Promise.resolve(null);const r=this.getSipSessionIdFromCallSession(e);if(r&&!(r in this.callSessions))return logger$8.warn("Call session already ended or not found, can't accept it.",{sipSessionId:r}),Promise.resolve(null);if(e.getId()in this.acceptedSessions)return logger$8.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(ON_CALL_ANSWERED,e);const n=this.client.getSipSession(e.getId());if(n)return logger$8.info("accept call, session found",{sipId:n.id}),this.client.answer(n,!!this.allowVideo&&t).then((()=>e.sipCallId)).catch((t=>{throw logger$8.error(t),this.endCurrentCall(e),t}));const i="No CallSession found to accept.";return logger$8.warn(i,{id:e?e.getId():"n/a",ids:this.client.getSipSessionIds()}),e&&this.eventEmitter.emit(ON_CALL_ERROR,new Error(i),e),Promise.resolve(null)}isAccepted(e){return e&&e.getId()in this.acceptedSessions}async reject(e){if(logger$8.info("reject WebRTC called",{id:e.getId()}),this.eventEmitter.emit(ON_TERMINATE_SOUND,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&&(logger$8.info("WebRTC rejecting",{sipId:t.id}),this.client.hangup(t))}async ignore(e){logger$8.info("WebRTC ignore",{id:e.getId()}),this.eventEmitter.emit(ON_TERMINATE_SOUND,e,"ignoring call"),this.ignoredSessions[e.getId()]=!0,e.ignore()}atxfer(e){const t=this.findSipSession(e);if(t)return logger$8.info("WebRTC atxfer",{sipId:t.id}),this.client.atxfer(t)}hold(e,t=!0){logger$8.info("WebRTC hold",{id:e.getId()});const r=this.findSipSession(e);return r?this.holdSipSession(r,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){logger$8.info("WebRTC resume called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return new Promise(((e,t)=>t(new Error("No session to resume"))));logger$8.info("WebRTC resuming",{sipId:r.id}),this.currentSipSession&&this.currentSipSession.id!==r.id&&(logger$8.info("WebRTC hold call after resume",{id:this.currentSipSession.id}),this.holdSipSession(this.currentSipSession,this.currentCallSession,t));const n=this.unholdSipSession(r,e,t);return this.currentSipSession=r,e&&(this.currentCallSession=e),n}async holdSipSession(e,t,r=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to hold"))));const n=this.getSipSessionId(e),i=this.client.hasLocalVideo(n);logger$8.info("WebRTC hold sip session",{sipId:e.id,hasVideo:i}),this.currentScreenShare&&this.currentScreenShare.sipSessionId===n&&(this.lastScreenShare=this.currentScreenShare,await this.stopScreenSharing(!1,t)),i&&await this.client.downgradeToAudio(e);const s=!!t&&t.isConference(),o=this.client.hold(e,s,i);return r&&this.eventEmitter.emit(ON_CALL_HELD,this._createCallSession(e,t)),o}async unholdSipSession(e,t,r=!0){if(!e)return new Promise(((e,t)=>t(new Error("No session to unhold"))));const n=!!t&&t.isConference(),i=this.getSipSessionId(e);logger$8.info("WebRTC unhold sip session",{sessionId:i,isConference:n});const{hasVideo:s}=this.client.getHeldSession(i)||{},o=this.lastScreenShare&&this.lastScreenShare.sipSessionId===i,a=this.lastScreenShare&&this.lastScreenShare.desktop,d=this.client.unhold(e,n);if(s){const t={audio:!1,video:!0,screen:o,desktop:a};await this.client.upgradeToVideo(e,t,n)}const c=r=>{const n=this.lastScreenShare&&this.lastScreenShare.hadVideo;r&&this._onScreenSharing(r,e,t,n),this.lastScreenShare=null};if(r){t&&(t.muted=!1);const r=this._createCallSession(e,t);this.eventEmitter.emit(ON_CALL_UNHELD,r),this.eventEmitter.emit(ON_CALL_RESUMED,r)}return d.then((()=>{const e=t?this.getLocalVideoStream(t):null;return o&&c(e),e}))}mute(e,t=!0){logger$8.info("WebRTC mute called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return;logger$8.info("WebRTC muting",{sipId:r.id}),this.client.mute(r);const n=this._createCallSession(r,e,{muted:!0});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(ON_CALL_MUTED,n)}unmute(e,t=!0){logger$8.info("WebRTC unmute called",{id:e?e.getId():null});const r=this.findSipSession(e);if(!r)return;logger$8.info("WebRTC unmuting",{sipId:r.id}),this.client.unmute(r);const n=this._createCallSession(r,e,{muted:!1});this.currentCallSession&&n.is(this.currentCallSession)&&(this.currentCallSession=n),t&&this.eventEmitter.emit(ON_CALL_UNMUTED,n)}isAudioMuted(e){const t=this.findSipSession(e);return!t||this.client.isAudioMuted(t)}turnCameraOn(e){const t=this.findSipSession(e);t&&(logger$8.info("WebRTC turn camera on",{sipId:t.id}),this.client.toggleCameraOn(t),this.eventEmitter.emit(ON_CAMERA_RESUMED,this._createCameraResumedCallSession(t,e)))}turnCameraOff(e){const t=this.findSipSession(e);t&&(logger$8.info("WebRTC turn camera off",{sipId:t.id}),this.client.toggleCameraOff(t),this.eventEmitter.emit(ON_CAMERA_DISABLED,this._createCameraDisabledCallSession(t,e)))}sendKey(e,t){const r=this.findSipSession(e);r&&(logger$8.info("WebRTC send key",{sipId:r.id,tone:t}),this.client.sendDTMF(r,t))}async makeCall(e,t,r,n=!1,i=!1){if(logger$8.info("make WebRTC call",{number:e,lineId:t?t.id:null,cameraEnabled:r,audioOnly:n,conference:i}),!e)return Promise.resolve(null);let s;this.client.isRegistered()||await this.client.register(),this.currentSipSession&&this.holdSipSession(this.currentSipSession,this.currentCallSession,!0).catch((e=>{logger$8.warn("Unable to hold current session when making another call",e)}));try{s=this.client.call(e,!!this.allowVideo&&r,n,i),this._bindEvents(s)}catch(e){return logger$8.warn("make WebRTC call, error",{message:e.message,stack:e.stack}),Promise.resolve(null)}const o=this._createOutgoingCallSession(s,r||!1);return o.setIsConference(i),o.creationTime=new Date,this._updateCallSession(o),this.eventEmitter.emit(ON_PLAY_PROGRESS_SOUND,this.audioOutputDeviceId,this.audioOutputVolume),this.currentSipSession=s,this.currentCallSession=o,this.eventEmitter.emit(ON_CALL_OUTGOING,o),s.invitePromise&&s.invitePromise.catch((e=>{this.eventEmitter.emit(ON_CALL_ERROR,e,o)})),Promise.resolve(o)}transfer(e,t){const r=this.findSipSession(e);r&&(logger$8.info("WebRTC transfer",{sipId:r.id,target:t}),this.client.transfer(r,t))}async indirectTransfer(e,t){const r=this.client.getSipSession(e.sipCallId),n=this.client.getSipSession(t.sipCallId);return logger$8.info("WebRTC indirect transfer",{sipId:r?r.id:null,target:n?n.id:null}),n?new Promise((e=>{const i={requestDelegate:{onAccept:()=>{setTimeout((()=>{this.hangup(t).then(e)}),200)}}};return n.refer(r,i)})):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 r=this.getSipSessionId(t);return logger$8.info("WebRTC hangup",{sipId:t.id,sipSessionId:r}),await this.client.hangup(t),e?this.endCurrentCall(e):r&&delete this.callSessions[r],this.shouldSendReinvite=!1,!0}async getStats(e){const t=this.findSipSession(e);return t?this.client.getStats(t):null}startNetworkMonitoring(e,t=1e3){const r=this.findSipSession(e);return r?this.client.startNetworkMonitoring(r,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){logger$8.info("force cancel, error",e)}}endCurrentCall(e){const t=this.isCurrentCallSipSession(e);logger$8.info("Ending current call",{id:e?e.getId():null,isCurrent:t}),t&&(this.currentSipSession=void 0,this.currentCallSession=void 0),this.eventEmitter.emit(ON_TERMINATE_SOUND,e,"locally ended")}onConnectionMade(){}isConference(e){return!!e&&(this.client&&this.client.isConference(e.sipCallId))}async close(e=!1){logger$8.info("WebRTC close");try{await Promise.race([this.unregister(),new Promise(((e,t)=>setTimeout((()=>t(new Error("Unregister, timed out"))),3e3)))])}catch(e){logger$8.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(){logger$8.info("WebRTC enable ringing"),this.ringingEnabled=!0}disableRinging(){logger$8.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,r="text/plain"){return this.client.sendMessage(e,t,r)}getLocalStream(e){return e?this.client.getLocalStream(e.sipCallId):null}getLocalVideoStream(e){return e?this.client.getLocalVideoStream(e.sipCallId):null}getLocalMediaStream(e){return logger$8.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 r="Auto"===e.request.getHeader("Answer-Mode"),n=!!this.allowVideo&&t;logger$8.info("WebRTC invite received",{sipId:e.id,withVideo:n,autoAnswer:r});const i=this._createIncomingCallSession(e,n,null,r);this.incomingSessions.push(i.getId()),this._bindEvents(e),this.client.storeSipSession(e),this.currentSipSession?this.eventEmitter.emit(ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,this.audioOutputDeviceId,this.audioOutputVolume,i):this.ringingEnabled&&this.eventEmitter.emit(ON_PLAY_RING_SOUND,this.audioRingDeviceId,this.audioRingVolume,i),i.creationTime=new Date,this._updateCallSession(i),this.eventEmitter.emit(ON_CALL_INCOMING,i,t)})),this.client.on(this.client.ON_REINVITE,((...e)=>{logger$8.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,(e=>{const t=this.getSipSessionId(e),r=t in this.callSessions;logger$8.info("WebRTC call accepted",{sipId:t,hasSession:r}),r?(this._onCallAccepted(e,this.client.hasVideo(t)),this.audioOutputDeviceId&&this.client.changeAudioOutputDevice(this.audioOutputDeviceId)):logger$8.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=>{logger$8.error("WebRTC error",e),this.eventEmitter.emit(ON_CALL_ERROR,e)})),this.client.on(this.client.REJECTED,(e=>{logger$8.info("WebRTC call rejected",e.id);const t=this._createCallSession(e);delete this.callSessions[this.getSipSessionId(e)],t.endTime=new Date,this.eventEmitter.emit(ON_CALL_REJECTED,t)})),this.client.on(this.client.UNREGISTERED,(()=>{logger$8.info("WebRTC unregistered"),this.eventEmitter.emit(ON_UNREGISTERED)})),this.client.on(this.client.ON_DISCONNECTED,(()=>{logger$8.info("WebRTC disconnected"),this.eventEmitter.emit(ON_DISCONNECTED$1)})),this.client.on(this.client.ON_PROGRESS,(e=>{logger$8.info("WebRTC progress (180)");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit(ON_PROGRESS$1,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.ON_EARLY_MEDIA,(e=>{logger$8.info("WebRTC early media");const t=this._createCallSession(e,null,{incoming:!1,ringing:!0,callId:this.getSipSessionId(e)});this.eventEmitter.emit(ON_EARLY_MEDIA$1,t,this.audioOutputDeviceId,this.audioOutputVolume)})),this.client.on(this.client.REGISTERED,(()=>{if(logger$8.info("WebRTC registered",{shouldSendReinvite:this.shouldSendReinvite,state:this.currentSipSession?this.currentSipSession.state:null,currentSipSession:!!this.currentSipSession}),this.stopHeartbeat(),this.eventEmitter.emit(ON_REGISTERED),this.shouldSendReinvite&&this.currentSipSession&&this.currentSipSession.state===SessionState$1.Established){this.shouldSendReinvite=!1;const e=this.currentSipSession?.sessionDescriptionHandler?.peerConnection,t=!!e&&e.sfu,r=this.currentCallSession&&this.currentCallSession.cameraEnabled;try{this.sendReinvite(this.currentCallSession,null,t,!r,!0)}catch(e){logger$8.error("WebRTC reinvite after register, error",{message:e.message,stack:e.stack})}}})),this.client.on(this.client.CONNECTED,(()=>{logger$8.info("WebRTC client connected"),this.stopHeartbeat()})),this.client.on(this.client.DISCONNECTED,(()=>{logger$8.info("WebRTC client disconnected"),this.eventEmitter.emit(ON_UNREGISTERED),this.client.hasHeartbeat()||this.startHeartbeat(),this.shouldSendReinvite=!0})),this.client.on(this.client.ON_TRACK,((e,t)=>{this.eventEmitter.emit(ON_TRACK$1,e,t)})),this.client.on("onVideoInputChange",(e=>{this.eventEmitter.emit(ON_VIDEO_INPUT_CHANGE,e)})),this.client.on(this.client.MESSAGE,(e=>{this._onMessage(e),this.eventEmitter.emit(ON_MESSAGE,e)})),this.client.on(this.client.ON_NETWORK_STATS,((e,t,r)=>{const n=this.getCallSession(this.getSipSessionId(e));this.eventEmitter.emit(ON_NETWORK_STATS$1,n,t,r)})),this.client.on(this.client.ON_SCREEN_SHARING_REINVITE,((e,t,r)=>{const n=this.getSipSessionId(e),i=this.client.getLocalStream(n),s=this.callSessions[n];logger$8.info("Updrading directly in screensharing mode",{sipSessionId:n,tracks:i?.getTracks()||null}),this._onScreenSharing(i,e,s,!1,r)}))}findSipSession(e){const t=this.client.getSipSessionIds(),r=t.findIndex((t=>e&&e.isId(t)));if(-1===r){const e=this.currentSipSession?this.getSipSessionId(this.currentSipSession):this.client.getSipSessionIds()[0];return e?this.client.getSipSession(e):null}return this.client.getSipSession(t[r])}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:r,content:n}=t;switch(r){case MESSAGE_TYPE_CHAT:this.eventEmitter.emit(ON_CHAT,n);break;case MESSAGE_TYPE_SIGNAL:this.eventEmitter.emit(ON_SIGNAL,n)}}_createIncomingCallSession(e,t,r,n=!1){return this._createCallSession(e,r,{incoming:!0,ringing:!0,cameraEnabled:t,autoAnswer:n})}_createOutgoingCallSession(e,t,r){return this._createCallSession(e,r,{incoming:!1,ringing:!0,cameraEnabled:t})}_createAcceptedCallSession(e,t,r){return this._createCallSession(e,r,{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,r={}){const n=e?e.remoteIdentity||e.assertedIdentity:null,i=n?n.uri._normal.user:null,{state:s}=e||{},o=this.getSipSessionId(e);t=t||this.callSessions[o];const a=new CallSession({callId:t&&t.callId,sipCallId:o,sipStatus:s,displayName:n&&n.displayName||i,startTime:t?t.startTime:new Date,creationTime:t?t.creationTime:null,answerTime:t?t.answerTime:null,endTime:t?t.endTime:null,answered:s===SessionState$1.Established,paused:this.client.isCallHeld(e),isCaller:t?t.isCaller:"incoming"in r&&!r.incoming,cameraEnabled:t?t.isCameraEnabled():this.client.hasVideo(o),number:i,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(),...r});return this.callSessions[o]=a,a}}var PHONE_EVENTS=Object.freeze({__proto__:null,MESSAGE_TYPE_CHAT:MESSAGE_TYPE_CHAT,MESSAGE_TYPE_SIGNAL:MESSAGE_TYPE_SIGNAL,ON_AUDIO_STREAM:ON_AUDIO_STREAM,ON_CALL_ACCEPTED:ON_CALL_ACCEPTED,ON_CALL_ANSWERED:ON_CALL_ANSWERED,ON_CALL_CANCELED:ON_CALL_CANCELED,ON_CALL_ENDED:ON_CALL_ENDED,ON_CALL_ENDING:ON_CALL_ENDING,ON_CALL_ERROR:ON_CALL_ERROR,ON_CALL_FAILED:ON_CALL_FAILED,ON_CALL_HELD:ON_CALL_HELD,ON_CALL_INCOMING:ON_CALL_INCOMING,ON_CALL_MUTED:ON_CALL_MUTED,ON_CALL_OUTGOING:ON_CALL_OUTGOING,ON_CALL_REJECTED:ON_CALL_REJECTED,ON_CALL_RESUMED:ON_CALL_RESUMED,ON_CALL_UNHELD:ON_CALL_UNHELD,ON_CALL_UNMUTED:ON_CALL_UNMUTED,ON_CAMERA_DISABLED:ON_CAMERA_DISABLED,ON_CAMERA_RESUMED:ON_CAMERA_RESUMED,ON_CHAT:ON_CHAT,ON_DISCONNECTED:ON_DISCONNECTED$1,ON_EARLY_MEDIA:ON_EARLY_MEDIA$1,ON_MESSAGE:ON_MESSAGE,ON_MESSAGE_TRACK_UPDATED:ON_MESSAGE_TRACK_UPDATED,ON_NETWORK_STATS:ON_NETWORK_STATS$1,ON_PLAY_HANGUP_SOUND:ON_PLAY_HANGUP_SOUND,ON_PLAY_INBOUND_CALL_SIGNAL_SOUND:ON_PLAY_INBOUND_CALL_SIGNAL_SOUND,ON_PLAY_PROGRESS_SOUND:ON_PLAY_PROGRESS_SOUND,ON_PLAY_RING_SOUND:ON_PLAY_RING_SOUND,ON_PROGRESS:ON_PROGRESS$1,ON_REGISTERED:ON_REGISTERED,ON_REINVITE:ON_REINVITE$1,ON_REMOVE_STREAM:ON_REMOVE_STREAM,ON_SHARE_SCREEN_ENDED:ON_SHARE_SCREEN_ENDED,ON_SHARE_SCREEN_ENDING:ON_SHARE_SCREEN_ENDING,ON_SHARE_SCREEN_STARTED:ON_SHARE_SCREEN_STARTED,ON_SIGNAL:ON_SIGNAL,ON_TERMINATE_SOUND:ON_TERMINATE_SOUND,ON_TRACK:ON_TRACK$1,ON_UNREGISTERED:ON_UNREGISTERED,ON_USER_AGENT:ON_USER_AGENT,ON_VIDEO_INPUT_CHANGE:ON_VIDEO_INPUT_CHANGE,ON_VIDEO_STREAM:ON_VIDEO_STREAM,default:WebRTCPhone,events:events$1});let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function wrapPeerConnectionEvent(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(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),i.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),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 disableLog(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(logDisabled_=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(deprecationWarnings_=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){deprecationWarnings_&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(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:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=extractVersion(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=extractVersion(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=extractVersion(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,r){const n=isObject(e[r]),i=n?compactObject(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function walkStats(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?walkStats(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach((t=>{walkStats(e,e.get(t),r)}))})))}function filterStats(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===n&&r.trackId===t.id&&walkStats(e,r,i)}))})),i}const logging=log;function shimGetUserMedia$2(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=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[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=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 o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){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 r.mediaDevices.enumerateDevices().then((r=>{r=r.filter((e=>"videoinput"===e.kind));let o=r.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),logging("chrome: "+JSON.stringify(e)),i(e)}))}e.video=n(e.video)}return logging("chrome: "+JSON.stringify(e)),i(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(r.getUserMedia=function(e,t,n){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(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 shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const n=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(r.video.mandatory.maxWidth=n),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(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",(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(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 r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};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 r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.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 shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,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 i=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){r(s(i(e)))};return t.apply(this,[n,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,n)}}function shimSenderReceiverGetStats(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(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}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(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,r,n;return this.getSenders().forEach((r=>{r.track===e&&(t?n=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?n=!0:r=t),t.track===e))),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(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,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};const r=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();r.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 i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),i.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.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 r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,r){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 i=this._streams[r.id];if(i)i.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.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((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var chromeShim=Object.freeze({__proto__:null,fixNegotiationNeeded:fixNegotiationNeeded,shimAddTrackRemoveTrack:shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative:shimAddTrackRemoveTrackWithNative,shimGetDisplayMedia:shimGetDisplayMedia$1,shimGetSendersWithDtmf:shimGetSendersWithDtmf,shimGetStats:shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream:shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats:shimSenderReceiverGetStats});function shimGetUserMedia$1(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}function shimOnTrack(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 shimPeerConnection(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 r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const r={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,i,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function shimSenderGetStats(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.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 shimReceiverGetStats(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}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(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 r=e.length>0;r&&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(r){const{sender:t}=n,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function shimGetParameters(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 shimCreateOffer(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 shimCreateAnswer(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 firefoxShim=Object.freeze({__proto__:null,shimAddTransceiver:shimAddTransceiver,shimCreateAnswer:shimCreateAnswer,shimCreateOffer:shimCreateOffer,shimGetDisplayMedia:shimGetDisplayMedia,shimGetParameters:shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack:shimOnTrack,shimPeerConnection:shimPeerConnection,shimRTCDataChannel:shimRTCDataChannel,shimReceiverGetStats:shimReceiverGetStats,shimRemoveStream:shimRemoveStream,shimSenderGetStats:shimSenderGetStats});function shimLocalStreamsAPI(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((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.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 r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function shimRemoteStreamsAPI(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 r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function shimGetUserMedia(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let n=e.iceServers[r];void 0===n.urls&&n.url?(deprecated("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function shimTrackEventTransceiver(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 shimCreateOfferLegacy(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 r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var safariShim=Object.freeze({__proto__:null,shimAudioContext:shimAudioContext,shimCallbacksAPI:shimCallbacksAPI,shimConstraints:shimConstraints,shimCreateOfferLegacy:shimCreateOfferLegacy,shimGetUserMedia:shimGetUserMedia,shimLocalStreamsAPI:shimLocalStreamsAPI,shimRTCIceServerUrls:shimRTCIceServerUrls,shimRemoteStreamsAPI:shimRemoteStreamsAPI,shimTrackEventTransceiver:shimTrackEventTransceiver}),sdp$1={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 r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={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":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),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 r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\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 r;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=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:"+r+" "+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="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},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 r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.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,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},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,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.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 r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{i.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.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",r.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let i=0;return r.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let d;const c=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));c.length>0&&c[0].length>1&&c[0][0]===a&&(d=c[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&d&&(t.rtx={ssrc:d}),r.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});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,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},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 r;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:i};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let r=[];return r="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&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){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 r?t.getDirection(r):"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 r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(sdp$1);var sdpExports=sdp$1.exports,SDPUtils=getDefaultExportFromCjs(sdpExports),sdp=_mergeNamespaces({__proto__:null,default:SDPUtils},[sdpExports]);function shimRTCIceCandidate(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 r=new t(e),n=SDPUtils.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,wrapPeerConnectionEvent(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimRTCIceCandidateRelayProtocol(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||wrapPeerConnectionEvent(e,"icecandidate",(e=>{if(e.candidate){const t=SDPUtils.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function shimMaxMessageSize(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 r=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=SDPUtils.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=SDPUtils.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 r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=SDPUtils.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function shimConnectionState(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 r=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 r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function removeExtmapAllowMixed(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=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:r}):t.sdp=r}return r.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.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 r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var commonShim=Object.freeze({__proto__:null,removeExtmapAllowMixed:removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty:shimAddIceCandidateNullOrEmpty,shimConnectionState:shimConnectionState,shimMaxMessageSize:shimMaxMessageSize,shimParameterlessSetLocalDescription:shimParameterlessSetLocalDescription,shimRTCIceCandidate:shimRTCIceCandidate,shimRTCIceCandidateRelayProtocol:shimRTCIceCandidateRelayProtocol,shimSendThrowTypeError:shimSendThrowTypeError});function adapterFactory({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=log,n=detectBrowser(e),i={browserDetails:n,commonShim:commonShim,extractVersion:extractVersion,disableLog:disableLog,disableWarnings:disableWarnings,sdp:sdp};switch(n.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,n),shimMediaStream(e),shimPeerConnection$1(e,n),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,n),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,n),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,n),shimPeerConnection(e,n),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e);break;case"safari":if(!safariShim||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(e,n),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimMaxMessageSize(e,n),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,n);break;default:r("Unsupported browser!")}return i}adapterFactory({window:"undefined"==typeof window?void 0:window});const stripMediaDescription=(e,t)=>{const r=new RegExp("m="+t+".*$","gm"),n=new RegExp("^a=group:.*$","gm");if(r.test(e)){let r;const i=(e=e.split(/^m=/gm).filter((e=>{if(e.substr(0,t.length)===t){if(r=e.match(/^a=mid:.*$/gm),r){const e=r[0].match(/:.+$/g);e&&(r=e[0].substr(1))}return!1}return!0})).join("m=")).match(n);if(i&&1===i.length){let t=i[0];const s=new RegExp(" *"+r+"[^ ]*","g");t=t.replace(s,""),e=e.split(n).join(t)}}return e};function stripVideo(e){return e.sdp=stripMediaDescription(e.sdp||"","video"),Promise.resolve(e)}function holdModifier(e){if(!e.sdp||!e.type)throw new Error("Invalid SDP");let t=e.sdp;const r=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:r})}var getStats$1={exports:{}};!function(e){e.exports=function(e,t,r){var n;(n=void 0!==commonjsGlobal?commonjsGlobal:null)&&"undefined"==typeof window&&void 0!==commonjsGlobal&&(commonjsGlobal.navigator={userAgent:"Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45",getUserMedia:function(){}},commonjsGlobal.console||(commonjsGlobal.console={}),void 0!==commonjsGlobal.console.log&&void 0!==commonjsGlobal.console.error||(commonjsGlobal.console.error=commonjsGlobal.console.log=commonjsGlobal.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===i&&(n.RTCPeerConnection=function(){}),n.window=commonjsGlobal);var i=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 r=e.type.split("-")[0];t="outbound"===r?"send":"inbound"===r?"recv":null}return t}},nomore:function(){c=!0}},o={checkIfOfferer:function(e){"googLibjingleSession"===e.type&&(s.isOfferer=e.googInitiator)}},a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),d=this;if(!(arguments[0]instanceof i))throw"1st argument is not instance of RTCPeerConnection.";d=arguments[0],arguments[1]instanceof MediaStreamTrack&&(e=arguments[1],t=arguments[2],r=arguments[3]);var c=!1;o.datachannel=function(e){"datachannel"===e.type&&(s.datachannel={state:e.state})},o.googCertificate=function(e){"googCertificate"==e.type&&(s.encryption=e.googFingerprintAlgorithm),"certificate"==e.type&&(s.encryption=e.fingerprintAlgorithm)},o.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 r=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,r=n/1024,s.audio[t].availableBandwidth=r.toFixed(1),s.audio.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=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,r=n/1024,s.audio.bytesReceived=r.toFixed(1)),e.googTrackId&&-1===s.audio[t].tracks.indexOf(e.googTrackId)&&s.audio[t].tracks.push(e.googTrackId),e.googCurrentDelayMs&&(r=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&&(r=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))}}},o.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 r=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,r=n/1024,s.video[t].availableBandwidth=r.toFixed(1),s.video.bytesSent=r.toFixed(1)}e.bytesReceived&&(r=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,r=n/1024,s.video.bytesReceived=r.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,r=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,r=n/1024,s.video[t].framerateMean=n.toFixed(1)),e.bitrateMean&&(s.bandwidth.bitrateMean=e.bitrateMean,r=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,r=n/1024,s.video[t].bitrateMean=n.toFixed(1)),e.googCurrentDelayMs&&(r=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&&(r=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))}}},o.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)},o.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 r=s.internal.candidates[t];-1!==r.ipAddress.indexOf(e.googLocalAddress)&&(s.connectionType.local.candidateType=r.candidateType,s.connectionType.local.ipAddress=r.ipAddress,s.connectionType.local.networkType=r.networkType,s.connectionType.local.transport=r.transport),-1!==r.ipAddress.indexOf(e.googRemoteAddress)&&(s.connectionType.remote.candidateType=r.candidateType,s.connectionType.remote.ipAddress=r.ipAddress,s.connectionType.remote.networkType=r.networkType,s.connectionType.remote.transport=r.transport)})),s.connectionType.transport=e.googTransportType,(t=s.internal.candidates[e.localCandidateId])&&t.ipAddress&&(s.connectionType.systemIpAddress=t.ipAddress),(r=s.internal.candidates[e.remoteCandidateId])&&r.ipAddress&&(s.connectionType.systemIpAddress=r.ipAddress)),"candidate-pair"===e.type&&!0===e.selected&&!0===e.nominated&&"succeeded"===e.state)var t=s.internal.candidates[e.remoteCandidateId],r=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),a){var n=e.localCandidateId?"send":"recv";if(!n)return;if(e.bytesSent){var i=0;s.internal.video[n].prevBytesSent||(s.internal.video[n].prevBytesSent=e.bytesSent);var o=e.bytesSent-s.internal.video[n].prevBytesSent;s.internal.video[n].prevBytesSent=e.bytesSent,i=o/1024,s.video[n].availableBandwidth=i.toFixed(1),s.video.bytesSent=i.toFixed(1)}e.bytesReceived&&(i=0,s.internal.video[n].prevBytesReceived||(s.internal.video[n].prevBytesReceived=e.bytesReceived),o=e.bytesReceived-s.internal.video[n].prevBytesReceived,s.internal.video[n].prevBytesReceived=e.bytesReceived,i=o/1024,s.video.bytesReceived=i.toFixed(1)),e.availableOutgoingBitrate&&(i=0,s.internal.video[n].prevAvailableOutgoingBitrate||(s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate),o=e.availableOutgoingBitrate-s.internal.video[n].prevAvailableOutgoingBitrate,s.internal.video[n].prevAvailableOutgoingBitrate=e.availableOutgoingBitrate,i=o/1024,s.video.availableOutgoingBitrate=i.toFixed(1)),e.availableIncomingBitrate&&(i=0,s.internal.video[n].prevAvailableIncomingBitrate||(s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate),o=e.availableIncomingBitrate-s.internal.video[n].prevAvailableIncomingBitrate,s.internal.video[n].prevAvailableIncomingBitrate=e.availableIncomingBitrate,i=o/1024,s.video.availableIncomingBitrate=i.toFixed(1))}}};var l={},u={},h={},g={};o.localcandidate=function(e){"localcandidate"!==e.type&&"local-candidate"!==e.type||e.id&&(l[e.id]||(l[e.id]=[]),u[e.id]||(u[e.id]=[]),h[e.id]||(h[e.id]=[]),g[e.id]||(g[e.id]=[]),e.candidateType&&-1===l[e.id].indexOf(e.candidateType)&&l[e.id].push(e.candidateType),e.transport&&-1===u[e.id].indexOf(e.transport)&&u[e.id].push(e.transport),e.ipAddress&&-1===h[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&h[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===g[e.id].indexOf(e.networkType)&&g[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:l[e.id],ipAddress:h[e.id],portNumber:e.portNumber,networkType:g[e.id],priority:e.priority,transport:u[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.local.candidateType=l[e.id],s.connectionType.local.ipAddress=h[e.id],s.connectionType.local.networkType=g[e.id],s.connectionType.local.transport=u[e.id])};var p={},m={},f={},S={};o.remotecandidate=function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||e.id&&(p[e.id]||(p[e.id]=[]),m[e.id]||(m[e.id]=[]),f[e.id]||(f[e.id]=[]),S[e.id]||(S[e.id]=[]),e.candidateType&&-1===p[e.id].indexOf(e.candidateType)&&p[e.id].push(e.candidateType),e.transport&&-1===m[e.id].indexOf(e.transport)&&m[e.id].push(e.transport),e.ipAddress&&-1===f[e.id].indexOf(e.ipAddress+":"+e.portNumber)&&f[e.id].push(e.ipAddress+":"+e.portNumber),e.networkType&&-1===S[e.id].indexOf(e.networkType)&&S[e.id].push(e.networkType),s.internal.candidates[e.id]={candidateType:p[e.id],ipAddress:f[e.id],portNumber:e.portNumber,networkType:S[e.id],priority:e.priority,transport:m[e.id],timestamp:e.timestamp,id:e.id,type:e.type},s.connectionType.remote.candidateType=p[e.id],s.connectionType.remote.ipAddress=f[e.id],s.connectionType.remote.networkType=S[e.id],s.connectionType.remote.transport=m[e.id])},o.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)))},o.inboundrtp=function(e){if(a&&"inbound-rtp"===e.type){var t=e.mediaType||"audio",r=e.isRemote?"recv":"send";if(r){if(e.bytesSent){var n=0;s.internal[t][r].prevBytesSent||(s.internal[t][r].prevBytesSent=e.bytesSent);var i=e.bytesSent-s.internal[t][r].prevBytesSent;s.internal[t][r].prevBytesSent=e.bytesSent,n=i/1024,s[t][r].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][r].prevBytesReceived||(s.internal[t][r].prevBytesReceived=e.bytesReceived),i=e.bytesReceived-s.internal[t][r].prevBytesReceived,s.internal[t][r].prevBytesReceived=e.bytesReceived,n=i/1024,s[t].bytesReceived=n.toFixed(1))}}},o.outboundrtp=function(e){if(a&&"outbound-rtp"===e.type){var t=e.mediaType||"audio",r=e.isRemote?"recv":"send";if(r){if(e.bytesSent){var n=0;s.internal[t][r].prevBytesSent||(s.internal[t][r].prevBytesSent=e.bytesSent);var i=e.bytesSent-s.internal[t][r].prevBytesSent;s.internal[t][r].prevBytesSent=e.bytesSent,n=i/1024,s[t][r].availableBandwidth=n.toFixed(1),s[t].bytesSent=n.toFixed(1)}e.bytesReceived&&(n=0,s.internal[t][r].prevBytesReceived||(s.internal[t][r].prevBytesReceived=e.bytesReceived),i=e.bytesReceived-s.internal[t][r].prevBytesReceived,s.internal[t][r].prevBytesReceived=e.bytesReceived,n=i/1024,s[t].bytesReceived=n.toFixed(1))}}},o.track=function(e){if(a&&"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:[]}};o.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(o).forEach((function(t){if("function"==typeof o[t])try{o[t](e)}catch(e){console.error(e.message,e.stack,e)}}))}));try{-1!==d.iceConnectionState.search(/failed|closed|disconnected/gi)&&(c=!0)}catch(e){c=!0}!0===c&&(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),c||null!=typeof r&&r&&setTimeout(e,r||1e3)}},void 0!==window.InstallTrigger||a?d.getStats(window.mediaStreamTrack||null).then((function(e){var t=[];e.forEach((function(e){t.push(e)})),n(t)})).catch(n):d.getStats((function(e){var t=[];e.result().forEach((function(e){var r={};e.names().forEach((function(t){r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,t.push(r)})),n(t)}))}()}}(getStats$1);var getStatsExports=getStats$1.exports,getStats=getDefaultExportFromCjs(getStatsExports),lib={},parser$1={},grammar$2={exports:{}},grammar$1=grammar$2.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(grammar$1).forEach((function(e){grammar$1[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$2.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var d=n[t][a];if(d.reg.test(i))return r(d,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.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 r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},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 r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(parser$1);var grammar=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=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 r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach((function(t){grammar[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))})),e.media.forEach((function(e){i.push(makeLine("m",grammar.m[0],e)),n.forEach((function(t){grammar[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1;lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;const parseCandidate$1=e=>{if(!e)return null;const t=lib.parse(0===e.indexOf("a=")?e:`a=${e}`);return t.candidates?t.candidates[0]:null},getSrflxOrRelay=e=>e.filter((e=>e&&("srflx"===e.type||"relay"===e.type))),getVideoDirection=e=>{const t=lib.parse(e).media.find((e=>"video"===e.type));return t?t.direction:null},hasAnActiveVideo=e=>{if(!e)return!1;return!!lib.parse(e).media.find((e=>"video"===e.type&&e.port>10&&(!e.direction||"inactive"!==e.direction)))},fixSdp=(e,t,r=!0)=>{const n=lib.parse(e),i=getSrflxOrRelay(t)[0],s=i?i.ip:null;s&&(n.origin.address=s),n.media=n.media.map((e=>{const n=r&&i?i.port:e.port;return{...e,port:n,candidates:(e.candidates||[]).concat(t),direction:n<10?"inactive":e.direction}}));let o=lib.write(n);return s&&(o=o.replace(/IN IP4 0.0.0.0/g,`IN IP4 ${s}`)),o},addIcesInAllBundles=e=>{const t=lib.parse(e),r=t.media.find((e=>!!e.candidates));if(!r)return e;const{candidates:n}=r;return t.media=t.media.map((e=>({...e,candidates:e.candidates||n}))),lib.write(t)},wazoLogger=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-sdh"):console,wazoMediaStreamFactory=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 WazoSessionDescriptionHandler extends SessionDescriptionHandler{gatheredCandidates;eventEmitter;isWeb;session;constructor(e,t,r,n,i){super(e,t,r),this.eventEmitter=new EventEmitter$2,this.isWeb=n,this.session=i}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 r=!!e.offerOptions&&e.offerOptions.iceRestart,n=!!e&&!!e.conference,i=!!e&&!!e.audioOnly,s=!this.session.pendingReinviteAck&&(r||"constraints"in e),o=void 0===e.iceGatheringTimeout?this.sessionDescriptionHandlerConfiguration?.iceGatheringTimeout:e.iceGatheringTimeout;return wazoLogger.trace("getting SDP description",{iceRestart:r,shouldWaitForIce:s,iceTimeout:o}),this.gatheredCandidates=[],this.peerConnectionDelegate||(this.peerConnectionDelegate={}),this.peerConnectionDelegate.onicecandidate=e=>{wazoLogger.trace("onicecandidate",e.candidate?e.candidate.candidate:{done:!0}),e.candidate&&(this.gatheredCandidates.push(parseCandidate$1(e.candidate.candidate)),-1===e.candidate.candidate.indexOf("srflx")&&-1===e.candidate.candidate.indexOf("relay")||(wazoLogger.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,i))).then((()=>this.createDataChannel(e))).then((()=>{!n||!e.constraints||e.constraints.video||"hold"in e||i||this.peerConnection?.addTransceiver&&this.peerConnection.addTransceiver("video",{streams:[this._localMediaStream],direction:"sendrecv"})})).then((()=>this.createLocalOfferOrAnswer(e))).then((e=>this.setLocalSessionDescription(e))).then((()=>this.waitForIceGatheringComplete(r,o))).then((()=>this.getLocalSessionDescription())).then((t=>{const{sdp:r}=t;return-1!==r.indexOf("a=candidate")?{type:t.type,sdp:addIcesInAllBundles(r)}:(wazoLogger.info("No ICE candidates found in SDP, fixing it with gathered ices",this.gatheredCandidates),{type:t.type,sdp:fixSdp(r,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 wazoLogger.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 r={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=${t.duration||1e3}`}};return this.session.info({requestOptions:r})}close(){if(wazoLogger.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,r=!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,i)=>{if(t)return r&&i.receiver.track&&"video"===i.receiver.track.kind||e&&e.hold?"sendonly":"sendrecv";switch(n){case"inactive":return e&&e.hold?"inactive":t&&!r?"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"})(),i=(()=>{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&&r&&n.track&&"video"===n.track.kind)return void(e.direction="inactive");"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()}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,{sfu:r}=t,n=this._localMediaStream,i=[],s=e=>{const{kind:s}=e;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const o=t.getSenders&&t.getSenders().find((e=>e.track&&e.track.kind===s));!o||r&&"audio"!==e.kind?i.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),SessionDescriptionHandler.dispatchAddTrackEvent(n,e)}))):(o.track&&(e.enabled=o.track.enabled),i.push(new Promise((e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e(null)})).then((()=>o.replaceTrack(e).then((()=>{const t=n.getTracks().find((e=>e.kind===s));t&&(t.stop(),n.removeTrack(t),SessionDescriptionHandler.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),SessionDescriptionHandler.dispatchAddTrackEvent(n,e)})).catch((e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))))))},o=e.getAudioTracks();o.length&&s(o[0]);const a=e.getVideoTracks();return a.length&&s(a[0]),i.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)))}}const DEFAULT_HEARTBEAT_DELAY=2e3,DEFAULT_HEARTBEAT_TIMEOUT=5e3,DEFAULT_MAX_HEARTBEATS=3;class Heartbeat{heartbeatDelay;heartbeatTimeout;maxHeartbeats;hasHeartbeat;_heartbeatDelayTimeout;_heartbeatNotReceivedTimeout;_heartbeatTries;_sendHeartbeatCallback;_onTimeoutCallback;constructor(e=DEFAULT_HEARTBEAT_DELAY,t=DEFAULT_HEARTBEAT_TIMEOUT,r=DEFAULT_MAX_HEARTBEATS){this.heartbeatDelay=e,this.heartbeatTimeout=t,this.maxHeartbeats=r,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 lastIndexOf=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},replaceLocalIpModifier=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")}),SIP_ID_LENGTH=36,DEFAULT_ICE_TIMEOUT=3e3,SEND_STATS_DELAY=5e3,states=["STATUS_NULL","STATUS_NEW","STATUS_CONNECTING","STATUS_CONNECTED","STATUS_COMPLETED"],logger$7=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-client"):console,statsLogger=IssueReporter$1?IssueReporter$1.loggerFor("webrtc-stats"):console,REGISTERED="registered",UNREGISTERED="unregistered",REGISTRATION_FAILED="registrationFailed",INVITE="invite",CONNECTED="connected",DISCONNECTED="disconnected",TRANSPORT_ERROR="transportError",MESSAGE="message",ACCEPTED="accepted",REJECTED="rejected",ON_TRACK="onTrack",ON_PROGRESS="onProgress",ON_EARLY_MEDIA="onEarlyMedia",ON_REINVITE="reinvite",ON_ERROR="onError",ON_SCREEN_SHARING_REINVITE="onScreenSharingReinvite",ON_NETWORK_STATS="onNetworkStats",ON_DISCONNECTED="onDisconnected",events=[REGISTERED,UNREGISTERED,REGISTRATION_FAILED,INVITE],transportEvents=[CONNECTED,DISCONNECTED,TRANSPORT_ERROR,MESSAGE];class CanceledCallError extends Error{}const MAX_REGISTER_TRIES=5,NO_ANSWER_TIMEOUT=86400;class WebRTCClient extends Emitter{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 WebRTCClient.isAPrivateIp(e)?[{urls:["stun:stun.l.google.com:19302","stun:stun4.l.google.com:19302"]}]:[]}constructor(e,t,r){super(),this.clientId=Math.ceil(1e3*Math.random()),logger$7.info("sdk webrtc constructor",{clientId:this.clientId}),this.uaConfigOverrides=r,this.config=e,this.skipRegister=e.skipRegister,this._buildConfig(e,t).then((e=>{this.config=e,this.userAgent=this.createUserAgent(r)})),this.audioOutputDeviceId=e.audioOutputDeviceId,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 Heartbeat(e.heartbeatDelay,e.heartbeatTimeout,e.maxHeartbeats),this.heartbeat.setSendHeartbeat(this.pingServer.bind(this)),this.heartbeat.setOnHeartbeatTimeout(this._onHeartbeatTimeout.bind(this)),this.REGISTERED=REGISTERED,this.UNREGISTERED=UNREGISTERED,this.REGISTRATION_FAILED=REGISTRATION_FAILED,this.INVITE=INVITE,this.CONNECTED=CONNECTED,this.DISCONNECTED=DISCONNECTED,this.TRANSPORT_ERROR=TRANSPORT_ERROR,this.MESSAGE=MESSAGE,this.ACCEPTED=ACCEPTED,this.REJECTED=REJECTED,this.ON_TRACK=ON_TRACK,this.ON_REINVITE=ON_REINVITE,this.ON_ERROR=ON_ERROR,this.ON_SCREEN_SHARING_REINVITE=ON_SCREEN_SHARING_REINVITE,this.ON_NETWORK_STATS=ON_NETWORK_STATS,this.ON_DISCONNECTED=ON_DISCONNECTED,this.ON_EARLY_MEDIA=ON_EARLY_MEDIA,this.ON_PROGRESS=ON_PROGRESS}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);logger$7.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=>{logger$7.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(INVITE,e,this.sessionWantsToDoVideo(e),t)}};const r=new UserAgent(t);return r.start(),r.transport&&r.transport.connectPromise&&r.transport.connectPromise.catch((e=>{logger$7.warn("Transport connect error",e)})),r.transport.onMessage=e=>{const t=Parser.parseMessage(e,r.transport.logger);r.onTransportMessage(e),this.eventEmitter.emit(MESSAGE,t),t&&t.method===C.MESSAGE&&r.userAgentCore.replyStateless(t,{statusCode:200})},r}isConnected(){return Boolean(this.userAgent?.isConnected())}isConnecting(){return this.userAgent?.transport?.state===TransportState.Connecting}isRegistered(){return Boolean(this.registerer&&this.registerer.state===RegistererState.Registered)}onConnect(){return logger$7.info("sdk webrtc connected",{method:"delegate.onConnect",clientId:this.clientId}),this.eventEmitter.emit(CONNECTED),!this.isRegistered()&&this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.register()}async onDisconnect(e){logger$7.info("sdk webrtc disconnected",{method:"delegate.onConnect",clientId:this.clientId,error:e}),this.connectionPromise=null,this.eventEmitter.emit(DISCONNECTED,e),this.isRegistered()&&(await this.unregister(),this.registerer?.waiting&&this.registerer.waitingToggle(!1),this.eventEmitter.emit(UNREGISTERED))}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 logger$7.info("sdk webrtc skip register...",t),Promise.resolve();if(logger$7.info("sdk webrtc registering...",t),this.userAgent||(logger$7.info("sdk webrtc recreating User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),!this.userAgent||this.isRegistered())return logger$7.info("sdk webrtc registering aborted, already registered or no UA can be created"),Promise.resolve();if(this.connectionPromise||this.registerer?.waiting)return logger$7.info("sdk webrtc registering aborted due to a registration in progress.",{clientId:this.clientId}),Promise.resolve();const r=this._isWeb()?{}:{extraContactHeaderParams:["mobility=mobile"]},n=()=>{logger$7.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<=MAX_REGISTER_TRIES&&(logger$7.info("sdk webrtc registering, retrying...",{clientId:this.clientId,tries:e}),setTimeout((()=>this.register(e+1)),300)))};return this._connectIfNeeded().then((()=>{this.userAgent||(logger$7.info("sdk webrtc recreating User Agent after connection"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),logger$7.info("sdk webrtc registering, transport connected",{registerOptions:r,ua:!!this.userAgent,clientId:this.clientId}),this.registerer=new Registerer(this.userAgent,r),this.connectionPromise=null,this._monkeyPatchRegisterer(this.registerer),this.registerer.stateChange.addListener((e=>{logger$7.info("sdk webrtc registering, state changed",{newState:e,clientId:this.clientId}),e===RegistererState.Registered&&this.registerer&&this.registerer.state===RegistererState.Registered?this.eventEmitter.emit(REGISTERED):e===RegistererState.Unregistered&&this.eventEmitter.emit(UNREGISTERED)}));const e={requestDelegate:{onReject:e=>{logger$7.error("sdk webrtc registering, rejected",{clientId:this.clientId,response:e}),n()}}};return this.registerer.register(e).catch((e=>(logger$7.error("sdk webrtc registering, error",e),this.eventEmitter.emit(REGISTRATION_FAILED),e)))})).catch((e=>{logger$7.error("sdk webrtc registering, transport error",e),n()}))}_monkeyPatchRegisterer(e){if(!e)return;const t=e.waitingToggle.bind(e),r=e.unregistered.bind(e);e.waitingToggle=r=>{e&&e.waiting!==r&&t(r)},e.unregistered=()=>{e&&e.state!==RegistererState.Terminated&&r()}}async unregister(){logger$7.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 r=t=>{t===RegistererState.Unregistered&&(logger$7.info("sdk webrtc unregistered",{clientId:this.clientId}),this.registerer&&this.registerer.stateChange.addListener(r),this._cleanupRegister(),e())};this.registerer.stateChange.addListener(r),this.registerer.unregister().then().catch((e=>{logger$7.error("sdk webrtc unregistering, promise error",e),this._cleanupRegister(),t()}))}))}catch(e){logger$7.error("sdk webrtc unregistering, error",e),this._cleanupRegister()}}stop(){return logger$7.info("sdk webrtc stop",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent?this.userAgent.stop().then((()=>this._cleanupRegister())).catch((e=>{logger$7.warn("sdk webrtc stop, error",{message:e.message,stack:e.stack})})):Promise.resolve()}call(e,t,r=!1,n=!1){logger$7.info("sdk webrtc creating call",{clientId:this.clientId,number:e,enableVideo:t,audioOnly:r,conference:n});const i={sessionDescriptionHandlerOptionsReInvite:{conference:n,audioOnly:r},earlyMedia:!0};r&&(i.sessionDescriptionHandlerModifiersReInvite=[stripVideo]);const s=this._makeURI(e);let o=null;s?o=this.userAgent?new Inviter(this.userAgent,s,i):null:logger$7.error("Null URI"),o&&(this.storeSipSession(o),this._setupSession(o)),n&&(this.conferences[this.getSipSessionId(o)]=!0);const a={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=>{logger$7.info("on call rejected",{id:o?.id,fromTag:o?.fromTag}),this._stopSendingStats(o),this.stopNetworkMonitoring(o),this.eventEmitter.emit(REJECTED,o,e)}},sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1,n)};return a.sessionDescriptionHandlerOptions&&(a.sessionDescriptionHandlerOptions.audioOnly=r),a.sessionDescriptionHandlerModifiers=[replaceLocalIpModifier],r&&a.sessionDescriptionHandlerModifiers.push(stripVideo),o&&(o.invitePromise=o.invite(a).catch((e=>{logger$7.warn("sdk webrtc creating call, error",e)}))),o}answer(e,t){if(logger$7.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 logger$7.warn(e),Promise.reject(new Error(e))}const r={sessionDescriptionHandlerOptions:this.getMediaConfiguration(t||!1)};return this._accept(e,r).then((()=>{if(e.isCanceled){const t="accepted a canceled session (or was canceled during the accept phase).";throw logger$7.error(t,{id:e.id}),this.onCallEnded(e),new CanceledCallError(t)}logger$7.info("sdk webrtc answer, accepted."),this._onAccepted(e)})).catch((t=>{throw logger$7.error(`answer call error for ${e?e.id:"n/a"}`,t),t}))}async hangup(e){const{state:t,id:r}=e;logger$7.info("sdk webrtc hangup call",{clientId:this.clientId,id:r,state:t});try{this._stopSendingStats(e),this._cleanupMedia(e),delete this.sipSessions[this.getSipSessionId(e)];const r=e instanceof Inviter,n={[SessionState$1.Initial]:r?this._cancel.bind(this,e):this._reject.bind(this,e),[SessionState$1.Establishing]:r?this._cancel.bind(this,e):this._reject.bind(this,e),[SessionState$1.Established]:this._bye.bind(this,e)};return n[t]?await n[t]():await this._bye(e)}catch(e){logger$7.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 r=this.getSipSessionId(e);logger$7.info("starting network inspection",{id:r,clientId:this.clientId}),this.sessionNetworkStats[r]=[],this.networkMonitoringInterval[r]=setInterval((()=>this._fetchNetworkStats(r)),t)}stopNetworkMonitoring(e){const t=this.getSipSessionId(e),r=t in this.networkMonitoringInterval;logger$7.info("stopping network inspection",{clientId:this.clientId,id:t,exists:r}),r&&(clearInterval(this.networkMonitoringInterval[t]),delete this.networkMonitoringInterval[t],delete this.sessionNetworkStats[t])}async reject(e){logger$7.info("sdk webrtc reject call",{clientId:this.clientId,id:e.id});try{if(e instanceof Invitation)return this._reject(e);if(e instanceof Inviter)return this._cancel(e)}catch(e){logger$7.warn("Error when rejecting call",e.message,e.stack)}}async close(e=!1){if(logger$7.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,logger$7.info("sdk webrtc client closed",{clientId:this.clientId})}}getNumber(e){return e?e.remoteIdentity.uri._normal.user:null}mute(e){logger$7.info("sdk webrtc mute",{id:e.id}),this._toggleAudio(e,!0)}unmute(e){logger$7.info("sdk webrtc unmute",{id:e.id}),this._toggleAudio(e,!1)}isAudioMuted(e){if(!e||!e.sessionDescriptionHandler)return!1;let t=!0;const r=e.sessionDescriptionHandler.peerConnection;if(!r)return!1;if(r.getSenders){if(!r.getSenders().length)return!1;r.getSenders().forEach((e=>{e&&e.track&&"audio"===e.track.kind&&(t=t&&!e.track.enabled)}))}else{if(!r.getLocalStreams().length)return!1;r.getLocalStreams().forEach((e=>{e.getAudioTracks().forEach((e=>{t=t&&!e.enabled}))}))}return t}toggleCameraOn(e){logger$7.info("sdk webrtc toggle camera on",{id:e.id}),this._toggleVideo(e,!1)}toggleCameraOff(e){logger$7.info("sdk webrtc toggle camera off",{id:e.id}),this._toggleVideo(e,!0)}hold(e,t=!1,r=!1){const n=this.getSipSessionId(e),i=r||this.hasLocalVideo(n);if(logger$7.info("sdk webrtc hold",{sessionId:n,keys:Object.keys(this.heldSessions),pendingReinvite:!!e.pendingReinvite,isConference:t,hasVideo:i}),n in this.heldSessions)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();this.heldSessions[n]={hasVideo:i,isConference:t},this.mute(e),e.sessionDescriptionHandlerOptionsReInvite={hold:!0,conference:t};const s=this.getMediaConfiguration(!1,t);return this._isWeb()||(s.sessionDescriptionHandlerModifiers=[holdModifier]),s.sessionDescriptionHandlerOptions={constraints:s.constraints,hold:!0,conference:t},e.sessionDescriptionHandler&&(e.sessionDescriptionHandler.localMediaStreamConstraints=s.constraints),e.invite(s).catch((e=>{logger$7.warn("sdk webrtc re-invite during hold, error",e)}))}unhold(e,t=!1){const r=this.getSipSessionId(e),n=r in this.heldSessions&&this.heldSessions[r].hasVideo;if(logger$7.info("sdk webrtc unhold",{sessionId:r,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 i=this.getMediaConfiguration(!1,t);return this._isWeb()||(i.sessionDescriptionHandlerModifiers=[]),i.sessionDescriptionHandlerOptions={constraints:i.constraints,hold:!1,conference:t},e.invite(i).catch((e=>{logger$7.warn("sdk webrtc re-invite during resume, error",e)}))}async upgradeToVideo(e,t,r){const n=e.sessionDescriptionHandler?.peerConnection;let i;if(r){const e=n?.getTransceivers()||[],t=lastIndexOf(e,(e=>null===e.sender.track&&e.mid&&-1===e.mid.indexOf("video")));i=-1!==t?e[t].sender:null}else i=n&&n.getSenders&&n.getSenders().find((e=>null===e.track));if(!i)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,r=t.getTracks().find((e=>"audio"===e.kind));r&&s.addTrack(r)}const o=s.getVideoTracks()[0];return o&&i.replaceTrack(o),this.setLocalMediaStream(this.getSipSessionId(e),s),s}downgradeToAudio(e){const t=e.sessionDescriptionHandler,r=t?.localMediaStream,n=t?.peerConnection,i=r.getVideoTracks();n?.getSenders&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).forEach((e=>{e.replaceTrack(null)})),i.forEach((e=>{e.enabled=!1,e.stop(),r.removeTrack(e)}))}async getStreamFromConstraints(e,t=!1){const r=e&&e.video,{constraints:n}=this.getMediaConfiguration(r,t,e);let i=null;try{i=await wazoMediaStreamFactory(n)}catch(e){}return i?(i.local=!0,i):null}getHeldSession(e){return this.heldSessions[e]}isCallHeld(e){return this.getSipSessionId(e)in this.heldSessions}isVideoRemotelyHeld(e){const t=this.getPeerConnection(e),r=t&&t.remoteDescription?t.remoteDescription.sdp:null;if(!r)return!1;return"sendonly"===getVideoDirection(r)}sendDTMF(e,t){return!!e.sessionDescriptionHandler&&(logger$7.info("Sending DTMF",{id:this.getSipSessionId(e),tone:t}),e.sessionDescriptionHandler.sendDtmf(t))}message(e,t){const r=this._makeURI(e);if(!this.userAgent||!r)return void logger$7.warn("Null value on message",{uri:r,userAgent:this.userAgent});new Messager(this.userAgent,r,t).message()}transfer(e,t){this.hold(e),logger$7.info("Transfering a session",{id:this.getSipSessionId(e),target:t});const r={requestDelegate:{onAccept:()=>{this.hangup(e)}}};setTimeout((()=>{const n=this._makeURI(t);n?e.refer(n,r):logger$7.warn("transfer timeout: null URI")}),50)}atxfer(e){this.hold(e),logger$7.info("webrtc transfer started",{id:this.getSipSessionId(e)});const t={newSession:null,init:async r=>{logger$7.info("webrtc transfer initialized",{id:this.getSipSessionId(e),target:r}),t.newSession=await this.call(r)},complete:()=>{logger$7.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,r="text/plain"){if(e){logger$7.info("send WebRTC message",{sipId:e.id,contentType:r});try{e.message({requestOptions:{body:{content:t,contentType:r,contentDisposition:""}}})}catch(e){console.warn(e)}}}pingServer(){if(!this.isConnected())return;const e=this.userAgent?.userAgentCore,t=this._makeURI(this.config.authorizationUser||""),r=new URI("sip","",this.config.host);if(t){const n=e?.makeOutgoingRequestMessage("OPTIONS",r,t,r,{});if(n)return e?.request(n);logger$7.warn("pingServer: null message")}logger$7.warn("pingServer: null fromURI")}getState(){return this.userAgent?states[this.userAgent.state]:UserAgentState.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){logger$7.info("Changing audio output volume",{volume:e}),Object.values(this.audioElements).forEach((t=>{t instanceof HTMLAudioElement&&(t.volume=e)})),this.audioOutputVolume=e}changeAudioOutputDevice(e){logger$7.info("Changing audio output device",{id:e}),this.audioOutputDeviceId=e,Object.values(this.audioElements).forEach((t=>{t.setSinkId&&t.setSinkId(e)}))}async changeAudioInputDevice(e,t,r){const n=this.getAudioDeviceId();if(logger$7.info("setting audio input device",{id:e,currentId:n,session:!!t}),!r&&e===n)return null;let i=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 - ",""),o=e.find((e=>e.label===s));if(o&&(i=o.deviceId,!r&&i===n))return null}}if(this.audio&&(this.audio={deviceId:{exact:i}}),t&&navigator.mediaDevices){const e=t.sessionDescriptionHandler,r=e?.peerConnection,n={audio:{deviceId:{exact:i}}},s=await navigator.mediaDevices.getUserMedia(n),o=s.getAudioTracks()[0],a=r&&r.getSenders&&r.getSenders().find((e=>o&&e&&e.track&&e.track.kind===o.kind));return a&&(a.track&&(o.enabled=a.track.enabled),a.replaceTrack(o)),s}return null}async changeVideoInputDevice(e,t){if(this.setVideoInputDevice(e),t)return this.changeSessionVideoInputDevice(e,t)}setVideoInputDevice(e){const t=this.getVideoDeviceId();if(logger$7.info("setting video input device",{id:e,currentId:t}),e===t)return null;const r="object"==typeof this.video?this.video:{};this.video={...r,deviceId:{exact:e}}}changeSessionVideoInputDevice(e,t){if(!this.sessionWantsToDoVideo(t))return Promise.resolve();const r=t.sessionDescriptionHandler.peerConnection,n=this.getSipSessionId(t),i=this.getLocalStream(n);logger$7.info("changing video input device",{id:e,sessionId:n}),i&&i.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 i=r&&r.getSenders&&r.getSenders().find((e=>t&&e&&e.track&&e.track.kind===t.kind)),s=!1;return i||(i=r&&r.getSenders&&r.getSenders().find((e=>!e.track))),i&&(s=!!i.track&&i.track.enabled,t.enabled=s,s||t.stop(),i.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,r=!1,n=!1,i=!1){if(!e)return Promise.resolve();if(e.pendingReinvite)return Promise.resolve();const s=this.isAudioMuted(e),o=t?t.video:this.sessionWantsToDoVideo(e),a=t&&t.screen,d=t&&t.desktop;if(logger$7.info("Sending reinvite",{clientId:this.clientId,id:this.getSipSessionId(e),newConstraints:t,conference:r,audioOnly:n,wasMuted:s,shouldDoVideo:o,shouldDoScreenSharing:a,desktop:d}),t&&t.video){const t=e.sessionDescriptionHandlerModifiersReInvite;e.sessionDescriptionHandlerModifiersReInvite=t.filter((e=>e!==stripVideo))}e.sessionDescriptionHandlerOptionsReInvite={...e.sessionDescriptionHandlerOptionsReInvite,conference:r,audioOnly:n};const{constraints:c}=this.getMediaConfiguration(o,r,t);return e.invite({requestDelegate:{onAccept:t=>(e instanceof Inviter&&e.outgoingRequestMessage.body?e.outgoingRequestMessage.body.body=t.message.body:e instanceof Invitation&&(e.incomingInviteRequest.message.body=t.message.body),logger$7.info("on re-INVITE accepted",{id:this.getSipSessionId(e),wasMuted:s,shouldDoScreenSharing:a}),this.updateRemoteStream(this.getSipSessionId(e),!1),s&&this.mute(e),this._onAccepted(e,t.session,!1,!1),a&&this.eventEmitter.emit(ON_SCREEN_SHARING_REINVITE,e,t,d),this.eventEmitter.emit(ON_REINVITE,e,t))},sessionDescriptionHandlerModifiers:[replaceLocalIpModifier],requestOptions:{extraHeaders:["Subject: "+(a?"screenshare":"upgrade-video")]},sessionDescriptionHandlerOptions:{constraints:c,conference:r,audioOnly:n,offerOptions:{iceRestart:i}}})}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,SIP_ID_LENGTH):e instanceof Inviter&&e.outgoingRequestMessage?e.outgoingRequestMessage.callId.substring(0,SIP_ID_LENGTH):(e.id||"").substring(0,SIP_ID_LENGTH)}async waitForRegister(){return new Promise((e=>this.on(REGISTERED,e)))}sessionWantsToDoVideo(e){if(!e)return!1;const{body:t}=e.request||e,r="object"==typeof t&&t?t.body:t;return hasAnActiveVideo(r)}hasHeartbeat(){return this.heartbeat.hasHeartbeat}startHeartbeat(){logger$7.info("sdk webrtc start heartbeat",{userAgent:!!this.userAgent,clientId:this.clientId}),this.userAgent?(this.eventEmitter.off(MESSAGE,this._boundOnHeartbeat),this.eventEmitter.on(MESSAGE,this._boundOnHeartbeat),this.heartbeat.start()):this.heartbeat.stop()}stopHeartbeat(){logger$7.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(){logger$7.info("attempt reconnection",{clientId:this.clientId,userAgent:!!this.userAgent}),this.userAgent&&this.userAgent.attemptReconnection()}storeSipSession(e){const t=this.getSipSessionId(e);logger$7.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,SIP_ID_LENGTH)]:null}getSipSessionIds(){return Object.keys(this.sipSessions)}setLocalMediaStream(e,t){const r=this.sipSessions[e];r&&(logger$7.info("setting local media stream",{sipSessionId:e,tracks:t?t.getTracks():null}),r.sessionDescriptionHandler&&(r.sessionDescriptionHandler._localMediaStream=t))}updateLocalStream(e,t){const r=this.sipSessions[e];if(!r)return;const n=this.getLocalStream(e);logger$7.info("updating local stream",{sipSessionId:e,oldStream:!!n,tracks:t.getTracks()}),n&&this._cleanupStream(n),this.setLocalMediaStream(e,t),this._setupMedias(r,t)}updateRemoteStream(e,t=!0){const r=this.getRemoteStream(e),n=this.getPeerConnection(e);logger$7.info("Updating remote stream",{sessionId:e,tracks:r?r.getTracks():null,receiverTracks:n&&n.getReceivers?n.getReceivers().map((e=>e.track)):null}),n&&r&&(r.getTracks().forEach((e=>{(t||"video"===e.kind)&&r.removeTrack(e)})),n.getReceivers&&n.getReceivers().forEach((e=>{(t||"video"===e.track.kind)&&r.addTrack(e.track)})))}getMediaConfiguration(e,t=!1,r=null){const n=!(!r||!("screen"in r))&&r.screen,i=!(!r||!("desktop"in r))&&r.desktop,s=!r||!("audio"in r)||r.audio,o=r&&"object"==typeof r.video?r.video.mandatory:{};return logger$7.info("Retrieving media a configuration",{enableVideo:e,screenSharing:n,isDesktop:i,withAudio:s,constraints:r}),{constraints:{audio:n?!i:!!s&&this._getAudioConstraints(),video:n?i?{mandatory:{chromeMediaSource:"desktop",...o||{}}}:{cursor:"always"}:this._getVideoConstraints(e),screen:n,desktop:i,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}createAudioElementFor(e){const t=document.createElement("audio");return t.setAttribute("id",`audio-${e}`),logger$7.info("creating audio element",{sessionId:e,audioOutputDeviceId:this.audioOutputDeviceId}),t.setSinkId&&this.audioOutputDeviceId&&t.setSinkId(this.audioOutputDeviceId),document.body&&document.body.appendChild(t),this.audioElements[e]=t,t.volume=this.audioOutputVolume,t.autoplay=!0,t}_onTransportError(){logger$7.error("on transport error"),this.eventEmitter.emit(TRANSPORT_ERROR),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()&&(logger$7.info("on heartbeat received from Asterisk",{hasHeartbeat:this.hasHeartbeat()}),this.heartbeat.onHeartbeat(),this.heartbeatCb&&this.heartbeatCb())}async _onHeartbeatTimeout(){if(logger$7.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){logger$7.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 logger$7.info("connect if needed, checking",{connected:this.isConnected(),clientId:this.clientId}),this.userAgent||(logger$7.info("need to recreate User Agent"),this.userAgent=this.createUserAgent(this.uaConfigOverrides)),this.isConnected()?(logger$7.info("webrtc sdk, already connected"),Promise.resolve()):this.isConnecting()?(logger$7.info("webrtc sdk, already connecting..."),this.connectionPromise=this.userAgent.transport.connectPromise,Promise.resolve(this.connectionPromise)):this.connectionPromise?(logger$7.info("webrtc sdk, connection promise connecting..."),this.connectionPromise):(logger$7.info("WebRTC UA needs to connect"),this.userAgent&&this.userAgent.state!==UserAgentState.Stopped&&this.userAgent.transitionState(UserAgentState.Stopped),this.userAgent.transport&&this.userAgent.transport.state!==TransportState.Disconnected&&this.userAgent.transport.transitionState(TransportState.Disconnected),this.connectionPromise=this.userAgent.start().catch(console.error),this.connectionPromise)}_buildConfig(e,t){if(!t)return new Promise((t=>t(e)));const r=new ApiClient({server:`${e.host}:${String(e.port||443)}`});return r.setToken(t.token),r.setRefreshToken(t.refreshToken),r.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,r=this.config.port||443;if(this.config.websocketSip){const e=this.config.websocketSip.split(":");[t]=e,r=Number(e[1])}const{userUuid:n}=this.config,i={noAnswerTimeout:NO_ANSWER_TIMEOUT,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 r=e.userAgent.getLogger("sip.WazoSessionDescriptionHandler"),n=this._isWeb(),i="peerConnectionOptions"in t&&t.peerConnectionOptions.iceGatheringTimeout||DEFAULT_ICE_TIMEOUT,s={...t,iceGatheringTimeout:i,peerConnectionConfiguration:{...defaultPeerConnectionConfiguration(),...t.peerConnectionConfiguration||{}}};return new WazoSessionDescriptionHandler(r,wazoMediaStreamFactory,s,n,e)},transportOptions:{traceSip:e?.traceSip||!1,wsServers:`wss://${t}:${r}/api/asterisk/ws${n?`?userUuid=${n}`:""}`},sessionDescriptionHandlerFactoryOptions:{modifiers:[replaceLocalIpModifier],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:WebRTCClient.getIceServers(this.config.host),...this._getRtcOptions(),...e?.peerConnectionOptions||{}}},peerConnectionConfiguration:{rtcpMuxPolicy:"require",iceServers:WebRTCClient.getIceServers(this.config.host),...e?.peerConnectionOptions||{}}}};return delete e?.traceSip,{...i,...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(ON_ERROR,e)})),e.peerConnectionDelegate={onicecandidateerror:e=>{logger$7.error("on icecandidate error",{address:e.address,port:e.port,errorCode:e.errorCode,errorText:e.errorText,url:e.url})}}};const r=e.onInviteRequest.bind(e);let n=!1;e.onInviteRequest=e=>{n=this.hasARemoteVideoTrack(t),r(e)},e.delegate.onInvite=r=>{let i=null,s=null;return e.assertedIdentity&&(s=e.assertedIdentity.uri.normal.user,i=e.assertedIdentity.displayName||s),logger$7.info("re-invite received",{updatedCalleeName:i,updatedNumber:s,hadRemoteVideo:n}),e instanceof Invitation?e.incomingInviteRequest.message.body=r.body:e instanceof Inviter&&e.outgoingInviteRequest.message.body&&(e.outgoingInviteRequest.message.body.body=r.body),this.updateRemoteStream(t,!1),this._setupMedias(e),this.eventEmitter.emit(ON_REINVITE,e,r,i,s,n)}}_onProgress(e,t=!1){this._setupMedias(e);const r=this.getSipSessionId(e).substr(0,20);this.updateRemoteStream(r),logger$7.info("progress received",{sessionId:r,early:t}),this.eventEmitter.emit(t?ON_EARLY_MEDIA:ON_PROGRESS,e)}_onAccepted(e,t,r=!0,n=!0){logger$7.info("on call accepted",{id:e.id,clientId:this.clientId,remoteTag:e.remoteTag}),this.storeSipSession(e),this._setupMedias(e),this.updateRemoteStream(this.getSipSessionId(e),n);const i=e.sessionDescriptionHandler?.peerConnection,s=t=>{const r=this._isAudioOnly(e),{kind:n,label:i,readyState:s,id:o,muted:a}=t.track;logger$7.info("on track event",{isAudioOnly:r,kind:n,label:i,readyState:s,id:o,muted:a}),r&&"video"===n&&t.track.stop(),this.eventEmitter.emit(ON_TRACK,e,t)},o=e.sessionDescriptionHandler;o?.peerConnection&&o.peerConnection.addEventListener("track",s),o.remoteMediaStream.onaddtrack=s,i&&(i.oniceconnectionstatechange=()=>{logger$7.info("on ice connection state changed",{state:i.iceConnectionState}),"disconnected"===i.iceConnectionState&&this.eventEmitter.emit(ON_DISCONNECTED)}),r&&this.eventEmitter.emit(ACCEPTED,e,t),this._startSendingStats(e)}_isAudioOnly(e){return Boolean(e.sessionDescriptionHandlerModifiersReInvite.find((e=>e===stripVideo)))}_setupMedias(e,t=null){if(!this._isWeb())return void logger$7.info("Setup media on mobile, no need to setup html element, bailing");const r=this.getSipSessionId(e),n=this.isConference(r);if(r in this.audioElements)return void logger$7.info("html element already exists for session",{sessionId:r});this._hasAudio()&&this._isWeb()&&!(r in this.audioElements)&&this.createAudioElementFor(r);const i=this.audioElements[r],s=this.sipSessions[e.callId],o=this.getRemoteStream(r),a=s?.sessionDescriptionHandler,d=a?a.remoteMediaStream:null,c=t||o||d;if(!c)return void logger$7.info("Setup media no stream to attach, bailing");const l=i.currentTime>0&&!i.paused&&!i.ended&&i.readyState>2;logger$7.info("setting up media",{sessionId:r,streams:{new:!!t,remove:!!o,early:!!d},hasAudio:this._hasAudio(),isConference:n,shouldPause:l}),n||(l&&i.pause(),i.srcObject=c,i.volume=this.audioOutputVolume,i.play().catch((()=>{})))}_cleanupMedia(e){const t=this.getSipSessionId(e),r=this.getLocalStream(t);r&&this._cleanupStream(r);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 r=e.sessionDescriptionHandler,n=r?.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 r=e.sessionDescriptionHandler,n=r?.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:r}=e;r&&t&&t.addTrack(r)}))):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 r=this.getSipSessionId(e);getStats(t,(e=>{const{results:t,internal:n,nomore:i,...s}=e;this.statsIntervals[r]=i,statsLogger.trace("stats",{sessionId:r,...s})}),SEND_STATS_DELAY)}_stopSendingStats(e){const t=this.getSipSessionId(e);logger$7.trace("Check for stopping stats",{sessionId:t,ids:Object.keys(this.statsIntervals)}),t in this.statsIntervals&&(logger$7.trace("Stop sending stats for call",{sessionId:t}),this.statsIntervals[t](),delete this.statsIntervals[t])}_makeURI(e){return UserAgent.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){logger$7.error("WebRTC transport disconnect, error",e)}}async _fetchNetworkStats(e){const t=this.getSipSession(e),r=t?await this.getStats(t):null;if(!r||!(e in this.sessionNetworkStats))return Promise.resolve(null);const n={audioBytesSent:0,videoBytesSent:0,videoBytesReceived:0,audioBytesReceived:0},i=this.sessionNetworkStats[e].length,s=this.sessionNetworkStats[e][i-1],o=s?s.audioBytesSent:0,a=s?s.audioContentSent:0,d=s?s.videoBytesSent:0,c=s?s.audioBytesReceived:0,l=s?s.audioContentReceived:0,u=s?s.videoBytesReceived:0,h=s?s.transportSent:0,g=s?s.transportReceived:0;let p=0,m=0,f=0,S=0,y=0,b=0,E=0,v=0,_=0;r.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.kind&&(p+=Number(e.bytesSent)+Number(e.headerBytesSent),f+=Number(e.bytesSent)),"remote-outbound-rtp"===e.type&&"audio"===e.kind&&(p+=Number(e.bytesSent)),"outbound-rtp"===e.type&&"video"===e.kind&&(y+=Number(e.bytesSent)+Number(e.headerBytesSent)),"inbound-rtp"===e.type&&"audio"===e.kind&&(_+=Number(e.packetsLost),n.packetsReceived=Number(e.packetsReceived),m+=Number(e.bytesReceived)+Number(e.headerBytesReceived),S+=Number(e.bytesReceived)),"inbound-rtp"===e.type&&"video"===e.kind&&(b+=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&&(_+=Number(e.packetsLost),n.roundTripTime=Number(e.roundTripTime),n.jitter=Number(e.jitter)),"remote-inbound-rtp"===e.type&&"video"===e.kind&&(_+=Number(e.packetsLost)),"transport"===e.type&&(E+=Number(e.bytesSent),v+=Number(e.bytesReceived))})),n.packetsLost=_,n.totalAudioBytesSent=p,n.audioBytesSent=p-o,n.totalAudioBytesReceived=m-c,n.audioBytesReceived=m,n.totalAudioContentSent=f,n.audioContentSent=f-a,n.totalAudioBytesReceived=S-l,n.audioContentReceived=S,n.totalVideoBytesSent=y,n.videoBytesSent=y-d,n.totalVideoBytesReceived=b,n.videoBytesReceived=b-u,n.totalTransportSent=E-h,n.transportSent=E,n.totalTransportReceived=v,n.transportReceived=v-g,n.bandwidth=n.audioBytesSent+n.audioBytesReceived+n.videoBytesSent+n.videoBytesReceived+n.transportReceived+n.transportSent,this.sessionNetworkStats[e]&&(this.eventEmitter.emit(ON_NETWORK_STATS,t,n,this.sessionNetworkStats[e]),e in this.sessionNetworkStats&&this.sessionNetworkStats[e].push(n))}async _accept(e,t={}){if(e.state===SessionState$1.Terminated||e.state===SessionState$1.Terminating){const t="Trying to accept a terminated sipSession.";throw logger$7.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}if(e.state!==SessionState$1.Initial){const t="Trying to accept a non Initial sipSession.";throw logger$7.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 logger$7.warn(t,{state:e.state,sessionId:e.id}),new Error(t)}try{return await e.accept(t)}catch(e){logger$7.warn("Session accept, error",e)}}async _reject(e,t={}){if(e.state===SessionState$1.Initial||e.state===SessionState$1.Establishing)if(e.incomingInviteRequest.rejectable)try{return await e.reject(t)}catch(e){logger$7.warn("Session reject, error",e)}else logger$7.warn("Trying to reject a non `rejectable` session",{state:e.state,sessionId:e.id});else logger$7.warn("Trying to reject a session in a wrong state",{state:e.state,sessionId:e.id})}async _cancel(e,t={}){if(e.state===SessionState$1.Initial||e.state===SessionState$1.Establishing)try{return await e.cancel(t)}catch(e){logger$7.warn("Session cancel, error",e)}else logger$7.warn("Trying to cancel a session in a wrong state",{state:e.state,sessionId:e.id})}async _bye(e,t={}){if(e.state!==SessionState$1.Established)return logger$7.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){logger$7.warn("Session bye, error",e)}return null}}class SFUNotAvailableError extends Error{constructor(e="Sorry your user is not configured to support video conference"){super(e),this.name="SFUNotAvailableError"}}const logger$6=IssueReporter$1.loggerFor("simple-phone"),sipLogger=IssueReporter$1.loggerFor("sip.js"),protocolLogger=IssueReporter$1.loggerFor("sip"),protocolDebugMessages=["Received WebSocket text message:","Sending WebSocket message:"];class Phone extends Emitter{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(PHONE_EVENTS).forEach((e=>{this[e]=PHONE_EVENTS[e]})),this.SessionState=SessionState$1}async connect(e={},t=null){const r=e;if(this.phone)return void(r.media&&this.phone.setMediaConstraints(r.media));const n=Wazo$1.Auth.getHost(),i=Wazo$1.Auth.getSession();if(!n||!i)throw new Error("Please connect to the server using `Wazo.Auth.logIn` or `Wazo.Auth.authenticate` before using Room.connect().");if(this.session=i,this.sipLine=t||this.getPrimaryWebRtcLine(),!this.sipLine)throw new Error("Sorry, no sip lines found for this user");r.userUuid=i.uuid||"",this.connectWithCredentials(n,this.sipLine,i.displayName(),r)}connectWithCredentials(e,t,r,n={}){if(this.phone)return;const[i,s=443]=e.split(":"),o=n;o.media=o.media||{audio:!0,video:!1},o.uaConfigOverrides=o.uaConfigOverrides||{},IssueReporter$1.enabled&&(o.uaConfigOverrides.traceSip=!0,o.log=o.log||{},o.log.builtinEnabled=!1,o.log.logLevel="debug",o.log.connector=this._logConnector),this.client=new WebRTCClient({host:i,port:"string"==typeof s?parseInt(s,10):s,displayName:r,authorizationUser:t.username,password:t.secret,uri:`${t.username}@${e}`,...o},null,o.uaConfigOverrides),this.phone=new WebRTCPhone(this.client,o.audioDeviceOutput,!0,o.audioDeviceRing),this._transferEvents()}async disconnect(){this.phone&&(this.phone.hasAnActiveCall()&&(logger$6.info("hangup call on disconnect"),await this.phone.hangup()),await this.phone.close()),this.phone=null}async call(e,t=!1,r=null,n=!1,i=!1){if(!this.phone)return;const s=r||this.getPrimaryWebRtcLine();return this.phone.makeCall(e,s,t,n,i)}async hangup(e){return logger$6.info("hangup via simple phone",{callId:e.getId()}),!!this.phone&&this.phone.hangup(e)}async accept(e,t){return logger$6.info("accept via simple phone",{callId:e.getId(),cameraEnabled:t}),this.phone?this.phone.accept(e,t):null}async startConference(e,t){const r=[e,...t].reduce(((e,t)=>(e[t.getTalkingToIds()[0]]=t,e)),{});if(!this.phone)return Promise.reject();return new AdHocAPIConference({phone:this.phone,host:e,participants:r}).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&&Wazo$1.getApiClient().calld.mute(e.callId).catch((e=>{logger$6.error("Mute via API, error",e)}))}unmuteViaAPI(e){e&&e.callId&&Wazo$1.getApiClient().calld.unmute(e.callId).catch((e=>{logger$6.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,r=!1){return this.phone?this.phone.sendReinvite(e,t,r):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,r="text/plain"){const n=t||this.getCurrentSipSession();n&&this.phone&&this.phone.sendMessage(n,e,r)}sendChat(e,t){this.sendMessage(JSON.stringify({type:MESSAGE_TYPE_CHAT,content:e}),t,"application/json")}sendSignal(e,t){this.sendMessage(JSON.stringify({type:MESSAGE_TYPE_SIGNAL,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 logger$6.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 logger$6.warn("Phone.getRemoteStreamForCall is deprecated, use Phone.getRemoteStream instead"),this.getRemoteStream(e)||null}getRemoteStreamsForCall(e){return logger$6.warn("Phone.getRemoteStreamsForCall is deprecated, use Phone.getLocalStream instead"),this.getLocalStream(e)||null}getRemoteVideoStreamForCall(e){return logger$6.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=Wazo$1.Auth.getSession();return e?.primaryWebRtcLine()||null}getOutputDevice(){return this.phone?.audioOutputDeviceId||null}getPrimaryLine(){const e=Wazo$1.Auth.getSession();return e?.primarySipLine()||null}getLineById(e){return this.getSipLines().find((t=>t&&t.id===e))||null}getSipLines(){const e=Wazo$1.Auth.getSession();return e&&e.profile?.sipLines||[]}hasSfu(){return this.sipLine?.hasVideoConference()||!1}checkSfu(){if(!this.hasSfu())throw new SFUNotAvailableError}enableLogger(){this.client.enableLogger(this._logConnector)}_transferEvents(){this.unbind(),[...events,...transportEvents].forEach((e=>{this.client.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter.emit,[`client-${e}`,...t])))})),Object.values(PHONE_EVENTS).forEach((e=>{"string"==typeof e&&this.phone&&this.phone.on(e,((...t)=>this.eventEmitter.emit.apply(this.eventEmitter,[e,...t])))}))}_logConnector(e,t,r,n){const i=n&&n.indexOf?protocolDebugMessages.findIndex((e=>-1!==n.indexOf(e))):-1;if("sip.Transport"===t&&-1!==i){const e=0===i?"receiving":"sending",r=n.replace(`${protocolDebugMessages[i]}\n\n`,"").replace("\r\n","\n");protocolLogger.trace(r,{className:t,direction:e})}else sipLogger.trace(n,{className:t})}}global.wazoTelephonyInstance||(global.wazoTelephonyInstance=new Phone);var Phone$1=global.wazoTelephonyInstance,extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},extendStatics(e,t)};
32
29
  /*! *****************************************************************************
33
30
  Copyright (c) Microsoft Corporation. All rights reserved.
34
31
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use