diff options
author | RaindropsSys <contact@minteck.org> | 2023-04-24 14:03:36 +0200 |
---|---|---|
committer | RaindropsSys <contact@minteck.org> | 2023-04-24 14:03:36 +0200 |
commit | 633c92eae865e957121e08de634aeee11a8b3992 (patch) | |
tree | 09d881bee1dae0b6eee49db1dfaf0f500240606c /includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js | |
parent | c4657e4509733699c0f26a3c900bab47e915d5a0 (diff) | |
download | pluralconnect-633c92eae865e957121e08de634aeee11a8b3992.tar.gz pluralconnect-633c92eae865e957121e08de634aeee11a8b3992.tar.bz2 pluralconnect-633c92eae865e957121e08de634aeee11a8b3992.zip |
Updated 18 files, added 1692 files and deleted includes/system/compare.inc (automated)
Diffstat (limited to 'includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js')
-rw-r--r-- | includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js new file mode 100644 index 0000000..12920d0 --- /dev/null +++ b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js @@ -0,0 +1,18 @@ +!function e(t,i,n){function r(s,a){if(!i[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var d=new Error("Cannot find module '"+s+"'");throw d.code="MODULE_NOT_FOUND",d}var l=i[s]={exports:{}};t[s][0].call(l.exports,(function(e){return r(t[s][1][e]||e)}),l,l.exports,e,t,i,n)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<n.length;s++)r(n[s]);return r}({1:[function(e,t,i){"use strict";for(var n=/[\\\"\x00-\x1F]/g,r={},o=0;o<32;++o)r[String.fromCharCode(o)]="\\U"+("0000"+o.toString(16)).slice(-4).toUpperCase();function s(e){return n.lastIndex=0,e.replace(n,(function(e){return r[e]}))}function a(e){switch(typeof e){case"string":return'"'+s(e)+'"';case"number":return isFinite(e)?e:"null";case"boolean":return e;case"object":return null===e?"null":Array.isArray(e)?function(e){for(var t="[",i="",n=0;n<e.length;++n)i+=t,t=",",i+=a(e[n]);return","!=t?"[]":i+"]"}(e):function(e){var t="{",i="",n=Object.keys(e);n.sort();for(var r=0;r<n.length;++r){var o=n[r];i+=t+'"'+s(o)+'":',t=",",i+=a(e[o])}return","!=t?"{}":i+"}"}(e);default:throw new Error("Cannot stringify: "+typeof e)}}r["\b"]="\\b",r["\t"]="\\t",r["\n"]="\\n",r["\f"]="\\f",r["\r"]="\\r",r['"']='\\"',r["\\"]="\\\\",t.exports={stringify:a}},{}],2:[function(e,t,i){"use strict";const n=i;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":3,"./asn1/base":5,"./asn1/constants":9,"./asn1/decoders":11,"./asn1/encoders":14,"bn.js":18}],3:[function(e,t,i){"use strict";const n=e("./encoders"),r=e("./decoders"),o=e("inherits");function s(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}i.define=function(e,t){return new s(e,t)},s.prototype._createNamed=function(e){const t=this.name;function i(e){this._initNamed(e,t)}return o(i,e),i.prototype._initNamed=function(t,i){e.call(this,t,i)},new i(this)},s.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(r[e])),this.decoders[e]},s.prototype.decode=function(e,t,i){return this._getDecoder(t).decode(e,i)},s.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n[e])),this.encoders[e]},s.prototype.encode=function(e,t,i){return this._getEncoder(t).encode(e,i)}},{"./decoders":11,"./encoders":14,inherits:146}],4:[function(e,t,i){"use strict";const n=e("inherits"),r=e("../base/reporter").Reporter,o=e("safer-buffer").Buffer;function s(e,t){r.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function a(e,t){if(Array.isArray(e))this.length=0,this.value=e.map((function(e){return a.isEncoderBuffer(e)||(e=new a(e,t)),this.length+=e.length,e}),this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(s,r),i.DecoderBuffer=s,s.isDecoderBuffer=function(e){if(e instanceof s)return!0;return"object"==typeof e&&o.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},s.prototype.save=function(){return{offset:this.offset,reporter:r.prototype.save.call(this)}},s.prototype.restore=function(e){const t=new s(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,r.prototype.restore.call(this,e.reporter),t},s.prototype.isEmpty=function(){return this.offset===this.length},s.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},s.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");const i=new s(this.base);return i._reporterState=this._reporterState,i.offset=this.offset,i.length=this.offset+e,this.offset+=e,i},s.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},i.EncoderBuffer=a,a.isEncoderBuffer=function(e){if(e instanceof a)return!0;return"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},a.prototype.join=function(e,t){return e||(e=o.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach((function(i){i.join(e,t),t+=i.length})):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},{"../base/reporter":7,inherits:146,"safer-buffer":251}],5:[function(e,t,i){"use strict";const n=i;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":4,"./node":6,"./reporter":7}],6:[function(e,t,i){"use strict";const n=e("../base/reporter").Reporter,r=e("../base/buffer").EncoderBuffer,o=e("../base/buffer").DecoderBuffer,s=e("minimalistic-assert"),a=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],c=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(a);function d(e,t,i){const n={};this._baseState=n,n.name=i,n.enc=e,n.parent=t||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}t.exports=d;const l=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];d.prototype.clone=function(){const e=this._baseState,t={};l.forEach((function(i){t[i]=e[i]}));const i=new this.constructor(t.parent);return i._baseState=t,i},d.prototype._wrap=function(){const e=this._baseState;c.forEach((function(t){this[t]=function(){const i=new this.constructor(this);return e.children.push(i),i[t].apply(i,arguments)}}),this)},d.prototype._init=function(e){const t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter((function(e){return e._baseState.parent===this}),this),s.equal(t.children.length,1,"Root node can have only one child")},d.prototype._useArgs=function(e){const t=this._baseState,i=e.filter((function(e){return e instanceof this.constructor}),this);e=e.filter((function(e){return!(e instanceof this.constructor)}),this),0!==i.length&&(s(null===t.children),t.children=i,i.forEach((function(e){e._baseState.parent=this}),this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map((function(e){if("object"!=typeof e||e.constructor!==Object)return e;const t={};return Object.keys(e).forEach((function(i){i==(0|i)&&(i|=0);const n=e[i];t[n]=i})),t})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(e){d.prototype[e]=function(){const t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}})),a.forEach((function(e){d.prototype[e]=function(){const t=this._baseState,i=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(i),this}})),d.prototype.use=function(e){s(e);const t=this._baseState;return s(null===t.use),t.use=e,this},d.prototype.optional=function(){return this._baseState.optional=!0,this},d.prototype.def=function(e){const t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},d.prototype.explicit=function(e){const t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},d.prototype.implicit=function(e){const t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},d.prototype.obj=function(){const e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},d.prototype.key=function(e){const t=this._baseState;return s(null===t.key),t.key=e,this},d.prototype.any=function(){return this._baseState.any=!0,this},d.prototype.choice=function(e){const t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map((function(t){return e[t]}))),this},d.prototype.contains=function(e){const t=this._baseState;return s(null===t.use),t.contains=e,this},d.prototype._decode=function(e,t){const i=this._baseState;if(null===i.parent)return e.wrapResult(i.children[0]._decode(e,t));let n,r=i.default,s=!0,a=null;if(null!==i.key&&(a=e.enterKey(i.key)),i.optional){let n=null;if(null!==i.explicit?n=i.explicit:null!==i.implicit?n=i.implicit:null!==i.tag&&(n=i.tag),null!==n||i.any){if(s=this._peekTag(e,n,i.any),e.isError(s))return s}else{const n=e.save();try{null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(n)}}if(i.obj&&s&&(n=e.enterObject()),s){if(null!==i.explicit){const t=this._decodeTag(e,i.explicit);if(e.isError(t))return t;e=t}const n=e.offset;if(null===i.use&&null===i.choice){let t;i.any&&(t=e.save());const n=this._decodeTag(e,null!==i.implicit?i.implicit:i.tag,i.any);if(e.isError(n))return n;i.any?r=e.raw(t):e=n}if(t&&t.track&&null!==i.tag&&t.track(e.path(),n,e.length,"tagged"),t&&t.track&&null!==i.tag&&t.track(e.path(),e.offset,e.length,"content"),i.any||(r=null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t)),e.isError(r))return r;if(i.any||null!==i.choice||null===i.children||i.children.forEach((function(i){i._decode(e,t)})),i.contains&&("octstr"===i.tag||"bitstr"===i.tag)){const n=new o(r);r=this._getUse(i.contains,e._reporterState.obj)._decode(n,t)}}return i.obj&&s&&(r=e.leaveObject(n)),null===i.key||null===r&&!0!==s?null!==a&&e.exitKey(a):e.leaveKey(a,i.key,r),r},d.prototype._decodeGeneric=function(e,t,i){const n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],i):/str$/.test(e)?this._decodeStr(t,e,i):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],i):"objid"===e?this._decodeObjid(t,null,null,i):"gentime"===e||"utctime"===e?this._decodeTime(t,e,i):"null_"===e?this._decodeNull(t,i):"bool"===e?this._decodeBool(t,i):"objDesc"===e?this._decodeStr(t,e,i):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],i):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,i):t.error("unknown tag: "+e)},d.prototype._getUse=function(e,t){const i=this._baseState;return i.useDecoder=this._use(e,t),s(null===i.useDecoder._baseState.parent),i.useDecoder=i.useDecoder._baseState.children[0],i.implicit!==i.useDecoder._baseState.implicit&&(i.useDecoder=i.useDecoder.clone(),i.useDecoder._baseState.implicit=i.implicit),i.useDecoder},d.prototype._decodeChoice=function(e,t){const i=this._baseState;let n=null,r=!1;return Object.keys(i.choice).some((function(o){const s=e.save(),a=i.choice[o];try{const i=a._decode(e,t);if(e.isError(i))return!1;n={type:o,value:i},r=!0}catch(t){return e.restore(s),!1}return!0}),this),r?n:e.error("Choice not matched")},d.prototype._createEncoderBuffer=function(e){return new r(e,this.reporter)},d.prototype._encode=function(e,t,i){const n=this._baseState;if(null!==n.default&&n.default===e)return;const r=this._encodeValue(e,t,i);return void 0===r||this._skipDefault(r,t,i)?void 0:r},d.prototype._encodeValue=function(e,t,i){const r=this._baseState;if(null===r.parent)return r.children[0]._encode(e,t||new n);let o=null;if(this.reporter=t,r.optional&&void 0===e){if(null===r.default)return;e=r.default}let s=null,a=!1;if(r.any)o=this._createEncoderBuffer(e);else if(r.choice)o=this._encodeChoice(e,t);else if(r.contains)s=this._getUse(r.contains,i)._encode(e,t),a=!0;else if(r.children)s=r.children.map((function(i){if("null_"===i._baseState.tag)return i._encode(null,t,e);if(null===i._baseState.key)return t.error("Child should have a key");const n=t.enterKey(i._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");const r=i._encode(e[i._baseState.key],t,e);return t.leaveKey(n),r}),this).filter((function(e){return e})),s=this._createEncoderBuffer(s);else if("seqof"===r.tag||"setof"===r.tag){if(!r.args||1!==r.args.length)return t.error("Too many args for : "+r.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");const i=this.clone();i._baseState.implicit=null,s=this._createEncoderBuffer(e.map((function(i){const n=this._baseState;return this._getUse(n.args[0],e)._encode(i,t)}),i))}else null!==r.use?o=this._getUse(r.use,i)._encode(e,t):(s=this._encodePrimitive(r.tag,e),a=!0);if(!r.any&&null===r.choice){const e=null!==r.implicit?r.implicit:r.tag,i=null===r.implicit?"universal":"context";null===e?null===r.use&&t.error("Tag could be omitted only for .use()"):null===r.use&&(o=this._encodeComposite(e,a,i,s))}return null!==r.explicit&&(o=this._encodeComposite(r.explicit,!1,"context",o)),o},d.prototype._encodeChoice=function(e,t){const i=this._baseState,n=i.choice[e.type];return n||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(i.choice))),n._encode(e.value,t)},d.prototype._encodePrimitive=function(e,t){const i=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&i.args)return this._encodeObjid(t,i.reverseArgs[0],i.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,i.args&&i.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},d.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},d.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},{"../base/buffer":4,"../base/reporter":7,"minimalistic-assert":223}],7:[function(e,t,i){"use strict";const n=e("inherits");function r(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}i.Reporter=r,r.prototype.isError=function(e){return e instanceof o},r.prototype.save=function(){const e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},r.prototype.restore=function(e){const t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},r.prototype.enterKey=function(e){return this._reporterState.path.push(e)},r.prototype.exitKey=function(e){const t=this._reporterState;t.path=t.path.slice(0,e-1)},r.prototype.leaveKey=function(e,t,i){const n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=i)},r.prototype.path=function(){return this._reporterState.path.join("/")},r.prototype.enterObject=function(){const e=this._reporterState,t=e.obj;return e.obj={},t},r.prototype.leaveObject=function(e){const t=this._reporterState,i=t.obj;return t.obj=e,i},r.prototype.error=function(e){let t;const i=this._reporterState,n=e instanceof o;if(t=n?e:new o(i.path.map((function(e){return"["+JSON.stringify(e)+"]"})).join(""),e.message||e,e.stack),!i.options.partial)throw t;return n||i.errors.push(t),t},r.prototype.wrapResult=function(e){const t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:146}],8:[function(e,t,i){"use strict";function n(e){const t={};return Object.keys(e).forEach((function(i){(0|i)==i&&(i|=0);const n=e[i];t[n]=i})),t}i.tagClass={0:"universal",1:"application",2:"context",3:"private"},i.tagClassByName=n(i.tagClass),i.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},i.tagByName=n(i.tag)},{}],9:[function(e,t,i){"use strict";const n=i;n._reverse=function(e){const t={};return Object.keys(e).forEach((function(i){(0|i)==i&&(i|=0);const n=e[i];t[n]=i})),t},n.der=e("./der")},{"./der":8}],10:[function(e,t,i){"use strict";const n=e("inherits"),r=e("bn.js"),o=e("../base/buffer").DecoderBuffer,s=e("../base/node"),a=e("../constants/der");function c(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new d,this.tree._init(e.body)}function d(e){s.call(this,"der",e)}function l(e,t){let i=e.readUInt8(t);if(e.isError(i))return i;const n=a.tagClass[i>>6],r=0==(32&i);if(31==(31&i)){let n=i;for(i=0;128==(128&n);){if(n=e.readUInt8(t),e.isError(n))return n;i<<=7,i|=127&n}}else i&=31;return{cls:n,primitive:r,tag:i,tagStr:a.tag[i]}}function u(e,t,i){let n=e.readUInt8(i);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;const r=127&n;if(r>4)return e.error("length octect is too long");n=0;for(let t=0;t<r;t++){n<<=8;const t=e.readUInt8(i);if(e.isError(t))return t;n|=t}return n}t.exports=c,c.prototype.decode=function(e,t){return o.isDecoderBuffer(e)||(e=new o(e,t)),this.tree._decode(e,t)},n(d,s),d.prototype._peekTag=function(e,t,i){if(e.isEmpty())return!1;const n=e.save(),r=l(e,'Failed to peek tag: "'+t+'"');return e.isError(r)?r:(e.restore(n),r.tag===t||r.tagStr===t||r.tagStr+"of"===t||i)},d.prototype._decodeTag=function(e,t,i){const n=l(e,'Failed to decode tag of "'+t+'"');if(e.isError(n))return n;let r=u(e,n.primitive,'Failed to get length of "'+t+'"');if(e.isError(r))return r;if(!i&&n.tag!==t&&n.tagStr!==t&&n.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(n.primitive||null!==r)return e.skip(r,'Failed to match body of: "'+t+'"');const o=e.save(),s=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(s)?s:(r=e.offset-o.offset,e.restore(o),e.skip(r,'Failed to match body of: "'+t+'"'))},d.prototype._skipUntilEnd=function(e,t){for(;;){const i=l(e,t);if(e.isError(i))return i;const n=u(e,i.primitive,t);if(e.isError(n))return n;let r;if(r=i.primitive||null!==n?e.skip(n):this._skipUntilEnd(e,t),e.isError(r))return r;if("end"===i.tagStr)break}},d.prototype._decodeList=function(e,t,i,n){const r=[];for(;!e.isEmpty();){const t=this._peekTag(e,"end");if(e.isError(t))return t;const o=i.decode(e,"der",n);if(e.isError(o)&&t)break;r.push(o)}return r},d.prototype._decodeStr=function(e,t){if("bitstr"===t){const t=e.readUInt8();return e.isError(t)?t:{unused:t,data:e.raw()}}if("bmpstr"===t){const t=e.raw();if(t.length%2==1)return e.error("Decoding of string type: bmpstr length mismatch");let i="";for(let e=0;e<t.length/2;e++)i+=String.fromCharCode(t.readUInt16BE(2*e));return i}if("numstr"===t){const t=e.raw().toString("ascii");return this._isNumstr(t)?t:e.error("Decoding of string type: numstr unsupported characters")}if("octstr"===t)return e.raw();if("objDesc"===t)return e.raw();if("printstr"===t){const t=e.raw().toString("ascii");return this._isPrintstr(t)?t:e.error("Decoding of string type: printstr unsupported characters")}return/str$/.test(t)?e.raw().toString():e.error("Decoding of string type: "+t+" unsupported")},d.prototype._decodeObjid=function(e,t,i){let n;const r=[];let o=0,s=0;for(;!e.isEmpty();)s=e.readUInt8(),o<<=7,o|=127&s,0==(128&s)&&(r.push(o),o=0);128&s&&r.push(o);const a=r[0]/40|0,c=r[0]%40;if(n=i?r:[a,c].concat(r.slice(1)),t){let e=t[n.join(" ")];void 0===e&&(e=t[n.join(".")]),void 0!==e&&(n=e)}return n},d.prototype._decodeTime=function(e,t){const i=e.raw().toString();let n,r,o,s,a,c;if("gentime"===t)n=0|i.slice(0,4),r=0|i.slice(4,6),o=0|i.slice(6,8),s=0|i.slice(8,10),a=0|i.slice(10,12),c=0|i.slice(12,14);else{if("utctime"!==t)return e.error("Decoding "+t+" time is not supported yet");n=0|i.slice(0,2),r=0|i.slice(2,4),o=0|i.slice(4,6),s=0|i.slice(6,8),a=0|i.slice(8,10),c=0|i.slice(10,12),n=n<70?2e3+n:1900+n}return Date.UTC(n,r-1,o,s,a,c,0)},d.prototype._decodeNull=function(){return null},d.prototype._decodeBool=function(e){const t=e.readUInt8();return e.isError(t)?t:0!==t},d.prototype._decodeInt=function(e,t){const i=e.raw();let n=new r(i);return t&&(n=t[n.toString(10)]||n),n},d.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getDecoder("der").tree}},{"../base/buffer":4,"../base/node":6,"../constants/der":8,"bn.js":18,inherits:146}],11:[function(e,t,i){"use strict";const n=i;n.der=e("./der"),n.pem=e("./pem")},{"./der":10,"./pem":12}],12:[function(e,t,i){"use strict";const n=e("inherits"),r=e("safer-buffer").Buffer,o=e("./der");function s(e){o.call(this,e),this.enc="pem"}n(s,o),t.exports=s,s.prototype.decode=function(e,t){const i=e.toString().split(/[\r\n]+/g),n=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/;let a=-1,c=-1;for(let e=0;e<i.length;e++){const t=i[e].match(s);if(null!==t&&t[2]===n){if(-1!==a){if("END"!==t[1])break;c=e;break}if("BEGIN"!==t[1])break;a=e}}if(-1===a||-1===c)throw new Error("PEM section not found for: "+n);const d=i.slice(a+1,c).join("");d.replace(/[^a-z0-9+/=]+/gi,"");const l=r.from(d,"base64");return o.prototype.decode.call(this,l,t)}},{"./der":10,inherits:146,"safer-buffer":251}],13:[function(e,t,i){"use strict";const n=e("inherits"),r=e("safer-buffer").Buffer,o=e("../base/node"),s=e("../constants/der");function a(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.call(this,"der",e)}function d(e){return e<10?"0"+e:e}t.exports=a,a.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},n(c,o),c.prototype._encodeComposite=function(e,t,i,n){const o=function(e,t,i,n){let r;"seqof"===e?e="seq":"setof"===e&&(e="set");if(s.tagByName.hasOwnProperty(e))r=s.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return n.error("Unknown tag: "+e);r=e}if(r>=31)return n.error("Multi-octet tag encoding unsupported");t||(r|=32);return r|=s.tagClassByName[i||"universal"]<<6,r}(e,t,i,this.reporter);if(n.length<128){const e=r.alloc(2);return e[0]=o,e[1]=n.length,this._createEncoderBuffer([e,n])}let a=1;for(let e=n.length;e>=256;e>>=8)a++;const c=r.alloc(2+a);c[0]=o,c[1]=128|a;for(let e=1+a,t=n.length;t>0;e--,t>>=8)c[e]=255&t;return this._createEncoderBuffer([c,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=r.alloc(2*e.length);for(let i=0;i<e.length;i++)t.writeUInt16BE(e.charCodeAt(i),2*i);return this._createEncoderBuffer(t)}return"numstr"===t?this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space"):"printstr"===t?this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(t)||"objDesc"===t?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: "+t+" unsupported")},c.prototype._encodeObjid=function(e,t,i){if("string"==typeof e){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let t=0;t<e.length;t++)e[t]|=0}else if(Array.isArray(e)){e=e.slice();for(let t=0;t<e.length;t++)e[t]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!i){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let n=0;for(let t=0;t<e.length;t++){let i=e[t];for(n++;i>=128;i>>=7)n++}const o=r.alloc(n);let s=o.length-1;for(let t=e.length-1;t>=0;t--){let i=e[t];for(o[s--]=127&i;(i>>=7)>0;)o[s--]=128|127&i}return this._createEncoderBuffer(o)},c.prototype._encodeTime=function(e,t){let i;const n=new Date(e);return"gentime"===t?i=[d(n.getUTCFullYear()),d(n.getUTCMonth()+1),d(n.getUTCDate()),d(n.getUTCHours()),d(n.getUTCMinutes()),d(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?i=[d(n.getUTCFullYear()%100),d(n.getUTCMonth()+1),d(n.getUTCDate()),d(n.getUTCHours()),d(n.getUTCMinutes()),d(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(i,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!r.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=r.from(t)}if(r.isBuffer(e)){let t=e.length;0===e.length&&t++;const i=r.alloc(t);return e.copy(i),0===e.length&&(i[0]=0),this._createEncoderBuffer(i)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let i=1;for(let t=e;t>=256;t>>=8)i++;const n=new Array(i);for(let t=n.length-1;t>=0;t--)n[t]=255&e,e>>=8;return 128&n[0]&&n.unshift(0),this._createEncoderBuffer(r.from(n))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,i){const n=this._baseState;let r;if(null===n.default)return!1;const o=e.join();if(void 0===n.defaultBuffer&&(n.defaultBuffer=this._encodeValue(n.default,t,i).join()),o.length!==n.defaultBuffer.length)return!1;for(r=0;r<o.length;r++)if(o[r]!==n.defaultBuffer[r])return!1;return!0}},{"../base/node":6,"../constants/der":8,inherits:146,"safer-buffer":251}],14:[function(e,t,i){"use strict";const n=i;n.der=e("./der"),n.pem=e("./pem")},{"./der":13,"./pem":15}],15:[function(e,t,i){"use strict";const n=e("inherits"),r=e("./der");function o(e){r.call(this,e),this.enc="pem"}n(o,r),t.exports=o,o.prototype.encode=function(e,t){const i=r.prototype.encode.call(this,e).toString("base64"),n=["-----BEGIN "+t.label+"-----"];for(let e=0;e<i.length;e+=64)n.push(i.slice(e,e+64));return n.push("-----END "+t.label+"-----"),n.join("\n")}},{"./der":13,inherits:146}],16:[function(e,t,i){(function(e){(function(){"use strict";var i=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],n="undefined"==typeof globalThis?e:globalThis;t.exports=function(){for(var e=[],t=0;t<i.length;t++)"function"==typeof n[i[t]]&&(e[e.length]=i[t]);return e}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],17:[function(e,t,i){"use strict";i.byteLength=function(e){var t=d(e),i=t[0],n=t[1];return 3*(i+n)/4-n},i.toByteArray=function(e){var t,i,n=d(e),s=n[0],a=n[1],c=new o(function(e,t,i){return 3*(t+i)/4-i}(0,s,a)),l=0,u=a>0?s-4:s;for(i=0;i<u;i+=4)t=r[e.charCodeAt(i)]<<18|r[e.charCodeAt(i+1)]<<12|r[e.charCodeAt(i+2)]<<6|r[e.charCodeAt(i+3)],c[l++]=t>>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===a&&(t=r[e.charCodeAt(i)]<<2|r[e.charCodeAt(i+1)]>>4,c[l++]=255&t);1===a&&(t=r[e.charCodeAt(i)]<<10|r[e.charCodeAt(i+1)]<<4|r[e.charCodeAt(i+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},i.fromByteArray=function(e){for(var t,i=e.length,r=i%3,o=[],s=16383,a=0,c=i-r;a<c;a+=s)o.push(l(e,a,a+s>c?c:a+s));1===r?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a<c;++a)n[a]=s[a],r[s.charCodeAt(a)]=a;function d(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function l(e,t,i){for(var r,o,s=[],a=t;a<i;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(n[(o=r)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],18:[function(e,t,i){!function(t,i){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}function o(e,t,i){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(i=t,t=10),this._init(e||0,t||10,i||"be"))}var s;"object"==typeof t?t.exports=o:i.BN=o,o.BN=o,o.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:e("buffer").Buffer}catch(e){}function a(e,t){var i=e.charCodeAt(t);return i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:i-48&15}function c(e,t,i){var n=a(e,i);return i-1>=t&&(n|=a(e,i-1)<<4),n}function d(e,t,i,n){for(var r=0,o=Math.min(e.length,i),s=t;s<o;s++){var a=e.charCodeAt(s)-48;r*=n,r+=a>=49?a-49+10:a>=17?a-17+10:a}return r}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r<e.length&&(16===t?this._parseHex(e,r,i):(this._parseBase(e,t,r),"le"===i&&this._initArray(this.toArray(),t,i)))},o.prototype._initNumber=function(e,t,i){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===i&&this._initArray(this.toArray(),t,i)},o.prototype._initArray=function(e,t,i){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var o,s,a=0;if("be"===i)for(r=e.length-1,o=0;r>=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===i)for(r=0,o=0;r<e.length;r+=3)s=e[r]|e[r+1]<<8|e[r+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n<this.length;n++)this.words[n]=0;var r,o=0,s=0;if("be"===i)for(n=e.length-1;n>=t;n-=2)r=c(e,t,n)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n<e.length;n+=2)r=c(e,t,n)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var o=e.length-i,s=o%n,a=Math.min(o,o-s)+i,c=0,l=i;l<a;l+=n)c=d(e,l,l+n,t),this.imuln(r),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==s){var u=1;for(c=d(e,l,e.length,t),l=0;l<s;l++)u*=t;this.imuln(u),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this.strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,c=s/67108864|0;i.words[0]=a;for(var d=1;d<n;d++){for(var l=c>>>26,u=67108863&c,h=Math.min(d,t.length-1),f=Math.max(0,d-e.length+1);f<=h;f++){var p=d-f|0;l+=(s=(r=0|e.words[p])*(o=0|t.words[f])+u)/67108864|0,u=67108863&s}i.words[d]=0|u,c=0|l}return 0!==c?i.words[d]=0|c:i.length--,i.strip()}o.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<r|o)).toString(16);i=0!==(o=a>>>24-r&16777215)||s!==this.length-1?l[6-c.length]+c+i:c+i,(r+=2)>=26&&(r-=26,s--)}for(0!==o&&(i=o.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var d=u[e],f=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(f).toString(e);i=(p=p.idivn(f)).isZero()?g+i:l[d-g.length]+g+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==s),this.toArrayLike(s,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,i){var r=this.byteLength(),o=i||Math.max(1,r);n(r<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var s,a,c="le"===t,d=new e(o),l=this.clone();if(c){for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),d[a]=s;for(;a<o;a++)d[a]=0}else{for(a=0;a<o-r;a++)d[a]=0;for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),d[o-a-1]=s}return d},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,i=0;return t>=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var i=this._zeroBits(this.words[t]);if(e+=i,26!==i)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},o.prototype.ior=function(e){return n(0==(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;i<t.length;i++)this.words[i]=this.words[i]&e.words[i];return this.length=t.length,this.strip()},o.prototype.iand=function(e){return n(0==(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;n<i.length;n++)this.words[n]=t.words[n]^i.words[n];if(this!==t)for(;n<t.length;n++)this.words[n]=t.words[n];return this.length=t.length,this.strip()},o.prototype.ixor=function(e){return n(0==(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r<t;r++)this.words[r]=67108863&~this.words[r];return i>0&&(this.words[r]=~this.words[r]&67108863>>26-i),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<<r:this.words[i]&~(1<<r),this.strip()},o.prototype.iadd=function(e){var t,i,n;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(i=this,n=e):(i=e,n=this);for(var r=0,o=0;o<n.length;o++)t=(0|i.words[o])+(0|n.words[o])+r,this.words[o]=67108863&t,r=t>>>26;for(;0!==r&&o<i.length;o++)t=(0|i.words[o])+r,this.words[o]=67108863&t,r=t>>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;o<i.length;o++)this.words[o]=i.words[o];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var o=0,s=0;s<n.length;s++)o=(t=(0|i.words[s])-(0|n.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<i.length;s++)o=(t=(0|i.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<i.length&&i!==this)for(;s<i.length;s++)this.words[s]=i.words[s];return this.length=Math.max(this.length,s),i!==this&&(this.negative=1),this.strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,i){var n,r,o,s=e.words,a=t.words,c=i.words,d=0,l=0|s[0],u=8191&l,h=l>>>13,f=0|s[1],p=8191&f,g=f>>>13,v=0|s[2],m=8191&v,y=v>>>13,b=0|s[3],S=8191&b,_=b>>>13,E=0|s[4],w=8191&E,T=E>>>13,I=0|s[5],R=8191&I,M=I>>>13,k=0|s[6],C=8191&k,O=k>>>13,A=0|s[7],P=8191&A,D=A>>>13,x=0|s[8],L=8191&x,U=x>>>13,B=0|s[9],N=8191&B,j=B>>>13,F=0|a[0],K=8191&F,q=F>>>13,$=0|a[1],V=8191&$,H=$>>>13,W=0|a[2],G=8191&W,z=W>>>13,Y=0|a[3],J=8191&Y,Q=Y>>>13,X=0|a[4],Z=8191&X,ee=X>>>13,te=0|a[5],ie=8191&te,ne=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ce=8191&ae,de=ae>>>13,le=0|a[8],ue=8191&le,he=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var ve=(d+(n=Math.imul(u,K))|0)+((8191&(r=(r=Math.imul(u,q))+Math.imul(h,K)|0))<<13)|0;d=((o=Math.imul(h,q))+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,K),r=(r=Math.imul(p,q))+Math.imul(g,K)|0,o=Math.imul(g,q);var me=(d+(n=n+Math.imul(u,V)|0)|0)+((8191&(r=(r=r+Math.imul(u,H)|0)+Math.imul(h,V)|0))<<13)|0;d=((o=o+Math.imul(h,H)|0)+(r>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,K),r=(r=Math.imul(m,q))+Math.imul(y,K)|0,o=Math.imul(y,q),n=n+Math.imul(p,V)|0,r=(r=r+Math.imul(p,H)|0)+Math.imul(g,V)|0,o=o+Math.imul(g,H)|0;var ye=(d+(n=n+Math.imul(u,G)|0)|0)+((8191&(r=(r=r+Math.imul(u,z)|0)+Math.imul(h,G)|0))<<13)|0;d=((o=o+Math.imul(h,z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(S,K),r=(r=Math.imul(S,q))+Math.imul(_,K)|0,o=Math.imul(_,q),n=n+Math.imul(m,V)|0,r=(r=r+Math.imul(m,H)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,G)|0,r=(r=r+Math.imul(p,z)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,z)|0;var be=(d+(n=n+Math.imul(u,J)|0)|0)+((8191&(r=(r=r+Math.imul(u,Q)|0)+Math.imul(h,J)|0))<<13)|0;d=((o=o+Math.imul(h,Q)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(w,K),r=(r=Math.imul(w,q))+Math.imul(T,K)|0,o=Math.imul(T,q),n=n+Math.imul(S,V)|0,r=(r=r+Math.imul(S,H)|0)+Math.imul(_,V)|0,o=o+Math.imul(_,H)|0,n=n+Math.imul(m,G)|0,r=(r=r+Math.imul(m,z)|0)+Math.imul(y,G)|0,o=o+Math.imul(y,z)|0,n=n+Math.imul(p,J)|0,r=(r=r+Math.imul(p,Q)|0)+Math.imul(g,J)|0,o=o+Math.imul(g,Q)|0;var Se=(d+(n=n+Math.imul(u,Z)|0)|0)+((8191&(r=(r=r+Math.imul(u,ee)|0)+Math.imul(h,Z)|0))<<13)|0;d=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(R,K),r=(r=Math.imul(R,q))+Math.imul(M,K)|0,o=Math.imul(M,q),n=n+Math.imul(w,V)|0,r=(r=r+Math.imul(w,H)|0)+Math.imul(T,V)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(S,G)|0,r=(r=r+Math.imul(S,z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(m,J)|0,r=(r=r+Math.imul(m,Q)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Q)|0,n=n+Math.imul(p,Z)|0,r=(r=r+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,o=o+Math.imul(g,ee)|0;var _e=(d+(n=n+Math.imul(u,ie)|0)|0)+((8191&(r=(r=r+Math.imul(u,ne)|0)+Math.imul(h,ie)|0))<<13)|0;d=((o=o+Math.imul(h,ne)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(C,K),r=(r=Math.imul(C,q))+Math.imul(O,K)|0,o=Math.imul(O,q),n=n+Math.imul(R,V)|0,r=(r=r+Math.imul(R,H)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(w,G)|0,r=(r=r+Math.imul(w,z)|0)+Math.imul(T,G)|0,o=o+Math.imul(T,z)|0,n=n+Math.imul(S,J)|0,r=(r=r+Math.imul(S,Q)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Q)|0,n=n+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,ie)|0,r=(r=r+Math.imul(p,ne)|0)+Math.imul(g,ie)|0,o=o+Math.imul(g,ne)|0;var Ee=(d+(n=n+Math.imul(u,oe)|0)|0)+((8191&(r=(r=r+Math.imul(u,se)|0)+Math.imul(h,oe)|0))<<13)|0;d=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(P,K),r=(r=Math.imul(P,q))+Math.imul(D,K)|0,o=Math.imul(D,q),n=n+Math.imul(C,V)|0,r=(r=r+Math.imul(C,H)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(R,G)|0,r=(r=r+Math.imul(R,z)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(w,J)|0,r=(r=r+Math.imul(w,Q)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Q)|0,n=n+Math.imul(S,Z)|0,r=(r=r+Math.imul(S,ee)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,ie)|0,r=(r=r+Math.imul(m,ne)|0)+Math.imul(y,ie)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,r=(r=r+Math.imul(p,se)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,se)|0;var we=(d+(n=n+Math.imul(u,ce)|0)|0)+((8191&(r=(r=r+Math.imul(u,de)|0)+Math.imul(h,ce)|0))<<13)|0;d=((o=o+Math.imul(h,de)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(L,K),r=(r=Math.imul(L,q))+Math.imul(U,K)|0,o=Math.imul(U,q),n=n+Math.imul(P,V)|0,r=(r=r+Math.imul(P,H)|0)+Math.imul(D,V)|0,o=o+Math.imul(D,H)|0,n=n+Math.imul(C,G)|0,r=(r=r+Math.imul(C,z)|0)+Math.imul(O,G)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(R,J)|0,r=(r=r+Math.imul(R,Q)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Q)|0,n=n+Math.imul(w,Z)|0,r=(r=r+Math.imul(w,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(S,ie)|0,r=(r=r+Math.imul(S,ne)|0)+Math.imul(_,ie)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,r=(r=r+Math.imul(m,se)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,se)|0,n=n+Math.imul(p,ce)|0,r=(r=r+Math.imul(p,de)|0)+Math.imul(g,ce)|0,o=o+Math.imul(g,de)|0;var Te=(d+(n=n+Math.imul(u,ue)|0)|0)+((8191&(r=(r=r+Math.imul(u,he)|0)+Math.imul(h,ue)|0))<<13)|0;d=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(N,K),r=(r=Math.imul(N,q))+Math.imul(j,K)|0,o=Math.imul(j,q),n=n+Math.imul(L,V)|0,r=(r=r+Math.imul(L,H)|0)+Math.imul(U,V)|0,o=o+Math.imul(U,H)|0,n=n+Math.imul(P,G)|0,r=(r=r+Math.imul(P,z)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,z)|0,n=n+Math.imul(C,J)|0,r=(r=r+Math.imul(C,Q)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Q)|0,n=n+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(w,ie)|0,r=(r=r+Math.imul(w,ne)|0)+Math.imul(T,ie)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(S,oe)|0,r=(r=r+Math.imul(S,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,n=n+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,de)|0)+Math.imul(y,ce)|0,o=o+Math.imul(y,de)|0,n=n+Math.imul(p,ue)|0,r=(r=r+Math.imul(p,he)|0)+Math.imul(g,ue)|0,o=o+Math.imul(g,he)|0;var Ie=(d+(n=n+Math.imul(u,pe)|0)|0)+((8191&(r=(r=r+Math.imul(u,ge)|0)+Math.imul(h,pe)|0))<<13)|0;d=((o=o+Math.imul(h,ge)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(N,V),r=(r=Math.imul(N,H))+Math.imul(j,V)|0,o=Math.imul(j,H),n=n+Math.imul(L,G)|0,r=(r=r+Math.imul(L,z)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(P,J)|0,r=(r=r+Math.imul(P,Q)|0)+Math.imul(D,J)|0,o=o+Math.imul(D,Q)|0,n=n+Math.imul(C,Z)|0,r=(r=r+Math.imul(C,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(R,ie)|0,r=(r=r+Math.imul(R,ne)|0)+Math.imul(M,ie)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(w,oe)|0,r=(r=r+Math.imul(w,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,n=n+Math.imul(S,ce)|0,r=(r=r+Math.imul(S,de)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,de)|0,n=n+Math.imul(m,ue)|0,r=(r=r+Math.imul(m,he)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,he)|0;var Re=(d+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;d=((o=o+Math.imul(g,ge)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,G),r=(r=Math.imul(N,z))+Math.imul(j,G)|0,o=Math.imul(j,z),n=n+Math.imul(L,J)|0,r=(r=r+Math.imul(L,Q)|0)+Math.imul(U,J)|0,o=o+Math.imul(U,Q)|0,n=n+Math.imul(P,Z)|0,r=(r=r+Math.imul(P,ee)|0)+Math.imul(D,Z)|0,o=o+Math.imul(D,ee)|0,n=n+Math.imul(C,ie)|0,r=(r=r+Math.imul(C,ne)|0)+Math.imul(O,ie)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(R,oe)|0,r=(r=r+Math.imul(R,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,n=n+Math.imul(w,ce)|0,r=(r=r+Math.imul(w,de)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,de)|0,n=n+Math.imul(S,ue)|0,r=(r=r+Math.imul(S,he)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,he)|0;var Me=(d+(n=n+Math.imul(m,pe)|0)|0)+((8191&(r=(r=r+Math.imul(m,ge)|0)+Math.imul(y,pe)|0))<<13)|0;d=((o=o+Math.imul(y,ge)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),r=(r=Math.imul(N,Q))+Math.imul(j,J)|0,o=Math.imul(j,Q),n=n+Math.imul(L,Z)|0,r=(r=r+Math.imul(L,ee)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(P,ie)|0,r=(r=r+Math.imul(P,ne)|0)+Math.imul(D,ie)|0,o=o+Math.imul(D,ne)|0,n=n+Math.imul(C,oe)|0,r=(r=r+Math.imul(C,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,n=n+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,de)|0)+Math.imul(M,ce)|0,o=o+Math.imul(M,de)|0,n=n+Math.imul(w,ue)|0,r=(r=r+Math.imul(w,he)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,he)|0;var ke=(d+(n=n+Math.imul(S,pe)|0)|0)+((8191&(r=(r=r+Math.imul(S,ge)|0)+Math.imul(_,pe)|0))<<13)|0;d=((o=o+Math.imul(_,ge)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),r=(r=Math.imul(N,ee))+Math.imul(j,Z)|0,o=Math.imul(j,ee),n=n+Math.imul(L,ie)|0,r=(r=r+Math.imul(L,ne)|0)+Math.imul(U,ie)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(P,oe)|0,r=(r=r+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,n=n+Math.imul(C,ce)|0,r=(r=r+Math.imul(C,de)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,de)|0,n=n+Math.imul(R,ue)|0,r=(r=r+Math.imul(R,he)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,he)|0;var Ce=(d+(n=n+Math.imul(w,pe)|0)|0)+((8191&(r=(r=r+Math.imul(w,ge)|0)+Math.imul(T,pe)|0))<<13)|0;d=((o=o+Math.imul(T,ge)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,ie),r=(r=Math.imul(N,ne))+Math.imul(j,ie)|0,o=Math.imul(j,ne),n=n+Math.imul(L,oe)|0,r=(r=r+Math.imul(L,se)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,se)|0,n=n+Math.imul(P,ce)|0,r=(r=r+Math.imul(P,de)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,de)|0,n=n+Math.imul(C,ue)|0,r=(r=r+Math.imul(C,he)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,he)|0;var Oe=(d+(n=n+Math.imul(R,pe)|0)|0)+((8191&(r=(r=r+Math.imul(R,ge)|0)+Math.imul(M,pe)|0))<<13)|0;d=((o=o+Math.imul(M,ge)|0)+(r>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,oe),r=(r=Math.imul(N,se))+Math.imul(j,oe)|0,o=Math.imul(j,se),n=n+Math.imul(L,ce)|0,r=(r=r+Math.imul(L,de)|0)+Math.imul(U,ce)|0,o=o+Math.imul(U,de)|0,n=n+Math.imul(P,ue)|0,r=(r=r+Math.imul(P,he)|0)+Math.imul(D,ue)|0,o=o+Math.imul(D,he)|0;var Ae=(d+(n=n+Math.imul(C,pe)|0)|0)+((8191&(r=(r=r+Math.imul(C,ge)|0)+Math.imul(O,pe)|0))<<13)|0;d=((o=o+Math.imul(O,ge)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,ce),r=(r=Math.imul(N,de))+Math.imul(j,ce)|0,o=Math.imul(j,de),n=n+Math.imul(L,ue)|0,r=(r=r+Math.imul(L,he)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,he)|0;var Pe=(d+(n=n+Math.imul(P,pe)|0)|0)+((8191&(r=(r=r+Math.imul(P,ge)|0)+Math.imul(D,pe)|0))<<13)|0;d=((o=o+Math.imul(D,ge)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,ue),r=(r=Math.imul(N,he))+Math.imul(j,ue)|0,o=Math.imul(j,he);var De=(d+(n=n+Math.imul(L,pe)|0)|0)+((8191&(r=(r=r+Math.imul(L,ge)|0)+Math.imul(U,pe)|0))<<13)|0;d=((o=o+Math.imul(U,ge)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863;var xe=(d+(n=Math.imul(N,pe))|0)+((8191&(r=(r=Math.imul(N,ge))+Math.imul(j,pe)|0))<<13)|0;return d=((o=Math.imul(j,ge))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=ve,c[1]=me,c[2]=ye,c[3]=be,c[4]=Se,c[5]=_e,c[6]=Ee,c[7]=we,c[8]=Te,c[9]=Ie,c[10]=Re,c[11]=Me,c[12]=ke,c[13]=Ce,c[14]=Oe,c[15]=Ae,c[16]=Pe,c[17]=De,c[18]=xe,0!==d&&(c[19]=d,i.length++),i};function g(e,t,i){return(new v).mulp(e,t,i)}function v(e,t){this.x=e,this.y=t}Math.imul||(p=f),o.prototype.mulTo=function(e,t){var i,n=this.length+e.length;return i=10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?function(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,o=0;o<i.length-1;o++){var s=r;r=0;for(var a=67108863&n,c=Math.min(o,t.length-1),d=Math.max(0,o-e.length+1);d<=c;d++){var l=o-d,u=(0|e.words[l])*(0|t.words[d]),h=67108863&u;a=67108863&(h=h+a|0),r+=(s=(s=s+(u/67108864|0)|0)+(h>>>26)|0)>>>26,s&=67108863}i.words[o]=a,n=s,s=r}return 0!==n?i.words[o]=n:i.length--,i.strip()}(this,e,t):g(this,e,t),i},v.prototype.makeRBT=function(e){for(var t=new Array(e),i=o.prototype._countBits(e)-1,n=0;n<e;n++)t[n]=this.revBin(n,i,e);return t},v.prototype.revBin=function(e,t,i){if(0===e||e===i-1)return e;for(var n=0,r=0;r<t;r++)n|=(1&e)<<t-r-1,e>>=1;return n},v.prototype.permute=function(e,t,i,n,r,o){for(var s=0;s<o;s++)n[s]=t[e[s]],r[s]=i[e[s]]},v.prototype.transform=function(e,t,i,n,r,o){this.permute(o,e,t,i,n,r);for(var s=1;s<r;s<<=1)for(var a=s<<1,c=Math.cos(2*Math.PI/a),d=Math.sin(2*Math.PI/a),l=0;l<r;l+=a)for(var u=c,h=d,f=0;f<s;f++){var p=i[l+f],g=n[l+f],v=i[l+f+s],m=n[l+f+s],y=u*v-h*m;m=u*m+h*v,v=y,i[l+f]=p+v,n[l+f]=g+m,i[l+f+s]=p-v,n[l+f+s]=g-m,f!==a&&(y=c*u-d*h,h=c*h+d*u,u=y)}},v.prototype.guessLen13b=function(e,t){var i=1|Math.max(t,e),n=1&i,r=0;for(i=i/2|0;i;i>>>=1)r++;return 1<<r+1+n},v.prototype.conjugate=function(e,t,i){if(!(i<=1))for(var n=0;n<i/2;n++){var r=e[n];e[n]=e[i-n-1],e[i-n-1]=r,r=t[n],t[n]=-t[i-n-1],t[i-n-1]=-r}},v.prototype.normalize13b=function(e,t){for(var i=0,n=0;n<t/2;n++){var r=8192*Math.round(e[2*n+1]/t)+Math.round(e[2*n]/t)+i;e[n]=67108863&r,i=r<67108864?0:r/67108864|0}return e},v.prototype.convert13b=function(e,t,i,r){for(var o=0,s=0;s<t;s++)o+=0|e[s],i[2*s]=8191&o,o>>>=13,i[2*s+1]=8191&o,o>>>=13;for(s=2*t;s<r;++s)i[s]=0;n(0===o),n(0==(-8192&o))},v.prototype.stub=function(e){for(var t=new Array(e),i=0;i<e;i++)t[i]=0;return t},v.prototype.mulp=function(e,t,i){var n=2*this.guessLen13b(e.length,t.length),r=this.makeRBT(n),o=this.stub(n),s=new Array(n),a=new Array(n),c=new Array(n),d=new Array(n),l=new Array(n),u=new Array(n),h=i.words;h.length=n,this.convert13b(e.words,e.length,s,n),this.convert13b(t.words,t.length,d,n),this.transform(s,o,a,c,n,r),this.transform(d,o,l,u,n,r);for(var f=0;f<n;f++){var p=a[f]*l[f]-c[f]*u[f];c[f]=a[f]*u[f]+c[f]*l[f],a[f]=p}return this.conjugate(a,c,n),this.transform(a,c,h,o,n,r),this.conjugate(h,o,n),this.normalize13b(h,n),i.negative=e.negative^t.negative,i.length=e.length+t.length,i.strip()},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),g(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){n("number"==typeof e),n(e<67108864);for(var t=0,i=0;i<this.length;i++){var r=(0|this.words[i])*e,o=(67108863&r)+(67108863&t);t>>=26,t+=r/67108864|0,t+=o>>>26,this.words[i]=67108863&o}return 0!==t&&(this.words[i]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i<t.length;i++){var n=i/26|0,r=i%26;t[i]=(e.words[n]&1<<r)>>>r}return t}(e);if(0===t.length)return new o(1);for(var i=this,n=0;n<t.length&&0===t[n];n++,i=i.sqr());if(++n<t.length)for(var r=i.sqr();n<t.length;n++,r=r.sqr())0!==t[n]&&(i=i.mul(r));return i},o.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,i=e%26,r=(e-i)/26,o=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<i;this.words[t]=c|s,s=a>>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t<r;t++)this.words[t]=0;this.length+=r}return this.strip()},o.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,i){var r;n("number"==typeof e&&e>=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=i;if(r-=s,r=Math.max(0,r),c){for(var d=0;d<s;d++)c.words[d]=this.words[d];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,d=0;d<this.length;d++)this.words[d]=this.words[d+s];else this.words[0]=0,this.length=1;var l=0;for(d=this.length-1;d>=0&&(0!==l||d>=r);d--){var u=0|this.words[d];this.words[d]=l<<26-o|u>>>o,l=u&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<<t;return!(this.length<=i)&&!!(this.words[i]&r)},o.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<<t;this.words[this.length-1]&=r}return this.strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,i){var r,o,s=e.length+i;this._expand(s);var a=0;for(r=0;r<e.length;r++){o=(0|this.words[r+i])+a;var c=(0|e.words[r])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[r+i]=67108863&o}for(;r<this.length-i;r++)a=(o=(0|this.words[r+i])+a)>>26,this.words[r+i]=67108863&o;if(0===a)return this.strip();for(n(-1===a),a=0,r=0;r<this.length;r++)a=(o=-(0|this.words[r])+a)>>26,this.words[r]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,s=0|r.words[r.length-1];0!==(i=26-this._countBits(s))&&(r=r.ushln(i),n.iushln(i),s=0|r.words[r.length-1]);var a,c=n.length-r.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var d=0;d<a.length;d++)a.words[d]=0}var l=n.clone()._ishlnsubmul(r,1,c);0===l.negative&&(n=l,a&&(a.words[c]=1));for(var u=c-1;u>=0;u--){var h=67108864*(0|n.words[r.length+u])+(0|n.words[r.length+u-1]);for(h=Math.min(h/s|0,67108863),n._ishlnsubmul(r,h,u);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(r,1,u),n.isZero()||(n.negative^=1);a&&(a.words[u]=h)}return a&&a.strip(),n.strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:a||null,mod:n}},o.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(r=a.div.neg()),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:r,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(r=a.div.neg()),{div:r,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var r,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),o=i.cmp(n);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,i=0,r=this.length-1;r>=0;r--)i=(t*i+(0|this.words[r]))%e;return i},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,i=this.length-1;i>=0;i--){var r=(0|this.words[i])+67108864*t;this.words[i]=r/e|0,t=r%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new o(1),s=new o(0),a=new o(0),c=new o(1),d=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++d;for(var l=i.clone(),u=t.clone();!t.isZero();){for(var h=0,f=1;0==(t.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(r.isOdd()||s.isOdd())&&(r.iadd(l),s.isub(u)),r.iushrn(1),s.iushrn(1);for(var p=0,g=1;0==(i.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(u)),a.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(a),s.isub(c)):(i.isub(t),a.isub(r),c.isub(s))}return{a:a,b:c,gcd:i.iushln(d)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,s=new o(1),a=new o(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var d=0,l=1;0==(t.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(t.iushrn(d);d-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var u=0,h=1;0==(i.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(i.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(a)):(i.isub(t),a.isub(s))}return(r=0===t.cmpn(1)?s:a).cmpn(0)<0&&r.iadd(e),r},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var o=t;t=i,i=o}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<<t;if(this.length<=i)return this._expand(i+1),this.words[i]|=r,this;for(var o=r,s=i;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this.strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:r<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,i=this.length-1;i>=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){n<r?t=-1:n>r&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new w(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function y(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function _(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function w(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){w.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},y.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t<this.n?-1:i.ucmp(this.p);return 0===n?(i.words[0]=0,i.length=1):n>0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},y.prototype.split=function(e,t){e.iushrn(this.n,0,t)},y.prototype.imulK=function(e){return e.imul(this.k)},r(b,y),b.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r<n;r++)t.words[r]=e.words[r];if(t.length=n,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&i,r=10;r<e.length;r++){var s=0|e.words[r];e.words[r-10]=(s&i)<<4|o>>>22,o=s}o>>>=22,e.words[r-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i<e.length;i++){var n=0|e.words[i];t+=977*n,e.words[i]=67108863&t,t=64*n+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(S,y),r(_,y),r(E,y),E.prototype.imulK=function(e){for(var t=0,i=0;i<e.length;i++){var n=19*(0|e.words[i])+t,r=67108863&n;n>>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new b;else if("p224"===e)t=new S;else if("p192"===e)t=new _;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new E}return m[e]=t,t},w.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},w.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},w.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},w.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},w.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},w.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},w.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},w.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},w.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},w.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},w.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},w.prototype.isqr=function(e){return this.imul(e,e.clone())},w.prototype.sqr=function(e){return this.mul(e,e)},w.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new o(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),s=0;!r.isZero()&&0===r.andln(1);)s++,r.iushrn(1);n(!r.isZero());var a=new o(1).toRed(this),c=a.redNeg(),d=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,d).cmp(c);)l.redIAdd(c);for(var u=this.pow(l,r),h=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),p=s;0!==f.cmp(a);){for(var g=f,v=0;0!==g.cmp(a);v++)g=g.redSqr();n(v<p);var m=this.pow(u,new o(1).iushln(p-v-1));h=h.redMul(m),u=m.redSqr(),f=f.redMul(u),p=v}return h},w.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},w.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var i=new Array(16);i[0]=new o(1).toRed(this),i[1]=e;for(var n=2;n<i.length;n++)i[n]=this.mul(i[n-1],e);var r=i[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),n=t.length-1;n>=0;n--){for(var d=t.words[n],l=c-1;l>=0;l--){var u=d>>l&1;r!==i[0]&&(r=this.sqr(r)),0!==u||0!==s?(s<<=1,s|=u,(4===++a||0===n&&0===l)&&(r=this.mul(r,i[s]),a=0,s=0)):a=0}c=26}return r},w.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},w.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new T(e)},r(T,w),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:20}],19:[function(e,t,i){var n;function r(e){this.rand=e}if(t.exports=function(e){return n||(n=new r(null)),n.generate(e)},t.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i<t.length;i++)t[i]=this.rand.getByte();return t},"object"==typeof self)self.crypto&&self.crypto.getRandomValues?r.prototype._rand=function(e){var t=new Uint8Array(e);return self.crypto.getRandomValues(t),t}:self.msCrypto&&self.msCrypto.getRandomValues?r.prototype._rand=function(e){var t=new Uint8Array(e);return self.msCrypto.getRandomValues(t),t}:"object"==typeof window&&(r.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var o=e("crypto");if("function"!=typeof o.randomBytes)throw new Error("Not supported");r.prototype._rand=function(e){return o.randomBytes(e)}}catch(e){}},{crypto:20}],20:[function(e,t,i){},{}],21:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e){n.isBuffer(e)||(e=n.from(e));for(var t=e.length/4|0,i=new Array(t),r=0;r<t;r++)i[r]=e.readUInt32BE(4*r);return i}function o(e){for(;0<e.length;e++)e[0]=0}function s(e,t,i,n,r){for(var o,s,a,c,d=i[0],l=i[1],u=i[2],h=i[3],f=e[0]^t[0],p=e[1]^t[1],g=e[2]^t[2],v=e[3]^t[3],m=4,y=1;y<r;y++)o=d[f>>>24]^l[p>>>16&255]^u[g>>>8&255]^h[255&v]^t[m++],s=d[p>>>24]^l[g>>>16&255]^u[v>>>8&255]^h[255&f]^t[m++],a=d[g>>>24]^l[v>>>16&255]^u[f>>>8&255]^h[255&p]^t[m++],c=d[v>>>24]^l[f>>>16&255]^u[p>>>8&255]^h[255&g]^t[m++],f=o,p=s,g=a,v=c;return o=(n[f>>>24]<<24|n[p>>>16&255]<<16|n[g>>>8&255]<<8|n[255&v])^t[m++],s=(n[p>>>24]<<24|n[g>>>16&255]<<16|n[v>>>8&255]<<8|n[255&f])^t[m++],a=(n[g>>>24]<<24|n[v>>>16&255]<<16|n[f>>>8&255]<<8|n[255&p])^t[m++],c=(n[v>>>24]<<24|n[f>>>16&255]<<16|n[p>>>8&255]<<8|n[255&g])^t[m++],[o>>>=0,s>>>=0,a>>>=0,c>>>=0]}var a=[0,1,2,4,8,16,32,64,128,27,54],c=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var i=[],n=[],r=[[],[],[],[]],o=[[],[],[],[]],s=0,a=0,c=0;c<256;++c){var d=a^a<<1^a<<2^a<<3^a<<4;d=d>>>8^255&d^99,i[s]=d,n[d]=s;var l=e[s],u=e[l],h=e[u],f=257*e[d]^16843008*d;r[0][s]=f<<24|f>>>8,r[1][s]=f<<16|f>>>16,r[2][s]=f<<8|f>>>24,r[3][s]=f,f=16843009*h^65537*u^257*l^16843008*s,o[0][d]=f<<24|f>>>8,o[1][d]=f<<16|f>>>16,o[2][d]=f<<8|f>>>24,o[3][d]=f,0===s?s=a=1:(s=l^e[e[e[h^l]]],a^=e[e[a]])}return{SBOX:i,INV_SBOX:n,SUB_MIX:r,INV_SUB_MIX:o}}();function d(e){this._key=r(e),this._reset()}d.blockSize=16,d.keySize=32,d.prototype.blockSize=d.blockSize,d.prototype.keySize=d.keySize,d.prototype._reset=function(){for(var e=this._key,t=e.length,i=t+6,n=4*(i+1),r=[],o=0;o<t;o++)r[o]=e[o];for(o=t;o<n;o++){var s=r[o-1];o%t==0?(s=s<<8|s>>>24,s=c.SBOX[s>>>24]<<24|c.SBOX[s>>>16&255]<<16|c.SBOX[s>>>8&255]<<8|c.SBOX[255&s],s^=a[o/t|0]<<24):t>6&&o%t==4&&(s=c.SBOX[s>>>24]<<24|c.SBOX[s>>>16&255]<<16|c.SBOX[s>>>8&255]<<8|c.SBOX[255&s]),r[o]=r[o-t]^s}for(var d=[],l=0;l<n;l++){var u=n-l,h=r[u-(l%4?0:4)];d[l]=l<4||u<=4?h:c.INV_SUB_MIX[0][c.SBOX[h>>>24]]^c.INV_SUB_MIX[1][c.SBOX[h>>>16&255]]^c.INV_SUB_MIX[2][c.SBOX[h>>>8&255]]^c.INV_SUB_MIX[3][c.SBOX[255&h]]}this._nRounds=i,this._keySchedule=r,this._invKeySchedule=d},d.prototype.encryptBlockRaw=function(e){return s(e=r(e),this._keySchedule,c.SUB_MIX,c.SBOX,this._nRounds)},d.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),i=n.allocUnsafe(16);return i.writeUInt32BE(t[0],0),i.writeUInt32BE(t[1],4),i.writeUInt32BE(t[2],8),i.writeUInt32BE(t[3],12),i},d.prototype.decryptBlock=function(e){var t=(e=r(e))[1];e[1]=e[3],e[3]=t;var i=s(e,this._invKeySchedule,c.INV_SUB_MIX,c.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(i[0],0),o.writeUInt32BE(i[3],4),o.writeUInt32BE(i[2],8),o.writeUInt32BE(i[1],12),o},d.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=d},{"safe-buffer":250}],22:[function(e,t,i){var n=e("./aes"),r=e("safe-buffer").Buffer,o=e("cipher-base"),s=e("inherits"),a=e("./ghash"),c=e("buffer-xor"),d=e("./incr32");function l(e,t,i,s){o.call(this);var c=r.alloc(4,0);this._cipher=new n.AES(t);var l=this._cipher.encryptBlock(c);this._ghash=new a(l),i=function(e,t,i){if(12===t.length)return e._finID=r.concat([t,r.from([0,0,0,1])]),r.concat([t,r.from([0,0,0,2])]);var n=new a(i),o=t.length,s=o%16;n.update(t),s&&(s=16-s,n.update(r.alloc(s,0))),n.update(r.alloc(8,0));var c=8*o,l=r.alloc(8);l.writeUIntBE(c,0,8),n.update(l),e._finID=n.state;var u=r.from(e._finID);return d(u),u}(this,i,l),this._prev=r.from(i),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=s,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}s(l,o),l.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=r.alloc(t,0),this._ghash.update(t))}this._called=!0;var i=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(i),this._len+=e.length,i},l.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=c(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var i=0;e.length!==t.length&&i++;for(var n=Math.min(e.length,t.length),r=0;r<n;++r)i+=e[r]^t[r];return i}(e,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=e,this._cipher.scrub()},l.prototype.getAuthTag=function(){if(this._decrypt||!r.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag},l.prototype.setAuthTag=function(e){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=e},l.prototype.setAAD=function(e){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(e),this._alen+=e.length},t.exports=l},{"./aes":21,"./ghash":26,"./incr32":27,"buffer-xor":67,"cipher-base":71,inherits:146,"safe-buffer":250}],23:[function(e,t,i){var n=e("./encrypter"),r=e("./decrypter"),o=e("./modes/list.json");i.createCipher=i.Cipher=n.createCipher,i.createCipheriv=i.Cipheriv=n.createCipheriv,i.createDecipher=i.Decipher=r.createDecipher,i.createDecipheriv=i.Decipheriv=r.createDecipheriv,i.listCiphers=i.getCiphers=function(){return Object.keys(o)}},{"./decrypter":24,"./encrypter":25,"./modes/list.json":35}],24:[function(e,t,i){var n=e("./authCipher"),r=e("safe-buffer").Buffer,o=e("./modes"),s=e("./streamCipher"),a=e("cipher-base"),c=e("./aes"),d=e("evp_bytestokey");function l(e,t,i){a.call(this),this._cache=new u,this._last=void 0,this._cipher=new c.AES(t),this._prev=r.from(i),this._mode=e,this._autopadding=!0}function u(){this.cache=r.allocUnsafe(0)}function h(e,t,i){var a=o[e.toLowerCase()];if(!a)throw new TypeError("invalid suite type");if("string"==typeof i&&(i=r.from(i)),"GCM"!==a.mode&&i.length!==a.iv)throw new TypeError("invalid iv length "+i.length);if("string"==typeof t&&(t=r.from(t)),t.length!==a.key/8)throw new TypeError("invalid key length "+t.length);return"stream"===a.type?new s(a.module,t,i,!0):"auth"===a.type?new n(a.module,t,i,!0):new l(a.module,t,i)}e("inherits")(l,a),l.prototype._update=function(e){var t,i;this._cache.add(e);for(var n=[];t=this._cache.get(this._autopadding);)i=this._mode.decrypt(this,t),n.push(i);return r.concat(n)},l.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return function(e){var t=e[15];if(t<1||t>16)throw new Error("unable to decrypt data");var i=-1;for(;++i<t;)if(e[i+(16-t)]!==t)throw new Error("unable to decrypt data");if(16===t)return;return e.slice(0,16-t)}(this._mode.decrypt(this,e));if(e)throw new Error("data not multiple of block length")},l.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},u.prototype.add=function(e){this.cache=r.concat([this.cache,e])},u.prototype.get=function(e){var t;if(e){if(this.cache.length>16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},u.prototype.flush=function(){if(this.cache.length)return this.cache},i.createDecipher=function(e,t){var i=o[e.toLowerCase()];if(!i)throw new TypeError("invalid suite type");var n=d(t,!1,i.key,i.iv);return h(e,n.key,n.iv)},i.createDecipheriv=h},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":71,evp_bytestokey:106,inherits:146,"safe-buffer":250}],25:[function(e,t,i){var n=e("./modes"),r=e("./authCipher"),o=e("safe-buffer").Buffer,s=e("./streamCipher"),a=e("cipher-base"),c=e("./aes"),d=e("evp_bytestokey");function l(e,t,i){a.call(this),this._cache=new h,this._cipher=new c.AES(t),this._prev=o.from(i),this._mode=e,this._autopadding=!0}e("inherits")(l,a),l.prototype._update=function(e){var t,i;this._cache.add(e);for(var n=[];t=this._cache.get();)i=this._mode.encrypt(this,t),n.push(i);return o.concat(n)};var u=o.alloc(16,16);function h(){this.cache=o.allocUnsafe(0)}function f(e,t,i){var a=n[e.toLowerCase()];if(!a)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==a.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof i&&(i=o.from(i)),"GCM"!==a.mode&&i.length!==a.iv)throw new TypeError("invalid iv length "+i.length);return"stream"===a.type?new s(a.module,t,i):"auth"===a.type?new r(a.module,t,i):new l(a.module,t,i)}l.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(u))throw this._cipher.scrub(),new Error("data not multiple of block length")},l.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},h.prototype.add=function(e){this.cache=o.concat([this.cache,e])},h.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},h.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),i=-1;++i<e;)t.writeUInt8(e,i);return o.concat([this.cache,t])},i.createCipheriv=f,i.createCipher=function(e,t){var i=n[e.toLowerCase()];if(!i)throw new TypeError("invalid suite type");var r=d(t,!1,i.key,i.iv);return f(e,r.key,r.iv)}},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":71,evp_bytestokey:106,inherits:146,"safe-buffer":250}],26:[function(e,t,i){var n=e("safe-buffer").Buffer,r=n.alloc(16,0);function o(e){var t=n.allocUnsafe(16);return t.writeUInt32BE(e[0]>>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function s(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}s.prototype.ghash=function(e){for(var t=-1;++t<e.length;)this.state[t]^=e[t];this._multiply()},s.prototype._multiply=function(){for(var e,t,i,n=[(e=this.h).readUInt32BE(0),e.readUInt32BE(4),e.readUInt32BE(8),e.readUInt32BE(12)],r=[0,0,0,0],s=-1;++s<128;){for(0!=(this.state[~~(s/8)]&1<<7-s%8)&&(r[0]^=n[0],r[1]^=n[1],r[2]^=n[2],r[3]^=n[3]),i=0!=(1&n[3]),t=3;t>0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,i&&(n[0]=n[0]^225<<24)}this.state=o(r)},s.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},s.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,r],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=s},{"safe-buffer":250}],27:[function(e,t,i){t.exports=function(e){for(var t,i=e.length;i--;){if(255!==(t=e.readUInt8(i))){t++,e.writeUInt8(t,i);break}e.writeUInt8(0,i)}}},{}],28:[function(e,t,i){var n=e("buffer-xor");i.encrypt=function(e,t){var i=n(t,e._prev);return e._prev=e._cipher.encryptBlock(i),e._prev},i.decrypt=function(e,t){var i=e._prev;e._prev=t;var r=e._cipher.decryptBlock(t);return n(r,i)}},{"buffer-xor":67}],29:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("buffer-xor");function o(e,t,i){var o=t.length,s=r(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,i?t:s]),s}i.encrypt=function(e,t,i){for(var r,s=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){s=n.concat([s,o(e,t,i)]);break}r=e._cache.length,s=n.concat([s,o(e,t.slice(0,r),i)]),t=t.slice(r)}return s}},{"buffer-xor":67,"safe-buffer":250}],30:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t,i){for(var n,r,s=-1,a=0;++s<8;)n=t&1<<7-s?128:0,a+=(128&(r=e._cipher.encryptBlock(e._prev)[0]^n))>>s%8,e._prev=o(e._prev,i?n:r);return a}function o(e,t){var i=e.length,r=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++r<i;)o[r]=e[r]<<1|e[r+1]>>7;return o}i.encrypt=function(e,t,i){for(var o=t.length,s=n.allocUnsafe(o),a=-1;++a<o;)s[a]=r(e,t[a],i);return s}},{"safe-buffer":250}],31:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t,i){var r=e._cipher.encryptBlock(e._prev)[0]^t;return e._prev=n.concat([e._prev.slice(1),n.from([i?t:r])]),r}i.encrypt=function(e,t,i){for(var o=t.length,s=n.allocUnsafe(o),a=-1;++a<o;)s[a]=r(e,t[a],i);return s}},{"safe-buffer":250}],32:[function(e,t,i){var n=e("buffer-xor"),r=e("safe-buffer").Buffer,o=e("../incr32");function s(e){var t=e._cipher.encryptBlockRaw(e._prev);return o(e._prev),t}i.encrypt=function(e,t){var i=Math.ceil(t.length/16),o=e._cache.length;e._cache=r.concat([e._cache,r.allocUnsafe(16*i)]);for(var a=0;a<i;a++){var c=s(e),d=o+16*a;e._cache.writeUInt32BE(c[0],d+0),e._cache.writeUInt32BE(c[1],d+4),e._cache.writeUInt32BE(c[2],d+8),e._cache.writeUInt32BE(c[3],d+12)}var l=e._cache.slice(0,t.length);return e._cache=e._cache.slice(t.length),n(t,l)}},{"../incr32":27,"buffer-xor":67,"safe-buffer":250}],33:[function(e,t,i){i.encrypt=function(e,t){return e._cipher.encryptBlock(t)},i.decrypt=function(e,t){return e._cipher.decryptBlock(t)}},{}],34:[function(e,t,i){var n={ECB:e("./ecb"),CBC:e("./cbc"),CFB:e("./cfb"),CFB8:e("./cfb8"),CFB1:e("./cfb1"),OFB:e("./ofb"),CTR:e("./ctr"),GCM:e("./ctr")},r=e("./list.json");for(var o in r)r[o].module=n[r[o].mode];t.exports=r},{"./cbc":28,"./cfb":29,"./cfb1":30,"./cfb8":31,"./ctr":32,"./ecb":33,"./list.json":35,"./ofb":36}],35:[function(e,t,i){t.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},{}],36:[function(e,t,i){(function(t){(function(){var n=e("buffer-xor");function r(e){return e._prev=e._cipher.encryptBlock(e._prev),e._prev}i.encrypt=function(e,i){for(;e._cache.length<i.length;)e._cache=t.concat([e._cache,r(e)]);var o=e._cache.slice(0,i.length);return e._cache=e._cache.slice(i.length),n(i,o)}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:68,"buffer-xor":67}],37:[function(e,t,i){var n=e("./aes"),r=e("safe-buffer").Buffer,o=e("cipher-base");function s(e,t,i,s){o.call(this),this._cipher=new n.AES(t),this._prev=r.from(i),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=s,this._mode=e}e("inherits")(s,o),s.prototype._update=function(e){return this._mode.encrypt(this,e,this._decrypt)},s.prototype._final=function(){this._cipher.scrub()},t.exports=s},{"./aes":21,"cipher-base":71,inherits:146,"safe-buffer":250}],38:[function(e,t,i){var n=e("browserify-des"),r=e("browserify-aes/browser"),o=e("browserify-aes/modes"),s=e("browserify-des/modes"),a=e("evp_bytestokey");function c(e,t,i){if(e=e.toLowerCase(),o[e])return r.createCipheriv(e,t,i);if(s[e])return new n({key:t,iv:i,mode:e});throw new TypeError("invalid suite type")}function d(e,t,i){if(e=e.toLowerCase(),o[e])return r.createDecipheriv(e,t,i);if(s[e])return new n({key:t,iv:i,mode:e,decrypt:!0});throw new TypeError("invalid suite type")}i.createCipher=i.Cipher=function(e,t){var i,n;if(e=e.toLowerCase(),o[e])i=o[e].key,n=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");i=8*s[e].key,n=s[e].iv}var r=a(t,!1,i,n);return c(e,r.key,r.iv)},i.createCipheriv=i.Cipheriv=c,i.createDecipher=i.Decipher=function(e,t){var i,n;if(e=e.toLowerCase(),o[e])i=o[e].key,n=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");i=8*s[e].key,n=s[e].iv}var r=a(t,!1,i,n);return d(e,r.key,r.iv)},i.createDecipheriv=i.Decipheriv=d,i.listCiphers=i.getCiphers=function(){return Object.keys(s).concat(r.getCiphers())}},{"browserify-aes/browser":23,"browserify-aes/modes":34,"browserify-des":39,"browserify-des/modes":40,evp_bytestokey:106}],39:[function(e,t,i){var n=e("cipher-base"),r=e("des.js"),o=e("inherits"),s=e("safe-buffer").Buffer,a={"des-ede3-cbc":r.CBC.instantiate(r.EDE),"des-ede3":r.EDE,"des-ede-cbc":r.CBC.instantiate(r.EDE),"des-ede":r.EDE,"des-cbc":r.CBC.instantiate(r.DES),"des-ecb":r.DES};function c(e){n.call(this);var t,i=e.mode.toLowerCase(),r=a[i];t=e.decrypt?"decrypt":"encrypt";var o=e.key;s.isBuffer(o)||(o=s.from(o)),"des-ede"!==i&&"des-ede-cbc"!==i||(o=s.concat([o,o.slice(0,8)]));var c=e.iv;s.isBuffer(c)||(c=s.from(c)),this._des=r.create({key:o,iv:c,type:t})}a.des=a["des-cbc"],a.des3=a["des-ede3-cbc"],t.exports=c,o(c,n),c.prototype._update=function(e){return s.from(this._des.update(e))},c.prototype._final=function(){return s.from(this._des.final())}},{"cipher-base":71,"des.js":79,inherits:146,"safe-buffer":250}],40:[function(e,t,i){i["des-ecb"]={key:8,iv:0},i["des-cbc"]=i.des={key:8,iv:8},i["des-ede3-cbc"]=i.des3={key:24,iv:8},i["des-ede3"]={key:24,iv:0},i["des-ede-cbc"]={key:16,iv:8},i["des-ede"]={key:16,iv:0}},{}],41:[function(e,t,i){(function(i){(function(){var n=e("bn.js"),r=e("randombytes");function o(e){var t,i=e.modulus.byteLength();do{t=new n(r(i))}while(t.cmp(e.modulus)>=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function s(e,t){var r=function(e){var t=o(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),s=t.modulus.byteLength(),a=new n(e).mul(r.blinder).umod(t.modulus),c=a.toRed(n.mont(t.prime1)),d=a.toRed(n.mont(t.prime2)),l=t.coefficient,u=t.prime1,h=t.prime2,f=c.redPow(t.exponent1).fromRed(),p=d.redPow(t.exponent2).fromRed(),g=f.isub(p).imul(l).umod(u).imul(h);return p.iadd(g).imul(r.unblinder).umod(t.modulus).toArrayLike(i,"be",s)}s.getr=o,t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":42,buffer:68,randombytes:244}],42:[function(e,t,i){!function(t,i){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}function o(e,t,i){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(i=t,t=10),this._init(e||0,t||10,i||"be"))}var s;"object"==typeof t?t.exports=o:i.BN=o,o.BN=o,o.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:e("buffer").Buffer}catch(e){}function a(e,t){var i=e.charCodeAt(t);return i>=48&&i<=57?i-48:i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:void n(!1,"Invalid character in "+e)}function c(e,t,i){var n=a(e,i);return i-1>=t&&(n|=a(e,i-1)<<4),n}function d(e,t,i,r){for(var o=0,s=0,a=Math.min(e.length,i),c=t;c<a;c++){var d=e.charCodeAt(c)-48;o*=r,s=d>=49?d-49+10:d>=17?d-17+10:d,n(d>=0&&s<r,"Invalid character"),o+=s}return o}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r<e.length&&(16===t?this._parseHex(e,r,i):(this._parseBase(e,t,r),"le"===i&&this._initArray(this.toArray(),t,i)))},o.prototype._initNumber=function(e,t,i){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===i&&this._initArray(this.toArray(),t,i)},o.prototype._initArray=function(e,t,i){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var o,s,a=0;if("be"===i)for(r=e.length-1,o=0;r>=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===i)for(r=0,o=0;r<e.length;r+=3)s=e[r]|e[r+1]<<8|e[r+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n<this.length;n++)this.words[n]=0;var r,o=0,s=0;if("be"===i)for(n=e.length-1;n>=t;n-=2)r=c(e,t,n)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n<e.length;n+=2)r=c(e,t,n)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;this._strip()},o.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var o=e.length-i,s=o%n,a=Math.min(o,o-s)+i,c=0,l=i;l<a;l+=n)c=d(e,l,l+n,t),this.imuln(r),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==s){var u=1;for(c=d(e,l,e.length,t),l=0;l<s;l++)u*=t;this.imuln(u),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this._strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype._move=function(e){l(e,this)},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){o.prototype.inspect=u}else o.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<r|o)).toString(16);o=a>>>24-r&16777215,(r+=2)>=26&&(r-=26,s--),i=0!==o||s!==this.length-1?h[6-c.length]+c+i:c+i}for(0!==o&&(i=o.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var d=f[e],l=p[e];i="";var u=this.clone();for(u.negative=0;!u.isZero();){var g=u.modrn(l).toString(e);i=(u=u.idivn(l)).isZero()?g+i:h[d-g.length]+g+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},s&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function g(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,c=s/67108864|0;i.words[0]=a;for(var d=1;d<n;d++){for(var l=c>>>26,u=67108863&c,h=Math.min(d,t.length-1),f=Math.max(0,d-e.length+1);f<=h;f++){var p=d-f|0;l+=(s=(r=0|e.words[p])*(o=0|t.words[f])+u)/67108864|0,u=67108863&s}i.words[d]=0|u,c=0|l}return 0!==c?i.words[d]=0|c:i.length--,i._strip()}o.prototype.toArrayLike=function(e,t,i){this._strip();var r=this.byteLength(),o=i||Math.max(1,r);n(r<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,r),s},o.prototype._toArrayLikeLE=function(e,t){for(var i=0,n=0,r=0,o=0;r<this.length;r++){var s=this.words[r]<<o|n;e[i++]=255&s,i<e.length&&(e[i++]=s>>8&255),i<e.length&&(e[i++]=s>>16&255),6===o?(i<e.length&&(e[i++]=s>>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(i<e.length)for(e[i++]=n;i<e.length;)e[i++]=0},o.prototype._toArrayLikeBE=function(e,t){for(var i=e.length-1,n=0,r=0,o=0;r<this.length;r++){var s=this.words[r]<<o|n;e[i--]=255&s,i>=0&&(e[i--]=s>>8&255),i>=0&&(e[i--]=s>>16&255),6===o?(i>=0&&(e[i--]=s>>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(i>=0)for(e[i--]=n;i>=0;)e[i--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,i=0;return t>=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var i=this._zeroBits(this.words[t]);if(e+=i,26!==i)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},o.prototype.ior=function(e){return n(0==(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;i<t.length;i++)this.words[i]=this.words[i]&e.words[i];return this.length=t.length,this._strip()},o.prototype.iand=function(e){return n(0==(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;n<i.length;n++)this.words[n]=t.words[n]^i.words[n];if(this!==t)for(;n<t.length;n++)this.words[n]=t.words[n];return this.length=t.length,this._strip()},o.prototype.ixor=function(e){return n(0==(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r<t;r++)this.words[r]=67108863&~this.words[r];return i>0&&(this.words[r]=~this.words[r]&67108863>>26-i),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<<r:this.words[i]&~(1<<r),this._strip()},o.prototype.iadd=function(e){var t,i,n;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(i=this,n=e):(i=e,n=this);for(var r=0,o=0;o<n.length;o++)t=(0|i.words[o])+(0|n.words[o])+r,this.words[o]=67108863&t,r=t>>>26;for(;0!==r&&o<i.length;o++)t=(0|i.words[o])+r,this.words[o]=67108863&t,r=t>>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;o<i.length;o++)this.words[o]=i.words[o];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var o=0,s=0;s<n.length;s++)o=(t=(0|i.words[s])-(0|n.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<i.length;s++)o=(t=(0|i.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<i.length&&i!==this)for(;s<i.length;s++)this.words[s]=i.words[s];return this.length=Math.max(this.length,s),i!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var v=function(e,t,i){var n,r,o,s=e.words,a=t.words,c=i.words,d=0,l=0|s[0],u=8191&l,h=l>>>13,f=0|s[1],p=8191&f,g=f>>>13,v=0|s[2],m=8191&v,y=v>>>13,b=0|s[3],S=8191&b,_=b>>>13,E=0|s[4],w=8191&E,T=E>>>13,I=0|s[5],R=8191&I,M=I>>>13,k=0|s[6],C=8191&k,O=k>>>13,A=0|s[7],P=8191&A,D=A>>>13,x=0|s[8],L=8191&x,U=x>>>13,B=0|s[9],N=8191&B,j=B>>>13,F=0|a[0],K=8191&F,q=F>>>13,$=0|a[1],V=8191&$,H=$>>>13,W=0|a[2],G=8191&W,z=W>>>13,Y=0|a[3],J=8191&Y,Q=Y>>>13,X=0|a[4],Z=8191&X,ee=X>>>13,te=0|a[5],ie=8191&te,ne=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ce=8191&ae,de=ae>>>13,le=0|a[8],ue=8191&le,he=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var ve=(d+(n=Math.imul(u,K))|0)+((8191&(r=(r=Math.imul(u,q))+Math.imul(h,K)|0))<<13)|0;d=((o=Math.imul(h,q))+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,K),r=(r=Math.imul(p,q))+Math.imul(g,K)|0,o=Math.imul(g,q);var me=(d+(n=n+Math.imul(u,V)|0)|0)+((8191&(r=(r=r+Math.imul(u,H)|0)+Math.imul(h,V)|0))<<13)|0;d=((o=o+Math.imul(h,H)|0)+(r>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,K),r=(r=Math.imul(m,q))+Math.imul(y,K)|0,o=Math.imul(y,q),n=n+Math.imul(p,V)|0,r=(r=r+Math.imul(p,H)|0)+Math.imul(g,V)|0,o=o+Math.imul(g,H)|0;var ye=(d+(n=n+Math.imul(u,G)|0)|0)+((8191&(r=(r=r+Math.imul(u,z)|0)+Math.imul(h,G)|0))<<13)|0;d=((o=o+Math.imul(h,z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(S,K),r=(r=Math.imul(S,q))+Math.imul(_,K)|0,o=Math.imul(_,q),n=n+Math.imul(m,V)|0,r=(r=r+Math.imul(m,H)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,G)|0,r=(r=r+Math.imul(p,z)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,z)|0;var be=(d+(n=n+Math.imul(u,J)|0)|0)+((8191&(r=(r=r+Math.imul(u,Q)|0)+Math.imul(h,J)|0))<<13)|0;d=((o=o+Math.imul(h,Q)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(w,K),r=(r=Math.imul(w,q))+Math.imul(T,K)|0,o=Math.imul(T,q),n=n+Math.imul(S,V)|0,r=(r=r+Math.imul(S,H)|0)+Math.imul(_,V)|0,o=o+Math.imul(_,H)|0,n=n+Math.imul(m,G)|0,r=(r=r+Math.imul(m,z)|0)+Math.imul(y,G)|0,o=o+Math.imul(y,z)|0,n=n+Math.imul(p,J)|0,r=(r=r+Math.imul(p,Q)|0)+Math.imul(g,J)|0,o=o+Math.imul(g,Q)|0;var Se=(d+(n=n+Math.imul(u,Z)|0)|0)+((8191&(r=(r=r+Math.imul(u,ee)|0)+Math.imul(h,Z)|0))<<13)|0;d=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(R,K),r=(r=Math.imul(R,q))+Math.imul(M,K)|0,o=Math.imul(M,q),n=n+Math.imul(w,V)|0,r=(r=r+Math.imul(w,H)|0)+Math.imul(T,V)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(S,G)|0,r=(r=r+Math.imul(S,z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(m,J)|0,r=(r=r+Math.imul(m,Q)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Q)|0,n=n+Math.imul(p,Z)|0,r=(r=r+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,o=o+Math.imul(g,ee)|0;var _e=(d+(n=n+Math.imul(u,ie)|0)|0)+((8191&(r=(r=r+Math.imul(u,ne)|0)+Math.imul(h,ie)|0))<<13)|0;d=((o=o+Math.imul(h,ne)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(C,K),r=(r=Math.imul(C,q))+Math.imul(O,K)|0,o=Math.imul(O,q),n=n+Math.imul(R,V)|0,r=(r=r+Math.imul(R,H)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(w,G)|0,r=(r=r+Math.imul(w,z)|0)+Math.imul(T,G)|0,o=o+Math.imul(T,z)|0,n=n+Math.imul(S,J)|0,r=(r=r+Math.imul(S,Q)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Q)|0,n=n+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,ie)|0,r=(r=r+Math.imul(p,ne)|0)+Math.imul(g,ie)|0,o=o+Math.imul(g,ne)|0;var Ee=(d+(n=n+Math.imul(u,oe)|0)|0)+((8191&(r=(r=r+Math.imul(u,se)|0)+Math.imul(h,oe)|0))<<13)|0;d=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(P,K),r=(r=Math.imul(P,q))+Math.imul(D,K)|0,o=Math.imul(D,q),n=n+Math.imul(C,V)|0,r=(r=r+Math.imul(C,H)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(R,G)|0,r=(r=r+Math.imul(R,z)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(w,J)|0,r=(r=r+Math.imul(w,Q)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Q)|0,n=n+Math.imul(S,Z)|0,r=(r=r+Math.imul(S,ee)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,ie)|0,r=(r=r+Math.imul(m,ne)|0)+Math.imul(y,ie)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,r=(r=r+Math.imul(p,se)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,se)|0;var we=(d+(n=n+Math.imul(u,ce)|0)|0)+((8191&(r=(r=r+Math.imul(u,de)|0)+Math.imul(h,ce)|0))<<13)|0;d=((o=o+Math.imul(h,de)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(L,K),r=(r=Math.imul(L,q))+Math.imul(U,K)|0,o=Math.imul(U,q),n=n+Math.imul(P,V)|0,r=(r=r+Math.imul(P,H)|0)+Math.imul(D,V)|0,o=o+Math.imul(D,H)|0,n=n+Math.imul(C,G)|0,r=(r=r+Math.imul(C,z)|0)+Math.imul(O,G)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(R,J)|0,r=(r=r+Math.imul(R,Q)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Q)|0,n=n+Math.imul(w,Z)|0,r=(r=r+Math.imul(w,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(S,ie)|0,r=(r=r+Math.imul(S,ne)|0)+Math.imul(_,ie)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,r=(r=r+Math.imul(m,se)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,se)|0,n=n+Math.imul(p,ce)|0,r=(r=r+Math.imul(p,de)|0)+Math.imul(g,ce)|0,o=o+Math.imul(g,de)|0;var Te=(d+(n=n+Math.imul(u,ue)|0)|0)+((8191&(r=(r=r+Math.imul(u,he)|0)+Math.imul(h,ue)|0))<<13)|0;d=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(N,K),r=(r=Math.imul(N,q))+Math.imul(j,K)|0,o=Math.imul(j,q),n=n+Math.imul(L,V)|0,r=(r=r+Math.imul(L,H)|0)+Math.imul(U,V)|0,o=o+Math.imul(U,H)|0,n=n+Math.imul(P,G)|0,r=(r=r+Math.imul(P,z)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,z)|0,n=n+Math.imul(C,J)|0,r=(r=r+Math.imul(C,Q)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Q)|0,n=n+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(w,ie)|0,r=(r=r+Math.imul(w,ne)|0)+Math.imul(T,ie)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(S,oe)|0,r=(r=r+Math.imul(S,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,n=n+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,de)|0)+Math.imul(y,ce)|0,o=o+Math.imul(y,de)|0,n=n+Math.imul(p,ue)|0,r=(r=r+Math.imul(p,he)|0)+Math.imul(g,ue)|0,o=o+Math.imul(g,he)|0;var Ie=(d+(n=n+Math.imul(u,pe)|0)|0)+((8191&(r=(r=r+Math.imul(u,ge)|0)+Math.imul(h,pe)|0))<<13)|0;d=((o=o+Math.imul(h,ge)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(N,V),r=(r=Math.imul(N,H))+Math.imul(j,V)|0,o=Math.imul(j,H),n=n+Math.imul(L,G)|0,r=(r=r+Math.imul(L,z)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(P,J)|0,r=(r=r+Math.imul(P,Q)|0)+Math.imul(D,J)|0,o=o+Math.imul(D,Q)|0,n=n+Math.imul(C,Z)|0,r=(r=r+Math.imul(C,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(R,ie)|0,r=(r=r+Math.imul(R,ne)|0)+Math.imul(M,ie)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(w,oe)|0,r=(r=r+Math.imul(w,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,n=n+Math.imul(S,ce)|0,r=(r=r+Math.imul(S,de)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,de)|0,n=n+Math.imul(m,ue)|0,r=(r=r+Math.imul(m,he)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,he)|0;var Re=(d+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;d=((o=o+Math.imul(g,ge)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,G),r=(r=Math.imul(N,z))+Math.imul(j,G)|0,o=Math.imul(j,z),n=n+Math.imul(L,J)|0,r=(r=r+Math.imul(L,Q)|0)+Math.imul(U,J)|0,o=o+Math.imul(U,Q)|0,n=n+Math.imul(P,Z)|0,r=(r=r+Math.imul(P,ee)|0)+Math.imul(D,Z)|0,o=o+Math.imul(D,ee)|0,n=n+Math.imul(C,ie)|0,r=(r=r+Math.imul(C,ne)|0)+Math.imul(O,ie)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(R,oe)|0,r=(r=r+Math.imul(R,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,n=n+Math.imul(w,ce)|0,r=(r=r+Math.imul(w,de)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,de)|0,n=n+Math.imul(S,ue)|0,r=(r=r+Math.imul(S,he)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,he)|0;var Me=(d+(n=n+Math.imul(m,pe)|0)|0)+((8191&(r=(r=r+Math.imul(m,ge)|0)+Math.imul(y,pe)|0))<<13)|0;d=((o=o+Math.imul(y,ge)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),r=(r=Math.imul(N,Q))+Math.imul(j,J)|0,o=Math.imul(j,Q),n=n+Math.imul(L,Z)|0,r=(r=r+Math.imul(L,ee)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(P,ie)|0,r=(r=r+Math.imul(P,ne)|0)+Math.imul(D,ie)|0,o=o+Math.imul(D,ne)|0,n=n+Math.imul(C,oe)|0,r=(r=r+Math.imul(C,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,n=n+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,de)|0)+Math.imul(M,ce)|0,o=o+Math.imul(M,de)|0,n=n+Math.imul(w,ue)|0,r=(r=r+Math.imul(w,he)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,he)|0;var ke=(d+(n=n+Math.imul(S,pe)|0)|0)+((8191&(r=(r=r+Math.imul(S,ge)|0)+Math.imul(_,pe)|0))<<13)|0;d=((o=o+Math.imul(_,ge)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),r=(r=Math.imul(N,ee))+Math.imul(j,Z)|0,o=Math.imul(j,ee),n=n+Math.imul(L,ie)|0,r=(r=r+Math.imul(L,ne)|0)+Math.imul(U,ie)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(P,oe)|0,r=(r=r+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,n=n+Math.imul(C,ce)|0,r=(r=r+Math.imul(C,de)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,de)|0,n=n+Math.imul(R,ue)|0,r=(r=r+Math.imul(R,he)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,he)|0;var Ce=(d+(n=n+Math.imul(w,pe)|0)|0)+((8191&(r=(r=r+Math.imul(w,ge)|0)+Math.imul(T,pe)|0))<<13)|0;d=((o=o+Math.imul(T,ge)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,ie),r=(r=Math.imul(N,ne))+Math.imul(j,ie)|0,o=Math.imul(j,ne),n=n+Math.imul(L,oe)|0,r=(r=r+Math.imul(L,se)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,se)|0,n=n+Math.imul(P,ce)|0,r=(r=r+Math.imul(P,de)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,de)|0,n=n+Math.imul(C,ue)|0,r=(r=r+Math.imul(C,he)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,he)|0;var Oe=(d+(n=n+Math.imul(R,pe)|0)|0)+((8191&(r=(r=r+Math.imul(R,ge)|0)+Math.imul(M,pe)|0))<<13)|0;d=((o=o+Math.imul(M,ge)|0)+(r>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,oe),r=(r=Math.imul(N,se))+Math.imul(j,oe)|0,o=Math.imul(j,se),n=n+Math.imul(L,ce)|0,r=(r=r+Math.imul(L,de)|0)+Math.imul(U,ce)|0,o=o+Math.imul(U,de)|0,n=n+Math.imul(P,ue)|0,r=(r=r+Math.imul(P,he)|0)+Math.imul(D,ue)|0,o=o+Math.imul(D,he)|0;var Ae=(d+(n=n+Math.imul(C,pe)|0)|0)+((8191&(r=(r=r+Math.imul(C,ge)|0)+Math.imul(O,pe)|0))<<13)|0;d=((o=o+Math.imul(O,ge)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,ce),r=(r=Math.imul(N,de))+Math.imul(j,ce)|0,o=Math.imul(j,de),n=n+Math.imul(L,ue)|0,r=(r=r+Math.imul(L,he)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,he)|0;var Pe=(d+(n=n+Math.imul(P,pe)|0)|0)+((8191&(r=(r=r+Math.imul(P,ge)|0)+Math.imul(D,pe)|0))<<13)|0;d=((o=o+Math.imul(D,ge)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,ue),r=(r=Math.imul(N,he))+Math.imul(j,ue)|0,o=Math.imul(j,he);var De=(d+(n=n+Math.imul(L,pe)|0)|0)+((8191&(r=(r=r+Math.imul(L,ge)|0)+Math.imul(U,pe)|0))<<13)|0;d=((o=o+Math.imul(U,ge)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863;var xe=(d+(n=Math.imul(N,pe))|0)+((8191&(r=(r=Math.imul(N,ge))+Math.imul(j,pe)|0))<<13)|0;return d=((o=Math.imul(j,ge))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=ve,c[1]=me,c[2]=ye,c[3]=be,c[4]=Se,c[5]=_e,c[6]=Ee,c[7]=we,c[8]=Te,c[9]=Ie,c[10]=Re,c[11]=Me,c[12]=ke,c[13]=Ce,c[14]=Oe,c[15]=Ae,c[16]=Pe,c[17]=De,c[18]=xe,0!==d&&(c[19]=d,i.length++),i};function m(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,o=0;o<i.length-1;o++){var s=r;r=0;for(var a=67108863&n,c=Math.min(o,t.length-1),d=Math.max(0,o-e.length+1);d<=c;d++){var l=o-d,u=(0|e.words[l])*(0|t.words[d]),h=67108863&u;a=67108863&(h=h+a|0),r+=(s=(s=s+(u/67108864|0)|0)+(h>>>26)|0)>>>26,s&=67108863}i.words[o]=a,n=s,s=r}return 0!==n?i.words[o]=n:i.length--,i._strip()}function y(e,t,i){return m(e,t,i)}function b(e,t){this.x=e,this.y=t}Math.imul||(v=g),o.prototype.mulTo=function(e,t){var i=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):i<63?g(this,e,t):i<1024?m(this,e,t):y(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),i=o.prototype._countBits(e)-1,n=0;n<e;n++)t[n]=this.revBin(n,i,e);return t},b.prototype.revBin=function(e,t,i){if(0===e||e===i-1)return e;for(var n=0,r=0;r<t;r++)n|=(1&e)<<t-r-1,e>>=1;return n},b.prototype.permute=function(e,t,i,n,r,o){for(var s=0;s<o;s++)n[s]=t[e[s]],r[s]=i[e[s]]},b.prototype.transform=function(e,t,i,n,r,o){this.permute(o,e,t,i,n,r);for(var s=1;s<r;s<<=1)for(var a=s<<1,c=Math.cos(2*Math.PI/a),d=Math.sin(2*Math.PI/a),l=0;l<r;l+=a)for(var u=c,h=d,f=0;f<s;f++){var p=i[l+f],g=n[l+f],v=i[l+f+s],m=n[l+f+s],y=u*v-h*m;m=u*m+h*v,v=y,i[l+f]=p+v,n[l+f]=g+m,i[l+f+s]=p-v,n[l+f+s]=g-m,f!==a&&(y=c*u-d*h,h=c*h+d*u,u=y)}},b.prototype.guessLen13b=function(e,t){var i=1|Math.max(t,e),n=1&i,r=0;for(i=i/2|0;i;i>>>=1)r++;return 1<<r+1+n},b.prototype.conjugate=function(e,t,i){if(!(i<=1))for(var n=0;n<i/2;n++){var r=e[n];e[n]=e[i-n-1],e[i-n-1]=r,r=t[n],t[n]=-t[i-n-1],t[i-n-1]=-r}},b.prototype.normalize13b=function(e,t){for(var i=0,n=0;n<t/2;n++){var r=8192*Math.round(e[2*n+1]/t)+Math.round(e[2*n]/t)+i;e[n]=67108863&r,i=r<67108864?0:r/67108864|0}return e},b.prototype.convert13b=function(e,t,i,r){for(var o=0,s=0;s<t;s++)o+=0|e[s],i[2*s]=8191&o,o>>>=13,i[2*s+1]=8191&o,o>>>=13;for(s=2*t;s<r;++s)i[s]=0;n(0===o),n(0==(-8192&o))},b.prototype.stub=function(e){for(var t=new Array(e),i=0;i<e;i++)t[i]=0;return t},b.prototype.mulp=function(e,t,i){var n=2*this.guessLen13b(e.length,t.length),r=this.makeRBT(n),o=this.stub(n),s=new Array(n),a=new Array(n),c=new Array(n),d=new Array(n),l=new Array(n),u=new Array(n),h=i.words;h.length=n,this.convert13b(e.words,e.length,s,n),this.convert13b(t.words,t.length,d,n),this.transform(s,o,a,c,n,r),this.transform(d,o,l,u,n,r);for(var f=0;f<n;f++){var p=a[f]*l[f]-c[f]*u[f];c[f]=a[f]*u[f]+c[f]*l[f],a[f]=p}return this.conjugate(a,c,n),this.transform(a,c,h,o,n,r),this.conjugate(h,o,n),this.normalize13b(h,n),i.negative=e.negative^t.negative,i.length=e.length+t.length,i._strip()},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),y(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var i=0,r=0;r<this.length;r++){var o=(0|this.words[r])*e,s=(67108863&o)+(67108863&i);i>>=26,i+=o/67108864|0,i+=s>>>26,this.words[r]=67108863&s}return 0!==i&&(this.words[r]=i,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i<t.length;i++){var n=i/26|0,r=i%26;t[i]=e.words[n]>>>r&1}return t}(e);if(0===t.length)return new o(1);for(var i=this,n=0;n<t.length&&0===t[n];n++,i=i.sqr());if(++n<t.length)for(var r=i.sqr();n<t.length;n++,r=r.sqr())0!==t[n]&&(i=i.mul(r));return i},o.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,i=e%26,r=(e-i)/26,o=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<i;this.words[t]=c|s,s=a>>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t<r;t++)this.words[t]=0;this.length+=r}return this._strip()},o.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,i){var r;n("number"==typeof e&&e>=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=i;if(r-=s,r=Math.max(0,r),c){for(var d=0;d<s;d++)c.words[d]=this.words[d];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,d=0;d<this.length;d++)this.words[d]=this.words[d+s];else this.words[0]=0,this.length=1;var l=0;for(d=this.length-1;d>=0&&(0!==l||d>=r);d--){var u=0|this.words[d];this.words[d]=l<<26-o|u>>>o,l=u&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<<t;return!(this.length<=i)&&!!(this.words[i]&r)},o.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<<t;this.words[this.length-1]&=r}return this._strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,i){var r,o,s=e.length+i;this._expand(s);var a=0;for(r=0;r<e.length;r++){o=(0|this.words[r+i])+a;var c=(0|e.words[r])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[r+i]=67108863&o}for(;r<this.length-i;r++)a=(o=(0|this.words[r+i])+a)>>26,this.words[r+i]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,r=0;r<this.length;r++)a=(o=-(0|this.words[r])+a)>>26,this.words[r]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,s=0|r.words[r.length-1];0!==(i=26-this._countBits(s))&&(r=r.ushln(i),n.iushln(i),s=0|r.words[r.length-1]);var a,c=n.length-r.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var d=0;d<a.length;d++)a.words[d]=0}var l=n.clone()._ishlnsubmul(r,1,c);0===l.negative&&(n=l,a&&(a.words[c]=1));for(var u=c-1;u>=0;u--){var h=67108864*(0|n.words[r.length+u])+(0|n.words[r.length+u-1]);for(h=Math.min(h/s|0,67108863),n._ishlnsubmul(r,h,u);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(r,1,u),n.isZero()||(n.negative^=1);a&&(a.words[u]=h)}return a&&a._strip(),n._strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:a||null,mod:n}},o.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(r=a.div.neg()),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:r,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(r=a.div.neg()),{div:r,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var r,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),o=i.cmp(n);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=(1<<26)%e,r=0,o=this.length-1;o>=0;o--)r=(i*r+(0|this.words[o]))%e;return t?-r:r},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=0,r=this.length-1;r>=0;r--){var o=(0|this.words[r])+67108864*i;this.words[r]=o/e|0,i=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new o(1),s=new o(0),a=new o(0),c=new o(1),d=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++d;for(var l=i.clone(),u=t.clone();!t.isZero();){for(var h=0,f=1;0==(t.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(r.isOdd()||s.isOdd())&&(r.iadd(l),s.isub(u)),r.iushrn(1),s.iushrn(1);for(var p=0,g=1;0==(i.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(u)),a.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(a),s.isub(c)):(i.isub(t),a.isub(r),c.isub(s))}return{a:a,b:c,gcd:i.iushln(d)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,s=new o(1),a=new o(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var d=0,l=1;0==(t.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(t.iushrn(d);d-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var u=0,h=1;0==(i.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(i.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(a)):(i.isub(t),a.isub(s))}return(r=0===t.cmpn(1)?s:a).cmpn(0)<0&&r.iadd(e),r},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var o=t;t=i,i=o}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<<t;if(this.length<=i)return this._expand(i+1),this.words[i]|=r,this;for(var o=r,s=i;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this._strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:r<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,i=this.length-1;i>=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){n<r?t=-1:n>r&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new R(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var S={k256:null,p224:null,p192:null,p25519:null};function _(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function E(){_.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){_.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function T(){_.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function I(){_.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function R(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function M(e){R.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}_.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},_.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t<this.n?-1:i.ucmp(this.p);return 0===n?(i.words[0]=0,i.length=1):n>0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},_.prototype.split=function(e,t){e.iushrn(this.n,0,t)},_.prototype.imulK=function(e){return e.imul(this.k)},r(E,_),E.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r<n;r++)t.words[r]=e.words[r];if(t.length=n,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&i,r=10;r<e.length;r++){var s=0|e.words[r];e.words[r-10]=(s&i)<<4|o>>>22,o=s}o>>>=22,e.words[r-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},E.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i<e.length;i++){var n=0|e.words[i];t+=977*n,e.words[i]=67108863&t,t=64*n+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(w,_),r(T,_),r(I,_),I.prototype.imulK=function(e){for(var t=0,i=0;i<e.length;i++){var n=19*(0|e.words[i])+t,r=67108863&n;n>>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(S[e])return S[e];var t;if("k256"===e)t=new E;else if("p224"===e)t=new w;else if("p192"===e)t=new T;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new I}return S[e]=t,t},R.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},R.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},R.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},R.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},R.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},R.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},R.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},R.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},R.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},R.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},R.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},R.prototype.isqr=function(e){return this.imul(e,e.clone())},R.prototype.sqr=function(e){return this.mul(e,e)},R.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new o(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),s=0;!r.isZero()&&0===r.andln(1);)s++,r.iushrn(1);n(!r.isZero());var a=new o(1).toRed(this),c=a.redNeg(),d=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,d).cmp(c);)l.redIAdd(c);for(var u=this.pow(l,r),h=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),p=s;0!==f.cmp(a);){for(var g=f,v=0;0!==g.cmp(a);v++)g=g.redSqr();n(v<p);var m=this.pow(u,new o(1).iushln(p-v-1));h=h.redMul(m),u=m.redSqr(),f=f.redMul(u),p=v}return h},R.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},R.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var i=new Array(16);i[0]=new o(1).toRed(this),i[1]=e;for(var n=2;n<i.length;n++)i[n]=this.mul(i[n-1],e);var r=i[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),n=t.length-1;n>=0;n--){for(var d=t.words[n],l=c-1;l>=0;l--){var u=d>>l&1;r!==i[0]&&(r=this.sqr(r)),0!==u||0!==s?(s<<=1,s|=u,(4===++a||0===n&&0===l)&&(r=this.mul(r,i[s]),a=0,s=0)):a=0}c=26}return r},R.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},R.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new M(e)},r(M,R),M.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},M.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},M.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},M.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},M.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:20}],43:[function(e,t,i){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":44}],44:[function(e,t,i){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],45:[function(e,t,i){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],46:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hash"),o=e("readable-stream"),s=e("inherits"),a=e("./sign"),c=e("./verify"),d=e("./algorithms.json");function l(e){o.Writable.call(this);var t=d[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function u(e){o.Writable.call(this);var t=d[e];if(!t)throw new Error("Unknown message digest");this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new l(e)}function f(e){return new u(e)}Object.keys(d).forEach((function(e){d[e].id=n.from(d[e].id,"hex"),d[e.toLowerCase()]=d[e]})),s(l,o.Writable),l.prototype._write=function(e,t,i){this._hash.update(e),i()},l.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},l.prototype.sign=function(e,t){this.end();var i=this._hash.digest(),n=a(i,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},s(u,o.Writable),u.prototype._write=function(e,t,i){this._hash.update(e),i()},u.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},u.prototype.verify=function(e,t,i){"string"==typeof t&&(t=n.from(t,i)),this.end();var r=this._hash.digest();return c(t,r,e,this._signType,this._tag)},t.exports={Sign:h,Verify:f,createSign:h,createVerify:f}},{"./algorithms.json":44,"./sign":47,"./verify":48,"create-hash":74,inherits:146,"readable-stream":64,"safe-buffer":250}],47:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hmac"),o=e("browserify-rsa"),s=e("elliptic").ec,a=e("bn.js"),c=e("parse-asn1"),d=e("./curves.json");function l(e,t,i,o){if((e=n.from(e.toArray())).length<t.byteLength()){var s=n.alloc(t.byteLength()-e.length);e=n.concat([s,e])}var a=i.length,c=function(e,t){e=u(e,t),e=e.mod(t);var i=n.from(e.toArray());if(i.length<t.byteLength()){var r=n.alloc(t.byteLength()-i.length);i=n.concat([r,i])}return i}(i,t),d=n.alloc(a);d.fill(1);var l=n.alloc(a);return l=r(o,l).update(d).update(n.from([0])).update(e).update(c).digest(),d=r(o,l).update(d).digest(),{k:l=r(o,l).update(d).update(n.from([1])).update(e).update(c).digest(),v:d=r(o,l).update(d).digest()}}function u(e,t){var i=new a(e),n=(e.length<<3)-t.bitLength();return n>0&&i.ishrn(n),i}function h(e,t,i){var o,s;do{for(o=n.alloc(0);8*o.length<e.bitLength();)t.v=r(i,t.k).update(t.v).digest(),o=n.concat([o,t.v]);s=u(o,e),t.k=r(i,t.k).update(t.v).update(n.from([0])).digest(),t.v=r(i,t.k).update(t.v).digest()}while(-1!==s.cmp(e));return s}function f(e,t,i,n){return e.toRed(a.mont(i)).redPow(t).fromRed().mod(n)}t.exports=function(e,t,i,r,p){var g=c(t);if(g.curve){if("ecdsa"!==r&&"ecdsa/rsa"!==r)throw new Error("wrong private key type");return function(e,t){var i=d[t.curve.join(".")];if(!i)throw new Error("unknown curve "+t.curve.join("."));var r=new s(i).keyFromPrivate(t.privateKey),o=r.sign(e);return n.from(o.toDER())}(e,g)}if("dsa"===g.type){if("dsa"!==r)throw new Error("wrong private key type");return function(e,t,i){var r,o=t.params.priv_key,s=t.params.p,c=t.params.q,d=t.params.g,p=new a(0),g=u(e,c).mod(c),v=!1,m=l(o,c,e,i);for(;!1===v;)p=f(d,r=h(c,m,i),s,c),0===(v=r.invm(c).imul(g.add(o.mul(p))).mod(c)).cmpn(0)&&(v=!1,p=new a(0));return function(e,t){e=e.toArray(),t=t.toArray(),128&e[0]&&(e=[0].concat(e));128&t[0]&&(t=[0].concat(t));var i=e.length+t.length+4,r=[48,i,2,e.length];return r=r.concat(e,[2,t.length],t),n.from(r)}(p,v)}(e,g,i)}if("rsa"!==r&&"ecdsa/rsa"!==r)throw new Error("wrong private key type");e=n.concat([p,e]);for(var v=g.modulus.byteLength(),m=[0,1];e.length+m.length+1<v;)m.push(255);m.push(0);for(var y=-1;++y<e.length;)m.push(e[y]);return o(m,g)},t.exports.getKey=l,t.exports.makeKey=h},{"./curves.json":45,"bn.js":49,"browserify-rsa":41,"create-hmac":76,elliptic:89,"parse-asn1":230,"safe-buffer":250}],48:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("bn.js"),o=e("elliptic").ec,s=e("parse-asn1"),a=e("./curves.json");function c(e,t){if(e.cmpn(0)<=0)throw new Error("invalid sig");if(e.cmp(t)>=t)throw new Error("invalid sig")}t.exports=function(e,t,i,d,l){var u=s(i);if("ec"===u.type){if("ecdsa"!==d&&"ecdsa/rsa"!==d)throw new Error("wrong public key type");return function(e,t,i){var n=a[i.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+i.data.algorithm.curve.join("."));var r=new o(n),s=i.data.subjectPrivateKey.data;return r.verify(t,e,s)}(e,t,u)}if("dsa"===u.type){if("dsa"!==d)throw new Error("wrong public key type");return function(e,t,i){var n=i.data.p,o=i.data.q,a=i.data.g,d=i.data.pub_key,l=s.signature.decode(e,"der"),u=l.s,h=l.r;c(u,o),c(h,o);var f=r.mont(n),p=u.invm(o),g=a.toRed(f).redPow(new r(t).mul(p).mod(o)).fromRed().mul(d.toRed(f).redPow(h.mul(p).mod(o)).fromRed()).mod(n).mod(o);return 0===g.cmp(h)}(e,t,u)}if("rsa"!==d&&"ecdsa/rsa"!==d)throw new Error("wrong public key type");t=n.concat([l,t]);for(var h=u.modulus.byteLength(),f=[1],p=0;t.length+f.length+2<h;)f.push(255),p++;f.push(0);for(var g=-1;++g<t.length;)f.push(t[g]);f=n.from(f);var v=r.mont(u.modulus);e=(e=new r(e).toRed(v)).redPow(new r(u.publicExponent)),e=n.from(e.fromRed().toArray());var m=p<8?1:0;for(h=Math.min(e.length,f.length),e.length!==f.length&&(m=1),g=-1;++g<h;)m|=e[g]^f[g];return 0===m}},{"./curves.json":45,"bn.js":49,elliptic:89,"parse-asn1":230,"safe-buffer":250}],49:[function(e,t,i){arguments[4][42][0].apply(i,arguments)},{buffer:20,dup:42}],50:[function(e,t,i){"use strict";var n={};function r(e,t,i){i||(i=Error);var r=function(e){var i,n;function r(i,n,r){return e.call(this,function(e,i,n){return"string"==typeof t?t:t(e,i,n)}(i,n,r))||this}return n=e,(i=r).prototype=Object.create(n.prototype),i.prototype.constructor=i,i.__proto__=n,r}(i);r.prototype.name=i.name,r.prototype.code=e,n[e]=r}function o(e,t){if(Array.isArray(e)){var i=e.length;return e=e.map((function(e){return String(e)})),i>2?"one of ".concat(t," ").concat(e.slice(0,i-1).join(", "),", or ")+e[i-1]:2===i?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}r("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),r("ERR_INVALID_ARG_TYPE",(function(e,t,i){var n,r,s,a;if("string"==typeof t&&(r="not ",t.substr(!s||s<0?0:+s,r.length)===r)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,i){return(void 0===i||i>e.length)&&(i=e.length),e.substring(i-t.length,i)===t}(e," argument"))a="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var c=function(e,t,i){return"number"!=typeof i&&(i=0),!(i+t.length>e.length)&&-1!==e.indexOf(t,i)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(c," ").concat(n," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof i)}),TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=n},{}],51:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a<s.length;a++){var c=s[a];d.prototype[c]||(d.prototype[c]=o.prototype[c])}function d(e){if(!(this instanceof d))return new d(e);r.call(this,e),o.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",l)))}function l(){this._writableState.ended||i.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(d.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(d.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":53,"./_stream_writable":55,_process:237,inherits:146}],52:[function(e,t,i){"use strict";t.exports=r;var n=e("./_stream_transform");function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}e("inherits")(r,n),r.prototype._transform=function(e,t,i){i(null,e)}},{"./_stream_transform":54,inherits:146}],53:[function(e,t,i){(function(i,n){(function(){"use strict";var r;t.exports=I,I.ReadableState=T;e("events").EventEmitter;var o=function(e,t){return e.listeners(t).length},s=e("./internal/streams/stream"),a=e("buffer").Buffer,c=n.Uint8Array||function(){};var d,l=e("util");d=l&&l.debuglog?l.debuglog("stream"):function(){};var u,h,f,p=e("./internal/streams/buffer_list"),g=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,m=e("../errors").codes,y=m.ERR_INVALID_ARG_TYPE,b=m.ERR_STREAM_PUSH_AFTER_EOF,S=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(I,s);var E=g.errorOrDestroy,w=["error","close","destroy","pause","resume"];function T(t,i,n){r=r||e("./_stream_duplex"),t=t||{},"boolean"!=typeof n&&(n=i instanceof r),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",n),this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(u||(u=e("string_decoder/").StringDecoder),this.decoder=new u(t.encoding),this.encoding=t.encoding)}function I(t){if(r=r||e("./_stream_duplex"),!(this instanceof I))return new I(t);var i=this instanceof r;this._readableState=new T(t,this,i),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),s.call(this)}function R(e,t,i,n,r){d("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(d("onEofChunk"),t.ended)return;if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,t.sync?O(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,A(e)))}(e,s);else if(r||(o=function(e,t){var i;n=t,a.isBuffer(n)||n instanceof c||"string"==typeof t||void 0===t||e.objectMode||(i=new y("chunk",["string","Buffer","Uint8Array"],t));var n;return i}(s,t)),o)E(e,o);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function M(e,t,i,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",i)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&O(e)),P(e,t)}Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),I.prototype.destroy=g.destroy,I.prototype._undestroy=g.undestroy,I.prototype._destroy=function(e,t){t(e)},I.prototype.push=function(e,t){var i,n=this._readableState;return n.objectMode?i=!0:"string"==typeof e&&((t=t||n.defaultEncoding)!==n.encoding&&(e=a.from(e,t),t=""),i=!0),R(this,e,t,!1,i)},I.prototype.unshift=function(e){return R(this,e,null,!0,!1)},I.prototype.isPaused=function(){return!1===this._readableState.flowing},I.prototype.setEncoding=function(t){u||(u=e("string_decoder/").StringDecoder);var i=new u(t);this._readableState.decoder=i,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=i.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function C(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var i=t.length;if(d("maybeReadMore read 0"),e.read(0),i===t.length)break}t.readingMore=!1}function x(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}I.prototype.read=function(e){d("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",r=!0),t.ended||t.reading?d("reading or ended",r=!1):r&&(d("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=C(i,t))),null===(n=e>0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<r;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=K(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i)),this},I.prototype.on=function(e,t){var n=s.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));return this._read=function(t){d("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(I.prototype[Symbol.asyncIterator]=function(){return void 0===h&&(h=e("./internal/streams/async_iterator")),h(this)}),Object.defineProperty(I.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(I.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(I.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),I._fromList=N,Object.defineProperty(I.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(I.from=function(t,i){return void 0===f&&(f=e("./internal/streams/from")),f(I,t,i)})}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":50,"./_stream_duplex":51,"./internal/streams/async_iterator":56,"./internal/streams/buffer_list":57,"./internal/streams/destroy":58,"./internal/streams/from":60,"./internal/streams/state":62,"./internal/streams/stream":63,_process:237,buffer:68,events:105,inherits:146,"string_decoder/":279,util:20}],54:[function(e,t,i){"use strict";t.exports=l;var n=e("../errors").codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,o=n.ERR_MULTIPLE_CALLBACK,s=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=n.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function d(e,t){var i=this._transformState;i.transforming=!1;var n=i.writecb;if(null===n)return this.emit("error",new o);i.writechunk=null,i.writecb=null,null!=t&&this.push(t),n(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);c.call(this,e),this._transformState={afterTransform:d.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,i){h(e,t,i)}))}function h(e,t,i){if(t)return e.emit("error",t);if(null!=i&&e.push(i),e._writableState.length)throw new a;if(e._transformState.transforming)throw new s;return e.push(null)}e("inherits")(l,c),l.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,i){i(new r("_transform()"))},l.prototype._write=function(e,t,i){var n=this._transformState;if(n.writecb=i,n.writechunk=e,n.writeencoding=t,!n.transforming){var r=this._readableState;(n.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},l.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":50,"./_stream_duplex":51,inherits:146}],55:[function(e,t,i){(function(i,n){(function(){"use strict";function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,i){var n=e.entry;e.entry=null;for(;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var o;t.exports=I,I.WritableState=T;var s={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),c=e("buffer").Buffer,d=n.Uint8Array||function(){};var l,u=e("./internal/streams/destroy"),h=e("./internal/streams/state").getHighWaterMark,f=e("../errors").codes,p=f.ERR_INVALID_ARG_TYPE,g=f.ERR_METHOD_NOT_IMPLEMENTED,v=f.ERR_MULTIPLE_CALLBACK,m=f.ERR_STREAM_CANNOT_PIPE,y=f.ERR_STREAM_DESTROYED,b=f.ERR_STREAM_NULL_VALUES,S=f.ERR_STREAM_WRITE_AFTER_END,_=f.ERR_UNKNOWN_ENCODING,E=u.errorOrDestroy;function w(){}function T(t,n,s){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof s&&(s=n instanceof o),this.objectMode=!!t.objectMode,s&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=h(this,t,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,o=n.writecb;if("function"!=typeof o)throw new v;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,o){--t.pendingcb,n?(i.nextTick(o,r),i.nextTick(A,e,t),e._writableState.errorEmitted=!0,E(e,r)):(o(r),e._writableState.errorEmitted=!0,E(e,r),A(e,t))}(e,n,r,t,o);else{var s=C(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?i.nextTick(M,e,n,s,o):M(e,n,s,o)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}function I(t){var i=this instanceof(o=o||e("./_stream_duplex"));if(!i&&!l.call(I,this))return new I(t);this._writableState=new T(t,this,i),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function R(e,t,i,n,r,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new y("write")):i?e._writev(r,t.onwrite):e._write(r,o,t.onwrite),t.sync=!1}function M(e,t,i,n){i||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),A(e,t)}function k(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,o=new Array(n),s=t.corkedRequestsFree;s.entry=i;for(var a=0,c=!0;i;)o[a]=i,i.isBuf||(c=!1),i=i.next,a+=1;o.allBuffers=c,R(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;i;){var d=i.chunk,l=i.encoding,u=i.callback;if(R(e,t,!1,t.objectMode?1:d.length,d,l,u),i=i.next,t.bufferedRequestCount--,t.writing)break}null===i&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}function C(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function O(e,t){e._final((function(i){t.pendingcb--,i&&E(e,i),t.prefinished=!0,e.emit("prefinish"),A(e,t)}))}function A(e,t){var n=C(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,i.nextTick(O,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}e("inherits")(I,a),T.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(T.prototype,"buffer",{get:s.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(l=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!l.call(this,e)||this===I&&(e&&e._writableState instanceof T)}})):l=function(e){return e instanceof this},I.prototype.pipe=function(){E(this,new m)},I.prototype.write=function(e,t,n){var r,o=this._writableState,s=!1,a=!o.objectMode&&(r=e,c.isBuffer(r)||r instanceof d);return a&&!c.isBuffer(e)&&(e=function(e){return c.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof n&&(n=w),o.ending?function(e,t){var n=new S;E(e,n),i.nextTick(t,n)}(this,n):(a||function(e,t,n,r){var o;return null===n?o=new b:"string"==typeof n||t.objectMode||(o=new p("chunk",["string","Buffer"],n)),!o||(E(e,o),i.nextTick(r,o),!1)}(this,o,e,n))&&(o.pendingcb++,s=function(e,t,i,n,r,o){if(!i){var s=function(e,t,i){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,i));return t}(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var a=t.objectMode?1:n.length;t.length+=a;var d=t.length<t.highWaterMark;d||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,a,n,r,o);return d}(this,o,a,e,t,n)),s},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},I.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":50,"./_stream_duplex":51,"./internal/streams/destroy":58,"./internal/streams/state":62,"./internal/streams/stream":63,_process:237,buffer:68,inherits:146,"util-deprecate":283}],56:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":59,_process:237}],57:[function(e,t,i){"use strict";function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function o(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var s=e("buffer").Buffer,a=e("util").inspect,c=a&&a.custom||"inspect";t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}var t,i,d;return t=e,i=[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,i=""+t.data;t=t.next;)i+=e+t.data;return i}},{key:"concat",value:function(e){if(0===this.length)return s.alloc(0);for(var t,i,n,r=s.allocUnsafe(e>>>0),o=this.head,a=0;o;)t=o.data,i=r,n=a,s.prototype.copy.call(t,i,n),a+=o.data.length,o=o.next;return r}},{key:"consume",value:function(e,t){var i;return e<this.head.data.length?(i=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):i=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),i}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,i=1,n=t.data;for(e-=n.length;t=t.next;){var r=t.data,o=e>r.length?r.length:e;if(o===r.length?n+=r:n+=r.slice(0,e),0==(e-=o)){o===r.length?(++i,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=r.slice(o));break}++i}return this.length-=i,n}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),i=this.head,n=1;for(i.data.copy(t),e-=i.data.length;i=i.next;){var r=i.data,o=e>r.length?r.length:e;if(r.copy(t,t.length-e,0,o),0==(e-=o)){o===r.length?(++n,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=r.slice(o));break}++n}return this.length-=n,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?n(Object(i),!0).forEach((function(t){r(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t,{depth:0,customInspect:!1}))}}],i&&o(t.prototype,i),d&&o(t,d),e}()},{buffer:68,util:20}],58:[function(e,t,i){(function(e){(function(){"use strict";function i(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(r,this,t)):e.nextTick(r,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(n,s):(s._writableState.errorEmitted=!0,e.nextTick(i,s,t)):e.nextTick(i,s,t):o?(e.nextTick(n,s),o(t)):e.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var i=e._readableState,n=e._writableState;i&&i.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:237}],59:[function(e,t,i){"use strict";var n=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function r(){}t.exports=function e(t,i,o){if("function"==typeof i)return e(t,null,i);i||(i={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.apply(this,n)}}}(o||r);var s=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||l()},d=t._writableState&&t._writableState.finished,l=function(){a=!1,d=!0,s||o.call(t)},u=t._readableState&&t._readableState.endEmitted,h=function(){s=!1,u=!0,a||o.call(t)},f=function(e){o.call(t,e)},p=function(){var e;return s&&!u?(t._readableState&&t._readableState.ended||(e=new n),o.call(t,e)):a&&!d?(t._writableState&&t._writableState.ended||(e=new n),o.call(t,e)):void 0},g=function(){t.req.on("finish",l)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(t)?a&&!t._writableState&&(t.on("end",c),t.on("close",c)):(t.on("complete",l),t.on("abort",p),t.req?g():t.on("request",g)),t.on("end",h),t.on("finish",l),!1!==i.error&&t.on("error",f),t.on("close",p),function(){t.removeListener("complete",l),t.removeListener("abort",p),t.removeListener("request",g),t.req&&t.req.removeListener("finish",l),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("end",h),t.removeListener("error",f),t.removeListener("close",p)}}},{"../../../errors":50}],60:[function(e,t,i){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],61:[function(e,t,i){"use strict";var n;var r=e("../../../errors").codes,o=r.ERR_MISSING_ARGS,s=r.ERR_STREAM_DESTROYED;function a(e){if(e)throw e}function c(e){e()}function d(e,t){return e.pipe(t)}t.exports=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var l,u=function(e){return e.length?"function"!=typeof e[e.length-1]?a:e.pop():a}(i);if(Array.isArray(i[0])&&(i=i[0]),i.length<2)throw new o("streams");var h=i.map((function(t,r){var o=r<i.length-1;return function(t,i,r,o){o=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(o);var a=!1;t.on("close",(function(){a=!0})),void 0===n&&(n=e("./end-of-stream")),n(t,{readable:i,writable:r},(function(e){if(e)return o(e);a=!0,o()}));var c=!1;return function(e){if(!a&&!c)return c=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new s("pipe"))}}(t,o,r>0,(function(e){l||(l=e),e&&h.forEach(c),o||(h.forEach(c),u(l))}))}));return i.reduce(d)}},{"../../../errors":50,"./end-of-stream":59}],62:[function(e,t,i){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,i,r){var o=function(e,t,i){return null!=e.highWaterMark?e.highWaterMark:t?e[i]:null}(t,r,i);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(r?i:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}}},{"../../../errors":50}],63:[function(e,t,i){t.exports=e("events").EventEmitter},{events:105}],64:[function(e,t,i){(i=t.exports=e("./lib/_stream_readable.js")).Stream=i,i.Readable=i,i.Writable=e("./lib/_stream_writable.js"),i.Duplex=e("./lib/_stream_duplex.js"),i.Transform=e("./lib/_stream_transform.js"),i.PassThrough=e("./lib/_stream_passthrough.js"),i.finished=e("./lib/internal/streams/end-of-stream.js"),i.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":51,"./lib/_stream_passthrough.js":52,"./lib/_stream_readable.js":53,"./lib/_stream_transform.js":54,"./lib/_stream_writable.js":55,"./lib/internal/streams/end-of-stream.js":59,"./lib/internal/streams/pipeline.js":61}],65:[function(e,t,i){const n=e("base-x");t.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},{"base-x":66}],66:[function(e,t,i){"use strict";t.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var n=0;n<e.length;n++){var r=e.charAt(n),o=r.charCodeAt(0);if(255!==t[o])throw new TypeError(r+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),d=Math.log(256)/Math.log(s);function l(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;for(var i=0,n=0,r=0;e[i]===a;)n++,i++;for(var o=(e.length-i)*c+1>>>0,d=new Uint8Array(o);e[i];){var l=t[e.charCodeAt(i)];if(255===l)return;for(var u=0,h=o-1;(0!==l||u<r)&&-1!==h;h--,u++)l+=s*d[h]>>>0,d[h]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,i++}for(var f=o-r;f!==o&&0===d[f];)f++;for(var p=new Uint8Array(n+(o-f)),g=n;f!==o;)p[g++]=d[f++];return p}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,n=0,r=0,o=t.length;r!==o&&0===t[r];)r++,i++;for(var c=(o-r)*d+1>>>0,l=new Uint8Array(c);r!==o;){for(var u=t[r],h=0,f=c-1;(0!==u||h<n)&&-1!==f;f--,h++)u+=256*l[f]>>>0,l[f]=u%s>>>0,u=u/s>>>0;if(0!==u)throw new Error("Non-zero carry");n=h,r++}for(var p=c-n;p!==c&&0===l[p];)p++;for(var g=a.repeat(i);p<c;++p)g+=e.charAt(l[p]);return g},decodeUnsafe:l,decode:function(e){var t=l(e);if(t)return t;throw new Error("Non-base"+s+" character")}}}},{}],67:[function(e,t,i){(function(e){(function(){t.exports=function(t,i){for(var n=Math.min(t.length,i.length),r=new e(n),o=0;o<n;++o)r[o]=t[o]^i[o];return r}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:68}],68:[function(e,t,i){(function(t){(function(){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <https://feross.org> + * @license MIT + */ +"use strict";var t=e("base64-js"),n=e("ieee754");i.Buffer=s,i.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},i.INSPECT_MAX_BYTES=50;var r=2147483647;function o(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return a(e,t,i)}function a(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|h(e,t),n=o(i),r=n.write(e,t);r!==i&&(n=n.slice(0,r));return n}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');var n;n=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);return n.__proto__=s.prototype,n}(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,i);var r=function(e){if(s.isBuffer(e)){var t=0|u(e.length),i=o(t);return 0===i.length||e.copy(i,0,0,t),i}if(void 0!==e.length)return"number"!=typeof e.length||K(e.length)?o(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return c(e),o(e<0?0:0|u(e))}function l(e){for(var t=e.length<0?0:0|u(e.length),i=o(t),n=0;n<t;n+=1)i[n]=255&e[n];return i}function u(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===i)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return N(e).length;default:if(r)return n?-1:B(e).length;t=(""+t).toLowerCase(),r=!0}}function f(e,t,i){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,i);case"utf8":case"utf-8":return T(this,t,i);case"ascii":return R(this,t,i);case"latin1":case"binary":return M(this,t,i);case"base64":return w(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,i);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function p(e,t,i){var n=e[t];e[t]=e[i],e[i]=n}function g(e,t,i,n,r){if(0===e.length)return-1;if("string"==typeof i?(n=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),K(i=+i)&&(i=r?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(r)return-1;i=e.length-1}else if(i<0){if(!r)return-1;i=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:v(e,t,i,n,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):v(e,[t],i,n,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,i,n,r){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,i/=2}function d(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(o=i;o<a;o++)if(d(e,o)===d(t,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===c)return l*s}else-1!==l&&(o-=o-l),l=-1}else for(i+c>a&&(i=a-c),o=i;o>=0;o--){for(var u=!0,h=0;h<c;h++)if(d(e,o+h)!==d(t,h)){u=!1;break}if(u)return o}return-1}function m(e,t,i,n){i=Number(i)||0;var r=e.length-i;n?(n=Number(n))>r&&(n=r):n=r;var o=t.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var a=parseInt(t.substr(2*s,2),16);if(K(a))return s;e[i+s]=a}return s}function y(e,t,i,n){return j(B(t,e.length-i),e,i,n)}function b(e,t,i,n){return j(function(e){for(var t=[],i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,n)}function S(e,t,i,n){return b(e,t,i,n)}function _(e,t,i,n){return j(N(t),e,i,n)}function E(e,t,i,n){return j(function(e,t){for(var i,n,r,o=[],s=0;s<e.length&&!((t-=2)<0);++s)n=(i=e.charCodeAt(s))>>8,r=i%256,o.push(r),o.push(n);return o}(t,e.length-i),e,i,n)}function w(e,i,n){return 0===i&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(i,n))}function T(e,t,i){i=Math.min(e.length,i);for(var n=[],r=t;r<i;){var o,s,a,c,d=e[r],l=null,u=d>239?4:d>223?3:d>191?2:1;if(r+u<=i)switch(u){case 1:d<128&&(l=d);break;case 2:128==(192&(o=e[r+1]))&&(c=(31&d)<<6|63&o)>127&&(l=c);break;case 3:o=e[r+1],s=e[r+2],128==(192&o)&&128==(192&s)&&(c=(15&d)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[r+1],s=e[r+2],a=e[r+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&d)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,u=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),r+=u}return function(e){var t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);var i="",n=0;for(;n<t;)i+=String.fromCharCode.apply(String,e.slice(n,n+=I));return i}(n)}i.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,i){return a(e,t,i)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,i){return function(e,t,i){return c(e),e<=0?o(e):void 0!==t?"string"==typeof i?o(e).fill(t,i):o(e).fill(t):o(e)}(e,t,i)},s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(F(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),F(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var i=e.length,n=t.length,r=0,o=Math.min(i,n);r<o;++r)if(e[r]!==t[r]){i=e[r],n=t[r];break}return i<n?-1:n<i?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var n=s.allocUnsafe(t),r=0;for(i=0;i<e.length;++i){var o=e[i];if(F(o,Uint8Array)&&(o=s.from(o)),!s.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(n,r),r+=o.length}return n},s.byteLength=h,s.prototype._isBuffer=!0,s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):f.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=i.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},s.prototype.compare=function(e,t,i,n,r){if(F(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===r&&(r=this.length),t<0||i>e.length||n<0||r>this.length)throw new RangeError("out of range index");if(n>=r&&t>=i)return 0;if(n>=r)return-1;if(t>=i)return 1;if(this===e)return 0;for(var o=(r>>>=0)-(n>>>=0),a=(i>>>=0)-(t>>>=0),c=Math.min(o,a),d=this.slice(n,r),l=e.slice(t,i),u=0;u<c;++u)if(d[u]!==l[u]){o=d[u],a=l[u];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,i){return-1!==this.indexOf(e,t,i)},s.prototype.indexOf=function(e,t,i){return g(this,e,t,i,!0)},s.prototype.lastIndexOf=function(e,t,i){return g(this,e,t,i,!1)},s.prototype.write=function(e,t,i,n){if(void 0===t)n="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)n=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,i);case"utf8":case"utf-8":return y(this,e,t,i);case"ascii":return b(this,e,t,i);case"latin1":case"binary":return S(this,e,t,i);case"base64":return _(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,i);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function R(e,t,i){var n="";i=Math.min(e.length,i);for(var r=t;r<i;++r)n+=String.fromCharCode(127&e[r]);return n}function M(e,t,i){var n="";i=Math.min(e.length,i);for(var r=t;r<i;++r)n+=String.fromCharCode(e[r]);return n}function k(e,t,i){var n=e.length;(!t||t<0)&&(t=0),(!i||i<0||i>n)&&(i=n);for(var r="",o=t;o<i;++o)r+=U(e[o]);return r}function C(e,t,i){for(var n=e.slice(t,i),r="",o=0;o<n.length;o+=2)r+=String.fromCharCode(n[o]+256*n[o+1]);return r}function O(e,t,i){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>i)throw new RangeError("Trying to access beyond buffer length")}function A(e,t,i,n,r,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<o)throw new RangeError('"value" argument is out of bounds');if(i+n>e.length)throw new RangeError("Index out of range")}function P(e,t,i,n,r,o){if(i+n>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function D(e,t,i,r,o){return t=+t,i>>>=0,o||P(e,0,i,4),n.write(e,t,i,r,23,4),i+4}function x(e,t,i,r,o){return t=+t,i>>>=0,o||P(e,0,i,8),n.write(e,t,i,r,52,8),i+8}s.prototype.slice=function(e,t){var i=this.length;(e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t<e&&(t=e);var n=this.subarray(e,t);return n.__proto__=s.prototype,n},s.prototype.readUIntLE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e],r=1,o=0;++o<t&&(r*=256);)n+=this[e+o]*r;return n},s.prototype.readUIntBE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e+--t],r=1;t>0&&(r*=256);)n+=this[e+--t]*r;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e],r=1,o=0;++o<t&&(r*=256);)n+=this[e+o]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=t,r=1,o=this[e+--n];n>0&&(r*=256);)o+=this[e+--n]*r;return o>=(r*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,i,n){(e=+e,t>>>=0,i>>>=0,n)||A(this,e,t,i,Math.pow(2,8*i)-1,0);var r=1,o=0;for(this[t]=255&e;++o<i&&(r*=256);)this[t+o]=e/r&255;return t+i},s.prototype.writeUIntBE=function(e,t,i,n){(e=+e,t>>>=0,i>>>=0,n)||A(this,e,t,i,Math.pow(2,8*i)-1,0);var r=i-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+i},s.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,i,n){if(e=+e,t>>>=0,!n){var r=Math.pow(2,8*i-1);A(this,e,t,i,r-1,-r)}var o=0,s=1,a=0;for(this[t]=255&e;++o<i&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+i},s.prototype.writeIntBE=function(e,t,i,n){if(e=+e,t>>>=0,!n){var r=Math.pow(2,8*i-1);A(this,e,t,i,r-1,-r)}var o=i-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+i},s.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,i){return D(this,e,t,!0,i)},s.prototype.writeFloatBE=function(e,t,i){return D(this,e,t,!1,i)},s.prototype.writeDoubleLE=function(e,t,i){return x(this,e,t,!0,i)},s.prototype.writeDoubleBE=function(e,t,i){return x(this,e,t,!1,i)},s.prototype.copy=function(e,t,i,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-i&&(n=e.length-t+i);var r=n-i;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,i,n);else if(this===e&&i<t&&t<n)for(var o=r-1;o>=0;--o)e[o+t]=this[o+i];else Uint8Array.prototype.set.call(e,this.subarray(i,n),t);return r},s.prototype.fill=function(e,t,i,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var r=e.charCodeAt(0);("utf8"===n&&r<128||"latin1"===n)&&(e=r)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;var o;if(t>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(o=t;o<i;++o)this[o]=e;else{var a=s.isBuffer(e)?e:s.from(e,n),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<i-t;++o)this[o+t]=a[o%c]}return this};var L=/[^+/0-9A-Za-z-_]/g;function U(e){return e<16?"0"+e.toString(16):e.toString(16)}function B(e,t){var i;t=t||1/0;for(var n=e.length,r=null,o=[],s=0;s<n;++s){if((i=e.charCodeAt(s))>55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&o.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;o.push(i)}else if(i<2048){if((t-=2)<0)break;o.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;o.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return o}function N(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,i,n){for(var r=0;r<n&&!(r+i>=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function K(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":17,buffer:68,ieee754:145}],69:[function(e,t,i){"use strict";var n=e("get-intrinsic"),r=e("./"),o=r(n("String.prototype.indexOf"));t.exports=function(e,t){var i=n(e,!!t);return"function"==typeof i&&o(e,".prototype.")>-1?r(i):i}},{"./":70,"get-intrinsic":110}],70:[function(e,t,i){"use strict";var n=e("function-bind"),r=e("get-intrinsic"),o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||n.call(s,o),c=r("%Object.getOwnPropertyDescriptor%",!0),d=r("%Object.defineProperty%",!0),l=r("%Math.max%");if(d)try{d({},"a",{value:1})}catch(e){d=null}t.exports=function(e){var t=a(n,s,arguments);c&&d&&(c(t,"length").configurable&&d(t,"length",{value:1+l(0,e.length-(arguments.length-1))}));return t};var u=function(){return a(n,o,arguments)};d?d(t.exports,"apply",{value:u}):t.exports.apply=u},{"function-bind":109,"get-intrinsic":110}],71:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("stream").Transform,o=e("string_decoder").StringDecoder;function s(e){r.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(s,r),s.prototype.update=function(e,t,i){"string"==typeof e&&(e=n.from(e,t));var r=this._update(e);return this.hashMode?this:(i&&(r=this._toString(r,i)),r)},s.prototype.setAutoPadding=function(){},s.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},s.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},s.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},s.prototype._transform=function(e,t,i){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{i(n)}},s.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},s.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},s.prototype._toString=function(e,t,i){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return i&&(n+=this._decoder.end()),n},t.exports=s},{inherits:146,"safe-buffer":250,stream:264,string_decoder:279}],72:[function(e,t,i){ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +"use strict";var n=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s=/\\([\u000b\u0020-\u00ff])/g,a=/([\\"])/g,c=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function d(e){var t=String(e);if(o.test(t))return t;if(t.length>0&&!r.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(a,"\\$1")+'"'}function l(e){this.parameters=Object.create(null),this.type=e}i.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,i=e.type;if(!i||!c.test(i))throw new TypeError("invalid type");var n=i;if(t&&"object"==typeof t)for(var r,s=Object.keys(t).sort(),a=0;a<s.length;a++){if(r=s[a],!o.test(r))throw new TypeError("invalid parameter name");n+="; "+r+"="+d(t[r])}return n},i.parse=function(e){if(!e)throw new TypeError("argument string is required");var t="object"==typeof e?function(e){var t;"function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]);if("string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(e):e;if("string"!=typeof t)throw new TypeError("argument string is required to be a string");var i=t.indexOf(";"),r=-1!==i?t.slice(0,i).trim():t.trim();if(!c.test(r))throw new TypeError("invalid media type");var o=new l(r.toLowerCase());if(-1!==i){var a,d,u;for(n.lastIndex=i;d=n.exec(t);){if(d.index!==i)throw new TypeError("invalid parameter format");i+=d[0].length,a=d[1].toLowerCase(),34===(u=d[2]).charCodeAt(0)&&-1!==(u=u.slice(1,-1)).indexOf("\\")&&(u=u.replace(s,"$1")),o.parameters[a]=u}if(i!==t.length)throw new TypeError("invalid parameter format")}return o}},{}],73:[function(e,t,i){(function(i){(function(){var n=e("elliptic"),r=e("bn.js");t.exports=function(e){return new s(e)};var o={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};function s(e){this.curveType=o[e],this.curveType||(this.curveType={name:e}),this.curve=new n.ec(this.curveType.name),this.keys=void 0}function a(e,t,n){Array.isArray(e)||(e=e.toArray());var r=new i(e);if(n&&r.length<n){var o=new i(n-r.length);o.fill(0),r=i.concat([o,r])}return t?r.toString(t):r}o.p224=o.secp224r1,o.p256=o.secp256r1=o.prime256v1,o.p192=o.secp192r1=o.prime192v1,o.p384=o.secp384r1,o.p521=o.secp521r1,s.prototype.generateKeys=function(e,t){return this.keys=this.curve.genKeyPair(),this.getPublicKey(e,t)},s.prototype.computeSecret=function(e,t,n){return t=t||"utf8",i.isBuffer(e)||(e=new i(e,t)),a(this.curve.keyFromPublic(e).getPublic().mul(this.keys.getPrivate()).getX(),n,this.curveType.byteLength)},s.prototype.getPublicKey=function(e,t){var i=this.keys.getPublic("compressed"===t,!0);return"hybrid"===t&&(i[i.length-1]%2?i[0]=7:i[0]=6),a(i,e)},s.prototype.getPrivateKey=function(e){return a(this.keys.getPrivate(),e)},s.prototype.setPublicKey=function(e,t){return t=t||"utf8",i.isBuffer(e)||(e=new i(e,t)),this.keys._importPublic(e),this},s.prototype.setPrivateKey=function(e,t){t=t||"utf8",i.isBuffer(e)||(e=new i(e,t));var n=new r(e);return n=n.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(n),this}}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":18,buffer:68,elliptic:89}],74:[function(e,t,i){"use strict";var n=e("inherits"),r=e("md5.js"),o=e("ripemd160"),s=e("sha.js"),a=e("cipher-base");function c(e){a.call(this,"digest"),this._hash=e}n(c,a),c.prototype._update=function(e){this._hash.update(e)},c.prototype._final=function(){return this._hash.digest()},t.exports=function(e){return"md5"===(e=e.toLowerCase())?new r:"rmd160"===e||"ripemd160"===e?new o:new c(s(e))}},{"cipher-base":71,inherits:146,"md5.js":221,ripemd160:249,"sha.js":257}],75:[function(e,t,i){var n=e("md5.js");t.exports=function(e){return(new n).update(e).digest()}},{"md5.js":221}],76:[function(e,t,i){"use strict";var n=e("inherits"),r=e("./legacy"),o=e("cipher-base"),s=e("safe-buffer").Buffer,a=e("create-hash/md5"),c=e("ripemd160"),d=e("sha.js"),l=s.alloc(128);function u(e,t){o.call(this,"digest"),"string"==typeof t&&(t=s.from(t));var i="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>i)?t=("rmd160"===e?new c:d(e)).update(t).digest():t.length<i&&(t=s.concat([t,l],i));for(var n=this._ipad=s.allocUnsafe(i),r=this._opad=s.allocUnsafe(i),a=0;a<i;a++)n[a]=54^t[a],r[a]=92^t[a];this._hash="rmd160"===e?new c:d(e),this._hash.update(n)}n(u,o),u.prototype._update=function(e){this._hash.update(e)},u.prototype._final=function(){var e=this._hash.digest();return("rmd160"===this._alg?new c:d(this._alg)).update(this._opad).update(e).digest()},t.exports=function(e,t){return"rmd160"===(e=e.toLowerCase())||"ripemd160"===e?new u("rmd160",t):"md5"===e?new r(a,t):new u(e,t)}},{"./legacy":77,"cipher-base":71,"create-hash/md5":75,inherits:146,ripemd160:249,"safe-buffer":250,"sha.js":257}],77:[function(e,t,i){"use strict";var n=e("inherits"),r=e("safe-buffer").Buffer,o=e("cipher-base"),s=r.alloc(128),a=64;function c(e,t){o.call(this,"digest"),"string"==typeof t&&(t=r.from(t)),this._alg=e,this._key=t,t.length>a?t=e(t):t.length<a&&(t=r.concat([t,s],a));for(var i=this._ipad=r.allocUnsafe(a),n=this._opad=r.allocUnsafe(a),c=0;c<a;c++)i[c]=54^t[c],n[c]=92^t[c];this._hash=[i]}n(c,o),c.prototype._update=function(e){this._hash.push(e)},c.prototype._final=function(){var e=this._alg(r.concat(this._hash));return this._alg(r.concat([this._opad,e]))},t.exports=c},{"cipher-base":71,inherits:146,"safe-buffer":250}],78:[function(e,t,i){"use strict";i.randomBytes=i.rng=i.pseudoRandomBytes=i.prng=e("randombytes"),i.createHash=i.Hash=e("create-hash"),i.createHmac=i.Hmac=e("create-hmac");var n=e("browserify-sign/algos"),r=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(r);i.getHashes=function(){return o};var s=e("pbkdf2");i.pbkdf2=s.pbkdf2,i.pbkdf2Sync=s.pbkdf2Sync;var a=e("browserify-cipher");i.Cipher=a.Cipher,i.createCipher=a.createCipher,i.Cipheriv=a.Cipheriv,i.createCipheriv=a.createCipheriv,i.Decipher=a.Decipher,i.createDecipher=a.createDecipher,i.Decipheriv=a.Decipheriv,i.createDecipheriv=a.createDecipheriv,i.getCiphers=a.getCiphers,i.listCiphers=a.listCiphers;var c=e("diffie-hellman");i.DiffieHellmanGroup=c.DiffieHellmanGroup,i.createDiffieHellmanGroup=c.createDiffieHellmanGroup,i.getDiffieHellman=c.getDiffieHellman,i.createDiffieHellman=c.createDiffieHellman,i.DiffieHellman=c.DiffieHellman;var d=e("browserify-sign");i.createSign=d.createSign,i.Sign=d.Sign,i.createVerify=d.createVerify,i.Verify=d.Verify,i.createECDH=e("create-ecdh");var l=e("public-encrypt");i.publicEncrypt=l.publicEncrypt,i.privateEncrypt=l.privateEncrypt,i.publicDecrypt=l.publicDecrypt,i.privateDecrypt=l.privateDecrypt;var u=e("randomfill");i.randomFill=u.randomFill,i.randomFillSync=u.randomFillSync,i.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},i.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}},{"browserify-cipher":38,"browserify-sign":46,"browserify-sign/algos":43,"create-ecdh":73,"create-hash":74,"create-hmac":76,"diffie-hellman":85,pbkdf2:231,"public-encrypt":238,randombytes:244,randomfill:245}],79:[function(e,t,i){"use strict";i.utils=e("./des/utils"),i.Cipher=e("./des/cipher"),i.DES=e("./des/des"),i.CBC=e("./des/cbc"),i.EDE=e("./des/ede")},{"./des/cbc":80,"./des/cipher":81,"./des/des":82,"./des/ede":83,"./des/utils":84}],80:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits"),o={};function s(e){n.equal(e.length,8,"Invalid IV length"),this.iv=new Array(8);for(var t=0;t<this.iv.length;t++)this.iv[t]=e[t]}i.instantiate=function(e){function t(t){e.call(this,t),this._cbcInit()}r(t,e);for(var i=Object.keys(o),n=0;n<i.length;n++){var s=i[n];t.prototype[s]=o[s]}return t.create=function(e){return new t(e)},t},o._cbcInit=function(){var e=new s(this.options.iv);this._cbcState=e},o._update=function(e,t,i,n){var r=this._cbcState,o=this.constructor.super_.prototype,s=r.iv;if("encrypt"===this.type){for(var a=0;a<this.blockSize;a++)s[a]^=e[t+a];o._update.call(this,s,0,i,n);for(a=0;a<this.blockSize;a++)s[a]=i[n+a]}else{o._update.call(this,e,t,i,n);for(a=0;a<this.blockSize;a++)i[n+a]^=s[a];for(a=0;a<this.blockSize;a++)s[a]=e[t+a]}}},{inherits:146,"minimalistic-assert":223}],81:[function(e,t,i){"use strict";var n=e("minimalistic-assert");function r(e){this.options=e,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0}t.exports=r,r.prototype._init=function(){},r.prototype.update=function(e){return 0===e.length?[]:"decrypt"===this.type?this._updateDecrypt(e):this._updateEncrypt(e)},r.prototype._buffer=function(e,t){for(var i=Math.min(this.buffer.length-this.bufferOff,e.length-t),n=0;n<i;n++)this.buffer[this.bufferOff+n]=e[t+n];return this.bufferOff+=i,i},r.prototype._flushBuffer=function(e,t){return this._update(this.buffer,0,e,t),this.bufferOff=0,this.blockSize},r.prototype._updateEncrypt=function(e){var t=0,i=0,n=(this.bufferOff+e.length)/this.blockSize|0,r=new Array(n*this.blockSize);0!==this.bufferOff&&(t+=this._buffer(e,t),this.bufferOff===this.buffer.length&&(i+=this._flushBuffer(r,i)));for(var o=e.length-(e.length-t)%this.blockSize;t<o;t+=this.blockSize)this._update(e,t,r,i),i+=this.blockSize;for(;t<e.length;t++,this.bufferOff++)this.buffer[this.bufferOff]=e[t];return r},r.prototype._updateDecrypt=function(e){for(var t=0,i=0,n=Math.ceil((this.bufferOff+e.length)/this.blockSize)-1,r=new Array(n*this.blockSize);n>0;n--)t+=this._buffer(e,t),i+=this._flushBuffer(r,i);return t+=this._buffer(e,t),r},r.prototype.final=function(e){var t,i;return e&&(t=this.update(e)),i="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(i):i},r.prototype._pad=function(e,t){if(0===t)return!1;for(;t<e.length;)e[t++]=0;return!0},r.prototype._finalEncrypt=function(){if(!this._pad(this.buffer,this.bufferOff))return[];var e=new Array(this.blockSize);return this._update(this.buffer,0,e,0),e},r.prototype._unpad=function(e){return e},r.prototype._finalDecrypt=function(){n.equal(this.bufferOff,this.blockSize,"Not enough data to decrypt");var e=new Array(this.blockSize);return this._flushBuffer(e,0),this._unpad(e)}},{"minimalistic-assert":223}],82:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits"),o=e("./utils"),s=e("./cipher");function a(){this.tmp=new Array(2),this.keys=null}function c(e){s.call(this,e);var t=new a;this._desState=t,this.deriveKeys(t,e.key)}r(c,s),t.exports=c,c.create=function(e){return new c(e)};var d=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];c.prototype.deriveKeys=function(e,t){e.keys=new Array(32),n.equal(t.length,this.blockSize,"Invalid key length");var i=o.readUInt32BE(t,0),r=o.readUInt32BE(t,4);o.pc1(i,r,e.tmp,0),i=e.tmp[0],r=e.tmp[1];for(var s=0;s<e.keys.length;s+=2){var a=d[s>>>1];i=o.r28shl(i,a),r=o.r28shl(r,a),o.pc2(i,r,e.keys,s)}},c.prototype._update=function(e,t,i,n){var r=this._desState,s=o.readUInt32BE(e,t),a=o.readUInt32BE(e,t+4);o.ip(s,a,r.tmp,0),s=r.tmp[0],a=r.tmp[1],"encrypt"===this.type?this._encrypt(r,s,a,r.tmp,0):this._decrypt(r,s,a,r.tmp,0),s=r.tmp[0],a=r.tmp[1],o.writeUInt32BE(i,s,n),o.writeUInt32BE(i,a,n+4)},c.prototype._pad=function(e,t){for(var i=e.length-t,n=t;n<e.length;n++)e[n]=i;return!0},c.prototype._unpad=function(e){for(var t=e[e.length-1],i=e.length-t;i<e.length;i++)n.equal(e[i],t);return e.slice(0,e.length-t)},c.prototype._encrypt=function(e,t,i,n,r){for(var s=t,a=i,c=0;c<e.keys.length;c+=2){var d=e.keys[c],l=e.keys[c+1];o.expand(a,e.tmp,0),d^=e.tmp[0],l^=e.tmp[1];var u=o.substitute(d,l),h=a;a=(s^o.permute(u))>>>0,s=h}o.rip(a,s,n,r)},c.prototype._decrypt=function(e,t,i,n,r){for(var s=i,a=t,c=e.keys.length-2;c>=0;c-=2){var d=e.keys[c],l=e.keys[c+1];o.expand(s,e.tmp,0),d^=e.tmp[0],l^=e.tmp[1];var u=o.substitute(d,l),h=s;s=(a^o.permute(u))>>>0,a=h}o.rip(s,a,n,r)}},{"./cipher":81,"./utils":84,inherits:146,"minimalistic-assert":223}],83:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits"),o=e("./cipher"),s=e("./des");function a(e,t){n.equal(t.length,24,"Invalid key length");var i=t.slice(0,8),r=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i})]}function c(e){o.call(this,e);var t=new a(this.type,this.options.key);this._edeState=t}r(c,o),t.exports=c,c.create=function(e){return new c(e)},c.prototype._update=function(e,t,i,n){var r=this._edeState;r.ciphers[0]._update(e,t,i,n),r.ciphers[1]._update(i,n,i,n),r.ciphers[2]._update(i,n,i,n)},c.prototype._pad=s.prototype._pad,c.prototype._unpad=s.prototype._unpad},{"./cipher":81,"./des":82,inherits:146,"minimalistic-assert":223}],84:[function(e,t,i){"use strict";i.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},i.writeUInt32BE=function(e,t,i){e[0+i]=t>>>24,e[1+i]=t>>>16&255,e[2+i]=t>>>8&255,e[3+i]=255&t},i.ip=function(e,t,i,n){for(var r=0,o=0,s=6;s>=0;s-=2){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>>a+s&1}for(s=6;s>=0;s-=2){for(a=1;a<=25;a+=8)o<<=1,o|=t>>>a+s&1;for(a=1;a<=25;a+=8)o<<=1,o|=e>>>a+s&1}i[n+0]=r>>>0,i[n+1]=o>>>0},i.rip=function(e,t,i,n){for(var r=0,o=0,s=0;s<4;s++)for(var a=24;a>=0;a-=8)r<<=1,r|=t>>>a+s&1,r<<=1,r|=e>>>a+s&1;for(s=4;s<8;s++)for(a=24;a>=0;a-=8)o<<=1,o|=t>>>a+s&1,o<<=1,o|=e>>>a+s&1;i[n+0]=r>>>0,i[n+1]=o>>>0},i.pc1=function(e,t,i,n){for(var r=0,o=0,s=7;s>=5;s--){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>a+s&1}for(a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(s=1;s<=3;s++){for(a=0;a<=24;a+=8)o<<=1,o|=t>>a+s&1;for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1}for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1;i[n+0]=r>>>0,i[n+1]=o>>>0},i.r28shl=function(e,t){return e<<t&268435455|e>>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];i.pc2=function(e,t,i,r){for(var o=0,s=0,a=n.length>>>1,c=0;c<a;c++)o<<=1,o|=e>>>n[c]&1;for(c=a;c<n.length;c++)s<<=1,s|=t>>>n[c]&1;i[r+0]=o>>>0,i[r+1]=s>>>0},i.expand=function(e,t,i){var n=0,r=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)r|=e>>>o&63,r<<=6;r|=(31&e)<<1|e>>>31,t[i+0]=n>>>0,t[i+1]=r>>>0};var r=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];i.substitute=function(e,t){for(var i=0,n=0;n<4;n++){i<<=4,i|=r[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){i<<=4,i|=r[256+64*n+(t>>>18-6*n&63)]}return i>>>0};var o=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];i.permute=function(e){for(var t=0,i=0;i<o.length;i++)t<<=1,t|=e>>>o[i]&1;return t>>>0},i.padSplit=function(e,t,i){for(var n=e.toString(2);n.length<t;)n="0"+n;for(var r=[],o=0;o<t;o+=i)r.push(n.slice(o,o+i));return r.join(" ")}},{}],85:[function(e,t,i){(function(t){(function(){var n=e("./lib/generatePrime"),r=e("./lib/primes.json"),o=e("./lib/dh");var s={binary:!0,hex:!0,base64:!0};i.DiffieHellmanGroup=i.createDiffieHellmanGroup=i.getDiffieHellman=function(e){var i=new t(r[e].prime,"hex"),n=new t(r[e].gen,"hex");return new o(i,n)},i.createDiffieHellman=i.DiffieHellman=function e(i,r,a,c){return t.isBuffer(r)||void 0===s[r]?e(i,"binary",r,a):(r=r||"binary",c=c||"binary",a=a||new t([2]),t.isBuffer(a)||(a=new t(a,c)),"number"==typeof i?new o(n(i,a),a,!0):(t.isBuffer(i)||(i=new t(i,r)),new o(i,a,!0)))}}).call(this)}).call(this,e("buffer").Buffer)},{"./lib/dh":86,"./lib/generatePrime":87,"./lib/primes.json":88,buffer:68}],86:[function(e,t,i){(function(i){(function(){var n=e("bn.js"),r=new(e("miller-rabin")),o=new n(24),s=new n(11),a=new n(10),c=new n(3),d=new n(7),l=e("./generatePrime"),u=e("randombytes");function h(e,t){return t=t||"utf8",i.isBuffer(e)||(e=new i(e,t)),this._pub=new n(e),this}function f(e,t){return t=t||"utf8",i.isBuffer(e)||(e=new i(e,t)),this._priv=new n(e),this}t.exports=g;var p={};function g(e,t,i){this.setGenerator(t),this.__prime=new n(e),this._prime=n.mont(this.__prime),this._primeLen=e.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,i?(this.setPublicKey=h,this.setPrivateKey=f):this._primeCode=8}function v(e,t){var n=new i(e.toArray());return t?n.toString(t):n}Object.defineProperty(g.prototype,"verifyError",{enumerable:!0,get:function(){return"number"!=typeof this._primeCode&&(this._primeCode=function(e,t){var i=t.toString("hex"),n=[i,e.toString(16)].join("_");if(n in p)return p[n];var u,h=0;if(e.isEven()||!l.simpleSieve||!l.fermatTest(e)||!r.test(e))return h+=1,h+="02"===i||"05"===i?8:4,p[n]=h,h;switch(r.test(e.shrn(1))||(h+=2),i){case"02":e.mod(o).cmp(s)&&(h+=8);break;case"05":(u=e.mod(a)).cmp(c)&&u.cmp(d)&&(h+=8);break;default:h+=4}return p[n]=h,h}(this.__prime,this.__gen)),this._primeCode}}),g.prototype.generateKeys=function(){return this._priv||(this._priv=new n(u(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},g.prototype.computeSecret=function(e){var t=(e=(e=new n(e)).toRed(this._prime)).redPow(this._priv).fromRed(),r=new i(t.toArray()),o=this.getPrime();if(r.length<o.length){var s=new i(o.length-r.length);s.fill(0),r=i.concat([s,r])}return r},g.prototype.getPublicKey=function(e){return v(this._pub,e)},g.prototype.getPrivateKey=function(e){return v(this._priv,e)},g.prototype.getPrime=function(e){return v(this.__prime,e)},g.prototype.getGenerator=function(e){return v(this._gen,e)},g.prototype.setGenerator=function(e,t){return t=t||"utf8",i.isBuffer(e)||(e=new i(e,t)),this.__gen=e,this._gen=new n(e),this}}).call(this)}).call(this,e("buffer").Buffer)},{"./generatePrime":87,"bn.js":18,buffer:68,"miller-rabin":222,randombytes:244}],87:[function(e,t,i){var n=e("randombytes");t.exports=y,y.simpleSieve=v,y.fermatTest=m;var r=e("bn.js"),o=new r(24),s=new(e("miller-rabin")),a=new r(1),c=new r(2),d=new r(5),l=(new r(16),new r(8),new r(10)),u=new r(3),h=(new r(7),new r(11)),f=new r(4),p=(new r(12),null);function g(){if(null!==p)return p;var e=[];e[0]=2;for(var t=1,i=3;i<1048576;i+=2){for(var n=Math.ceil(Math.sqrt(i)),r=0;r<t&&e[r]<=n&&i%e[r]!=0;r++);t!==r&&e[r]<=n||(e[t++]=i)}return p=e,e}function v(e){for(var t=g(),i=0;i<t.length;i++)if(0===e.modn(t[i]))return 0===e.cmpn(t[i]);return!0}function m(e){var t=r.mont(e);return 0===c.toRed(t).redPow(e.subn(1)).fromRed().cmpn(1)}function y(e,t){if(e<16)return new r(2===t||5===t?[140,123]:[140,39]);var i,p;for(t=new r(t);;){for(i=new r(n(Math.ceil(e/8)));i.bitLength()>e;)i.ishrn(1);if(i.isEven()&&i.iadd(a),i.testn(1)||i.iadd(c),t.cmp(c)){if(!t.cmp(d))for(;i.mod(l).cmp(u);)i.iadd(f)}else for(;i.mod(o).cmp(h);)i.iadd(f);if(v(p=i.shrn(1))&&v(i)&&m(p)&&m(i)&&s.test(p)&&s.test(i))return i}}},{"bn.js":18,"miller-rabin":222,randombytes:244}],88:[function(e,t,i){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],89:[function(e,t,i){"use strict";var n=i;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":104,"./elliptic/curve":92,"./elliptic/curves":95,"./elliptic/ec":96,"./elliptic/eddsa":99,"./elliptic/utils":103,brorand:19}],90:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils"),o=r.getNAF,s=r.getJSF,a=r.assert;function c(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var i=this.n&&this.p.div(this.n);!i||i.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function d(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=c,c.prototype.point=function(){throw new Error("Not implemented")},c.prototype.validate=function(){throw new Error("Not implemented")},c.prototype._fixedNafMul=function(e,t){a(e.precomputed);var i=e._getDoubles(),n=o(t,1,this._bitLength),r=(1<<i.step+1)-(i.step%2==0?2:1);r/=3;var s,c,d=[];for(s=0;s<n.length;s+=i.step){c=0;for(var l=s+i.step-1;l>=s;l--)c=(c<<1)+n[l];d.push(c)}for(var u=this.jpoint(null,null,null),h=this.jpoint(null,null,null),f=r;f>0;f--){for(s=0;s<d.length;s++)(c=d[s])===f?h=h.mixedAdd(i.points[s]):c===-f&&(h=h.mixedAdd(i.points[s].neg()));u=u.add(h)}return u.toP()},c.prototype._wnafMul=function(e,t){var i=4,n=e._getNAFPoints(i);i=n.wnd;for(var r=n.points,s=o(t,i,this._bitLength),c=this.jpoint(null,null,null),d=s.length-1;d>=0;d--){for(var l=0;d>=0&&0===s[d];d--)l++;if(d>=0&&l++,c=c.dblp(l),d<0)break;var u=s[d];a(0!==u),c="affine"===e.type?u>0?c.mixedAdd(r[u-1>>1]):c.mixedAdd(r[-u-1>>1].neg()):u>0?c.add(r[u-1>>1]):c.add(r[-u-1>>1].neg())}return"affine"===e.type?c.toP():c},c.prototype._wnafMulAdd=function(e,t,i,n,r){var a,c,d,l=this._wnafT1,u=this._wnafT2,h=this._wnafT3,f=0;for(a=0;a<n;a++){var p=(d=t[a])._getNAFPoints(e);l[a]=p.wnd,u[a]=p.points}for(a=n-1;a>=1;a-=2){var g=a-1,v=a;if(1===l[g]&&1===l[v]){var m=[t[g],null,null,t[v]];0===t[g].y.cmp(t[v].y)?(m[1]=t[g].add(t[v]),m[2]=t[g].toJ().mixedAdd(t[v].neg())):0===t[g].y.cmp(t[v].y.redNeg())?(m[1]=t[g].toJ().mixedAdd(t[v]),m[2]=t[g].add(t[v].neg())):(m[1]=t[g].toJ().mixedAdd(t[v]),m[2]=t[g].toJ().mixedAdd(t[v].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],b=s(i[g],i[v]);for(f=Math.max(b[0].length,f),h[g]=new Array(f),h[v]=new Array(f),c=0;c<f;c++){var S=0|b[0][c],_=0|b[1][c];h[g][c]=y[3*(S+1)+(_+1)],h[v][c]=0,u[g]=m}}else h[g]=o(i[g],l[g],this._bitLength),h[v]=o(i[v],l[v],this._bitLength),f=Math.max(h[g].length,f),f=Math.max(h[v].length,f)}var E=this.jpoint(null,null,null),w=this._wnafT4;for(a=f;a>=0;a--){for(var T=0;a>=0;){var I=!0;for(c=0;c<n;c++)w[c]=0|h[c][a],0!==w[c]&&(I=!1);if(!I)break;T++,a--}if(a>=0&&T++,E=E.dblp(T),a<0)break;for(c=0;c<n;c++){var R=w[c];0!==R&&(R>0?d=u[c][R-1>>1]:R<0&&(d=u[c][-R-1>>1].neg()),E="affine"===d.type?E.mixedAdd(d):E.add(d))}}for(a=0;a<n;a++)u[a]=null;return r?E:E.toP()},c.BasePoint=d,d.prototype.eq=function(){throw new Error("Not implemented")},d.prototype.validate=function(){return this.curve.validate(this)},c.prototype.decodePoint=function(e,t){e=r.toArray(e,t);var i=this.p.byteLength();if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==2*i)return 6===e[0]?a(e[e.length-1]%2==0):7===e[0]&&a(e[e.length-1]%2==1),this.point(e.slice(1,1+i),e.slice(1+i,1+2*i));if((2===e[0]||3===e[0])&&e.length-1===i)return this.pointFromX(e.slice(1,1+i),3===e[0]);throw new Error("Unknown point format")},d.prototype.encodeCompressed=function(e){return this.encode(e,!0)},d.prototype._encode=function(e){var t=this.curve.p.byteLength(),i=this.getX().toArray("be",t);return e?[this.getY().isEven()?2:3].concat(i):[4].concat(i,this.getY().toArray("be",t))},d.prototype.encode=function(e,t){return r.encode(this._encode(t),e)},d.prototype.precompute=function(e){if(this.precomputed)return this;var t={doubles:null,naf:null,beta:null};return t.naf=this._getNAFPoints(8),t.doubles=this._getDoubles(4,e),t.beta=this._getBeta(),this.precomputed=t,this},d.prototype._hasDoubles=function(e){if(!this.precomputed)return!1;var t=this.precomputed.doubles;return!!t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)},d.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,r=0;r<t;r+=e){for(var o=0;o<e;o++)n=n.dbl();i.push(n)}return{step:e,points:i}},d.prototype._getNAFPoints=function(e){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;for(var t=[this],i=(1<<e)-1,n=1===i?null:this.dbl(),r=1;r<i;r++)t[r]=t[r-1].add(n);return{wnd:e,points:t}},d.prototype._getBeta=function(){return null},d.prototype.dblp=function(e){for(var t=this,i=0;i<e;i++)t=t.dbl();return t}},{"../utils":103,"bn.js":18}],91:[function(e,t,i){"use strict";var n=e("../utils"),r=e("bn.js"),o=e("inherits"),s=e("./base"),a=n.assert;function c(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,s.call(this,"edwards",e),this.a=new r(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new r(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new r(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),a(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}function d(e,t,i,n,o){s.BasePoint.call(this,e,"projective"),null===t&&null===i&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new r(t,16),this.y=new r(i,16),this.z=n?new r(n,16):this.curve.one,this.t=o&&new r(o,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}o(c,s),t.exports=c,c.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},c.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},c.prototype.jpoint=function(e,t,i,n){return this.point(e,t,i,n)},c.prototype.pointFromX=function(e,t){(e=new r(e,16)).red||(e=e.toRed(this.red));var i=e.redSqr(),n=this.c2.redSub(this.a.redMul(i)),o=this.one.redSub(this.c2.redMul(this.d).redMul(i)),s=n.redMul(o.redInvm()),a=s.redSqrt();if(0!==a.redSqr().redSub(s).cmp(this.zero))throw new Error("invalid point");var c=a.fromRed().isOdd();return(t&&!c||!t&&c)&&(a=a.redNeg()),this.point(e,a)},c.prototype.pointFromY=function(e,t){(e=new r(e,16)).red||(e=e.toRed(this.red));var i=e.redSqr(),n=i.redSub(this.c2),o=i.redMul(this.d).redMul(this.c2).redSub(this.a),s=n.redMul(o.redInvm());if(0===s.cmp(this.zero)){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var a=s.redSqrt();if(0!==a.redSqr().redSub(s).cmp(this.zero))throw new Error("invalid point");return a.fromRed().isOdd()!==t&&(a=a.redNeg()),this.point(a,e)},c.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),i=e.y.redSqr(),n=t.redMul(this.a).redAdd(i),r=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(i)));return 0===n.cmp(r)},o(d,s.BasePoint),c.prototype.pointFromJSON=function(e){return d.fromJSON(this,e)},c.prototype.point=function(e,t,i,n){return new d(this,e,t,i,n)},d.fromJSON=function(e,t){return new d(e,t[0],t[1],t[2])},d.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"},d.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},d.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr();i=i.redIAdd(i);var n=this.curve._mulA(e),r=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),s=o.redSub(i),a=n.redSub(t),c=r.redMul(s),d=o.redMul(a),l=r.redMul(a),u=s.redMul(o);return this.curve.point(c,d,u,l)},d.prototype._projDbl=function(){var e,t,i,n,r,o,s=this.x.redAdd(this.y).redSqr(),a=this.x.redSqr(),c=this.y.redSqr();if(this.curve.twisted){var d=(n=this.curve._mulA(a)).redAdd(c);this.zOne?(e=s.redSub(a).redSub(c).redMul(d.redSub(this.curve.two)),t=d.redMul(n.redSub(c)),i=d.redSqr().redSub(d).redSub(d)):(r=this.z.redSqr(),o=d.redSub(r).redISub(r),e=s.redSub(a).redISub(c).redMul(o),t=d.redMul(n.redSub(c)),i=d.redMul(o))}else n=a.redAdd(c),r=this.curve._mulC(this.z).redSqr(),o=n.redSub(r).redSub(r),e=this.curve._mulC(s.redISub(n)).redMul(o),t=this.curve._mulC(n).redMul(a.redISub(c)),i=n.redMul(o);return this.curve.point(e,t,i)},d.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},d.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),i=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),r=this.z.redMul(e.z.redAdd(e.z)),o=i.redSub(t),s=r.redSub(n),a=r.redAdd(n),c=i.redAdd(t),d=o.redMul(s),l=a.redMul(c),u=o.redMul(c),h=s.redMul(a);return this.curve.point(d,l,h,u)},d.prototype._projAdd=function(e){var t,i,n=this.z.redMul(e.z),r=n.redSqr(),o=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(o).redMul(s),c=r.redSub(a),d=r.redAdd(a),l=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(s),u=n.redMul(c).redMul(l);return this.curve.twisted?(t=n.redMul(d).redMul(s.redSub(this.curve._mulA(o))),i=c.redMul(d)):(t=n.redMul(d).redMul(s.redSub(o)),i=this.curve._mulC(c).redMul(d)),this.curve.point(u,t,i)},d.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},d.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},d.prototype.mulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!1)},d.prototype.jmulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!0)},d.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},d.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},d.prototype.getX=function(){return this.normalize(),this.x.fromRed()},d.prototype.getY=function(){return this.normalize(),this.y.fromRed()},d.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},d.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var i=e.clone(),n=this.curve.redN.redMul(this.z);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}},d.prototype.toP=d.prototype.normalize,d.prototype.mixedAdd=d.prototype.add},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],92:[function(e,t,i){"use strict";var n=i;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":90,"./edwards":91,"./mont":93,"./short":94}],93:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("inherits"),o=e("./base"),s=e("../utils");function a(e){o.call(this,"mont",e),this.a=new n(e.a,16).toRed(this.red),this.b=new n(e.b,16).toRed(this.red),this.i4=new n(4).toRed(this.red).redInvm(),this.two=new n(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,i){o.BasePoint.call(this,e,"projective"),null===t&&null===i?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new n(t,16),this.z=new n(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}r(a,o),t.exports=a,a.prototype.validate=function(e){var t=e.normalize().x,i=t.redSqr(),n=i.redMul(t).redAdd(i.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},r(c,o.BasePoint),a.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},a.prototype.point=function(e,t){return new c(this,e,t)},a.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),i=e.redSub(t),n=e.redMul(t),r=i.redMul(t.redAdd(this.curve.a24.redMul(i)));return this.curve.point(n,r)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var i=this.x.redAdd(this.z),n=this.x.redSub(this.z),r=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(i),s=r.redMul(n),a=t.z.redMul(o.redAdd(s).redSqr()),c=t.x.redMul(o.redISub(s).redSqr());return this.curve.point(a,c)},c.prototype.mul=function(e){for(var t=e.clone(),i=this,n=this.curve.point(null,null),r=[];0!==t.cmpn(0);t.iushrn(1))r.push(t.andln(1));for(var o=r.length-1;o>=0;o--)0===r[o]?(i=i.diffAdd(n,this),n=n.dbl()):(n=i.diffAdd(n,this),i=i.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],94:[function(e,t,i){"use strict";var n=e("../utils"),r=e("bn.js"),o=e("inherits"),s=e("./base"),a=n.assert;function c(e){s.call(this,"short",e),this.a=new r(e.a,16).toRed(this.red),this.b=new r(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function d(e,t,i,n){s.BasePoint.call(this,e,"affine"),null===t&&null===i?(this.x=null,this.y=null,this.inf=!0):(this.x=new r(t,16),this.y=new r(i,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function l(e,t,i,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===i&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new r(0)):(this.x=new r(t,16),this.y=new r(i,16),this.z=new r(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}o(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,i;if(e.beta)t=new r(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)i=new r(e.lambda,16);else{var o=this._getEndoRoots(this.n);0===this.g.mul(o[0]).x.cmp(this.g.x.redMul(t))?i=o[0]:(i=o[1],a(0===this.g.mul(i).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:i,basis:e.basis?e.basis.map((function(e){return{a:new r(e.a,16),b:new r(e.b,16)}})):this._getEndoBasis(i)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:r.mont(e),i=new r(2).toRed(t).redInvm(),n=i.redNeg(),o=new r(3).toRed(t).redNeg().redSqrt().redMul(i);return[n.redAdd(o).fromRed(),n.redSub(o).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,i,n,o,s,a,c,d,l,u=this.n.ushrn(Math.floor(this.n.bitLength()/2)),h=e,f=this.n.clone(),p=new r(1),g=new r(0),v=new r(0),m=new r(1),y=0;0!==h.cmpn(0);){var b=f.div(h);d=f.sub(b.mul(h)),l=v.sub(b.mul(p));var S=m.sub(b.mul(g));if(!n&&d.cmp(u)<0)t=c.neg(),i=p,n=d.neg(),o=l;else if(n&&2==++y)break;c=d,f=h,h=d,v=p,p=l,m=g,g=S}s=d.neg(),a=l;var _=n.sqr().add(o.sqr());return s.sqr().add(a.sqr()).cmp(_)>=0&&(s=t,a=i),n.negative&&(n=n.neg(),o=o.neg()),s.negative&&(s=s.neg(),a=a.neg()),[{a:n,b:o},{a:s,b:a}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],r=n.b.mul(e).divRound(this.n),o=i.b.neg().mul(e).divRound(this.n),s=r.mul(i.a),a=o.mul(n.a),c=r.mul(i.b),d=o.mul(n.b);return{k1:e.sub(s).sub(a),k2:c.add(d).neg()}},c.prototype.pointFromX=function(e,t){(e=new r(e,16)).red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(0!==n.redSqr().redSub(i).cmp(this.zero))throw new Error("invalid point");var o=n.fromRed().isOdd();return(t&&!o||!t&&o)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),r=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===i.redSqr().redISub(r).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,r=this._endoWnafT2,o=0;o<e.length;o++){var s=this._endoSplit(t[o]),a=e[o],c=a._getBeta();s.k1.negative&&(s.k1.ineg(),a=a.neg(!0)),s.k2.negative&&(s.k2.ineg(),c=c.neg(!0)),n[2*o]=a,n[2*o+1]=c,r[2*o]=s.k1,r[2*o+1]=s.k2}for(var d=this._wnafMulAdd(1,n,r,2*o,i),l=0;l<2*o;l++)n[l]=null,r[l]=null;return d},o(d,s.BasePoint),c.prototype.point=function(e,t,i){return new d(this,e,t,i)},c.prototype.pointFromJSON=function(e,t){return d.fromJSON(this,e,t)},d.prototype._getBeta=function(){if(this.curve.endo){var e=this.precomputed;if(e&&e.beta)return e.beta;var t=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(e){var i=this.curve,n=function(e){return i.point(e.x.redMul(i.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:e.naf&&{wnd:e.naf.wnd,points:e.naf.points.map(n)},doubles:e.doubles&&{step:e.doubles.step,points:e.doubles.points.map(n)}}}return t}},d.prototype.toJSON=function(){return this.precomputed?[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]:[this.x,this.y]},d.fromJSON=function(e,t,i){"string"==typeof t&&(t=JSON.parse(t));var n=e.point(t[0],t[1],i);if(!t[2])return n;function r(t){return e.point(t[0],t[1],i)}var o=t[2];return n.precomputed={beta:null,doubles:o.doubles&&{step:o.doubles.step,points:[n].concat(o.doubles.points.map(r))},naf:o.naf&&{wnd:o.naf.wnd,points:[n].concat(o.naf.points.map(r))}},n},d.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"},d.prototype.isInfinity=function(){return this.inf},d.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},d.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),r=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),o=r.redSqr().redISub(this.x.redAdd(this.x)),s=r.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},d.prototype.getX=function(){return this.x.fromRed()},d.prototype.getY=function(){return this.y.fromRed()},d.prototype.mul=function(e){return e=new r(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},d.prototype.mulAdd=function(e,t,i){var n=[this,t],r=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,r):this.curve._wnafMulAdd(1,n,r,2)},d.prototype.jmulAdd=function(e,t,i){var n=[this,t],r=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,r,!0):this.curve._wnafMulAdd(1,n,r,2,!0)},d.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},d.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},d.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},o(l,s.BasePoint),c.prototype.jpoint=function(e,t,i){return new l(this,e,t,i)},l.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},l.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},l.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),r=e.x.redMul(i),o=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(i.redMul(this.z)),a=n.redSub(r),c=o.redSub(s);if(0===a.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var d=a.redSqr(),l=d.redMul(a),u=n.redMul(d),h=c.redSqr().redIAdd(l).redISub(u).redISub(u),f=c.redMul(u.redISub(h)).redISub(o.redMul(l)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(h,f,p)},l.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),r=this.y,o=e.y.redMul(t).redMul(this.z),s=i.redSub(n),a=r.redSub(o);if(0===s.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),d=c.redMul(s),l=i.redMul(c),u=a.redSqr().redIAdd(d).redISub(l).redISub(l),h=a.redMul(l.redISub(u)).redISub(r.redMul(d)),f=this.z.redMul(s);return this.curve.jpoint(u,h,f)},l.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t<e;t++)i=i.dbl();return i}var n=this.curve.a,r=this.curve.tinv,o=this.x,s=this.y,a=this.z,c=a.redSqr().redSqr(),d=s.redAdd(s);for(t=0;t<e;t++){var l=o.redSqr(),u=d.redSqr(),h=u.redSqr(),f=l.redAdd(l).redIAdd(l).redIAdd(n.redMul(c)),p=o.redMul(u),g=f.redSqr().redISub(p.redAdd(p)),v=p.redISub(g),m=f.redMul(v);m=m.redIAdd(m).redISub(h);var y=d.redMul(a);t+1<e&&(c=c.redMul(h)),o=g,a=y,d=m}return this.curve.jpoint(o,d.redMul(r),a)},l.prototype.dbl=function(){return this.isInfinity()?this:this.curve.zeroA?this._zeroDbl():this.curve.threeA?this._threeDbl():this._dbl()},l.prototype._zeroDbl=function(){var e,t,i;if(this.zOne){var n=this.x.redSqr(),r=this.y.redSqr(),o=r.redSqr(),s=this.x.redAdd(r).redSqr().redISub(n).redISub(o);s=s.redIAdd(s);var a=n.redAdd(n).redIAdd(n),c=a.redSqr().redISub(s).redISub(s),d=o.redIAdd(o);d=(d=d.redIAdd(d)).redIAdd(d),e=c,t=a.redMul(s.redISub(c)).redISub(d),i=this.y.redAdd(this.y)}else{var l=this.x.redSqr(),u=this.y.redSqr(),h=u.redSqr(),f=this.x.redAdd(u).redSqr().redISub(l).redISub(h);f=f.redIAdd(f);var p=l.redAdd(l).redIAdd(l),g=p.redSqr(),v=h.redIAdd(h);v=(v=v.redIAdd(v)).redIAdd(v),e=g.redISub(f).redISub(f),t=p.redMul(f.redISub(e)).redISub(v),i=(i=this.y.redMul(this.z)).redIAdd(i)}return this.curve.jpoint(e,t,i)},l.prototype._threeDbl=function(){var e,t,i;if(this.zOne){var n=this.x.redSqr(),r=this.y.redSqr(),o=r.redSqr(),s=this.x.redAdd(r).redSqr().redISub(n).redISub(o);s=s.redIAdd(s);var a=n.redAdd(n).redIAdd(n).redIAdd(this.curve.a),c=a.redSqr().redISub(s).redISub(s);e=c;var d=o.redIAdd(o);d=(d=d.redIAdd(d)).redIAdd(d),t=a.redMul(s.redISub(c)).redISub(d),i=this.y.redAdd(this.y)}else{var l=this.z.redSqr(),u=this.y.redSqr(),h=this.x.redMul(u),f=this.x.redSub(l).redMul(this.x.redAdd(l));f=f.redAdd(f).redIAdd(f);var p=h.redIAdd(h),g=(p=p.redIAdd(p)).redAdd(p);e=f.redSqr().redISub(g),i=this.y.redAdd(this.z).redSqr().redISub(u).redISub(l);var v=u.redSqr();v=(v=(v=v.redIAdd(v)).redIAdd(v)).redIAdd(v),t=f.redMul(p.redISub(e)).redISub(v)}return this.curve.jpoint(e,t,i)},l.prototype._dbl=function(){var e=this.curve.a,t=this.x,i=this.y,n=this.z,r=n.redSqr().redSqr(),o=t.redSqr(),s=i.redSqr(),a=o.redAdd(o).redIAdd(o).redIAdd(e.redMul(r)),c=t.redAdd(t),d=(c=c.redIAdd(c)).redMul(s),l=a.redSqr().redISub(d.redAdd(d)),u=d.redISub(l),h=s.redSqr();h=(h=(h=h.redIAdd(h)).redIAdd(h)).redIAdd(h);var f=a.redMul(u).redISub(h),p=i.redAdd(i).redMul(n);return this.curve.jpoint(l,f,p)},l.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr(),n=t.redSqr(),r=e.redAdd(e).redIAdd(e),o=r.redSqr(),s=this.x.redAdd(t).redSqr().redISub(e).redISub(n),a=(s=(s=(s=s.redIAdd(s)).redAdd(s).redIAdd(s)).redISub(o)).redSqr(),c=n.redIAdd(n);c=(c=(c=c.redIAdd(c)).redIAdd(c)).redIAdd(c);var d=r.redIAdd(s).redSqr().redISub(o).redISub(a).redISub(c),l=t.redMul(d);l=(l=l.redIAdd(l)).redIAdd(l);var u=this.x.redMul(a).redISub(l);u=(u=u.redIAdd(u)).redIAdd(u);var h=this.y.redMul(d.redMul(c.redISub(d)).redISub(s.redMul(a)));h=(h=(h=h.redIAdd(h)).redIAdd(h)).redIAdd(h);var f=this.z.redAdd(s).redSqr().redISub(i).redISub(a);return this.curve.jpoint(u,h,f)},l.prototype.mul=function(e,t){return e=new r(e,t),this.curve._wnafMul(this,e)},l.prototype.eq=function(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e)return!0;var t=this.z.redSqr(),i=e.z.redSqr();if(0!==this.x.redMul(i).redISub(e.x.redMul(t)).cmpn(0))return!1;var n=t.redMul(this.z),r=i.redMul(e.z);return 0===this.y.redMul(r).redISub(e.y.redMul(n)).cmpn(0)},l.prototype.eqXToP=function(e){var t=this.z.redSqr(),i=e.toRed(this.curve.red).redMul(t);if(0===this.x.cmp(i))return!0;for(var n=e.clone(),r=this.curve.redN.redMul(t);;){if(n.iadd(this.curve.n),n.cmp(this.curve.p)>=0)return!1;if(i.redIAdd(r),0===this.x.cmp(i))return!0}},l.prototype.inspect=function(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"},l.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],95:[function(e,t,i){"use strict";var n,r=i,o=e("hash.js"),s=e("./curve"),a=e("./utils").assert;function c(e){"short"===e.type?this.curve=new s.short(e):"edwards"===e.type?this.curve=new s.edwards(e):this.curve=new s.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,a(this.g.validate(),"Invalid curve"),a(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function d(e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get:function(){var i=new c(t);return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:i}),i}})}r.PresetCurve=c,d("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),d("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),d("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),d("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),d("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),d("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),d("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}d("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"./curve":92,"./precomputed/secp256k1":102,"./utils":103,"hash.js":132}],96:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("hmac-drbg"),o=e("../utils"),s=e("../curves"),a=e("brorand"),c=o.assert,d=e("./key"),l=e("./signature");function u(e){if(!(this instanceof u))return new u(e);"string"==typeof e&&(c(Object.prototype.hasOwnProperty.call(s,e),"Unknown curve "+e),e=s[e]),e instanceof s.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=u,u.prototype.keyPair=function(e){return new d(this,e)},u.prototype.keyFromPrivate=function(e,t){return d.fromPrivate(this,e,t)},u.prototype.keyFromPublic=function(e,t){return d.fromPublic(this,e,t)},u.prototype.genKeyPair=function(e){e||(e={});for(var t=new r({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||a(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),o=this.n.sub(new n(2));;){var s=new n(t.generate(i));if(!(s.cmp(o)>0))return s.iaddn(1),this.keyFromPrivate(s)}},u.prototype._truncateToN=function(e,t){var i=8*e.byteLength()-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},u.prototype.sign=function(e,t,i,o){"object"==typeof i&&(o=i,i=null),o||(o={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(new n(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),c=e.toArray("be",s),d=new r({hash:this.hash,entropy:a,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),u=this.n.sub(new n(1)),h=0;;h++){var f=o.k?o.k(h):new n(d.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(u)>=0)){var p=this.g.mul(f);if(!p.isInfinity()){var g=p.getX(),v=g.umod(this.n);if(0!==v.cmpn(0)){var m=f.invm(this.n).mul(v.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var y=(p.getY().isOdd()?1:0)|(0!==g.cmp(v)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),y^=1),new l({r:v,s:m,recoveryParam:y})}}}}}},u.prototype.verify=function(e,t,i,r){e=this._truncateToN(new n(e,16)),i=this.keyFromPublic(i,r);var o=(t=new l(t,"hex")).r,s=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a,c=s.invm(this.n),d=c.mul(e).umod(this.n),u=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(d,i.getPublic(),u)).isInfinity()&&a.eqXToP(o):!(a=this.g.mulAdd(d,i.getPublic(),u)).isInfinity()&&0===a.getX().umod(this.n).cmp(o)},u.prototype.recoverPubKey=function(e,t,i,r){c((3&i)===i,"The recovery param is more than two bits"),t=new l(t,r);var o=this.n,s=new n(e),a=t.r,d=t.s,u=1&i,h=i>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");a=h?this.curve.pointFromX(a.add(this.curve.n),u):this.curve.pointFromX(a,u);var f=t.r.invm(o),p=o.sub(s).mul(f).umod(o),g=d.mul(f).umod(o);return this.g.mulAdd(p,a,g)},u.prototype.getKeyRecoveryParam=function(e,t,i,n){if(null!==(t=new l(t,n)).recoveryParam)return t.recoveryParam;for(var r=0;r<4;r++){var o;try{o=this.recoverPubKey(e,t,r)}catch(e){continue}if(o.eq(i))return r}throw new Error("Unable to find valid recovery factor")}},{"../curves":95,"../utils":103,"./key":97,"./signature":98,"bn.js":18,brorand:19,"hmac-drbg":144}],97:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils").assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,i){return t instanceof o?t:new o(e,{pub:t,pubEnc:i})},o.fromPrivate=function(e,t,i){return t instanceof o?t:new o(e,{priv:t,privEnc:i})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?r(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||r(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.validate()||r(e.validate(),"public point not validated"),e.mul(this.priv).getX()},o.prototype.sign=function(e,t,i){return this.ec.sign(e,this,t,i)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"}},{"../utils":103,"bn.js":18}],98:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils"),o=r.assert;function s(e,t){if(e instanceof s)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function a(){this.place=0}function c(e,t){var i=e[t.place++];if(!(128&i))return i;var n=15&i;if(0===n||n>4)return!1;for(var r=0,o=0,s=t.place;o<n;o++,s++)r<<=8,r|=e[s],r>>>=0;return!(r<=127)&&(t.place=s,r)}function d(e){for(var t=0,i=e.length-1;!e[t]&&!(128&e[t+1])&&t<i;)t++;return 0===t?e:e.slice(t)}function l(e,t){if(t<128)e.push(t);else{var i=1+(Math.log(t)/Math.LN2>>>3);for(e.push(128|i);--i;)e.push(t>>>(i<<3)&255);e.push(t)}}t.exports=s,s.prototype._importDER=function(e,t){e=r.toArray(e,t);var i=new a;if(48!==e[i.place++])return!1;var o=c(e,i);if(!1===o)return!1;if(o+i.place!==e.length)return!1;if(2!==e[i.place++])return!1;var s=c(e,i);if(!1===s)return!1;var d=e.slice(i.place,s+i.place);if(i.place+=s,2!==e[i.place++])return!1;var l=c(e,i);if(!1===l)return!1;if(e.length!==l+i.place)return!1;var u=e.slice(i.place,l+i.place);if(0===d[0]){if(!(128&d[1]))return!1;d=d.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new n(d),this.s=new n(u),this.recoveryParam=null,!0},s.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&i[0]&&(i=[0].concat(i)),t=d(t),i=d(i);!(i[0]||128&i[1]);)i=i.slice(1);var n=[2];l(n,t.length),(n=n.concat(t)).push(2),l(n,i.length);var o=n.concat(i),s=[48];return l(s,o.length),s=s.concat(o),r.encode(s,e)}},{"../utils":103,"bn.js":18}],99:[function(e,t,i){"use strict";var n=e("hash.js"),r=e("../curves"),o=e("../utils"),s=o.assert,a=o.parseBytes,c=e("./key"),d=e("./signature");function l(e){if(s("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof l))return new l(e);e=r[e].curve,this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=l,l.prototype.sign=function(e,t){e=a(e);var i=this.keyFromSecret(t),n=this.hashInt(i.messagePrefix(),e),r=this.g.mul(n),o=this.encodePoint(r),s=this.hashInt(o,i.pubBytes(),e).mul(i.priv()),c=n.add(s).umod(this.curve.n);return this.makeSignature({R:r,S:c,Rencoded:o})},l.prototype.verify=function(e,t,i){e=a(e),t=this.makeSignature(t);var n=this.keyFromPublic(i),r=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(r)).eq(o)},l.prototype.hashInt=function(){for(var e=this.hash(),t=0;t<arguments.length;t++)e.update(arguments[t]);return o.intFromLE(e.digest()).umod(this.curve.n)},l.prototype.keyFromPublic=function(e){return c.fromPublic(this,e)},l.prototype.keyFromSecret=function(e){return c.fromSecret(this,e)},l.prototype.makeSignature=function(e){return e instanceof d?e:new d(this,e)},l.prototype.encodePoint=function(e){var t=e.getY().toArray("le",this.encodingLength);return t[this.encodingLength-1]|=e.getX().isOdd()?128:0,t},l.prototype.decodePoint=function(e){var t=(e=o.parseBytes(e)).length-1,i=e.slice(0,t).concat(-129&e[t]),n=0!=(128&e[t]),r=o.intFromLE(i);return this.curve.pointFromY(r,n)},l.prototype.encodeInt=function(e){return e.toArray("le",this.encodingLength)},l.prototype.decodeInt=function(e){return o.intFromLE(e)},l.prototype.isPoint=function(e){return e instanceof this.pointClass}},{"../curves":95,"../utils":103,"./key":100,"./signature":101,"hash.js":132}],100:[function(e,t,i){"use strict";var n=e("../utils"),r=n.assert,o=n.parseBytes,s=n.cachedProperty;function a(e,t){this.eddsa=e,this._secret=o(t.secret),e.isPoint(t.pub)?this._pub=t.pub:this._pubBytes=o(t.pub)}a.fromPublic=function(e,t){return t instanceof a?t:new a(e,{pub:t})},a.fromSecret=function(e,t){return t instanceof a?t:new a(e,{secret:t})},a.prototype.secret=function(){return this._secret},s(a,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),s(a,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),s(a,"privBytes",(function(){var e=this.eddsa,t=this.hash(),i=e.encodingLength-1,n=t.slice(0,e.encodingLength);return n[0]&=248,n[i]&=127,n[i]|=64,n})),s(a,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),s(a,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),s(a,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),a.prototype.sign=function(e){return r(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},a.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},a.prototype.getSecret=function(e){return r(this._secret,"KeyPair is public only"),n.encode(this.secret(),e)},a.prototype.getPublic=function(e){return n.encode(this.pubBytes(),e)},t.exports=a},{"../utils":103}],101:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils"),o=r.assert,s=r.cachedProperty,a=r.parseBytes;function c(e,t){this.eddsa=e,"object"!=typeof t&&(t=a(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),o(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof n&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}s(c,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),s(c,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),s(c,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),s(c,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),c.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},c.prototype.toHex=function(){return r.encode(this.toBytes(),"hex").toUpperCase()},t.exports=c},{"../utils":103,"bn.js":18}],102:[function(e,t,i){t.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}},{}],103:[function(e,t,i){"use strict";var n=i,r=e("bn.js"),o=e("minimalistic-assert"),s=e("minimalistic-crypto-utils");n.assert=o,n.toArray=s.toArray,n.zero2=s.zero2,n.toHex=s.toHex,n.encode=s.encode,n.getNAF=function(e,t,i){var n=new Array(Math.max(e.bitLength(),i)+1);n.fill(0);for(var r=1<<t+1,o=e.clone(),s=0;s<n.length;s++){var a,c=o.andln(r-1);o.isOdd()?(a=c>(r>>1)-1?(r>>1)-c:c,o.isubn(a)):a=0,n[s]=a,o.iushrn(1)}return n},n.getJSF=function(e,t){var i=[[],[]];e=e.clone(),t=t.clone();for(var n,r=0,o=0;e.cmpn(-r)>0||t.cmpn(-o)>0;){var s,a,c=e.andln(3)+r&3,d=t.andln(3)+o&3;3===c&&(c=-1),3===d&&(d=-1),s=0==(1&c)?0:3!==(n=e.andln(7)+r&7)&&5!==n||2!==d?c:-c,i[0].push(s),a=0==(1&d)?0:3!==(n=t.andln(7)+o&7)&&5!==n||2!==c?d:-d,i[1].push(a),2*r===s+1&&(r=1-r),2*o===a+1&&(o=1-o),e.iushrn(1),t.iushrn(1)}return i},n.cachedProperty=function(e,t,i){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=i.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new r(e,"hex","le")}},{"bn.js":18,"minimalistic-assert":223,"minimalistic-crypto-utils":224}],104:[function(e,t,i){t.exports={name:"elliptic",version:"6.5.4",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny <fedor@indutny.com>",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}},{}],105:[function(e,t,i){"use strict";var n,r="object"==typeof Reflect?Reflect:null,o=r&&"function"==typeof r.apply?r.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};n=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}t.exports=a,t.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,r,{once:!0})}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function d(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,i,n){var r,o,s,a;if(d(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),s=o[t]),void 0===s)s=o[t]=i,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[i,s]:[s,i]:n?s.unshift(i):s.push(i),(r=l(e))>0&&s.length>r&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=h.bind(n);return r.listener=i,n.wrapFn=r,r}function p(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):v(r,r.length)}function g(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function v(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(o){n.once&&e.removeEventListener(t,r),i(o)}))}}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");c=e}}),a.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return l(this)},a.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)o(c,this,t);else{var d=c.length,l=v(c,d);for(i=0;i<d;++i)o(l[i],this,t)}return!0},a.prototype.addListener=function(e,t){return u(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return u(this,e,t,!0)},a.prototype.once=function(e,t){return d(t),this.on(e,f(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return d(t),this.prependListener(e,f(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,n,r,o,s;if(d(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){s=i[o].listener,r=o;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(r=o[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],106:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("md5.js");t.exports=function(e,t,i,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var s=i/8,a=n.alloc(s),c=n.alloc(o||0),d=n.alloc(0);s>0||o>0;){var l=new r;l.update(d),l.update(e),t&&l.update(t),d=l.digest();var u=0;if(s>0){var h=a.length-s;u=Math.min(s,d.length),d.copy(a,h,0,u),s-=u}if(u<d.length&&o>0){var f=c.length-o,p=Math.min(o,d.length-u);d.copy(c,f,u,u+p),o-=p}}return d.fill(0),{key:a,iv:c}}},{"md5.js":221,"safe-buffer":250}],107:[function(e,t,i){"use strict";var n=e("is-callable"),r=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=function(e,t,i){for(var n=0,r=e.length;n<r;n++)o.call(e,n)&&(null==i?t(e[n],n,e):t.call(i,e[n],n,e))},a=function(e,t,i){for(var n=0,r=e.length;n<r;n++)null==i?t(e.charAt(n),n,e):t.call(i,e.charAt(n),n,e)},c=function(e,t,i){for(var n in e)o.call(e,n)&&(null==i?t(e[n],n,e):t.call(i,e[n],n,e))};t.exports=function(e,t,i){if(!n(t))throw new TypeError("iterator must be a function");var o;arguments.length>=3&&(o=i),"[object Array]"===r.call(e)?s(e,t,o):"string"==typeof e?a(e,t,o):c(e,t,o)}},{"is-callable":148}],108:[function(e,t,i){"use strict";var n="Function.prototype.bind called on incompatible ",r=Array.prototype.slice,o=Object.prototype.toString,s="[object Function]";t.exports=function(e){var t=this;if("function"!=typeof t||o.call(t)!==s)throw new TypeError(n+t);for(var i,a=r.call(arguments,1),c=Math.max(0,t.length-a.length),d=[],l=0;l<c;l++)d.push("$"+l);if(i=Function("binder","return function ("+d.join(",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof i){var n=t.apply(this,a.concat(r.call(arguments)));return Object(n)===n?n:this}return t.apply(e,a.concat(r.call(arguments)))})),t.prototype){var u=function(){};u.prototype=t.prototype,i.prototype=new u,u.prototype=null}return i}},{}],109:[function(e,t,i){"use strict";var n=e("./implementation");t.exports=Function.prototype.bind||n},{"./implementation":108}],110:[function(e,t,i){"use strict";var n,r=SyntaxError,o=Function,s=TypeError,a=function(e){try{return o('"use strict"; return ('+e+").constructor;")()}catch(e){}},c=Object.getOwnPropertyDescriptor;if(c)try{c({},"")}catch(e){c=null}var d=function(){throw new s},l=c?function(){try{return d}catch(e){try{return c(arguments,"callee").get}catch(e){return d}}}():d,u=e("has-symbols")(),h=Object.getPrototypeOf||function(e){return e.__proto__},f={},p="undefined"==typeof Uint8Array?n:h(Uint8Array),g={"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":u?h([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":f,"%AsyncGenerator%":f,"%AsyncGeneratorFunction%":f,"%AsyncIteratorPrototype%":f,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":f,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":u?h(h([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&u?h((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&u?h((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":u?h(""[Symbol.iterator]()):n,"%Symbol%":u?Symbol:n,"%SyntaxError%":r,"%ThrowTypeError%":l,"%TypedArray%":p,"%TypeError%":s,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet};try{null.error}catch(e){var v=h(h(e));g["%Error.prototype%"]=v}var m=function e(t){var i;if("%AsyncFunction%"===t)i=a("async function () {}");else if("%GeneratorFunction%"===t)i=a("function* () {}");else if("%AsyncGeneratorFunction%"===t)i=a("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(i=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var r=e("%AsyncGenerator%");r&&(i=h(r.prototype))}return g[t]=i,i},y={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},b=e("function-bind"),S=e("has"),_=b.call(Function.call,Array.prototype.concat),E=b.call(Function.apply,Array.prototype.splice),w=b.call(Function.call,String.prototype.replace),T=b.call(Function.call,String.prototype.slice),I=b.call(Function.call,RegExp.prototype.exec),R=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,M=/\\(\\)?/g,k=function(e){var t=T(e,0,1),i=T(e,-1);if("%"===t&&"%"!==i)throw new r("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==t)throw new r("invalid intrinsic syntax, expected opening `%`");var n=[];return w(e,R,(function(e,t,i,r){n[n.length]=i?w(r,M,"$1"):t||e})),n},C=function(e,t){var i,n=e;if(S(y,n)&&(n="%"+(i=y[n])[0]+"%"),S(g,n)){var o=g[n];if(o===f&&(o=m(n)),void 0===o&&!t)throw new s("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new r("intrinsic "+e+" does not exist!")};t.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new s('"allowMissing" argument must be a boolean');if(null===I(/^%?[^%]*%?$/,e))throw new r("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=k(e),n=i.length>0?i[0]:"",o=C("%"+n+"%",t),a=o.name,d=o.value,l=!1,u=o.alias;u&&(n=u[0],E(i,_([0,1],u)));for(var h=1,f=!0;h<i.length;h+=1){var p=i[h],v=T(p,0,1),m=T(p,-1);if(('"'===v||"'"===v||"`"===v||'"'===m||"'"===m||"`"===m)&&v!==m)throw new r("property names with quotes must have matching quotes");if("constructor"!==p&&f||(l=!0),S(g,a="%"+(n+="."+p)+"%"))d=g[a];else if(null!=d){if(!(p in d)){if(!t)throw new s("base intrinsic for "+e+" exists, but the property is not available.");return}if(c&&h+1>=i.length){var y=c(d,p);d=(f=!!y)&&"get"in y&&!("originalValue"in y.get)?y.get:d[p]}else f=S(d,p),d=d[p];f&&!l&&(g[a]=d)}}return d}},{"function-bind":109,has:115,"has-symbols":112}],111:[function(e,t,i){"use strict";var n=e("get-intrinsic")("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}t.exports=n},{"get-intrinsic":110}],112:[function(e,t,i){"use strict";var n="undefined"!=typeof Symbol&&Symbol,r=e("./shams");t.exports=function(){return"function"==typeof n&&("function"==typeof Symbol&&("symbol"==typeof n("foo")&&("symbol"==typeof Symbol("bar")&&r())))}},{"./shams":113}],113:[function(e,t,i){"use strict";t.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),i=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var r=Object.getOwnPropertyDescriptor(e,t);if(42!==r.value||!0!==r.enumerable)return!1}return!0}},{}],114:[function(e,t,i){"use strict";var n=e("has-symbols/shams");t.exports=function(){return n()&&!!Symbol.toStringTag}},{"has-symbols/shams":113}],115:[function(e,t,i){"use strict";var n=e("function-bind");t.exports=n.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":109}],116:[function(e,t,i){"use strict";var n=e("safe-buffer").Buffer,r=e("readable-stream").Transform;function o(e){r.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,r),o.prototype._transform=function(e,t,i){var n=null;try{this.update(e,t)}catch(e){n=e}i(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var i=this._block,r=0;this._blockOffset+e.length-r>=this._blockSize;){for(var o=this._blockOffset;o<this._blockSize;)i[o++]=e[r++];this._update(),this._blockOffset=0}for(;r<e.length;)i[this._blockOffset++]=e[r++];for(var s=0,a=8*e.length;a>0;++s)this._length[s]+=a,(a=this._length[s]/4294967296|0)>0&&(this._length[s]-=4294967296*a);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:146,"readable-stream":131,"safe-buffer":250}],117:[function(e,t,i){arguments[4][50][0].apply(i,arguments)},{dup:50}],118:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a<s.length;a++){var c=s[a];d.prototype[c]||(d.prototype[c]=o.prototype[c])}function d(e){if(!(this instanceof d))return new d(e);r.call(this,e),o.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",l)))}function l(){this._writableState.ended||i.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(d.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(d.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":120,"./_stream_writable":122,_process:237,inherits:146}],119:[function(e,t,i){arguments[4][52][0].apply(i,arguments)},{"./_stream_transform":121,dup:52,inherits:146}],120:[function(e,t,i){(function(i,n){(function(){"use strict";var r;t.exports=I,I.ReadableState=T;e("events").EventEmitter;var o=function(e,t){return e.listeners(t).length},s=e("./internal/streams/stream"),a=e("buffer").Buffer,c=n.Uint8Array||function(){};var d,l=e("util");d=l&&l.debuglog?l.debuglog("stream"):function(){};var u,h,f,p=e("./internal/streams/buffer_list"),g=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,m=e("../errors").codes,y=m.ERR_INVALID_ARG_TYPE,b=m.ERR_STREAM_PUSH_AFTER_EOF,S=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(I,s);var E=g.errorOrDestroy,w=["error","close","destroy","pause","resume"];function T(t,i,n){r=r||e("./_stream_duplex"),t=t||{},"boolean"!=typeof n&&(n=i instanceof r),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",n),this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(u||(u=e("string_decoder/").StringDecoder),this.decoder=new u(t.encoding),this.encoding=t.encoding)}function I(t){if(r=r||e("./_stream_duplex"),!(this instanceof I))return new I(t);var i=this instanceof r;this._readableState=new T(t,this,i),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),s.call(this)}function R(e,t,i,n,r){d("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(d("onEofChunk"),t.ended)return;if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,t.sync?O(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,A(e)))}(e,s);else if(r||(o=function(e,t){var i;n=t,a.isBuffer(n)||n instanceof c||"string"==typeof t||void 0===t||e.objectMode||(i=new y("chunk",["string","Buffer","Uint8Array"],t));var n;return i}(s,t)),o)E(e,o);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function M(e,t,i,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",i)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&O(e)),P(e,t)}Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),I.prototype.destroy=g.destroy,I.prototype._undestroy=g.undestroy,I.prototype._destroy=function(e,t){t(e)},I.prototype.push=function(e,t){var i,n=this._readableState;return n.objectMode?i=!0:"string"==typeof e&&((t=t||n.defaultEncoding)!==n.encoding&&(e=a.from(e,t),t=""),i=!0),R(this,e,t,!1,i)},I.prototype.unshift=function(e){return R(this,e,null,!0,!1)},I.prototype.isPaused=function(){return!1===this._readableState.flowing},I.prototype.setEncoding=function(t){u||(u=e("string_decoder/").StringDecoder);var i=new u(t);this._readableState.decoder=i,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=i.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function C(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var i=t.length;if(d("maybeReadMore read 0"),e.read(0),i===t.length)break}t.readingMore=!1}function x(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}I.prototype.read=function(e){d("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",r=!0),t.ended||t.reading?d("reading or ended",r=!1):r&&(d("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=C(i,t))),null===(n=e>0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<r;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=K(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i)),this},I.prototype.on=function(e,t){var n=s.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));return this._read=function(t){d("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(I.prototype[Symbol.asyncIterator]=function(){return void 0===h&&(h=e("./internal/streams/async_iterator")),h(this)}),Object.defineProperty(I.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(I.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(I.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),I._fromList=N,Object.defineProperty(I.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(I.from=function(t,i){return void 0===f&&(f=e("./internal/streams/from")),f(I,t,i)})}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":117,"./_stream_duplex":118,"./internal/streams/async_iterator":123,"./internal/streams/buffer_list":124,"./internal/streams/destroy":125,"./internal/streams/from":127,"./internal/streams/state":129,"./internal/streams/stream":130,_process:237,buffer:68,events:105,inherits:146,"string_decoder/":279,util:20}],121:[function(e,t,i){arguments[4][54][0].apply(i,arguments)},{"../errors":117,"./_stream_duplex":118,dup:54,inherits:146}],122:[function(e,t,i){(function(i,n){(function(){"use strict";function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,i){var n=e.entry;e.entry=null;for(;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var o;t.exports=I,I.WritableState=T;var s={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),c=e("buffer").Buffer,d=n.Uint8Array||function(){};var l,u=e("./internal/streams/destroy"),h=e("./internal/streams/state").getHighWaterMark,f=e("../errors").codes,p=f.ERR_INVALID_ARG_TYPE,g=f.ERR_METHOD_NOT_IMPLEMENTED,v=f.ERR_MULTIPLE_CALLBACK,m=f.ERR_STREAM_CANNOT_PIPE,y=f.ERR_STREAM_DESTROYED,b=f.ERR_STREAM_NULL_VALUES,S=f.ERR_STREAM_WRITE_AFTER_END,_=f.ERR_UNKNOWN_ENCODING,E=u.errorOrDestroy;function w(){}function T(t,n,s){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof s&&(s=n instanceof o),this.objectMode=!!t.objectMode,s&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=h(this,t,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,o=n.writecb;if("function"!=typeof o)throw new v;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,o){--t.pendingcb,n?(i.nextTick(o,r),i.nextTick(A,e,t),e._writableState.errorEmitted=!0,E(e,r)):(o(r),e._writableState.errorEmitted=!0,E(e,r),A(e,t))}(e,n,r,t,o);else{var s=C(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?i.nextTick(M,e,n,s,o):M(e,n,s,o)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}function I(t){var i=this instanceof(o=o||e("./_stream_duplex"));if(!i&&!l.call(I,this))return new I(t);this._writableState=new T(t,this,i),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function R(e,t,i,n,r,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new y("write")):i?e._writev(r,t.onwrite):e._write(r,o,t.onwrite),t.sync=!1}function M(e,t,i,n){i||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),A(e,t)}function k(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,o=new Array(n),s=t.corkedRequestsFree;s.entry=i;for(var a=0,c=!0;i;)o[a]=i,i.isBuf||(c=!1),i=i.next,a+=1;o.allBuffers=c,R(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;i;){var d=i.chunk,l=i.encoding,u=i.callback;if(R(e,t,!1,t.objectMode?1:d.length,d,l,u),i=i.next,t.bufferedRequestCount--,t.writing)break}null===i&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}function C(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function O(e,t){e._final((function(i){t.pendingcb--,i&&E(e,i),t.prefinished=!0,e.emit("prefinish"),A(e,t)}))}function A(e,t){var n=C(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,i.nextTick(O,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}e("inherits")(I,a),T.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(T.prototype,"buffer",{get:s.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(l=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!l.call(this,e)||this===I&&(e&&e._writableState instanceof T)}})):l=function(e){return e instanceof this},I.prototype.pipe=function(){E(this,new m)},I.prototype.write=function(e,t,n){var r,o=this._writableState,s=!1,a=!o.objectMode&&(r=e,c.isBuffer(r)||r instanceof d);return a&&!c.isBuffer(e)&&(e=function(e){return c.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof n&&(n=w),o.ending?function(e,t){var n=new S;E(e,n),i.nextTick(t,n)}(this,n):(a||function(e,t,n,r){var o;return null===n?o=new b:"string"==typeof n||t.objectMode||(o=new p("chunk",["string","Buffer"],n)),!o||(E(e,o),i.nextTick(r,o),!1)}(this,o,e,n))&&(o.pendingcb++,s=function(e,t,i,n,r,o){if(!i){var s=function(e,t,i){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,i));return t}(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var a=t.objectMode?1:n.length;t.length+=a;var d=t.length<t.highWaterMark;d||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,a,n,r,o);return d}(this,o,a,e,t,n)),s},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},I.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":117,"./_stream_duplex":118,"./internal/streams/destroy":125,"./internal/streams/state":129,"./internal/streams/stream":130,_process:237,buffer:68,inherits:146,"util-deprecate":283}],123:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":126,_process:237}],124:[function(e,t,i){arguments[4][57][0].apply(i,arguments)},{buffer:68,dup:57,util:20}],125:[function(e,t,i){(function(e){(function(){"use strict";function i(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(r,this,t)):e.nextTick(r,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(n,s):(s._writableState.errorEmitted=!0,e.nextTick(i,s,t)):e.nextTick(i,s,t):o?(e.nextTick(n,s),o(t)):e.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var i=e._readableState,n=e._writableState;i&&i.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:237}],126:[function(e,t,i){arguments[4][59][0].apply(i,arguments)},{"../../../errors":117,dup:59}],127:[function(e,t,i){arguments[4][60][0].apply(i,arguments)},{dup:60}],128:[function(e,t,i){arguments[4][61][0].apply(i,arguments)},{"../../../errors":117,"./end-of-stream":126,dup:61}],129:[function(e,t,i){arguments[4][62][0].apply(i,arguments)},{"../../../errors":117,dup:62}],130:[function(e,t,i){arguments[4][63][0].apply(i,arguments)},{dup:63,events:105}],131:[function(e,t,i){arguments[4][64][0].apply(i,arguments)},{"./lib/_stream_duplex.js":118,"./lib/_stream_passthrough.js":119,"./lib/_stream_readable.js":120,"./lib/_stream_transform.js":121,"./lib/_stream_writable.js":122,"./lib/internal/streams/end-of-stream.js":126,"./lib/internal/streams/pipeline.js":128,dup:64}],132:[function(e,t,i){var n=i;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":133,"./hash/hmac":134,"./hash/ripemd":135,"./hash/sha":136,"./hash/utils":143}],133:[function(e,t,i){"use strict";var n=e("./utils"),r=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}i.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var i=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-i,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-i,this.endian);for(var r=0;r<e.length;r+=this._delta32)this._update(e,r,r+this._delta32)}return this},o.prototype.digest=function(e){return this.update(this._pad()),r(null===this.pending),this._digest(e)},o.prototype._pad=function(){var e=this.pendingTotal,t=this._delta8,i=t-(e+this.padLength)%t,n=new Array(i+this.padLength);n[0]=128;for(var r=1;r<i;r++)n[r]=0;if(e<<=3,"big"===this.endian){for(var o=8;o<this.padLength;o++)n[r++]=0;n[r++]=0,n[r++]=0,n[r++]=0,n[r++]=0,n[r++]=e>>>24&255,n[r++]=e>>>16&255,n[r++]=e>>>8&255,n[r++]=255&e}else for(n[r++]=255&e,n[r++]=e>>>8&255,n[r++]=e>>>16&255,n[r++]=e>>>24&255,n[r++]=0,n[r++]=0,n[r++]=0,n[r++]=0,o=8;o<this.padLength;o++)n[r++]=0;return n}},{"./utils":143,"minimalistic-assert":223}],134:[function(e,t,i){"use strict";var n=e("./utils"),r=e("minimalistic-assert");function o(e,t,i){if(!(this instanceof o))return new o(e,t,i);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(n.toArray(t,i))}t.exports=o,o.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),r(e.length<=this.blockSize);for(var t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new this.Hash).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new this.Hash).update(e)},o.prototype.update=function(e,t){return this.inner.update(e,t),this},o.prototype.digest=function(e){return this.outer.update(this.inner.digest()),this.outer.digest(e)}},{"./utils":143,"minimalistic-assert":223}],135:[function(e,t,i){"use strict";var n=e("./utils"),r=e("./common"),o=n.rotl32,s=n.sum32,a=n.sum32_3,c=n.sum32_4,d=r.BlockHash;function l(){if(!(this instanceof l))return new l;d.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function u(e,t,i,n){return e<=15?t^i^n:e<=31?t&i|~t&n:e<=47?(t|~i)^n:e<=63?t&n|i&~n:t^(i|~n)}function h(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function f(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}n.inherits(l,d),i.ripemd160=l,l.blockSize=512,l.outSize=160,l.hmacStrength=192,l.padLength=64,l.prototype._update=function(e,t){for(var i=this.h[0],n=this.h[1],r=this.h[2],d=this.h[3],l=this.h[4],y=i,b=n,S=r,_=d,E=l,w=0;w<80;w++){var T=s(o(c(i,u(w,n,r,d),e[p[w]+t],h(w)),v[w]),l);i=l,l=d,d=o(r,10),r=n,n=T,T=s(o(c(y,u(79-w,b,S,_),e[g[w]+t],f(w)),m[w]),E),y=E,E=_,_=o(S,10),S=b,b=T}T=a(this.h[1],r,_),this.h[1]=a(this.h[2],d,E),this.h[2]=a(this.h[3],l,y),this.h[3]=a(this.h[4],i,b),this.h[4]=a(this.h[0],n,S),this.h[0]=T},l.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"little"):n.split32(this.h,"little")};var p=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],g=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],v=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],m=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},{"./common":133,"./utils":143}],136:[function(e,t,i){"use strict";i.sha1=e("./sha/1"),i.sha224=e("./sha/224"),i.sha256=e("./sha/256"),i.sha384=e("./sha/384"),i.sha512=e("./sha/512")},{"./sha/1":137,"./sha/224":138,"./sha/256":139,"./sha/384":140,"./sha/512":141}],137:[function(e,t,i){"use strict";var n=e("../utils"),r=e("../common"),o=e("./common"),s=n.rotl32,a=n.sum32,c=n.sum32_5,d=o.ft_1,l=r.BlockHash,u=[1518500249,1859775393,2400959708,3395469782];function h(){if(!(this instanceof h))return new h;l.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}n.inherits(h,l),t.exports=h,h.blockSize=512,h.outSize=160,h.hmacStrength=80,h.padLength=64,h.prototype._update=function(e,t){for(var i=this.W,n=0;n<16;n++)i[n]=e[t+n];for(;n<i.length;n++)i[n]=s(i[n-3]^i[n-8]^i[n-14]^i[n-16],1);var r=this.h[0],o=this.h[1],l=this.h[2],h=this.h[3],f=this.h[4];for(n=0;n<i.length;n++){var p=~~(n/20),g=c(s(r,5),d(p,o,l,h),f,i[n],u[p]);f=h,h=l,l=s(o,30),o=r,r=g}this.h[0]=a(this.h[0],r),this.h[1]=a(this.h[1],o),this.h[2]=a(this.h[2],l),this.h[3]=a(this.h[3],h),this.h[4]=a(this.h[4],f)},h.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},{"../common":133,"../utils":143,"./common":142}],138:[function(e,t,i){"use strict";var n=e("../utils"),r=e("./256");function o(){if(!(this instanceof o))return new o;r.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}n.inherits(o,r),t.exports=o,o.blockSize=512,o.outSize=224,o.hmacStrength=192,o.padLength=64,o.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,7),"big"):n.split32(this.h.slice(0,7),"big")}},{"../utils":143,"./256":139}],139:[function(e,t,i){"use strict";var n=e("../utils"),r=e("../common"),o=e("./common"),s=e("minimalistic-assert"),a=n.sum32,c=n.sum32_4,d=n.sum32_5,l=o.ch32,u=o.maj32,h=o.s0_256,f=o.s1_256,p=o.g0_256,g=o.g1_256,v=r.BlockHash,m=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function y(){if(!(this instanceof y))return new y;v.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=m,this.W=new Array(64)}n.inherits(y,v),t.exports=y,y.blockSize=512,y.outSize=256,y.hmacStrength=192,y.padLength=64,y.prototype._update=function(e,t){for(var i=this.W,n=0;n<16;n++)i[n]=e[t+n];for(;n<i.length;n++)i[n]=c(g(i[n-2]),i[n-7],p(i[n-15]),i[n-16]);var r=this.h[0],o=this.h[1],v=this.h[2],m=this.h[3],y=this.h[4],b=this.h[5],S=this.h[6],_=this.h[7];for(s(this.k.length===i.length),n=0;n<i.length;n++){var E=d(_,f(y),l(y,b,S),this.k[n],i[n]),w=a(h(r),u(r,o,v));_=S,S=b,b=y,y=a(m,E),m=v,v=o,o=r,r=a(E,w)}this.h[0]=a(this.h[0],r),this.h[1]=a(this.h[1],o),this.h[2]=a(this.h[2],v),this.h[3]=a(this.h[3],m),this.h[4]=a(this.h[4],y),this.h[5]=a(this.h[5],b),this.h[6]=a(this.h[6],S),this.h[7]=a(this.h[7],_)},y.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},{"../common":133,"../utils":143,"./common":142,"minimalistic-assert":223}],140:[function(e,t,i){"use strict";var n=e("../utils"),r=e("./512");function o(){if(!(this instanceof o))return new o;r.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}n.inherits(o,r),t.exports=o,o.blockSize=1024,o.outSize=384,o.hmacStrength=192,o.padLength=128,o.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h.slice(0,12),"big"):n.split32(this.h.slice(0,12),"big")}},{"../utils":143,"./512":141}],141:[function(e,t,i){"use strict";var n=e("../utils"),r=e("../common"),o=e("minimalistic-assert"),s=n.rotr64_hi,a=n.rotr64_lo,c=n.shr64_hi,d=n.shr64_lo,l=n.sum64,u=n.sum64_hi,h=n.sum64_lo,f=n.sum64_4_hi,p=n.sum64_4_lo,g=n.sum64_5_hi,v=n.sum64_5_lo,m=r.BlockHash,y=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function b(){if(!(this instanceof b))return new b;m.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=y,this.W=new Array(160)}function S(e,t,i,n,r){var o=e&i^~e&r;return o<0&&(o+=4294967296),o}function _(e,t,i,n,r,o){var s=t&n^~t&o;return s<0&&(s+=4294967296),s}function E(e,t,i,n,r){var o=e&i^e&r^i&r;return o<0&&(o+=4294967296),o}function w(e,t,i,n,r,o){var s=t&n^t&o^n&o;return s<0&&(s+=4294967296),s}function T(e,t){var i=s(e,t,28)^s(t,e,2)^s(t,e,7);return i<0&&(i+=4294967296),i}function I(e,t){var i=a(e,t,28)^a(t,e,2)^a(t,e,7);return i<0&&(i+=4294967296),i}function R(e,t){var i=s(e,t,14)^s(e,t,18)^s(t,e,9);return i<0&&(i+=4294967296),i}function M(e,t){var i=a(e,t,14)^a(e,t,18)^a(t,e,9);return i<0&&(i+=4294967296),i}function k(e,t){var i=s(e,t,1)^s(e,t,8)^c(e,t,7);return i<0&&(i+=4294967296),i}function C(e,t){var i=a(e,t,1)^a(e,t,8)^d(e,t,7);return i<0&&(i+=4294967296),i}function O(e,t){var i=s(e,t,19)^s(t,e,29)^c(e,t,6);return i<0&&(i+=4294967296),i}function A(e,t){var i=a(e,t,19)^a(t,e,29)^d(e,t,6);return i<0&&(i+=4294967296),i}n.inherits(b,m),t.exports=b,b.blockSize=1024,b.outSize=512,b.hmacStrength=192,b.padLength=128,b.prototype._prepareBlock=function(e,t){for(var i=this.W,n=0;n<32;n++)i[n]=e[t+n];for(;n<i.length;n+=2){var r=O(i[n-4],i[n-3]),o=A(i[n-4],i[n-3]),s=i[n-14],a=i[n-13],c=k(i[n-30],i[n-29]),d=C(i[n-30],i[n-29]),l=i[n-32],u=i[n-31];i[n]=f(r,o,s,a,c,d,l,u),i[n+1]=p(r,o,s,a,c,d,l,u)}},b.prototype._update=function(e,t){this._prepareBlock(e,t);var i=this.W,n=this.h[0],r=this.h[1],s=this.h[2],a=this.h[3],c=this.h[4],d=this.h[5],f=this.h[6],p=this.h[7],m=this.h[8],y=this.h[9],b=this.h[10],k=this.h[11],C=this.h[12],O=this.h[13],A=this.h[14],P=this.h[15];o(this.k.length===i.length);for(var D=0;D<i.length;D+=2){var x=A,L=P,U=R(m,y),B=M(m,y),N=S(m,y,b,k,C),j=_(m,y,b,k,C,O),F=this.k[D],K=this.k[D+1],q=i[D],$=i[D+1],V=g(x,L,U,B,N,j,F,K,q,$),H=v(x,L,U,B,N,j,F,K,q,$);x=T(n,r),L=I(n,r),U=E(n,r,s,a,c),B=w(n,r,s,a,c,d);var W=u(x,L,U,B),G=h(x,L,U,B);A=C,P=O,C=b,O=k,b=m,k=y,m=u(f,p,V,H),y=h(p,p,V,H),f=c,p=d,c=s,d=a,s=n,a=r,n=u(V,H,W,G),r=h(V,H,W,G)}l(this.h,0,n,r),l(this.h,2,s,a),l(this.h,4,c,d),l(this.h,6,f,p),l(this.h,8,m,y),l(this.h,10,b,k),l(this.h,12,C,O),l(this.h,14,A,P)},b.prototype._digest=function(e){return"hex"===e?n.toHex32(this.h,"big"):n.split32(this.h,"big")}},{"../common":133,"../utils":143,"minimalistic-assert":223}],142:[function(e,t,i){"use strict";var n=e("../utils").rotr32;function r(e,t,i){return e&t^~e&i}function o(e,t,i){return e&t^e&i^t&i}function s(e,t,i){return e^t^i}i.ft_1=function(e,t,i,n){return 0===e?r(t,i,n):1===e||3===e?s(t,i,n):2===e?o(t,i,n):void 0},i.ch32=r,i.maj32=o,i.p32=s,i.s0_256=function(e){return n(e,2)^n(e,13)^n(e,22)},i.s1_256=function(e){return n(e,6)^n(e,11)^n(e,25)},i.g0_256=function(e){return n(e,7)^n(e,18)^e>>>3},i.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":143}],143:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits");function o(e,t){return 55296==(64512&e.charCodeAt(t))&&(!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1)))}function s(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function c(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}i.inherits=r,i.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var i=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),r=0;r<e.length;r+=2)i.push(parseInt(e[r]+e[r+1],16))}else for(var n=0,r=0;r<e.length;r++){var s=e.charCodeAt(r);s<128?i[n++]=s:s<2048?(i[n++]=s>>6|192,i[n++]=63&s|128):o(e,r)?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++r)),i[n++]=s>>18|240,i[n++]=s>>12&63|128,i[n++]=s>>6&63|128,i[n++]=63&s|128):(i[n++]=s>>12|224,i[n++]=s>>6&63|128,i[n++]=63&s|128)}else for(r=0;r<e.length;r++)i[r]=0|e[r];return i},i.toHex=function(e){for(var t="",i=0;i<e.length;i++)t+=a(e[i].toString(16));return t},i.htonl=s,i.toHex32=function(e,t){for(var i="",n=0;n<e.length;n++){var r=e[n];"little"===t&&(r=s(r)),i+=c(r.toString(16))}return i},i.zero2=a,i.zero8=c,i.join32=function(e,t,i,r){var o=i-t;n(o%4==0);for(var s=new Array(o/4),a=0,c=t;a<s.length;a++,c+=4){var d;d="big"===r?e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3]:e[c+3]<<24|e[c+2]<<16|e[c+1]<<8|e[c],s[a]=d>>>0}return s},i.split32=function(e,t){for(var i=new Array(4*e.length),n=0,r=0;n<e.length;n++,r+=4){var o=e[n];"big"===t?(i[r]=o>>>24,i[r+1]=o>>>16&255,i[r+2]=o>>>8&255,i[r+3]=255&o):(i[r+3]=o>>>24,i[r+2]=o>>>16&255,i[r+1]=o>>>8&255,i[r]=255&o)}return i},i.rotr32=function(e,t){return e>>>t|e<<32-t},i.rotl32=function(e,t){return e<<t|e>>>32-t},i.sum32=function(e,t){return e+t>>>0},i.sum32_3=function(e,t,i){return e+t+i>>>0},i.sum32_4=function(e,t,i,n){return e+t+i+n>>>0},i.sum32_5=function(e,t,i,n,r){return e+t+i+n+r>>>0},i.sum64=function(e,t,i,n){var r=e[t],o=n+e[t+1]>>>0,s=(o<n?1:0)+i+r;e[t]=s>>>0,e[t+1]=o},i.sum64_hi=function(e,t,i,n){return(t+n>>>0<t?1:0)+e+i>>>0},i.sum64_lo=function(e,t,i,n){return t+n>>>0},i.sum64_4_hi=function(e,t,i,n,r,o,s,a){var c=0,d=t;return c+=(d=d+n>>>0)<t?1:0,c+=(d=d+o>>>0)<o?1:0,e+i+r+s+(c+=(d=d+a>>>0)<a?1:0)>>>0},i.sum64_4_lo=function(e,t,i,n,r,o,s,a){return t+n+o+a>>>0},i.sum64_5_hi=function(e,t,i,n,r,o,s,a,c,d){var l=0,u=t;return l+=(u=u+n>>>0)<t?1:0,l+=(u=u+o>>>0)<o?1:0,l+=(u=u+a>>>0)<a?1:0,e+i+r+s+c+(l+=(u=u+d>>>0)<d?1:0)>>>0},i.sum64_5_lo=function(e,t,i,n,r,o,s,a,c,d){return t+n+o+a+d>>>0},i.rotr64_hi=function(e,t,i){return(t<<32-i|e>>>i)>>>0},i.rotr64_lo=function(e,t,i){return(e<<32-i|t>>>i)>>>0},i.shr64_hi=function(e,t,i){return e>>>i},i.shr64_lo=function(e,t,i){return(e<<32-i|t>>>i)>>>0}},{inherits:146,"minimalistic-assert":223}],144:[function(e,t,i){"use strict";var n=e("hash.js"),r=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function s(e){if(!(this instanceof s))return new s(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=r.toArray(e.entropy,e.entropyEnc||"hex"),i=r.toArray(e.nonce,e.nonceEnc||"hex"),n=r.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,i,n)}t.exports=s,s.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var r=0;r<this.V.length;r++)this.K[r]=0,this.V[r]=1;this._update(n),this._reseed=1,this.reseedInterval=281474976710656},s.prototype._hmac=function(){return new n.hmac(this.hash,this.K)},s.prototype._update=function(e){var t=this._hmac().update(this.V).update([0]);e&&(t=t.update(e)),this.K=t.digest(),this.V=this._hmac().update(this.V).digest(),e&&(this.K=this._hmac().update(this.V).update([1]).update(e).digest(),this.V=this._hmac().update(this.V).digest())},s.prototype.reseed=function(e,t,i,n){"string"!=typeof t&&(n=i,i=t,t=null),e=r.toArray(e,t),i=r.toArray(i,n),o(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},s.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=i,i=t,t=null),i&&(i=r.toArray(i,n||"hex"),this._update(i));for(var o=[];o.length<e;)this.V=this._hmac().update(this.V).digest(),o=o.concat(this.V);var s=o.slice(0,e);return this._update(i),this._reseed++,r.encode(s,t)}},{"hash.js":132,"minimalistic-assert":223,"minimalistic-crypto-utils":224}],145:[function(e,t,i){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ +i.read=function(e,t,i,n,r){var o,s,a=8*r-n-1,c=(1<<a)-1,d=c>>1,l=-7,u=i?r-1:0,h=i?-1:1,f=e[t+u];for(u+=h,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+e[t+u],u+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+e[t+u],u+=h,l-=8);if(0===o)o=1-d;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=d}return(f?-1:1)*s*Math.pow(2,o-n)},i.write=function(e,t,i,n,r,o){var s,a,c,d=8*o-r-1,l=(1<<d)-1,u=l>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=l?(a=0,s=l):s+u>=1?(a=(t*c-1)*Math.pow(2,r),s+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),s=0));r>=8;e[i+f]=255&a,f+=p,a/=256,r-=8);for(s=s<<r|a,d+=r;d>0;e[i+f]=255&s,f+=p,s/=256,d-=8);e[i+f-p]|=128*g}},{}],146:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}}},{}],147:[function(e,t,i){"use strict";var n=e("has-tostringtag/shams")(),r=e("call-bind/callBound")("Object.prototype.toString"),o=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===r(e)},s=function(e){return!!o(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==r(e)&&"[object Function]"===r(e.callee)},a=function(){return o(arguments)}();o.isLegacyArguments=s,t.exports=a?o:s},{"call-bind/callBound":69,"has-tostringtag/shams":114}],148:[function(e,t,i){"use strict";var n,r,o=Function.prototype.toString,s="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof s&&"function"==typeof Object.defineProperty)try{n=Object.defineProperty({},"length",{get:function(){throw r}}),r={},s((function(){throw 42}),null,n)}catch(e){e!==r&&(s=null)}else s=null;var a=/^\s*class\b/,c=function(e){try{var t=o.call(e);return a.test(t)}catch(e){return!1}},d=function(e){try{return!c(e)&&(o.call(e),!0)}catch(e){return!1}},l=Object.prototype.toString,u="function"==typeof Symbol&&!!Symbol.toStringTag,h=!(0 in[,]),f=function(){return!1};if("object"==typeof document){var p=document.all;l.call(p)===l.call(document.all)&&(f=function(e){if((h||!e)&&(void 0===e||"object"==typeof e))try{var t=l.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}t.exports=s?function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{s(e,null,n)}catch(e){if(e!==r)return!1}return!c(e)&&d(e)}:function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(u)return d(e);if(c(e))return!1;var t=l.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&d(e)}},{}],149:[function(e,t,i){"use strict";var n,r=Object.prototype.toString,o=Function.prototype.toString,s=/^\s*(?:function)?\*/,a=e("has-tostringtag/shams")(),c=Object.getPrototypeOf;t.exports=function(e){if("function"!=typeof e)return!1;if(s.test(o.call(e)))return!0;if(!a)return"[object GeneratorFunction]"===r.call(e);if(!c)return!1;if(void 0===n){var t=function(){if(!a)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&c(t)}return c(e)===n}},{"has-tostringtag/shams":114}],150:[function(e,t,i){(function(i){(function(){"use strict";var n=e("for-each"),r=e("available-typed-arrays"),o=e("call-bind/callBound"),s=o("Object.prototype.toString"),a=e("has-tostringtag/shams")(),c=e("gopd"),d="undefined"==typeof globalThis?i:globalThis,l=r(),u=o("Array.prototype.indexOf",!0)||function(e,t){for(var i=0;i<e.length;i+=1)if(e[i]===t)return i;return-1},h=o("String.prototype.slice"),f={},p=Object.getPrototypeOf;a&&c&&p&&n(l,(function(e){var t=new d[e];if(Symbol.toStringTag in t){var i=p(t),n=c(i,Symbol.toStringTag);if(!n){var r=p(i);n=c(r,Symbol.toStringTag)}f[e]=n.get}}));t.exports=function(e){if(!e||"object"!=typeof e)return!1;if(!a||!(Symbol.toStringTag in e)){var t=h(s(e),8,-1);return u(l,t)>-1}return!!c&&function(e){var t=!1;return n(f,(function(i,n){if(!t)try{t=i.call(e)===n}catch(e){}})),t}(e)}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"available-typed-arrays":16,"call-bind/callBound":69,"for-each":107,gopd:111,"has-tostringtag/shams":114}],151:[function(e,t,i){!function(e,i){"use strict";"function"==typeof define&&define.amd?define(i):"object"==typeof t&&t.exports?t.exports=i():e.log=i()}(this,(function(){"use strict";var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function s(t,i){for(var r=0;r<n.length;r++){var o=n[r];this[o]=r<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(s.call(this,i,n),this[e].apply(this,arguments))}}function c(n,s,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,r){var o,a=this;i=null==i?"WARN":i;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=r||c,a.getLevel=function(){return o},a.setLevel=function(i,r){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),s.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=i),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l}))},{}],152:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ExtensibleEvents=void 0;var n=e("./NamespacedMap"),r=e("./InvalidEventError"),o=e("./interpreters/legacy/MRoomMessage"),s=e("./interpreters/modern/MMessage"),a=e("./events/message_types"),c=e("./events/poll_types"),d=e("./interpreters/modern/MPoll");function l(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return u(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,r=function(){};return{s:r,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==i.return||i.return()}finally{if(a)throw o}}}}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function h(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function f(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var p=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),f(this,"interpreters",new n.NamespacedMap([[o.LEGACY_M_ROOM_MESSAGE,o.parseMRoomMessage],[a.M_MESSAGE,s.parseMMessage],[a.M_EMOTE,s.parseMMessage],[a.M_NOTICE,s.parseMMessage],[c.M_POLL_START,d.parseMPoll],[c.M_POLL_RESPONSE,d.parseMPoll],[c.M_POLL_END,d.parseMPoll]])),f(this,"_unknownInterpretOrder",[a.M_MESSAGE])}var t,i,u;return t=e,u=[{key:"defaultInstance",get:function(){return e._defaultInstance}},{key:"unknownInterpretOrder",get:function(){return e.defaultInstance.unknownInterpretOrder},set:function(t){e.defaultInstance.unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,i){e.defaultInstance.registerInterpreter(t,i)}},{key:"parse",value:function(t){return e.defaultInstance.parse(t)}}],(i=[{key:"unknownInterpretOrder",get:function(){var e;return null!==(e=this._unknownInterpretOrder)&&void 0!==e?e:[]},set:function(e){this._unknownInterpretOrder=e}},{key:"registerInterpreter",value:function(e,t){this.interpreters.set(e,t)}},{key:"parse",value:function(e){try{if(this.interpreters.hasNamespaced(e.type))return this.interpreters.getNamespaced(e.type)(e);var t,i=l(this.unknownInterpretOrder);try{for(i.s();!(t=i.n()).done;){var n=t.value;if(this.interpreters.has(n)){var o=this.interpreters.get(n)(e);if(o)return o}}}catch(e){i.e(e)}finally{i.f()}return null}catch(e){if(e instanceof r.InvalidEventError)return null;throw e}}}])&&h(t.prototype,i),u&&h(t,u),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.ExtensibleEvents=p,f(p,"_defaultInstance",new p)},{"./InvalidEventError":154,"./NamespacedMap":155,"./events/message_types":164,"./events/poll_types":165,"./interpreters/legacy/MRoomMessage":168,"./interpreters/modern/MMessage":169,"./interpreters/modern/MPoll":170}],153:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0})},{}],154:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function r(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function o(e){var t=c();return function(){var i,r=l(e);if(t){var o=l(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,i)}}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return a(e,arguments,l(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},s(e)}function a(e,t,i){return a=c()?Reflect.construct:function(e,t,i){var n=[null];n.push.apply(n,t);var r=new(Function.bind.apply(e,n));return i&&d(r,i.prototype),r},a.apply(null,arguments)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.InvalidEventError=void 0;var u=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&d(e,t)}(a,e);var t,i,n,s=o(a);function a(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),s.call(this,e)}return t=a,i&&r(t.prototype,i),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}(s(Error));i.InvalidEventError=u},{}],155:[function(e,t,i){"use strict";function n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return r(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function o(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}Object.defineProperty(i,"__esModule",{value:!0}),i.NamespacedMap=void 0;var s=function(){function e(t){var i,r,o;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),i=this,r="internalMap",o=new Map,r in i?Object.defineProperty(i,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[r]=o,t){var s,a=n(t);try{for(a.s();!(s=a.n()).done;){var c=s.value;this.set(c[0],c[1])}}catch(e){a.e(e)}finally{a.f()}}}var t,i,r;return t=e,(i=[{key:"get",value:function(e){return e.name&&this.internalMap.has(e.name)?this.internalMap.get(e.name):e.altName&&this.internalMap.has(e.altName)?this.internalMap.get(e.altName):null}},{key:"set",value:function(e,t){e.name&&this.internalMap.set(e.name,t),e.altName&&this.internalMap.set(e.altName,t)}},{key:"has",value:function(e){return!!this.get(e)}},{key:"delete",value:function(e){e.name&&this.internalMap.delete(e.name),e.altName&&this.internalMap.delete(e.altName)}},{key:"hasNamespaced",value:function(e){return this.internalMap.has(e)}},{key:"getNamespaced",value:function(e){return this.internalMap.get(e)}}])&&o(t.prototype,i),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.NamespacedMap=s},{}],156:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function r(e,t){return r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},r(e,t)}function o(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=s(e);if(t){var o=s(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,i)}}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(e,t,i){return t&&c(e.prototype,t),i&&c(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(i,"__esModule",{value:!0}),i.UnstableValue=i.NamespacedValue=void 0;var l=function(){function e(t,i){if(a(this,e),this.stable=t,this.unstable=i,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}return d(e,[{key:"name",get:function(){return this.stable?this.stable:this.unstable}},{key:"altName",get:function(){return this.stable?this.unstable:null}},{key:"matches",value:function(e){return!!this.name&&this.name===e||!!this.altName&&this.altName===e}},{key:"findIn",value:function(e){var t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}},{key:"includedIn",value:function(e){var t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}]),e}();i.NamespacedValue=l;var u=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&r(e,t)}(i,e);var t=o(i);function i(e,n){var r;if(a(this,i),!(r=t.call(this,e,n)).unstable)throw new Error("Unstable value must be supplied");return r}return d(i,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),i}(l);i.UnstableValue=u},{}],157:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.EmoteEvent=void 0;var r=e("./MessageEvent"),o=e("./message_types"),s=e("../utility/events");function a(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function c(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(){return d="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,i){var n=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}(e,t);if(n){var r=Object.getOwnPropertyDescriptor(n,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},d.apply(this,arguments)}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function u(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=h(e);if(t){var o=h(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,i)}}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}var f=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&l(e,t)}(f,e);var t,i,n,r=u(f);function f(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,f),r.call(this,e)}return t=f,n=[{key:"from",value:function(e,t){var i;return new f({type:o.M_EMOTE.name,content:(i={},a(i,o.M_TEXT.name,e),a(i,o.M_HTML.name,t),i)})}}],(i=[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,s.isEventTypeSame)(e,o.M_EMOTE)||d(h(f.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=d(h(f.prototype),"serialize",this).call(this);return e.content.msgtype="m.emote",e}}])&&c(t.prototype,i),n&&c(t,n),Object.defineProperty(t,"prototype",{writable:!1}),f}(r.MessageEvent);i.EmoteEvent=f},{"../utility/events":173,"./MessageEvent":159,"./message_types":164}],158:[function(e,t,i){"use strict";function n(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}Object.defineProperty(i,"__esModule",{value:!0}),i.ExtensibleEvent=void 0;var r=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.wireFormat=t}var t,i,r;return t=e,(i=[{key:"wireContent",get:function(){return this.wireFormat.content}}])&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.ExtensibleEvent=r},{}],159:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.MessageEvent=void 0;var r=e("./ExtensibleEvent"),o=e("../types"),s=e("../InvalidEventError"),a=e("./message_types"),c=e("../utility/events");function d(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function l(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?d(Object(i),!0).forEach((function(t){v(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):d(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function u(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function h(e,t){return h=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},h(e,t)}function f(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=g(e);if(t){var o=g(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return p(e)}(this,i)}}function p(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function g(e){return g=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},g(e)}function v(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var m=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(d,e);var t,i,n,r=f(d);function d(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,d),v(p(t=r.call(this,e)),"text",void 0),v(p(t),"html",void 0),v(p(t),"renderings",void 0);var i=a.M_MESSAGE.findIn(t.wireContent),n=a.M_TEXT.findIn(t.wireContent),c=a.M_HTML.findIn(t.wireContent);if((0,o.isProvided)(i)){if(!Array.isArray(i))throw new s.InvalidEventError("m.message contents must be an array");var l=i.find((function(e){return!(0,o.isProvided)(e.mimetype)||"text/plain"===e.mimetype})),u=i.find((function(e){return"text/html"===e.mimetype}));if(!l)throw new s.InvalidEventError("m.message is missing a plain text representation");t.text=l.body,t.html=null==u?void 0:u.body,t.renderings=i}else{if(!(0,o.isOptionalAString)(n))throw new s.InvalidEventError("Missing textual representation for event");t.text=n,t.html=c,t.renderings=[{body:n,mimetype:"text/plain"}],t.html&&t.renderings.push({body:t.html,mimetype:"text/html"})}return t}return t=d,n=[{key:"from",value:function(e,t){var i;return new d({type:a.M_MESSAGE.name,content:(i={},v(i,a.M_TEXT.name,e),v(i,a.M_HTML.name,t),i)})}}],(i=[{key:"isEmote",get:function(){return a.M_EMOTE.matches(this.wireFormat.type)||(0,o.isProvided)(a.M_EMOTE.findIn(this.wireFormat.content))}},{key:"isNotice",get:function(){return a.M_NOTICE.matches(this.wireFormat.type)||(0,o.isProvided)(a.M_NOTICE.findIn(this.wireFormat.content))}},{key:"isEquivalentTo",value:function(e){return(0,c.isEventTypeSame)(e,a.M_MESSAGE)}},{key:"serializeMMessageOnly",value:function(){var e=v({},a.M_MESSAGE.name,this.renderings);if(1===this.renderings.length){var t=this.renderings[0].mimetype;void 0!==t&&"text/plain"!==t||(e=v({},a.M_TEXT.name,this.renderings[0].body))}return e}},{key:"serialize",value:function(){var e;return{type:"m.room.message",content:l(l({},this.serializeMMessageOnly()),{},{body:this.text,msgtype:"m.text",format:this.html?"org.matrix.custom.html":void 0,formatted_body:null!==(e=this.html)&&void 0!==e?e:void 0})}}}])&&u(t.prototype,i),n&&u(t,n),Object.defineProperty(t,"prototype",{writable:!1}),d}(r.ExtensibleEvent);i.MessageEvent=m},{"../InvalidEventError":154,"../types":171,"../utility/events":173,"./ExtensibleEvent":158,"./message_types":164}],160:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.NoticeEvent=void 0;var r=e("./MessageEvent"),o=e("./message_types"),s=e("../utility/events");function a(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function c(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(){return d="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,i){var n=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}(e,t);if(n){var r=Object.getOwnPropertyDescriptor(n,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},d.apply(this,arguments)}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function u(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=h(e);if(t){var o=h(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,i)}}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}var f=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&l(e,t)}(f,e);var t,i,n,r=u(f);function f(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,f),r.call(this,e)}return t=f,n=[{key:"from",value:function(e,t){var i;return new f({type:o.M_NOTICE.name,content:(i={},a(i,o.M_TEXT.name,e),a(i,o.M_HTML.name,t),i)})}}],(i=[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,s.isEventTypeSame)(e,o.M_NOTICE)||d(h(f.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=d(h(f.prototype),"serialize",this).call(this);return e.content.msgtype="m.notice",e}}])&&c(t.prototype,i),n&&c(t,n),Object.defineProperty(t,"prototype",{writable:!1}),f}(r.MessageEvent);i.NoticeEvent=f},{"../utility/events":173,"./MessageEvent":159,"./message_types":164}],161:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.PollEndEvent=void 0;var r=e("./poll_types"),o=e("../InvalidEventError"),s=e("./relationship_types"),a=e("./MessageEvent"),c=e("./message_types"),d=e("../utility/events");function l(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function u(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?l(Object(i),!0).forEach((function(t){m(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):l(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function h(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function f(e,t){return f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},f(e,t)}function p(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=v(e);if(t){var o=v(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return g(e)}(this,i)}}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function v(e){return v=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},v(e)}function m(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var y=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}(v,e);var t,i,n,l=p(v);function v(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,v),m(g(t=l.call(this,e)),"pollEventId",void 0),m(g(t),"closingMessage",void 0);var i=t.wireContent["m.relates_to"];if(!s.REFERENCE_RELATION.matches(null==i?void 0:i.rel_type)||"string"!=typeof(null==i?void 0:i.event_id))throw new o.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=i.event_id,t.closingMessage=new a.MessageEvent(t.wireFormat),t}return t=v,n=[{key:"from",value:function(e,t){var i;return new v({type:r.M_POLL_END.name,content:(i={"m.relates_to":{rel_type:s.REFERENCE_RELATION.name,event_id:e}},m(i,r.M_POLL_END.name,{}),m(i,c.M_TEXT.name,t),i)})}}],(i=[{key:"isEquivalentTo",value:function(e){return(0,d.isEventTypeSame)(e,r.M_POLL_END)}},{key:"serialize",value:function(){return{type:r.M_POLL_END.name,content:u(m({"m.relates_to":{rel_type:s.REFERENCE_RELATION.name,event_id:this.pollEventId}},r.M_POLL_END.name,{}),this.closingMessage.serialize().content)}}}])&&h(t.prototype,i),n&&h(t,n),Object.defineProperty(t,"prototype",{writable:!1}),v}(e("./ExtensibleEvent").ExtensibleEvent);i.PollEndEvent=y},{"../InvalidEventError":154,"../utility/events":173,"./ExtensibleEvent":158,"./MessageEvent":159,"./message_types":164,"./poll_types":165,"./relationship_types":166}],162:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.PollResponseEvent=void 0;var r=e("./ExtensibleEvent"),o=e("./poll_types"),s=e("../InvalidEventError"),a=e("./relationship_types"),c=e("../utility/events");function d(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function u(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=f(e);if(t){var o=f(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return h(e)}(this,i)}}function h(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}function p(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var g=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&l(e,t)}(f,e);var t,i,n,r=u(f);function f(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,f),p(h(t=r.call(this,e)),"internalAnswerIds",void 0),p(h(t),"internalSpoiled",void 0),p(h(t),"pollEventId",void 0);var i=t.wireContent["m.relates_to"];if(!a.REFERENCE_RELATION.matches(null==i?void 0:i.rel_type)||"string"!=typeof(null==i?void 0:i.event_id))throw new s.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=i.event_id,t.validateAgainst(null),t}return t=f,n=[{key:"from",value:function(e,t){return new f({type:o.M_POLL_RESPONSE.name,content:p({"m.relates_to":{rel_type:a.REFERENCE_RELATION.name,event_id:t}},o.M_POLL_RESPONSE.name,{answers:e})})}}],(i=[{key:"answerIds",get:function(){return this.internalAnswerIds}},{key:"spoiled",get:function(){return this.internalSpoiled}},{key:"validateAgainst",value:function(e){var t=o.M_POLL_RESPONSE.findIn(this.wireContent);if(!Array.isArray(null==t?void 0:t.answers))return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);var i=t.answers;if(i.some((function(e){return"string"!=typeof e}))||0===i.length)return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);if(e){if(i.some((function(t){return!e.answers.some((function(e){return e.id===t}))})))return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);i=i.slice(0,e.maxSelections)}this.internalAnswerIds=i,this.internalSpoiled=!1}},{key:"isEquivalentTo",value:function(e){return(0,c.isEventTypeSame)(e,o.M_POLL_RESPONSE)}},{key:"serialize",value:function(){return{type:o.M_POLL_RESPONSE.name,content:p({"m.relates_to":{rel_type:a.REFERENCE_RELATION.name,event_id:this.pollEventId}},o.M_POLL_RESPONSE.name,{answers:this.spoiled?void 0:this.answerIds})}}}])&&d(t.prototype,i),n&&d(t,n),Object.defineProperty(t,"prototype",{writable:!1}),f}(r.ExtensibleEvent);i.PollResponseEvent=g},{"../InvalidEventError":154,"../utility/events":173,"./ExtensibleEvent":158,"./poll_types":165,"./relationship_types":166}],163:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.PollStartEvent=i.PollAnswerSubevent=void 0;var r=e("./poll_types"),o=e("./MessageEvent"),s=e("./message_types"),a=e("../InvalidEventError"),c=e("../NamespacedValue"),d=e("../utility/events"),l=e("./ExtensibleEvent");function u(e){return function(e){if(Array.isArray(e))return h(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return h(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return h(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function f(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function p(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?f(Object(i),!0).forEach((function(t){w(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):f(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function m(e,t,i){return t&&v(e.prototype,t),i&&v(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&b(e,t)}function b(e,t){return b=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},b(e,t)}function S(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=E(e);if(t){var o=E(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _(e)}(this,i)}}function _(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function E(e){return E=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},E(e)}function w(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var T=function(e){y(i,e);var t=S(i);function i(e){var n;g(this,i),w(_(n=t.call(this,e)),"id",void 0);var r=e.content.id;if(!r||"string"!=typeof r)throw new a.InvalidEventError("Answer ID must be a non-empty string");return n.id=r,n}return m(i,[{key:"serialize",value:function(){return{type:"org.matrix.sdk.poll.answer",content:p({id:this.id},this.serializeMMessageOnly())}}}],[{key:"from",value:function(e,t){return new i({type:"org.matrix.sdk.poll.answer",content:w({id:e},s.M_TEXT.name,t)})}}]),i}(o.MessageEvent);i.PollAnswerSubevent=T;var I=function(e){y(i,e);var t=S(i);function i(e){var n;g(this,i),w(_(n=t.call(this,e)),"question",void 0),w(_(n),"kind",void 0),w(_(n),"rawKind",void 0),w(_(n),"maxSelections",void 0),w(_(n),"answers",void 0);var s=r.M_POLL_START.findIn(n.wireContent);if(!s.question)throw new a.InvalidEventError("A question is required");if(n.question=new o.MessageEvent({type:"org.matrix.sdk.poll.question",content:s.question}),n.rawKind=s.kind,r.M_POLL_KIND_DISCLOSED.matches(n.rawKind)?n.kind=r.M_POLL_KIND_DISCLOSED:n.kind=r.M_POLL_KIND_UNDISCLOSED,n.maxSelections=Number.isFinite(s.max_selections)&&s.max_selections>0?s.max_selections:1,!Array.isArray(s.answers))throw new a.InvalidEventError("Poll answers must be an array");var c=s.answers.slice(0,20).map((function(e){return new T({type:"org.matrix.sdk.poll.answer",content:e})}));if(c.length<=0)throw new a.InvalidEventError("No answers available");return n.answers=c,n}return m(i,[{key:"isEquivalentTo",value:function(e){return(0,d.isEventTypeSame)(e,r.M_POLL_START)}},{key:"serialize",value:function(){var e;return{type:r.M_POLL_START.name,content:(e={},w(e,r.M_POLL_START.name,{question:this.question.serialize().content,kind:this.rawKind,max_selections:this.maxSelections,answers:this.answers.map((function(e){return e.serialize().content}))}),w(e,s.M_TEXT.name,"".concat(this.question.text,"\n").concat(this.answers.map((function(e,t){return"".concat(t+1,". ").concat(e.text)})).join("\n"))),e)}}}],[{key:"from",value:function(e,t,n){var o,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return new i({type:r.M_POLL_START.name,content:(o={},w(o,s.M_TEXT.name,e),w(o,r.M_POLL_START.name,{question:w({},s.M_TEXT.name,e),kind:n instanceof c.NamespacedValue?n.name:n,max_selections:a,answers:t.map((function(e){return w({id:u(Array(16)).map((function(){return R.charAt(Math.floor(Math.random()*R.length))})).join("")},s.M_TEXT.name,e)}))}),o)})}}]),i}(l.ExtensibleEvent);i.PollStartEvent=I;var R="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"},{"../InvalidEventError":154,"../NamespacedValue":156,"../utility/events":173,"./ExtensibleEvent":158,"./MessageEvent":159,"./message_types":164,"./poll_types":165}],164:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_TEXT=i.M_NOTICE=i.M_MESSAGE=i.M_HTML=i.M_EMOTE=void 0;var n=e("../NamespacedValue"),r=new n.UnstableValue("m.message","org.matrix.msc1767.message");i.M_MESSAGE=r;var o=new n.UnstableValue("m.text","org.matrix.msc1767.text");i.M_TEXT=o;var s=new n.UnstableValue("m.html","org.matrix.msc1767.html");i.M_HTML=s;var a=new n.UnstableValue("m.emote","org.matrix.msc1767.emote");i.M_EMOTE=a;var c=new n.UnstableValue("m.notice","org.matrix.msc1767.notice");i.M_NOTICE=c},{"../NamespacedValue":156}],165:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_POLL_START=i.M_POLL_RESPONSE=i.M_POLL_KIND_UNDISCLOSED=i.M_POLL_KIND_DISCLOSED=i.M_POLL_END=void 0;var n=e("../NamespacedValue"),r=new n.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");i.M_POLL_KIND_DISCLOSED=r;var o=new n.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");i.M_POLL_KIND_UNDISCLOSED=o;var s=new n.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");i.M_POLL_START=s;var a=new n.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");i.M_POLL_RESPONSE=a;var c=new n.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");i.M_POLL_END=c},{"../NamespacedValue":156}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REFERENCE_RELATION=void 0;var n=new(e("../NamespacedValue").NamespacedValue)("m.reference");i.REFERENCE_RELATION=n},{"../NamespacedValue":156}],167:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=e("./ExtensibleEvents");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===n[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return n[e]}}))}));var r=e("./IPartialEvent");Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===r[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return r[e]}}))}));var o=e("./InvalidEventError");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===o[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return o[e]}}))}));var s=e("./NamespacedValue");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return s[e]}}))}));var a=e("./NamespacedMap");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=e("./types");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===c[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return c[e]}}))}));var d=e("./utility/MessageMatchers");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===d[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return d[e]}}))}));var l=e("./utility/events");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===l[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return l[e]}}))}));var u=e("./interpreters/legacy/MRoomMessage");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return u[e]}}))}));var h=e("./interpreters/modern/MMessage");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===h[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return h[e]}}))}));var f=e("./interpreters/modern/MPoll");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===f[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./events/relationship_types");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===p[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return p[e]}}))}));var g=e("./events/ExtensibleEvent");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===g[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return g[e]}}))}));var v=e("./events/message_types");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===v[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./events/MessageEvent");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===m[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./events/EmoteEvent");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===y[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return y[e]}}))}));var b=e("./events/NoticeEvent");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===b[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return b[e]}}))}));var S=e("./events/poll_types");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===S[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return S[e]}}))}));var _=e("./events/PollStartEvent");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===_[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _[e]}}))}));var E=e("./events/PollResponseEvent");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===E[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return E[e]}}))}));var w=e("./events/PollEndEvent");Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===w[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return w[e]}}))}))},{"./ExtensibleEvents":152,"./IPartialEvent":153,"./InvalidEventError":154,"./NamespacedMap":155,"./NamespacedValue":156,"./events/EmoteEvent":157,"./events/ExtensibleEvent":158,"./events/MessageEvent":159,"./events/NoticeEvent":160,"./events/PollEndEvent":161,"./events/PollResponseEvent":162,"./events/PollStartEvent":163,"./events/message_types":164,"./events/poll_types":165,"./events/relationship_types":166,"./interpreters/legacy/MRoomMessage":168,"./interpreters/modern/MMessage":169,"./interpreters/modern/MPoll":170,"./types":171,"./utility/MessageMatchers":172,"./utility/events":173}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LEGACY_M_ROOM_MESSAGE=void 0,i.parseMRoomMessage=function(e){var t,i,s;if(a.M_MESSAGE.findIn(e.content)||a.M_TEXT.findIn(e.content))return new n.MessageEvent(e);var c,u=null===(t=e.content)||void 0===t?void 0:t.msgtype,h=null===(i=e.content)||void 0===i?void 0:i.body,f="org.matrix.custom.html"===(null===(s=e.content)||void 0===s?void 0:s.format)?e.content.formatted_body:null;return"m.text"===u?new n.MessageEvent(d(d({},e),{},{content:d(d({},e.content),{},(c={},l(c,a.M_TEXT.name,h),l(c,a.M_HTML.name,f),c))})):"m.notice"===u?new r.NoticeEvent(d(d({},e),{},{content:d(d({},e.content),{},(p={},l(p,a.M_TEXT.name,h),l(p,a.M_HTML.name,f),p))})):"m.emote"===u?new o.EmoteEvent(d(d({},e),{},{content:d(d({},e.content),{},(g={},l(g,a.M_TEXT.name,h),l(g,a.M_HTML.name,f),g))})):null;var p,g};var n=e("../../events/MessageEvent"),r=e("../../events/NoticeEvent"),o=e("../../events/EmoteEvent"),s=e("../../NamespacedValue"),a=e("../../events/message_types");function c(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function d(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?c(Object(i),!0).forEach((function(t){l(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):c(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function l(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var u=new s.NamespacedValue("m.room.message");i.LEGACY_M_ROOM_MESSAGE=u},{"../../NamespacedValue":156,"../../events/EmoteEvent":157,"../../events/MessageEvent":159,"../../events/NoticeEvent":160,"../../events/message_types":164}],169:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.parseMMessage=function(e){if(r.M_EMOTE.matches(e.type))return new o.EmoteEvent(e);if(r.M_NOTICE.matches(e.type))return new s.NoticeEvent(e);return new n.MessageEvent(e)};var n=e("../../events/MessageEvent"),r=e("../../events/message_types"),o=e("../../events/EmoteEvent"),s=e("../../events/NoticeEvent")},{"../../events/EmoteEvent":157,"../../events/MessageEvent":159,"../../events/NoticeEvent":160,"../../events/message_types":164}],170:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.parseMPoll=function(e){if(n.M_POLL_START.matches(e.type))return new r.PollStartEvent(e);if(n.M_POLL_RESPONSE.matches(e.type))return new o.PollResponseEvent(e);if(n.M_POLL_END.matches(e.type))return new s.PollEndEvent(e);return null};var n=e("../../events/poll_types"),r=e("../../events/PollStartEvent"),o=e("../../events/PollResponseEvent"),s=e("../../events/PollEndEvent")},{"../../events/PollEndEvent":161,"../../events/PollResponseEvent":162,"../../events/PollStartEvent":163,"../../events/poll_types":165}],171:[function(e,t,i){"use strict";function n(e){return null!=e}Object.defineProperty(i,"__esModule",{value:!0}),i.isOptionalAString=function(e){return n(e)&&"string"==typeof e},i.isProvided=n},{}],172:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LegacyMsgType=void 0,i.isEventLike=function(e,t){var i=e.content;if(t===n.Text)return r.M_MESSAGE.matches(e.type)||"m.room.message"===e.type&&"m.text"===(null==i?void 0:i.msgtype);if(t===n.Emote)return r.M_EMOTE.matches(e.type)||"m.room.message"===e.type&&"m.emote"===(null==i?void 0:i.msgtype);if(t===n.Notice)return r.M_NOTICE.matches(e.type)||"m.room.message"===e.type&&"m.notice"===(null==i?void 0:i.msgtype);return!1};var n,r=e("../events/message_types");i.LegacyMsgType=n,function(e){e.Text="m.text",e.Notice="m.notice",e.Emote="m.emote"}(n||(i.LegacyMsgType=n={}))},{"../events/message_types":164}],173:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isEventTypeSame=function(e,t){if("string"==typeof e)return"string"==typeof t?t===e:t.matches(e);if("string"==typeof t)return e.matches(t);var i=t,n=e;return i.matches(n.name)||i.matches(n.altName)}},{}],174:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.ClientWidgetApi=void 0;var r=e("events"),o=e("./transport/PostmessageTransport"),s=e("./interfaces/WidgetApiDirection"),a=e("./interfaces/WidgetApiAction"),c=e("./interfaces/Capabilities"),d=e("./interfaces/ApiVersion"),l=e("./models/WidgetEventCapability"),u=e("./interfaces/GetOpenIDAction"),h=e("./util/SimpleObservable"),f=e("./Symbols");function p(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */p=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},o=r.iterator||"@@iterator",s=r.asyncIterator||"@@asyncIterator",a=r.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function d(e,t,i,n){var r=t&&t.prototype instanceof h?t:h,o=Object.create(r.prototype),s=new I(n||[]);return o._invoke=function(e,t,i){var n="suspendedStart";return function(r,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===r)throw o;return M()}for(i.method=r,i.arg=o;;){var s=i.delegate;if(s){var a=E(s,i);if(a){if(a===u)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var c=l(e,t,i);if("normal"===c.type){if(n=i.done?"completed":"suspendedYield",c.arg===u)continue;return{value:c.arg,done:i.done}}"throw"===c.type&&(n="completed",i.method="throw",i.arg=c.arg)}}}(e,i,s),o}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=d;var u={};function h(){}function f(){}function g(){}var v={};c(v,o,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(R([])));y&&y!==t&&i.call(y,o)&&(v=y);var b=g.prototype=h.prototype=Object.create(v);function S(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,s,a,c){var d=l(e[o],e,s);if("throw"!==d.type){var u=d.arg,h=u.value;return h&&"object"==n(h)&&i.call(h,"__await")?t.resolve(h.__await).then((function(e){r("next",e,a,c)}),(function(e){r("throw",e,a,c)})):t.resolve(h).then((function(e){u.value=e,a(u)}),(function(e){return r("throw",e,a,c)}))}c(d.arg)}var o;this._invoke=function(e,i){function n(){return new t((function(t,n){r(e,i,t,n)}))}return o=o?o.then(n,n):n()}}function E(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,E(e,t),"throw"===t.method))return u;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return u}var n=l(i,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,u;var r=n.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,u):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,u)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function R(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n<e.length;)if(i.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return r.next=r}}return{next:M}}function M(){return{value:void 0,done:!0}}return f.prototype=g,c(b,"constructor",g),c(g,"constructor",f),f.displayName=c(g,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===f||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,c(e,a,"GeneratorFunction")),e.prototype=Object.create(b),e},e.awrap=function(e){return{__await:e}},S(_.prototype),c(_.prototype,s,(function(){return this})),e.AsyncIterator=_,e.async=function(t,i,n,r,o){void 0===o&&(o=Promise);var s=new _(d(t,i,n,r),o);return e.isGeneratorFunction(i)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},S(b),c(b,a,"Generator"),c(b,o,(function(){return this})),c(b,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var n=t.pop();if(n in e)return i.value=n,i.done=!1,i}return i.done=!0,i}},e.values=R,I.prototype={constructor:I,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(i,n){return s.type="throw",s.arg=e,t.next=i,n&&(t.method="next",t.arg=void 0),!!n}for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r],s=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=i.call(o,"catchLoc"),c=i.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,u):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),u},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;T(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:R(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}function g(e,t,i,n,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void i(e)}a.done?t(c):Promise.resolve(c).then(n,r)}function v(e){return function(){var t=this,i=arguments;return new Promise((function(n,r){var o=e.apply(t,i);function s(e){g(o,n,r,s,a,"next",e)}function a(e){g(o,n,r,s,a,"throw",e)}s(void 0)}))}}function m(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return y(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return y(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,r=function(){};return{s:r,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==i.return||i.return()}finally{if(a)throw o}}}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function b(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function S(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?b(Object(i),!0).forEach((function(t){R(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):b(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function _(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function E(e,t){return E=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},E(e,t)}function w(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=I(e);if(t){var o=I(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return T(e)}(this,i)}}function T(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function I(e){return I=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},I(e)}function R(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function M(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new k(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function k(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return k=function(e){this.s=e,this.n=e.next},k.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new k(e)}var C=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&E(e,t)}(P,e);var t,i,n,r,g,y,b,I,k,C,O,A=w(P);function P(e,t,i){var n;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,P),(n=A.call(this)).widget=e,n.iframe=t,n.driver=i,R(T(n),"transport",void 0),R(T(n),"contentLoadedActionSent",!1),R(T(n),"allowedCapabilities",new Set),R(T(n),"allowedEvents",[]),R(T(n),"isStopped",!1),R(T(n),"turnServers",null),null==t||!t.contentWindow)throw new Error("No iframe supplied");if(!e)throw new Error("Invalid widget");if(!i)throw new Error("Invalid driver");return n.transport=new o.PostmessageTransport(s.WidgetApiDirection.ToWidget,e.id,t.contentWindow,window),n.transport.targetOrigin=e.origin,n.transport.on("message",n.handleMessage.bind(T(n))),t.addEventListener("load",n.onIframeLoad.bind(T(n))),n.transport.start(),n}return t=P,i=[{key:"hasCapability",value:function(e){return this.allowedCapabilities.has(e)}},{key:"canUseRoomTimeline",value:function(e){return this.hasCapability("org.matrix.msc2762.timeline:".concat(f.Symbols.AnyRoom))||this.hasCapability("org.matrix.msc2762.timeline:".concat(e))}},{key:"canSendRoomEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(i){return i.matchesAsRoomEvent(l.EventDirection.Send,e,t)}))}},{key:"canSendStateEvent",value:function(e,t){return this.allowedEvents.some((function(i){return i.matchesAsStateEvent(l.EventDirection.Send,e,t)}))}},{key:"canSendToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(l.EventDirection.Send,e)}))}},{key:"canReceiveRoomEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(i){return i.matchesAsRoomEvent(l.EventDirection.Receive,e,t)}))}},{key:"canReceiveStateEvent",value:function(e,t){return this.allowedEvents.some((function(i){return i.matchesAsStateEvent(l.EventDirection.Receive,e,t)}))}},{key:"canReceiveToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(l.EventDirection.Receive,e)}))}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"beginCapabilities",value:function(){var e,t=this;this.emit("preparing"),this.transport.send(a.WidgetApiToWidgetAction.Capabilities,{}).then((function(i){return e=i.capabilities,t.driver.validateCapabilities(new Set(i.capabilities))})).then((function(i){console.log("Widget ".concat(t.widget.id," is allowed capabilities:"),Array.from(i)),t.allowedCapabilities=i,t.allowedEvents=l.WidgetEventCapability.findEventCapabilities(i),t.notifyCapabilities(e),t.emit("ready")}))}},{key:"notifyCapabilities",value:function(e){var t=this;this.transport.send(a.WidgetApiToWidgetAction.NotifyCapabilities,{requested:e,approved:Array.from(this.allowedCapabilities)}).catch((function(e){console.warn("non-fatal error notifying widget of approved capabilities:",e)})).then((function(){t.emit("capabilitiesNotified")}))}},{key:"onIframeLoad",value:function(e){this.widget.waitForIframeLoad?this.beginCapabilities():this.contentLoadedActionSent=!1}},{key:"handleContentLoadedAction",value:function(e){if(this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)");this.widget.waitForIframeLoad?this.transport.reply(e,{error:{message:"Improper sequence: not expecting ContentLoaded event if waitForIframLoad is true (default=true)"}}):(this.transport.reply(e,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:d.CurrentApiVersions})}},{key:"handleCapabilitiesRenegotiate",value:function(e){var t,i=this;this.transport.reply(e,{});var n=(null===(t=e.data)||void 0===t?void 0:t.capabilities)||[],r=new Set(n.filter((function(e){return!i.hasCapability(e)})));if(0===r.size)return this.notifyCapabilities([]);this.driver.validateCapabilities(r).then((function(e){return e.forEach((function(e){return i.allowedCapabilities.add(e)})),l.WidgetEventCapability.findEventCapabilities(e).forEach((function(e){return i.allowedEvents.push(e)})),i.notifyCapabilities(Array.from(r))}))}},{key:"handleNavigate",value:function(e){var t,i,n=this;if(!this.hasCapability(c.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(e,{error:{message:"Missing capability"}});if(null===(t=e.data)||void 0===t||!t.uri||null===(i=e.data)||void 0===i||!i.uri.toString().startsWith("https://matrix.to/#"))return this.transport.reply(e,{error:{message:"Invalid matrix.to URI"}});var r=function(t){return console.error("[ClientWidgetApi] Failed to handle navigation: ",t),n.transport.reply(e,{error:{message:"Error handling navigation"}})};try{this.driver.navigate(e.data.uri.toString()).catch((function(e){return r(e)})).then((function(){return n.transport.reply(e,{})}))}catch(e){return r(e)}}},{key:"handleOIDC",value:function(e){var t=this,i=1,n=function(n,r){return r=r||{},i>1?t.transport.send(a.WidgetApiToWidgetAction.OpenIDCredentials,S({state:n,original_request_id:e.requestId},r)):t.transport.reply(e,S({state:n},r))},r=function(r){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",r),i>1?n(u.OpenIDRequestState.Blocked):t.transport.reply(e,{error:{message:r}})},o=new h.SimpleObservable((function(e){return e.state===u.OpenIDRequestState.PendingUserConfirmation&&i>1?(o.close(),r("client provided out-of-phase response to OIDC flow")):e.state===u.OpenIDRequestState.PendingUserConfirmation?(n(e.state),void i++):e.state!==u.OpenIDRequestState.Allowed||e.token?(e.state===u.OpenIDRequestState.Blocked&&(e.token=void 0),o.close(),n(e.state,e.token)):r("client provided invalid OIDC token for an allowed request")}));this.driver.askOpenID(o)}},{key:"handleReadEvents",value:function(e){var t=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(void 0!==e.data.limit&&(!e.data.limit||e.data.limit<0))return this.transport.reply(e,{error:{message:"Invalid request - limit out of range"}});var i=null;if(e.data.room_ids){i=e.data.room_ids,Array.isArray(i)||(i=[i]);var n,r=m(i);try{for(r.s();!(n=r.n()).done;){var o=n.value;if(!this.canUseRoomTimeline(o))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(o)}})}}catch(e){r.e(e)}finally{r.f()}}var s=e.data.limit||0,a=Promise.resolve([]);if(void 0!==e.data.state_key){var c=!0===e.data.state_key?void 0:e.data.state_key.toString();if(!this.canReceiveStateEvent(e.data.type,null!=c?c:null))return this.transport.reply(e,{error:{message:"Cannot read state events of this type"}});a=this.driver.readStateEvents(e.data.type,c,s,i)}else{if(!this.canReceiveRoomEvent(e.data.type,e.data.msgtype))return this.transport.reply(e,{error:{message:"Cannot read room events of this type"}});a=this.driver.readRoomEvents(e.data.type,e.data.msgtype,s,i)}return a.then((function(i){return t.transport.reply(e,{events:i})}))}},{key:"handleSendEvent",value:function(e){var t,i=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(e.data.room_id&&!this.canUseRoomTimeline(e.data.room_id))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(e.data.room_id)}});if(null!==e.data.state_key&&void 0!==e.data.state_key){if(!this.canSendStateEvent(e.data.type,e.data.state_key))return this.transport.reply(e,{error:{message:"Cannot send state events of this type"}});t=this.driver.sendEvent(e.data.type,e.data.content||{},e.data.state_key,e.data.room_id)}else{var n=e.data.content||{},r=n.msgtype;if(!this.canSendRoomEvent(e.data.type,r))return this.transport.reply(e,{error:{message:"Cannot send room events of this type"}});t=this.driver.sendEvent(e.data.type,n,null,e.data.room_id)}t.then((function(t){return i.transport.reply(e,{room_id:t.roomId,event_id:t.eventId})})).catch((function(t){return console.error("error sending event: ",t),i.transport.reply(e,{error:{message:"Error sending event"}})}))}},{key:"handleSendToDevice",value:(O=v(p().mark((function e(t){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.type){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Invalid request - missing event type"}});case 3:case 8:case 13:case 18:case 25:e.next=32;break;case 5:if(t.data.messages){e.next=10;break}return e.next=8,this.transport.reply(t,{error:{message:"Invalid request - missing event contents"}});case 10:if("boolean"==typeof t.data.encrypted){e.next=15;break}return e.next=13,this.transport.reply(t,{error:{message:"Invalid request - missing encryption flag"}});case 15:if(this.canSendToDeviceEvent(t.data.type)){e.next=20;break}return e.next=18,this.transport.reply(t,{error:{message:"Cannot send to-device events of this type"}});case 20:return e.prev=20,e.next=23,this.driver.sendToDevice(t.data.type,t.data.encrypted,t.data.messages);case 23:return e.next=25,this.transport.reply(t,{});case 27:return e.prev=27,e.t0=e.catch(20),console.error("error sending to-device event",e.t0),e.next=32,this.transport.reply(t,{error:{message:"Error sending event"}});case 32:case"end":return e.stop()}}),e,this,[[20,27]])}))),function(e){return O.apply(this,arguments)})},{key:"pollTurnServers",value:(C=v(p().mark((function e(t,i){var n,r,o,s,c,d;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.transport.send(a.WidgetApiToWidgetAction.UpdateTurnServers,i);case 3:n=!1,r=!1,e.prev=5,s=M(t);case 7:return e.next=9,s.next();case 9:if(!(n=!(c=e.sent).done)){e.next=16;break}return d=c.value,e.next=13,this.transport.send(a.WidgetApiToWidgetAction.UpdateTurnServers,d);case 13:n=!1,e.next=7;break;case 16:e.next=22;break;case 18:e.prev=18,e.t0=e.catch(5),r=!0,o=e.t0;case 22:if(e.prev=22,e.prev=23,!n||null==s.return){e.next=27;break}return e.next=27,s.return();case 27:if(e.prev=27,!r){e.next=30;break}throw o;case 30:return e.finish(27);case 31:return e.finish(22);case 32:e.next=37;break;case 34:e.prev=34,e.t1=e.catch(0),console.error("error polling for TURN servers",e.t1);case 37:case"end":return e.stop()}}),e,this,[[0,34],[5,18,22,32],[23,,27,31]])}))),function(e,t){return C.apply(this,arguments)})},{key:"handleWatchTurnServers",value:(k=v(p().mark((function e(t){var i,n,r,o;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=30;break;case 5:if(!this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.prev=10,i=this.driver.getTurnServers(),e.next=14,i.next();case 14:if(n=e.sent,r=n.done,o=n.value,!r){e.next=19;break}throw new Error("Client refuses to provide any TURN servers");case 19:return e.next=21,this.transport.reply(t,{});case 21:this.pollTurnServers(i,o),this.turnServers=i,e.next=30;break;case 25:return e.prev=25,e.t0=e.catch(10),console.error("error getting first TURN server results",e.t0),e.next=30,this.transport.reply(t,{error:{message:"TURN servers not available"}});case 30:case"end":return e.stop()}}),e,this,[[10,25]])}))),function(e){return k.apply(this,arguments)})},{key:"handleUnwatchTurnServers",value:(I=v(p().mark((function e(t){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=15;break;case 5:if(this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.next=12,this.turnServers.return(void 0);case 12:return this.turnServers=null,e.next=15,this.transport.reply(t,{});case 15:case"end":return e.stop()}}),e,this)}))),function(e){return I.apply(this,arguments)})},{key:"handleReadRelations",value:(b=v(p().mark((function e(t){var i,n,r=this;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.event_id){e.next=2;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(void 0!==t.data.limit&&t.data.limit<0)){e.next=4;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - limit out of range"}}));case 4:if(void 0===t.data.room_id||this.canUseRoomTimeline(t.data.room_id)){e.next=6;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Unable to access room timeline: ".concat(t.data.room_id)}}));case 6:return e.prev=6,e.next=9,this.driver.readEventRelations(t.data.event_id,t.data.room_id,t.data.rel_type,t.data.event_type,t.data.from,t.data.to,t.data.limit,t.data.direction);case 9:return i=e.sent,n=i.chunk.filter((function(e){return void 0!==e.state_key?r.canReceiveStateEvent(e.type,e.state_key):r.canReceiveRoomEvent(e.type,e.content.msgtype)})),e.abrupt("return",this.transport.reply(t,{chunk:n,prev_batch:i.prevBatch,next_batch:i.nextBatch}));case 14:return e.prev=14,e.t0=e.catch(6),console.error("error getting the relations",e.t0),e.next=19,this.transport.reply(t,{error:{message:"Unexpected error while reading relations"}});case 19:case"end":return e.stop()}}),e,this,[[6,14]])}))),function(e){return b.apply(this,arguments)})},{key:"handleUserDirectorySearch",value:(y=v(p().mark((function e(t){var i;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3973UserDirectorySearch)){e.next=2;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Missing capability"}}));case 2:if("string"==typeof t.data.search_term){e.next=4;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - missing search term"}}));case 4:if(!(void 0!==t.data.limit&&t.data.limit<0)){e.next=6;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - limit out of range"}}));case 6:return e.prev=6,e.next=9,this.driver.searchUserDirectory(t.data.search_term,t.data.limit);case 9:return i=e.sent,e.abrupt("return",this.transport.reply(t,{limited:i.limited,results:i.results.map((function(e){return{user_id:e.userId,display_name:e.displayName,avatar_url:e.avatarUrl}}))}));case 13:return e.prev=13,e.t0=e.catch(6),console.error("error searching in the user directory",e.t0),e.next=18,this.transport.reply(t,{error:{message:"Unexpected error while searching in the user directory"}});case 18:case"end":return e.stop()}}),e,this,[[6,13]])}))),function(e){return y.apply(this,arguments)})},{key:"handleMessage",value:function(e){if(!this.isStopped){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case a.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(e.detail);case a.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case a.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(e.detail);case a.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(e.detail);case a.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(e.detail);case a.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(e.detail);case a.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(e.detail);case a.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(e.detail);case a.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(e.detail);case a.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(e.detail);case a.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(e.detail);case a.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:return this.handleUserDirectorySearch(e.detail);default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}}},{key:"takeScreenshot",value:function(){return this.transport.send(a.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.UpdateVisibility,{visible:e})}},{key:"sendWidgetConfig",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.WidgetConfig,e).then()}},{key:"notifyModalWidgetButtonClicked",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.ButtonClicked,{id:e}).then()}},{key:"notifyModalWidgetClose",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.CloseModalWidget,e).then()}},{key:"feedEvent",value:(g=v(p().mark((function e(t,i){var n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.room_id===i||this.canUseRoomTimeline(t.room_id)){e.next=2;break}return e.abrupt("return");case 2:if(void 0===t.state_key||null===t.state_key){e.next=7;break}if(this.canReceiveStateEvent(t.type,t.state_key)){e.next=5;break}return e.abrupt("return");case 5:e.next=9;break;case 7:if(this.canReceiveRoomEvent(t.type,null===(n=t.content)||void 0===n?void 0:n.msgtype)){e.next=9;break}return e.abrupt("return");case 9:return e.next=11,this.transport.send(a.WidgetApiToWidgetAction.SendEvent,t);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t){return g.apply(this,arguments)})},{key:"feedToDevice",value:(r=v(p().mark((function e(t,i){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.canReceiveToDeviceEvent(t.type)){e.next=3;break}return e.next=3,this.transport.send(a.WidgetApiToWidgetAction.SendToDevice,S(S({},t),{},{encrypted:i}));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})}],i&&_(t.prototype,i),n&&_(t,n),Object.defineProperty(t,"prototype",{writable:!1}),P}(r.EventEmitter);i.ClientWidgetApi=C},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/Capabilities":180,"./interfaces/GetOpenIDAction":183,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,"./util/SimpleObservable":220,events:105}],175:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.Symbols=void 0,i.Symbols=n,function(e){e.AnyRoom="*"}(n||(i.Symbols=n={}))},{}],176:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetApi=void 0;var r=e("events"),o=e("./interfaces/WidgetApiDirection"),s=e("./interfaces/ApiVersion"),a=e("./transport/PostmessageTransport"),c=e("./interfaces/WidgetApiAction"),d=e("./interfaces/GetOpenIDAction"),l=e("./interfaces/WidgetType"),u=e("./interfaces/ModalWidgetActions"),h=e("./models/WidgetEventCapability"),f=e("./Symbols");function p(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */p=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},o=r.iterator||"@@iterator",s=r.asyncIterator||"@@asyncIterator",a=r.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function d(e,t,i,n){var r=t&&t.prototype instanceof h?t:h,o=Object.create(r.prototype),s=new I(n||[]);return o._invoke=function(e,t,i){var n="suspendedStart";return function(r,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===r)throw o;return M()}for(i.method=r,i.arg=o;;){var s=i.delegate;if(s){var a=E(s,i);if(a){if(a===u)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var c=l(e,t,i);if("normal"===c.type){if(n=i.done?"completed":"suspendedYield",c.arg===u)continue;return{value:c.arg,done:i.done}}"throw"===c.type&&(n="completed",i.method="throw",i.arg=c.arg)}}}(e,i,s),o}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=d;var u={};function h(){}function f(){}function g(){}var v={};c(v,o,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(R([])));y&&y!==t&&i.call(y,o)&&(v=y);var b=g.prototype=h.prototype=Object.create(v);function S(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,s,a,c){var d=l(e[o],e,s);if("throw"!==d.type){var u=d.arg,h=u.value;return h&&"object"==n(h)&&i.call(h,"__await")?t.resolve(h.__await).then((function(e){r("next",e,a,c)}),(function(e){r("throw",e,a,c)})):t.resolve(h).then((function(e){u.value=e,a(u)}),(function(e){return r("throw",e,a,c)}))}c(d.arg)}var o;this._invoke=function(e,i){function n(){return new t((function(t,n){r(e,i,t,n)}))}return o=o?o.then(n,n):n()}}function E(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,E(e,t),"throw"===t.method))return u;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return u}var n=l(i,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,u;var r=n.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,u):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,u)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function R(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n<e.length;)if(i.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return r.next=r}}return{next:M}}function M(){return{value:void 0,done:!0}}return f.prototype=g,c(b,"constructor",g),c(g,"constructor",f),f.displayName=c(g,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===f||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,c(e,a,"GeneratorFunction")),e.prototype=Object.create(b),e},e.awrap=function(e){return{__await:e}},S(_.prototype),c(_.prototype,s,(function(){return this})),e.AsyncIterator=_,e.async=function(t,i,n,r,o){void 0===o&&(o=Promise);var s=new _(d(t,i,n,r),o);return e.isGeneratorFunction(i)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},S(b),c(b,a,"Generator"),c(b,o,(function(){return this})),c(b,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var i in e)t.push(i);return t.reverse(),function i(){for(;t.length;){var n=t.pop();if(n in e)return i.value=n,i.done=!1,i}return i.done=!0,i}},e.values=R,I.prototype={constructor:I,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(i,n){return s.type="throw",s.arg=e,t.next=i,n&&(t.method="next",t.arg=void 0),!!n}for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r],s=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=i.call(o,"catchLoc"),c=i.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,u):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),u},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;T(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:R(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}function g(e,t,i,n,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void i(e)}a.done?t(c):Promise.resolve(c).then(n,r)}function v(e){return function(){var t=this,i=arguments;return new Promise((function(n,r){var o=e.apply(t,i);function s(e){g(o,n,r,s,a,"next",e)}function a(e){g(o,n,r,s,a,"throw",e)}s(void 0)}))}}function m(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function y(e,t){return y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},y(e,t)}function b(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=_(e);if(t){var o=_(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return S(e)}(this,i)}}function S(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _(e){return _=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_(e)}function E(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function w(e){return new I(e)}function T(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof I;Promise.resolve(a?s.wrapped:s).then((function(e){a?n("return"===t?"return":"next",e):r(o.done?"return":"normal",e)}),(function(e){n("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new Promise((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function I(e){this.wrapped=e}T.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},T.prototype.next=function(e){return this._invoke("next",e)},T.prototype.throw=function(e){return this._invoke("throw",e)},T.prototype.return=function(e){return this._invoke("return",e)};var R=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&y(e,t)}(I,e);var t,i,n,r,g,_=b(I);function I(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,I),(e=_.call(this)).clientOrigin=i,E(S(e),"transport",void 0),E(S(e),"capabilitiesFinished",!1),E(S(e),"supportsMSC2974Renegotiate",!1),E(S(e),"requestedCapabilities",[]),E(S(e),"approvedCapabilities",void 0),E(S(e),"cachedClientVersions",void 0),E(S(e),"turnServerWatchers",0),!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return e.transport=new a.PostmessageTransport(o.WidgetApiDirection.FromWidget,t,window.parent,window),e.transport.targetOrigin=i,e.transport.on("message",e.handleMessage.bind(S(e))),e}return t=I,i=[{key:"hasCapability",value:function(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}},{key:"requestCapability",value:function(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}},{key:"requestCapabilities",value:function(e){var t=this;e.forEach((function(e){return t.requestCapability(e)}))}},{key:"requestCapabilityForRoomTimeline",value:function(e){this.requestCapability("org.matrix.msc2762.timeline:".concat(e))}},{key:"requestCapabilityToSendState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Send,e,t).raw)}},{key:"requestCapabilityToReceiveState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Receive,e,t).raw)}},{key:"requestCapabilityToSendToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Receive,e).raw)}},{key:"requestOpenIDConnectToken",value:function(){var e=this;return new Promise((function(t,i){e.transport.sendComplete(c.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then((function(n){var r=n.response;r.state===d.OpenIDRequestState.Allowed?t(r):r.state===d.OpenIDRequestState.Blocked?i(new Error("User declined to verify their identity")):r.state===d.OpenIDRequestState.PendingUserConfirmation?e.on("action:".concat(c.WidgetApiToWidgetAction.OpenIDCredentials),(function o(s){s.preventDefault();var a=s.detail;a.data.original_request_id===n.requestId&&(a.data.state===d.OpenIDRequestState.Allowed?(t(a.data),e.transport.reply(a,{})):a.data.state===d.OpenIDRequestState.Blocked?(i(new Error("User declined to verify their identity")),e.transport.reply(a,{})):(i(new Error("Invalid state on reply: "+r.state)),e.transport.reply(a,{error:{message:"Invalid state"}})),e.off("action:".concat(c.WidgetApiToWidgetAction.OpenIDCredentials),o))})):i(new Error("Invalid state: "+r.state))})).catch(i)}))}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(c.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(c.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(e){return this.transport.send(c.WidgetApiFromWidgetAction.SendSticker,e).then()}},{key:"setAlwaysOnScreen",value:function(e){return this.transport.send(c.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:e}).then((function(e){return e.success}))}},{key:"openModalWidget",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:l.MatrixWidgetType.Custom;return this.transport.send(c.WidgetApiFromWidgetAction.OpenModalWidget,{type:r,url:e,name:t,buttons:i,data:n}).then()}},{key:"closeModalWidget",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.transport.send(c.WidgetApiFromWidgetAction.CloseModalWidget,e).then()}},{key:"sendRoomEvent",value:function(e,t,i){return this.transport.send(c.WidgetApiFromWidgetAction.SendEvent,{type:e,content:t,room_id:i})}},{key:"sendStateEvent",value:function(e,t,i,n){return this.transport.send(c.WidgetApiFromWidgetAction.SendEvent,{type:e,content:i,state_key:t,room_id:n})}},{key:"sendToDevice",value:function(e,t,i){return this.transport.send(c.WidgetApiFromWidgetAction.SendToDevice,{type:e,encrypted:t,messages:i})}},{key:"readRoomEvents",value:function(e,t,i,n){var r={type:e,msgtype:i};return void 0!==t&&(r.limit=t),n&&(n.includes(f.Symbols.AnyRoom)?r.room_ids=f.Symbols.AnyRoom:r.room_ids=n),this.transport.send(c.WidgetApiFromWidgetAction.MSC2876ReadEvents,r).then((function(e){return e.events}))}},{key:"readEventRelations",value:(g=v(p().mark((function e(t,i,n,r,o,a,d,l){var u;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(e.sent.includes(s.UnstableApiVersion.MSC3869)){e.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return u={event_id:t,rel_type:n,event_type:r,room_id:i,to:d,from:a,limit:o,direction:l},e.abrupt("return",this.transport.send(c.WidgetApiFromWidgetAction.MSC3869ReadRelations,u));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t,i,n,r,o,s,a){return g.apply(this,arguments)})},{key:"readStateEvents",value:function(e,t,i,n){var r={type:e,state_key:void 0===i||i};return void 0!==t&&(r.limit=t),n&&(n.includes(f.Symbols.AnyRoom)?r.room_ids=f.Symbols.AnyRoom:r.room_ids=n),this.transport.send(c.WidgetApiFromWidgetAction.MSC2876ReadEvents,r).then((function(e){return e.events}))}},{key:"setModalButtonEnabled",value:function(e,t){if(e===u.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(c.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:e,enabled:t}).then()}},{key:"navigateTo",value:function(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(c.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:e}).then()}},{key:"getTurnServers",value:function(){var e,t=this;return(e=p().mark((function e(){var i,n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=function(){var e=v(p().mark((function e(n){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n.preventDefault(),i(n.detail.data),e.next=4,t.transport.reply(n.detail,{});case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.on("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),0!==t.turnServerWatchers){e.next=12;break}return e.prev=3,e.next=6,w(t.transport.send(c.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(3),t.off("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),e.t0;case 12:t.turnServerWatchers++,e.prev=13;case 14:return e.next=17,w(new Promise((function(e){return i=e})));case 17:return e.next=19,e.sent;case 19:e.next=14;break;case 21:if(e.prev=21,t.off("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),t.turnServerWatchers--,0!==t.turnServerWatchers){e.next=27;break}return e.next=27,w(t.transport.send(c.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return e.finish(21);case 28:case"end":return e.stop()}}),e,null,[[3,8],[13,,21,28]])})),function(){return new T(e.apply(this,arguments))})()}},{key:"searchUserDirectory",value:(r=v(p().mark((function e(t,i){var n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(e.sent.includes(s.UnstableApiVersion.MSC3973)){e.next=5;break}throw new Error("The user_directory_search action is not supported by the client.");case 5:return n={search_term:t,limit:i},e.abrupt("return",this.transport.send(c.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch,n));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"start",value:function(){var e=this;this.transport.start(),this.getClientVersions().then((function(t){t.includes(s.UnstableApiVersion.MSC2974)&&(e.supportsMSC2974Renegotiate=!0)}))}},{key:"handleMessage",value:function(e){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case c.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case c.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(e.detail);case c.WidgetApiToWidgetAction.UpdateVisibility:case c.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:s.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var e=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(c.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then((function(t){return e.cachedClientVersions=t.supported_versions,t.supported_versions})).catch((function(e){return console.warn("non-fatal error getting supported client versions: ",e),[]}))}},{key:"handleCapabilities",value:function(e){var t=this;return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then((function(i){return i.includes(s.UnstableApiVersion.MSC2871)?t.once("action:".concat(c.WidgetApiToWidgetAction.NotifyCapabilities),(function(e){t.approvedCapabilities=e.detail.data.approved,t.emit("ready")})):t.emit("ready"),t.capabilitiesFinished=!0,t.transport.reply(e,{capabilities:t.requestedCapabilities})}))}}],i&&m(t.prototype,i),n&&m(t,n),Object.defineProperty(t,"prototype",{writable:!1}),I}(r.EventEmitter);i.WidgetApi=R},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/GetOpenIDAction":183,"./interfaces/ModalWidgetActions":193,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./interfaces/WidgetType":211,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,events:105}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetDriver=void 0;var n=e("..");function r(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var o=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,i,o;return t=e,(i=[{key:"validateCapabilities",value:function(e){return Promise.resolve(new Set)}},{key:"sendEvent",value:function(e,t){return Promise.reject(new Error("Failed to override function"))}},{key:"sendToDevice",value:function(e,t,i){return Promise.reject(new Error("Failed to override function"))}},{key:"readRoomEvents",value:function(e,t,i){return Promise.resolve([])}},{key:"readStateEvents",value:function(e,t,i){return Promise.resolve([])}},{key:"readEventRelations",value:function(e,t,i,n,r,o,s,a){return Promise.resolve({chunk:[]})}},{key:"askOpenID",value:function(e){e.update({state:n.OpenIDRequestState.Blocked})}},{key:"navigate",value:function(e){throw new Error("Navigation is not implemented")}},{key:"getTurnServers",value:function(){throw new Error("TURN server support is not implemented")}},{key:"searchUserDirectory",value:function(e,t){return Promise.resolve({limited:!1,results:[]})}}])&&r(t.prototype,i),o&&r(t,o),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.WidgetDriver=o},{"..":178}],178:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=e("./WidgetApi");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===n[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return n[e]}}))}));var r=e("./ClientWidgetApi");Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===r[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return r[e]}}))}));var o=e("./Symbols");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===o[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return o[e]}}))}));var s=e("./transport/ITransport");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return s[e]}}))}));var a=e("./transport/PostmessageTransport");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=e("./interfaces/ICustomWidgetData");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===c[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return c[e]}}))}));var d=e("./interfaces/IJitsiWidgetData");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===d[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return d[e]}}))}));var l=e("./interfaces/IStickerpickerWidgetData");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===l[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return l[e]}}))}));var u=e("./interfaces/IWidget");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return u[e]}}))}));var h=e("./interfaces/WidgetType");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===h[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return h[e]}}))}));var f=e("./interfaces/IWidgetApiErrorResponse");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===f[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./interfaces/IWidgetApiRequest");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===p[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return p[e]}}))}));var g=e("./interfaces/IWidgetApiResponse");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===g[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return g[e]}}))}));var v=e("./interfaces/WidgetApiAction");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===v[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./interfaces/WidgetApiDirection");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===m[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./interfaces/ApiVersion");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===y[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return y[e]}}))}));var b=e("./interfaces/Capabilities");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===b[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return b[e]}}))}));var S=e("./interfaces/CapabilitiesAction");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===S[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return S[e]}}))}));var _=e("./interfaces/ContentLoadedAction");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===_[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _[e]}}))}));var E=e("./interfaces/ScreenshotAction");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===E[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return E[e]}}))}));var w=e("./interfaces/StickerAction");Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===w[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return w[e]}}))}));var T=e("./interfaces/StickyAction");Object.keys(T).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===T[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return T[e]}}))}));var I=e("./interfaces/SupportedVersionsAction");Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===I[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return I[e]}}))}));var R=e("./interfaces/VisibilityAction");Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===R[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return R[e]}}))}));var M=e("./interfaces/GetOpenIDAction");Object.keys(M).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===M[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return M[e]}}))}));var k=e("./interfaces/OpenIDCredentialsAction");Object.keys(k).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===k[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return k[e]}}))}));var C=e("./interfaces/WidgetKind");Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===C[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return C[e]}}))}));var O=e("./interfaces/ModalButtonKind");Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===O[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return O[e]}}))}));var A=e("./interfaces/ModalWidgetActions");Object.keys(A).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===A[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return A[e]}}))}));var P=e("./interfaces/SetModalButtonEnabledAction");Object.keys(P).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===P[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return P[e]}}))}));var D=e("./interfaces/WidgetConfigAction");Object.keys(D).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===D[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return D[e]}}))}));var x=e("./interfaces/SendEventAction");Object.keys(x).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===x[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return x[e]}}))}));var L=e("./interfaces/SendToDeviceAction");Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===L[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return L[e]}}))}));var U=e("./interfaces/ReadEventAction");Object.keys(U).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===U[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return U[e]}}))}));var B=e("./interfaces/IRoomEvent");Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===B[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return B[e]}}))}));var N=e("./interfaces/NavigateAction");Object.keys(N).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===N[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return N[e]}}))}));var j=e("./interfaces/TurnServerActions");Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===j[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return j[e]}}))}));var F=e("./interfaces/ReadRelationsAction");Object.keys(F).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===F[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return F[e]}}))}));var K=e("./models/WidgetEventCapability");Object.keys(K).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===K[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return K[e]}}))}));var q=e("./models/validation/url");Object.keys(q).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===q[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return q[e]}}))}));var $=e("./models/validation/utils");Object.keys($).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===$[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $[e]}}))}));var V=e("./models/Widget");Object.keys(V).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===V[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return V[e]}}))}));var H=e("./models/WidgetParser");Object.keys(H).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===H[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return H[e]}}))}));var W=e("./templating/url-template");Object.keys(W).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===W[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return W[e]}}))}));var G=e("./util/SimpleObservable");Object.keys(G).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===G[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return G[e]}}))}));var z=e("./driver/WidgetDriver");Object.keys(z).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===z[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return z[e]}}))}))},{"./ClientWidgetApi":174,"./Symbols":175,"./WidgetApi":176,"./driver/WidgetDriver":177,"./interfaces/ApiVersion":179,"./interfaces/Capabilities":180,"./interfaces/CapabilitiesAction":181,"./interfaces/ContentLoadedAction":182,"./interfaces/GetOpenIDAction":183,"./interfaces/ICustomWidgetData":184,"./interfaces/IJitsiWidgetData":185,"./interfaces/IRoomEvent":186,"./interfaces/IStickerpickerWidgetData":187,"./interfaces/IWidget":188,"./interfaces/IWidgetApiErrorResponse":189,"./interfaces/IWidgetApiRequest":190,"./interfaces/IWidgetApiResponse":191,"./interfaces/ModalButtonKind":192,"./interfaces/ModalWidgetActions":193,"./interfaces/NavigateAction":194,"./interfaces/OpenIDCredentialsAction":195,"./interfaces/ReadEventAction":196,"./interfaces/ReadRelationsAction":197,"./interfaces/ScreenshotAction":198,"./interfaces/SendEventAction":199,"./interfaces/SendToDeviceAction":200,"./interfaces/SetModalButtonEnabledAction":201,"./interfaces/StickerAction":202,"./interfaces/StickyAction":203,"./interfaces/SupportedVersionsAction":204,"./interfaces/TurnServerActions":205,"./interfaces/VisibilityAction":206,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./interfaces/WidgetConfigAction":209,"./interfaces/WidgetKind":210,"./interfaces/WidgetType":211,"./models/Widget":212,"./models/WidgetEventCapability":213,"./models/WidgetParser":214,"./models/validation/url":215,"./models/validation/utils":216,"./templating/url-template":217,"./transport/ITransport":218,"./transport/PostmessageTransport":219,"./util/SimpleObservable":220}],179:[function(e,t,i){"use strict";var n,r;Object.defineProperty(i,"__esModule",{value:!0}),i.UnstableApiVersion=i.MatrixApiVersion=i.CurrentApiVersions=void 0,i.MatrixApiVersion=n,function(e){e.Prerelease1="0.0.1",e.Prerelease2="0.0.2"}(n||(i.MatrixApiVersion=n={})),i.UnstableApiVersion=r,function(e){e.MSC2762="org.matrix.msc2762",e.MSC2871="org.matrix.msc2871",e.MSC2931="org.matrix.msc2931",e.MSC2974="org.matrix.msc2974",e.MSC2876="org.matrix.msc2876",e.MSC3819="org.matrix.msc3819",e.MSC3846="town.robin.msc3846",e.MSC3869="org.matrix.msc3869",e.MSC3973="org.matrix.msc3973"}(r||(i.UnstableApiVersion=r={}));var o=[n.Prerelease1,n.Prerelease2,r.MSC2762,r.MSC2871,r.MSC2931,r.MSC2974,r.MSC2876,r.MSC3819,r.MSC3846,r.MSC3869,r.MSC3973];i.CurrentApiVersions=o},{}],180:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.VideoConferenceCapabilities=i.StickerpickerCapabilities=i.MatrixCapabilities=void 0,i.getTimelineRoomIDFromCapability=function(e){return e.substring(e.indexOf(":")+1)},i.isTimelineCapability=function(e){return null==e?void 0:e.startsWith("org.matrix.msc2762.timeline:")},i.isTimelineCapabilityFor=function(e,t){return e==="org.matrix.msc2762.timeline:".concat(t)},i.MatrixCapabilities=n,function(e){e.Screenshots="m.capability.screenshot",e.StickerSending="m.sticker",e.AlwaysOnScreen="m.always_on_screen",e.RequiresClient="io.element.requires_client",e.MSC2931Navigate="org.matrix.msc2931.navigate",e.MSC3846TurnServers="town.robin.msc3846.turn_servers",e.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search"}(n||(i.MatrixCapabilities=n={}));var r=[n.StickerSending];i.StickerpickerCapabilities=r;var o=[n.AlwaysOnScreen];i.VideoConferenceCapabilities=o},{}],181:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],182:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],183:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.OpenIDRequestState=void 0,i.OpenIDRequestState=n,function(e){e.Allowed="allowed",e.Blocked="blocked",e.PendingUserConfirmation="request"}(n||(i.OpenIDRequestState=n={}))},{}],184:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],185:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],186:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],187:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],188:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],189:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isErrorResponse=function(e){if("error"in e){return!!e.error.message}return!1}},{}],190:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],191:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],192:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.ModalButtonKind=void 0,i.ModalButtonKind=n,function(e){e.Primary="m.primary",e.Secondary="m.secondary",e.Warning="m.warning",e.Danger="m.danger",e.Link="m.link"}(n||(i.ModalButtonKind=n={}))},{}],193:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.BuiltInModalButtonID=void 0,i.BuiltInModalButtonID=n,function(e){e.Close="m.close"}(n||(i.BuiltInModalButtonID=n={}))},{}],194:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],195:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],196:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],197:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],198:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],199:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],200:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],201:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],202:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],203:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],204:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],205:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],206:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],207:[function(e,t,i){"use strict";var n,r;Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetApiToWidgetAction=i.WidgetApiFromWidgetAction=void 0,i.WidgetApiToWidgetAction=n,function(e){e.SupportedApiVersions="supported_api_versions",e.Capabilities="capabilities",e.NotifyCapabilities="notify_capabilities",e.TakeScreenshot="screenshot",e.UpdateVisibility="visibility",e.OpenIDCredentials="openid_credentials",e.WidgetConfig="widget_config",e.CloseModalWidget="close_modal",e.ButtonClicked="button_clicked",e.SendEvent="send_event",e.SendToDevice="send_to_device",e.UpdateTurnServers="update_turn_servers"}(n||(i.WidgetApiToWidgetAction=n={})),i.WidgetApiFromWidgetAction=r,function(e){e.SupportedApiVersions="supported_api_versions",e.ContentLoaded="content_loaded",e.SendSticker="m.sticker",e.UpdateAlwaysOnScreen="set_always_on_screen",e.GetOpenIDCredentials="get_openid",e.CloseModalWidget="close_modal",e.OpenModalWidget="open_modal",e.SetModalButtonEnabled="set_button_enabled",e.SendEvent="send_event",e.SendToDevice="send_to_device",e.WatchTurnServers="watch_turn_servers",e.UnwatchTurnServers="unwatch_turn_servers",e.MSC2876ReadEvents="org.matrix.msc2876.read_events",e.MSC2931Navigate="org.matrix.msc2931.navigate",e.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",e.MSC3869ReadRelations="org.matrix.msc3869.read_relations",e.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search"}(r||(i.WidgetApiFromWidgetAction=r={}))},{}],208:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetApiDirection=void 0,i.invertedDirection=function(e){if(e===n.ToWidget)return n.FromWidget;if(e===n.FromWidget)return n.ToWidget;throw new Error("Invalid direction")},i.WidgetApiDirection=n,function(e){e.ToWidget="toWidget",e.FromWidget="fromWidget"}(n||(i.WidgetApiDirection=n={}))},{}],209:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],210:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetKind=void 0,i.WidgetKind=n,function(e){e.Room="room",e.Account="account",e.Modal="modal"}(n||(i.WidgetKind=n={}))},{}],211:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.MatrixWidgetType=void 0,i.MatrixWidgetType=n,function(e){e.Custom="m.custom",e.JitsiMeet="m.jitsi",e.Stickerpicker="m.stickerpicker"}(n||(i.MatrixWidgetType=n={}))},{}],212:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Widget=void 0;var n=e("./validation/utils"),r=e("..");function o(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var s=function(){function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.definition=t,!this.definition)throw new Error("Definition is required");(0,n.assertPresent)(t,"id"),(0,n.assertPresent)(t,"creatorUserId"),(0,n.assertPresent)(t,"type"),(0,n.assertPresent)(t,"url")}var t,i,s;return t=e,(i=[{key:"creatorUserId",get:function(){return this.definition.creatorUserId}},{key:"type",get:function(){return this.definition.type}},{key:"id",get:function(){return this.definition.id}},{key:"name",get:function(){return this.definition.name||null}},{key:"title",get:function(){return this.rawData.title||null}},{key:"templateUrl",get:function(){return this.definition.url}},{key:"origin",get:function(){return new URL(this.templateUrl).origin}},{key:"waitForIframeLoad",get:function(){return!1!==this.definition.waitForIframeLoad&&(this.definition.waitForIframeLoad,!0)}},{key:"rawData",get:function(){return this.definition.data||{}}},{key:"getCompleteUrl",value:function(e){return(0,r.runTemplate)(this.templateUrl,this.definition,e)}}])&&o(t.prototype,i),s&&o(t,s),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.Widget=s},{"..":178,"./validation/utils":216}],213:[function(e,t,i){"use strict";function n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return r(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function o(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var s,a;Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetEventCapability=i.EventKind=i.EventDirection=void 0,i.EventKind=s,function(e){e.Event="event",e.State="state_event",e.ToDevice="to_device"}(s||(i.EventKind=s={})),i.EventDirection=a,function(e){e.Send="send",e.Receive="receive"}(a||(i.EventDirection=a={}));var c=function(){function e(t,i,n,r,o){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.direction=t,this.eventType=i,this.kind=n,this.keyStr=r,this.raw=o}var t,i,r;return t=e,i=[{key:"matchesAsStateEvent",value:function(e,t,i){return this.kind===s.State&&this.direction===e&&this.eventType===t&&(null===this.keyStr||this.keyStr===i)}},{key:"matchesAsToDeviceEvent",value:function(e,t){return this.kind===s.ToDevice&&this.direction===e&&this.eventType===t}},{key:"matchesAsRoomEvent",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return this.kind===s.Event&&this.direction===e&&this.eventType===t&&("m.room.message"!==this.eventType||null===this.keyStr||this.keyStr===i)}}],r=[{key:"forStateEvent",value:function(t,i,n){i=i.replace(/#/g,"\\#"),n=null!=n?"#".concat(n):"";var r="org.matrix.msc2762.".concat(t,".state_event:").concat(i).concat(n);return e.findEventCapabilities([r])[0]}},{key:"forToDeviceEvent",value:function(t,i){var n="org.matrix.msc3819.".concat(t,".to_device:").concat(i);return e.findEventCapabilities([n])[0]}},{key:"forRoomEvent",value:function(t,i){var n="org.matrix.msc2762.".concat(t,".event:").concat(i);return e.findEventCapabilities([n])[0]}},{key:"forRoomMessageEvent",value:function(t,i){i=null==i?"":i;var n="org.matrix.msc2762.".concat(t,".event:m.room.message#").concat(i);return e.findEventCapabilities([n])[0]}},{key:"findEventCapabilities",value:function(t){var i,r=[],o=n(t);try{for(o.s();!(i=o.n()).done;){var c=i.value,d=null,l=void 0,u=null;if(c.startsWith("org.matrix.msc2762.send.event:")?(d=a.Send,u=s.Event,l=c.substring("org.matrix.msc2762.send.event:".length)):c.startsWith("org.matrix.msc2762.send.state_event:")?(d=a.Send,u=s.State,l=c.substring("org.matrix.msc2762.send.state_event:".length)):c.startsWith("org.matrix.msc3819.send.to_device:")?(d=a.Send,u=s.ToDevice,l=c.substring("org.matrix.msc3819.send.to_device:".length)):c.startsWith("org.matrix.msc2762.receive.event:")?(d=a.Receive,u=s.Event,l=c.substring("org.matrix.msc2762.receive.event:".length)):c.startsWith("org.matrix.msc2762.receive.state_event:")?(d=a.Receive,u=s.State,l=c.substring("org.matrix.msc2762.receive.state_event:".length)):c.startsWith("org.matrix.msc3819.receive.to_device:")&&(d=a.Receive,u=s.ToDevice,l=c.substring("org.matrix.msc3819.receive.to_device:".length)),null!==d&&null!==u&&void 0!==l){var h=l.startsWith("m.room.message#")||u===s.State,f=null;if(l.includes("#")&&h){var p=l.split("#"),g=p.findIndex((function(e){return!e.endsWith("\\")}));l=p.slice(0,g+1).map((function(e){return e.endsWith("\\")?e.substring(0,e.length-1):e})).join("#"),f=p.slice(g+1).join("#")}r.push(new e(d,l,u,f,c))}}}catch(e){o.e(e)}finally{o.f()}return r}}],i&&o(t.prototype,i),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.WidgetEventCapability=c},{}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetParser=void 0;var n=e("./Widget"),r=e("./validation/url");function o(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return s(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return s(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,r=function(){};return{s:r,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,o=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw o}}}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function a(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var c=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,i,s;return t=e,s=[{key:"parseAccountData",value:function(t){if(!t)return[];for(var i=[],n=0,r=Object.keys(t);n<r.length;n++){var o=r[n],s=t[o];if(s&&("m.widget"===s.type||"im.vector.modular.widgets"===s.type)&&s.sender&&(s.state_key||s.id)===o){var a={content:s.content,sender:s.sender,type:"m.widget",state_key:o,event_id:"$example",room_id:"!example",origin_server_ts:1},c=e.parseRoomWidget(a);c&&i.push(c)}}return i}},{key:"parseWidgetsFromRoomState",value:function(t){if(!t)return[];var i,n=[],r=o(t);try{for(r.s();!(i=r.n()).done;){var s=i.value,a=e.parseRoomWidget(s);a&&n.push(a)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"parseRoomWidget",value:function(t){if(!t)return null;if("m.widget"!==t.type&&"im.vector.modular.widgets"!==t.type)return null;var i=t.content||{},n={id:t.state_key,creatorUserId:i.creatorUserId||t.sender,name:i.name,type:i.type,url:i.url,waitForIframeLoad:i.waitForIframeLoad,data:i.data};return e.processEstimatedWidget(n)}},{key:"processEstimatedWidget",value:function(e){return e.id&&e.creatorUserId&&e.type&&(0,r.isValidUrl)(e.url)?new n.Widget(e):null}}],(i=null)&&a(t.prototype,i),s&&a(t,s),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.WidgetParser=c},{"./Widget":212,"./validation/url":215}],215:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isValidUrl=function(e){if(!e)return!1;try{var t=new URL(e);return"http"===t.protocol||"https"===t.protocol}catch(e){if(e instanceof TypeError)return!1;throw e}}},{}],216:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.assertPresent=function(e,t){if(!e[t])throw new Error("".concat(t," is required"))}},{}],217:[function(e,t,i){"use strict";function n(e){return null==e?"".concat(e):String(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.runTemplate=function(e,t,i){for(var r=Object.assign({},t.data,{matrix_room_id:i.widgetRoomId||"",matrix_user_id:i.currentUserId,matrix_display_name:i.userDisplayName||i.currentUserId,matrix_avatar_url:i.userHttpAvatarUrl||"",matrix_widget_id:t.id,"org.matrix.msc2873.client_id":i.clientId||"","org.matrix.msc2873.client_theme":i.clientTheme||"","org.matrix.msc2873.client_language":i.clientLanguage||""}),o=e,s=0,a=Object.keys(r);s<a.length;s++){var c=a[s],d="$".concat(c).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(d,"g");o=o.replace(l,encodeURIComponent(n(r[c])))}return o},i.toString=n},{}],218:[function(e,t,i){arguments[4][153][0].apply(i,arguments)},{dup:153}],219:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.PostmessageTransport=void 0;var r=e("events"),o=e("..");function s(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function a(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?s(Object(i),!0).forEach((function(t){f(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function c(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function l(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var i,r=h(e);if(t){var o=h(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return u(e)}(this,i)}}function u(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function f(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var p=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&d(e,t)}(s,e);var t,i,n,r=l(s);function s(e,t,i,n){var o;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,s),(o=r.call(this)).sendDirection=e,o.initialWidgetId=t,o.transportWindow=i,o.inboundWindow=n,f(u(o),"strictOriginCheck",!1),f(u(o),"targetOrigin","*"),f(u(o),"timeoutSeconds",10),f(u(o),"_ready",!1),f(u(o),"_widgetId",null),f(u(o),"outboundRequests",new Map),f(u(o),"stopController",new AbortController),o._widgetId=t,o}return t=s,(i=[{key:"ready",get:function(){return this._ready}},{key:"widgetId",get:function(){return this._widgetId||null}},{key:"nextRequestId",get:function(){for(var e="widgetapi-".concat(Date.now()),t=0,i=e;this.outboundRequests.has(i);)i="".concat(e,"-").concat(t++);return this.outboundRequests.set(i,null),i}},{key:"sendInternal",value:function(e){console.log("[PostmessageTransport] Sending object to ".concat(this.targetOrigin,": "),e),this.transportWindow.postMessage(e,this.targetOrigin)}},{key:"reply",value:function(e,t){return this.sendInternal(a(a({},e),{},{response:t}))}},{key:"send",value:function(e,t){return this.sendComplete(e,t).then((function(e){return e.response}))}},{key:"sendComplete",value:function(e,t){var i=this;if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));var n={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:e,data:t};return e===o.WidgetApiToWidgetAction.UpdateVisibility&&(n.visible=t.visible),new Promise((function(e,t){var r=function(e){a(),t(e)},o=setTimeout((function(){return r(new Error("Request timed out"))}),1e3*(i.timeoutSeconds||1)),s=function(){return r(new Error("Transport stopped"))};i.stopController.signal.addEventListener("abort",s);var a=function(){i.outboundRequests.delete(n.requestId),clearTimeout(o),i.stopController.signal.removeEventListener("abort",s)};i.outboundRequests.set(n.requestId,{request:n,resolve:function(t){a(),e(t)},reject:r}),i.sendInternal(n)}))}},{key:"start",value:function(){var e=this;this.inboundWindow.addEventListener("message",(function(t){e.handleMessage(t)})),this._ready=!0}},{key:"stop",value:function(){this._ready=!1,this.stopController.abort()}},{key:"handleMessage",value:function(e){if(!this.stopController.signal.aborted&&e.data&&(!this.strictOriginCheck||e.origin===window.origin)){var t=e.data;if(t.action&&t.requestId&&t.widgetId)if(t.response){if(t.api!==this.sendDirection)return;this.handleResponse(t)}else{var i=t;if(i.api!==(0,o.invertedDirection)(this.sendDirection))return;this.handleRequest(i)}}}},{key:"handleRequest",value:function(e){if(this.widgetId){if(this.widgetId!==e.widgetId)return}else this._widgetId=e.widgetId;this.emit("message",new CustomEvent("message",{detail:e}))}},{key:"handleResponse",value:function(e){if(e.widgetId===this.widgetId){var t=this.outboundRequests.get(e.requestId);if(t)if((0,o.isErrorResponse)(e.response)){var i=e.response;t.reject(new Error(i.error.message))}else t.resolve(e)}}}])&&c(t.prototype,i),n&&c(t,n),Object.defineProperty(t,"prototype",{writable:!1}),s}(r.EventEmitter);i.PostmessageTransport=p},{"..":178,events:105}],220:[function(e,t,i){"use strict";function n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return r(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function o(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}Object.defineProperty(i,"__esModule",{value:!0}),i.SimpleObservable=void 0;var s=function(){function e(t){var i,n,r;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),r=[],(n="listeners")in(i=this)?Object.defineProperty(i,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[n]=r,t&&this.listeners.push(t)}var t,i,r;return t=e,(i=[{key:"onUpdate",value:function(e){this.listeners.push(e)}},{key:"update",value:function(e){var t,i=n(this.listeners);try{for(i.s();!(t=i.n()).done;)(0,t.value)(e)}catch(e){i.e(e)}finally{i.f()}}},{key:"close",value:function(){this.listeners=[]}}])&&o(t.prototype,i),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.SimpleObservable=s},{}],221:[function(e,t,i){"use strict";var n=e("inherits"),r=e("hash-base"),o=e("safe-buffer").Buffer,s=new Array(16);function a(){r.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function c(e,t){return e<<t|e>>>32-t}function d(e,t,i,n,r,o,s){return c(e+(t&i|~t&n)+r+o|0,s)+t|0}function l(e,t,i,n,r,o,s){return c(e+(t&n|i&~n)+r+o|0,s)+t|0}function u(e,t,i,n,r,o,s){return c(e+(t^i^n)+r+o|0,s)+t|0}function h(e,t,i,n,r,o,s){return c(e+(i^(t|~n))+r+o|0,s)+t|0}n(a,r),a.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var i=this._a,n=this._b,r=this._c,o=this._d;i=d(i,n,r,o,e[0],3614090360,7),o=d(o,i,n,r,e[1],3905402710,12),r=d(r,o,i,n,e[2],606105819,17),n=d(n,r,o,i,e[3],3250441966,22),i=d(i,n,r,o,e[4],4118548399,7),o=d(o,i,n,r,e[5],1200080426,12),r=d(r,o,i,n,e[6],2821735955,17),n=d(n,r,o,i,e[7],4249261313,22),i=d(i,n,r,o,e[8],1770035416,7),o=d(o,i,n,r,e[9],2336552879,12),r=d(r,o,i,n,e[10],4294925233,17),n=d(n,r,o,i,e[11],2304563134,22),i=d(i,n,r,o,e[12],1804603682,7),o=d(o,i,n,r,e[13],4254626195,12),r=d(r,o,i,n,e[14],2792965006,17),i=l(i,n=d(n,r,o,i,e[15],1236535329,22),r,o,e[1],4129170786,5),o=l(o,i,n,r,e[6],3225465664,9),r=l(r,o,i,n,e[11],643717713,14),n=l(n,r,o,i,e[0],3921069994,20),i=l(i,n,r,o,e[5],3593408605,5),o=l(o,i,n,r,e[10],38016083,9),r=l(r,o,i,n,e[15],3634488961,14),n=l(n,r,o,i,e[4],3889429448,20),i=l(i,n,r,o,e[9],568446438,5),o=l(o,i,n,r,e[14],3275163606,9),r=l(r,o,i,n,e[3],4107603335,14),n=l(n,r,o,i,e[8],1163531501,20),i=l(i,n,r,o,e[13],2850285829,5),o=l(o,i,n,r,e[2],4243563512,9),r=l(r,o,i,n,e[7],1735328473,14),i=u(i,n=l(n,r,o,i,e[12],2368359562,20),r,o,e[5],4294588738,4),o=u(o,i,n,r,e[8],2272392833,11),r=u(r,o,i,n,e[11],1839030562,16),n=u(n,r,o,i,e[14],4259657740,23),i=u(i,n,r,o,e[1],2763975236,4),o=u(o,i,n,r,e[4],1272893353,11),r=u(r,o,i,n,e[7],4139469664,16),n=u(n,r,o,i,e[10],3200236656,23),i=u(i,n,r,o,e[13],681279174,4),o=u(o,i,n,r,e[0],3936430074,11),r=u(r,o,i,n,e[3],3572445317,16),n=u(n,r,o,i,e[6],76029189,23),i=u(i,n,r,o,e[9],3654602809,4),o=u(o,i,n,r,e[12],3873151461,11),r=u(r,o,i,n,e[15],530742520,16),i=h(i,n=u(n,r,o,i,e[2],3299628645,23),r,o,e[0],4096336452,6),o=h(o,i,n,r,e[7],1126891415,10),r=h(r,o,i,n,e[14],2878612391,15),n=h(n,r,o,i,e[5],4237533241,21),i=h(i,n,r,o,e[12],1700485571,6),o=h(o,i,n,r,e[3],2399980690,10),r=h(r,o,i,n,e[10],4293915773,15),n=h(n,r,o,i,e[1],2240044497,21),i=h(i,n,r,o,e[8],1873313359,6),o=h(o,i,n,r,e[15],4264355552,10),r=h(r,o,i,n,e[6],2734768916,15),n=h(n,r,o,i,e[13],1309151649,21),i=h(i,n,r,o,e[4],4149444226,6),o=h(o,i,n,r,e[11],3174756917,10),r=h(r,o,i,n,e[2],718787259,15),n=h(n,r,o,i,e[9],3951481745,21),this._a=this._a+i|0,this._b=this._b+n|0,this._c=this._c+r|0,this._d=this._d+o|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a},{"hash-base":116,inherits:146,"safe-buffer":250}],222:[function(e,t,i){var n=e("bn.js"),r=e("brorand");function o(e){this.rand=e||new r.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),i=Math.ceil(t/8);do{var r=new n(this.rand.generate(i))}while(r.cmp(e)>=0);return r},o.prototype._randrange=function(e,t){var i=t.sub(e);return e.add(this._randbelow(i))},o.prototype.test=function(e,t,i){var r=e.bitLength(),o=n.mont(e),s=new n(1).toRed(o);t||(t=Math.max(1,r/48|0));for(var a=e.subn(1),c=0;!a.testn(c);c++);for(var d=e.shrn(c),l=a.toRed(o);t>0;t--){var u=this._randrange(new n(2),a);i&&i(u);var h=u.toRed(o).redPow(d);if(0!==h.cmp(s)&&0!==h.cmp(l)){for(var f=1;f<c;f++){if(0===(h=h.redSqr()).cmp(s))return!1;if(0===h.cmp(l))break}if(f===c)return!1}}return!0},o.prototype.getDivisor=function(e,t){var i=e.bitLength(),r=n.mont(e),o=new n(1).toRed(r);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),a=0;!s.testn(a);a++);for(var c=e.shrn(a),d=s.toRed(r);t>0;t--){var l=this._randrange(new n(2),s),u=e.gcd(l);if(0!==u.cmpn(1))return u;var h=l.toRed(r).redPow(c);if(0!==h.cmp(o)&&0!==h.cmp(d)){for(var f=1;f<a;f++){if(0===(h=h.redSqr()).cmp(o))return h.fromRed().subn(1).gcd(e);if(0===h.cmp(d))break}if(f===a)return(h=h.redSqr()).fromRed().subn(1).gcd(e)}}return!1}},{"bn.js":18,brorand:19}],223:[function(e,t,i){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}t.exports=n,n.equal=function(e,t,i){if(e!=t)throw new Error(i||"Assertion failed: "+e+" != "+t)}},{}],224:[function(e,t,i){"use strict";var n=i;function r(e){return 1===e.length?"0"+e:e}function o(e){for(var t="",i=0;i<e.length;i++)t+=r(e[i].toString(16));return t}n.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var i=[];if("string"!=typeof e){for(var n=0;n<e.length;n++)i[n]=0|e[n];return i}if("hex"===t){(e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e);for(n=0;n<e.length;n+=2)i.push(parseInt(e[n]+e[n+1],16))}else for(n=0;n<e.length;n++){var r=e.charCodeAt(n),o=r>>8,s=255&r;o?i.push(o,s):i.push(s)}return i},n.zero2=r,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],225:[function(e,t,i){"use strict";const n=e("retry"),r=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class o extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const s=(e,t)=>new Promise(((i,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=n.operation(t);a.attempt((async n=>{try{i(await e(n))}catch(e){if(!(e instanceof Error))return void s(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof o)a.stop(),s(e.originalError);else if(e instanceof TypeError&&(c=e.message,!r.includes(c)))a.stop(),s(e);else{((e,t,i)=>{const n=i.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,n,t);try{await t.onFailedAttempt(e)}catch(e){return void s(e)}a.retry(e)||s(a.mainError())}}var c}))}));t.exports=s,t.exports.default=s,t.exports.AbortError=o},{retry:246}],226:[function(e,t,i){t.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],227:[function(e,t,i){"use strict";var n=e("asn1.js");i.certificate=e("./certificate");var r=n.define("RSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())}));i.RSAPrivateKey=r;var o=n.define("RSAPublicKey",(function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())}));i.RSAPublicKey=o;var s=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}));i.PublicKey=s;var a=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())})),c=n.define("PrivateKeyInfo",(function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(a),this.key("subjectPrivateKey").octstr())}));i.PrivateKey=c;var d=n.define("EncryptedPrivateKeyInfo",(function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())}));i.EncryptedPrivateKey=d;var l=n.define("DSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())}));i.DSAPrivateKey=l,i.DSAparam=n.define("DSAparam",(function(){this.int()}));var u=n.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(h),this.key("publicKey").optional().explicit(1).bitstr())}));i.ECPrivateKey=u;var h=n.define("ECParameters",(function(){this.choice({namedCurve:this.objid()})}));i.signature=n.define("signature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())}))},{"./certificate":228,"asn1.js":2}],228:[function(e,t,i){"use strict";var n=e("asn1.js"),r=n.define("Time",(function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})})),o=n.define("AttributeTypeValue",(function(){this.seq().obj(this.key("type").objid(),this.key("value").any())})),s=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())})),a=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())})),c=n.define("RelativeDistinguishedName",(function(){this.setof(o)})),d=n.define("RDNSequence",(function(){this.seqof(c)})),l=n.define("Name",(function(){this.choice({rdnSequence:this.use(d)})})),u=n.define("Validity",(function(){this.seq().obj(this.key("notBefore").use(r),this.key("notAfter").use(r))})),h=n.define("Extension",(function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())})),f=n.define("TBSCertificate",(function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(s),this.key("issuer").use(l),this.key("validity").use(u),this.key("subject").use(l),this.key("subjectPublicKeyInfo").use(a),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(h).optional())})),p=n.define("X509Certificate",(function(){this.seq().obj(this.key("tbsCertificate").use(f),this.key("signatureAlgorithm").use(s),this.key("signatureValue").bitstr())}));t.exports=p},{"asn1.js":2}],229:[function(e,t,i){var n=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,r=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,o=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,s=e("evp_bytestokey"),a=e("browserify-aes"),c=e("safe-buffer").Buffer;t.exports=function(e,t){var i,d=e.toString(),l=d.match(n);if(l){var u="aes"+l[1],h=c.from(l[2],"hex"),f=c.from(l[3].replace(/[\r\n]/g,""),"base64"),p=s(t,h.slice(0,8),parseInt(l[1],10)).key,g=[],v=a.createDecipheriv(u,p,h);g.push(v.update(f)),g.push(v.final()),i=c.concat(g)}else{var m=d.match(o);i=c.from(m[2].replace(/[\r\n]/g,""),"base64")}return{tag:d.match(r)[1],data:i}}},{"browserify-aes":23,evp_bytestokey:106,"safe-buffer":250}],230:[function(e,t,i){var n=e("./asn1"),r=e("./aesid.json"),o=e("./fixProc"),s=e("browserify-aes"),a=e("pbkdf2"),c=e("safe-buffer").Buffer;function d(e){var t;"object"!=typeof e||c.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=c.from(e));var i,d,l=o(e,t),u=l.tag,h=l.data;switch(u){case"CERTIFICATE":d=n.certificate.decode(h,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(d||(d=n.PublicKey.decode(h,"der")),i=d.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(d.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return d.subjectPrivateKey=d.subjectPublicKey,{type:"ec",data:d};case"1.2.840.10040.4.1":return d.algorithm.params.pub_key=n.DSAparam.decode(d.subjectPublicKey.data,"der"),{type:"dsa",data:d.algorithm.params};default:throw new Error("unknown key id "+i)}case"ENCRYPTED PRIVATE KEY":h=function(e,t){var i=e.algorithm.decrypt.kde.kdeparams.salt,n=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),o=r[e.algorithm.decrypt.cipher.algo.join(".")],d=e.algorithm.decrypt.cipher.iv,l=e.subjectPrivateKey,u=parseInt(o.split("-")[1],10)/8,h=a.pbkdf2Sync(t,i,n,u,"sha1"),f=s.createDecipheriv(o,h,d),p=[];return p.push(f.update(l)),p.push(f.final()),c.concat(p)}(h=n.EncryptedPrivateKey.decode(h,"der"),t);case"PRIVATE KEY":switch(i=(d=n.PrivateKey.decode(h,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(d.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:d.algorithm.curve,privateKey:n.ECPrivateKey.decode(d.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return d.algorithm.params.priv_key=n.DSAparam.decode(d.subjectPrivateKey,"der"),{type:"dsa",params:d.algorithm.params};default:throw new Error("unknown key id "+i)}case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(h,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(h,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(h,"der")};case"EC PRIVATE KEY":return{curve:(h=n.ECPrivateKey.decode(h,"der")).parameters.value,privateKey:h.privateKey};default:throw new Error("unknown key type "+u)}}t.exports=d,d.signature=n.signature},{"./aesid.json":226,"./asn1":227,"./fixProc":229,"browserify-aes":23,pbkdf2:231,"safe-buffer":250}],231:[function(e,t,i){i.pbkdf2=e("./lib/async"),i.pbkdf2Sync=e("./lib/sync")},{"./lib/async":232,"./lib/sync":235}],232:[function(e,t,i){(function(i){(function(){var n,r,o=e("safe-buffer").Buffer,s=e("./precondition"),a=e("./default-encoding"),c=e("./sync"),d=e("./to-buffer"),l=i.crypto&&i.crypto.subtle,u={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function f(){return r||(r=i.process&&i.process.nextTick?i.process.nextTick:i.queueMicrotask?i.queueMicrotask:i.setImmediate?i.setImmediate:i.setTimeout)}function p(e,t,i,n,r){return l.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then((function(e){return l.deriveBits({name:"PBKDF2",salt:t,iterations:i,hash:{name:r}},e,n<<3)})).then((function(e){return o.from(e)}))}t.exports=function(e,t,r,g,v,m){"function"==typeof v&&(m=v,v=void 0);var y=u[(v=v||"sha1").toLowerCase()];if(y&&"function"==typeof i.Promise){if(s(r,g),e=d(e,a,"Password"),t=d(t,a,"Salt"),"function"!=typeof m)throw new Error("No callback provided to pbkdf2");!function(e,t){e.then((function(e){f()((function(){t(null,e)}))}),(function(e){f()((function(){t(e)}))}))}(function(e){if(i.process&&!i.process.browser)return Promise.resolve(!1);if(!l||!l.importKey||!l.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=p(n=n||o.alloc(8),n,10,128,e).then((function(){return!0})).catch((function(){return!1}));return h[e]=t,t}(y).then((function(i){return i?p(e,t,r,g,y):c(e,t,r,g,v)})),m)}else f()((function(){var i;try{i=c(e,t,r,g,v)}catch(e){return m(e)}m(null,i)}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":233,"./precondition":234,"./sync":235,"./to-buffer":236,"safe-buffer":250}],233:[function(e,t,i){(function(e,i){(function(){var n;if(i.process&&i.process.browser)n="utf-8";else if(i.process&&i.process.version){n=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary"}else n="utf-8";t.exports=n}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:237}],234:[function(e,t,i){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],235:[function(e,t,i){var n=e("create-hash/md5"),r=e("ripemd160"),o=e("sha.js"),s=e("safe-buffer").Buffer,a=e("./precondition"),c=e("./default-encoding"),d=e("./to-buffer"),l=s.alloc(128),u={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,i){var a=function(e){function t(t){return o(e).update(t).digest()}function i(e){return(new r).update(e).digest()}return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:t}(e),c="sha512"===e||"sha384"===e?128:64;t.length>c?t=a(t):t.length<c&&(t=s.concat([t,l],c));for(var d=s.allocUnsafe(c+u[e]),h=s.allocUnsafe(c+u[e]),f=0;f<c;f++)d[f]=54^t[f],h[f]=92^t[f];var p=s.allocUnsafe(c+i+4);d.copy(p,0,0,c),this.ipad1=p,this.ipad2=d,this.opad=h,this.alg=e,this.blocksize=c,this.hash=a,this.size=u[e]}h.prototype.run=function(e,t){return e.copy(t,this.blocksize),this.hash(t).copy(this.opad,this.blocksize),this.hash(this.opad)},t.exports=function(e,t,i,n,r){a(i,n);var o=new h(r=r||"sha1",e=d(e,c,"Password"),(t=d(t,c,"Salt")).length),l=s.allocUnsafe(n),f=s.allocUnsafe(t.length+4);t.copy(f,0,0,t.length);for(var p=0,g=u[r],v=Math.ceil(n/g),m=1;m<=v;m++){f.writeUInt32BE(m,t.length);for(var y=o.run(f,o.ipad1),b=y,S=1;S<i;S++){b=o.run(b,o.ipad2);for(var _=0;_<g;_++)y[_]^=b[_]}y.copy(l,p),p+=g}return l}},{"./default-encoding":233,"./precondition":234,"./to-buffer":236,"create-hash/md5":75,ripemd160:249,"safe-buffer":250,"sha.js":257}],236:[function(e,t,i){var n=e("safe-buffer").Buffer;t.exports=function(e,t,i){if(n.isBuffer(e))return e;if("string"==typeof e)return n.from(e,t);if(ArrayBuffer.isView(e))return n.from(e.buffer);throw new TypeError(i+" must be a string, a Buffer, a typed array or a DataView")}},{"safe-buffer":250}],237:[function(e,t,i){var n,r,o=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function c(e){if(n===setTimeout)return setTimeout(e,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:s}catch(e){n=s}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var d,l=[],u=!1,h=-1;function f(){u&&d&&(u=!1,d.length?l=d.concat(l):h=-1,l.length&&p())}function p(){if(!u){var e=c(f);u=!0;for(var t=l.length;t;){for(d=l,l=[];++h<t;)d&&d[h].run();h=-1,t=l.length}d=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function g(e,t){this.fun=e,this.array=t}function v(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.push(new g(e,t)),1!==l.length||u||c(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=v,o.addListener=v,o.once=v,o.off=v,o.removeListener=v,o.removeAllListeners=v,o.emit=v,o.prependListener=v,o.prependOnceListener=v,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},{}],238:[function(e,t,i){i.publicEncrypt=e("./publicEncrypt"),i.privateDecrypt=e("./privateDecrypt"),i.privateEncrypt=function(e,t){return i.publicEncrypt(e,t,!0)},i.publicDecrypt=function(e,t){return i.privateDecrypt(e,t,!0)}},{"./privateDecrypt":240,"./publicEncrypt":241}],239:[function(e,t,i){var n=e("create-hash"),r=e("safe-buffer").Buffer;function o(e){var t=r.allocUnsafe(4);return t.writeUInt32BE(e,0),t}t.exports=function(e,t){for(var i,s=r.alloc(0),a=0;s.length<t;)i=o(a++),s=r.concat([s,n("sha1").update(e).update(i).digest()]);return s.slice(0,t)}},{"create-hash":74,"safe-buffer":250}],240:[function(e,t,i){var n=e("parse-asn1"),r=e("./mgf"),o=e("./xor"),s=e("bn.js"),a=e("browserify-rsa"),c=e("create-hash"),d=e("./withPublic"),l=e("safe-buffer").Buffer;t.exports=function(e,t,i){var u;u=e.padding?e.padding:i?1:4;var h,f=n(e),p=f.modulus.byteLength();if(t.length>p||new s(t).cmp(f.modulus)>=0)throw new Error("decryption error");h=i?d(new s(t),f):a(t,f);var g=l.alloc(p-h.length);if(h=l.concat([g,h],p),4===u)return function(e,t){var i=e.modulus.byteLength(),n=c("sha1").update(l.alloc(0)).digest(),s=n.length;if(0!==t[0])throw new Error("decryption error");var a=t.slice(1,s+1),d=t.slice(s+1),u=o(a,r(d,s)),h=o(d,r(u,i-s-1));if(function(e,t){e=l.from(e),t=l.from(t);var i=0,n=e.length;e.length!==t.length&&(i++,n=Math.min(e.length,t.length));var r=-1;for(;++r<n;)i+=e[r]^t[r];return i}(n,h.slice(0,s)))throw new Error("decryption error");var f=s;for(;0===h[f];)f++;if(1!==h[f++])throw new Error("decryption error");return h.slice(f)}(f,h);if(1===u)return function(e,t,i){var n=t.slice(0,2),r=2,o=0;for(;0!==t[r++];)if(r>=t.length){o++;break}var s=t.slice(2,r-1);("0002"!==n.toString("hex")&&!i||"0001"!==n.toString("hex")&&i)&&o++;s.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(r)}(0,h,i);if(3===u)return h;throw new Error("unknown padding")}},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,"safe-buffer":250}],241:[function(e,t,i){var n=e("parse-asn1"),r=e("randombytes"),o=e("create-hash"),s=e("./mgf"),a=e("./xor"),c=e("bn.js"),d=e("./withPublic"),l=e("browserify-rsa"),u=e("safe-buffer").Buffer;t.exports=function(e,t,i){var h;h=e.padding?e.padding:i?1:4;var f,p=n(e);if(4===h)f=function(e,t){var i=e.modulus.byteLength(),n=t.length,d=o("sha1").update(u.alloc(0)).digest(),l=d.length,h=2*l;if(n>i-h-2)throw new Error("message too long");var f=u.alloc(i-n-h-2),p=i-l-1,g=r(l),v=a(u.concat([d,f,u.alloc(1,1),t],p),s(g,p)),m=a(g,s(v,l));return new c(u.concat([u.alloc(1),m,v],i))}(p,t);else if(1===h)f=function(e,t,i){var n,o=t.length,s=e.modulus.byteLength();if(o>s-11)throw new Error("message too long");n=i?u.alloc(s-o-3,255):function(e){var t,i=u.allocUnsafe(e),n=0,o=r(2*e),s=0;for(;n<e;)s===o.length&&(o=r(2*e),s=0),(t=o[s++])&&(i[n++]=t);return i}(s-o-3);return new c(u.concat([u.from([0,i?1:2]),n,u.alloc(1),t],s))}(p,t,i);else{if(3!==h)throw new Error("unknown padding");if((f=new c(t)).cmp(p.modulus)>=0)throw new Error("data too long for modulus")}return i?l(f,p):d(f,p)}},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,randombytes:244,"safe-buffer":250}],242:[function(e,t,i){var n=e("bn.js"),r=e("safe-buffer").Buffer;t.exports=function(e,t){return r.from(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}},{"bn.js":18,"safe-buffer":250}],243:[function(e,t,i){t.exports=function(e,t){for(var i=e.length,n=-1;++n<i;)e[n]^=t[n];return e}},{}],244:[function(e,t,i){(function(i,n){(function(){"use strict";var r=65536,o=4294967295;var s=e("safe-buffer").Buffer,a=n.crypto||n.msCrypto;a&&a.getRandomValues?t.exports=function(e,t){if(e>o)throw new RangeError("requested too many random bytes");var n=s.allocUnsafe(e);if(e>0)if(e>r)for(var c=0;c<e;c+=r)a.getRandomValues(n.slice(c,c+r));else a.getRandomValues(n);if("function"==typeof t)return i.nextTick((function(){t(null,n)}));return n}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:237,"safe-buffer":250}],245:[function(e,t,i){(function(t,n){(function(){"use strict";function r(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=e("safe-buffer"),s=e("randombytes"),a=o.Buffer,c=o.kMaxLength,d=n.crypto||n.msCrypto,l=Math.pow(2,32)-1;function u(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>l||e<0)throw new TypeError("offset must be a uint32");if(e>c||e>t)throw new RangeError("offset out of range")}function h(e,t,i){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>l||e<0)throw new TypeError("size must be a uint32");if(e+t>i||e>c)throw new RangeError("buffer too small")}function f(e,i,n,r){if(t.browser){var o=e.buffer,a=new Uint8Array(o,i,n);return d.getRandomValues(a),r?void t.nextTick((function(){r(null,e)})):e}if(!r)return s(n).copy(e,i),e;s(n,(function(t,n){if(t)return r(t);n.copy(e,i),r(null,e)}))}d&&d.getRandomValues||!t.browser?(i.randomFill=function(e,t,i,r){if(!(a.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)r=t,t=0,i=e.length;else if("function"==typeof i)r=i,i=e.length-t;else if("function"!=typeof r)throw new TypeError('"cb" argument must be a function');return u(t,e.length),h(i,t,e.length),f(e,t,i,r)},i.randomFillSync=function(e,t,i){void 0===t&&(t=0);if(!(a.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');u(t,e.length),void 0===i&&(i=e.length-t);return h(i,t,e.length),f(e,t,i)}):(i.randomFill=r,i.randomFillSync=r)}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:237,randombytes:244,"safe-buffer":250}],246:[function(e,t,i){t.exports=e("./lib/retry")},{"./lib/retry":247}],247:[function(e,t,i){var n=e("./retry_operation");i.operation=function(e){var t=i.timeouts(e);return new n(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},i.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var i in e)t[i]=e[i];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],r=0;r<t.retries;r++)n.push(this.createTimeout(r,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(r,t)),n.sort((function(e,t){return e-t})),n},i.createTimeout=function(e,t){var i=t.randomize?Math.random()+1:1,n=Math.round(i*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout)},i.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n)for(var r in n=[],e)"function"==typeof e[r]&&n.push(r);for(var o=0;o<n.length;o++){var s=n[o],a=e[s];e[s]=function(n){var r=i.operation(t),o=Array.prototype.slice.call(arguments,1),s=o.pop();o.push((function(e){r.retry(e)||(e&&(arguments[0]=r.mainError()),s.apply(this,arguments))})),r.attempt((function(){n.apply(e,o)}))}.bind(e,a),e[s].options=t}}},{"./retry_operation":248}],248:[function(e,t,i){function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var i=this._timeouts.shift();if(void 0===i){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),i=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),i),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var i=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){i._operationTimeoutCb()}),i._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,i=0,n=0;n<this._errors.length;n++){var r=this._errors[n],o=r.message,s=(e[o]||0)+1;e[o]=s,s>=i&&(t=r,i=s)}return t}},{}],249:[function(e,t,i){"use strict";var n=e("buffer").Buffer,r=e("inherits"),o=e("hash-base"),s=new Array(16),a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],c=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],d=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],u=[0,1518500249,1859775393,2400959708,2840853838],h=[1352829926,1548603684,1836072691,2053994217,0];function f(){o.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function p(e,t){return e<<t|e>>>32-t}function g(e,t,i,n,r,o,s,a){return p(e+(t^i^n)+o+s|0,a)+r|0}function v(e,t,i,n,r,o,s,a){return p(e+(t&i|~t&n)+o+s|0,a)+r|0}function m(e,t,i,n,r,o,s,a){return p(e+((t|~i)^n)+o+s|0,a)+r|0}function y(e,t,i,n,r,o,s,a){return p(e+(t&n|i&~n)+o+s|0,a)+r|0}function b(e,t,i,n,r,o,s,a){return p(e+(t^(i|~n))+o+s|0,a)+r|0}r(f,o),f.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var i=0|this._a,n=0|this._b,r=0|this._c,o=0|this._d,f=0|this._e,S=0|this._a,_=0|this._b,E=0|this._c,w=0|this._d,T=0|this._e,I=0;I<80;I+=1){var R,M;I<16?(R=g(i,n,r,o,f,e[a[I]],u[0],d[I]),M=b(S,_,E,w,T,e[c[I]],h[0],l[I])):I<32?(R=v(i,n,r,o,f,e[a[I]],u[1],d[I]),M=y(S,_,E,w,T,e[c[I]],h[1],l[I])):I<48?(R=m(i,n,r,o,f,e[a[I]],u[2],d[I]),M=m(S,_,E,w,T,e[c[I]],h[2],l[I])):I<64?(R=y(i,n,r,o,f,e[a[I]],u[3],d[I]),M=v(S,_,E,w,T,e[c[I]],h[3],l[I])):(R=b(i,n,r,o,f,e[a[I]],u[4],d[I]),M=g(S,_,E,w,T,e[c[I]],h[4],l[I])),i=f,f=o,o=p(r,10),r=n,n=R,S=T,T=w,w=p(E,10),E=_,_=M}var k=this._b+r+w|0;this._b=this._c+o+T|0,this._c=this._d+f+S|0,this._d=this._e+i+_|0,this._e=this._a+n+E|0,this._a=k},f.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=n.alloc?n.alloc(20):new n(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=f},{buffer:68,"hash-base":116,inherits:146}],250:[function(e,t,i){ +/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ +var n=e("buffer"),r=n.Buffer;function o(e,t){for(var i in e)t[i]=e[i]}function s(e,t,i){return r(e,t,i)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(o(n,i),i.Buffer=s),s.prototype=Object.create(r.prototype),o(r,s),s.from=function(e,t,i){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,i)},s.alloc=function(e,t,i){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=r(e);return void 0!==t?"string"==typeof i?n.fill(t,i):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:68}],251:[function(e,t,i){(function(i){(function(){"use strict";var n,r=e("buffer"),o=r.Buffer,s={};for(n in r)r.hasOwnProperty(n)&&"SlowBuffer"!==n&&"Buffer"!==n&&(s[n]=r[n]);var a=s.Buffer={};for(n in o)o.hasOwnProperty(n)&&"allocUnsafe"!==n&&"allocUnsafeSlow"!==n&&(a[n]=o[n]);if(s.Buffer.prototype=o.prototype,a.from&&a.from!==Uint8Array.from||(a.from=function(e,t,i){if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return o(e,t,i)}),a.alloc||(a.alloc=function(e,t,i){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var n=o(e);return t&&0!==t.length?"string"==typeof i?n.fill(t,i):n.fill(t):n.fill(0),n}),!s.kStringMaxLength)try{s.kStringMaxLength=i.binding("buffer").kStringMaxLength}catch(e){}s.constants||(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),t.exports=s}).call(this)}).call(this,e("_process"))},{_process:237,buffer:68}],252:[function(e,t,i){var n=t.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(n).forEach((function(e){n[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))},{}],253:[function(e,t,i){var n=e("./parser"),r=e("./writer");i.write=r,i.parse=n.parse,i.parseParams=n.parseParams,i.parseFmtpConfig=n.parseFmtpConfig,i.parsePayloads=n.parsePayloads,i.parseRemoteCandidates=n.parseRemoteCandidates,i.parseImageAttributes=n.parseImageAttributes,i.parseSimulcastStreamList=n.parseSimulcastStreamList},{"./parser":254,"./writer":255}],254:[function(e,t,i){var n=function(e){return String(Number(e))===e?Number(e):e},r=function(e,t,i){var r=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:r&&!t[e.name]&&(t[e.name]={});var o=e.push?{}:r?t[e.name]:t;!function(e,t,i,r){if(r&&!i)t[r]=n(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(t[i[o]]=n(e[o+1]))}(i.match(e.reg),o,e.names,e.name),e.push&&t[e.push].push(o)},o=e("./grammar"),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(e){var t={},i=[],n=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(i.push({rtp:[],fmtp:[]}),n=i[i.length-1]);for(var a=0;a<(o[t]||[]).length;a+=1){var c=o[t][a];if(c.reg.test(s))return r(c,n,s)}})),t.media=i,t};var a=function(e,t){var i=t.split(/=(.+)/,2);return 2===i.length?e[i[0]]=n(i[1]):1===i.length&&t.length>1&&(e[i[0]]=void 0),e};i.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(e){return e.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(n),r=0;r<i.length;r+=3)t.push({component:i[r],ip:i[r+1],port:i[r+2]});return t},i.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},i.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var t,i=!1;return"~"!==e[0]?t=n(e):(t=n(e.substring(1,e.length)),i=!0),{scid:t,paused:i}}))}))}},{"./grammar":252}],255:[function(e,t,i){var n=e("./grammar"),r=/%[sdv%]/g,o=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return o.apply(null,n)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||a,r=t.innerOrder||c,o=[];return i.forEach((function(t){n[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(s(t,i,e))}))}))})),e.media.forEach((function(e){o.push(s("m",n.m[0],e)),r.forEach((function(t){n[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(s(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(s(t,i,e))}))}))}))})),o.join("\r\n")+"\r\n"}},{"./grammar":252}],256:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}r.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var i=this._block,r=this._blockSize,o=e.length,s=this._len,a=0;a<o;){for(var c=s%r,d=Math.min(o-a,r-c),l=0;l<d;l++)i[c+l]=e[a+l];a+=d,(s+=d)%r==0&&this._update(i)}return this._len+=o,this},r.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var i=8*this._len;if(i<=4294967295)this._block.writeUInt32BE(i,this._blockSize-4);else{var n=(4294967295&i)>>>0,r=(i-n)/4294967296;this._block.writeUInt32BE(r,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=r},{"safe-buffer":250}],257:[function(e,t,i){(i=t.exports=function(e){e=e.toLowerCase();var t=i[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),i.sha1=e("./sha1"),i.sha224=e("./sha224"),i.sha256=e("./sha256"),i.sha384=e("./sha384"),i.sha512=e("./sha512")},{"./sha":258,"./sha1":259,"./sha224":260,"./sha256":261,"./sha384":262,"./sha512":263}],258:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e){return e<<30|e>>>2}function l(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}n(c,r),c.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,u=0;u<16;++u)i[u]=e.readInt32BE(4*u);for(;u<80;++u)i[u]=i[u-3]^i[u-8]^i[u-14]^i[u-16];for(var h=0;h<80;++h){var f=~~(h/20),p=0|((t=n)<<5|t>>>27)+l(f,r,o,a)+c+i[h]+s[f];c=a,a=o,o=d(r),r=n,n=p}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0},c.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],259:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function u(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}n(c,r),c.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,h=0;h<16;++h)i[h]=e.readInt32BE(4*h);for(;h<80;++h)i[h]=(t=i[h-3]^i[h-8]^i[h-14]^i[h-16])<<1|t>>>31;for(var f=0;f<80;++f){var p=~~(f/20),g=d(n)+u(p,r,o,a)+c+i[f]+s[p]|0;c=a,a=o,o=l(r),r=n,n=g}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0},c.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],260:[function(e,t,i){var n=e("inherits"),r=e("./sha256"),o=e("./hash"),s=e("safe-buffer").Buffer,a=new Array(64);function c(){this.init(),this._w=a,o.call(this,64,56)}n(c,r),c.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},c.prototype._hash=function(){var e=s.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=c},{"./hash":256,"./sha256":261,inherits:146,"safe-buffer":250}],261:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],a=new Array(64);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e,t,i){return i^e&(t^i)}function l(e,t,i){return e&t|i&(e|t)}function u(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function h(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function f(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(c,r),c.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,p=0|this._f,g=0|this._g,v=0|this._h,m=0;m<16;++m)i[m]=e.readInt32BE(4*m);for(;m<64;++m)i[m]=0|(((t=i[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+i[m-7]+f(i[m-15])+i[m-16];for(var y=0;y<64;++y){var b=v+h(c)+d(c,p,g)+s[y]+i[y]|0,S=u(n)+l(n,r,o)|0;v=g,g=p,p=c,c=a+b|0,a=o,o=r,r=n,n=b+S|0}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0,this._f=p+this._f|0,this._g=g+this._g|0,this._h=v+this._h|0},c.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],262:[function(e,t,i){var n=e("inherits"),r=e("./sha512"),o=e("./hash"),s=e("safe-buffer").Buffer,a=new Array(160);function c(){this.init(),this._w=a,o.call(this,128,112)}n(c,r),c.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},c.prototype._hash=function(){var e=s.allocUnsafe(48);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=c},{"./hash":256,"./sha512":263,inherits:146,"safe-buffer":250}],263:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);function c(){this.init(),this._w=a,r.call(this,128,112)}function d(e,t,i){return i^e&(t^i)}function l(e,t,i){return e&t|i&(e|t)}function u(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function h(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function f(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function g(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function v(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0<t>>>0?1:0}n(c,r),c.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},c.prototype._update=function(e){for(var t=this._w,i=0|this._ah,n=0|this._bh,r=0|this._ch,o=0|this._dh,a=0|this._eh,c=0|this._fh,y=0|this._gh,b=0|this._hh,S=0|this._al,_=0|this._bl,E=0|this._cl,w=0|this._dl,T=0|this._el,I=0|this._fl,R=0|this._gl,M=0|this._hl,k=0;k<32;k+=2)t[k]=e.readInt32BE(4*k),t[k+1]=e.readInt32BE(4*k+4);for(;k<160;k+=2){var C=t[k-30],O=t[k-30+1],A=f(C,O),P=p(O,C),D=g(C=t[k-4],O=t[k-4+1]),x=v(O,C),L=t[k-14],U=t[k-14+1],B=t[k-32],N=t[k-32+1],j=P+U|0,F=A+L+m(j,P)|0;F=(F=F+D+m(j=j+x|0,x)|0)+B+m(j=j+N|0,N)|0,t[k]=F,t[k+1]=j}for(var K=0;K<160;K+=2){F=t[K],j=t[K+1];var q=l(i,n,r),$=l(S,_,E),V=u(i,S),H=u(S,i),W=h(a,T),G=h(T,a),z=s[K],Y=s[K+1],J=d(a,c,y),Q=d(T,I,R),X=M+G|0,Z=b+W+m(X,M)|0;Z=(Z=(Z=Z+J+m(X=X+Q|0,Q)|0)+z+m(X=X+Y|0,Y)|0)+F+m(X=X+j|0,j)|0;var ee=H+$|0,te=V+q+m(ee,H)|0;b=y,M=R,y=c,R=I,c=a,I=T,a=o+Z+m(T=w+X|0,w)|0,o=r,w=E,r=n,E=_,n=i,_=S,i=Z+te+m(S=X+ee|0,X)|0}this._al=this._al+S|0,this._bl=this._bl+_|0,this._cl=this._cl+E|0,this._dl=this._dl+w|0,this._el=this._el+T|0,this._fl=this._fl+I|0,this._gl=this._gl+R|0,this._hl=this._hl+M|0,this._ah=this._ah+i+m(this._al,S)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+r+m(this._cl,E)|0,this._dh=this._dh+o+m(this._dl,w)|0,this._eh=this._eh+a+m(this._el,T)|0,this._fh=this._fh+c+m(this._fl,I)|0,this._gh=this._gh+y+m(this._gl,R)|0,this._hh=this._hh+b+m(this._hl,M)|0},c.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],264:[function(e,t,i){t.exports=r;var n=e("events").EventEmitter;function r(){n.call(this)}e("inherits")(r,n),r.Readable=e("readable-stream/lib/_stream_readable.js"),r.Writable=e("readable-stream/lib/_stream_writable.js"),r.Duplex=e("readable-stream/lib/_stream_duplex.js"),r.Transform=e("readable-stream/lib/_stream_transform.js"),r.PassThrough=e("readable-stream/lib/_stream_passthrough.js"),r.finished=e("readable-stream/lib/internal/streams/end-of-stream.js"),r.pipeline=e("readable-stream/lib/internal/streams/pipeline.js"),r.Stream=r,r.prototype.pipe=function(e,t){var i=this;function r(t){e.writable&&!1===e.write(t)&&i.pause&&i.pause()}function o(){i.readable&&i.resume&&i.resume()}i.on("data",r),e.on("drain",o),e._isStdio||t&&!1===t.end||(i.on("end",a),i.on("close",c));var s=!1;function a(){s||(s=!0,e.end())}function c(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function d(e){if(l(),0===n.listenerCount(this,"error"))throw e}function l(){i.removeListener("data",r),e.removeListener("drain",o),i.removeListener("end",a),i.removeListener("close",c),i.removeListener("error",d),e.removeListener("error",d),i.removeListener("end",l),i.removeListener("close",l),e.removeListener("close",l)}return i.on("error",d),e.on("error",d),i.on("end",l),i.on("close",l),e.on("close",l),e.emit("pipe",i),e}},{events:105,inherits:146,"readable-stream/lib/_stream_duplex.js":266,"readable-stream/lib/_stream_passthrough.js":267,"readable-stream/lib/_stream_readable.js":268,"readable-stream/lib/_stream_transform.js":269,"readable-stream/lib/_stream_writable.js":270,"readable-stream/lib/internal/streams/end-of-stream.js":274,"readable-stream/lib/internal/streams/pipeline.js":276}],265:[function(e,t,i){arguments[4][50][0].apply(i,arguments)},{dup:50}],266:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a<s.length;a++){var c=s[a];d.prototype[c]||(d.prototype[c]=o.prototype[c])}function d(e){if(!(this instanceof d))return new d(e);r.call(this,e),o.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",l)))}function l(){this._writableState.ended||i.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(d.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(d.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":268,"./_stream_writable":270,_process:237,inherits:146}],267:[function(e,t,i){arguments[4][52][0].apply(i,arguments)},{"./_stream_transform":269,dup:52,inherits:146}],268:[function(e,t,i){(function(i,n){(function(){"use strict";var r;t.exports=I,I.ReadableState=T;e("events").EventEmitter;var o=function(e,t){return e.listeners(t).length},s=e("./internal/streams/stream"),a=e("buffer").Buffer,c=n.Uint8Array||function(){};var d,l=e("util");d=l&&l.debuglog?l.debuglog("stream"):function(){};var u,h,f,p=e("./internal/streams/buffer_list"),g=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,m=e("../errors").codes,y=m.ERR_INVALID_ARG_TYPE,b=m.ERR_STREAM_PUSH_AFTER_EOF,S=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(I,s);var E=g.errorOrDestroy,w=["error","close","destroy","pause","resume"];function T(t,i,n){r=r||e("./_stream_duplex"),t=t||{},"boolean"!=typeof n&&(n=i instanceof r),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",n),this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(u||(u=e("string_decoder/").StringDecoder),this.decoder=new u(t.encoding),this.encoding=t.encoding)}function I(t){if(r=r||e("./_stream_duplex"),!(this instanceof I))return new I(t);var i=this instanceof r;this._readableState=new T(t,this,i),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),s.call(this)}function R(e,t,i,n,r){d("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(d("onEofChunk"),t.ended)return;if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,t.sync?O(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,A(e)))}(e,s);else if(r||(o=function(e,t){var i;n=t,a.isBuffer(n)||n instanceof c||"string"==typeof t||void 0===t||e.objectMode||(i=new y("chunk",["string","Buffer","Uint8Array"],t));var n;return i}(s,t)),o)E(e,o);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function M(e,t,i,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",i)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&O(e)),P(e,t)}Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),I.prototype.destroy=g.destroy,I.prototype._undestroy=g.undestroy,I.prototype._destroy=function(e,t){t(e)},I.prototype.push=function(e,t){var i,n=this._readableState;return n.objectMode?i=!0:"string"==typeof e&&((t=t||n.defaultEncoding)!==n.encoding&&(e=a.from(e,t),t=""),i=!0),R(this,e,t,!1,i)},I.prototype.unshift=function(e){return R(this,e,null,!0,!1)},I.prototype.isPaused=function(){return!1===this._readableState.flowing},I.prototype.setEncoding=function(t){u||(u=e("string_decoder/").StringDecoder);var i=new u(t);this._readableState.decoder=i,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=i.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function C(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var i=t.length;if(d("maybeReadMore read 0"),e.read(0),i===t.length)break}t.readingMore=!1}function x(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}I.prototype.read=function(e){d("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",r=!0),t.ended||t.reading?d("reading or ended",r=!1):r&&(d("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=C(i,t))),null===(n=e>0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<r;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=K(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i)),this},I.prototype.on=function(e,t){var n=s.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));return this._read=function(t){d("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(I.prototype[Symbol.asyncIterator]=function(){return void 0===h&&(h=e("./internal/streams/async_iterator")),h(this)}),Object.defineProperty(I.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(I.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(I.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),I._fromList=N,Object.defineProperty(I.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(I.from=function(t,i){return void 0===f&&(f=e("./internal/streams/from")),f(I,t,i)})}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":265,"./_stream_duplex":266,"./internal/streams/async_iterator":271,"./internal/streams/buffer_list":272,"./internal/streams/destroy":273,"./internal/streams/from":275,"./internal/streams/state":277,"./internal/streams/stream":278,_process:237,buffer:68,events:105,inherits:146,"string_decoder/":279,util:20}],269:[function(e,t,i){arguments[4][54][0].apply(i,arguments)},{"../errors":265,"./_stream_duplex":266,dup:54,inherits:146}],270:[function(e,t,i){(function(i,n){(function(){"use strict";function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,i){var n=e.entry;e.entry=null;for(;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var o;t.exports=I,I.WritableState=T;var s={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),c=e("buffer").Buffer,d=n.Uint8Array||function(){};var l,u=e("./internal/streams/destroy"),h=e("./internal/streams/state").getHighWaterMark,f=e("../errors").codes,p=f.ERR_INVALID_ARG_TYPE,g=f.ERR_METHOD_NOT_IMPLEMENTED,v=f.ERR_MULTIPLE_CALLBACK,m=f.ERR_STREAM_CANNOT_PIPE,y=f.ERR_STREAM_DESTROYED,b=f.ERR_STREAM_NULL_VALUES,S=f.ERR_STREAM_WRITE_AFTER_END,_=f.ERR_UNKNOWN_ENCODING,E=u.errorOrDestroy;function w(){}function T(t,n,s){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof s&&(s=n instanceof o),this.objectMode=!!t.objectMode,s&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=h(this,t,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,o=n.writecb;if("function"!=typeof o)throw new v;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,o){--t.pendingcb,n?(i.nextTick(o,r),i.nextTick(A,e,t),e._writableState.errorEmitted=!0,E(e,r)):(o(r),e._writableState.errorEmitted=!0,E(e,r),A(e,t))}(e,n,r,t,o);else{var s=C(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?i.nextTick(M,e,n,s,o):M(e,n,s,o)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}function I(t){var i=this instanceof(o=o||e("./_stream_duplex"));if(!i&&!l.call(I,this))return new I(t);this._writableState=new T(t,this,i),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function R(e,t,i,n,r,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new y("write")):i?e._writev(r,t.onwrite):e._write(r,o,t.onwrite),t.sync=!1}function M(e,t,i,n){i||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),A(e,t)}function k(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,o=new Array(n),s=t.corkedRequestsFree;s.entry=i;for(var a=0,c=!0;i;)o[a]=i,i.isBuf||(c=!1),i=i.next,a+=1;o.allBuffers=c,R(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;i;){var d=i.chunk,l=i.encoding,u=i.callback;if(R(e,t,!1,t.objectMode?1:d.length,d,l,u),i=i.next,t.bufferedRequestCount--,t.writing)break}null===i&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}function C(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function O(e,t){e._final((function(i){t.pendingcb--,i&&E(e,i),t.prefinished=!0,e.emit("prefinish"),A(e,t)}))}function A(e,t){var n=C(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,i.nextTick(O,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}e("inherits")(I,a),T.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(T.prototype,"buffer",{get:s.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(l=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!l.call(this,e)||this===I&&(e&&e._writableState instanceof T)}})):l=function(e){return e instanceof this},I.prototype.pipe=function(){E(this,new m)},I.prototype.write=function(e,t,n){var r,o=this._writableState,s=!1,a=!o.objectMode&&(r=e,c.isBuffer(r)||r instanceof d);return a&&!c.isBuffer(e)&&(e=function(e){return c.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof n&&(n=w),o.ending?function(e,t){var n=new S;E(e,n),i.nextTick(t,n)}(this,n):(a||function(e,t,n,r){var o;return null===n?o=new b:"string"==typeof n||t.objectMode||(o=new p("chunk",["string","Buffer"],n)),!o||(E(e,o),i.nextTick(r,o),!1)}(this,o,e,n))&&(o.pendingcb++,s=function(e,t,i,n,r,o){if(!i){var s=function(e,t,i){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,i));return t}(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var a=t.objectMode?1:n.length;t.length+=a;var d=t.length<t.highWaterMark;d||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,a,n,r,o);return d}(this,o,a,e,t,n)),s},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},I.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":265,"./_stream_duplex":266,"./internal/streams/destroy":273,"./internal/streams/state":277,"./internal/streams/stream":278,_process:237,buffer:68,inherits:146,"util-deprecate":283}],271:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":274,_process:237}],272:[function(e,t,i){arguments[4][57][0].apply(i,arguments)},{buffer:68,dup:57,util:20}],273:[function(e,t,i){(function(e){(function(){"use strict";function i(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(r,this,t)):e.nextTick(r,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(n,s):(s._writableState.errorEmitted=!0,e.nextTick(i,s,t)):e.nextTick(i,s,t):o?(e.nextTick(n,s),o(t)):e.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var i=e._readableState,n=e._writableState;i&&i.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:237}],274:[function(e,t,i){arguments[4][59][0].apply(i,arguments)},{"../../../errors":265,dup:59}],275:[function(e,t,i){arguments[4][60][0].apply(i,arguments)},{dup:60}],276:[function(e,t,i){arguments[4][61][0].apply(i,arguments)},{"../../../errors":265,"./end-of-stream":274,dup:61}],277:[function(e,t,i){arguments[4][62][0].apply(i,arguments)},{"../../../errors":265,dup:62}],278:[function(e,t,i){arguments[4][63][0].apply(i,arguments)},{dup:63,events:105}],279:[function(e,t,i){"use strict";var n=e("safe-buffer").Buffer,r=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=d,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=u,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,i=function(e,t,i){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==i?i:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function d(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function l(e,t){var i=(e.length-t)%3;return 0===i?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,1===i?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}i.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,i;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""},o.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},o.prototype.text=function(e,t){var i=function(e,t,i){var n=t.length-1;if(n<i)return 0;var r=s(t[n]);if(r>=0)return r>0&&(e.lastNeed=r-1),r;if(--n<i||-2===r)return 0;if(r=s(t[n]),r>=0)return r>0&&(e.lastNeed=r-2),r;if(--n<i||-2===r)return 0;if(r=s(t[n]),r>=0)return r>0&&(2===r?r=0:e.lastNeed=r-3),r;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":250}],280:[function(e,t,i){(function(t,n){(function(){var r=e("process/browser.js").nextTick,o=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function d(e,t){this._id=e,this._clearFn=t}i.setTimeout=function(){return new d(o.call(setTimeout,window,arguments),clearTimeout)},i.setInterval=function(){return new d(o.call(setInterval,window,arguments),clearInterval)},i.clearTimeout=i.clearInterval=function(e){e.close()},d.prototype.unref=d.prototype.ref=function(){},d.prototype.close=function(){this._clearFn.call(window,this._id)},i.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},i.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},i._unrefActive=i.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},i.setImmediate="function"==typeof t?t:function(e){var t=c++,n=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,r((function(){a[t]&&(n?e.apply(null,n):e.call(null),i.clearImmediate(t))})),t},i.clearImmediate="function"==typeof n?n:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":237,timers:280}],281:[function(e,t,i){t.exports={0:"O",1:"l","֭":"֖","֮":"֘","֨":"֙","֤":"֚","᪴":"ۛ","⃛":"ۛ","ؙ":"̓","ࣳ":"̓","̓":"̓","̕":"̓","ُ":"̓","ٝ":"̔","֜":"́","֝":"́","ؘ":"́","݇":"́","́":"́","॔":"́","َ":"́","̀":"̀","॓":"̀","̌":"̆","꙼":"̆","٘":"̆","ٚ":"̆","ͮ":"̆","ۨ":"̆̇","̐":"̆̇","ँ":"̆̇","ঁ":"̆̇","ઁ":"̆̇","ଁ":"̆̇","ఀ":"̆̇","ಁ":"̆̇","ഁ":"̆̇","𑒿":"̆̇","᳐":"̂","̑":"̂","ٛ":"̂","߮":"̂","꛰":"̂","֯":"̊","۟":"̊","៓":"̊","゚":"̊","ْ":"̊","ஂ":"̊","ံ":"̊","ំ":"̊","𑌀":"̊","ํ":"̊","ໍ":"̊","ͦ":"̊","ⷪ":"̊","࣫":"̈","߳":"̈","ً":"̋","ࣰ":"̋","͂":"̃","ٓ":"̃","ׄ":"̇","۬":"̇","݀":"̇","࣪":"̇","݁":"̇","͘":"̇","ֹ":"̇","ֺ":"̇","ׂ":"̇","ׁ":"̇","߭":"̇","ं":"̇","ਂ":"̇","ં":"̇","்":"̇","̷":"̸","᪷":"̨","̢":"̨","ͅ":"̨","᳒":"̄","̅":"̄","ٙ":"̄","߫":"̄","꛱":"̄","᳚":"̎","ٗ":"̒","͗":"͐","ࣿ":"͐","ࣸ":"͐","ऀ":"͒","᳭":"̖","᳜":"̩","ٖ":"̩","᳕":"̫","͇":"̳","ࣹ":"͔","ࣺ":"͕","゛":"゙","゜":"゚","̶":"̵","〬":"̉","ׅ":"̣","࣭":"̣","᳝":"̣","ִ":"̣","ٜ":"̣","़":"̣","়":"̣","਼":"̣","઼":"̣","଼":"̣","𑇊":"̣","𑓃":"̣","𐨺":"̣","࣮":"̤","᳞":"̤","༷":"̥","〭":"̥","̧":"̦","̡":"̦","̹":"̦","᳙":"̭","᳘":"̮","॒":"̱","̠":"̱","ࣱ":"ٌ","ࣨ":"ٌ","ࣥ":"ٌ","ﱞ":"ﹲّ","ࣲ":"ٍ","ﱟ":"ﹴّ","ﳲ":"ﹷّ","ﱠ":"ﹶّ","ﳳ":"ﹹّ","ﱡ":"ﹸّ","ؚ":"ِ","̗":"ِ","ﳴ":"ﹻّ","ﱢ":"ﹺّ","ﱣ":"ﹼٰ","ٟ":"ٕ","̍":"ٰ","݂":"ܼ","ਃ":"ঃ","ః":"ঃ","ಃ":"ঃ","ഃ":"ঃ","ඃ":"ঃ","း":"ঃ","𑓁":"ঃ","់":"่","່":"่","້":"้","໊":"๊","໋":"๋","꙯":"⃩","\u2028":" ","\u2029":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" ","ߺ":"_","﹍":"_","﹎":"_","﹏":"_","‐":"-","‑":"-","‒":"-","–":"-","﹘":"-","۔":"-","⁃":"-","˗":"-","−":"-","➖":"-","Ⲻ":"-","⨩":"-̓","⸚":"-̈","﬩":"-̇","∸":"-̇","⨪":"-̣","꓾":"-.","~":"〜","؍":",","٫":",","‚":",","¸":",","ꓹ":",","⸲":"،","٬":"،",";":";","⸵":"؛","ः":":","ઃ":":",":":":","։":":","܃":":","܄":":","᛬":":","︰":":","᠃":":","᠉":":","⁚":":","׃":":","˸":":","꞉":":","∶":":","ː":":","ꓽ":":","⩴":"::=","⧴":":→","!":"!","ǃ":"!","ⵑ":"!","‼":"!!","⁉":"!?","ʔ":"?","Ɂ":"?","ॽ":"?","Ꭾ":"?","ꛫ":"?","⁈":"?!","⁇":"??","⸮":"؟","𝅭":".","․":".","܁":".","܂":".","꘎":".","𐩐":".","٠":".","۰":".","ꓸ":".","ꓻ":".,","‥":"..","ꓺ":"..","…":"...","꛴":"꛳꛳","・":"·","・":"·","᛫":"·","·":"·","⸱":"·","𐄁":"·","•":"·","‧":"·","∙":"·","⋅":"·","ꞏ":"·","ᐧ":"·","⋯":"···","ⵈ":"···","ᑄ":"·<","⋗":"·>","ᐷ":"·>","ᑀ":"·>","ᔯ":"·4","ᑾ":"·b","ᒀ":"·ḃ","ᑺ":"·d","ᒘ":"·J","ᒶ":"·L","ᑶ":"·P","ᑗ":"·U","ᐺ":"·V","ᐼ":"·Ʌ","ᒮ":"·Γ","ᐎ":"·Δ","ᑙ":"·Ո","ᐌ":"·ᐁ","ᐐ":"·ᐄ","ᐒ":"·ᐅ","ᐔ":"·ᐆ","ᐗ":"·ᐊ","ᐙ":"·ᐋ","ᐾ":"·ᐲ","ᑂ":"·ᐴ","ᑆ":"·ᐹ","ᑛ":"·ᑏ","ᑔ":"·ᑐ","ᑝ":"·ᑐ","ᑟ":"·ᑑ","ᑡ":"·ᑕ","ᑣ":"·ᑖ","ᑴ":"·ᑫ","ᑸ":"·ᑮ","ᑼ":"·ᑰ","ᒒ":"·ᒉ","ᒔ":"·ᒋ","ᒖ":"·ᒌ","ᒚ":"·ᒎ","ᒜ":"·ᒐ","ᒞ":"·ᒑ","ᒬ":"·ᒣ","ᒰ":"·ᒦ","ᒲ":"·ᒧ","ᒴ":"·ᒨ","ᒸ":"·ᒫ","ᓉ":"·ᓀ","ᣆ":"·ᓂ","ᣈ":"·ᓃ","ᣊ":"·ᓄ","ᣌ":"·ᓅ","ᓋ":"·ᓇ","ᓍ":"·ᓈ","ᓜ":"·ᓓ","ᓞ":"·ᓕ","ᓠ":"·ᓖ","ᓢ":"·ᓗ","ᓤ":"·ᓘ","ᓦ":"·ᓚ","ᓨ":"·ᓛ","ᓶ":"·ᓭ","ᓸ":"·ᓯ","ᓺ":"·ᓰ","ᓼ":"·ᓱ","ᓾ":"·ᓲ","ᔀ":"·ᓴ","ᔂ":"·ᓵ","ᔗ":"·ᔐ","ᔙ":"·ᔑ","ᔛ":"·ᔒ","ᔝ":"·ᔓ","ᔟ":"·ᔔ","ᔡ":"·ᔕ","ᔣ":"·ᔖ","ᔱ":"·ᔨ","ᔳ":"·ᔩ","ᔵ":"·ᔪ","ᔷ":"·ᔫ","ᔹ":"·ᔭ","ᔻ":"·ᔮ","ᣎ":"·ᕃ","ᣏ":"·ᕆ","ᣐ":"·ᕇ","ᣑ":"·ᕈ","ᣒ":"·ᕉ","ᣓ":"·ᕋ","ᕎ":"·ᕌ","ᕛ":"·ᕚ","ᕨ":"·ᕧ","ᢳ":"·ᢱ","ᢶ":"·ᢴ","ᢹ":"·ᢸ","ᣂ":"·ᣀ","꠰":"।","॥":"।।","᰼":"᰻᰻","။":"၊၊","᪩":"᪨᪨","᪫":"᪪᪨","᭟":"᭞᭞","𐩗":"𐩖𐩖","𑑌":"𑑋𑑋","𑙂":"𑙁𑙁","𑱂":"𑱁𑱁","᱿":"᱾᱾","՝":"'","'":"'","‘":"'","’":"'","‛":"'","′":"'","‵":"'","՚":"'","׳":"'","`":"'","`":"'","`":"'","´":"'","΄":"'","´":"'","᾽":"'","᾿":"'","῾":"'","ʹ":"'","ʹ":"'","ˈ":"'","ˊ":"'","ˋ":"'","˴":"'","ʻ":"'","ʽ":"'","ʼ":"'","ʾ":"'","ꞌ":"'","י":"'","ߴ":"'","ߵ":"'","ᑊ":"'","ᛌ":"'","𖽑":"'","𖽒":"'","᳓":"''",'"':"''",""":"''","“":"''","”":"''","‟":"''","″":"''","‶":"''","〃":"''","״":"''","˝":"''","ʺ":"''","˶":"''","ˮ":"''","ײ":"''","‴":"'''","‷":"'''","⁗":"''''","Ɓ":"'B","Ɗ":"'D","ʼn":"'n","Ƥ":"'P","Ƭ":"'T","Ƴ":"'Y","[":"(","❨":"(","❲":"(","〔":"(","﴾":"(","⸨":"((","㈠":"(ー)","⑵":"(2)","⒇":"(2O)","⑶":"(3)","⑷":"(4)","⑸":"(5)","⑹":"(6)","⑺":"(7)","⑻":"(8)","⑼":"(9)","⒜":"(a)","🄐":"(A)","⒝":"(b)","🄑":"(B)","⒞":"(c)","🄒":"(C)","⒟":"(d)","🄓":"(D)","⒠":"(e)","🄔":"(E)","⒡":"(f)","🄕":"(F)","⒢":"(g)","🄖":"(G)","⒣":"(h)","🄗":"(H)","⒤":"(i)","⒥":"(j)","🄙":"(J)","⒦":"(k)","🄚":"(K)","⑴":"(l)","🄘":"(l)","⒧":"(l)","🄛":"(L)","⑿":"(l2)","⒀":"(l3)","⒁":"(l4)","⒂":"(l5)","⒃":"(l6)","⒄":"(l7)","⒅":"(l8)","⒆":"(l9)","⑾":"(ll)","⑽":"(lO)","🄜":"(M)","⒩":"(n)","🄝":"(N)","⒪":"(o)","🄞":"(O)","⒫":"(p)","🄟":"(P)","⒬":"(q)","🄠":"(Q)","⒭":"(r)","🄡":"(R)","⒨":"(rn)","⒮":"(s)","🄢":"(S)","🄪":"(S)","⒯":"(t)","🄣":"(T)","⒰":"(u)","🄤":"(U)","⒱":"(v)","🄥":"(V)","⒲":"(w)","🄦":"(W)","⒳":"(x)","🄧":"(X)","⒴":"(y)","🄨":"(Y)","⒵":"(z)","🄩":"(Z)","㈀":"(ᄀ)","㈎":"(가)","㈁":"(ᄂ)","㈏":"(나)","㈂":"(ᄃ)","㈐":"(다)","㈃":"(ᄅ)","㈑":"(라)","㈄":"(ᄆ)","㈒":"(마)","㈅":"(ᄇ)","㈓":"(바)","㈆":"(ᄉ)","㈔":"(사)","㈇":"(ᄋ)","㈕":"(아)","㈝":"(오전)","㈞":"(오후)","㈈":"(ᄌ)","㈖":"(자)","㈜":"(주)","㈉":"(ᄎ)","㈗":"(차)","㈊":"(ᄏ)","㈘":"(카)","㈋":"(ᄐ)","㈙":"(타)","㈌":"(ᄑ)","㈚":"(파)","㈍":"(ᄒ)","㈛":"(하)","㈦":"(七)","㈢":"(三)","🉁":"(三)","㈨":"(九)","㈡":"(二)","🉂":"(二)","㈤":"(五)","㈹":"(代)","㈽":"(企)","㉁":"(休)","㈧":"(八)","㈥":"(六)","㈸":"(労)","🉇":"(勝)","㈩":"(十)","㈿":"(協)","㈴":"(名)","㈺":"(呼)","㈣":"(四)","㈯":"(土)","㈻":"(学)","🉃":"(安)","🉅":"(打)","🉈":"(敗)","㈰":"(日)","㈪":"(月)","㈲":"(有)","㈭":"(木)","🉀":"(本)","㈱":"(株)","㈬":"(水)","㈫":"(火)","🉄":"(点)","㈵":"(特)","🉆":"(盗)","㈼":"(監)","㈳":"(社)","㈷":"(祝)","㉀":"(祭)","㉂":"(自)","㉃":"(至)","㈶":"(財)","㈾":"(資)","㈮":"(金)","]":")","❩":")","❳":")","〕":")","﴿":")","⸩":"))","❴":"{","𝄔":"{","❵":"}","〚":"⟦","〛":"⟧","⟨":"❬","〈":"❬","〈":"❬","㇛":"❬","く":"❬","𡿨":"❬","⟩":"❭","〉":"❭","〉":"❭","^":"︿","⸿":"¶","⁎":"*","٭":"*","∗":"*","𐌟":"*","᜵":"/","⁁":"/","∕":"/","⁄":"/","╱":"/","⟋":"/","⧸":"/","𝈺":"/","㇓":"/","〳":"/","Ⳇ":"/","ノ":"/","丿":"/","⼃":"/","⧶":"/̄","⫽":"//","⫻":"///","\":"\\","﹨":"\\","∖":"\\","⟍":"\\","⧵":"\\","⧹":"\\","𝈏":"\\","𝈻":"\\","㇔":"\\","丶":"\\","⼂":"\\","⳹":"\\\\","⑊":"\\\\","⟈":"\\ᑕ","ꝸ":"&","૰":"॰","𑂻":"॰","𑇇":"॰","⚬":"॰","𑇛":"꣼","៙":"๏","៕":"๚","៚":"๛","༌":"་","༎":"།།","˄":"^","ˆ":"^","꙾":"ˇ","˘":"ˇ","‾":"ˉ","﹉":"ˉ","﹊":"ˉ","﹋":"ˉ","﹌":"ˉ","¯":"ˉ"," ̄":"ˉ","▔":"ˉ","ъ":"ˉb","ꙑ":"ˉbi","͵":"ˏ","˻":"˪","꜖":"˪","꜔":"˫","。":"˳","⸰":"°","˚":"°","∘":"°","○":"°","◦":"°","⍜":"°̲","⍤":"°̈","℃":"°C","℉":"°F","௵":"௳","༛":"༚༚","༟":"༚༝","࿎":"༝༚","༞":"༝༝","Ⓒ":"©","Ⓡ":"®","Ⓟ":"℗","𝈛":"⅄","⯬":"↞","⯭":"↟","⯮":"↠","⯯":"↡","↵":"↲","⥥":"⇃⇂","⥯":"⇃ᛚ","𝛛":"∂","𝜕":"∂","𝝏":"∂","𝞉":"∂","𝟃":"∂","𞣌":"∂","𞣍":"∂̵","ð":"∂̵","⌀":"∅","𝛁":"∇","𝛻":"∇","𝜵":"∇","𝝯":"∇","𝞩":"∇","𑢨":"∇","⍢":"∇̈","⍫":"∇̴","█":"∎","■":"∎","⨿":"∐","᛭":"+","➕":"+","𐊛":"+","⨣":"+̂","⨢":"+̊","⨤":"+̃","∔":"+̇","⨥":"+̣","⨦":"+̰","⨧":"+₂","➗":"÷","‹":"<","❮":"<","˂":"<","𝈶":"<","ᐸ":"<","ᚲ":"<","⋖":"<·","Ⲵ":"<·","ᑅ":"<·","≪":"<<","⋘":"<<<","᐀":"=","⹀":"=","゠":"=","꓿":"=","≚":"=̆","≙":"=̂","≗":"=̊","≐":"=̇","≑":"=̣̇","⩮":"=⃰","⩵":"==","⩶":"===","≞":"=ͫ","›":">","❯":">","˃":">","𝈷":">","ᐳ":">","𖼿":">","ᑁ":">·","⪥":"><","≫":">>","⨠":">>","⋙":">>>","⁓":"~","˜":"~","῀":"~","∼":"~","⍨":"~̈","⸞":"~̇","⩪":"~̇","⸟":"~̣","𞣈":"∠","⋀":"∧","∯":"∮∮","∰":"∮∮∮","⸫":"∴","⸪":"∵","⸬":"∷","𑇞":"≈","♎":"≏","🝞":"≏","≣":"≡","⨃":"⊍","⨄":"⊎","𝈸":"⊏","𝈹":"⊐","⨅":"⊓","⨆":"⊔","⨂":"⊗","⍟":"⊛","🝱":"⊠","🝕":"⊡","◁":"⊲","▷":"⊳","⍣":"⋆̈","︴":"⌇","◠":"⌒","⨽":"⌙","⌥":"⌤","⧇":"⌻","◎":"⌾","⦾":"⌾","⧅":"⍂","⦰":"⍉","⏃":"⍋","⏂":"⍎","⏁":"⍕","⏆":"⍭","☸":"⎈","︵":"⏜","︶":"⏝","︷":"⏞","︸":"⏟","︹":"⏠","︺":"⏡","▱":"⏥","⏼":"⏻","︱":"│","|":"│","┃":"│","┏":"┌","┣":"├","▐":"▌","▗":"▖","▝":"▘","☐":"□","■":"▪","▸":"▶","►":"▶","⳩":"☧","🜊":"☩","🌒":"☽","🌙":"☽","⏾":"☾","🌘":"☾","⧙":"⦚","🜺":"⧟","⨾":"⨟","𐆠":"⳨","♩":"𝅘𝅥","♪":"𝅘𝅥𝅮","⓪":"🄍","↺":"🄎","˙":"ॱ","ൎ":"ॱ","-":"ー","—":"ー","―":"ー","─":"ー","━":"ー","㇐":"ー","ꟷ":"ー","ᅳ":"ー","ㅡ":"ー","一":"ー","⼀":"ー","ᆖ":"ーー","ힹ":"ーᅡ","ힺ":"ーᅥ","ힻ":"ーᅥ丨","ힼ":"ーᅩ","ᆕ":"ーᅮ","ᅴ":"ー丨","ㅢ":"ー丨","ᆗ":"ー丨ᅮ","🄏":"$⃠","₤":"£","〒":"₸","〶":"₸","᭜":"᭐","꧆":"꧐","𑓑":"১","೧":"౧","ၥ":"၁","①":"➀","⑩":"➉","⏨":"₁₀","𝟐":"2","𝟚":"2","𝟤":"2","𝟮":"2","𝟸":"2","🯲":"2","Ꝛ":"2","Ƨ":"2","Ϩ":"2","Ꙅ":"2","ᒿ":"2","ꛯ":"2","ꧏ":"٢","۲":"٢","૨":"२","𑓒":"২","೨":"౨","②":"➁","ƻ":"2̵","🄃":"2,","⒉":"2.","㏵":"22日","㍮":"22点","㏶":"23日","㍯":"23点","㏷":"24日","㍰":"24点","㏸":"25日","㏹":"26日","㏺":"27日","㏻":"28日","㏼":"29日","㏴":"2l日","㍭":"2l点","⒛":"2O.","㏳":"2O日","㍬":"2O点","෩":"෨ා","෯":"෨ී","㏡":"2日","㋁":"2月","㍚":"2点","𝈆":"3","𝟑":"3","𝟛":"3","𝟥":"3","𝟯":"3","𝟹":"3","🯳":"3","Ɜ":"3","Ȝ":"3","Ʒ":"3","Ꝫ":"3","Ⳍ":"3","З":"3","Ӡ":"3","𖼻":"3","𑣊":"3","۳":"٣","𞣉":"٣","૩":"३","③":"➂","Ҙ":"3̦","🄄":"3,","⒊":"3.","㏾":"3l日","㏽":"3O日","㏢":"3日","㋂":"3月","㍛":"3点","𝟒":"4","𝟜":"4","𝟦":"4","𝟰":"4","𝟺":"4","🯴":"4","Ꮞ":"4","𑢯":"4","۴":"٤","૪":"४","④":"➃","🄅":"4,","⒋":"4.","ᔰ":"4·","㏣":"4日","㋃":"4月","㍜":"4点","𝟓":"5","𝟝":"5","𝟧":"5","𝟱":"5","𝟻":"5","🯵":"5","Ƽ":"5","𑢻":"5","⑤":"➄","🄆":"5,","⒌":"5.","㏤":"5日","㋄":"5月","㍝":"5点","𝟔":"6","𝟞":"6","𝟨":"6","𝟲":"6","𝟼":"6","🯶":"6","Ⳓ":"6","б":"6","Ꮾ":"6","𑣕":"6","۶":"٦","𑓖":"৬","⑥":"➅","🄇":"6,","⒍":"6.","㏥":"6日","㋅":"6月","㍞":"6点","𝈒":"7","𝟕":"7","𝟟":"7","𝟩":"7","𝟳":"7","𝟽":"7","🯷":"7","𐓒":"7","𑣆":"7","⑦":"➆","🄈":"7,","⒎":"7.","㏦":"7日","㋆":"7月","㍟":"7点","ଃ":"8","৪":"8","੪":"8","𞣋":"8","𝟖":"8","𝟠":"8","𝟪":"8","𝟴":"8","𝟾":"8","🯸":"8","ȣ":"8","Ȣ":"8","𐌚":"8","૮":"८","⑧":"➇","🄉":"8,","⒏":"8.","㏧":"8日","㋇":"8月","㍠":"8点","੧":"9","୨":"9","৭":"9","൭":"9","𝟗":"9","𝟡":"9","𝟫":"9","𝟵":"9","𝟿":"9","🯹":"9","Ꝯ":"9","Ⳋ":"9","𑣌":"9","𑢬":"9","𑣖":"9","१":"٩","𑣤":"٩","۹":"٩","೯":"౯","⑨":"➈","🄊":"9,","⒐":"9.","㏨":"9日","㋈":"9月","㍡":"9点","⍺":"a","a":"a","𝐚":"a","𝑎":"a","𝒂":"a","𝒶":"a","𝓪":"a","𝔞":"a","𝕒":"a","𝖆":"a","𝖺":"a","𝗮":"a","𝘢":"a","𝙖":"a","𝚊":"a","ɑ":"a","α":"a","𝛂":"a","𝛼":"a","𝜶":"a","𝝰":"a","𝞪":"a","а":"a","ⷶ":"ͣ","A":"A","𝐀":"A","𝐴":"A","𝑨":"A","𝒜":"A","𝓐":"A","𝔄":"A","𝔸":"A","𝕬":"A","𝖠":"A","𝗔":"A","𝘈":"A","𝘼":"A","𝙰":"A","Α":"A","𝚨":"A","𝛢":"A","𝜜":"A","𝝖":"A","𝞐":"A","А":"A","Ꭺ":"A","ᗅ":"A","ꓮ":"A","𖽀":"A","𐊠":"A","⍶":"a̲","ǎ":"ă","Ǎ":"Ă","ȧ":"å","Ȧ":"Å","ẚ":"ả","℀":"a/c","℁":"a/s","ꜳ":"aa","Ꜳ":"AA","æ":"ae","ӕ":"ae","Æ":"AE","Ӕ":"AE","ꜵ":"ao","Ꜵ":"AO","🜇":"AR","ꜷ":"au","Ꜷ":"AU","ꜹ":"av","ꜻ":"av","Ꜹ":"AV","Ꜻ":"AV","ꜽ":"ay","Ꜽ":"AY","ꭺ":"ᴀ","∀":"Ɐ","𝈗":"Ɐ","ᗄ":"Ɐ","ꓯ":"Ɐ","𐐟":"Ɒ","𝐛":"b","𝑏":"b","𝒃":"b","𝒷":"b","𝓫":"b","𝔟":"b","𝕓":"b","𝖇":"b","𝖻":"b","𝗯":"b","𝘣":"b","𝙗":"b","𝚋":"b","Ƅ":"b","Ь":"b","Ꮟ":"b","ᑲ":"b","ᖯ":"b","B":"B","ℬ":"B","𝐁":"B","𝐵":"B","𝑩":"B","𝓑":"B","𝔅":"B","𝔹":"B","𝕭":"B","𝖡":"B","𝗕":"B","𝘉":"B","𝘽":"B","𝙱":"B","Ꞵ":"B","Β":"B","𝚩":"B","𝛣":"B","𝜝":"B","𝝗":"B","𝞑":"B","В":"B","Ᏼ":"B","ᗷ":"B","ꓐ":"B","𐊂":"B","𐊡":"B","𐌁":"B","ɓ":"b̔","ᑳ":"ḃ","ƃ":"b̄","Ƃ":"b̄","Б":"b̄","ƀ":"b̵","ҍ":"b̵","Ҍ":"b̵","ѣ":"b̵","Ѣ":"b̵","ᑿ":"b·","ᒁ":"ḃ·","ᒈ":"b'","Ы":"bl","в":"ʙ","ᏼ":"ʙ","c":"c","ⅽ":"c","𝐜":"c","𝑐":"c","𝒄":"c","𝒸":"c","𝓬":"c","𝔠":"c","𝕔":"c","𝖈":"c","𝖼":"c","𝗰":"c","𝘤":"c","𝙘":"c","𝚌":"c","ᴄ":"c","ϲ":"c","ⲥ":"c","с":"c","ꮯ":"c","𐐽":"c","ⷭ":"ͨ","🝌":"C","𑣲":"C","𑣩":"C","C":"C","Ⅽ":"C","ℂ":"C","ℭ":"C","𝐂":"C","𝐶":"C","𝑪":"C","𝒞":"C","𝓒":"C","𝕮":"C","𝖢":"C","𝗖":"C","𝘊":"C","𝘾":"C","𝙲":"C","Ϲ":"C","Ⲥ":"C","С":"C","Ꮯ":"C","ꓚ":"C","𐊢":"C","𐌂":"C","𐐕":"C","𐔜":"C","¢":"c̸","ȼ":"c̸","₡":"C⃫","🅮":"C⃠","ç":"c̦","ҫ":"c̦","Ç":"C̦","Ҫ":"C̦","Ƈ":"C'","℅":"c/o","℆":"c/u","🅭":"㏄\t⃝","⋴":"ꞓ","ɛ":"ꞓ","ε":"ꞓ","ϵ":"ꞓ","𝛆":"ꞓ","𝛜":"ꞓ","𝜀":"ꞓ","𝜖":"ꞓ","𝜺":"ꞓ","𝝐":"ꞓ","𝝴":"ꞓ","𝞊":"ꞓ","𝞮":"ꞓ","𝟄":"ꞓ","ⲉ":"ꞓ","є":"ꞓ","ԑ":"ꞓ","ꮛ":"ꞓ","𑣎":"ꞓ","𐐩":"ꞓ","€":"Ꞓ","Ⲉ":"Ꞓ","Є":"Ꞓ","⍷":"ꞓ̲","ͽ":"ꜿ","Ͽ":"Ꜿ","ⅾ":"d","ⅆ":"d","𝐝":"d","𝑑":"d","𝒅":"d","𝒹":"d","𝓭":"d","𝔡":"d","𝕕":"d","𝖉":"d","𝖽":"d","𝗱":"d","𝘥":"d","𝙙":"d","𝚍":"d","ԁ":"d","Ꮷ":"d","ᑯ":"d","ꓒ":"d","Ⅾ":"D","ⅅ":"D","𝐃":"D","𝐷":"D","𝑫":"D","𝒟":"D","𝓓":"D","𝔇":"D","𝔻":"D","𝕯":"D","𝖣":"D","𝗗":"D","𝘋":"D","𝘿":"D","𝙳":"D","Ꭰ":"D","ᗞ":"D","ᗪ":"D","ꓓ":"D","ɗ":"d̔","ɖ":"d̨","ƌ":"d̄","đ":"d̵","Đ":"D̵","Ð":"D̵","Ɖ":"D̵","₫":"ḏ̵","ꝺ":"Ꝺ","ᑻ":"d·","ᒇ":"d'","ʤ":"dȝ","dz":"dz","ʣ":"dz","Dz":"Dz","DZ":"DZ","dž":"dž","Dž":"Dž","DŽ":"DŽ","ʥ":"dʑ","ꭰ":"ᴅ","⸹":"ẟ","δ":"ẟ","𝛅":"ẟ","𝛿":"ẟ","𝜹":"ẟ","𝝳":"ẟ","𝞭":"ẟ","ծ":"ẟ","ᕷ":"ẟ","℮":"e","e":"e","ℯ":"e","ⅇ":"e","𝐞":"e","𝑒":"e","𝒆":"e","𝓮":"e","𝔢":"e","𝕖":"e","𝖊":"e","𝖾":"e","𝗲":"e","𝘦":"e","𝙚":"e","𝚎":"e","ꬲ":"e","е":"e","ҽ":"e","ⷷ":"ͤ","⋿":"E","E":"E","ℰ":"E","𝐄":"E","𝐸":"E","𝑬":"E","𝓔":"E","𝔈":"E","𝔼":"E","𝕰":"E","𝖤":"E","𝗘":"E","𝘌":"E","𝙀":"E","𝙴":"E","Ε":"E","𝚬":"E","𝛦":"E","𝜠":"E","𝝚":"E","𝞔":"E","Е":"E","ⴹ":"E","Ꭼ":"E","ꓰ":"E","𑢦":"E","𑢮":"E","𐊆":"E","ě":"ĕ","Ě":"Ĕ","ɇ":"e̸","Ɇ":"E̸","ҿ":"ę","ꭼ":"ᴇ","ə":"ǝ","ә":"ǝ","∃":"Ǝ","ⴺ":"Ǝ","ꓱ":"Ǝ","ɚ":"ǝ˞","ᴔ":"ǝo","ꭁ":"ǝo̸","ꭂ":"ǝo̵","Ә":"Ə","𝈡":"Ɛ","ℇ":"Ɛ","Ԑ":"Ɛ","Ꮛ":"Ɛ","𖼭":"Ɛ","𐐁":"Ɛ","ᶟ":"ᵋ","ᴈ":"ɜ","з":"ɜ","ҙ":"ɜ̦","𐑂":"ɞ","ꞝ":"ʚ","𐐪":"ʚ","𝐟":"f","𝑓":"f","𝒇":"f","𝒻":"f","𝓯":"f","𝔣":"f","𝕗":"f","𝖋":"f","𝖿":"f","𝗳":"f","𝘧":"f","𝙛":"f","𝚏":"f","ꬵ":"f","ꞙ":"f","ſ":"f","ẝ":"f","ք":"f","𝈓":"F","ℱ":"F","𝐅":"F","𝐹":"F","𝑭":"F","𝓕":"F","𝔉":"F","𝔽":"F","𝕱":"F","𝖥":"F","𝗙":"F","𝘍":"F","𝙁":"F","𝙵":"F","Ꞙ":"F","Ϝ":"F","𝟊":"F","ᖴ":"F","ꓝ":"F","𑣂":"F","𑢢":"F","𐊇":"F","𐊥":"F","𐔥":"F","ƒ":"f̦","Ƒ":"F̦","ᵮ":"f̴","℻":"FAX","ff":"ff","ffi":"ffi","ffl":"ffl","fi":"fi","fl":"fl","ʩ":"fŋ","ᖵ":"Ⅎ","ꓞ":"Ⅎ","𝈰":"ꟻ","ᖷ":"ꟻ","g":"g","ℊ":"g","𝐠":"g","𝑔":"g","𝒈":"g","𝓰":"g","𝔤":"g","𝕘":"g","𝖌":"g","𝗀":"g","𝗴":"g","𝘨":"g","𝙜":"g","𝚐":"g","ɡ":"g","ᶃ":"g","ƍ":"g","ց":"g","𝐆":"G","𝐺":"G","𝑮":"G","𝒢":"G","𝓖":"G","𝔊":"G","𝔾":"G","𝕲":"G","𝖦":"G","𝗚":"G","𝘎":"G","𝙂":"G","𝙶":"G","Ԍ":"G","Ꮐ":"G","Ᏻ":"G","ꓖ":"G","ᶢ":"ᵍ","ɠ":"g̔","ǧ":"ğ","Ǧ":"Ğ","ǵ":"ģ","ǥ":"g̵","Ǥ":"G̵","Ɠ":"G'","ԍ":"ɢ","ꮐ":"ɢ","ᏻ":"ɢ","h":"h","ℎ":"h","𝐡":"h","𝒉":"h","𝒽":"h","𝓱":"h","𝔥":"h","𝕙":"h","𝖍":"h","𝗁":"h","𝗵":"h","𝘩":"h","𝙝":"h","𝚑":"h","һ":"h","հ":"h","Ꮒ":"h","H":"H","ℋ":"H","ℌ":"H","ℍ":"H","𝐇":"H","𝐻":"H","𝑯":"H","𝓗":"H","𝕳":"H","𝖧":"H","𝗛":"H","𝘏":"H","𝙃":"H","𝙷":"H","Η":"H","𝚮":"H","𝛨":"H","𝜢":"H","𝝜":"H","𝞖":"H","Ⲏ":"H","Н":"H","Ꮋ":"H","ᕼ":"H","ꓧ":"H","𐋏":"H","ᵸ":"ᴴ","ɦ":"h̔","ꚕ":"h̔","Ᏺ":"h̔","Ⱨ":"H̩","Ң":"H̩","ħ":"h̵","ℏ":"h̵","ћ":"h̵","Ħ":"H̵","Ӊ":"H̦","Ӈ":"H̦","н":"ʜ","ꮋ":"ʜ","ң":"ʜ̩","ӊ":"ʜ̦","ӈ":"ʜ̦","Ԋ":"Ƕ","ꮀ":"ⱶ","Ͱ":"Ⱶ","Ꭸ":"Ⱶ","Ꮀ":"Ⱶ","ꚱ":"Ⱶ","ꞕ":"ꜧ","˛":"i","⍳":"i","i":"i","ⅰ":"i","ℹ":"i","ⅈ":"i","𝐢":"i","𝑖":"i","𝒊":"i","𝒾":"i","𝓲":"i","𝔦":"i","𝕚":"i","𝖎":"i","𝗂":"i","𝗶":"i","𝘪":"i","𝙞":"i","𝚒":"i","ı":"i","𝚤":"i","ɪ":"i","ɩ":"i","ι":"i","ι":"i","ͺ":"i","𝛊":"i","𝜄":"i","𝜾":"i","𝝸":"i","𝞲":"i","і":"i","ꙇ":"i","ӏ":"i","ꭵ":"i","Ꭵ":"i","𑣃":"i","ⓛ":"Ⓘ","⍸":"i̲","ǐ":"ĭ","Ǐ":"Ĭ","ɨ":"i̵","ᵻ":"i̵","ᵼ":"i̵","ⅱ":"ii","ⅲ":"iii","ij":"ij","ⅳ":"iv","ⅸ":"ix","j":"j","ⅉ":"j","𝐣":"j","𝑗":"j","𝒋":"j","𝒿":"j","𝓳":"j","𝔧":"j","𝕛":"j","𝖏":"j","𝗃":"j","𝗷":"j","𝘫":"j","𝙟":"j","𝚓":"j","ϳ":"j","ј":"j","J":"J","𝐉":"J","𝐽":"J","𝑱":"J","𝒥":"J","𝓙":"J","𝔍":"J","𝕁":"J","𝕵":"J","𝖩":"J","𝗝":"J","𝘑":"J","𝙅":"J","𝙹":"J","Ʝ":"J","Ϳ":"J","Ј":"J","Ꭻ":"J","ᒍ":"J","ꓙ":"J","ɉ":"j̵","Ɉ":"J̵","ᒙ":"J·","𝚥":"ȷ","յ":"ȷ","ꭻ":"ᴊ","𝐤":"k","𝑘":"k","𝒌":"k","𝓀":"k","𝓴":"k","𝔨":"k","𝕜":"k","𝖐":"k","𝗄":"k","𝗸":"k","𝘬":"k","𝙠":"k","𝚔":"k","K":"K","K":"K","𝐊":"K","𝐾":"K","𝑲":"K","𝒦":"K","𝓚":"K","𝔎":"K","𝕂":"K","𝕶":"K","𝖪":"K","𝗞":"K","𝘒":"K","𝙆":"K","𝙺":"K","Κ":"K","𝚱":"K","𝛫":"K","𝜥":"K","𝝟":"K","𝞙":"K","Ⲕ":"K","К":"K","Ꮶ":"K","ᛕ":"K","ꓗ":"K","𐔘":"K","ƙ":"k̔","Ⱪ":"K̩","Қ":"K̩","₭":"K̵","Ꝁ":"K̵","Ҟ":"K̵","Ƙ":"K'","׀":"l","|":"l","∣":"l","⏽":"l","│":"l","١":"l","۱":"l","𐌠":"l","𞣇":"l","𝟏":"l","𝟙":"l","𝟣":"l","𝟭":"l","𝟷":"l","🯱":"l",I:"l","I":"l","Ⅰ":"l","ℐ":"l","ℑ":"l","𝐈":"l","𝐼":"l","𝑰":"l","𝓘":"l","𝕀":"l","𝕴":"l","𝖨":"l","𝗜":"l","𝘐":"l","𝙄":"l","𝙸":"l","Ɩ":"l","l":"l","ⅼ":"l","ℓ":"l","𝐥":"l","𝑙":"l","𝒍":"l","𝓁":"l","𝓵":"l","𝔩":"l","𝕝":"l","𝖑":"l","𝗅":"l","𝗹":"l","𝘭":"l","𝙡":"l","𝚕":"l","ǀ":"l","Ι":"l","𝚰":"l","𝛪":"l","𝜤":"l","𝝞":"l","𝞘":"l","Ⲓ":"l","І":"l","Ӏ":"l","ו":"l","ן":"l","ا":"l","𞸀":"l","𞺀":"l","ﺎ":"l","ﺍ":"l","ߊ":"l","ⵏ":"l","ᛁ":"l","ꓲ":"l","𖼨":"l","𐊊":"l","𐌉":"l","𝈪":"L","Ⅼ":"L","ℒ":"L","𝐋":"L","𝐿":"L","𝑳":"L","𝓛":"L","𝔏":"L","𝕃":"L","𝕷":"L","𝖫":"L","𝗟":"L","𝘓":"L","𝙇":"L","𝙻":"L","Ⳑ":"L","Ꮮ":"L","ᒪ":"L","ꓡ":"L","𖼖":"L","𑢣":"L","𑢲":"L","𐐛":"L","𐔦":"L","ﴼ":"l̋","ﴽ":"l̋","ł":"l̸","Ł":"L̸","ɭ":"l̨","Ɨ":"l̵","ƚ":"l̵","ɫ":"l̴","إ":"lٕ","ﺈ":"lٕ","ﺇ":"lٕ","ٳ":"lٕ","ŀ":"l·","Ŀ":"l·","ᒷ":"l·","🄂":"l,","⒈":"l.","ױ":"l'","⒓":"l2.","㏫":"l2日","㋋":"l2月","㍤":"l2点","⒔":"l3.","㏬":"l3日","㍥":"l3点","⒕":"l4.","㏭":"l4日","㍦":"l4点","⒖":"l5.","㏮":"l5日","㍧":"l5点","⒗":"l6.","㏯":"l6日","㍨":"l6点","⒘":"l7.","㏰":"l7日","㍩":"l7点","⒙":"l8.","㏱":"l8日","㍪":"l8点","⒚":"l9.","㏲":"l9日","㍫":"l9点","lj":"lj","IJ":"lJ","Lj":"Lj","LJ":"LJ","‖":"ll","∥":"ll","Ⅱ":"ll","ǁ":"ll","װ":"ll","𐆙":"l̵l̵","⒒":"ll.","Ⅲ":"lll","𐆘":"l̵l̵S̵","㏪":"ll日","㋊":"ll月","㍣":"ll点","Ю":"lO","⒑":"lO.","㏩":"lO日","㋉":"lO月","㍢":"lO点","ʪ":"ls","₶":"lt","Ⅳ":"lV","Ⅸ":"lX","ɮ":"lȝ","ʫ":"lz","أ":"lٴ","ﺄ":"lٴ","ﺃ":"lٴ","ٲ":"lٴ","ٵ":"lٴ","ﷳ":"lكبر","ﷲ":"lللّٰo","㏠":"l日","㋀":"l月","㍙":"l点","ⳑ":"ʟ","ꮮ":"ʟ","𐑃":"ʟ","M":"M","Ⅿ":"M","ℳ":"M","𝐌":"M","𝑀":"M","𝑴":"M","𝓜":"M","𝔐":"M","𝕄":"M","𝕸":"M","𝖬":"M","𝗠":"M","𝘔":"M","𝙈":"M","𝙼":"M","Μ":"M","𝚳":"M","𝛭":"M","𝜧":"M","𝝡":"M","𝞛":"M","Ϻ":"M","Ⲙ":"M","М":"M","Ꮇ":"M","ᗰ":"M","ᛖ":"M","ꓟ":"M","𐊰":"M","𐌑":"M","Ӎ":"M̦","🝫":"MB","ⷨ":"ᷟ","𝐧":"n","𝑛":"n","𝒏":"n","𝓃":"n","𝓷":"n","𝔫":"n","𝕟":"n","𝖓":"n","𝗇":"n","𝗻":"n","𝘯":"n","𝙣":"n","𝚗":"n","ո":"n","ռ":"n","N":"N","ℕ":"N","𝐍":"N","𝑁":"N","𝑵":"N","𝒩":"N","𝓝":"N","𝔑":"N","𝕹":"N","𝖭":"N","𝗡":"N","𝘕":"N","𝙉":"N","𝙽":"N","Ν":"N","𝚴":"N","𝛮":"N","𝜨":"N","𝝢":"N","𝞜":"N","Ⲛ":"N","ꓠ":"N","𐔓":"N","𐆎":"N̊","ɳ":"n̨","ƞ":"n̩","η":"n̩","𝛈":"n̩","𝜂":"n̩","𝜼":"n̩","𝝶":"n̩","𝞰":"n̩","Ɲ":"N̦","ᵰ":"n̴","nj":"nj","Nj":"Nj","NJ":"NJ","№":"No","ͷ":"ᴎ","и":"ᴎ","𐑍":"ᴎ","ņ":"ɲ","ం":"o","ಂ":"o","ം":"o","ං":"o","०":"o","੦":"o","૦":"o","௦":"o","౦":"o","೦":"o","൦":"o","๐":"o","໐":"o","၀":"o","٥":"o","۵":"o","o":"o","ℴ":"o","𝐨":"o","𝑜":"o","𝒐":"o","𝓸":"o","𝔬":"o","𝕠":"o","𝖔":"o","𝗈":"o","𝗼":"o","𝘰":"o","𝙤":"o","𝚘":"o","ᴏ":"o","ᴑ":"o","ꬽ":"o","ο":"o","𝛐":"o","𝜊":"o","𝝄":"o","𝝾":"o","𝞸":"o","σ":"o","𝛔":"o","𝜎":"o","𝝈":"o","𝞂":"o","𝞼":"o","ⲟ":"o","о":"o","ჿ":"o","օ":"o","ס":"o","ه":"o","𞸤":"o","𞹤":"o","𞺄":"o","ﻫ":"o","ﻬ":"o","ﻪ":"o","ﻩ":"o","ھ":"o","ﮬ":"o","ﮭ":"o","ﮫ":"o","ﮪ":"o","ہ":"o","ﮨ":"o","ﮩ":"o","ﮧ":"o","ﮦ":"o","ە":"o","ഠ":"o","ဝ":"o","𐓪":"o","𑣈":"o","𑣗":"o","𐐬":"o","߀":"O","০":"O","୦":"O","〇":"O","𑓐":"O","𑣠":"O","𝟎":"O","𝟘":"O","𝟢":"O","𝟬":"O","𝟶":"O","🯰":"O","O":"O","𝐎":"O","𝑂":"O","𝑶":"O","𝒪":"O","𝓞":"O","𝔒":"O","𝕆":"O","𝕺":"O","𝖮":"O","𝗢":"O","𝘖":"O","𝙊":"O","𝙾":"O","Ο":"O","𝚶":"O","𝛰":"O","𝜪":"O","𝝤":"O","𝞞":"O","Ⲟ":"O","О":"O","Օ":"O","ⵔ":"O","ዐ":"O","ଠ":"O","𐓂":"O","ꓳ":"O","𑢵":"O","𐊒":"O","𐊫":"O","𐐄":"O","𐔖":"O","⁰":"º","ᵒ":"º","ǒ":"ŏ","Ǒ":"Ŏ","ۿ":"ô","Ő":"Ö","ø":"o̸","ꬾ":"o̸","Ø":"O̸","ⵁ":"O̸","Ǿ":"Ó̸","ɵ":"o̵","ꝋ":"o̵","ө":"o̵","ѳ":"o̵","ꮎ":"o̵","ꮻ":"o̵","⊖":"O̵","⊝":"O̵","⍬":"O̵","𝈚":"O̵","🜔":"O̵","Ɵ":"O̵","Ꝋ":"O̵","θ":"O̵","ϑ":"O̵","𝛉":"O̵","𝛝":"O̵","𝜃":"O̵","𝜗":"O̵","𝜽":"O̵","𝝑":"O̵","𝝷":"O̵","𝞋":"O̵","𝞱":"O̵","𝟅":"O̵","Θ":"O̵","ϴ":"O̵","𝚯":"O̵","𝚹":"O̵","𝛩":"O̵","𝛳":"O̵","𝜣":"O̵","𝜭":"O̵","𝝝":"O̵","𝝧":"O̵","𝞗":"O̵","𝞡":"O̵","Ө":"O̵","Ѳ":"O̵","ⴱ":"O̵","Ꮎ":"O̵","Ꮻ":"O̵","ꭴ":"ơ","ﳙ":"oٰ","🄁":"O,","🄀":"O.","ơ":"o'","Ơ":"O'","Ꭴ":"O'","%":"º/₀","٪":"º/₀","⁒":"º/₀","‰":"º/₀₀","؉":"º/₀₀","‱":"º/₀₀₀","؊":"º/₀₀₀","œ":"oe","Œ":"OE","ɶ":"oᴇ","∞":"oo","ꝏ":"oo","ꚙ":"oo","Ꝏ":"OO","Ꚙ":"OO","ﳗ":"oج","ﱑ":"oج","ﳘ":"oم","ﱒ":"oم","ﶓ":"oمج","ﶔ":"oمم","ﱓ":"oى","ﱔ":"oى","ൟ":"oരo","တ":"oာ","㍘":"O点","ↄ":"ɔ","ᴐ":"ɔ","ͻ":"ɔ","𐑋":"ɔ","Ↄ":"Ɔ","Ͻ":"Ɔ","ꓛ":"Ɔ","𐐣":"Ɔ","ꬿ":"ɔ̸","ꭢ":"ɔe","𐐿":"ɷ","⍴":"p","p":"p","𝐩":"p","𝑝":"p","𝒑":"p","𝓅":"p","𝓹":"p","𝔭":"p","𝕡":"p","𝖕":"p","𝗉":"p","𝗽":"p","𝘱":"p","𝙥":"p","𝚙":"p","ρ":"p","ϱ":"p","𝛒":"p","𝛠":"p","𝜌":"p","𝜚":"p","𝝆":"p","𝝔":"p","𝞀":"p","𝞎":"p","𝞺":"p","𝟈":"p","ⲣ":"p","р":"p","P":"P","ℙ":"P","𝐏":"P","𝑃":"P","𝑷":"P","𝒫":"P","𝓟":"P","𝔓":"P","𝕻":"P","𝖯":"P","𝗣":"P","𝘗":"P","𝙋":"P","𝙿":"P","Ρ":"P","𝚸":"P","𝛲":"P","𝜬":"P","𝝦":"P","𝞠":"P","Ⲣ":"P","Р":"P","Ꮲ":"P","ᑭ":"P","ꓑ":"P","𐊕":"P","ƥ":"p̔","ᵽ":"p̵","ᑷ":"p·","ᒆ":"P'","ᴩ":"ᴘ","ꮲ":"ᴘ","φ":"ɸ","ϕ":"ɸ","𝛗":"ɸ","𝛟":"ɸ","𝜑":"ɸ","𝜙":"ɸ","𝝋":"ɸ","𝝓":"ɸ","𝞅":"ɸ","𝞍":"ɸ","𝞿":"ɸ","𝟇":"ɸ","ⲫ":"ɸ","ф":"ɸ","𝐪":"q","𝑞":"q","𝒒":"q","𝓆":"q","𝓺":"q","𝔮":"q","𝕢":"q","𝖖":"q","𝗊":"q","𝗾":"q","𝘲":"q","𝙦":"q","𝚚":"q","ԛ":"q","գ":"q","զ":"q","ℚ":"Q","𝐐":"Q","𝑄":"Q","𝑸":"Q","𝒬":"Q","𝓠":"Q","𝔔":"Q","𝕼":"Q","𝖰":"Q","𝗤":"Q","𝘘":"Q","𝙌":"Q","𝚀":"Q","ⵕ":"Q","ʠ":"q̔","🜀":"QE","ᶐ":"ɋ","ᴋ":"ĸ","κ":"ĸ","ϰ":"ĸ","𝛋":"ĸ","𝛞":"ĸ","𝜅":"ĸ","𝜘":"ĸ","𝜿":"ĸ","𝝒":"ĸ","𝝹":"ĸ","𝞌":"ĸ","𝞳":"ĸ","𝟆":"ĸ","ⲕ":"ĸ","к":"ĸ","ꮶ":"ĸ","қ":"ĸ̩","ҟ":"ĸ̵","𝐫":"r","𝑟":"r","𝒓":"r","𝓇":"r","𝓻":"r","𝔯":"r","𝕣":"r","𝖗":"r","𝗋":"r","𝗿":"r","𝘳":"r","𝙧":"r","𝚛":"r","ꭇ":"r","ꭈ":"r","ᴦ":"r","ⲅ":"r","г":"r","ꮁ":"r","𝈖":"R","ℛ":"R","ℜ":"R","ℝ":"R","𝐑":"R","𝑅":"R","𝑹":"R","𝓡":"R","𝕽":"R","𝖱":"R","𝗥":"R","𝘙":"R","𝙍":"R","𝚁":"R","Ʀ":"R","Ꭱ":"R","Ꮢ":"R","𐒴":"R","ᖇ":"R","ꓣ":"R","𖼵":"R","ɽ":"r̨","ɼ":"r̩","ɍ":"r̵","ғ":"r̵","ᵲ":"r̴","ґ":"r'","𑣣":"rn",m:"rn","ⅿ":"rn","𝐦":"rn","𝑚":"rn","𝒎":"rn","𝓂":"rn","𝓶":"rn","𝔪":"rn","𝕞":"rn","𝖒":"rn","𝗆":"rn","𝗺":"rn","𝘮":"rn","𝙢":"rn","𝚖":"rn","𑜀":"rn","₥":"rn̸","ɱ":"rn̦","ᵯ":"rn̴","₨":"Rs","ꭱ":"ʀ","ꮢ":"ʀ","я":"ᴙ","ᵳ":"ɾ̴","℩":"ɿ","s":"s","𝐬":"s","𝑠":"s","𝒔":"s","𝓈":"s","𝓼":"s","𝔰":"s","𝕤":"s","𝖘":"s","𝗌":"s","𝘀":"s","𝘴":"s","𝙨":"s","𝚜":"s","ꜱ":"s","ƽ":"s","ѕ":"s","ꮪ":"s","𑣁":"s","𐑈":"s","S":"S","𝐒":"S","𝑆":"S","𝑺":"S","𝒮":"S","𝓢":"S","𝔖":"S","𝕊":"S","𝕾":"S","𝖲":"S","𝗦":"S","𝘚":"S","𝙎":"S","𝚂":"S","Ѕ":"S","Տ":"S","Ꮥ":"S","Ꮪ":"S","ꓢ":"S","𖼺":"S","𐊖":"S","𐐠":"S","ʂ":"s̨","ᵴ":"s̴","ꞵ":"ß","β":"ß","ϐ":"ß","𝛃":"ß","𝛽":"ß","𝜷":"ß","𝝱":"ß","𝞫":"ß","Ᏸ":"ß","🝜":"sss","st":"st","∫":"ʃ","ꭍ":"ʃ","∑":"Ʃ","⅀":"Ʃ","Σ":"Ʃ","𝚺":"Ʃ","𝛴":"Ʃ","𝜮":"Ʃ","𝝨":"Ʃ","𝞢":"Ʃ","ⵉ":"Ʃ","∬":"ʃʃ","∭":"ʃʃʃ","⨌":"ʃʃʃʃ","𝐭":"t","𝑡":"t","𝒕":"t","𝓉":"t","𝓽":"t","𝔱":"t","𝕥":"t","𝖙":"t","𝗍":"t","𝘁":"t","𝘵":"t","𝙩":"t","𝚝":"t","⊤":"T","⟙":"T","🝨":"T","T":"T","𝐓":"T","𝑇":"T","𝑻":"T","𝒯":"T","𝓣":"T","𝔗":"T","𝕋":"T","𝕿":"T","𝖳":"T","𝗧":"T","𝘛":"T","𝙏":"T","𝚃":"T","Τ":"T","𝚻":"T","𝛵":"T","𝜯":"T","𝝩":"T","𝞣":"T","Ⲧ":"T","Т":"T","Ꭲ":"T","ꓔ":"T","𖼊":"T","𑢼":"T","𐊗":"T","𐊱":"T","𐌕":"T","ƭ":"t̔","⍡":"T̈","Ⱦ":"T̸","Ț":"Ţ","Ʈ":"T̨","Ҭ":"T̩","₮":"T⃫","ŧ":"t̵","Ŧ":"T̵","ᵵ":"t̴","Ⴀ":"Ꞇ","Ꜩ":"T3","ʨ":"tɕ","℡":"TEL","ꝷ":"tf","ʦ":"ts","ʧ":"tʃ","ꜩ":"tȝ","τ":"ᴛ","𝛕":"ᴛ","𝜏":"ᴛ","𝝉":"ᴛ","𝞃":"ᴛ","𝞽":"ᴛ","т":"ᴛ","ꭲ":"ᴛ","ҭ":"ᴛ̩","ţ":"ƫ","ț":"ƫ","Ꮏ":"ƫ","𝐮":"u","𝑢":"u","𝒖":"u","𝓊":"u","𝓾":"u","𝔲":"u","𝕦":"u","𝖚":"u","𝗎":"u","𝘂":"u","𝘶":"u","𝙪":"u","𝚞":"u","ꞟ":"u","ᴜ":"u","ꭎ":"u","ꭒ":"u","ʋ":"u","υ":"u","𝛖":"u","𝜐":"u","𝝊":"u","𝞄":"u","𝞾":"u","ս":"u","𐓶":"u","𑣘":"u","∪":"U","⋃":"U","𝐔":"U","𝑈":"U","𝑼":"U","𝒰":"U","𝓤":"U","𝔘":"U","𝕌":"U","𝖀":"U","𝖴":"U","𝗨":"U","𝘜":"U","𝙐":"U","𝚄":"U","Ս":"U","ሀ":"U","𐓎":"U","ᑌ":"U","ꓴ":"U","𖽂":"U","𑢸":"U","ǔ":"ŭ","Ǔ":"Ŭ","ᵾ":"u̵","ꮜ":"u̵","Ʉ":"U̵","Ꮜ":"U̵","ᑘ":"U·","ᑧ":"U'","ᵫ":"ue","ꭣ":"uo","ṃ":"ꭑ","պ":"ɰ","ሣ":"ɰ","℧":"Ʊ","ᘮ":"Ʊ","ᘴ":"Ʊ","ᵿ":"ʊ̵","∨":"v","⋁":"v","v":"v","ⅴ":"v","𝐯":"v","𝑣":"v","𝒗":"v","𝓋":"v","𝓿":"v","𝔳":"v","𝕧":"v","𝖛":"v","𝗏":"v","𝘃":"v","𝘷":"v","𝙫":"v","𝚟":"v","ᴠ":"v","ν":"v","𝛎":"v","𝜈":"v","𝝂":"v","𝝼":"v","𝞶":"v","ѵ":"v","ט":"v","𑜆":"v","ꮩ":"v","𑣀":"v","𝈍":"V","٧":"V","۷":"V","Ⅴ":"V","𝐕":"V","𝑉":"V","𝑽":"V","𝒱":"V","𝓥":"V","𝔙":"V","𝕍":"V","𝖁":"V","𝖵":"V","𝗩":"V","𝘝":"V","𝙑":"V","𝚅":"V","Ѵ":"V","ⴸ":"V","Ꮩ":"V","ᐯ":"V","ꛟ":"V","ꓦ":"V","𖼈":"V","𑢠":"V","𐔝":"V","𐆗":"V̵","ᐻ":"V·","🝬":"VB","ⅵ":"vi","ⅶ":"vii","ⅷ":"viii","Ⅵ":"Vl","Ⅶ":"Vll","Ⅷ":"Vlll","🜈":"Vᷤ","ᴧ":"ʌ","𐓘":"ʌ","٨":"Ʌ","۸":"Ʌ","Λ":"Ʌ","𝚲":"Ʌ","𝛬":"Ʌ","𝜦":"Ʌ","𝝠":"Ʌ","𝞚":"Ʌ","Л":"Ʌ","ⴷ":"Ʌ","𐒰":"Ʌ","ᐱ":"Ʌ","ꛎ":"Ʌ","ꓥ":"Ʌ","𖼽":"Ʌ","𐊍":"Ʌ","Ӆ":"Ʌ̦","ᐽ":"Ʌ·","ɯ":"w","𝐰":"w","𝑤":"w","𝒘":"w","𝓌":"w","𝔀":"w","𝔴":"w","𝕨":"w","𝖜":"w","𝗐":"w","𝘄":"w","𝘸":"w","𝙬":"w","𝚠":"w","ᴡ":"w","ѡ":"w","ԝ":"w","ա":"w","𑜊":"w","𑜎":"w","𑜏":"w","ꮃ":"w","𑣯":"W","𑣦":"W","𝐖":"W","𝑊":"W","𝑾":"W","𝒲":"W","𝓦":"W","𝔚":"W","𝕎":"W","𝖂":"W","𝖶":"W","𝗪":"W","𝘞":"W","𝙒":"W","𝚆":"W","Ԝ":"W","Ꮃ":"W","Ꮤ":"W","ꓪ":"W","ѽ":"w҆҇","𑓅":"ẇ","₩":"W̵","ꝡ":"w̦","ᴍ":"ʍ","м":"ʍ","ꮇ":"ʍ","ӎ":"ʍ̦","᙮":"x","×":"x","⤫":"x","⤬":"x","⨯":"x","x":"x","ⅹ":"x","𝐱":"x","𝑥":"x","𝒙":"x","𝓍":"x","𝔁":"x","𝔵":"x","𝕩":"x","𝖝":"x","𝗑":"x","𝘅":"x","𝘹":"x","𝙭":"x","𝚡":"x","х":"x","ᕁ":"x","ᕽ":"x","ⷯ":"ͯ","᙭":"X","╳":"X","𐌢":"X","𑣬":"X","X":"X","Ⅹ":"X","𝐗":"X","𝑋":"X","𝑿":"X","𝒳":"X","𝓧":"X","𝔛":"X","𝕏":"X","𝖃":"X","𝖷":"X","𝗫":"X","𝘟":"X","𝙓":"X","𝚇":"X","Ꭓ":"X","Χ":"X","𝚾":"X","𝛸":"X","𝜲":"X","𝝬":"X","𝞦":"X","Ⲭ":"X","Х":"X","ⵝ":"X","ᚷ":"X","ꓫ":"X","𐊐":"X","𐊴":"X","𐌗":"X","𐔧":"X","⨰":"ẋ","Ҳ":"X̩","𐆖":"X̵","ⅺ":"xi","ⅻ":"xii","Ⅺ":"Xl","Ⅻ":"Xll","ɣ":"y","ᶌ":"y","y":"y","𝐲":"y","𝑦":"y","𝒚":"y","𝓎":"y","𝔂":"y","𝔶":"y","𝕪":"y","𝖞":"y","𝗒":"y","𝘆":"y","𝘺":"y","𝙮":"y","𝚢":"y","ʏ":"y","ỿ":"y","ꭚ":"y","γ":"y","ℽ":"y","𝛄":"y","𝛾":"y","𝜸":"y","𝝲":"y","𝞬":"y","у":"y","ү":"y","ყ":"y","𑣜":"y","Y":"Y","𝐘":"Y","𝑌":"Y","𝒀":"Y","𝒴":"Y","𝓨":"Y","𝔜":"Y","𝕐":"Y","𝖄":"Y","𝖸":"Y","𝗬":"Y","𝘠":"Y","𝙔":"Y","𝚈":"Y","Υ":"Y","ϒ":"Y","𝚼":"Y","𝛶":"Y","𝜰":"Y","𝝪":"Y","𝞤":"Y","Ⲩ":"Y","У":"Y","Ү":"Y","Ꭹ":"Y","Ꮍ":"Y","ꓬ":"Y","𖽃":"Y","𑢤":"Y","𐊲":"Y","ƴ":"y̔","ɏ":"y̵","ұ":"y̵","¥":"Y̵","Ɏ":"Y̵","Ұ":"Y̵","ʒ":"ȝ","ꝫ":"ȝ","ⳍ":"ȝ","ӡ":"ȝ","ჳ":"ȝ","𝐳":"z","𝑧":"z","𝒛":"z","𝓏":"z","𝔃":"z","𝔷":"z","𝕫":"z","𝖟":"z","𝗓":"z","𝘇":"z","𝘻":"z","𝙯":"z","𝚣":"z","ᴢ":"z","ꮓ":"z","𑣄":"z","𐋵":"Z","𑣥":"Z","Z":"Z","ℤ":"Z","ℨ":"Z","𝐙":"Z","𝑍":"Z","𝒁":"Z","𝒵":"Z","𝓩":"Z","𝖅":"Z","𝖹":"Z","𝗭":"Z","𝘡":"Z","𝙕":"Z","𝚉":"Z","Ζ":"Z","𝚭":"Z","𝛧":"Z","𝜡":"Z","𝝛":"Z","𝞕":"Z","Ꮓ":"Z","ꓜ":"Z","𑢩":"Z","ʐ":"z̨","ƶ":"z̵","Ƶ":"Z̵","ȥ":"z̦","Ȥ":"Z̦","ᵶ":"z̴","ƿ":"þ","ϸ":"þ","Ϸ":"Þ","𐓄":"Þ","⁹":"ꝰ","ᴤ":"ƨ","ϩ":"ƨ","ꙅ":"ƨ","ь":"ƅ","ꮟ":"ƅ","ы":"ƅi","ꭾ":"ɂ","ˤ":"ˁ","ꛍ":"ʡ","⊙":"ʘ","☉":"ʘ","⨀":"ʘ","Ꙩ":"ʘ","ⵙ":"ʘ","𐓃":"ʘ","ℾ":"Γ","𝚪":"Γ","𝛤":"Γ","𝜞":"Γ","𝝘":"Γ","𝞒":"Γ","Ⲅ":"Γ","Г":"Γ","Ꮁ":"Γ","ᒥ":"Γ","𖼇":"Γ","Ғ":"Γ̵","ᒯ":"Γ·","Ґ":"Γ'","∆":"Δ","△":"Δ","🜂":"Δ","𝚫":"Δ","𝛥":"Δ","𝜟":"Δ","𝝙":"Δ","𝞓":"Δ","Ⲇ":"Δ","ⵠ":"Δ","ᐃ":"Δ","𖼚":"Δ","𐊅":"Δ","𐊣":"Δ","⍙":"Δ̲","ᐏ":"Δ·","ᐬ":"Δᐠ","𝟋":"ϝ","𝛇":"ζ","𝜁":"ζ","𝜻":"ζ","𝝵":"ζ","𝞯":"ζ","ⳤ":"ϗ","𝛌":"λ","𝜆":"λ","𝝀":"λ","𝝺":"λ","𝞴":"λ","Ⲗ":"λ","𐓛":"λ","µ":"μ","𝛍":"μ","𝜇":"μ","𝝁":"μ","𝝻":"μ","𝞵":"μ","𝛏":"ξ","𝜉":"ξ","𝝃":"ξ","𝝽":"ξ","𝞷":"ξ","𝚵":"Ξ","𝛯":"Ξ","𝜩":"Ξ","𝝣":"Ξ","𝞝":"Ξ","ϖ":"π","ℼ":"π","𝛑":"π","𝛡":"π","𝜋":"π","𝜛":"π","𝝅":"π","𝝕":"π","𝝿":"π","𝞏":"π","𝞹":"π","𝟉":"π","ᴨ":"π","п":"π","∏":"Π","ℿ":"Π","𝚷":"Π","𝛱":"Π","𝜫":"Π","𝝥":"Π","𝞟":"Π","Ⲡ":"Π","П":"Π","ꛛ":"Π","𐊭":"Ϙ","𐌒":"Ϙ","ϛ":"ς","𝛓":"ς","𝜍":"ς","𝝇":"ς","𝞁":"ς","𝞻":"ς","𝚽":"Φ","𝛷":"Φ","𝜱":"Φ","𝝫":"Φ","𝞥":"Φ","Ⲫ":"Φ","Ф":"Φ","Փ":"Φ","ቀ":"Φ","ᛰ":"Φ","𐊳":"Φ","ꭓ":"χ","ꭕ":"χ","𝛘":"χ","𝜒":"χ","𝝌":"χ","𝞆":"χ","𝟀":"χ","ⲭ":"χ","𝛙":"ψ","𝜓":"ψ","𝝍":"ψ","𝞇":"ψ","𝟁":"ψ","ѱ":"ψ","𐓹":"ψ","𝚿":"Ψ","𝛹":"Ψ","𝜳":"Ψ","𝝭":"Ψ","𝞧":"Ψ","Ⲯ":"Ψ","Ѱ":"Ψ","𐓑":"Ψ","ᛘ":"Ψ","𐊵":"Ψ","⍵":"ω","ꞷ":"ω","𝛚":"ω","𝜔":"ω","𝝎":"ω","𝞈":"ω","𝟂":"ω","ⲱ":"ω","ꙍ":"ω","Ω":"Ω","𝛀":"Ω","𝛺":"Ω","𝜴":"Ω","𝝮":"Ω","𝞨":"Ω","ᘯ":"Ω","ᘵ":"Ω","𐊶":"Ω","⍹":"ω̲","ώ":"ῴ","☰":"Ⲷ","Ⳝ":"Ϭ","җ":"ж̩","Җ":"Ж̩","𝈋":"И","Ͷ":"И","ꚡ":"И","𐐥":"И","Й":"Ѝ","Ҋ":"Ѝ̦","ѝ":"й","ҋ":"й̦","𐒼":"Ӄ","ᴫ":"л","ӆ":"л̦","ꭠ":"љ","𐓫":"ꙩ","ᷮ":"ⷬ","𐓍":"Ћ","𝈂":"Ӿ","𝈢":"Ѡ","Ꮗ":"Ѡ","ᗯ":"Ѡ","Ѽ":"Ѡ҆҇","ᣭ":"Ѡ·","Ꞷ":"Ꙍ","ӌ":"ҷ","Ӌ":"Ҷ","Ҿ":"Ҽ̨","ⲽ":"ш","Ⲽ":"Ш","Ꙑ":"Ъl","℈":"Э","🜁":"Ꙙ","𖼜":"Ꙙ","ꦒ":"ⰿ","և":"եւ","ኔ":"ձ","ﬔ":"մե","ﬕ":"մի","ﬗ":"մխ","ﬓ":"մն","∩":"Ո","⋂":"Ո","𝉅":"Ո","በ":"Ո","ᑎ":"Ո","ꓵ":"Ո","ᑚ":"Ո·","ᑨ":"Ո'","ﬖ":"վն","₽":"Ք","˓":"ՙ","ʿ":"ՙ","ℵ":"א","ﬡ":"א","אָ":"אַ","אּ":"אַ","ﭏ":"אל","ℶ":"ב","ℷ":"ג","ℸ":"ד","ﬢ":"ד","ﬣ":"ה","יּ":"יִ","ﬤ":"כ","ﬥ":"ל","ﬦ":"ם","ﬠ":"ע","ﬧ":"ר","שׂ":"שׁ","שּ":"שׁ","שּׂ":"שּׁ","ﬨ":"ת","ﺀ":"ء","۽":"ء͈","ﺂ":"آ","ﺁ":"آ","ﭑ":"ٱ","ﭐ":"ٱ","𞸁":"ب","𞸡":"ب","𞹡":"ب","𞺁":"ب","𞺡":"ب","ﺑ":"ب","ﺒ":"ب","ﺐ":"ب","ﺏ":"ب","ݑ":"بۛ","ࢶ":"بۢ","ࢡ":"بٔ","ﲠ":"بo","ﳢ":"بo","ﲜ":"بج","ﰅ":"بج","ﲝ":"بح","ﰆ":"بح","ﷂ":"بحى","ﲞ":"بخ","ﰇ":"بخ","ﳒ":"بخ","ﱋ":"بخ","ﶞ":"بخى","ﱪ":"بر","ﱫ":"بز","ﲟ":"بم","ﳡ":"بم","ﱬ":"بم","ﰈ":"بم","ﱭ":"بن","ﱮ":"بى","ﰉ":"بى","ﱯ":"بى","ﰊ":"بى","ﭔ":"ٻ","ﭕ":"ٻ","ﭓ":"ٻ","ﭒ":"ٻ","ې":"ٻ","ﯦ":"ٻ","ﯧ":"ٻ","ﯥ":"ٻ","ﯤ":"ٻ","ﭜ":"ڀ","ﭝ":"ڀ","ﭛ":"ڀ","ﭚ":"ڀ","ࢩ":"ݔ","ݧ":"ݔ","⍥":"ة","ö":"ة","ﺔ":"ة","ﺓ":"ة","ۃ":"ة","𞸕":"ت","𞸵":"ت","𞹵":"ت","𞺕":"ت","𞺵":"ت","ﺗ":"ت","ﺘ":"ت","ﺖ":"ت","ﺕ":"ت","ﲥ":"تo","ﳤ":"تo","ﲡ":"تج","ﰋ":"تج","ﵐ":"تجم","ﶠ":"تجى","ﶟ":"تجى","ﲢ":"تح","ﰌ":"تح","ﵒ":"تحج","ﵑ":"تحج","ﵓ":"تحم","ﲣ":"تخ","ﰍ":"تخ","ﵔ":"تخم","ﶢ":"تخى","ﶡ":"تخى","ﱰ":"تر","ﱱ":"تز","ﲤ":"تم","ﳣ":"تم","ﱲ":"تم","ﰎ":"تم","ﵕ":"تمج","ﵖ":"تمح","ﵗ":"تمخ","ﶤ":"تمى","ﶣ":"تمى","ﱳ":"تن","ﱴ":"تى","ﰏ":"تى","ﱵ":"تى","ﰐ":"تى","ﭠ":"ٺ","ﭡ":"ٺ","ﭟ":"ٺ","ﭞ":"ٺ","ﭤ":"ٿ","ﭥ":"ٿ","ﭣ":"ٿ","ﭢ":"ٿ","𞸂":"ج","𞸢":"ج","𞹂":"ج","𞹢":"ج","𞺂":"ج","𞺢":"ج","ﺟ":"ج","ﺠ":"ج","ﺞ":"ج","ﺝ":"ج","ﲧ":"جح","ﰕ":"جح","ﶦ":"جحى","ﶾ":"جحى","ﷻ":"جل جلlلo","ﲨ":"جم","ﰖ":"جم","ﵙ":"جمح","ﵘ":"جمح","ﶧ":"جمى","ﶥ":"جمى","ﴝ":"جى","ﴁ":"جى","ﴞ":"جى","ﴂ":"جى","ﭸ":"ڃ","ﭹ":"ڃ","ﭷ":"ڃ","ﭶ":"ڃ","ﭴ":"ڄ","ﭵ":"ڄ","ﭳ":"ڄ","ﭲ":"ڄ","ﭼ":"چ","ﭽ":"چ","ﭻ":"چ","ﭺ":"چ","ﮀ":"ڇ","ﮁ":"ڇ","ﭿ":"ڇ","ﭾ":"ڇ","𞸇":"ح","𞸧":"ح","𞹇":"ح","𞹧":"ح","𞺇":"ح","𞺧":"ح","ﺣ":"ح","ﺤ":"ح","ﺢ":"ح","ﺡ":"ح","څ":"حۛ","ځ":"حٔ","ݲ":"حٔ","ﲩ":"حج","ﰗ":"حج","ﶿ":"حجى","ﲪ":"حم","ﰘ":"حم","ﵛ":"حمى","ﵚ":"حمى","ﴛ":"حى","ﳿ":"حى","ﴜ":"حى","ﴀ":"حى","𞸗":"خ","𞸷":"خ","𞹗":"خ","𞹷":"خ","𞺗":"خ","𞺷":"خ","ﺧ":"خ","ﺨ":"خ","ﺦ":"خ","ﺥ":"خ","ﲫ":"خج","ﰙ":"خج","ﰚ":"خح","ﲬ":"خم","ﰛ":"خم","ﴟ":"خى","ﴃ":"خى","ﴠ":"خى","ﴄ":"خى","𐋡":"د","𞸃":"د","𞺃":"د","𞺣":"د","ﺪ":"د","ﺩ":"د","ڈ":"دؕ","ﮉ":"دؕ","ﮈ":"دؕ","ڎ":"دۛ","ﮇ":"دۛ","ﮆ":"دۛ","ۮ":"د̂","ࢮ":"د̤̣","𞸘":"ذ","𞺘":"ذ","𞺸":"ذ","ﺬ":"ذ","ﺫ":"ذ","ﱛ":"ذٰ","ڋ":"ڊؕ","ﮅ":"ڌ","ﮄ":"ڌ","ﮃ":"ڍ","ﮂ":"ڍ","𞸓":"ر","𞺓":"ر","𞺳":"ر","ﺮ":"ر","ﺭ":"ر","ڑ":"رؕ","ﮍ":"رؕ","ﮌ":"رؕ","ژ":"رۛ","ﮋ":"رۛ","ﮊ":"رۛ","ڒ":"ر̆","ࢹ":"ر̆̇","ۯ":"ر̂","ݬ":"رٔ","ﱜ":"رٰ","ﷶ":"رسول","﷼":"رىlل","𞸆":"ز","𞺆":"ز","𞺦":"ز","ﺰ":"ز","ﺯ":"ز","ࢲ":"ز̂","ݱ":"ڗؕ","𞸎":"س","𞸮":"س","𞹎":"س","𞹮":"س","𞺎":"س","𞺮":"س","ﺳ":"س","ﺴ":"س","ﺲ":"س","ﺱ":"س","ش":"سۛ","𞸔":"سۛ","𞸴":"سۛ","𞹔":"سۛ","𞹴":"سۛ","𞺔":"سۛ","𞺴":"سۛ","ﺷ":"سۛ","ﺸ":"سۛ","ﺶ":"سۛ","ﺵ":"سۛ","ݾ":"س̂","ﴱ":"سo","ﳨ":"سo","ﴲ":"سۛo","ﳪ":"سۛo","ﲭ":"سج","ﴴ":"سج","ﰜ":"سج","ﴭ":"سۛج","ﴷ":"سۛج","ﴥ":"سۛج","ﴉ":"سۛج","ﵝ":"سجح","ﵞ":"سجى","ﵩ":"سۛجى","ﲮ":"سح","ﴵ":"سح","ﰝ":"سح","ﴮ":"سۛح","ﴸ":"سۛح","ﴦ":"سۛح","ﴊ":"سۛح","ﵜ":"سحج","ﵨ":"سۛحم","ﵧ":"سۛحم","ﶪ":"سۛحى","ﲯ":"سخ","ﴶ":"سخ","ﰞ":"سخ","ﴯ":"سۛخ","ﴹ":"سۛخ","ﴧ":"سۛخ","ﴋ":"سۛخ","ﶨ":"سخى","ﷆ":"سخى","ﴪ":"سر","ﴎ":"سر","ﴩ":"سۛر","ﴍ":"سۛر","ﲰ":"سم","ﳧ":"سم","ﰟ":"سم","ﴰ":"سۛم","ﳩ":"سۛم","ﴨ":"سۛم","ﴌ":"سۛم","ﵡ":"سمج","ﵠ":"سمح","ﵟ":"سمح","ﵫ":"سۛمخ","ﵪ":"سۛمخ","ﵣ":"سمم","ﵢ":"سمم","ﵭ":"سۛمم","ﵬ":"سۛمم","ﴗ":"سى","ﳻ":"سى","ﴘ":"سى","ﳼ":"سى","ﴙ":"سۛى","ﳽ":"سۛى","ﴚ":"سۛى","ﳾ":"سۛى","𐋲":"ص","𞸑":"ص","𞸱":"ص","𞹑":"ص","𞹱":"ص","𞺑":"ص","𞺱":"ص","ﺻ":"ص","ﺼ":"ص","ﺺ":"ص","ﺹ":"ص","ڞ":"صۛ","ࢯ":"ص̤̣","ﲱ":"صح","ﰠ":"صح","ﵥ":"صحح","ﵤ":"صحح","ﶩ":"صحى","ﲲ":"صخ","ﴫ":"صر","ﴏ":"صر","ﷵ":"صلعم","ﷹ":"صلى","ﷰ":"صلى","ﷺ":"صلى lللo علىo وسلم","ﲳ":"صم","ﰡ":"صم","ﷅ":"صمم","ﵦ":"صمم","ﴡ":"صى","ﴅ":"صى","ﴢ":"صى","ﴆ":"صى","𞸙":"ض","𞸹":"ض","𞹙":"ض","𞹹":"ض","𞺙":"ض","𞺹":"ض","ﺿ":"ض","ﻀ":"ض","ﺾ":"ض","ﺽ":"ض","ﲴ":"ضج","ﰢ":"ضج","ﲵ":"ضح","ﰣ":"ضح","ﵮ":"ضحى","ﶫ":"ضحى","ﲶ":"ضخ","ﰤ":"ضخ","ﵰ":"ضخم","ﵯ":"ضخم","ﴬ":"ضر","ﴐ":"ضر","ﲷ":"ضم","ﰥ":"ضم","ﴣ":"ضى","ﴇ":"ضى","ﴤ":"ضى","ﴈ":"ضى","𐋨":"ط","𞸈":"ط","𞹨":"ط","𞺈":"ط","𞺨":"ط","ﻃ":"ط","ﻄ":"ط","ﻂ":"ط","ﻁ":"ط","ڟ":"طۛ","ﲸ":"طح","ﰦ":"طح","ﴳ":"طم","ﴺ":"طم","ﰧ":"طم","ﵲ":"طمح","ﵱ":"طمح","ﵳ":"طمم","ﵴ":"طمى","ﴑ":"طى","ﳵ":"طى","ﴒ":"طى","ﳶ":"طى","𞸚":"ظ","𞹺":"ظ","𞺚":"ظ","𞺺":"ظ","ﻇ":"ظ","ﻈ":"ظ","ﻆ":"ظ","ﻅ":"ظ","ﲹ":"ظم","ﴻ":"ظم","ﰨ":"ظم","؏":"ع","𞸏":"ع","𞸯":"ع","𞹏":"ع","𞹯":"ع","𞺏":"ع","𞺯":"ع","ﻋ":"ع","ﻌ":"ع","ﻊ":"ع","ﻉ":"ع","ﲺ":"عج","ﰩ":"عج","ﷄ":"عجم","ﵵ":"عجم","ﷷ":"علىo","ﲻ":"عم","ﰪ":"عم","ﵷ":"عمم","ﵶ":"عمم","ﵸ":"عمى","ﶶ":"عمى","ﴓ":"عى","ﳷ":"عى","ﴔ":"عى","ﳸ":"عى","𞸛":"غ","𞸻":"غ","𞹛":"غ","𞹻":"غ","𞺛":"غ","𞺻":"غ","ﻏ":"غ","ﻐ":"غ","ﻎ":"غ","ﻍ":"غ","ﲼ":"غج","ﰫ":"غج","ﲽ":"غم","ﰬ":"غم","ﵹ":"غمم","ﵻ":"غمى","ﵺ":"غمى","ﴕ":"غى","ﳹ":"غى","ﴖ":"غى","ﳺ":"غى","𞸐":"ف","𞸰":"ف","𞹰":"ف","𞺐":"ف","𞺰":"ف","ﻓ":"ف","ﻔ":"ف","ﻒ":"ف","ﻑ":"ف","ڧ":"ف","ﲾ":"فج","ﰭ":"فج","ﲿ":"فح","ﰮ":"فح","ﳀ":"فخ","ﰯ":"فخ","ﵽ":"فخم","ﵼ":"فخم","ﳁ":"فم","ﰰ":"فم","ﷁ":"فمى","ﱼ":"فى","ﰱ":"فى","ﱽ":"فى","ﰲ":"فى","𞸞":"ڡ","𞹾":"ڡ","ࢻ":"ڡ","ٯ":"ڡ","𞸟":"ڡ","𞹟":"ڡ","ࢼ":"ڡ","ڤ":"ڡۛ","ﭬ":"ڡۛ","ﭭ":"ڡۛ","ﭫ":"ڡۛ","ﭪ":"ڡۛ","ڨ":"ڡۛ","ࢤ":"ڢۛ","ﭰ":"ڦ","ﭱ":"ڦ","ﭯ":"ڦ","ﭮ":"ڦ","𞸒":"ق","𞸲":"ق","𞹒":"ق","𞹲":"ق","𞺒":"ق","𞺲":"ق","ﻗ":"ق","ﻘ":"ق","ﻖ":"ق","ﻕ":"ق","ﳂ":"قح","ﰳ":"قح","ﷱ":"قلى","ﳃ":"قم","ﰴ":"قم","ﶴ":"قمح","ﵾ":"قمح","ﵿ":"قمم","ﶲ":"قمى","ﱾ":"قى","ﰵ":"قى","ﱿ":"قى","ﰶ":"قى","𞸊":"ك","𞸪":"ك","𞹪":"ك","ﻛ":"ك","ﻜ":"ك","ﻚ":"ك","ﻙ":"ك","ک":"ك","ﮐ":"ك","ﮑ":"ك","ﮏ":"ك","ﮎ":"ك","ڪ":"ك","ڭ":"كۛ","ﯕ":"كۛ","ﯖ":"كۛ","ﯔ":"كۛ","ﯓ":"كۛ","ݣ":"كۛ","ﲀ":"كl","ﰷ":"كl","ﳄ":"كج","ﰸ":"كج","ﳅ":"كح","ﰹ":"كح","ﳆ":"كخ","ﰺ":"كخ","ﳇ":"كل","ﳫ":"كل","ﲁ":"كل","ﰻ":"كل","ﳈ":"كم","ﳬ":"كم","ﲂ":"كم","ﰼ":"كم","ﷃ":"كمم","ﶻ":"كمم","ﶷ":"كمى","ﲃ":"كى","ﰽ":"كى","ﲄ":"كى","ﰾ":"كى","ݢ":"ڬ","ﮔ":"گ","ﮕ":"گ","ﮓ":"گ","ﮒ":"گ","ࢰ":"گ","ڴ":"گۛ","ﮜ":"ڱ","ﮝ":"ڱ","ﮛ":"ڱ","ﮚ":"ڱ","ﮘ":"ڳ","ﮙ":"ڳ","ﮗ":"ڳ","ﮖ":"ڳ","𞸋":"ل","𞸫":"ل","𞹋":"ل","𞺋":"ل","𞺫":"ل","ﻟ":"ل","ﻠ":"ل","ﻞ":"ل","ﻝ":"ل","ڷ":"لۛ","ڵ":"ل̆","ﻼ":"لl","ﻻ":"لl","ﻺ":"لlٕ","ﻹ":"لlٕ","ﻸ":"لlٴ","ﻷ":"لlٴ","ﳍ":"لo","ﻶ":"لآ","ﻵ":"لآ","ﳉ":"لج","ﰿ":"لج","ﶃ":"لجج","ﶄ":"لجج","ﶺ":"لجم","ﶼ":"لجم","ﶬ":"لجى","ﳊ":"لح","ﱀ":"لح","ﶵ":"لحم","ﶀ":"لحم","ﶂ":"لحى","ﶁ":"لحى","ﳋ":"لخ","ﱁ":"لخ","ﶆ":"لخم","ﶅ":"لخم","ﳌ":"لم","ﳭ":"لم","ﲅ":"لم","ﱂ":"لم","ﶈ":"لمح","ﶇ":"لمح","ﶭ":"لمى","ﲆ":"لى","ﱃ":"لى","ﲇ":"لى","ﱄ":"لى","𞸌":"م","𞸬":"م","𞹬":"م","𞺌":"م","𞺬":"م","ﻣ":"م","ﻤ":"م","ﻢ":"م","ﻡ":"م","ࢧ":"مۛ","۾":"م͈","ﲈ":"مl","ﳎ":"مج","ﱅ":"مج","ﶌ":"مجح","ﶒ":"مجخ","ﶍ":"مجم","ﷀ":"مجى","ﳏ":"مح","ﱆ":"مح","ﶉ":"محج","ﶊ":"محم","ﷴ":"محمد","ﶋ":"محى","ﳐ":"مخ","ﱇ":"مخ","ﶎ":"مخج","ﶏ":"مخم","ﶹ":"مخى","ﳑ":"مم","ﲉ":"مم","ﱈ":"مم","ﶱ":"ممى","ﱉ":"مى","ﱊ":"مى","𞸍":"ن","𞸭":"ن","𞹍":"ن","𞹭":"ن","𞺍":"ن","𞺭":"ن","ﻧ":"ن","ﻨ":"ن","ﻦ":"ن","ﻥ":"ن","ݨ":"نؕ","ݩ":"ن̆","ﳖ":"نo","ﳯ":"نo","ﶸ":"نجح","ﶽ":"نجح","ﶘ":"نجم","ﶗ":"نجم","ﶙ":"نجى","ﷇ":"نجى","ﳓ":"نح","ﱌ":"نح","ﶕ":"نحم","ﶖ":"نحى","ﶳ":"نحى","ﳔ":"نخ","ﱍ":"نخ","ﲊ":"نر","ﲋ":"نز","ﳕ":"نم","ﳮ":"نم","ﲌ":"نم","ﱎ":"نم","ﶛ":"نمى","ﶚ":"نمى","ﲍ":"نن","ﲎ":"نى","ﱏ":"نى","ﲏ":"نى","ﱐ":"نى","ۂ":"ۀ","ﮥ":"ۀ","ﮤ":"ۀ","𐋤":"و","𞸅":"و","𞺅":"و","𞺥":"و","ﻮ":"و","ﻭ":"و","ࢱ":"و","ۋ":"وۛ","ﯟ":"وۛ","ﯞ":"وۛ","ۇ":"و̓","ﯘ":"و̓","ﯗ":"و̓","ۆ":"و̆","ﯚ":"و̆","ﯙ":"و̆","ۉ":"و̂","ﯣ":"و̂","ﯢ":"و̂","ۈ":"وٰ","ﯜ":"وٰ","ﯛ":"وٰ","ؤ":"وٴ","ﺆ":"وٴ","ﺅ":"وٴ","ٶ":"وٴ","ٷ":"و̓ٴ","ﯝ":"و̓ٴ","ﷸ":"وسلم","ﯡ":"ۅ","ﯠ":"ۅ","ٮ":"ى","𞸜":"ى","𞹼":"ى","ں":"ى","𞸝":"ى","𞹝":"ى","ﮟ":"ى","ﮞ":"ى","ࢽ":"ى","ﯨ":"ى","ﯩ":"ى","ﻰ":"ى","ﻯ":"ى","ي":"ى","𞸉":"ى","𞸩":"ى","𞹉":"ى","𞹩":"ى","𞺉":"ى","𞺩":"ى","ﻳ":"ى","ﻴ":"ى","ﻲ":"ى","ﻱ":"ى","ی":"ى","ﯾ":"ى","ﯿ":"ى","ﯽ":"ى","ﯼ":"ى","ے":"ى","ﮯ":"ى","ﮮ":"ى","ٹ":"ىؕ","ﭨ":"ىؕ","ﭩ":"ىؕ","ﭧ":"ىؕ","ﭦ":"ىؕ","ڻ":"ىؕ","ﮢ":"ىؕ","ﮣ":"ىؕ","ﮡ":"ىؕ","ﮠ":"ىؕ","پ":"ىۛ","ﭘ":"ىۛ","ﭙ":"ىۛ","ﭗ":"ىۛ","ﭖ":"ىۛ","ث":"ىۛ","𞸖":"ىۛ","𞸶":"ىۛ","𞹶":"ىۛ","𞺖":"ىۛ","𞺶":"ىۛ","ﺛ":"ىۛ","ﺜ":"ىۛ","ﺚ":"ىۛ","ﺙ":"ىۛ","ڽ":"ىۛ","ۑ":"ىۛ","ؿ":"ىۛ","ࢷ":"ىۛۢ","ݖ":"ى̆","ێ":"ى̆","ࢺ":"ى̆̇","ؽ":"ى̂","ࢨ":"ىٔ","ﲐ":"ىٰ","ﱝ":"ىٰ","ﳞ":"ىo","ﳱ":"ىo","ﳦ":"ىۛo","ئ":"ىٴ","ﺋ":"ىٴ","ﺌ":"ىٴ","ﺊ":"ىٴ","ﺉ":"ىٴ","ٸ":"ىٴ","ﯫ":"ىٴl","ﯪ":"ىٴl","ﲛ":"ىٴo","ﳠ":"ىٴo","ﯭ":"ىٴo","ﯬ":"ىٴo","ﯸ":"ىٴٻ","ﯷ":"ىٴٻ","ﯶ":"ىٴٻ","ﲗ":"ىٴج","ﰀ":"ىٴج","ﲘ":"ىٴح","ﰁ":"ىٴح","ﲙ":"ىٴخ","ﱤ":"ىٴر","ﱥ":"ىٴز","ﲚ":"ىٴم","ﳟ":"ىٴم","ﱦ":"ىٴم","ﰂ":"ىٴم","ﱧ":"ىٴن","ﯯ":"ىٴو","ﯮ":"ىٴو","ﯱ":"ىٴو̓","ﯰ":"ىٴو̓","ﯳ":"ىٴو̆","ﯲ":"ىٴو̆","ﯵ":"ىٴوٰ","ﯴ":"ىٴوٰ","ﯻ":"ىٴى","ﯺ":"ىٴى","ﱨ":"ىٴى","ﯹ":"ىٴى","ﰃ":"ىٴى","ﱩ":"ىٴى","ﰄ":"ىٴى","ﳚ":"ىج","ﱕ":"ىج","ﰑ":"ىۛج","ﶯ":"ىجى","ﳛ":"ىح","ﱖ":"ىح","ﶮ":"ىحى","ﳜ":"ىخ","ﱗ":"ىخ","ﲑ":"ىر","ﱶ":"ىۛر","ﲒ":"ىز","ﱷ":"ىۛز","ﳝ":"ىم","ﳰ":"ىم","ﲓ":"ىم","ﱘ":"ىم","ﲦ":"ىۛم","ﳥ":"ىۛم","ﱸ":"ىۛم","ﰒ":"ىۛم","ﶝ":"ىمم","ﶜ":"ىمم","ﶰ":"ىمى","ﲔ":"ىن","ﱹ":"ىۛن","ﲕ":"ىى","ﱙ":"ىى","ﲖ":"ىى","ﱚ":"ىى","ﱺ":"ىۛى","ﰓ":"ىۛى","ﱻ":"ىۛى","ﰔ":"ىۛى","ﮱ":"ۓ","ﮰ":"ۓ","𐊸":"ⵀ","⁞":"ⵂ","⸽":"ⵂ","⦙":"ⵂ","︙":"ⵗ","⁝":"ⵗ","⋮":"ⵗ","Մ":"ሆ","Ռ":"ቡ","Ի":"ኮ","Պ":"ጣ","आ":"अा","ऒ":"अाॆ","ओ":"अाे","औ":"अाै","ऄ":"अॆ","ऑ":"अॉ","ऍ":"एॅ","ऎ":"एॆ","ऐ":"एे","ई":"र्इ","ઽ":"ऽ","𑇜":"ꣻ","𑇋":"ऺ","ુ":"ु","ૂ":"ू","ੋ":"ॆ","੍":"्","્":"्","আ":"অা","ৠ":"ঋৃ","ৡ":"ঋৃ","𑒒":"ঘ","𑒔":"চ","𑒖":"জ","𑒘":"ঞ","𑒙":"ট","𑒛":"ড","𑒪":"ণ","𑒞":"ত","𑒟":"থ","𑒠":"দ","𑒡":"ধ","𑒢":"ন","𑒣":"প","𑒩":"ব","𑒧":"ম","𑒨":"য","𑒫":"র","𑒝":"ল","𑒭":"ষ","𑒮":"স","𑓄":"ঽ","𑒰":"া","𑒱":"ি","𑒹":"ে","𑒼":"ো","𑒾":"ৌ","𑓂":"্","𑒽":"ৗ","ਉ":"ੳੁ","ਊ":"ੳੂ","ਆ":"ਅਾ","ਐ":"ਅੈ","ਔ":"ਅੌ","ਇ":"ੲਿ","ਈ":"ੲੀ","ਏ":"ੲੇ","આ":"અા","ઑ":"અાૅ","ઓ":"અાે","ઔ":"અાૈ","ઍ":"અૅ","એ":"અે","ઐ":"અૈ","ଆ":"ଅା","௮":"அ","ர":"ஈ","ா":"ஈ","௫":"ஈு","௨":"உ","ഉ":"உ","ஊ":"உள","ഊ":"உൗ","௭":"எ","௷":"எவ","ஜ":"ஐ","ജ":"ஐ","௧":"க","௪":"ச","௬":"சு","௲":"சூ","ഺ":"டி","ണ":"ண","௺":"நீ","௴":"மீ","௰":"ய","ഴ":"ழ","ௗ":"ள","ை":"ன","ശ":"ஶ","௸":"ஷ","ി":"ி","ീ":"ி","ொ":"ெஈ","ௌ":"ெள","ோ":"ேஈ","ಅ":"అ","ಆ":"ఆ","ಇ":"ఇ","ౠ":"ఋా","ౡ":"ఌా","ಒ":"ఒ","ఔ":"ఒౌ","ಔ":"ఒౌ","ఓ":"ఒౕ","ಓ":"ఒౕ","ಜ":"జ","ಞ":"ఞ","ఢ":"డ̣","ಣ":"ణ","థ":"ధּ","భ":"బ̣","ಯ":"య","ఠ":"రּ","ಱ":"ఱ","ಲ":"ల","ష":"వ̣","హ":"వా","మ":"వు","ూ":"ుా","ౄ":"ృా","ೡ":"ಌಾ","ഈ":"ഇൗ","ഐ":"എെ","ഓ":"ഒാ","ഔ":"ഒൗ","ൡ":"ഞ","൫":"ദ്ര","൹":"നു","ഌ":"നു","ങ":"നു","൯":"ന്","ൻ":"ന്","൬":"ന്ന","൚":"ന്മ","റ":"ര","൪":"ര്","ർ":"ര്","൮":"വ്ര","൶":"ഹ്മ","ൂ":"ു","ൃ":"ു","ൈ":"െെ","෪":"ජ","෫":"ද","𑐓":"𑐴𑑂𑐒","𑐙":"𑐴𑑂𑐘","𑐤":"𑐴𑑂𑐣","𑐪":"𑐴𑑂𑐩","𑐭":"𑐴𑑂𑐬","𑐯":"𑐴𑑂𑐮","𑗘":"𑖂","𑗙":"𑖂","𑗚":"𑖃","𑗛":"𑖄","𑗜":"𑖲","𑗝":"𑖳","ฃ":"ข","ด":"ค","ต":"ค","ม":"ฆ","ຈ":"จ","ซ":"ช","ฏ":"ฎ","ท":"ฑ","ບ":"บ","ປ":"ป","ຝ":"ฝ","ພ":"พ","ຟ":"ฟ","ฦ":"ภ","ຍ":"ย","។":"ฯ","ๅ":"า","ำ":"̊า","ិ":"ิ","ី":"ี","ឹ":"ึ","ឺ":"ื","ຸ":"ุ","ູ":"ู","แ":"เเ","ໜ":"ຫນ","ໝ":"ຫມ","ຳ":"̊າ","༂":"འུྂཿ","༃":"འུྂ༔","ཪ":"ར","ༀ":"ཨོཾ","ཷ":"ྲཱྀ","ཹ":"ླཱྀ","𑲲":"𑲪","ႁ":"ဂှ","က":"ဂာ","ၰ":"ဃှ","ၦ":"ပှ","ဟ":"ပာ","ၯ":"ပာှ","ၾ":"ၽှ","ဩ":"သြ","ဪ":"သြော်","႞":"ႃ̊","ឣ":"អ","᧐":"ᦞ","᧑":"ᦱ","᪀":"ᩅ","᪐":"ᩅ","꩓":"ꨁ","꩖":"ꨣ","᭒":"ᬍ","᭓":"ᬑ","᭘":"ᬨ","ꦣ":"ꦝ","ᢖ":"ᡜ","ᡕ":"ᠵ","ῶ":"Ꮿ","ᐍ":"ᐁ·","ᐫ":"ᐁᐠ","ᐑ":"ᐄ·","ᐓ":"ᐅ·","ᐭ":"ᐅᐠ","ᐕ":"ᐆ·","ᐘ":"ᐊ·","ᐮ":"ᐊᐠ","ᐚ":"ᐋ·","ᣝ":"ᐞᣟ","ᓑ":"ᐡ","ᕀ":"ᐩ","ᐿ":"ᐲ·","ᑃ":"ᐴ·","⍩":"ᐵ","ᑇ":"ᐹ·","ᑜ":"ᑏ·","⸧":"ᑐ","⊃":"ᑐ","ᑞ":"ᑐ·","ᑩ":"ᑐ'","⟉":"ᑐ/","⫗":"ᑐᑕ","ᑠ":"ᑑ·","⸦":"ᑕ","⊂":"ᑕ","ᑢ":"ᑕ·","ᑪ":"ᑕ'","ᑤ":"ᑖ·","ᑵ":"ᑫ·","ᒅ":"ᑫ'","ᑹ":"ᑮ·","ᑽ":"ᑰ·","ᘃ":"ᒉ","ᒓ":"ᒉ·","ᒕ":"ᒋ·","ᒗ":"ᒌ·","ᒛ":"ᒎ·","ᘂ":"ᒐ","ᒝ":"ᒐ·","ᒟ":"ᒑ·","ᒭ":"ᒣ·","ᒱ":"ᒦ·","ᒳ":"ᒧ·","ᒵ":"ᒨ·","ᒹ":"ᒫ·","ᓊ":"ᓀ·","ᣇ":"ᓂ·","ᣉ":"ᓃ·","ᣋ":"ᓄ·","ᣍ":"ᓅ·","ᓌ":"ᓇ·","ᓎ":"ᓈ·","ᘄ":"ᓓ","ᓝ":"ᓓ·","ᓟ":"ᓕ·","ᓡ":"ᓖ·","ᓣ":"ᓗ·","ᓥ":"ᓘ·","ᘇ":"ᓚ","ᓧ":"ᓚ·","ᓩ":"ᓛ·","ᓷ":"ᓭ·","ᓹ":"ᓯ·","ᓻ":"ᓰ·","ᓽ":"ᓱ·","ᓿ":"ᓲ·","ᔁ":"ᓴ·","ᔃ":"ᓵ·","ᔌ":"ᔋ<","ᔎ":"ᔋb","ᔍ":"ᔋᑕ","ᔏ":"ᔋᒐ","ᔘ":"ᔐ·","ᔚ":"ᔑ·","ᔜ":"ᔒ·","ᔞ":"ᔓ·","ᔠ":"ᔔ·","ᔢ":"ᔕ·","ᔤ":"ᔖ·","ᔲ":"ᔨ·","ᔴ":"ᔩ·","ᔶ":"ᔪ·","ᔸ":"ᔫ·","ᔺ":"ᔭ·","ᔼ":"ᔮ·","ᘢ":"ᕃ","ᣠ":"ᕃ·","ᘣ":"ᕆ","ᘤ":"ᕊ","ᕏ":"ᕌ·","ᖃ":"ᕐb","ᖄ":"ᕐḃ","ᖁ":"ᕐd","ᕿ":"ᕐP","ᙯ":"ᕐᑫ","ᕾ":"ᕐᑬ","ᖀ":"ᕐᑮ","ᖂ":"ᕐᑰ","ᖅ":"ᕐᒃ","ᕜ":"ᕚ·","ᣣ":"ᕞ·","ᣤ":"ᕦ·","ᕩ":"ᕧ·","ᣥ":"ᕫ·","ᣨ":"ᖆ·","ᖑ":"ᖕJ","ᙰ":"ᖕᒉ","ᖎ":"ᖕᒊ","ᖏ":"ᖕᒋ","ᖐ":"ᖕᒌ","ᖒ":"ᖕᒎ","ᖓ":"ᖕᒐ","ᖔ":"ᖕᒑ","ᙳ":"ᖖJ","ᙱ":"ᖖᒋ","ᙲ":"ᖖᒌ","ᙴ":"ᖖᒎ","ᙵ":"ᖖᒐ","ᙶ":"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ","ˡ":"ᣳ","ʳ":"ᣴ","ˢ":"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ","ᛡ":"ᚼ","⍿":"ᚽ","ᛂ":"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥","ㄱ":"ᄀ","ᆨ":"ᄀ","ᄁ":"ᄀᄀ","ㄲ":"ᄀᄀ","ᆩ":"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ","ᇃ":"ᄀᄅ","ᇻ":"ᄀᄇ","ᆪ":"ᄀᄉ","ㄳ":"ᄀᄉ","ᇄ":"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ","ㄴ":"ᄂ","ᆫ":"ᄂ","ᄓ":"ᄂᄀ","ᇅ":"ᄂᄀ","ᄔ":"ᄂᄂ","ㅥ":"ᄂᄂ","ᇿ":"ᄂᄂ","ᄕ":"ᄂᄃ","ㅦ":"ᄂᄃ","ᇆ":"ᄂᄃ","ퟋ":"ᄂᄅ","ᄖ":"ᄂᄇ","ᅛ":"ᄂᄉ","ᇇ":"ᄂᄉ","ㅧ":"ᄂᄉ","ᅜ":"ᄂᄌ","ᆬ":"ᄂᄌ","ㄵ":"ᄂᄌ","ퟌ":"ᄂᄎ","ᇉ":"ᄂᄐ","ᅝ":"ᄂᄒ","ᆭ":"ᄂᄒ","ㄶ":"ᄂᄒ","ᇈ":"ᄂᅀ","ㅨ":"ᄂᅀ","ㄷ":"ᄃ","ᆮ":"ᄃ","ᄗ":"ᄃᄀ","ᇊ":"ᄃᄀ","ᄄ":"ᄃᄃ","ㄸ":"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ","ᇋ":"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ","ㄹ":"ᄅ","ᆯ":"ᄅ","ꥤ":"ᄅᄀ","ᆰ":"ᄅᄀ","ㄺ":"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ","ᇌ":"ᄅᄀᄉ","ㅩ":"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ","ᄘ":"ᄅᄂ","ᇍ":"ᄅᄂ","ꥦ":"ᄅᄃ","ᇎ":"ᄅᄃ","ㅪ":"ᄅᄃ","ꥧ":"ᄅᄃᄃ","ᇏ":"ᄅᄃᄒ","ᄙ":"ᄅᄅ","ᇐ":"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ","ᆱ":"ᄅᄆ","ㄻ":"ᄅᄆ","ᇑ":"ᄅᄆᄀ","ᇒ":"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ","ᆲ":"ᄅᄇ","ㄼ":"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ","ᇓ":"ᄅᄇᄉ","ㅫ":"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ","ᇕ":"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ","ᇔ":"ᄅᄇᄒ","ꥬ":"ᄅᄉ","ᆳ":"ᄅᄉ","ㄽ":"ᄅᄉ","ᇖ":"ᄅᄉᄉ","ᄛ":"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ","ᇘ":"ᄅᄏ","ᆴ":"ᄅᄐ","ㄾ":"ᄅᄐ","ᆵ":"ᄅᄑ","ㄿ":"ᄅᄑ","ᄚ":"ᄅᄒ","ㅀ":"ᄅᄒ","ᄻ":"ᄅᄒ","ᆶ":"ᄅᄒ","ퟲ":"ᄅᄒ","ᇗ":"ᄅᅀ","ㅬ":"ᄅᅀ","ퟛ":"ᄅᅌ","ᇙ":"ᄅᅙ","ㅭ":"ᄅᅙ","ퟜ":"ᄅᅙᄒ","ㅁ":"ᄆ","ᆷ":"ᄆ","ꥯ":"ᄆᄀ","ᇚ":"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ","ᇛ":"ᄆᄅ","ퟠ":"ᄆᄆ","ᄜ":"ᄆᄇ","ㅮ":"ᄆᄇ","ᇜ":"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ","ᇝ":"ᄆᄉ","ㅯ":"ᄆᄉ","ᇞ":"ᄆᄉᄉ","ᄝ":"ᄆᄋ","ㅱ":"ᄆᄋ","ᇢ":"ᄆᄋ","ퟢ":"ᄆᄌ","ᇠ":"ᄆᄎ","ᇡ":"ᄆᄒ","ᇟ":"ᄆᅀ","ㅰ":"ᄆᅀ","ㅂ":"ᄇ","ᆸ":"ᄇ","ᄞ":"ᄇᄀ","ㅲ":"ᄇᄀ","ᄟ":"ᄇᄂ","ᄠ":"ᄇᄃ","ㅳ":"ᄇᄃ","ퟣ":"ᄇᄃ","ᇣ":"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ","ᄈ":"ᄇᄇ","ㅃ":"ᄇᄇ","ퟦ":"ᄇᄇ","ᄬ":"ᄇᄇᄋ","ㅹ":"ᄇᄇᄋ","ᄡ":"ᄇᄉ","ㅄ":"ᄇᄉ","ᆹ":"ᄇᄉ","ᄢ":"ᄇᄉᄀ","ㅴ":"ᄇᄉᄀ","ᄣ":"ᄇᄉᄃ","ㅵ":"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ","ᄤ":"ᄇᄉᄇ","ᄥ":"ᄇᄉᄉ","ᄦ":"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ","ᄫ":"ᄇᄋ","ㅸ":"ᄇᄋ","ᇦ":"ᄇᄋ","ᄧ":"ᄇᄌ","ㅶ":"ᄇᄌ","ퟨ":"ᄇᄌ","ᄨ":"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ","ᄩ":"ᄇᄐ","ㅷ":"ᄇᄐ","ᄪ":"ᄇᄑ","ᇤ":"ᄇᄑ","ꥴ":"ᄇᄒ","ᇥ":"ᄇᄒ","ㅅ":"ᄉ","ᆺ":"ᄉ","ᄭ":"ᄉᄀ","ㅺ":"ᄉᄀ","ᇧ":"ᄉᄀ","ᄮ":"ᄉᄂ","ㅻ":"ᄉᄂ","ᄯ":"ᄉᄃ","ㅼ":"ᄉᄃ","ᇨ":"ᄉᄃ","ᄰ":"ᄉᄅ","ᇩ":"ᄉᄅ","ᄱ":"ᄉᄆ","ퟪ":"ᄉᄆ","ᄲ":"ᄉᄇ","ㅽ":"ᄉᄇ","ᇪ":"ᄉᄇ","ᄳ":"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ","ᄊ":"ᄉᄉ","ㅆ":"ᄉᄉ","ᆻ":"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ","ᄴ":"ᄉᄉᄉ","ᄵ":"ᄉᄋ","ᄶ":"ᄉᄌ","ㅾ":"ᄉᄌ","ퟯ":"ᄉᄌ","ᄷ":"ᄉᄎ","ퟰ":"ᄉᄎ","ᄸ":"ᄉᄏ","ᄹ":"ᄉᄐ","ퟱ":"ᄉᄐ","ᄺ":"ᄉᄑ","ퟮ":"ᄉᅀ","ㅇ":"ᄋ","ᆼ":"ᄋ","ᅁ":"ᄋᄀ","ᇬ":"ᄋᄀ","ᇭ":"ᄋᄀᄀ","ᅂ":"ᄋᄃ","ꥶ":"ᄋᄅ","ᅃ":"ᄋᄆ","ᅄ":"ᄋᄇ","ᅅ":"ᄋᄉ","ᇱ":"ᄋᄉ","ㆂ":"ᄋᄉ","ᅇ":"ᄋᄋ","ㆀ":"ᄋᄋ","ᇮ":"ᄋᄋ","ᅈ":"ᄋᄌ","ᅉ":"ᄋᄎ","ᇯ":"ᄋᄏ","ᅊ":"ᄋᄐ","ᅋ":"ᄋᄑ","ꥷ":"ᄋᄒ","ᅆ":"ᄋᅀ","ᇲ":"ᄋᅀ","ㆃ":"ᄋᅀ","ㅈ":"ᄌ","ᆽ":"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ","ᅍ":"ᄌᄋ","ᄍ":"ᄌᄌ","ㅉ":"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ","ㅊ":"ᄎ","ᆾ":"ᄎ","ᅒ":"ᄎᄏ","ᅓ":"ᄎᄒ","ㅋ":"ᄏ","ᆿ":"ᄏ","ㅌ":"ᄐ","ᇀ":"ᄐ","ꥹ":"ᄐᄐ","ㅍ":"ᄑ","ᇁ":"ᄑ","ᅖ":"ᄑᄇ","ᇳ":"ᄑᄇ","ퟺ":"ᄑᄉ","ᅗ":"ᄑᄋ","ㆄ":"ᄑᄋ","ᇴ":"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ","ㅎ":"ᄒ","ᇂ":"ᄒ","ᇵ":"ᄒᄂ","ᇶ":"ᄒᄅ","ᇷ":"ᄒᄆ","ᇸ":"ᄒᄇ","ꥻ":"ᄒᄉ","ᅘ":"ᄒᄒ","ㆅ":"ᄒᄒ","ᄽ":"ᄼᄼ","ᄿ":"ᄾᄾ","ㅿ":"ᅀ","ᇫ":"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ","ㆁ":"ᅌ","ᇰ":"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ","ᅏ":"ᅎᅎ","ᅑ":"ᅐᅐ","ㆆ":"ᅙ","ᇹ":"ᅙ","ꥼ":"ᅙᅙ","ㅤ":"ᅠ","ㅏ":"ᅡ","ᆣ":"ᅡー","ᅶ":"ᅡᅩ","ᅷ":"ᅡᅮ","ᅢ":"ᅡ丨","ㅐ":"ᅡ丨","ㅑ":"ᅣ","ᅸ":"ᅣᅩ","ᅹ":"ᅣᅭ","ᆤ":"ᅣᅮ","ᅤ":"ᅣ丨","ㅒ":"ᅣ丨","ㅓ":"ᅥ","ᅼ":"ᅥー","ᅺ":"ᅥᅩ","ᅻ":"ᅥᅮ","ᅦ":"ᅥ丨","ㅔ":"ᅥ丨","ㅕ":"ᅧ","ᆥ":"ᅧᅣ","ᅽ":"ᅧᅩ","ᅾ":"ᅧᅮ","ᅨ":"ᅧ丨","ㅖ":"ᅧ丨","ㅗ":"ᅩ","ᅪ":"ᅩᅡ","ㅘ":"ᅩᅡ","ᅫ":"ᅩᅡ丨","ㅙ":"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨","ᅿ":"ᅩᅥ","ᆀ":"ᅩᅥ丨","ힰ":"ᅩᅧ","ᆁ":"ᅩᅧ丨","ᆂ":"ᅩᅩ","ힱ":"ᅩᅩ丨","ᆃ":"ᅩᅮ","ᅬ":"ᅩ丨","ㅚ":"ᅩ丨","ㅛ":"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨","ᆄ":"ᅭᅣ","ㆇ":"ᅭᅣ","ᆆ":"ᅭᅣ","ᆅ":"ᅭᅣ丨","ㆈ":"ᅭᅣ丨","ힴ":"ᅭᅥ","ᆇ":"ᅭᅩ","ᆈ":"ᅭ丨","ㆉ":"ᅭ丨","ㅜ":"ᅮ","ᆉ":"ᅮᅡ","ᆊ":"ᅮᅡ丨","ᅯ":"ᅮᅥ","ㅝ":"ᅮᅥ","ᆋ":"ᅮᅥー","ᅰ":"ᅮᅥ丨","ㅞ":"ᅮᅥ丨","ힵ":"ᅮᅧ","ᆌ":"ᅮᅧ丨","ᆍ":"ᅮᅮ","ᅱ":"ᅮ丨","ㅟ":"ᅮ丨","ힶ":"ᅮ丨丨","ㅠ":"ᅲ","ᆎ":"ᅲᅡ","ힷ":"ᅲᅡ丨","ᆏ":"ᅲᅥ","ᆐ":"ᅲᅥ丨","ᆑ":"ᅲᅧ","ㆊ":"ᅲᅧ","ᆒ":"ᅲᅧ丨","ㆋ":"ᅲᅧ丨","ힸ":"ᅲᅩ","ᆓ":"ᅲᅮ","ᆔ":"ᅲ丨","ㆌ":"ᅲ丨","ㆍ":"ᆞ","ퟅ":"ᆞᅡ","ᆟ":"ᆞᅥ","ퟆ":"ᆞᅥ丨","ᆠ":"ᆞᅮ","ᆢ":"ᆞᆞ","ᆡ":"ᆞ丨","ㆎ":"ᆞ丨","ヘ":"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄","不":"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨","ᅵ":"丨","ㅣ":"丨","⼁":"丨","ᆜ":"丨ー","ᆘ":"丨ᅡ","ᆙ":"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨","ᆚ":"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ","ᆛ":"丨ᅮ","ퟃ":"丨ᅲ","ᆝ":"丨ᆞ","ퟄ":"丨丨","串":"串","丸":"丸","丹":"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀","亂":"亂","㇚":"亅","⼅":"亅","了":"了","ニ":"二","⼆":"二","𠄢":"𠄢","⼇":"亠","亮":"亮","⼈":"人","イ":"亻","⺅":"亻","什":"什","仌":"仌","令":"令","你":"你","倂":"併","倂":"併","侀":"侀","來":"來","例":"例","侮":"侮","侮":"侮","侻":"侻","便":"便","值":"値","倫":"倫","偺":"偺","備":"備","像":"像","僚":"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿","兀":"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全","兩":"兩","ハ":"八","⼋":"八","六":"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况","冷":"冷","凉":"凉","凌":"凌","凜":"凜","凞":"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃","切":"切","切":"切","列":"列","利":"利","㓟":"㓟","刺":"刺","刻":"刻","剆":"剆","割":"割","剷":"剷","劉":"劉","𠠄":"𠠄","カ":"力","力":"力","⼒":"力","劣":"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉","勒":"勒","勞":"勞","勤":"勤","勤":"勤","勵":"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕","北":"北","北":"北","⼕":"匚","⼖":"匸","匿":"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博","ト":"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即","卵":"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶","參":"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣","ロ":"口","⼝":"口","囗":"口","⼞":"口","句":"句","叫":"叫","叱":"叱","吆":"吆","吏":"吏","吝":"吝","吸":"吸","呂":"呂","呈":"呈","周":"周","咞":"咞","咢":"咢","咽":"咽","䎛":"㖈","哶":"哶","唐":"唐","啓":"啓","啟":"啓","啕":"啕","啣":"啣","善":"善","善":"善","喇":"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳","嗀":"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器","囹":"囹","圖":"圖","圗":"圗","⼟":"土","士":"土","⼠":"土","型":"型","城":"城","㦳":"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀","塚":"塚","塚":"塚","塞":"塞","填":"塡","壿":"墫","墬":"墬","墳":"墳","壘":"壘","壟":"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊","タ":"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄","奈":"奈","契":"契","奔":"奔","奢":"奢","女":"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦","嬀":"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀","宅":"宅","𡧈":"𡧈","寃":"寃","寘":"寘","寧":"寧","寧":"寧","寧":"寧","寮":"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸","尿":"尿","屠":"屠","屢":"屢","層":"層","履":"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦","崙":"崙","嵃":"嵃","嵐":"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲","嶺":"嶺","⼮":"巛","巢":"巢","エ":"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾","帲":"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干","年":"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广","度":"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶","廊":"廊","廊":"廊","廉":"廉","廒":"廒","廓":"廓","廙":"廙","廬":"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱","弄":"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳","律":"律","㣣":"㣣","徚":"徚","復":"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志","念":"念","忹":"忹","怒":"怒","怜":"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘","惡":"惡","𢛔":"𢛔","愈":"愈","慨":"慨","慄":"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎","憐":"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲","懶":"懶","懶":"懶","戀":"戀","⼽":"戈","成":"成","戛":"戛","戮":"戮","戴":"戴","⼾":"戶","戸":"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱","拉":"拉","拏":"拏","拓":"拓","拔":"拔","拼":"拼","拾":"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨","捻":"捻","掃":"掃","掠":"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮","搉":"㩁","撚":"撚","撝":"撝","擄":"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬","數":"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗","料":"料","⽄":"斤","⽅":"方","旅":"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日","易":"易","曶":"㫚","㫤":"㫤","晉":"晉","晩":"晚","晴":"晴","晴":"晴","暑":"暑","暑":"暑","暈":"暈","㬈":"㬈","暜":"暜","暴":"暴","曆":"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰","更":"更","書":"書","⽉":"月","𣍟":"𣍟","肦":"朌","胐":"朏","胊":"朐","脁":"朓","胶":"㬵","朗":"朗","朗":"朗","朗":"朗","脧":"朘","望":"望","望":"望","幐":"㬺","䐠":"㬻","𣎓":"𣎓","膧":"朣","𣎜":"𣎜","⽊":"木","李":"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃","柿":"杮","杻":"杻","枅":"枅","林":"林","㭉":"㭉","𣏕":"𣏕","柳":"柳","柺":"柺","栗":"栗","栟":"栟","桒":"桒","𣑭":"𣑭","梁":"梁","梅":"梅","梅":"梅","梎":"梎","梨":"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝","槩":"㮣","樧":"榝","榣":"榣","槪":"槪","樂":"樂","樂":"樂","樂":"樂","樓":"樓","𣚣":"𣚣","檨":"檨","櫓":"櫓","櫛":"櫛","欄":"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲","歷":"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟","殮":"殮","⽎":"殳","殺":"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧","沈":"沈","沿":"沿","泌":"泌","泍":"泍","泥":"泥","𣲼":"𣲼","洛":"洛","洞":"洞","洴":"洴","派":"派","流":"流","流":"流","流":"流","洖":"洖","浩":"浩","浪":"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞","淋":"淋","淚":"淚","淪":"淪","淹":"淹","渚":"渚","港":"港","湮":"湮","潙":"溈","滋":"滋","滋":"滋","溜":"溜","溺":"溺","滇":"滇","滑":"滑","滛":"滛","㴳":"㴳","漏":"漏","漢":"漢","漢":"漢","漣":"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆","濫":"濫","濾":"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災","炙":"炙","炭":"炭","烈":"烈","烙":"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅","煉":"煉","𤋮":"𤋮","熜":"熜","燎":"燎","燐":"燐","𤎫":"𤎫","爐":"爐","爛":"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛","牢":"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯","狀":"狀","𤜵":"𤜵","狼":"狼","猪":"猪","猪":"猪","𤠔":"𤠔","獵":"獵","獺":"獺","⽞":"玄","率":"率","率":"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥","玲":"玲","㺸":"㺸","㺸":"㺸","珞":"珞","琉":"琉","理":"理","琢":"琢","瑇":"瑇","瑜":"瑜","瑩":"瑩","瑱":"瑱","瑱":"瑱","璅":"璅","璉":"璉","璘":"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶","留":"留","略":"略","異":"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒","痢":"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝","療":"療","癩":"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼","益":"益","益":"益","盛":"盛","盧":"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳","省":"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹","晣":"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝","硏":"研","硎":"硎","硫":"硫","碌":"碌","碌":"碌","碑":"碑","磊":"磊","磌":"磌","磌":"磌","磻":"磻","䃣":"䃣","礪":"礪","⽰":"示","⺭":"礻","礼":"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝","神":"神","祥":"祥","視":"視","視":"視","祿":"祿","𥚚":"𥚚","禍":"禍","禎":"禎","福":"福","福":"福","𥛅":"𥛅","禮":"禮","⽱":"禸","⽲":"禾","秊":"秊","䄯":"䄯","秫":"秫","稜":"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱","立":"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹","笠":"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐","簾":"簾","籠":"籠","⽶":"米","类":"类","粒":"粒","精":"精","糒":"糒","糖":"糖","糨":"糨","䊠":"䊠","糣":"糣","糧":"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀","紐":"紐","索":"索","累":"累","絶":"絕","絣":"絣","絛":"絛","綠":"綠","綾":"綾","緇":"緇","練":"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉","縷":"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙","罹":"罹","罺":"罺","羅":"羅","𦌾":"𦌾","⽺":"羊","羕":"羕","羚":"羚","羽":"羽","⽻":"羽","翺":"翺","老":"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳","聆":"聆","聠":"聠","𦖨":"𦖨","聯":"聯","聰":"聰","聾":"聾","⾀":"聿","⺺":"肀","⾁":"肉","肋":"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙","腁":"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵","朦":"䑃","臘":"臘","⾂":"臣","臨":"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮","良":"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽","若":"若","若":"若","苦":"苦","𦬼":"𦬼","茶":"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓","菉":"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華","菱":"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭","落":"落","葉":"葉","蔿":"蒍","𦳕":"𦳕","𦵫":"𦵫","蓮":"蓮","蓱":"蓱","蓳":"蓳","蓼":"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬","藍":"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡","藺":"藺","蘆":"蘆","䕫":"䕫","蘒":"蘒","蘭":"蘭","𧃒":"𧃒","虁":"蘷","蘿":"蘿","⾌":"虍","⻁":"虎","虐":"虐","虜":"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊","螺":"螺","蠁":"蠁","䗹":"䗹","蠟":"蠟","⾎":"血","行":"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤","裂":"裂","𧙧":"𧙧","裏":"裏","裗":"裗","裞":"裞","裡":"裡","裸":"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁","襤":"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆","見":"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦","詽":"訮","訞":"䚶","䚾":"䚾","䛇":"䛇","誠":"誠","說":"說","說":"說","調":"調","請":"請","諒":"諒","論":"論","諭":"諭","諭":"諭","諸":"諸","諸":"諸","諾":"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹","識":"識","讀":"讀","讏":"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆","豈":"豈","豕":"豕","⾗":"豕","豣":"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁","賂":"賂","賈":"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起","趆":"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼","跺":"跥","路":"路","跰":"跰","躛":"躗","⾝":"身","車":"車","⾞":"車","軔":"軔","輧":"軿","輦":"輦","輪":"輪","輸":"輸","輸":"輸","輻":"輻","轢":"轢","⻋":"车","⾟":"辛","辞":"辞","辰":"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡","連":"連","逸":"逸","逸":"逸","遲":"遲","遼":"遼","𨗒":"𨗒","𨗭":"𨗭","邏":"邏","⾢":"邑","邔":"邔","郎":"郎","郞":"郎","郞":"郎","郱":"郱","都":"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉","酪":"酪","醙":"醙","醴":"醴","⾤":"釆","里":"里","⾥":"里","量":"量","金":"金","⾦":"金","鈴":"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼","錄":"錄","鍊":"鍊","鎮":"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕","閭":"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝","阮":"阮","陋":"陋","降":"降","陵":"陵","陸":"陸","陼":"陼","隆":"隆","隣":"隣","䧦":"䧦","⾪":"隶","隷":"隷","隸":"隷","隸":"隷","⾫":"隹","雃":"雃","離":"離","難":"難","難":"難","⾬":"雨","零":"零","雷":"雷","霣":"霣","𩅅":"𩅅","露":"露","靈":"靈","⾭":"靑","⻘":"青","靖":"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋","領":"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻","類":"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢","飯":"飯","飼":"飼","䬳":"䬳","館":"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂","駱":"駱","駾":"駾","驪":"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚","魯":"魯","鱀":"鱀","鱗":"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎","鶴":"鶴","𪄅":"𪄅","䳸":"䳸","鷺":"鷺","𪈎":"𪈎","鸞":"鸞","鹃":"鹂","⿄":"鹵","鹿":"鹿","⿅":"鹿","𪊑":"𪊑","麗":"麗","麟":"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍","黎":"黎","䵖":"䵖","⿊":"黑","黒":"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿","龍":"龍","⿓":"龍","龎":"龎","⻰":"龙","龜":"龜","龜":"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"}},{}],282:[function(e,t,i){"use strict";var n=e("./data.json");var r=RegExp(Object.keys(n).map((function(e){return e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")})).join("|"),"g");function o(e){return n[e]}t.exports=function(e){return e.replace(r,o)}},{"./data.json":281}],283:[function(e,t,i){(function(e){(function(){function i(t){try{if(!e.localStorage)return!1}catch(e){return!1}var i=e.localStorage[t];return null!=i&&"true"===String(i).toLowerCase()}t.exports=function(e,t){if(i("noDeprecation"))return e;var n=!1;return function(){if(!n){if(i("throwDeprecation"))throw new Error(t);i("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],284:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],285:[function(e,t,i){"use strict";var n=e("is-arguments"),r=e("is-generator-function"),o=e("which-typed-array"),s=e("is-typed-array");function a(e){return e.call.bind(e)}var c="undefined"!=typeof BigInt,d="undefined"!=typeof Symbol,l=a(Object.prototype.toString),u=a(Number.prototype.valueOf),h=a(String.prototype.valueOf),f=a(Boolean.prototype.valueOf);if(c)var p=a(BigInt.prototype.valueOf);if(d)var g=a(Symbol.prototype.valueOf);function v(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function m(e){return"[object Map]"===l(e)}function y(e){return"[object Set]"===l(e)}function b(e){return"[object WeakMap]"===l(e)}function S(e){return"[object WeakSet]"===l(e)}function _(e){return"[object ArrayBuffer]"===l(e)}function E(e){return"undefined"!=typeof ArrayBuffer&&(_.working?_(e):e instanceof ArrayBuffer)}function w(e){return"[object DataView]"===l(e)}function T(e){return"undefined"!=typeof DataView&&(w.working?w(e):e instanceof DataView)}i.isArgumentsObject=n,i.isGeneratorFunction=r,i.isTypedArray=s,i.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},i.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):s(e)||T(e)},i.isUint8Array=function(e){return"Uint8Array"===o(e)},i.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===o(e)},i.isUint16Array=function(e){return"Uint16Array"===o(e)},i.isUint32Array=function(e){return"Uint32Array"===o(e)},i.isInt8Array=function(e){return"Int8Array"===o(e)},i.isInt16Array=function(e){return"Int16Array"===o(e)},i.isInt32Array=function(e){return"Int32Array"===o(e)},i.isFloat32Array=function(e){return"Float32Array"===o(e)},i.isFloat64Array=function(e){return"Float64Array"===o(e)},i.isBigInt64Array=function(e){return"BigInt64Array"===o(e)},i.isBigUint64Array=function(e){return"BigUint64Array"===o(e)},m.working="undefined"!=typeof Map&&m(new Map),i.isMap=function(e){return"undefined"!=typeof Map&&(m.working?m(e):e instanceof Map)},y.working="undefined"!=typeof Set&&y(new Set),i.isSet=function(e){return"undefined"!=typeof Set&&(y.working?y(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),i.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},S.working="undefined"!=typeof WeakSet&&S(new WeakSet),i.isWeakSet=function(e){return S(e)},_.working="undefined"!=typeof ArrayBuffer&&_(new ArrayBuffer),i.isArrayBuffer=E,w.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&w(new DataView(new ArrayBuffer(1),0,1)),i.isDataView=T;var I="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function R(e){return"[object SharedArrayBuffer]"===l(e)}function M(e){return void 0!==I&&(void 0===R.working&&(R.working=R(new I)),R.working?R(e):e instanceof I)}function k(e){return v(e,u)}function C(e){return v(e,h)}function O(e){return v(e,f)}function A(e){return c&&v(e,p)}function P(e){return d&&v(e,g)}i.isSharedArrayBuffer=M,i.isAsyncFunction=function(e){return"[object AsyncFunction]"===l(e)},i.isMapIterator=function(e){return"[object Map Iterator]"===l(e)},i.isSetIterator=function(e){return"[object Set Iterator]"===l(e)},i.isGeneratorObject=function(e){return"[object Generator]"===l(e)},i.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===l(e)},i.isNumberObject=k,i.isStringObject=C,i.isBooleanObject=O,i.isBigIntObject=A,i.isSymbolObject=P,i.isBoxedPrimitive=function(e){return k(e)||C(e)||O(e)||A(e)||P(e)},i.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(E(e)||M(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(i,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},{"is-arguments":147,"is-generator-function":149,"is-typed-array":150,"which-typed-array":303}],286:[function(e,t,i){(function(t){(function(){var n=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),i={},n=0;n<t.length;n++)i[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return i},r=/%[sdj%]/g;i.format=function(e){if(!y(e)){for(var t=[],i=0;i<arguments.length;i++)t.push(c(arguments[i]));return t.join(" ")}i=1;for(var n=arguments,o=n.length,s=String(e).replace(r,(function(e){if("%%"===e)return"%";if(i>=o)return e;switch(e){case"%s":return String(n[i++]);case"%d":return Number(n[i++]);case"%j":try{return JSON.stringify(n[i++])}catch(e){return"[Circular]"}default:return e}})),a=n[i];i<o;a=n[++i])v(a)||!_(a)?s+=" "+a:s+=" "+c(a);return s},i.deprecate=function(e,n){if(void 0!==t&&!0===t.noDeprecation)return e;if(void 0===t)return function(){return i.deprecate(e,n).apply(this,arguments)};var r=!1;return function(){if(!r){if(t.throwDeprecation)throw new Error(n);t.traceDeprecation?console.trace(n):console.error(n),r=!0}return e.apply(this,arguments)}};var o={},s=/^$/;if(t.env.NODE_DEBUG){var a=t.env.NODE_DEBUG;a=a.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),s=new RegExp("^"+a+"$","i")}function c(e,t){var n={seen:[],stylize:l};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&i._extend(n,t),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=d),u(n,e,n.depth)}function d(e,t){var i=c.styles[t];return i?"["+c.colors[i][0]+"m"+e+"["+c.colors[i][1]+"m":e}function l(e,t){return e}function u(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==i.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return y(r)||(r=u(e,r,n)),r}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(y(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(m(t))return e.stylize(""+t,"number");if(g(t))return e.stylize(""+t,"boolean");if(v(t))return e.stylize("null","null")}(e,t);if(o)return o;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),w(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return h(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(S(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(E(t))return e.stylize(Date.prototype.toString.call(t),"date");if(w(t))return h(t)}var d,l="",_=!1,I=["{","}"];(p(t)&&(_=!0,I=["[","]"]),T(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return S(t)&&(l=" "+RegExp.prototype.toString.call(t)),E(t)&&(l=" "+Date.prototype.toUTCString.call(t)),w(t)&&(l=" "+h(t)),0!==s.length||_&&0!=t.length?n<0?S(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),d=_?function(e,t,i,n,r){for(var o=[],s=0,a=t.length;s<a;++s)k(t,String(s))?o.push(f(e,t,i,n,String(s),!0)):o.push("");return r.forEach((function(r){r.match(/^\d+$/)||o.push(f(e,t,i,n,r,!0))})),o}(e,t,n,a,s):s.map((function(i){return f(e,t,n,a,i,_)})),e.seen.pop(),function(e,t,i){var n=e.reduce((function(e,t){return t.indexOf("\n")>=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1];return i[0]+t+" "+e.join(", ")+" "+i[1]}(d,l,I)):I[0]+l+I[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,i,n,r,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),k(n,r)||(s="["+r+"]"),a||(e.seen.indexOf(c.value)<0?(a=v(i)?u(e,c.value,null):u(e,c.value,i-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),b(s)){if(o&&r.match(/^\d+$/))return a;(s=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.slice(1,-1),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function v(e){return null===e}function m(e){return"number"==typeof e}function y(e){return"string"==typeof e}function b(e){return void 0===e}function S(e){return _(e)&&"[object RegExp]"===I(e)}function _(e){return"object"==typeof e&&null!==e}function E(e){return _(e)&&"[object Date]"===I(e)}function w(e){return _(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function R(e){return e<10?"0"+e.toString(10):e.toString(10)}i.debuglog=function(e){if(e=e.toUpperCase(),!o[e])if(s.test(e)){var n=t.pid;o[e]=function(){var t=i.format.apply(i,arguments);console.error("%s %d: %s",e,n,t)}}else o[e]=function(){};return o[e]},i.inspect=c,c.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},c.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},i.types=e("./support/types"),i.isArray=p,i.isBoolean=g,i.isNull=v,i.isNullOrUndefined=function(e){return null==e},i.isNumber=m,i.isString=y,i.isSymbol=function(e){return"symbol"==typeof e},i.isUndefined=b,i.isRegExp=S,i.types.isRegExp=S,i.isObject=_,i.isDate=E,i.types.isDate=E,i.isError=w,i.types.isNativeError=w,i.isFunction=T,i.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},i.isBuffer=e("./support/isBuffer");var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[R(e.getHours()),R(e.getMinutes()),R(e.getSeconds())].join(":"),[e.getDate(),M[e.getMonth()],t].join(" ")),i.format.apply(i,arguments))},i.inherits=e("inherits"),i._extend=function(e,t){if(!t||!_(t))return e;for(var i=Object.keys(t),n=i.length;n--;)e[i[n]]=t[i[n]];return e};var C="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function O(e,t){if(!e){var i=new Error("Promise was rejected with a falsy value");i.reason=e,e=i}return t(e)}i.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(C&&e[C]){var t;if("function"!=typeof(t=e[C]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,C,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,i,n=new Promise((function(e,n){t=e,i=n})),r=[],o=0;o<arguments.length;o++)r.push(arguments[o]);r.push((function(e,n){e?i(e):t(n)}));try{e.apply(this,r)}catch(e){i(e)}return n}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),C&&Object.defineProperty(t,C,{value:t,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(t,n(e))},i.promisify.custom=C,i.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function i(){for(var i=[],n=0;n<arguments.length;n++)i.push(arguments[n]);var r=i.pop();if("function"!=typeof r)throw new TypeError("The last argument must be of type Function");var o=this,s=function(){return r.apply(o,arguments)};e.apply(this,i).then((function(e){t.nextTick(s.bind(null,null,e))}),(function(e){t.nextTick(O.bind(null,e,s))}))}return Object.setPrototypeOf(i,Object.getPrototypeOf(e)),Object.defineProperties(i,n(e)),i}}).call(this)}).call(this,e("_process"))},{"./support/isBuffer":284,"./support/types":285,_process:237,inherits:146}],287:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),Object.defineProperty(i,"NIL",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"parse",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"stringify",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"v3",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"v4",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(i,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(i,"validate",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(i,"version",{enumerable:!0,get:function(){return c.default}});var n=h(e("./v1.js")),r=h(e("./v3.js")),o=h(e("./v4.js")),s=h(e("./v5.js")),a=h(e("./nil.js")),c=h(e("./version.js")),d=h(e("./validate.js")),l=h(e("./stringify.js")),u=h(e("./parse.js"));function h(e){return e&&e.__esModule?e:{default:e}}},{"./nil.js":290,"./parse.js":291,"./stringify.js":295,"./v1.js":296,"./v3.js":297,"./v4.js":299,"./v5.js":300,"./validate.js":301,"./version.js":302}],288:[function(e,t,i){"use strict";function n(e){return 14+(e+64>>>9<<4)+1}function r(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function o(e,t,i,n,o,s){return r((a=r(r(t,e),r(n,s)))<<(c=o)|a>>>32-c,i);var a,c}function s(e,t,i,n,r,s,a){return o(t&i|~t&n,e,t,r,s,a)}function a(e,t,i,n,r,s,a){return o(t&n|i&~n,e,t,r,s,a)}function c(e,t,i,n,r,s,a){return o(t^i^n,e,t,r,s,a)}function d(e,t,i,n,r,s,a){return o(i^(t|~n),e,t,r,s,a)}Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var l=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let i=0;i<t.length;++i)e[i]=t.charCodeAt(i)}return function(e){const t=[],i=32*e.length,n="0123456789abcdef";for(let r=0;r<i;r+=8){const i=e[r>>5]>>>r%32&255,o=parseInt(n.charAt(i>>>4&15)+n.charAt(15&i),16);t.push(o)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[n(t)-1]=t;let i=1732584193,o=-271733879,l=-1732584194,u=271733878;for(let t=0;t<e.length;t+=16){const n=i,h=o,f=l,p=u;i=s(i,o,l,u,e[t],7,-680876936),u=s(u,i,o,l,e[t+1],12,-389564586),l=s(l,u,i,o,e[t+2],17,606105819),o=s(o,l,u,i,e[t+3],22,-1044525330),i=s(i,o,l,u,e[t+4],7,-176418897),u=s(u,i,o,l,e[t+5],12,1200080426),l=s(l,u,i,o,e[t+6],17,-1473231341),o=s(o,l,u,i,e[t+7],22,-45705983),i=s(i,o,l,u,e[t+8],7,1770035416),u=s(u,i,o,l,e[t+9],12,-1958414417),l=s(l,u,i,o,e[t+10],17,-42063),o=s(o,l,u,i,e[t+11],22,-1990404162),i=s(i,o,l,u,e[t+12],7,1804603682),u=s(u,i,o,l,e[t+13],12,-40341101),l=s(l,u,i,o,e[t+14],17,-1502002290),o=s(o,l,u,i,e[t+15],22,1236535329),i=a(i,o,l,u,e[t+1],5,-165796510),u=a(u,i,o,l,e[t+6],9,-1069501632),l=a(l,u,i,o,e[t+11],14,643717713),o=a(o,l,u,i,e[t],20,-373897302),i=a(i,o,l,u,e[t+5],5,-701558691),u=a(u,i,o,l,e[t+10],9,38016083),l=a(l,u,i,o,e[t+15],14,-660478335),o=a(o,l,u,i,e[t+4],20,-405537848),i=a(i,o,l,u,e[t+9],5,568446438),u=a(u,i,o,l,e[t+14],9,-1019803690),l=a(l,u,i,o,e[t+3],14,-187363961),o=a(o,l,u,i,e[t+8],20,1163531501),i=a(i,o,l,u,e[t+13],5,-1444681467),u=a(u,i,o,l,e[t+2],9,-51403784),l=a(l,u,i,o,e[t+7],14,1735328473),o=a(o,l,u,i,e[t+12],20,-1926607734),i=c(i,o,l,u,e[t+5],4,-378558),u=c(u,i,o,l,e[t+8],11,-2022574463),l=c(l,u,i,o,e[t+11],16,1839030562),o=c(o,l,u,i,e[t+14],23,-35309556),i=c(i,o,l,u,e[t+1],4,-1530992060),u=c(u,i,o,l,e[t+4],11,1272893353),l=c(l,u,i,o,e[t+7],16,-155497632),o=c(o,l,u,i,e[t+10],23,-1094730640),i=c(i,o,l,u,e[t+13],4,681279174),u=c(u,i,o,l,e[t],11,-358537222),l=c(l,u,i,o,e[t+3],16,-722521979),o=c(o,l,u,i,e[t+6],23,76029189),i=c(i,o,l,u,e[t+9],4,-640364487),u=c(u,i,o,l,e[t+12],11,-421815835),l=c(l,u,i,o,e[t+15],16,530742520),o=c(o,l,u,i,e[t+2],23,-995338651),i=d(i,o,l,u,e[t],6,-198630844),u=d(u,i,o,l,e[t+7],10,1126891415),l=d(l,u,i,o,e[t+14],15,-1416354905),o=d(o,l,u,i,e[t+5],21,-57434055),i=d(i,o,l,u,e[t+12],6,1700485571),u=d(u,i,o,l,e[t+3],10,-1894986606),l=d(l,u,i,o,e[t+10],15,-1051523),o=d(o,l,u,i,e[t+1],21,-2054922799),i=d(i,o,l,u,e[t+8],6,1873313359),u=d(u,i,o,l,e[t+15],10,-30611744),l=d(l,u,i,o,e[t+6],15,-1560198380),o=d(o,l,u,i,e[t+13],21,1309151649),i=d(i,o,l,u,e[t+4],6,-145523070),u=d(u,i,o,l,e[t+11],10,-1120210379),l=d(l,u,i,o,e[t+2],15,718787259),o=d(o,l,u,i,e[t+9],21,-343485551),i=r(i,n),o=r(o,h),l=r(l,f),u=r(u,p)}return[i,o,l,u]}(function(e){if(0===e.length)return[];const t=8*e.length,i=new Uint32Array(n(t));for(let n=0;n<t;n+=8)i[n>>5]|=(255&e[n/8])<<n%32;return i}(e),8*e.length))};i.default=l},{}],289:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};i.default=n},{}],290:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;i.default="00000000-0000-0000-0000-000000000000"},{}],291:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n,r=(n=e("./validate.js"))&&n.__esModule?n:{default:n};var o=function(e){if(!(0,r.default)(e))throw TypeError("Invalid UUID");let t;const i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i};i.default=o},{"./validate.js":301}],292:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;i.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],293:[function(e,t,i){"use strict";let n;Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(){if(!n&&(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!n))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(r)};const r=new Uint8Array(16)},{}],294:[function(e,t,i){"use strict";function n(e,t,i,n){switch(e){case 0:return t&i^~t&n;case 1:case 3:return t^i^n;case 2:return t&i^t&n^i&n}}function r(e,t){return e<<t|e>>>32-t}Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var o=function(e){const t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);const o=e.length/4+2,s=Math.ceil(o/16),a=new Array(s);for(let t=0;t<s;++t){const i=new Uint32Array(16);for(let n=0;n<16;++n)i[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];a[t]=i}a[s-1][14]=8*(e.length-1)/Math.pow(2,32),a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const o=new Uint32Array(80);for(let t=0;t<16;++t)o[t]=a[e][t];for(let e=16;e<80;++e)o[e]=r(o[e-3]^o[e-8]^o[e-14]^o[e-16],1);let s=i[0],c=i[1],d=i[2],l=i[3],u=i[4];for(let e=0;e<80;++e){const i=Math.floor(e/20),a=r(s,5)+n(i,c,d,l)+u+t[i]+o[e]>>>0;u=l,l=d,d=r(c,30)>>>0,c=s,s=a}i[0]=i[0]+s>>>0,i[1]=i[1]+c>>>0,i[2]=i[2]+d>>>0,i[3]=i[3]+l>>>0,i[4]=i[4]+u>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]};i.default=o},{}],295:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0,i.unsafeStringify=s;var n,r=(n=e("./validate.js"))&&n.__esModule?n:{default:n};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));function s(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}var a=function(e,t=0){const i=s(e,t);if(!(0,r.default)(i))throw TypeError("Stringified UUID is invalid");return i};i.default=a},{"./validate.js":301}],296:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n,r=(n=e("./rng.js"))&&n.__esModule?n:{default:n},o=e("./stringify.js");let s,a,c=0,d=0;var l=function(e,t,i){let n=t&&i||0;const l=t||new Array(16);let u=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==u||null==h){const t=e.random||(e.rng||r.default)();null==u&&(u=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let f=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:d+1;const g=f-c+(p-d)/1e4;if(g<0&&void 0===e.clockseq&&(h=h+1&16383),(g<0||f>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,d=p,a=h,f+=122192928e5;const v=(1e4*(268435455&f)+p)%4294967296;l[n++]=v>>>24&255,l[n++]=v>>>16&255,l[n++]=v>>>8&255,l[n++]=255&v;const m=f/4294967296*1e4&268435455;l[n++]=m>>>8&255,l[n++]=255&m,l[n++]=m>>>24&15|16,l[n++]=m>>>16&255,l[n++]=h>>>8|128,l[n++]=255&h;for(let e=0;e<6;++e)l[n+e]=u[e];return t||(0,o.unsafeStringify)(l)};i.default=l},{"./rng.js":293,"./stringify.js":295}],297:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n=o(e("./v35.js")),r=o(e("./md5.js"));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,r.default);i.default=s},{"./md5.js":288,"./v35.js":298}],298:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.URL=i.DNS=void 0,i.default=function(e,t,i){function n(e,n,s,a){var c;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let i=0;i<e.length;++i)t.push(e.charCodeAt(i));return t}(e)),"string"==typeof n&&(n=(0,o.default)(n)),16!==(null===(c=n)||void 0===c?void 0:c.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+e.length);if(d.set(n),d.set(e,n.length),d=i(d),d[6]=15&d[6]|t,d[8]=63&d[8]|128,s){a=a||0;for(let e=0;e<16;++e)s[a+e]=d[e];return s}return(0,r.unsafeStringify)(d)}try{n.name=e}catch(e){}return n.DNS=s,n.URL=a,n};var n,r=e("./stringify.js"),o=(n=e("./parse.js"))&&n.__esModule?n:{default:n};const s="6ba7b810-9dad-11d1-80b4-00c04fd430c8";i.DNS=s;const a="6ba7b811-9dad-11d1-80b4-00c04fd430c8";i.URL=a},{"./parse.js":291,"./stringify.js":295}],299:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n=s(e("./native.js")),r=s(e("./rng.js")),o=e("./stringify.js");function s(e){return e&&e.__esModule?e:{default:e}}var a=function(e,t,i){if(n.default.randomUUID&&!t&&!e)return n.default.randomUUID();const s=(e=e||{}).random||(e.rng||r.default)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=s[e];return t}return(0,o.unsafeStringify)(s)};i.default=a},{"./native.js":289,"./rng.js":293,"./stringify.js":295}],300:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n=o(e("./v35.js")),r=o(e("./sha1.js"));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v5",80,r.default);i.default=s},{"./sha1.js":294,"./v35.js":298}],301:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n,r=(n=e("./regex.js"))&&n.__esModule?n:{default:n};var o=function(e){return"string"==typeof e&&r.default.test(e)};i.default=o},{"./regex.js":292}],302:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n,r=(n=e("./validate.js"))&&n.__esModule?n:{default:n};var o=function(e){if(!(0,r.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)};i.default=o},{"./validate.js":301}],303:[function(e,t,i){(function(i){(function(){"use strict";var n=e("for-each"),r=e("available-typed-arrays"),o=e("call-bind/callBound"),s=e("gopd"),a=o("Object.prototype.toString"),c=e("has-tostringtag/shams")(),d="undefined"==typeof globalThis?i:globalThis,l=r(),u=o("String.prototype.slice"),h={},f=Object.getPrototypeOf;c&&s&&f&&n(l,(function(e){if("function"==typeof d[e]){var t=new d[e];if(Symbol.toStringTag in t){var i=f(t),n=s(i,Symbol.toStringTag);if(!n){var r=f(i);n=s(r,Symbol.toStringTag)}h[e]=n.get}}}));var p=e("is-typed-array");t.exports=function(e){return!!p(e)&&(c&&Symbol.toStringTag in e?function(e){var t=!1;return n(h,(function(i,n){if(!t)try{var r=i.call(e);r===n&&(t=r)}catch(e){}})),t}(e):u(a(e),8,-1))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"available-typed-arrays":16,"call-bind/callBound":69,"for-each":107,gopd:111,"has-tostringtag/shams":114,"is-typed-array":150}],304:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RuleId=i.PushRuleKind=i.ConditionKind=i.isDmMemberCountCondition=i.DMMemberCountCondition=i.ConditionOperator=i.TweakName=i.PushRuleActionName=void 0,function(e){e.DontNotify="dont_notify",e.Notify="notify",e.Coalesce="coalesce"}(i.PushRuleActionName||(i.PushRuleActionName={})),function(e){e.Highlight="highlight",e.Sound="sound"}(i.TweakName||(i.TweakName={})),function(e){e.ExactEquals="==",e.LessThan="<",e.GreaterThan=">",e.GreaterThanOrEqual=">=",e.LessThanOrEqual="<="}(i.ConditionOperator||(i.ConditionOperator={})),i.DMMemberCountCondition="2",i.isDmMemberCountCondition=function(e){return"==2"===e||"2"===e},function(e){e.EventMatch="event_match",e.EventPropertyIs="event_property_is",e.EventPropertyContains="event_property_contains",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission",e.CallStarted="call_started",e.CallStartedPrefix="org.matrix.msc3914.call_started"}(i.ConditionKind||(i.ConditionKind={})),function(e){e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride"}(i.PushRuleKind||(i.PushRuleKind={})),function(e){e.Master=".m.rule.master",e.IsUserMention=".org.matrix.msc3952.is_user_mention",e.IsRoomMention=".org.matrix.msc3952.is_room_mention",e.ContainsDisplayName=".m.rule.contains_display_name",e.ContainsUserName=".m.rule.contains_user_name",e.AtRoomNotification=".m.rule.roomnotif",e.DM=".m.rule.room_one_to_one",e.EncryptedDM=".m.rule.encrypted_room_one_to_one",e.Message=".m.rule.message",e.EncryptedMessage=".m.rule.encrypted",e.InviteToSelf=".m.rule.invite_for_me",e.MemberEvent=".m.rule.member_event",e.IncomingCall=".m.rule.call",e.SuppressNotices=".m.rule.suppress_notices",e.Tombstone=".m.rule.tombstone",e.PollStart=".m.rule.poll_start",e.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",e.PollEnd=".m.rule.poll_end",e.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",e.PollStartOneToOne=".m.rule.poll_start_one_to_one",e.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",e.PollEndOneToOne=".m.rule.poll_end_one_to_one",e.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one"}(i.RuleId||(i.RuleId={}))},{}],305:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_BEACON=i.M_BEACON_INFO=void 0;const n=e("../NamespacedValue");i.M_BEACON_INFO=new n.UnstableValue("m.beacon_info","org.matrix.msc3672.beacon_info"),i.M_BEACON=new n.UnstableValue("m.beacon","org.matrix.msc3672.beacon")},{"../NamespacedValue":316}],306:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCAL_NOTIFICATION_SETTINGS_PREFIX=i.PUSHER_DEVICE_ID=i.PUSHER_ENABLED=i.EVENT_VISIBILITY_CHANGE_TYPE=i.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=i.MSC3912_RELATION_BASED_REDACTIONS_PROP=i.UNSTABLE_MSC2716_MARKER=i.UNSTABLE_MSC3089_BRANCH=i.UNSTABLE_MSC3089_LEAF=i.UNSTABLE_MSC3089_TREE_SUBTYPE=i.UNSTABLE_MSC3088_ENABLED=i.UNSTABLE_MSC3088_PURPOSE=i.ToDeviceMessageId=i.RoomType=i.RoomCreateTypeField=i.MsgType=i.RelationType=i.EventType=void 0;const n=e("../NamespacedValue");!function(e){e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.RoomPredecessor="org.matrix.msc3946.room_predecessor",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.KeyVerificationKey="m.key.verification.key",e.KeyVerificationAccept="m.key.verification.accept",e.KeyVerificationReady="m.key.verification.ready",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.PollStart="org.matrix.msc3381.poll.start",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy",e.GroupCallPrefix="org.matrix.msc3401.call",e.GroupCallMemberPrefix="org.matrix.msc3401.call.member"}(i.EventType||(i.EventType={})),function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"}(i.RelationType||(i.RelationType={})),function(e){e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request"}(i.MsgType||(i.MsgType={})),i.RoomCreateTypeField="type",function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"}(i.RoomType||(i.RoomType={})),i.ToDeviceMessageId="org.matrix.msgid",i.UNSTABLE_MSC3088_PURPOSE=new n.UnstableValue("m.room.purpose","org.matrix.msc3088.purpose"),i.UNSTABLE_MSC3088_ENABLED=new n.UnstableValue("m.enabled","org.matrix.msc3088.enabled"),i.UNSTABLE_MSC3089_TREE_SUBTYPE=new n.UnstableValue("m.data_tree","org.matrix.msc3089.data_tree"),i.UNSTABLE_MSC3089_LEAF=new n.UnstableValue("m.leaf","org.matrix.msc3089.leaf"),i.UNSTABLE_MSC3089_BRANCH=new n.UnstableValue("m.branch","org.matrix.msc3089.branch"),i.UNSTABLE_MSC2716_MARKER=new n.UnstableValue("m.room.marker","org.matrix.msc2716.marker"),i.MSC3912_RELATION_BASED_REDACTIONS_PROP=new n.UnstableValue("with_relations","org.matrix.msc3912.with_relations"),i.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=new n.UnstableValue("io.element.functional_members","io.element.functional_members"),i.EVENT_VISIBILITY_CHANGE_TYPE=new n.UnstableValue("m.visibility","org.matrix.msc3531.visibility"),i.PUSHER_ENABLED=new n.UnstableValue("enabled","org.matrix.msc3881.enabled"),i.PUSHER_DEVICE_ID=new n.UnstableValue("device_id","org.matrix.msc3881.device_id"),i.LOCAL_NOTIFICATION_SETTINGS_PREFIX=new n.UnstableValue("m.local_notification_settings","org.matrix.msc3890.local_notification_settings")},{"../NamespacedValue":316}],307:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isEventTypeSame=i.REFERENCE_RELATION=i.M_HTML=i.M_TEXT=i.M_MESSAGE=void 0;const n=e("matrix-events-sdk"),r=e("../extensible_events_v1/utilities");i.M_MESSAGE=new n.UnstableValue("m.message","org.matrix.msc1767.message"),i.M_TEXT=new n.UnstableValue("m.text","org.matrix.msc1767.text"),i.M_HTML=new n.UnstableValue("m.html","org.matrix.msc1767.html"),i.REFERENCE_RELATION=new n.NamespacedValue("m.reference"),i.isEventTypeSame=function(e,t){if("string"==typeof e)return"string"==typeof t?t===e:t.matches(e);if("string"==typeof t)return e.matches(t);{const i=t,n=e;return i.matches(n.name)||(0,r.isProvided)(n.altName)&&i.matches(n.altName)}}},{"../extensible_events_v1/utilities":361,"matrix-events-sdk":167}],308:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_LOCATION=i.M_TIMESTAMP=i.M_ASSET=i.LocationAssetType=void 0;const n=e("../NamespacedValue");e("./extensible_events");!function(e){e.Self="m.self",e.Pin="m.pin"}(i.LocationAssetType||(i.LocationAssetType={})),i.M_ASSET=new n.UnstableValue("m.asset","org.matrix.msc3488.asset"),i.M_TIMESTAMP=new n.UnstableValue("m.ts","org.matrix.msc3488.ts"),i.M_LOCATION=new n.UnstableValue("m.location","org.matrix.msc3488.location")},{"../NamespacedValue":316,"./extensible_events":307}],309:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.HistoryVisibility=i.GuestAccess=i.RestrictedAllowType=i.JoinRule=i.Preset=i.Visibility=void 0,function(e){e.Public="public",e.Private="private"}(i.Visibility||(i.Visibility={})),function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"}(i.Preset||(i.Preset={})),function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"}(i.JoinRule||(i.JoinRule={})),function(e){e.RoomMembership="m.room_membership"}(i.RestrictedAllowType||(i.RestrictedAllowType={})),function(e){e.CanJoin="can_join",e.Forbidden="forbidden"}(i.GuestAccess||(i.GuestAccess={})),function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"}(i.HistoryVisibility||(i.HistoryVisibility={}))},{}],310:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_POLL_END=i.M_POLL_RESPONSE=i.M_POLL_START=i.M_POLL_KIND_UNDISCLOSED=i.M_POLL_KIND_DISCLOSED=void 0;const n=e("matrix-events-sdk");i.M_POLL_KIND_DISCLOSED=new n.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed"),i.M_POLL_KIND_UNDISCLOSED=new n.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed"),i.M_POLL_START=new n.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start"),i.M_POLL_RESPONSE=new n.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response"),i.M_POLL_END=new n.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end")},{"matrix-events-sdk":167}],311:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MAIN_ROOM_TIMELINE=i.ReceiptType=void 0,function(e){e.Read="m.read",e.FullyRead="m.fully_read",e.ReadPrivate="m.read.private"}(i.ReceiptType||(i.ReceiptType={})),i.MAIN_ROOM_TIMELINE="main"},{}],312:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0})},{}],313:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.SearchOrderBy=void 0,function(e){e.RoomId="room_id",e.Sender="sender"}(n||(n={})),function(e){e.Recent="recent",e.Rank="rank"}(i.SearchOrderBy||(i.SearchOrderBy={}))},{}],314:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UNREAD_THREAD_NOTIFICATIONS=void 0;const n=e("../NamespacedValue");i.UNREAD_THREAD_NOTIFICATIONS=new n.ServerControlledNamespacedValue("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications")},{"../NamespacedValue":316}],315:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_TOPIC=void 0;const n=e("../NamespacedValue");i.M_TOPIC=new n.UnstableValue("m.topic","org.matrix.msc3765.topic")},{"../NamespacedValue":316}],316:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UnstableValue=i.ServerControlledNamespacedValue=i.NamespacedValue=void 0;class n{constructor(e,t){if(this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}get names(){const e=[this.name],t=this.altName;return t&&e.push(t),e}matches(e){return this.name===e||this.altName===e}findIn(e){let t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}includedIn(e){let t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}i.NamespacedValue=n;i.ServerControlledNamespacedValue=class extends n{constructor(){super(...arguments),this.preferUnstable=!1}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}};i.UnstableValue=class extends n{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}}},{}],317:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TypedReEmitter=i.ReEmitter=void 0;class n{constructor(e){this.target=e,this.reEmitters=new Map}reEmit(e,t){let i=this.reEmitters.get(e);i||(i=new Map,this.reEmitters.set(e,i));for(const n of t){const t=(...t)=>{"error"===n&&0===this.target.listenerCount("error")||this.target.emit(n,...t,e)};e.on(n,t),i.set(n,t)}}stopReEmitting(e,t){const i=this.reEmitters.get(e);if(i){for(const n of t)e.off(n,i.get(n)),i.delete(n);0===i.size&&this.reEmitters.delete(e)}}}i.ReEmitter=n;i.TypedReEmitter=class extends n{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}stopReEmitting(e,t){super.stopReEmitting(e,t)}}},{}],318:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.ToDeviceMessageQueue=void 0;const r=e("./@types/event"),o=e("./logger"),s=e("./client"),a=e("./scheduler"),c=e("./sync"),d=e("./utils");i.ToDeviceMessageQueue=class{constructor(e){this.client=e,this.sending=!1,this.running=!0,this.retryTimeout=null,this.retryAttempts=0,this.sendQueue=()=>n(this,void 0,void 0,(function*(){if(null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.sending||!this.running)return;let e;o.logger.debug("Attempting to send queued to-device messages"),this.sending=!0;try{for(;this.running&&(e=yield this.client.store.getOldestToDeviceBatch(),null!==e);)yield this.sendBatch(e),yield this.client.store.removeToDeviceBatch(e.id),this.retryAttempts=0;if(!this.running)return;o.logger.debug("All queued to-device messages sent")}catch(t){++this.retryAttempts;const i=a.MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null,this.retryAttempts,t);if(-1===i)return void(4===Math.floor(t.httpStatus/100)?(o.logger.error("Fatal error when sending to-device message - dropping to-device batch!",t),yield this.client.store.removeToDeviceBatch(e.id)):o.logger.info("Automatic retry limit reached for to-device messages."));o.logger.info(`Failed to send batch of to-device messages. Will retry in ${i}ms`,t),this.retryTimeout=setTimeout(this.sendQueue,i)}finally{this.sending=!1}})),this.onResumedSync=(e,t)=>{e===c.SyncState.Syncing&&t!==c.SyncState.Syncing&&(o.logger.info("Resuming queue after resumed sync"),this.sendQueue())}}start(){this.running=!0,this.sendQueue(),this.client.on(s.ClientEvent.Sync,this.onResumedSync)}stop(){this.running=!1,null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(s.ClientEvent.Sync,this.onResumedSync)}queueBatch(e){return n(this,void 0,void 0,(function*(){const t=[];for(let i=0;i<e.batch.length;i+=20){const n={eventType:e.eventType,batch:e.batch.slice(i,i+20),txnId:this.client.makeTxnId()};t.push(n);const s=n.batch.map((e=>`${e.userId}/${e.deviceId} (msgid ${e.payload[r.ToDeviceMessageId]})`));o.logger.info(`Enqueuing batch of to-device messages. type=${e.eventType} txnid=${n.txnId}`,s)}yield this.client.store.saveToDeviceBatches(t),this.sendQueue()}))}sendBatch(e){return n(this,void 0,void 0,(function*(){const t=new d.MapWithDefault((()=>new Map));for(const i of e.batch)t.getOrCreate(i.userId).set(i.deviceId,i.payload);o.logger.info(`Sending batch of ${e.batch.length} to-device messages with ID ${e.id} and txnId ${e.txnId}`),yield this.client.sendToDevice(e.eventType,t,e.txnId)}))}}},{"./@types/event":306,"./client":321,"./logger":374,"./scheduler":403,"./sync":414,"./utils":416}],319:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.AutoDiscovery=i.AutoDiscoveryAction=void 0;const r=e("./logger"),o=e("./http-api");var s,a;!function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"}(s=i.AutoDiscoveryAction||(i.AutoDiscoveryAction={})),function(e){e.Invalid="Invalid homeserver discovery response",e.GenericFailure="Failed to get autodiscovery configuration from server",e.InvalidHsBaseUrl="Invalid base_url for m.homeserver",e.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",e.InvalidIsBaseUrl="Invalid base_url for m.identity_server",e.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",e.InvalidIs="Invalid identity server discovery response",e.MissingWellknown="No .well-known JSON file found",e.InvalidJson="Invalid JSON"}(a||(a={}));class c{static fromDiscoveryConfig(e){var t;return n(this,void 0,void 0,(function*(){const i={"m.homeserver":{state:c.FAIL_ERROR,error:c.ERROR_INVALID,base_url:null},"m.identity_server":{state:c.PROMPT,error:null,base_url:null}};if(!e||!e["m.homeserver"])return r.logger.error("No m.homeserver key in config"),i["m.homeserver"].state=c.FAIL_PROMPT,i["m.homeserver"].error=c.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return r.logger.error("No m.homeserver base_url in config"),i["m.homeserver"].state=c.FAIL_PROMPT,i["m.homeserver"].error=c.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const n=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!n)return r.logger.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=c.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const o=yield this.fetchWellKnownObject(`${n}/_matrix/client/versions`);if(!o||!(null===(t=o.raw)||void 0===t?void 0:t.versions))return r.logger.error("Invalid /versions response"),i["m.homeserver"].error=c.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=n,Promise.resolve(i);i["m.homeserver"]={state:c.SUCCESS,error:null,base_url:n};let a="";if(e["m.identity_server"]){const t={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:c.FAIL_PROMPT,error:c.ERROR_INVALID_IS,base_url:null}};if(a=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!a)return r.logger.error("Invalid base_url for m.identity_server"),t["m.identity_server"].error=c.ERROR_INVALID_IS_BASE_URL,Promise.resolve(t);const n=yield this.fetchWellKnownObject(`${a}/_matrix/identity/v2`);if(!(null==n?void 0:n.raw)||n.action!==s.SUCCESS)return r.logger.error("Invalid /v2 response"),t["m.identity_server"].error=c.ERROR_INVALID_IDENTITY_SERVER,t["m.identity_server"].base_url=a,Promise.resolve(t)}return a&&a.toString().length>0&&(i["m.identity_server"]={state:c.SUCCESS,error:null,base_url:a}),Object.keys(e).forEach((t=>{if("m.homeserver"===t||"m.identity_server"===t){const n=["error","state","base_url"];for(const r of Object.keys(e[t]))n.includes(r)||(i[t][r]=e[t][r])}else i[t]=e[t]})),Promise.resolve(i)}))}static findClientConfig(e){return n(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:c.FAIL_ERROR,error:c.ERROR_INVALID,base_url:null},"m.identity_server":{state:c.PROMPT,error:null,base_url:null}},i=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return i&&i.action===s.SUCCESS?c.fromDiscoveryConfig(i.raw):(r.logger.error("No response or error when parsing .well-known"),i.reason&&r.logger.error(i.reason),i.action===s.IGNORE?t["m.homeserver"]={state:c.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=c.FAIL_PROMPT,t["m.homeserver"].error=c.ERROR_INVALID),Promise.resolve(t))}))}static getRawClientConfig(e){return n(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return t&&t.raw||{}}))}static sanitizeWellKnownUrl(e){if(!e)return!1;try{let t;try{t=new URL(e)}catch(e){r.logger.error("Could not parse url",e)}if(!(null==t?void 0:t.hostname))return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const i=t.port?`:${t.port}`:"",n=t.pathname?t.pathname:"";let o=`${t.protocol}//${t.hostname}${i}${n}`;return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(e){return r.logger.error(e),!1}}static fetch(e,i){return this.fetchFn?this.fetchFn(e,i):t.fetch(e,i)}static setFetchFn(e){c.fetchFn=e}static fetchWellKnownObject(e){return n(this,void 0,void 0,(function*(){let t;try{if(t=yield c.fetch(e,{method:o.Method.Get,signal:(0,o.timeoutSignal)(5e3)}),404===t.status)return{raw:{},action:s.IGNORE,reason:c.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:s.FAIL_PROMPT,reason:"General failure"}}catch(e){const t=e;let i="";return"object"==typeof t&&(i=null==t?void 0:t.message),{error:t,raw:{},action:s.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield t.json(),action:s.SUCCESS}}catch(e){const t=e;return{error:t,raw:{},action:s.FAIL_PROMPT,reason:"SyntaxError"===(null==t?void 0:t.name)?c.ERROR_INVALID_JSON:c.ERROR_INVALID}}}))}}i.AutoDiscovery=c,c.ERROR_INVALID=a.Invalid,c.ERROR_GENERIC_FAILURE=a.GenericFailure,c.ERROR_INVALID_HS_BASE_URL=a.InvalidHsBaseUrl,c.ERROR_INVALID_HOMESERVER=a.InvalidHomeserver,c.ERROR_INVALID_IS_BASE_URL=a.InvalidIsBaseUrl,c.ERROR_INVALID_IDENTITY_SERVER=a.InvalidIdentityServer,c.ERROR_INVALID_IS=a.InvalidIs,c.ERROR_MISSING_WELLKNOWN=a.MissingWellknown,c.ERROR_INVALID_JSON=a.InvalidJson,c.ALL_ERRORS=Object.keys(a),c.FAIL_ERROR=s.FAIL_ERROR,c.FAIL_PROMPT=s.FAIL_PROMPT,c.PROMPT=s.PROMPT,c.SUCCESS=s.SUCCESS}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./http-api":367,"./logger":374}],320:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0});const a=o(e("./matrix"));if(t.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");let c;t.__js_sdk_entrypoint=!0;try{c=t.indexedDB}catch(e){}c&&a.setCryptoStoreFactory((()=>new a.IndexedDBCryptoStore(c,"matrix-js-sdk:crypto"))),s(e("./matrix"),i),i.default=a,t.matrixcs=a}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./matrix":375}],321:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},a=this&&this.__rest||function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};Object.defineProperty(i,"__esModule",{value:!0}),i.fixNotificationCountOnDecryption=i.MatrixClient=i.ClientEvent=i.M_AUTHENTICATION=i.RoomVersionStability=i.PendingEventOrdering=i.UNSTABLE_MSC3852_LAST_SEEN_UA=i.CRYPTO_ENABLED=void 0;const c=e("./sync"),d=e("./models/event"),l=e("./store/stub"),u=e("./webrtc/call"),h=e("./filter"),f=e("./webrtc/callEventHandler"),p=o(e("./utils")),g=e("./utils"),v=e("./models/event-timeline"),m=e("./pushprocessor"),y=e("./autodiscovery"),b=o(e("./crypto/olmlib")),S=e("./crypto/olmlib"),_=e("./ReEmitter"),E=e("./crypto/RoomList"),w=e("./logger"),T=e("./service-types"),I=e("./http-api"),R=e("./crypto"),M=e("./crypto/recoverykey"),k=e("./crypto/key_passphrase"),C=e("./models/user"),O=e("./content-repo"),A=e("./models/search-result"),P=e("./crypto/dehydration"),D=e("./crypto/api"),x=o(e("./content-helpers")),L=e("./models/room"),U=e("./models/room-member"),B=e("./@types/event"),N=e("./@types/partials"),j=e("./event-mapper"),F=e("./randomstring"),K=e("./crypto/backup"),q=e("./models/MSC3089TreeSpace"),$=e("./@types/search"),V=e("./@types/PushRules"),H=e("./webrtc/groupCall"),W=e("./webrtc/mediaHandler"),G=e("./webrtc/groupCallEventHandler"),z=e("./models/typed-event-emitter"),Y=e("./@types/read_receipts"),J=e("./sliding-sync-sdk"),Q=e("./models/thread"),X=e("./@types/beacon"),Z=e("./NamespacedValue"),ee=e("./ToDeviceMessageQueue"),te=e("./models/invites-ignorer"),ie=e("./feature"),ne=e("./rust-crypto/constants");i.CRYPTO_ENABLED=(0,R.isCryptoAvailable)();const re=6e5;var oe;i.UNSTABLE_MSC3852_LAST_SEEN_UA=new Z.UnstableValue("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),function(e){e.Chronological="chronological",e.Detached="detached"}(i.PendingEventOrdering||(i.PendingEventOrdering={})),function(e){e.Stable="stable",e.Unstable="unstable"}(i.RoomVersionStability||(i.RoomVersionStability={})),function(e){e.MasterKey="master_key",e.SelfSigningKey="self_signing_key",e.UserSigningKey="user_signing_key"}(oe||(oe={})),i.M_AUTHENTICATION=new Z.UnstableValue("m.authentication","org.matrix.msc2965.authentication");const se="$";var ae;!function(e){e.Sync="sync",e.Event="event",e.ToDeviceEvent="toDeviceEvent",e.AccountData="accountData",e.Room="Room",e.DeleteRoom="deleteRoom",e.SyncUnexpectedError="sync.unexpectedError",e.ClientWellKnown="WellKnown.client",e.ReceivedVoipEvent="received_voip_event",e.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",e.TurnServers="turnServers",e.TurnServersError="turnServers.error"}(ae=i.ClientEvent||(i.ClientEvent={}));const ce=new Z.UnstableValue("action","org.matrix.msc3824.action");class de extends z.TypedEventEmitter{constructor(e){var t;super(),this.reEmitter=new _.TypedReEmitter(this),this.olmVersion=null,this.usingExternalCrypto=!1,this.clientRunning=!1,this.timelineSupport=!1,this.urlPreviewCache={},this.supportsCallTransfer=!1,this.forceTURN=!1,this.iceCandidatePoolSize=0,this.canSupportVoip=!1,this.peekSync=null,this.isGuestAccount=!1,this.ongoingScrollbacks={},this.notifTimelineSet=null,this.fallbackICEServerAllowed=!1,this.syncedLeftRooms=!1,this.canSupport=new Map,this.pushProcessor=new m.PushProcessor(this),this.turnServers=[],this.turnServersExpiry=0,this.txnCtr=0,this.mediaHandler=new W.MediaHandler(this),this.pendingEventEncryption=new Map,this.useE2eForGroupCall=!0,this.startCallEventHandler=()=>{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.groupCallEventHandler.start(),this.off(ae.Sync,this.startCallEventHandler))},this.fixupRoomNotifications=()=>{var e;if(this.isInitialSyncComplete()){const t=(null!==(e=this.getRooms())&&void 0!==e?e:[]).filter((e=>e.getUnreadNotificationCount(L.NotificationCountType.Total)>0));for(const e of t){const t=this.getSafeUserId();e.fixupNotifications(t)}this.off(ae.Sync,this.fixupRoomNotifications)}},e.baseUrl=p.ensureNoTrailingSlash(e.baseUrl),e.idBaseUrl=p.ensureNoTrailingSlash(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=null!==(t=e.usingExternalCrypto)&&void 0!==t&&t,this.store=e.store||new l.StubStore,this.deviceId=e.deviceId||null,this.sessionId=(0,F.randomString)(10);const i=e.userId||null;this.credentials={userId:i},this.http=new I.MatrixHttpApi(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,prefix:I.ClientPrefix.R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?w.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?w.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):w.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction((e=>s(this,void 0,void 0,(function*(){const t=this.getRoom(e.getRoomId());e.status!==d.EventStatus.SENDING&&this.updatePendingEventStatus(t,e,d.EventStatus.SENDING);const i=yield this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,d.EventStatus.SENT,i.event_id),i})))),(0,u.supportsMatrixCall)()&&(this.callEventHandler=new f.CallEventHandler(this),this.groupCallEventHandler=new G.GroupCallEventHandler(this),this.canSupportVoip=!0,this.on(ae.Sync,this.startCallEventHandler)),this.on(ae.Sync,this.fixupRoomNotifications),this.timelineSupport=Boolean(e.timelineSupport),this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,void 0!==e.useE2eForGroupCall&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.roomList=new E.RoomList(this.cryptoStore),this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new ee.ToDeviceMessageQueue(this),this.on(d.MatrixEventEvent.Decrypted,(e=>{le(this,e)})),this.on(L.RoomEvent.Receipt,((e,t)=>{var i;if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter((e=>{for(const[t,i]of Object.entries(n[e]))if(p.isSupportedReceiptType(t)&&i&&Object.keys(i).includes(this.getUserId()))return!0;return!1})).length>0))return;const r=20,o=t.getLiveTimeline().getEvents();let s=0;for(let e=o.length-1;e>=0;e--){if(e===o.length-r)return;const n=o[e];if(t.hasUserReadEvent(this.getUserId(),n.getId()))break;const a=this.getPushActionsForEvent(n);s+=(null===(i=null==a?void 0:a.tweaks)||void 0===i?void 0:i.highlight)?1:0}t.setUnreadNotificationCount(L.NotificationCountType.Highlight,s)}})),this.ignoredInvites=new te.IgnoredInvites(this)}startClient(e){return s(this,void 0,void 0,(function*(){if(this.clientRunning)return;this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e});const t=this.getUserId();t&&this.store.storeUser(new C.User(t)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),re),this.checkTurnServers()),this.syncApi&&(w.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{yield this.getVersions();const{threads:e,list:t,fwdPagination:i}=yield this.doesServerSupportThread();Q.Thread.setServerSideSupport(e),Q.Thread.setServerSideListSupport(t),Q.Thread.setServerSideFwdPaginationSupport(i)}catch(e){w.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",e)}this.clientOpts=null!=e?e:{},this.clientOpts.slidingSync?this.syncApi=new J.SlidingSyncSdk(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()),this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&w.logger.warn("`experimentalThreadSupport` has been deprecated, use `threadSupport` instead"),!this.clientOpts.hasOwnProperty("threadSupport")&&this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&(this.clientOpts.threadSupport=this.clientOpts.experimentalThreadSupport),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval((()=>{this.fetchClientWellKnown()}),1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start()}))}buildSyncApiOptions(){return{crypto:this.crypto,cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e)}}stopClient(){var e,i,n,r,o;null===(e=this.cryptoBackend)||void 0===e||e.stop(),this.clientRunning&&(w.logger.log("stopping MatrixClient"),this.clientRunning=!1,null===(i=this.syncApi)||void 0===i||i.stop(),this.syncApi=void 0,null===(n=this.peekSync)||void 0===n||n.stopPeeking(),null===(r=this.callEventHandler)||void 0===r||r.stop(),null===(o=this.groupCallEventHandler)||void 0===o||o.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,void 0!==this.clientWellKnownIntervalID&&t.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop())}rehydrateDevice(){return s(this,void 0,void 0,(function*(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const e=yield this.getDehydratedDevice();if(!e)return;if(!e.device_data||!e.device_id)return void w.logger.info("no dehydrated device found");const i=new t.Olm.Account;try{const t=e.device_data;if(t.algorithm!==P.DEHYDRATION_ALGORITHM)return void w.logger.warn("Wrong algorithm for dehydrated device");w.logger.log("unpickling dehydrated device");const n=yield this.cryptoCallbacks.getDehydrationKey(t,(e=>{i.unpickle(new Uint8Array(e),t.account)}));i.unpickle(n,t.account),w.logger.log("unpickled device");if((yield this.http.authedRequest(I.Method.Post,"/dehydrated_device/claim",void 0,{device_id:e.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=e.device_id,w.logger.info("using dehydrated device");const t=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:i.pickle(t),sessions:[],pickleKey:t},i.free(),this.deviceId}return i.free(),void w.logger.info("not using dehydrated device")}catch(e){i.free(),w.logger.warn("could not unpickle",e)}}))}getDehydratedDevice(){return s(this,void 0,void 0,(function*(){try{return yield this.http.authedRequest(I.Method.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void w.logger.info("could not get dehydrated device",e)}}))}setDehydrationKey(e,t,i){return s(this,void 0,void 0,(function*(){if(this.crypto)return this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,i);w.logger.warn("not dehydrating device if crypto is not enabled")}))}createDehydratedDevice(e,t,i){return s(this,void 0,void 0,(function*(){if(this.crypto)return yield this.crypto.dehydrationManager.setKey(e,t,i),this.crypto.dehydrationManager.dehydrateDevice();w.logger.warn("not dehydrating device if crypto is not enabled")}))}exportDevice(){return s(this,void 0,void 0,(function*(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:yield this.crypto.olmDevice.export()};w.logger.warn("not exporting device if crypto is not enabled")}))}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];e.push(this.store.deleteAllData()),this.cryptoStore&&e.push(this.cryptoStore.deleteAllData());return e.push((()=>s(this,void 0,void 0,(function*(){let e;try{e=t.indexedDB}catch(e){return}for(const t of[`${ne.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,`${ne.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`]){const i=new Promise(((i,n)=>{w.logger.info(`Removing IndexedDB instance ${t}`);const r=e.deleteDatabase(t);r.onsuccess=e=>{w.logger.info(`Removed IndexedDB instance ${t}`),i(0)},r.onerror=e=>{w.logger.warn(`Failed to remove IndexedDB instance ${t}:`,e),i(0)},r.onblocked=e=>{w.logger.info(`cannot yet remove IndexedDB instance ${t}`)}}));yield i}})))()),Promise.all(e).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return(0,u.createNewMatrixCall)(this,e)}createGroupCall(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const s=this.getRoom(e);if(!s)throw new Error(`Cannot find room ${e}`);return new H.GroupCall(this,s,t,i,n,void 0,r||this.isVoipWithNoMediaAllowed,o,this.isVoipWithNoMediaAllowed).create()}))}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return null!==(t=null===(e=this.syncApi)||void 0===e?void 0:e.getSyncState())&&void 0!==t?t:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===c.SyncState.Prepared||e===c.SyncState.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),null!==(t=null===(e=this.syncApi)||void 0===e?void 0:e.retryImmediately())&&void 0!==t&&t}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(e=!1){const t=(new Date).getTime();return this.cachedCapabilities&&!e&&t<this.cachedCapabilities.expiration?(w.logger.log("Returning cached capabilities"),Promise.resolve(this.cachedCapabilities.capabilities)):this.http.authedRequest(I.Method.Get,"/capabilities").catch((e=>(w.logger.error(e),{}))).then(((e={})=>{const i=e.capabilities||{},n=Object.keys(i).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:i,expiration:t+n},w.logger.log("Caching capabilities: ",i),i}))}initCrypto(){return s(this,void 0,void 0,(function*(){if(!(0,R.isCryptoAvailable)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.cryptoBackend)return void w.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");w.logger.log("Crypto: Starting up crypto store..."),yield this.cryptoStore.startup(),w.logger.log("Crypto: initialising roomlist..."),yield this.roomList.init();const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(null===this.deviceId)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const t=new R.Crypto(this,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,[R.CryptoEvent.KeyBackupFailed,R.CryptoEvent.KeyBackupSessionsRemaining,R.CryptoEvent.RoomKeyRequest,R.CryptoEvent.RoomKeyRequestCancellation,R.CryptoEvent.Warning,R.CryptoEvent.DevicesUpdated,R.CryptoEvent.WillUpdateDevices,R.CryptoEvent.DeviceVerificationChanged,R.CryptoEvent.UserTrustStatusChanged,R.CryptoEvent.KeysChanged]),w.logger.log("Crypto: initialising crypto object..."),yield t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=R.Crypto.getOlmVersion(),t.registerEventHandlers(this),this.cryptoBackend=this.crypto=t,this.crypto.uploadDeviceKeys().catch((e=>{w.logger.error("Error uploading device keys",e)}))}))}initRustCrypto(){return s(this,void 0,void 0,(function*(){if(this.cryptoBackend)return void w.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");const t=this.getUserId();if(null===t)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const i=this.getDeviceId();if(null===i)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const n=yield Promise.resolve().then((()=>o(e("./rust-crypto")))),r=yield n.initRustCrypto(this.http,t,i);this.cryptoBackend=r,this.on(U.RoomMemberEvent.Membership,r.onRoomMembership.bind(r))}))}getCrypto(){return this.cryptoBackend}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var e,t;return null!==(t=null===(e=this.crypto)||void 0===e?void 0:e.getDeviceEd25519Key())&&void 0!==t?t:null}getDeviceCurve25519Key(){var e,t;return null!==(t=null===(e=this.crypto)||void 0===e?void 0:e.getDeviceCurve25519Key())&&void 0!==t?t:null}uploadKeys(){return s(this,void 0,void 0,(function*(){w.logger.warn("MatrixClient.uploadKeys is deprecated")}))}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t,i=!0){const n=this.setDeviceVerification(e,t,i,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),n}setDeviceBlocked(e,t,i=!0){return this.setDeviceVerification(e,t,null,i,null)}setDeviceKnown(e,t,i=!0){return this.setDeviceVerification(e,t,null,null,i)}setDeviceVerification(e,t,i,n,r){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.setDeviceVerification(e,t,i,n,r)}))}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,i)}checkSecretStorageKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=e,e}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(e=D.CrossSigningKey.Master){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,i)}prepareToEncrypt(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.prepareToEncrypt(e)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,i)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,i)}getSecret(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(e)}isSecretStored(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}getEventSenderDeviceInfo(e){return s(this,void 0,void 0,(function*(){return this.crypto?this.crypto.getEventSenderDeviceInfo(e):null}))}isEventSenderVerified(e){return s(this,void 0,void 0,(function*(){const t=yield this.getEventSenderDeviceInfo(e);return!!t&&t.isVerified()}))}getOutgoingRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");const t=e.getWireContent(),i={session_id:t.session_id,sender_key:t.sender_key,algorithm:t.algorithm,room_id:e.getRoomId()};return i.session_id&&i.sender_key&&i.algorithm&&i.room_id?this.crypto.cryptoStore.getOutgoingRoomKeyRequest(i):Promise.resolve(null)}cancelAndResendEventRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){const t=this.getRoom(e);if(!t)return!1;return!!t.currentState.getStateEvents(B.EventType.RoomEncryption,"")||this.roomList.isRoomEncrypted(e)}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.cryptoBackend)throw new Error("End-to-End encryption disabled");this.cryptoBackend.forceDiscardSession(e)}exportRoomKeys(){return this.cryptoBackend?this.cryptoBackend.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(e,t)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}getKeyBackupVersion(){return s(this,void 0,void 0,(function*(){let e;try{e=yield this.http.authedRequest(I.Method.Get,"/room_keys/version",void 0,void 0,{prefix:I.ClientPrefix.V3})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}return K.BackupManager.checkBackupVersion(e),e}))}isKeyBackupTrusted(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}prepareKeyBackupVersion(e,t={secureSecretStorage:!1}){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:i,auth_data:n,recovery_key:r,privateKey:o}=yield this.crypto.backupManager.prepareKeyBackupVersion(e);return t.secureSecretStorage&&(yield this.storeSecret("m.megolm_backup.v1",(0,S.encodeBase64)(o)),w.logger.info("Key backup private key stored in secret storage")),{algorithm:i,auth_data:n,recovery_key:r}}))}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1"))}createKeyBackupVersion(e){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.backupManager.createKeyBackupVersion(e);const t={algorithm:e.algorithm,auth_data:e.auth_data};yield this.crypto.signObject(t.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&(yield this.crypto.crossSigningInfo.signObject(t.auth_data,"master"));const i=yield this.http.authedRequest(I.Method.Post,"/room_keys/version",void 0,t,{prefix:I.ClientPrefix.V3});return yield this.checkKeyBackup(),this.getKeyBackupEnabled()||w.logger.error("Key backup not usable even though we just created it"),i}))}deleteKeyBackupVersion(e){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const t=p.encodeUri("/room_keys/version/$version",{$version:e});yield this.http.authedRequest(I.Method.Delete,t,void 0,void 0,{prefix:I.ClientPrefix.V3})}))}makeKeyBackupPath(e,t,i){let n;n=void 0!==t?p.encodeUri("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?p.encodeUri("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys";return{path:n,queryData:void 0===i?void 0:{version:i}}}sendKeyBackup(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,i);yield this.http.authedRequest(I.Method.Put,r.path,r.queryData,n,{prefix:I.ClientPrefix.V3})}))}scheduleAllGroupSessionsForBackup(){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.backupManager.scheduleAllGroupSessionsForBackup()}))}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return(0,M.decodeRecoveryKey)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return(0,k.keyFromAuthData)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return(0,M.decodeRecoveryKey)(e)}restoreKeyBackupWithPassword(e,t,i,n,r){return s(this,void 0,void 0,(function*(){const o=yield(0,k.keyFromAuthData)(n.auth_data,e);return this.restoreKeyBackup(o,t,i,n,r)}))}restoreKeyBackupWithSecretStorage(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=yield this.getSecret("m.megolm_backup.v1"),o=(0,R.fixBackupKey)(r);if(o){const e=yield this.crypto.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",o,[e[0]])}const s=(0,S.decodeBase64)(o||r);return this.restoreKeyBackup(s,t,i,e,n)}))}restoreKeyBackupWithRecoveryKey(e,t,i,n,r){const o=(0,M.decodeRecoveryKey)(e);return this.restoreKeyBackup(o,t,i,n,r)}restoreKeyBackupWithCache(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=yield this.crypto.getSessionBackupPrivateKey();if(!r)throw new Error("Couldn't get key");return this.restoreKeyBackup(r,e,t,i,n)}))}restoreKeyBackup(e,t,i,n,r){return s(this,void 0,void 0,(function*(){const o=null==r?void 0:r.cacheCompleteCallback,a=null==r?void 0:r.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let c=0,d=[];const l=this.makeKeyBackupPath(t,i,n.version),u=yield K.BackupManager.makeAlgorithm(n,(()=>s(this,void 0,void 0,(function*(){return e})))),h=u.untrusted;try{if(!(yield u.keyMatches(e)))return Promise.reject(new I.MatrixError({errcode:de.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{w.logger.warn("Error caching session backup key:",e)})).then(o),a&&a({stage:"fetch"});const n=yield this.http.authedRequest(I.Method.Get,l.path,l.queryData,void 0,{prefix:I.ClientPrefix.V3});if(n.rooms){const e=n.rooms;for(const[t,i]of Object.entries(e)){if(!i.sessions)continue;c+=Object.keys(i.sessions).length;const e=yield u.decryptSessions(i.sessions);for(const i of e)i.room_id=t,d.push(i)}}else if(n.sessions){const e=n.sessions;c=Object.keys(e).length,d=yield u.decryptSessions(e);for(const e of d)e.room_id=t}else{c=1;try{const[e]=yield u.decryptSessions({[i]:n});e.room_id=t,e.session_id=i,d.push(e)}catch(e){w.logger.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return yield this.importRoomKeys(d,{progressCallback:a,untrusted:h,source:"backup"}),yield this.checkKeyBackup(),{total:c,imported:d.length}}))}deleteKeysFromBackup(e,t,i){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.makeKeyBackupPath(e,t,i);yield this.http.authedRequest(I.Method.Delete,n.path,n.queryData,void 0,{prefix:I.ClientPrefix.V3})}))}sendSharedHistoryKeys(e,t){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=this.roomList.getRoomEncryption(e);if(!i)return void w.logger.error("Unknown room. Not sharing decryption keys");const n=yield this.crypto.downloadKeys(t),r=new Map;for(const[e,t]of n)r.set(e,Array.from(t.values()));const o=this.crypto.getRoomDecryptor(e,i.algorithm);o.sendSharedHistoryInboundSessions?yield o.sendSharedHistoryInboundSessions(r):w.logger.warn("Algorithm does not support sharing previous keys",i.algorithm)}))}getMediaConfig(){return this.http.authedRequest(I.Method.Get,"/config",void 0,void 0,{prefix:I.MediaPrefix.R0})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(e=!1){var t;const i=this.store.getRooms(),n=new Set;for(const r of i){const i=null===(t=r.findPredecessor(e))||void 0===t?void 0:t.roomId;i&&n.add(i)}return i.filter((e=>!e.currentState.getStateEvents(B.EventType.RoomTombstone,"")||!n.has(e.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return(0,I.retryNetworkOperation)(5,(()=>this.http.authedRequest(I.Method.Put,i,void 0,t)))}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t;return s(this,void 0,void 0,(function*(){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return yield this.http.authedRequest(I.Method.Get,i)}catch(e){if("M_NOT_FOUND"===(null===(t=e.data)||void 0===t?void 0:t.errcode))return null;throw e}}))}deleteAccountData(e){return s(this,void 0,void 0,(function*(){const t=this.canSupport.get(ie.Feature.AccountDataDeletion);if(t===ie.ServerSupport.Unsupported)return void(yield this.setAccountData(e,{}));const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),n=t===ie.ServerSupport.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield this.http.authedRequest(I.Method.Delete,i,void 0,void 0,n)}))}getIgnoredUsers(){const e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach((e=>{t.ignored_users[e]={}})),this.setAccountData("m.ignored_user_list",t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e,t={}){return s(this,void 0,void 0,(function*(){void 0===t.syncRoom&&(t.syncRoom=!0);const i=this.getRoom(e);if(null==i?void 0:i.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(i);let n=Promise.resolve();if(t.inviteSignUrl){const e=new URL(t.inviteSignUrl);e.searchParams.set("mxid",this.credentials.userId),n=this.http.requestOtherUrl(I.Method.Post,e)}const r={};t.viaServers&&(r.server_name=t.viaServers);try{const i={},o=yield n;o&&(i.third_party_signed=o);const s=p.encodeUri("/join/$roomid",{$roomid:e}),a=(yield this.http.authedRequest(I.Method.Post,s,r,i)).room_id,d=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(a);return t.syncRoom,d}catch(e){throw e}}))}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,d.EventStatus.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![d.EventStatus.QUEUED,d.EventStatus.NOT_SENT,d.EventStatus.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===d.EventStatus.ENCRYPTING?this.pendingEventEncryption.delete(e.getId()):this.scheduler&&e.status===d.EventStatus.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,d.EventStatus.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,B.EventType.RoomName,{name:t})}setRoomTopic(e,t,i){const n=x.makeTopicContent(t,i);return this.sendStateEvent(e,B.EventType.RoomTopic,n)}getRoomTags(e){const t=p.encodeUri("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(I.Method.Get,t)}setRoomTag(e,t,i){const n=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.Method.Put,n,void 0,i)}deleteRoomTag(e,t){const i=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.Method.Delete,i)}setRoomAccountData(e,t,i){const n=p.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(I.Method.Put,n,void 0,i)}setPowerLevel(e,t,i,n){let r={users:{}};(null==n?void 0:n.getType())===B.EventType.RoomPowerLevels&&(r=p.deepCopy(n.getContent()));const o=Array.isArray(t)?t:[t];for(const e of o)null==i?delete r.users[e]:r.users[e]=i;const s=p.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(I.Method.Put,s,void 0,r)}unstable_createLiveBeacon(e,t){return s(this,void 0,void 0,(function*(){return this.unstable_setLiveBeacon(e,t)}))}unstable_setLiveBeacon(e,t){return s(this,void 0,void 0,(function*(){return this.sendStateEvent(e,X.M_BEACON_INFO.name,t,this.getUserId())}))}sendEvent(e,t,i,n,r){var o,s,a,c,d;let l,u,h,f;if((null==t?void 0:t.startsWith(se))||null===t?(f=r,h=n,u=i,l=t):(f=n,h=i,u=t,l=null),l&&!(null===(o=h["m.relates_to"])||void 0===o?void 0:o.rel_type)){const t=!!(null===(s=h["m.relates_to"])||void 0===s?void 0:s["m.in_reply_to"]);h["m.relates_to"]=Object.assign(Object.assign({},h["m.relates_to"]),{rel_type:Q.THREAD_RELATION_TYPE.name,event_id:l,is_falling_back:!t});const i=null===(a=this.getRoom(e))||void 0===a?void 0:a.getThread(l);i&&!t&&(h["m.relates_to"]["m.in_reply_to"]={event_id:null!==(d=null===(c=i.lastReply((e=>e.isRelation(Q.THREAD_RELATION_TYPE.name)&&!e.status)))||void 0===c?void 0:c.getId())&&void 0!==d?d:l})}return this.sendCompleteEvent(e,l,{type:u,content:h},f)}sendCompleteEvent(e,t,i,n){n||(n=this.makeTxnId());const r=new d.MatrixEvent(Object.assign(i,{event_id:"~"+e+":"+n,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),o=this.getRoom(e),s=t?null==o?void 0:o.getThread(t):void 0;s&&r.setThread(s),this.reEmitter.reEmit(r,[d.MatrixEventEvent.Replaced,d.MatrixEventEvent.VisibilityChange]),null==o||o.reEmitter.reEmit(r,[d.MatrixEventEvent.BeforeRedaction]);const a=r.getAssociatedId();if(null==a?void 0:a.startsWith("~")){const e=null==o?void 0:o.getPendingEvents().find((e=>e.getId()===a));null==e||e.once(d.MatrixEventEvent.LocalEventIdReplaced,(()=>{r.updateAssociatedId(e.getId())}))}const c=r.getType();return w.logger.log(`sendEvent of type ${c} in ${e} with txnId ${n}`),r.setTxnId(n),r.setStatus(d.EventStatus.SENDING),null==o||o.addPendingEvent(r,n),r.status===d.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(o,r)}encryptAndSendEvent(e,t){let i=!1;return Promise.resolve().then((()=>{const n=this.encryptEventIfNeeded(t,null!=e?e:void 0);return n?(this.pendingEventEncryption.set(t.getId(),n),this.updatePendingEventStatus(e,t,d.EventStatus.ENCRYPTING),n.then((()=>{this.pendingEventEncryption.has(t.getId())?this.updatePendingEventStatus(e,t,d.EventStatus.SENDING):i=!0}))):null})).then((()=>{if(i)return{};let n=null;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,d.EventStatus.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then((i=>(e.updatePendingEvent(t,d.EventStatus.SENT,i.event_id),i))))),n})).catch((i=>{w.logger.error("Error sending event",i.stack||i);try{t.error=i,this.updatePendingEventStatus(e,t,d.EventStatus.NOT_SENT)}catch(e){w.logger.error("Exception in error handler!",e.stack||i)}throw i instanceof I.MatrixError&&(i.event=t),i}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(e.isRedaction())return null;if(!t||!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.cryptoBackend&&this.usingExternalCrypto)return null;if(e.getType()===B.EventType.Reaction)return null;if(!this.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.cryptoBackend.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===B.EventType.Reaction?t:this.isRoomEncrypted(e)?B.EventType.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,i){e?e.updatePendingEvent(t,i):t.setStatus(i)}sendEventHttpRequest(e){let t=e.getTxnId();t||(t=this.makeTxnId(),e.setTxnId(t));const i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:t};let n;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),n=p.encodeUri(t,i)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";n=p.encodeUri(t,Object.assign({$redactsEventId:e.event.redacts},i))}else n=p.encodeUri("/rooms/$roomId/send/$eventType/$txnId",i);return this.http.authedRequest(I.Method.Put,n,void 0,e.getWireContent()).then((t=>(w.logger.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,i,n,r){(null==i?void 0:i.startsWith(se))||(r=n,n=i,i=t,t=null);const o=null==r?void 0:r.reason;if((null==r?void 0:r.with_relations)&&this.canSupport.get(ie.Feature.RelationBasedRedactions)===ie.ServerSupport.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${i} txnId: ${n} threadId ${t}`);const s=(null==r?void 0:r.with_relations)?{[this.canSupport.get(ie.Feature.RelationBasedRedactions)===ie.ServerSupport.Stable?B.MSC3912_RELATION_BASED_REDACTIONS_PROP.stable:B.MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable]:null==r?void 0:r.with_relations}:{};return this.sendCompleteEvent(e,t,{type:B.EventType.RoomRedaction,content:Object.assign(Object.assign({},s),{reason:o}),redacts:i},n)}sendMessage(e,t,i,n){"string"!=typeof t&&null!==t&&(n=i,i=t,t=null);const r=B.EventType.RoomMessage,o=i;return this.sendEvent(e,t,r,o,n)}sendTextMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeTextMessage(i);return this.sendMessage(e,t,r,n)}sendNotice(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeNotice(i);return this.sendMessage(e,t,r,n)}sendEmoteMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeEmoteMessage(i);return this.sendMessage(e,t,r,n)}sendImageMessage(e,t,i,n,r="Image"){(null==t?void 0:t.startsWith(se))||null===t||(r=n||"Image",n=i,i=t,t=null);const o={msgtype:B.MsgType.Image,url:i,info:n,body:r};return this.sendMessage(e,t,o)}sendStickerMessage(e,t,i,n,r="Sticker"){(null==t?void 0:t.startsWith(se))||null===t||(r=n||"Sticker",n=i,i=t,t=null);const o={url:i,info:n,body:r};return this.sendEvent(e,t,B.EventType.Sticker,o)}sendHtmlMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlMessage(i,n);return this.sendMessage(e,t,r)}sendHtmlNotice(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlNotice(i,n);return this.sendMessage(e,t,r)}sendHtmlEmote(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlEmote(i,n);return this.sendMessage(e,t,r)}sendReceipt(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){if(this.isGuest())return Promise.resolve({});const r=p.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()});if(!n){const t=!!e.threadRootId;i=Object.assign(Object.assign({},i),{thread_id:t?e.threadRootId:Y.MAIN_ROOM_TIMELINE})}const o=this.http.authedRequest(I.Method.Post,r,void 0,i||{}),s=this.getRoom(e.getRoomId());return s&&this.credentials.userId&&s.addLocalEchoReceipt(this.credentials.userId,e,t),o}))}sendReadReceipt(e,t=Y.ReceiptType.Read,i=!1){return s(this,void 0,void 0,(function*(){if(!e)return;const n=e.getId(),r=this.getRoom(e.getRoomId());if(null==r?void 0:r.hasPendingEvent(n))throw new Error(`Cannot set read receipt to a pending event (${n})`);return this.sendReceipt(e,t,{},i)}))}setRoomReadMarkers(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=this.getRoom(e);if(r&&r.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let o,s;if(i){if(o=i.getId(),null==r?void 0:r.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);null==r||r.addLocalEchoReceipt(this.credentials.userId,i,Y.ReceiptType.Read)}if(n){if(s=n.getId(),null==r?void 0:r.hasPendingEvent(s))throw new Error(`Cannot set read receipt to a pending event (${s})`);null==r||r.addLocalEchoReceipt(this.credentials.userId,n,Y.ReceiptType.ReadPrivate)}return yield this.setRoomReadMarkersHttpRequest(e,t,o,s)}))}getUrlPreview(e,t){t=6e4*Math.floor(t/6e4);const i=new URL(e);i.hash="";const n=t+"_"+(e=i.toString()),r=this.urlPreviewCache[n];if(r)return r;const o=this.http.authedRequest(I.Method.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:I.MediaPrefix.R0});return this.urlPreviewCache[n]=o,o}sendTyping(e,t,i){if(this.isGuest())return Promise.resolve({});const n=p.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),r={typing:t};return t&&(r.timeout=i||2e4),this.http.authedRequest(I.Method.Put,n,void 0,r)}getRoomUpgradeHistory(e,t=!1,i=!1){const n=this.getRoom(e);if(!n)return[];return[...this.findPredecessorRooms(n,t,i),n,...this.findSuccessorRooms(n,t,i)]}findPredecessorRooms(e,t,i){var n,r;const o=[];let s=null===(n=e.findPredecessor(i))||void 0===n?void 0:n.roomId;for(;null!==s;){const n=this.getRoom(s);if(null===n)break;if(t){const t=n.currentState.getStateEvents(B.EventType.RoomTombstone,"");if(!t||t.getContent().replacement_room!==e.roomId)break}o.splice(0,0,n),s=null===(r=(e=n).findPredecessor(i))||void 0===r?void 0:r.roomId}return o}findSuccessorRooms(e,t,i){var n;const r=[];let o=e.currentState.getStateEvents(B.EventType.RoomTombstone,"");for(;o;){const s=this.getRoom(o.getContent().replacement_room);if(!s)break;if(s.roomId===e.roomId)break;if(t){const t=null===(n=s.findPredecessor(i))||void 0===n?void 0:n.roomId;if(!t||t!==e.roomId)break}r.push(s);if(new Set(r.map((e=>e.roomId))).size<r.length)return r.slice(0,r.length-1);o=(e=s).currentState.getStateEvents(B.EventType.RoomTombstone,"")}return r}invite(e,t,i){return this.membershipChange(e,t,"invite",i)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}inviteByThreePid(e,t,i){var n;return s(this,void 0,void 0,(function*(){const r=p.encodeUri("/rooms/$roomId/invite",{$roomId:e}),o=this.getIdentityServerUrl(!0);if(!o)return Promise.reject(new I.MatrixError({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const s={id_server:o,medium:t,address:i};if((null===(n=this.identityServer)||void 0===n?void 0:n.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(s.id_access_token=e)}return this.http.authedRequest(I.Method.Post,r,void 0,s)}))}leave(e){return this.membershipChange(e,void 0,"leave")}leaveRoomChain(e,t=!0){const i=this.getRoomUpgradeHistory(e);let n=i;if(!t){n=[];for(const t of i)if(n.push(t),t.roomId===e)break}const r={},o=[],s=e=>this.leave(e).then((()=>{delete r[e]})).catch((t=>{r[e]=t}));for(const e of n)o.push(s(e.roomId));return Promise.all(o).then((()=>r))}ban(e,t,i){return this.membershipChange(e,t,"ban",i)}forget(e,t=!0){const i=this.membershipChange(e,void 0,"forget");return t?i.then((t=>(this.store.removeRoom(e),this.emit(ae.DeleteRoom,e),t))):i}unban(e,t){const i=p.encodeUri("/rooms/$roomId/unban",{$roomId:e}),n={user_id:t};return this.http.authedRequest(I.Method.Post,i,void 0,n)}kick(e,t,i){const n=p.encodeUri("/rooms/$roomId/kick",{$roomId:e}),r={user_id:t,reason:i};return this.http.authedRequest(I.Method.Post,n,void 0,r)}membershipChange(e,t,i,n){const r=p.encodeUri("/rooms/$room_id/$membership",{$room_id:e,$membership:i});return this.http.authedRequest(I.Method.Post,r,void 0,{user_id:t,reason:n})}getPushActionsForEvent(e,t=!1){return e.getPushActions()&&!t||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t){const i=p.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(I.Method.Put,i,void 0,t)}setDisplayName(e){return s(this,void 0,void 0,(function*(){const t=yield this.setProfileInfo("displayname",{displayname:e}),i=this.getUser(this.getUserId());return i&&(i.displayName=e,i.emit(C.UserEvent.DisplayName,i.events.presence,i)),t}))}setAvatarUrl(e){return s(this,void 0,void 0,(function*(){const t=yield this.setProfileInfo("avatar_url",{avatar_url:e}),i=this.getUser(this.getUserId());return i&&(i.avatarUrl=e,i.emit(C.UserEvent.AvatarUrl,i.events.presence,i)),t}))}mxcUrlToHttp(e,t,i,n,r){return(0,O.getHttpUriForMxc)(this.baseUrl,e,t,i,n,r)}setPresence(e){return s(this,void 0,void 0,(function*(){const t=p.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);yield this.http.authedRequest(I.Method.Put,t,void 0,e)}))}getPresence(e){const t=p.encodeUri("/presence/$userId/status",{$userId:e});return this.http.authedRequest(I.Method.Get,t)}scrollback(e,t=30){let i=0,n=this.ongoingScrollbacks[e.roomId]||{};if(n.promise)return n.promise;if(n.errorTs){const e=Date.now()-n.errorTs;i=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const r=this.store.scrollback(e,t).length;if(r===t)return Promise.resolve(e);t-=r;const o=new Promise(((n,r)=>{(0,g.sleep)(i).then((()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,v.Direction.Backward))).then((t=>{var i,r;const o=t.chunk.map(this.getEventMapper());if(t.state){const i=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(i)}const[s,a]=e.partitionThreadedEvents(o);this.processAggregatedTimelineEvents(e,s),e.addEventsToTimeline(s,!0,e.getLiveTimeline()),this.processThreadEvents(e,a,!0),e.oldState.paginationToken=null!==(i=t.end)&&void 0!==i?i:null,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,o,null!==(r=t.end)&&void 0!==r?r:null,!0),delete this.ongoingScrollbacks[e.roomId],n(e)})).catch((t=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},r(t)}))}));return n={promise:o},this.ongoingScrollbacks[e.roomId]=n,o}getEventMapper(e){return(0,j.eventMapperFor)(this,e||{})}getEventTimeline(e,t){var i,n,r,o;return s(this,void 0,void 0,(function*(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(null==e?void 0:e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&this.supportsThreads())return this.getThreadTimeline(e,t);const s=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let a;(null===(i=this.clientOpts)||void 0===i?void 0:i.lazyLoadMembers)&&(a={filter:JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER)});const c=yield this.http.authedRequest(I.Method.Get,s,a);if(!c.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const d=this.getEventMapper(),l=d(c.event);if(l.isRelation(Q.THREAD_RELATION_TYPE.name))return void w.logger.warn("Tried loading a regular timeline at the position of a thread event");const u=[...c.events_after.reverse().map(d),l,...c.events_before.map(d)];let f=e.getTimelineForEvent(u[0].getId());f?f.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(c.state.map(d)):(f=e.addTimeline(),f.initialiseState(c.state.map(d)),f.getState(v.EventTimeline.FORWARDS).paginationToken=c.end);const[g,m]=e.room.partitionThreadedEvents(u);return e.addEventsToTimeline(g,!0,f,c.start),this.processThreadEvents(e.room,m,!0),this.processAggregatedTimelineEvents(e.room,g),null!==(o=null!==(n=e.getTimelineForEvent(t))&&void 0!==n?n:null===(r=e.room.findThreadForEvent(l))||void 0===r?void 0:r.liveTimeline)&&void 0!==o?o:f}))}getThreadTimeline(e,t){var i,n,r,o,a,c,d,l;return s(this,void 0,void 0,(function*(){if(!this.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const s=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),u={limit:"0"};(null===(i=this.clientOpts)||void 0===i?void 0:i.lazyLoadMembers)&&(u.filter=JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER));const f=yield this.http.authedRequest(I.Method.Get,s,u),g=this.getEventMapper(),m=g(f.event);if(e.canContain(m)&&Q.Thread.hasServerSideSupport){if(Q.Thread.hasServerSideFwdPaginationSupport){if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const i=e.thread,s=yield this.fetchRelations(e.room.roomId,i.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,from:f.start}),c=yield this.fetchRelations(e.room.roomId,i.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Forward,from:f.end}),d=[...c.chunk.reverse().map(g),m,...s.chunk.map(g)];for(const t of d)yield null===(n=e.thread)||void 0===n?void 0:n.processEvent(t);let l=e.getTimelineForEvent(m.getId());if(l?l.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(f.state.map(g)):(l=e.addTimeline(),l.initialiseState(f.state.map(g))),e.addEventsToTimeline(d,!0,l,c.next_batch),!s.next_batch){const t=yield this.fetchRoomEvent(e.room.roomId,i.id);e.addEventsToTimeline([g(t)],!0,l,null)}return l.setPaginationToken(null!==(r=s.next_batch)&&void 0!==r?r:null,v.Direction.Backward),l.setPaginationToken(null!==(o=c.next_batch)&&void 0!==o?o:null,v.Direction.Forward),this.processAggregatedTimelineEvents(e.room,d),null!==(a=e.getTimelineForEvent(t))&&void 0!==a?a:l}{const t=e.thread,i=yield this.fetchRelations(e.room.roomId,t.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,from:f.start}),n=[];let r=f.end;for(;r;){const i=yield this.fetchRelations(e.room.roomId,t.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Forward,from:r});r=null!==(c=i.next_batch)&&void 0!==c?c:null,n.push(...i.chunk)}const o=[...n.reverse().map(g),m,...i.chunk.map(g)];for(const t of o)yield null===(d=e.thread)||void 0===d?void 0:d.processEvent(t);const s=e.getLiveTimeline();if(s.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(f.state.map(g)),e.addEventsToTimeline(o,!0,s,null),!i.next_batch){const i=yield this.fetchRoomEvent(e.room.roomId,t.id);e.addEventsToTimeline([g(i)],!0,s,null)}return s.setPaginationToken(null!==(l=i.next_batch)&&void 0!==l?l:null,v.Direction.Backward),s.setPaginationToken(null,v.Direction.Forward),this.processAggregatedTimelineEvents(e.room,o),s}}}))}getLatestTimeline(e){var t,i,n,r;return s(this,void 0,void 0,(function*(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");let o;if(null!==e.threadListType){const i=yield this.createThreadListMessagesRequest(e.room.roomId,null,1,v.Direction.Backward,e.threadListType,e.getFilter());o=null===(t=i.chunk)||void 0===t?void 0:t[0]}else if(e.thread&&Q.Thread.hasServerSideSupport){const t=yield this.fetchRelations(e.room.roomId,e.thread.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,limit:1});o=null===(i=t.chunk)||void 0===i?void 0:i[0]}else{const t=p.encodeUri("/rooms/$roomId/messages",{$roomId:e.room.roomId}),i={dir:"b"};(null===(n=this.clientOpts)||void 0===n?void 0:n.lazyLoadMembers)&&(i.filter=JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER));const s=yield this.http.authedRequest(I.Method.Get,t,i);o=null===(r=s.chunk)||void 0===r?void 0:r[0]}if(!o)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,o.event_id)}))}createMessagesRequest(e,t,i=30,n,r){var o,s;const a=p.encodeUri("/rooms/$roomId/messages",{$roomId:e}),c={limit:i.toString(),dir:n};t&&(c.from=t);let d=null;return(null===(o=this.clientOpts)||void 0===o?void 0:o.lazyLoadMembers)&&(d=Object.assign({},h.Filter.LAZY_LOADING_MESSAGES_FILTER)),r&&(d=d||{},Object.assign(d,null===(s=r.getRoomTimelineFilterComponent())||void 0===s?void 0:s.toJSON())),d&&(c.filter=JSON.stringify(d)),this.http.authedRequest(I.Method.Get,a,c)}createThreadListMessagesRequest(e,t,i=30,n=v.Direction.Backward,r=Q.ThreadFilterType.All,o){var s,a;const c=p.encodeUri("/rooms/$roomId/threads",{$roomId:e}),d={limit:i.toString(),dir:n,include:(0,Q.threadFilterTypeToFilter)(r)};t&&(d.from=t);let l={};(null===(s=this.clientOpts)||void 0===s?void 0:s.lazyLoadMembers)&&(l=Object.assign({},h.Filter.LAZY_LOADING_MESSAGES_FILTER)),o&&(l=Object.assign(Object.assign({},l),null===(a=o.getRoomTimelineFilterComponent())||void 0===a?void 0:a.toJSON())),Object.keys(l).length&&(d.filter=JSON.stringify(l));const u={prefix:Q.Thread.hasServerSideListSupport===Q.FeatureSupport.Stable?"/_matrix/client/v1":"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(I.Method.Get,c,d,void 0,u).then((e=>{var t;return Object.assign(Object.assign({},e),{chunk:null===(t=e.chunk)||void 0===t?void 0:t.reverse(),start:e.prev_batch,end:e.next_batch})}))}paginateEventTimeline(e,t){var i,n,r;const o=e.getTimelineSet()===this.notifTimelineSet,a=this.getRoom(e.getRoomId()),c=e.getTimelineSet().threadListType,d=e.getTimelineSet().thread,l=(t=t||{}).backwards||!1;if(o&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");const u=l?v.EventTimeline.BACKWARDS:v.EventTimeline.FORWARDS,h=e.getPaginationToken(u),f=e.paginationRequests[u];if(f)return f;let p,y,b;if(o)p="/notifications",y={limit:(null!==(i=t.limit)&&void 0!==i?i:30).toString(),only:"highlight"},h&&"end"!==h&&(y.from=h),b=this.http.authedRequest(I.Method.Get,"/notifications",y).then((t=>s(this,void 0,void 0,(function*(){const i=t.next_token,n=[];t.notifications=t.notifications.filter(g.noUnsafeEventProps);for(let e=0;e<t.notifications.length;e++){const i=t.notifications[e],r=this.getEventMapper()(i.event);r.setPushActions(m.PushProcessor.actionListToActionsObject(i.actions)),r.event.room_id=i.room_id,n[e]=r}const r=e.getTimelineSet();return r.addEventsToTimeline(n,l,e,i),this.processAggregatedTimelineEvents(r.room,n),l&&!t.next_token&&e.setPaginationToken(null,u),Boolean(t.next_token)})))).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b;else if(null!==c){if(!a)throw new Error("Unknown room "+e.getRoomId());if(!Q.Thread.hasServerSideFwdPaginationSupport&&u===v.Direction.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");b=this.createThreadListMessagesRequest(e.getRoomId(),h,t.limit,u,c,e.getFilter()).then((t=>{if(t.state){const i=e.getState(u),n=t.state.filter(g.noUnsafeEventProps).map(this.getEventMapper());i.setUnknownStateEvents(n)}const i=t.end,n=t.chunk.filter(g.noUnsafeEventProps).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(n,l,e,i),this.processAggregatedTimelineEvents(a,n),this.processThreadRoots(a,n,l),l&&t.end==t.start&&e.setPaginationToken(null,u),t.end!==t.start})).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}else if(d){const i=this.getRoom(null!==(n=e.getRoomId())&&void 0!==n?n:void 0);if(!i)throw new Error("Unknown room "+e.getRoomId());b=this.fetchRelations(null!==(r=e.getRoomId())&&void 0!==r?r:"",d.id,Q.THREAD_RELATION_TYPE.name,null,{dir:u,limit:t.limit,from:null!=h?h:void 0}).then((t=>s(this,void 0,void 0,(function*(){var n;const r=this.getEventMapper(),o=t.chunk.filter(g.noUnsafeEventProps).map(r);for(const e of o.slice().reverse()){yield null==d?void 0:d.processEvent(e);const t=e.getSender();l&&null!==(null==d?void 0:d.getEventReadUpTo(t))||i.addLocalEchoReceipt(t,e,Y.ReceiptType.Read)}const s=t.next_batch,a=e.getTimelineSet();if(a.addEventsToTimeline(o,l,e,null!=s?s:null),!s&&l){const t=yield this.fetchRoomEvent(null!==(n=e.getRoomId())&&void 0!==n?n:"",d.id);a.addEventsToTimeline([r(t)],!0,e,null)}return this.processAggregatedTimelineEvents(a.room,o),l&&!s&&e.setPaginationToken(null,u),Boolean(s)})))).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}else{if(!a)throw new Error("Unknown room "+e.getRoomId());b=this.createMessagesRequest(e.getRoomId(),h,t.limit,u,e.getFilter()).then((t=>{if(t.state){const i=e.getState(u),n=t.state.filter(g.noUnsafeEventProps).map(this.getEventMapper());i.setUnknownStateEvents(n)}const i=t.end,n=t.chunk.filter(g.noUnsafeEventProps).map(this.getEventMapper()),r=e.getTimelineSet(),[o]=a.partitionThreadedEvents(n);r.addEventsToTimeline(o,l,e,i),this.processAggregatedTimelineEvents(a,o),this.processThreadRoots(a,o.filter((e=>e.getServerAggregatedRelation(Q.THREAD_RELATION_TYPE.name))),!1);const s=void 0===t.end||t.end===t.start;return l&&s&&e.setPaginationToken(null,u),!s})).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}return b}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t;return null===(t=this.peekSync)||void 0===t||t.stopPeeking(),this.peekSync=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const i=this.sendStateEvent(e,B.EventType.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let n=Promise.resolve(void 0);return t.allowRead&&(n=this.sendStateEvent(e,B.EventType.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([n,i]).then()}requestRegisterEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestRegisterMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestAdd3pidEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestAdd3pidMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestPasswordEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestPasswordMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestTokenFromEndpoint(e,t){var i;return s(this,void 0,void 0,(function*(){const n=Object.assign({},t);if(!(yield this.doesServerSupportSeparateAddAndBind())&&this.idBaseUrl){const e=new URL(this.idBaseUrl);if(n.id_server=e.host,(null===(i=this.identityServer)||void 0===i?void 0:i.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(I.Method.Post,e,void 0,n)}))}getRoomPushRule(e,t){var i,n;if(this.pushRules)return null===(n=null===(i=this.pushRules[e])||void 0===i?void 0:i.room)||void 0===n?void 0:n.find((e=>e.rule_id===t));throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,i){let n,r=!1;const o=this.getRoomPushRule(e,t);if((null==o?void 0:o.actions.includes(V.PushRuleActionName.DontNotify))&&(r=!0),i)if(o){if(!r){const i=p.defer();this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id).then((()=>{this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[V.PushRuleActionName.DontNotify]}).then((()=>{i.resolve()})).catch((e=>{i.reject(e)}))})).catch((e=>{i.reject(e)})),n=i.promise}}else n=this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[V.PushRuleActionName.DontNotify]});else r&&(n=this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id));if(n)return new Promise(((e,t)=>{n.then((()=>{this.getPushRules().then((t=>{this.pushRules=t,e()})).catch((e=>{t(e)}))})).catch((e=>{this.getPushRules().then((i=>{this.pushRules=i,t(e)})).catch((i=>{t(e)}))}))}))}searchMessageText(e){const t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:$.SearchOrderBy.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},i={_query:t,results:[],highlights:[]};return this.search({body:t}).then((e=>this.processRoomEventsSearch(i,e)))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},i=this.search(t,e.abortSignal).then((t=>this.processRoomEventsSearch(e,t))).finally((()=>{e.pendingRequest=void 0}));return e.pendingRequest=i,i}processRoomEventsSearch(e,t){var i,n;const r=t.search_categories.room_events;e.count=r.count,e.next_batch=r.next_batch;const o=new Set(r.highlights);e.highlights.forEach((e=>{o.add(e)})),e.highlights=Array.from(o);const s=this.getEventMapper(),a=null!==(n=null===(i=r.results)||void 0===i?void 0:i.length)&&void 0!==n?n:0;for(let t=0;t<a;t++){const i=A.SearchResult.fromJson(r.results[t],s),n=this.getRoom(i.context.getEvent().getRoomId());if(n)for(const e of i.context.getTimeline()){const t=n.getMember(e.getSender());!e.sender&&t&&(e.sender=t)}e.results.push(i)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions());return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then((()=>{w.logger.log("Marking success of sync left room request"),this.syncedLeftRooms=!0})).finally((()=>{this.syncLeftRoomsPromise=void 0})),this.syncLeftRoomsPromise}createFilter(e){const t=p.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(I.Method.Post,t,void 0,e).then((t=>{const i=h.Filter.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(i),i}))}getFilter(e,t,i){if(i){const i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}const n=p.encodeUri("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(I.Method.Get,n).then((i=>{const n=h.Filter.fromJson(e,t,i);return this.store.storeFilter(n),n}))}getOrCreateFilter(e,t){return s(this,void 0,void 0,(function*(){const i=this.store.getFilterIdByName(e);let n;if(i){try{const e=yield this.getFilter(this.credentials.userId,i,!0);if(e){const r=e.getDefinition(),o=t.getDefinition();p.deepCompare(r,o)&&(n=i)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}n||this.store.setFilterIdByName(e,void 0)}if(n)return n;const r=yield this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,r.filterId),r.filterId}))}getOpenIdToken(){const e=p.encodeUri("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(I.Method.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(I.Method.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return void 0!==this.checkTurnServersIntervalID}checkTurnServers(){return s(this,void 0,void 0,(function*(){if(!this.canSupportVoip)return;let e=!1;const i=this.turnServersExpiry-Date.now();if(i>re)w.logger.debug("TURN creds are valid for another "+i+" ms: not fetching new ones."),e=!0;else{w.logger.debug("Fetching new TURN credentials");try{const t=yield this.turnServer();if(t.uris){w.logger.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const i={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[i],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0,this.emit(ae.TurnServers,this.turnServers)}}catch(e){w.logger.error("Failed to get TURN URIs",e),403===e.httpStatus?(w.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit(ae.TurnServersError,e,!0)):this.emit(ae.TurnServersError,e,!1)}}return e}))}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=p.encodeUri("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(I.Method.Get,e,void 0,void 0,{prefix:""}).then((e=>e.admin))}whoisSynapseUser(e){const t=p.encodeUri("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(I.Method.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=p.encodeUri("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(I.Method.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e;return s(this,void 0,void 0,(function*(){this.clientWellKnownPromise=y.AutoDiscovery.getRawClientConfig(null!==(e=this.getDomain())&&void 0!==e?e:void 0),this.clientWellKnown=yield this.clientWellKnownPromise,this.emit(ae.ClientWellKnown,this.clientWellKnown)}))}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter((([t,i])=>e.includes(typeof i))).reduce(((e,[t,i])=>(e[t]=i,e)),{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){return s(this,void 0,void 0,(function*(){const t=yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),i=yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!t&&!i)throw Error("Server does not support mutual_rooms API");const n=p.encodeUri(`/uk.half-shot.msc2666/user/${i?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e});return(yield this.http.authedRequest(I.Method.Get,n,void 0,void 0,{prefix:I.ClientPrefix.Unstable})).joined}))}getVersions(){return s(this,void 0,void 0,(function*(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.request(I.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch((e=>{throw this.serverVersionsPromise=void 0,e}));const e=yield this.serverVersionsPromise;return this.canSupport=yield(0,ie.buildFeatureSupportMap)(e),this.serverVersionsPromise}))}isVersionSupported(e){return s(this,void 0,void 0,(function*(){const{versions:t}=yield this.getVersions();return t&&t.includes(e)}))}doesServerSupportLazyLoading(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return t&&t.includes("r0.5.0")||i&&i["m.lazy_load_members"]}))}doesServerRequireIdServerParam(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!0;const t=e.versions;if(t&&t.includes("r0.6.0"))return!1;const i=e.unstable_features;return!i||(void 0===i["m.require_identity_server"]||i["m.require_identity_server"])}))}doesServerAcceptIdentityAccessToken(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return t&&t.includes("r0.6.0")||i&&i["m.id_access_token"]}))}doesServerSupportSeparateAddAndBind(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return(null==t?void 0:t.includes("r0.6.0"))||(null==i?void 0:i["m.separate_add_and_bind"])}))}doesServerSupportUnstableFeature(e){return s(this,void 0,void 0,(function*(){const t=yield this.getVersions();if(!t)return!1;const i=t.unstable_features;return i&&!!i[e]}))}doesServerForceEncryptionForPreset(e){return s(this,void 0,void 0,(function*(){const t=yield this.getVersions();if(!t)return!1;const i=t.unstable_features,n=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i[`io.element.e2ee_forced.${n}`]}))}doesServerSupportThread(){return s(this,void 0,void 0,(function*(){if(yield this.isVersionSupported("v1.4"))return{threads:Q.FeatureSupport.Stable,list:Q.FeatureSupport.Stable,fwdPagination:Q.FeatureSupport.Stable};try{const[e,t,i,n,r,o]=yield Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:(0,Q.determineFeatureSupport)(t,e),list:(0,Q.determineFeatureSupport)(n,i),fwdPagination:(0,Q.determineFeatureSupport)(o,r)}}catch(e){return{threads:Q.FeatureSupport.None,list:Q.FeatureSupport.None,fwdPagination:Q.FeatureSupport.None}}}))}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){var e;return!!(null===(e=this.clientOpts)||void 0===e?void 0:e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,i,n,r={dir:v.Direction.Backward}){var o,a;return s(this,void 0,void 0,(function*(){const s=n?this.getEncryptedIfNeededEventType(e,n):null,[c,d]=yield Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,i,s,r)]),l=this.getEventMapper(),u=c?l(c):void 0;let h=d.chunk.map(l);if(s===B.EventType.RoomMessageEncrypted){const e=u?h.concat(u):h;yield Promise.all(e.map((e=>this.decryptEventIfNeeded(e)))),null!==n&&(h=h.filter((e=>e.getType()===n)))}return u&&i===B.RelationType.Replace&&(h=h.filter((e=>e.getSender()===u.getSender()))),{originalEvent:null!=u?u:null,events:h,nextBatch:null!==(o=d.next_batch)&&void 0!==o?o:null,prevBatch:null!==(a=d.prev_batch)&&void 0!==a?a:null}}))}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,F.randomString)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.isCryptoEnabled()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case T.SERVICE_TYPES.IS:return this.http.getUrl("/terms",void 0,I.IdentityPrefix.V2,t);case T.SERVICE_TYPES.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){var t,i;return e&&((null===(t=this.idBaseUrl)||void 0===t?void 0:t.startsWith("http://"))||(null===(i=this.idBaseUrl)||void 0===i?void 0:i.startsWith("https://")))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=p.ensureNoTrailingSlash(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}setAccessToken(e){this.http.opts.accessToken=e}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(I.Method.Get,"/register/available",{username:e}).then((e=>e.available)).catch((e=>"M_USER_IN_USE"!==e.errcode&&Promise.reject(e)))}register(e,t,i,n,r,o,s){!0===r?r={email:!0}:null!=r&&!1!==r||(r={}),i&&(n.session=i);const a={auth:n,refresh_token:!0};return null!=e&&(a.username=e),null!=t&&(a.password=t),r.email&&(a.bind_email=!0),r.msisdn&&(a.bind_msisdn=!0),null!=o&&(a.guest_access_token=o),null!=s&&(a.inhibit_login=s),null!=t&&(a.x_show_msisdn=!0),this.registerRequest(a)}registerGuest({body:e}={}){return this.registerRequest(e||{},"guest")}registerRequest(e,t){const i={};return t&&(i.kind=t),this.http.request(I.Method.Post,"/register",i,e)}refreshToken(e){return this.http.authedRequest(I.Method.Post,"/refresh",void 0,{refresh_token:e},{prefix:I.ClientPrefix.V1,inhibitLogoutEmit:!0})}loginFlows(){return this.http.request(I.Method.Get,"/login")}login(e,t){const i={type:e};return Object.assign(i,t),this.http.authedRequest(I.Method.Post,"/login",void 0,i).then((e=>(e.access_token&&e.user_id&&(this.http.opts.accessToken=e.access_token,this.credentials={userId:e.user_id}),e)))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}loginWithSAML2(e){return this.login("m.login.saml2",{relay_state:e})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",i,n){let r="/login/"+t+"/redirect";i&&(r+="/"+i);const o={redirectUrl:e,[ce.unstable]:n};return this.http.getUrl(r,o,I.ClientPrefix.R0).href}loginWithToken(e){return this.login("m.login.token",{token:e})}logout(e=!1){var t,i;return s(this,void 0,void 0,(function*(){if(null===(i=null===(t=this.crypto)||void 0===t?void 0:t.backupManager)||void 0===i?void 0:i.getKeyBackupEnabled())try{for(;(yield this.crypto.backupManager.backupPendingKeys(200))>0;);}catch(e){w.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",e)}return e&&(this.stopClient(),this.http.abort()),this.http.authedRequest(I.Method.Post,"/logout")}))}deactivateAccount(e,t){const i={};return e&&(i.auth=e),void 0!==t&&(i.erase=t),this.http.authedRequest(I.Method.Post,"/account/deactivate",void 0,i)}requestLoginToken(e){const t={auth:e};return this.http.authedRequest(I.Method.Post,"/org.matrix.msc3882/login/token",void 0,t,{prefix:I.ClientPrefix.Unstable})}getFallbackAuthUrl(e,t){const i=p.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(i,{session:t},I.ClientPrefix.R0).href}createRoom(e){var t;return s(this,void 0,void 0,(function*(){const i=(e.invite_3pid||[]).filter((e=>!e.id_access_token));if(i.length>0&&(null===(t=this.identityServer)||void 0===t?void 0:t.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();if(e)for(const t of i)t.id_access_token=e}return this.http.authedRequest(I.Method.Post,"/createRoom",void 0,e)}))}fetchRelations(e,t,i,n,r={dir:v.Direction.Backward}){let o=r;Q.Thread.hasServerSideFwdPaginationSupport===Q.FeatureSupport.Experimental&&(o=(0,g.replaceParam)("dir","org.matrix.msc3715.dir",o));const s=p.encodeParams(o);let a="/rooms/$roomId/relations/$eventId";null!==i?(a+="/$relationType",null!==n&&(a+="/$eventType")):null!==n&&(w.logger.warn(`eventType: ${n} ignored when fetching\n relations as relationType is null`),n=null);const c=p.encodeUri(a+"?"+s,{$roomId:e,$eventId:t,$relationType:i,$eventType:n});return this.http.authedRequest(I.Method.Get,c,void 0,void 0,{prefix:I.ClientPrefix.V1})}roomState(e){const t=p.encodeUri("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}fetchRoomEvent(e,t){const i=p.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.Method.Get,i)}members(e,t,i,n){const r={};t&&(r.membership=t),i&&(r.not_membership=i),n&&(r.at=n);const o=p.encodeParams(r),s=p.encodeUri("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(I.Method.Get,s)}upgradeRoom(e,t){const i=p.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(I.Method.Post,i,void 0,{new_version:t})}getStateEvent(e,t,i){const n={$roomId:e,$eventType:t,$stateKey:i};let r=p.encodeUri("/rooms/$roomId/state/$eventType",n);return void 0!==i&&(r=p.encodeUri(r+"/$stateKey",n)),this.http.authedRequest(I.Method.Get,r)}sendStateEvent(e,t,i,n="",r={}){const o={$roomId:e,$eventType:t,$stateKey:n};let s=p.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(s=p.encodeUri(s+"/$stateKey",o)),this.http.authedRequest(I.Method.Put,s,void 0,i,r)}roomInitialSync(e,t){var i;const n=p.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(I.Method.Get,n,{limit:null!==(i=null==t?void 0:t.toString())&&void 0!==i?i:"30"})}setRoomReadMarkersHttpRequest(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=p.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),o={[Y.ReceiptType.FullyRead]:t,[Y.ReceiptType.Read]:i};return((yield this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield this.isVersionSupported("v1.4")))&&(o[Y.ReceiptType.ReadPrivate]=n),this.http.authedRequest(I.Method.Post,r,void 0,o)}))}getJoinedRooms(){const e=p.encodeUri("/joined_rooms",{});return this.http.authedRequest(I.Method.Get,e)}getJoinedRoomMembers(e){const t=p.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}publicRooms(e={}){var{server:t,limit:i,since:n}=e,r=a(e,["server","limit","since"]);const o={server:t,limit:i,since:n};return 0===Object.keys(r).length?this.http.authedRequest(I.Method.Get,"/publicRooms",o):this.http.authedRequest(I.Method.Post,"/publicRooms",o,r)}createAlias(e,t){const i=p.encodeUri("/directory/room/$alias",{$alias:e}),n={room_id:t};return this.http.authedRequest(I.Method.Put,i,void 0,n)}deleteAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.Method.Delete,t)}getLocalAliases(e){const t=p.encodeUri("/rooms/$roomId/aliases",{$roomId:e}),i=I.ClientPrefix.V3;return this.http.authedRequest(I.Method.Get,t,void 0,void 0,{prefix:i})}getRoomIdForAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.Method.Get,t)}resolveRoomAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.request(I.Method.Get,t)}getRoomDirectoryVisibility(e){const t=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}setRoomDirectoryVisibility(e,t){const i=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.Method.Put,i,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,i){const n=p.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(I.Method.Put,n,void 0,{visibility:i})}searchUserDirectory({term:e,limit:t}){const i={search_term:e};return void 0!==t&&(i.limit=t),this.http.authedRequest(I.Method.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){const i=t?p.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):p.encodeUri("/profile/$userId",{$userId:e});return this.http.authedRequest(I.Method.Get,i)}getThreePids(){return this.http.authedRequest(I.Method.Get,"/account/3pid")}addThreePid(e,t){const i={threePidCreds:e,bind:t};return this.http.authedRequest(I.Method.Post,"/account/3pid",void 0,i)}addThreePidOnly(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/add",void 0,e,{prefix:t})}))}bindThreePid(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/bind",void 0,e,{prefix:t})}))}unbindThreePid(e,t){return s(this,void 0,void 0,(function*(){const i={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},n=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/unbind",void 0,i,{prefix:n})}))}deleteThreePid(e,t){return this.http.authedRequest(I.Method.Post,"/account/3pid/delete",void 0,{medium:e,address:t})}setPassword(e,t,i){const n={auth:e,new_password:t,logout_devices:i};return this.http.authedRequest(I.Method.Post,"/account/password",void 0,n)}getDevices(){return this.http.authedRequest(I.Method.Get,"/devices")}getDevice(e){const t=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.Method.Get,t)}setDeviceDetails(e,t){const i=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.Method.Put,i,void 0,t)}deleteDevice(e,t){const i=p.encodeUri("/devices/$device_id",{$device_id:e}),n={};return t&&(n.auth=t),this.http.authedRequest(I.Method.Delete,i,void 0,n)}deleteMultipleDevices(e,t){const i={devices:e};t&&(i.auth=t);return this.http.authedRequest(I.Method.Post,"/delete_devices",void 0,i)}getPushers(){return s(this,void 0,void 0,(function*(){const e=yield this.http.authedRequest(I.Method.Get,"/pushers");return(yield this.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(e.pushers=e.pushers.map((e=>(e.hasOwnProperty(B.PUSHER_ENABLED.name)||(e[B.PUSHER_ENABLED.name]=!0),e)))),e}))}setPusher(e){return this.http.authedRequest(I.Method.Post,"/pushers/set",void 0,e)}setLocalNotificationSettings(e,t){const i=`${B.LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${e}`;return this.setAccountData(i,t)}getPushRules(){return this.http.authedRequest(I.Method.Get,"/pushrules/").then((e=>(this.setPushRules(e),this.pushRules)))}setPushRules(e){this.pushRules=m.PushProcessor.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,n)}deletePushRule(e,t,i){const n=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Delete,n)}setPushRuleEnabled(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,{enabled:n})}setPushRuleActions(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,{actions:n})}search({body:e,next_batch:t},i){const n={};return t&&(n.next_batch=t),this.http.authedRequest(I.Method.Post,"/search",n,e,{abortSignal:i})}uploadKeysRequest(e,t){return this.http.authedRequest(I.Method.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(I.Method.Post,"/keys/signatures/upload",void 0,e,{prefix:I.ClientPrefix.V3})}downloadKeysForUsers(e,{token:t}={}){const i={device_keys:{}};return void 0!==t&&(i.token=t),e.forEach((e=>{i.device_keys[e]=[]})),this.http.authedRequest(I.Method.Post,"/keys/query",void 0,i)}claimOneTimeKeys(e,t="signed_curve25519",i){const n={};void 0===t&&(t="signed_curve25519");for(const[i,r]of e){const e=n[i]||{};n[i]=e,e[r]=t}const r={one_time_keys:n};i&&(r.timeout=i);return this.http.authedRequest(I.Method.Post,"/keys/claim",void 0,r)}getKeyChanges(e,t){const i={from:e,to:t};return this.http.authedRequest(I.Method.Get,"/keys/changes",i)}uploadDeviceSigningKeys(e,t){const i=Object.assign({},t);return e&&Object.assign(i,{auth:e}),this.http.authedRequest(I.Method.Post,"/keys/device_signing/upload",void 0,i,{prefix:I.ClientPrefix.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.http.getUrl("/account/register",void 0,I.IdentityPrefix.V2,this.idBaseUrl);return this.http.requestOtherUrl(I.Method.Post,t,e)}requestEmailToken(e,t,i,n,r){const o={client_secret:t,email:e,send_attempt:null==i?void 0:i.toString()};return n&&(o.next_link=n),this.http.idServerRequest(I.Method.Post,"/validate/email/requestToken",o,I.IdentityPrefix.V2,r)}requestMsisdnToken(e,t,i,n,r,o){const s={client_secret:i,country:e,phone_number:t,send_attempt:null==n?void 0:n.toString()};return r&&(s.next_link=r),this.http.idServerRequest(I.Method.Post,"/validate/msisdn/requestToken",s,I.IdentityPrefix.V2,o)}submitMsisdnToken(e,t,i,n){const r={sid:e,client_secret:t,token:i};return this.http.idServerRequest(I.Method.Post,"/validate/msisdn/submitToken",r,I.IdentityPrefix.V2,n)}submitMsisdnTokenOtherUrl(e,t,i,n){const r={sid:t,client_secret:i,token:n};return this.http.requestOtherUrl(I.Method.Post,e,r)}getIdentityHashDetails(e){return this.http.idServerRequest(I.Method.Get,"/hash_details",void 0,I.IdentityPrefix.V2,e)}identityHashedLookup(e,i){return s(this,void 0,void 0,(function*(){const n={},r=yield this.getIdentityHashDetails(i);if(!r||!r.lookup_pepper||!r.algorithms)throw new Error("Unsupported identity server: bad response");n.pepper=r.lookup_pepper;const o={};if(r.algorithms.includes("sha256")){const i=new t.Olm.Utility;n.addresses=e.map((e=>{const t=e[0].toLowerCase(),r=e[1].toLowerCase(),s=i.sha256(`${t} ${r} ${n.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return o[s]=e[0],s})),n.algorithm="sha256"}else{if(!r.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");n.addresses=e.map((e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return o[t]=e[0],t})),n.algorithm="none"}const s=yield this.http.idServerRequest(I.Method.Post,"/lookup",n,I.IdentityPrefix.V2,i);if(!(null==s?void 0:s.mappings))return[];const a=[];for(const e of Object.keys(s.mappings)){const t=s.mappings[e],i=o[e];if(!i)throw new Error("Identity server returned more results than expected");a.push({address:i,mxid:t})}return a}))}lookupThreePid(e,t,i){return s(this,void 0,void 0,(function*(){const n=(yield this.identityHashedLookup([[t,e]],i)).find((e=>e.address===t));if(!n)return{};return{address:t,medium:e,mxid:n.mxid}}))}bulkLookupThreePids(e,t){return s(this,void 0,void 0,(function*(){const i=yield this.identityHashedLookup(e.map((e=>[e[1],e[0]])),t),n=[];for(const t of i){const i=e.find((e=>e[1]===t.address));if(!i)throw new Error("Identity sever returned unexpected results");n.push([i[0],t.address,t.mxid])}return{threepids:n}}))}getIdentityAccount(e){return this.http.idServerRequest(I.Method.Get,"/account",void 0,I.IdentityPrefix.V2,e)}sendToDevice(e,t,i){const n=p.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:i||this.makeTxnId()}),r={messages:p.recursiveMapToObject(t)},o=new Map;for(const[e,i]of t)o.set(e,Array.from(i.keys()));return w.logger.log(`PUT ${n}`,o),this.http.authedRequest(I.Method.Put,n,void 0,r)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(I.Method.Get,"/thirdparty/protocols").then((e=>{if(!e||"object"!=typeof e)throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e}))}getThirdpartyLocation(e,t){const i=p.encodeUri("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(I.Method.Get,i,t)}getThirdpartyUser(e,t){const i=p.encodeUri("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(I.Method.Get,i,t)}getTerms(e,t){const i=this.termsUrlForService(e,t);return this.http.requestOtherUrl(I.Method.Get,i)}agreeToTerms(e,t,i,n){const r=this.termsUrlForService(e,t),o={Authorization:"Bearer "+i};return this.http.requestOtherUrl(I.Method.Post,r,{user_accepts:n},{headers:o})}reportEvent(e,t,i,n){const r=p.encodeUri("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.Method.Post,r,void 0,{score:i,reason:n})}getRoomHierarchy(e,t,i,n=!1,r){const o=p.encodeUri("/rooms/$roomId/hierarchy",{$roomId:e}),s={suggested_only:String(n),max_depth:null==i?void 0:i.toString(),from:r,limit:null==t?void 0:t.toString()};return this.http.authedRequest(I.Method.Get,o,s,void 0,{prefix:I.ClientPrefix.V1}).catch((e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(I.Method.Get,o,s,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw e}))}unstableCreateFileTree(e){return s(this,void 0,void 0,(function*(){const{room_id:t}=yield this.createRoom({name:e,preset:N.Preset.PrivateChat,power_level_content_override:Object.assign(Object.assign({},q.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{users:{[this.getUserId()]:100}}),creation_content:{[B.RoomCreateTypeField]:B.RoomType.Space},initial_state:[{type:B.UNSTABLE_MSC3088_PURPOSE.name,state_key:B.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[B.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:B.EventType.RoomEncryption,state_key:"",content:{algorithm:b.MEGOLM_ALGORITHM}}]});return new q.MSC3089TreeSpace(this,t)}))}unstableGetFileTreeSpace(e){var t,i;const n=this.getRoom(e);if("join"!==(null==n?void 0:n.getMyMembership()))return null;const r=n.currentState.getStateEvents(B.EventType.RoomCreate,""),o=n.currentState.getStateEvents(B.UNSTABLE_MSC3088_PURPOSE.name,B.UNSTABLE_MSC3089_TREE_SUBTYPE.name);if(!r)throw new Error("Expected single room create event");return(null===(t=null==o?void 0:o.getContent())||void 0===t?void 0:t[B.UNSTABLE_MSC3088_ENABLED.name])?(null===(i=r.getContent())||void 0===i?void 0:i[B.RoomCreateTypeField])!==B.RoomType.Space?null:new q.MSC3089TreeSpace(this,e):null}slidingSync(e,t,i){const n={};e.pos&&(n.pos=e.pos,delete e.pos),e.timeout&&(n.timeout=e.timeout,delete e.timeout);const r=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(I.Method.Post,"/sync",n,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:r,abortSignal:i})}supportsExperimentalThreads(){var e;return w.logger.warn("supportsExperimentalThreads() is deprecated, use supportThreads() instead"),(null===(e=this.clientOpts)||void 0===e?void 0:e.experimentalThreadSupport)||!1}supportsThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.intentionalMentions)||!1}getRoomSummary(e,t){return s(this,void 0,void 0,(function*(){const i=p.encodeUri("/rooms/$roomid/summary",{$roomid:e});return this.http.authedRequest(I.Method.Get,i,{via:t},void 0,{prefix:"/_matrix/client/unstable/im.nheko.summary"})}))}processThreadEvents(e,t,i){e.processThreadedEvents(t,i)}processThreadRoots(e,t,i){e.processThreadRoots(t,i)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){(null==t?void 0:t.length)&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}whoami(){return s(this,void 0,void 0,(function*(){return this.http.authedRequest(I.Method.Get,"/account/whoami")}))}timestampToEvent(e,t,i){return s(this,void 0,void 0,(function*(){const n=p.encodeUri("/rooms/$roomId/timestamp_to_event",{$roomId:e}),r={ts:t.toString(),dir:i};try{return yield this.http.authedRequest(I.Method.Get,n,r,void 0,{prefix:I.ClientPrefix.V1})}catch(e){if("M_UNRECOGNIZED"===e.errcode&&(400===e.httpStatus||404===e.httpStatus||405===e.httpStatus))return yield this.http.authedRequest(I.Method.Get,n,r,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw e}}))}}function le(e,t){var i,n;const r=e.getUserId(),o=t.getId(),s=e.getRoom(t.getRoomId());if(!s||!r||!o)return;const a=t.getPushActions(),c=e.getPushActionsForEvent(t,!0),d=!!t.threadRootId&&!t.isThreadRoot,l=s.getUnreadCountForEventContext(L.NotificationCountType.Highlight,t),u=!!(null===(i=null==a?void 0:a.tweaks)||void 0===i?void 0:i.highlight),h=!!(null===(n=null==c?void 0:c.tweaks)||void 0===n?void 0:n.highlight);let f;if(d){const e=s.getThread(t.threadRootId);f=!e||e.hasUserReadEvent(r,o)}else f=s.hasUserReadEvent(r,o);if(f)return;if(u!==h||l>0){let e=l;h&&!u&&e++,!h&&u&&e--,d?s.setThreadUnreadNotificationCount(t.threadRootId,L.NotificationCountType.Highlight,e):s.setUnreadNotificationCount(L.NotificationCountType.Highlight,e)}const p=s.getUnreadCountForEventContext(L.NotificationCountType.Total,t);!!(null==c?void 0:c.notify)&&(d?s.setThreadUnreadNotificationCount(t.threadRootId,L.NotificationCountType.Total,p+1):s.setUnreadNotificationCount(L.NotificationCountType.Total,p+1))}i.MatrixClient=de,de.RESTORE_BACKUP_ERROR_BAD_KEY="RESTORE_BACKUP_ERROR_BAD_KEY",i.fixNotificationCountOnDecryption=le}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":304,"./@types/beacon":305,"./@types/event":306,"./@types/partials":309,"./@types/read_receipts":311,"./@types/search":313,"./NamespacedValue":316,"./ReEmitter":317,"./ToDeviceMessageQueue":318,"./autodiscovery":319,"./content-helpers":322,"./content-repo":323,"./crypto":341,"./crypto/RoomList":329,"./crypto/api":336,"./crypto/backup":337,"./crypto/dehydration":339,"./crypto/key_passphrase":342,"./crypto/olmlib":343,"./crypto/recoverykey":344,"./event-mapper":360,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/MSC3089TreeSpace":377,"./models/event":383,"./models/event-timeline":382,"./models/invites-ignorer":384,"./models/room":392,"./models/room-member":389,"./models/search-result":393,"./models/thread":394,"./models/typed-event-emitter":395,"./models/user":396,"./pushprocessor":397,"./randomstring":398,"./rust-crypto":402,"./rust-crypto/constants":401,"./service-types":405,"./sliding-sync-sdk":406,"./store/stub":412,"./sync":414,"./utils":416,"./webrtc/call":418,"./webrtc/callEventHandler":419,"./webrtc/groupCall":422,"./webrtc/groupCallEventHandler":423,"./webrtc/mediaHandler":424}],322:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.parseBeaconContent=i.makeBeaconContent=i.parseBeaconInfoContent=i.makeBeaconInfoContent=i.parseTopicContent=i.makeTopicContent=i.parseLocationEvent=i.makeLocationContent=i.getTextForLocationEvent=i.makeEmoteMessage=i.makeNotice=i.makeTextMessage=i.makeHtmlEmote=i.makeHtmlNotice=i.makeHtmlMessage=void 0;const n=e("./@types/event"),r=e("./@types/extensible_events"),o=e("./extensible_events_v1/utilities"),s=e("./@types/location"),a=e("./@types/topic");i.makeHtmlMessage=function(e,t){return{msgtype:n.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeHtmlNotice=function(e,t){return{msgtype:n.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeHtmlEmote=function(e,t){return{msgtype:n.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeTextMessage=function(e){return{msgtype:n.MsgType.Text,body:e}},i.makeNotice=function(e){return{msgtype:n.MsgType.Notice,body:e}},i.makeEmoteMessage=function(e){return{msgtype:n.MsgType.Emote,body:e}};i.getTextForLocationEvent=(e,t,i,n)=>{const r=`at ${new Date(i).toISOString()}`;return[t===s.LocationAssetType.Self?"User":void 0,"Location",n?`"${n}"`:void 0,e,r].filter(Boolean).join(" ")};i.makeLocationContent=(e,t,o,a,c)=>{const d=null!=e?e:(0,i.getTextForLocationEvent)(t,c||s.LocationAssetType.Self,o,a),l=o?{[s.M_TIMESTAMP.name]:o}:{};return Object.assign({msgtype:n.MsgType.Location,body:d,geo_uri:t,[s.M_LOCATION.name]:{description:a,uri:t},[s.M_ASSET.name]:{type:c||s.LocationAssetType.Self},[r.M_TEXT.name]:d},l)};i.parseLocationEvent=e=>{var t,n;const o=s.M_LOCATION.findIn(e),a=s.M_ASSET.findIn(e),c=s.M_TIMESTAMP.findIn(e),d=r.M_TEXT.findIn(e),l=null!==(t=null==o?void 0:o.uri)&&void 0!==t?t:null==e?void 0:e.geo_uri,u=null==o?void 0:o.description,h=null!==(n=null==a?void 0:a.type)&&void 0!==n?n:s.LocationAssetType.Self,f=null!=d?d:e.body;return(0,i.makeLocationContent)(f,l,null!=c?c:void 0,u,h)};i.makeTopicContent=(e,t)=>{const i=[{body:e,mimetype:"text/plain"}];return(0,o.isProvided)(t)&&i.push({body:t,mimetype:"text/html"}),{topic:e,[a.M_TOPIC.name]:i}};i.parseTopicContent=e=>{var t,i,n;const r=a.M_TOPIC.findIn(e);if(!Array.isArray(r))return{text:e.topic};return{text:null!==(i=null===(t=null==r?void 0:r.find((e=>!(0,o.isProvided)(e.mimetype)||"text/plain"===e.mimetype)))||void 0===t?void 0:t.body)&&void 0!==i?i:e.topic,html:null===(n=null==r?void 0:r.find((e=>"text/html"===e.mimetype)))||void 0===n?void 0:n.body}};i.makeBeaconInfoContent=(e,t,i,n,r)=>({description:i,timeout:e,live:t,[s.M_TIMESTAMP.name]:r||Date.now(),[s.M_ASSET.name]:{type:null!=n?n:s.LocationAssetType.Self}});i.parseBeaconInfoContent=e=>{var t;const{description:i,timeout:n,live:r}=e,o=null!==(t=s.M_TIMESTAMP.findIn(e))&&void 0!==t?t:void 0,a=s.M_ASSET.findIn(e);return{description:i,timeout:n,live:r,assetType:null==a?void 0:a.type,timestamp:o}};i.makeBeaconContent=(e,t,i,n)=>({[s.M_LOCATION.name]:{description:n,uri:e},[s.M_TIMESTAMP.name]:t,"m.relates_to":{rel_type:r.REFERENCE_RELATION.name,event_id:i}});i.parseBeaconContent=e=>{var t;const i=s.M_LOCATION.findIn(e),n=null!==(t=s.M_TIMESTAMP.findIn(e))&&void 0!==t?t:void 0;return{description:null==i?void 0:i.description,uri:null==i?void 0:i.uri,timestamp:n}}},{"./@types/event":306,"./@types/extensible_events":307,"./@types/location":308,"./@types/topic":315,"./extensible_events_v1/utilities":361}],323:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.getHttpUriForMxc=void 0;const s=o(e("./utils"));i.getHttpUriForMxc=function(e,t,i,n,r,o=!1){if("string"!=typeof t||!t)return"";if(0!==t.indexOf("mxc://"))return o?t:"";let a=t.slice(6),c="/_matrix/media/r0/download/";const d={};i&&(d.width=Math.round(i).toString()),n&&(d.height=Math.round(n).toString()),r&&(d.method=r),Object.keys(d).length>0&&(c="/_matrix/media/r0/thumbnail/");const l=a.indexOf("#");let u="";return l>=0&&(u=a.slice(l),a=a.slice(0,l)),e+c+a+(0===Object.keys(d).length?"":"?"+s.encodeParams(d))+u}},{"./utils":416}],324:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.requestKeysDuringVerification=i.createCryptoStoreCacheCallbacks=i.DeviceTrustLevel=i.UserTrustLevel=i.CrossSigningLevel=i.CrossSigningInfo=void 0;const o=e("./olmlib"),s=e("../logger"),a=e("../crypto/store/indexeddb-crypto-store"),c=e("./aes"),d=6e4;function l(e){return Object.values(e.keys)[0]}class u{constructor(e,t={},i={}){this.userId=e,this.callbacks=t,this.cacheCallbacks=i,this.keys={},this.firstUse=!0,this.crossSigningVerifiedBefore=!1}static fromStorage(e,t){const i=new u(t);for(const t in e)e.hasOwnProperty(t)&&(i[t]=e[t]);return i}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}getCrossSigningKey(e,i){return r(this,void 0,void 0,(function*(){const n=["master","self_signing","user_signing"].indexOf(e)>=0;if(!this.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");function r(e){if(!e)return;const n=new t.Olm.PkSigning,r=n.init_with_seed(e);if(r===i)return[r,n];n.free()}void 0===i&&(i=this.getId(e));let o=null;this.cacheCallbacks.getCrossSigningKeyCache&&n&&(o=yield this.cacheCallbacks.getCrossSigningKeyCache(e,i));const s=r(o);if(s)return s;o=yield this.callbacks.getCrossSigningKey(e,i);const a=r(o);if(a)return this.cacheCallbacks.storeCrossSigningKeyCache&&n&&(yield this.cacheCallbacks.storeCrossSigningKeyCache(e,o)),a;if(!o)throw new Error("getCrossSigningKey callback for "+e+" returned falsey");throw new Error("Key type "+e+" from getCrossSigningKey callback did not match")}))}isStoredInSecretStorage(e){return r(this,void 0,void 0,(function*(){const t=(yield e.isStored("m.cross_signing.master"))||{};function i(e){for(const i of Object.keys(t))e[i]||delete t[i]}for(const t of["self_signing","user_signing"])i((yield e.isStored(`m.cross_signing.${t}`))||{});return Object.keys(t).length?t:null}))}static storeInSecretStorage(e,t){return r(this,void 0,void 0,(function*(){for(const[i,n]of e){const e=(0,o.encodeBase64)(n);yield t.store(`m.cross_signing.${i}`,e)}}))}static getFromSecretStorage(e,t){return r(this,void 0,void 0,(function*(){const i=yield t.get(`m.cross_signing.${e}`);return i?(0,o.decodeBase64)(i):null}))}isStoredInKeyCache(e){var t;return r(this,void 0,void 0,(function*(){const i=this.cacheCallbacks;if(!i)return!1;const n=e?[e]:["master","self_signing","user_signing"];for(const e of n)if(!(yield null===(t=i.getCrossSigningKeyCache)||void 0===t?void 0:t.call(i,e)))return!1;return!0}))}getCrossSigningKeysFromCache(){var e;return r(this,void 0,void 0,(function*(){const t=new Map,i=this.cacheCallbacks;if(!i)return t;for(const n of["master","self_signing","user_signing"]){const r=yield null===(e=i.getCrossSigningKeyCache)||void 0===e?void 0:e.call(i,n);r&&t.set(n,r)}return t}))}getId(e="master"){if(!this.keys[e])return null;return l(this.keys[e])}resetKeys(e){return r(this,void 0,void 0,(function*(){if(!this.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(void 0===e||e&h.MASTER||!this.keys.master)e=h.MASTER|h.USER_SIGNING|h.SELF_SIGNING;else if(0===e)return;const i={},n={};let r,s;try{if(e&h.MASTER?(r=new t.Olm.PkSigning,i.master=r.generate_seed(),s=r.init_with_seed(i.master),n.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+s]:s}}):[s,r]=yield this.getCrossSigningKey("master"),e&h.SELF_SIGNING){const e=new t.Olm.PkSigning;try{i.self_signing=e.generate_seed();const t=e.init_with_seed(i.self_signing);n.self_signing={user_id:this.userId,usage:["self_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(n.self_signing,r,this.userId,s)}finally{e.free()}}if(e&h.USER_SIGNING){const e=new t.Olm.PkSigning;try{i.user_signing=e.generate_seed();const t=e.init_with_seed(i.user_signing);n.user_signing={user_id:this.userId,usage:["user_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(n.user_signing,r,this.userId,s)}finally{e.free()}}Object.assign(this.keys,n),this.callbacks.saveCrossSigningKeys(i)}finally{r&&r.free()}}))}clearKeys(){this.keys={}}setKeys(e){const t={};if(e.master){if(e.master.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in master key from "+this.userId;throw s.logger.error(t),new Error(t)}this.keys.master?l(e.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,t.master=e.master}else{if(!this.keys.master)throw new Error("Tried to set cross-signing keys without a master key");t.master=this.keys.master}const i=l(t.master);if(e.user_signing){if(e.user_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in user_signing key from "+this.userId;throw s.logger.error(t),new Error(t)}try{(0,o.pkVerify)(e.user_signing,i,this.userId)}catch(e){throw s.logger.error("invalid signature on user-signing key"),e}}if(e.self_signing){if(e.self_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in self_signing key from "+this.userId;throw s.logger.error(t),new Error(t)}try{(0,o.pkVerify)(e.self_signing,i,this.userId)}catch(e){throw s.logger.error("invalid signature on self-signing key"),e}}e.master&&(this.keys.master=e.master,delete this.keys.self_signing,delete this.keys.user_signing),e.self_signing&&(this.keys.self_signing=e.self_signing),e.user_signing&&(this.keys.user_signing=e.user_signing)}updateCrossSigningVerifiedBefore(e){!this.crossSigningVerifiedBefore&&e&&(this.crossSigningVerifiedBefore=!0)}signObject(e,t){return r(this,void 0,void 0,(function*(){if(!this.keys[t])throw new Error("Attempted to sign with "+t+" key but no such key present");const[i,n]=yield this.getCrossSigningKey(t);try{return(0,o.pkSign)(e,n,this.userId,i),e}finally{n.free()}}))}signUser(e){return r(this,void 0,void 0,(function*(){if(this.keys.user_signing)return this.signObject(e.keys.master,"user_signing");s.logger.info("No user signing key: not signing user")}))}signDevice(e,t){return r(this,void 0,void 0,(function*(){if(e!==this.userId)throw new Error(`Trying to sign ${e}'s device; can only sign our own device`);if(this.keys.self_signing)return this.signObject({algorithms:t.algorithms,keys:t.keys,device_id:t.deviceId,user_id:e},"self_signing");s.logger.info("No self signing key: not signing device")}))}checkUserTrust(e){if(this.userId===e.userId&&this.getId()&&this.getId()===e.getId()&&this.getId("self_signing")&&this.getId("self_signing")===e.getId("self_signing"))return new f(!0,!0,this.firstUse);if(!this.keys.user_signing)return new f(!1,!1,e.firstUse);let t;const i=e.keys.master,n=this.getId("user_signing");try{(0,o.pkVerify)(i,n,this.userId),t=!0}catch(e){t=!1}return new f(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,i,n){const r=this.checkUserTrust(e),s=e.keys.self_signing;if(!s)return new p(!1,!1,i,n);const a=function(e,t){return{algorithms:e.algorithms,keys:e.keys,device_id:e.deviceId,user_id:t,signatures:e.signatures}}(t,e.userId);try{return(0,o.pkVerify)(s,e.getId(),e.userId),(0,o.pkVerify)(a,l(s),e.userId),p.fromUserTrustLevel(r,i,n)}catch(e){return new p(!1,!1,i,n)}}getCacheCallbacks(){return this.cacheCallbacks}}var h;i.CrossSigningInfo=u,function(e){e[e.MASTER=4]="MASTER",e[e.USER_SIGNING=2]="USER_SIGNING",e[e.SELF_SIGNING=1]="SELF_SIGNING"}(h=i.CrossSigningLevel||(i.CrossSigningLevel={}));class f{constructor(e,t,i){this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}i.UserTrustLevel=f;class p{constructor(e,t,i,n){this.crossSigningVerified=e,this.tofu=t,this.localVerified=i,this.trustCrossSignedDevices=n}static fromUserTrustLevel(e,t,i){return new p(e.isCrossSigningVerified(),e.isTofu(),t,i)}isVerified(){return Boolean(this.isLocallyVerified()||this.trustCrossSignedDevices&&this.isCrossSigningVerified())}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}i.DeviceTrustLevel=p,i.createCryptoStoreCacheCallbacks=function(e,t){return{getCrossSigningKeyCache:function(i,s){return r(this,void 0,void 0,(function*(){const r=yield new Promise((t=>e.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(n=>{e.getSecretStorePrivateKey(n,t,i)}))));if(r&&r.ciphertext){const e=n.from(t.pickleKey),s=yield(0,c.decryptAES)(r,e,i);return(0,o.decodeBase64)(s)}return r}))},storeCrossSigningKeyCache:function(i,s){return r(this,void 0,void 0,(function*(){if(!(s instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${s}`);const r=n.from(t.pickleKey),d=yield(0,c.encryptAES)((0,o.encodeBase64)(s),r,i);return e.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.storeSecretStorePrivateKey(t,i,d)}))}))}}},i.requestKeysDuringVerification=function(e,t,i){return r(this,void 0,void 0,(function*(){if(e.getUserId()===t)return s.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise(((t,n)=>{const a=e,c=a.crypto.crossSigningInfo,l=new u(c.userId,{getCrossSigningKey:e=>r(this,void 0,void 0,(function*(){s.logger.debug("Cross-signing: requesting secret",e,i);const{promise:t}=a.requestSecret(`m.cross_signing.${e}`,[i]),n=yield t,r=(0,o.decodeBase64)(n);return Uint8Array.from(r)}))},c.getCacheCallbacks());l.keys=c.keys;const h=new Promise((e=>{setTimeout(e,d,new Error("Timeout"))})),f=(()=>r(this,void 0,void 0,(function*(){if(!(yield a.crypto.getSessionBackupPrivateKey())){s.logger.info("No cached backup key found. Requesting...");const e=a.requestSecret("m.megolm_backup.v1",[i]),t=yield e.promise;s.logger.info("Got key backup key, decoding...");const n=(0,o.decodeBase64)(t);s.logger.info("Decoded backup key, storing..."),yield a.crypto.storeSessionBackupPrivateKey(Uint8Array.from(n)),s.logger.info("Backup key stored. Starting backup restore...");const r=yield a.getKeyBackupVersion();a.restoreKeyBackupWithCache(void 0,void 0,r).then((()=>{s.logger.info("Backup restored.")}))}})))();return Promise.race([Promise.all([l.getCrossSigningKey("master"),l.getCrossSigningKey("self_signing"),l.getCrossSigningKey("user_signing"),f]),h]).then(t,n)})).catch((e=>{s.logger.warn("Cross-signing: failure while requesting keys:",e)}))}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../crypto/store/indexeddb-crypto-store":346,"../logger":374,"./aes":331,"./olmlib":343,buffer:68}],325:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceList=i.TrackingStatus=void 0;const a=e("../logger"),c=e("./deviceinfo"),d=e("./CrossSigning"),l=o(e("./olmlib")),u=e("./store/indexeddb-crypto-store"),h=e("../utils"),f=e("../models/typed-event-emitter"),p=e("./index");var g;!function(e){e[e.NotTracked=0]="NotTracked",e[e.PendingDownload=1]="PendingDownload",e[e.DownloadInProgress=2]="DownloadInProgress",e[e.UpToDate=3]="UpToDate"}(g=i.TrackingStatus||(i.TrackingStatus={}));class v extends f.TypedEventEmitter{constructor(e,t,i,n=250){super(),this.cryptoStore=t,this.keyDownloadChunkSize=n,this.devices={},this.crossSigningInfo={},this.userByIdentityKey={},this.deviceTrackingStatus={},this.syncToken=null,this.keyDownloadsInProgressByUser=new Map,this.dirty=!1,this.savePromise=null,this.resolveSavePromise=null,this.savePromiseTime=null,this.saveTimer=null,this.hasFetched=null,this.serialiser=new m(e,i,this)}load(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readonly",[u.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{this.cryptoStore.getEndToEndDeviceData(e,(e=>{var t;this.hasFetched=Boolean(e&&e.devices),this.devices=e?e.devices:{},this.crossSigningInfo=e&&e.crossSigningInfo||{},this.deviceTrackingStatus=e?e.trackingStatus:{},this.syncToken=null!==(t=null==e?void 0:e.syncToken)&&void 0!==t?t:null,this.userByIdentityKey={};for(const e of Object.keys(this.devices)){const t=this.devices[e];for(const i of Object.keys(t)){const n=t[i].keys["curve25519:"+i];void 0!==n&&(this.userByIdentityKey[n]=e)}}}))}));for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]==g.DownloadInProgress&&(this.deviceTrackingStatus[e]=g.PendingDownload)}))}stop(){null!==this.saveTimer&&clearTimeout(this.saveTimer)}saveIfDirty(e=500){return s(this,void 0,void 0,(function*(){if(!this.dirty)return Promise.resolve(!1);const t=Date.now()+e;this.savePromiseTime&&t<this.savePromiseTime&&(clearTimeout(this.saveTimer),this.saveTimer=null,this.savePromiseTime=null);let i=this.savePromise;if(null===i&&(i=new Promise((e=>{this.resolveSavePromise=e})),this.savePromise=i),null===this.saveTimer){const i=this.resolveSavePromise;this.savePromiseTime=t,this.saveTimer=setTimeout((()=>{a.logger.log("Saving device tracking data",this.syncToken),this.savePromiseTime=null,this.saveTimer=null,this.savePromise=null,this.resolveSavePromise=null,this.cryptoStore.doTxn("readwrite",[u.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{var t;this.cryptoStore.storeEndToEndDeviceData({devices:this.devices,crossSigningInfo:this.crossSigningInfo,trackingStatus:this.deviceTrackingStatus,syncToken:null!==(t=this.syncToken)&&void 0!==t?t:void 0},e)})).then((()=>{this.dirty=!1,null==i||i(!0)}),(e=>{a.logger.error("Failed to save device tracking data",this.syncToken),a.logger.error(e)}))}),e)}return i}))}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){const i=[],n=[];if(e.forEach((e=>{const r=this.deviceTrackingStatus[e];this.keyDownloadsInProgressByUser.has(e)?(a.logger.log(`downloadKeys: already have a download in progress for ${e}: awaiting its result`),n.push(this.keyDownloadsInProgressByUser.get(e))):(t||r!=g.UpToDate)&&i.push(e)})),0!=i.length){a.logger.log("downloadKeys: downloading for",i);const e=this.doKeyDownload(i);n.push(e)}return 0===n.length&&a.logger.log("downloadKeys: already have all necessary keys"),Promise.all(n).then((()=>this.getDevicesFromStore(e)))}getDevicesFromStore(e){const t=new Map;return e.forEach((e=>{var i;const n=new Map;null===(i=this.getStoredDevicesForUser(e))||void 0===i||i.forEach((function(e){n.set(e.deviceId,e)})),t.set(e,n)})),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){const t=this.devices[e];if(!t)return null;const i=[];for(const e in t)t.hasOwnProperty(e)&&i.push(c.DeviceInfo.fromStorage(t[e],e));return i}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?d.CrossSigningInfo.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){const i=this.devices[e];if(null==i?void 0:i[t])return c.DeviceInfo.fromStorage(i[t],t)}getUserByIdentityKey(e,t){return e!==l.OLM_ALGORITHM&&e!==l.MEGOLM_ALGORITHM?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){const i=this.getUserByIdentityKey(e,t);if(!i)return null;const n=this.devices[i];if(!n)return null;for(const e in n){if(!n.hasOwnProperty(e))continue;const i=n[e];for(const n in i.keys){if(!i.keys.hasOwnProperty(n))continue;if(0!==n.indexOf("curve25519:"))continue;if(i.keys[n]==t)return c.DeviceInfo.fromStorage(i,e)}}return null}storeDevicesForUser(e,t){this.setRawStoredDevicesForUser(e,t),this.dirty=!0}startTrackingDeviceList(e){if("string"!=typeof e)throw new Error("userId must be a string; was "+e);this.deviceTrackingStatus[e]||(a.logger.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=g.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=g.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this.deviceTrackingStatus)){this.deviceTrackingStatus[t]==g.PendingDownload&&e.push(t)}return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(void 0!==this.devices[e])for(const[t,i]of Object.entries(this.devices[e])){const e=i.keys["curve25519:"+t];delete this.userByIdentityKey[e]}this.devices[e]=t;for(const[i,n]of Object.entries(t)){const t=n.keys["curve25519:"+i];this.userByIdentityKey[t]=e}}setRawStoredCrossSigningForUser(e,t){this.crossSigningInfo[e]=t}doKeyDownload(e){if(0===e.length)return Promise.resolve();const t=this.serialiser.updateDevicesForUsers(e,this.syncToken).then((()=>{i(!0)}),(t=>{throw a.logger.error("Error downloading keys for "+e+":",t),i(!1),t}));e.forEach((e=>{this.keyDownloadsInProgressByUser.set(e,t);this.deviceTrackingStatus[e]==g.PendingDownload&&(this.deviceTrackingStatus[e]=g.DownloadInProgress)}));const i=i=>{this.emit(p.CryptoEvent.WillUpdateDevices,e,!this.hasFetched),e.forEach((e=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser.get(e)!==t)return void a.logger.log("Another update in the queue for",e,"- not marking up-to-date");this.keyDownloadsInProgressByUser.delete(e);this.deviceTrackingStatus[e]==g.DownloadInProgress&&(i?(this.deviceTrackingStatus[e]=g.UpToDate,a.logger.log("Device list for",e,"now up to date")):this.deviceTrackingStatus[e]=g.PendingDownload)})),this.saveIfDirty(),this.emit(p.CryptoEvent.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}i.DeviceList=v;class m{constructor(e,t,i){this.baseApis=e,this.olmDevice=t,this.deviceList=i,this.downloadInProgress=!1,this.keyDownloadsQueuedByUser={}}updateDevicesForUsers(e,t){return e.forEach((e=>{this.keyDownloadsQueuedByUser[e]=!0})),this.queuedQueryDeferred||(this.queuedQueryDeferred=(0,h.defer)()),this.syncToken=t,this.downloadInProgress?(a.logger.log("Queued key download for",e),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");const e=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};const t=this.queuedQueryDeferred;this.queuedQueryDeferred=void 0,a.logger.log("Starting key download for",e),this.downloadInProgress=!0;const i={};this.syncToken&&(i.token=this.syncToken);const n=[];for(let t=0;t<e.length;t+=this.deviceList.keyDownloadChunkSize){const r=e.slice(t,t+this.deviceList.keyDownloadChunkSize);n.push((()=>this.baseApis.downloadKeysForUsers(r,i)))}return(0,h.chunkPromises)(n,3).then((t=>s(this,void 0,void 0,(function*(){const i=Object.assign({},...t.map((e=>e.device_keys||{}))),n=Object.assign({},...t.map((e=>e.master_keys||{}))),r=Object.assign({},...t.map((e=>e.self_signing_keys||{}))),o=Object.assign({},...t.map((e=>e.user_signing_keys||{})));for(const t of e){yield(0,h.sleep)(5);try{yield this.processQueryResponseForUser(t,i[t],{master:null==n?void 0:n[t],self_signing:null==r?void 0:r[t],user_signing:null==o?void 0:o[t]})}catch(e){a.logger.error(`Error processing keys for ${t}:`,e)}}})))).then((()=>{a.logger.log("Completed key download for "+e),this.downloadInProgress=!1,null==t||t.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()}),(i=>{a.logger.warn("Error downloading keys for "+e+":",i),this.downloadInProgress=!1,null==t||t.reject(i)})),t.promise}processQueryResponseForUser(e,t,i){return s(this,void 0,void 0,(function*(){a.logger.log("got device keys for "+e+":",t),a.logger.log("got cross-signing keys for "+e+":",i);{const i={},n=this.deviceList.getRawStoredDevicesForUser(e);n&&Object.keys(n).forEach((e=>{const t=c.DeviceInfo.fromStorage(n[e],e);i[e]=t})),yield function(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){let s=!1;for(const e in i)if(i.hasOwnProperty(e)&&!(e in n)){if(t===r&&e===o){a.logger.warn(`Local device ${e} missing from sync, skipping removal`);continue}a.logger.log("Device "+t+":"+e+" has been removed"),delete i[e],s=!0}for(const r in n){if(!n.hasOwnProperty(r))continue;const o=n[r];o.user_id===t?o.device_id===r?(yield y(e,i,o))&&(s=!0):a.logger.warn("Mismatched device_id "+o.device_id+" in keys from "+t+":"+r):a.logger.warn("Mismatched user_id "+o.user_id+" in keys from "+t+":"+r)}return s}))}(this.olmDevice,e,i,t||{},this.baseApis.getUserId(),this.baseApis.deviceId);const r={};Object.keys(i).forEach((e=>{r[e]=i[e].toStorage()})),this.deviceList.setRawStoredDevicesForUser(e,r)}if(i&&(i.master||i.self_signing||i.user_signing)){const t=this.deviceList.getStoredCrossSigningForUser(e)||new d.CrossSigningInfo(e);t.setKeys(i),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage()),this.deviceList.emit(p.CryptoEvent.UserCrossSigningUpdated,e)}}))}}function y(e,t,i){return s(this,void 0,void 0,(function*(){if(!i.keys)return!1;const n=i.device_id,r=i.user_id,o="ed25519:"+n,s=i.keys[o];if(!s)return a.logger.warn("Device "+r+":"+n+" has no ed25519 key"),!1;const d=i.unsigned||{},u=i.signatures||{};try{yield l.verifySignature(e,i,r,n,s)}catch(e){return a.logger.warn("Unable to verify signature on device "+r+":"+n+":"+e),!1}let h;if(n in t){if(h=t[n],h.getFingerprint()!=s)return a.logger.warn("Ed25519 key for device "+r+":"+n+" has changed"),!1}else t[n]=h=new c.DeviceInfo(n);return h.keys=i.keys||{},h.algorithms=i.algorithms||[],h.unsigned=d,h.signatures=u,!0}))}},{"../logger":374,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./deviceinfo":340,"./index":341,"./olmlib":343,"./store/indexeddb-crypto-store":346}],326:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.EncryptionSetupOperation=i.EncryptionSetupBuilder=void 0;const r=e("../logger"),o=e("../models/event"),s=e("./CrossSigning"),a=e("./store/indexeddb-crypto-store"),c=e("../http-api"),d=e("../client"),l=e("../models/typed-event-emitter");i.EncryptionSetupBuilder=class{constructor(e,t){this.accountDataClientAdapter=new h(e),this.crossSigningCallbacks=new f,this.ssssCryptoCallbacks=new p(t)}addCrossSigningKeys(e,t){this.crossSigningKeys={authUpload:e,keys:t}}addSessionBackup(e){this.keyBackupInfo=e}addSessionBackupPrivateKeyToCache(e){this.sessionBackupPrivateKey=e}addKeySignature(e,t,i){this.keySignatures||(this.keySignatures={});const n=this.keySignatures[e]||{};this.keySignatures[e]=n,n[t]=i}setAccountData(e,t){return n(this,void 0,void 0,(function*(){yield this.accountDataClientAdapter.setAccountData(e,t)}))}buildOperation(){const e=this.accountDataClientAdapter.values;return new u(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}persist(e){var t;return n(this,void 0,void 0,(function*(){if(this.crossSigningKeys){const i=(0,s.createCryptoStoreCacheCallbacks)(e.cryptoStore,e.olmDevice);for(const e of["master","self_signing","user_signing"]){r.logger.log(`Cache ${e} cross-signing private key locally`);const n=this.crossSigningCallbacks.privateKeys.get(e);yield null===(t=i.storeCrossSigningKeyCache)||void 0===t?void 0:t.call(i,e,n)}yield e.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.cryptoStore.storeCrossSigningKeys(t,this.crossSigningKeys.keys)}))}this.sessionBackupPrivateKey&&(yield e.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey))}))}};class u{constructor(e,t,i,n){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=i,this.keySignatures=n}apply(e){var t,i;return n(this,void 0,void 0,(function*(){const n=e.baseApis;if(this.crossSigningKeys){const r={};for(const[e,t]of Object.entries(this.crossSigningKeys.keys))r[e+"_key"]=t;yield null===(i=(t=this.crossSigningKeys).authUpload)||void 0===i?void 0:i.call(t,(e=>n.uploadDeviceSigningKeys(e,r))),e.crossSigningInfo.setKeys(this.crossSigningKeys.keys)}if(this.accountData)for(const[e,t]of this.accountData)yield n.setAccountData(e,t);this.keySignatures&&(yield n.uploadKeySignatures(this.keySignatures)),this.keyBackupInfo&&(this.keyBackupInfo.version?yield n.http.authedRequest(c.Method.Put,"/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:c.ClientPrefix.V3}):yield n.http.authedRequest(c.Method.Post,"/room_keys/version",void 0,this.keyBackupInfo,{prefix:c.ClientPrefix.V3}))}))}}i.EncryptionSetupOperation=u;class h extends l.TypedEventEmitter{constructor(e){super(),this.existingValues=e,this.values=new Map}getAccountDataFromServer(e){return Promise.resolve(this.getAccountData(e))}getAccountData(e){const t=this.values.get(e);if(t)return t;const i=this.existingValues.get(e);return i?i.getContent():null}setAccountData(e,t){const i=this.values.get(e);return this.values.set(e,t),Promise.resolve().then((()=>{const n=new o.MatrixEvent({type:e,content:t});return this.emit(d.ClientEvent.AccountData,n,i),{}}))}}class f{constructor(){this.privateKeys=new Map}getCrossSigningKeyCache(e,t){return this.getCrossSigningKey(e,t)}storeCrossSigningKeyCache(e,t){return this.privateKeys.set(e,t),Promise.resolve()}getCrossSigningKey(e,t){var i;return Promise.resolve(null!==(i=this.privateKeys.get(e))&&void 0!==i?i:null)}saveCrossSigningKeys(e){for(const[t,i]of Object.entries(e))this.privateKeys.set(t,i)}}class p{constructor(e){this.delegateCryptoCallbacks=e,this.privateKeys=new Map}getSecretStorageKey({keys:e},t){var i;return n(this,void 0,void 0,(function*(){for(const t of Object.keys(e)){const e=this.privateKeys.get(t);if(e)return[t,e]}if(null===(i=null==this?void 0:this.delegateCryptoCallbacks)||void 0===i?void 0:i.getSecretStorageKey){const i=yield this.delegateCryptoCallbacks.getSecretStorageKey({keys:e},t);if(i){const[e,t]=i;this.privateKeys.set(e,t)}return i}return null}))}addPrivateKey(e,t,i){var n,r;this.privateKeys.set(e,i),null===(r=null===(n=this.delegateCryptoCallbacks)||void 0===n?void 0:n.cacheSecretStorageKey)||void 0===r||r.call(n,e,t,i)}}},{"../client":321,"../http-api":367,"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"./CrossSigning":324,"./store/indexeddb-crypto-store":346}],327:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.WITHHELD_MESSAGES=i.OlmDevice=i.PayloadTooLargeError=void 0;const a=e("../logger"),c=e("./store/indexeddb-crypto-store"),d=o(e("./algorithms")),l=49152;class u extends Error{constructor(){super(...arguments),this.data={errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"}}}function h(e){if(void 0===e)throw new Error("payloadString undefined");if(e.length>l)throw new u(`Message too long (${e.length} bytes). The maximum for an encrypted message is ${l} bytes.`)}i.PayloadTooLargeError=u;function f(e){return e.code&&e.code in i.WITHHELD_MESSAGES?i.WITHHELD_MESSAGES[e.code]:e.reason?e.reason:"decryption key withheld"}i.OlmDevice=class{constructor(e){this.cryptoStore=e,this.pickleKey="DEFAULT_KEY",this.deviceCurve25519Key=null,this.deviceEd25519Key=null,this.maxOneTimeKeys=null,this.outboundGroupSessionStore={},this.inboundGroupSessionMessageIndexes={},this.sessionsInProgress={},this.olmPrekeyPromise=Promise.resolve()}static getOlmVersion(){return t.Olm.get_library_version()}init({pickleKey:e,fromExportedDevice:i}={}){return s(this,void 0,void 0,(function*(){let n;const r=new t.Olm.Account;try{i?(e&&a.logger.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),this.pickleKey=i.pickleKey,yield this.initialiseFromExportedDevice(i,r)):(e&&(this.pickleKey=e),yield this.initialiseAccount(r)),n=JSON.parse(r.identity_keys()),this.maxOneTimeKeys=r.max_number_of_one_time_keys()}finally{r.free()}this.deviceCurve25519Key=n.curve25519,this.deviceEd25519Key=n.ed25519}))}initialiseFromExportedDevice(e,t){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.storeAccount(t,e.pickledAccount),e.sessions.forEach((e=>{const{deviceKey:i,sessionId:n}=e,r={session:e.session,lastReceivedMessageTs:e.lastReceivedMessageTs};this.cryptoStore.storeEndToEndSession(i,n,r,t)}))})),t.unpickle(this.pickleKey,e.pickledAccount)}))}initialiseAccount(e){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getAccount(t,(i=>{null!==i?e.unpickle(this.pickleKey,i):(e.create(),i=e.pickle(this.pickleKey),this.cryptoStore.storeAccount(t,i))}))}))}))}getAccount(e,i){this.cryptoStore.getAccount(e,(e=>{const n=new t.Olm.Account;try{n.unpickle(this.pickleKey,e),i(n)}finally{n.free()}}))}storeAccount(e,t){this.cryptoStore.storeAccount(e,t.pickle(this.pickleKey))}export(){return s(this,void 0,void 0,(function*(){const e={pickleKey:this.pickleKey};return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getAccount(t,(t=>{e.pickledAccount=t})),e.sessions=[],this.cryptoStore.getAllEndToEndSessions(t,(t=>{e.sessions.push(t)}))})),e}))}getSession(e,t,i,n){this.cryptoStore.getEndToEndSession(e,t,i,(e=>{this.unpickleSession(e,n)}))}unpickleSession(e,i){const n=new t.Olm.Session;try{n.unpickle(this.pickleKey,e.session);i(Object.assign({},e,{session:n}))}finally{n.free()}}saveSession(e,t,i){const n=t.session.session_id();a.logger.debug(`Saving Olm session ${n} with device ${e}: ${t.session.describe()}`);const r=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,n,r,i)}getUtility(e){const i=new t.Olm.Utility;try{return e(i)}finally{i.free()}}sign(e){return s(this,void 0,void 0,(function*(){let t;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(i=>{this.getAccount(i,(i=>{t=i.sign(e)}))})),t}))}getOneTimeKeys(){return s(this,void 0,void 0,(function*(){let e;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.one_time_keys())}))})),e}))}maxNumberOfOneTimeKeys(){var e;return null!==(e=this.maxOneTimeKeys)&&void 0!==e?e:-1}markKeysAsPublished(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.mark_keys_as_published(),this.storeAccount(e,t)}))}))}))}generateOneTimeKeys(e){return this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(i=>{i.generate_one_time_keys(e),this.storeAccount(t,i)}))}))}generateFallbackKey(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.generate_fallback_key(),this.storeAccount(e,t)}))}))}))}getFallbackKey(){return s(this,void 0,void 0,(function*(){let e;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.unpublished_fallback_key())}))})),e}))}forgetOldFallbackKey(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.forget_old_fallback_key(),this.storeAccount(e,t)}))}))}))}createOutboundSession(e,i){return s(this,void 0,void 0,(function*(){let n;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(r=>{this.getAccount(r,(o=>{const s=new t.Olm.Session;try{s.create_outbound(o,e,i),n=s.session_id(),this.storeAccount(r,o);const t={session:s,lastReceivedMessageTs:Date.now()};this.saveSession(e,t,r)}finally{s.free()}}))}),a.logger.withPrefix("[createOutboundSession]")),n}))}createInboundSession(e,i,n){return s(this,void 0,void 0,(function*(){if(0!==i)throw new Error("Need messageType == 0 to create inbound session");let r;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(o=>{this.getAccount(o,(s=>{const a=new t.Olm.Session;try{a.create_inbound_from(s,e,n),s.remove_one_time_keys(a),this.storeAccount(o,s);const t=a.decrypt(i,n),c={session:a,lastReceivedMessageTs:Date.now()};this.saveSession(e,c,o),r={payload:t,session_id:a.session_id()}}finally{a.free()}}))}),a.logger.withPrefix("[createInboundSession]")),r}))}getSessionIdsForDevice(e){return s(this,void 0,void 0,(function*(){const t=a.logger.withPrefix("[getSessionIdsForDevice]");if(e in this.sessionsInProgress){t.debug(`Waiting for Olm session for ${e} to be created`);try{yield this.sessionsInProgress[e]}catch(e){}}let i;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{i=Object.keys(e)}))}),t),i}))}getSessionIdForDevice(e,t=!1,i){return s(this,void 0,void 0,(function*(){const n=yield this.getSessionInfoForDevice(e,t,i);if(0===n.length)return null;let r=0;for(let e=1;e<n.length;e++){const t=n[e],i=void 0===t.lastReceivedMessageTs?0:t.lastReceivedMessageTs,o=n[r],s=void 0===o.lastReceivedMessageTs?0:o.lastReceivedMessageTs;(i>s||i===s&&t.sessionId<o.sessionId)&&(r=e)}return n[r].sessionId}))}getSessionInfoForDevice(e,t=!1,i=a.logger){return s(this,void 0,void 0,(function*(){if(i=i.withPrefix("[getSessionInfoForDevice]"),e in this.sessionsInProgress&&!t){i.debug(`Waiting for Olm session for ${e} to be created`);try{yield this.sessionsInProgress[e]}catch(e){}}const n=[];return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{const t=Object.keys(e).sort();for(const i of t)this.unpickleSession(e[i],(e=>{n.push({lastReceivedMessageTs:e.lastReceivedMessageTs,hasReceivedMessage:e.session.has_received_message(),sessionId:i})}))}))}),i),n}))}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){let n;return h(i),yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_SESSIONS],(r=>{this.getSession(e,t,r,(o=>{const s=o.session.describe();a.logger.log("encryptMessage: Olm Session ID "+t+" to "+e+": "+s),n=o.session.encrypt(i),this.saveSession(e,o,r)}))}),a.logger.withPrefix("[encryptMessage]")),n}))}decryptMessage(e,t,i,n){return s(this,void 0,void 0,(function*(){let r;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_SESSIONS],(o=>{this.getSession(e,t,o,(s=>{const c=s.session.describe();a.logger.log("decryptMessage: Olm Session ID "+t+" from "+e+": "+c),r=s.session.decrypt(i,n),s.lastReceivedMessageTs=Date.now(),this.saveSession(e,s,o)}))}),a.logger.withPrefix("[decryptMessage]")),r}))}matchesSession(e,t,i,n){return s(this,void 0,void 0,(function*(){if(0!==i)return!1;let r;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(i=>{this.getSession(e,t,i,(e=>{r=e.session.matches_inbound(n)}))}),a.logger.withPrefix("[matchesSession]")),r}))}recordSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){a.logger.info(`Recording problem on olm session with ${e} of type ${t}. Recreating: ${i}`),yield this.cryptoStore.storeEndToEndSessionProblem(e,t,i)}))}sessionMayHaveProblems(e,t){return this.cryptoStore.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.cryptoStore.filterOutNotifiedErrorDevices(e)}saveOutboundGroupSession(e){this.outboundGroupSessionStore[e.session_id()]=e.pickle(this.pickleKey)}getOutboundGroupSession(e,i){const n=this.outboundGroupSessionStore[e];if(void 0===n)throw new Error("Unknown outbound group session "+e);const r=new t.Olm.OutboundGroupSession;try{return r.unpickle(this.pickleKey,n),i(r)}finally{r.free()}}createOutboundGroupSession(){const e=new t.Olm.OutboundGroupSession;try{return e.create(),this.saveOutboundGroupSession(e),e.session_id()}finally{e.free()}}encryptGroupMessage(e,t){return a.logger.log(`encrypting msg with megolm session ${e}`),h(t),this.getOutboundGroupSession(e,(e=>{const i=e.encrypt(t);return this.saveOutboundGroupSession(e),i}))}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,(function(e){return{chain_index:e.message_index(),key:e.session_key()}}))}unpickleInboundGroupSession(e,i){const n=new t.Olm.InboundGroupSession;try{return n.unpickle(this.pickleKey,e.session),i(n)}finally{n.free()}}getInboundGroupSession(e,t,i,n,r){this.cryptoStore.getEndToEndInboundGroupSession(t,i,n,((t,i)=>{if(null!==t){if(null!==e&&e!==t.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+t.room_id+", was "+e+")");this.unpickleInboundGroupSession(t,(e=>{r(e,t,i)}))}else r(null,null,i)}))}addInboundGroupSession(e,i,n,r,o,d,l,u={}){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,c.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(s=>{this.getInboundGroupSession(e,i,r,s,((c,h)=>{const f=new t.Olm.InboundGroupSession;try{if(l?f.import_session(o):f.create(o),r!=f.session_id())throw new Error("Mismatched group session ID from senderKey: "+i);if(c&&(a.logger.log(`Update for megolm session ${i}|${r}`),c.first_known_index()<=f.first_known_index())){if(!h.untrusted||u.untrusted)return void a.logger.log(`Keeping existing megolm session ${i}|${r}`);if(c.first_known_index()<f.first_known_index())return void(c.export_session(f.first_known_index())===f.export_session(f.first_known_index())?(a.logger.info(`Upgrading trust of existing megolm session ${i}|${r} based on newly-received trusted session`),h.untrusted=!1,this.cryptoStore.storeEndToEndInboundGroupSession(i,r,h,s)):a.logger.warn(`Newly-received megolm session ${i}|$sessionId} does not match existing session! Keeping existing session`))}a.logger.info(`Storing megolm session ${i}|${r} with first index `+f.first_known_index());const t=Object.assign({},u,{room_id:e,session:f.pickle(this.pickleKey),keysClaimed:d,forwardingCurve25519KeyChain:n});this.cryptoStore.storeEndToEndInboundGroupSession(i,r,t,s),!c&&u.sharedHistory&&this.cryptoStore.addSharedHistoryInboundGroupSession(e,i,r,s)}finally{f.free()}}))}),a.logger.withPrefix("[addInboundGroupSession]"))}))}addInboundGroupSessionWithheld(e,t,i,n,r){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(o=>{this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(t,i,{room_id:e,code:n,reason:r},o)}))}))}decryptGroupMessage(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){let s,l=null;if(yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(a=>{this.getInboundGroupSession(e,t,i,a,((e,c,u)=>{if(null===e||null===c)return u&&(s=new d.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",f(u),{session:t+"|"+i})),void(l=null);let h;try{h=e.decrypt(n)}catch(e){return void(s="OLM.UNKNOWN_MESSAGE_INDEX"===(null==e?void 0:e.message)&&u?new d.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",f(u),{session:t+"|"+i}):e)}let p=h.plaintext;if(void 0===p)p=h;else{const e=t+"|"+i+"|"+h.message_index;if(e in this.inboundGroupSessionMessageIndexes){const t=this.inboundGroupSessionMessageIndexes[e];if(t.id!==r||t.timestamp!==o)return void(s=new Error("Duplicate message index, possible replay attack: "+e))}this.inboundGroupSessionMessageIndexes[e]={id:r,timestamp:o}}c.session=e.pickle(this.pickleKey),this.cryptoStore.storeEndToEndInboundGroupSession(t,i,c,a),l={result:p,keysClaimed:c.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:c.forwardingCurve25519KeyChain||[],untrusted:!!c.untrusted}}))}),a.logger.withPrefix("[decryptGroupMessage]")),s)throw s;return l}))}hasInboundSessionKeys(e,t,i){return s(this,void 0,void 0,(function*(){let n;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(r=>{this.cryptoStore.getEndToEndInboundGroupSession(t,i,r,(r=>{null!==r?e!==r.room_id?(a.logger.warn(`requested keys for inbound group session ${t}|${i}, with incorrect room_id (expected ${r.room_id}, was ${e})`),n=!1):n=!0:n=!1}))}),a.logger.withPrefix("[hasInboundSessionKeys]")),n}))}getInboundGroupSessionKey(e,t,i,n){return s(this,void 0,void 0,(function*(){let r=null;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(o=>{this.getInboundGroupSession(e,t,i,o,((e,t)=>{if(null===e||null===t)return void(r=null);void 0===n&&(n=e.first_known_index());const i=e.export_session(n),o=(t.keysClaimed||{}).ed25519||null,s=t.forwardingCurve25519KeyChain||[],a="untrusted"in t?t.untrusted:s.length>0;r={chain_index:n,key:i,forwarding_curve25519_key_chain:s,sender_claimed_ed25519_key:o,shared_history:t.sharedHistory||!1,untrusted:a}}))}),a.logger.withPrefix("[getInboundGroupSessionKey]")),r}))}exportInboundGroupSession(e,t,i){return this.unpickleInboundGroupSession(i,(n=>{const r=n.first_known_index();return{sender_key:e,sender_claimed_keys:i.keysClaimed,room_id:i.room_id,session_id:t,session_key:n.export_session(r),forwarding_curve25519_key_chain:i.forwardingCurve25519KeyChain||[],first_known_index:n.first_known_index(),"org.matrix.msc3061.shared_history":i.sharedHistory||!1}}))}getSharedHistoryInboundGroupSessions(e){return s(this,void 0,void 0,(function*(){let t;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(i=>{t=this.cryptoStore.getSharedHistoryInboundGroupSessions(e,i)}),a.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")),t}))}verifySignature(e,t,i){this.getUtility((function(n){n.ed25519_verify(e,t,i)}))}},i.WITHHELD_MESSAGES={"m.unverified":"The sender has disabled encrypting to unverified devices.","m.blacklisted":"The sender has blocked you.","m.unauthorised":"You are not authorised to read the message.","m.no_olm":"Unable to establish a secure channel."}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":374,"./algorithms":333,"./store/indexeddb-crypto-store":346}],328:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.OutgoingRoomKeyRequestManager=i.RoomKeyRequestState=void 0;const r=e("uuid"),o=e("../logger"),s=e("../@types/event"),a=e("../utils");var c;!function(e){e[e.Unsent=0]="Unsent",e[e.Sent=1]="Sent",e[e.CancellationPending=2]="CancellationPending",e[e.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend"}(c=i.RoomKeyRequestState||(i.RoomKeyRequestState={}));function d(e){return e.room_id+" / "+e.session_id}function l(e){return`[${e.map((e=>`${e.userId}:${e.deviceId}`)).join(",")}]`}i.OutgoingRoomKeyRequestManager=class{constructor(e,t,i){this.baseApis=e,this.deviceId=t,this.cryptoStore=i,this.sendOutgoingRoomKeyRequestsRunning=!1,this.clientRunning=!0}stop(){o.logger.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}queueRoomKeyRequest(e,t,i=!1){return n(this,void 0,void 0,(function*(){const n=yield this.cryptoStore.getOutgoingRoomKeyRequest(e);if(n)switch(n.state){case c.CancellationPendingAndWillResend:case c.Unsent:return;case c.CancellationPending:{const e=i?c.CancellationPendingAndWillResend:c.Sent;yield this.cryptoStore.updateOutgoingRoomKeyRequest(n.requestId,c.CancellationPending,{state:e,cancellationTxnId:this.baseApis.makeTxnId()});break}case c.Sent:if(i){const r=c.CancellationPendingAndWillResend,s=yield this.cryptoStore.updateOutgoingRoomKeyRequest(n.requestId,c.Sent,{state:r,cancellationTxnId:this.baseApis.makeTxnId(),requestTxnId:this.baseApis.makeTxnId()});if(!s)return this.queueRoomKeyRequest(e,t,i);try{yield this.sendOutgoingRoomKeyRequestCancellation(s,!0)}catch(e){o.logger.error("Error sending room key request cancellation; will retry later.",e)}}break;default:throw new Error("unhandled state: "+n.state)}else yield this.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:this.baseApis.makeTxnId(),state:c.Unsent})}))}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then((t=>{if(t)switch(t.state){case c.CancellationPending:case c.CancellationPendingAndWillResend:return;case c.Unsent:return o.logger.log("deleting unnecessary room key request for "+d(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,c.Unsent);case c.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,c.Sent,{state:c.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then((t=>{t?this.sendOutgoingRoomKeyRequestCancellation(t).catch((e=>{o.logger.error("Error sending room key request cancellation; will retry later.",e),this.startTimer()})):o.logger.log("Tried to cancel room key request for "+d(e)+" but it was already cancelled in another tab")}));default:throw new Error("unhandled state: "+t.state)}}))}getOutgoingSentRoomKeyRequest(e,t){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[c.Sent])}cancelAndResendAllOutgoingRequests(){return n(this,void 0,void 0,(function*(){const e=yield this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(c.Sent);return Promise.all(e.map((({requestBody:e,recipients:t})=>this.queueRoomKeyRequest(e,t,!0))))}))}startTimer(){if(this.sendOutgoingRoomKeyRequestsTimer)return;this.sendOutgoingRoomKeyRequestsTimer=setTimeout((()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally((()=>{this.sendOutgoingRoomKeyRequestsRunning=!1})).catch((e=>{o.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`)}))}),500)}sendOutgoingRoomKeyRequests(){return n(this,void 0,void 0,(function*(){if(!this.clientRunning)return void(this.sendOutgoingRoomKeyRequestsTimer=void 0);const e=yield this.cryptoStore.getOutgoingRoomKeyRequestByState([c.CancellationPending,c.CancellationPendingAndWillResend,c.Unsent]);if(e)try{switch(e.state){case c.Unsent:yield this.sendOutgoingRoomKeyRequest(e);break;case c.CancellationPending:yield this.sendOutgoingRoomKeyRequestCancellation(e);break;case c.CancellationPendingAndWillResend:yield this.sendOutgoingRoomKeyRequestCancellation(e,!0)}return this.sendOutgoingRoomKeyRequests()}catch(e){o.logger.error("Error sending room key request; will retry later.",e),this.sendOutgoingRoomKeyRequestsTimer=void 0}else this.sendOutgoingRoomKeyRequestsTimer=void 0}))}sendOutgoingRoomKeyRequest(e){o.logger.log(`Requesting keys for ${d(e.requestBody)} from ${l(e.recipients)}(id ${e.requestId})`);const t={action:"request",requesting_device_id:this.deviceId,request_id:e.requestId,body:e.requestBody};return this.sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then((()=>this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,c.Unsent,{state:c.Sent})))}sendOutgoingRoomKeyRequestCancellation(e,t=!1){o.logger.log(`Sending cancellation for key request for ${d(e.requestBody)} to ${l(e.recipients)} (cancellation id ${e.cancellationTxnId})`);const i={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(i,e.recipients,e.cancellationTxnId).then((()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,c.CancellationPendingAndWillResend,{state:c.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,c.CancellationPending)))}sendMessageToDevices(e,t,i){const n=new a.MapWithDefault((()=>new Map));for(const i of t){n.getOrCreate(i.userId).set(i.deviceId,Object.assign(Object.assign({},e),{[s.ToDeviceMessageId]:(0,r.v4)()}))}return this.baseApis.sendToDevice(s.EventType.RoomKeyRequest,n,i)}}},{"../@types/event":306,"../logger":374,"../utils":416,uuid:287}],329:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomList=void 0;const r=e("./store/indexeddb-crypto-store");i.RoomList=class{constructor(e){this.cryptoStore=e,this.roomEncryption={}}init(){return n(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],(e=>{this.cryptoStore.getEndToEndRooms(e,(e=>{this.roomEncryption=e}))}))}))}getRoomEncryption(e){return this.roomEncryption[e]||null}isRoomEncrypted(e){return Boolean(this.getRoomEncryption(e))}setRoomEncryption(e,t){return n(this,void 0,void 0,(function*(){this.roomEncryption[e]=t,yield this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],(i=>{this.cryptoStore.storeEndToEndRoom(e,t,i)}))}))}}},{"./store/indexeddb-crypto-store":346}],330:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SecretStorage=i.SECRET_STORAGE_ALGORITHM_V1_AES=void 0;const a=e("uuid"),c=e("../logger"),d=o(e("./olmlib")),l=e("../randomstring"),u=e("./aes"),h=e("../client"),f=e("../utils"),p=e("../@types/event");i.SECRET_STORAGE_ALGORITHM_V1_AES="m.secret_storage.v1.aes-hmac-sha2";i.SecretStorage=class{constructor(e,t,i){this.accountDataAdapter=e,this.cryptoCallbacks=t,this.baseApis=i,this.requests=new Map}getDefaultKeyId(){return s(this,void 0,void 0,(function*(){const e=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return e?e.key:null}))}setDefaultKeyId(e){return new Promise(((t,i)=>{const n=i=>{"m.secret_storage.default_key"===i.getType()&&i.getContent().key===e&&(this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,n),t())};this.accountDataAdapter.on(h.ClientEvent.AccountData,n),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch((e=>{this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,n),i(e)}))}))}addKey(e,t={},n){return s(this,void 0,void 0,(function*(){if(e!==i.SECRET_STORAGE_ALGORITHM_V1_AES)throw new Error(`Unknown key algorithm ${e}`);const r={algorithm:e};if(t.name&&(r.name=t.name),t.passphrase&&(r.passphrase=t.passphrase),t.key){const{iv:e,mac:i}=yield(0,u.calculateKeyCheck)(t.key);r.iv=e,r.mac=i}if(!n)do{n=(0,l.randomString)(32)}while(yield this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${n}`));return yield this.accountDataAdapter.setAccountData(`m.secret_storage.key.${n}`,r),{keyId:n,keyInfo:r}}))}getKey(e){return s(this,void 0,void 0,(function*(){if(e||(e=yield this.getDefaultKeyId()),!e)return null;const t=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);return t?[e,t]:null}))}hasKey(e){return s(this,void 0,void 0,(function*(){return Boolean(yield this.getKey(e))}))}checkKey(e,t){return s(this,void 0,void 0,(function*(){if(t.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){if(t.mac){const{mac:i}=yield(0,u.calculateKeyCheck)(e,t.iv);return t.mac.replace(/=+$/g,"")===i.replace(/=+$/g,"")}return!0}throw new Error("Unknown algorithm")}))}store(e,t,n){return s(this,void 0,void 0,(function*(){const r={};if(!n){const e=yield this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");n=[e]}if(0===n.length)throw new Error("Zero keys given to encrypt with!");for(const o of n){const n=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o);if(!n)throw new Error("Unknown key: "+o);if(n.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){const i={[o]:n},[,s]=yield this.getSecretStorageKey(i,e);r[o]=yield s.encrypt(t)}else c.logger.warn("unknown algorithm for secret storage key "+o+": "+n.algorithm)}yield this.accountDataAdapter.setAccountData(e,{encrypted:r})}))}get(e){return s(this,void 0,void 0,(function*(){const t=yield this.accountDataAdapter.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const n={};for(const e of Object.keys(t.encrypted)){const r=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e),o=t.encrypted[e];r.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(n[e]=r)}if(0===Object.keys(n).length)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);const[r,o]=yield this.getSecretStorageKey(n,e),s=t.encrypted[r];return o.decrypt(s)}))}isStored(e){return s(this,void 0,void 0,(function*(){const t=yield this.accountDataAdapter.getAccountDataFromServer(e);if(!(null==t?void 0:t.encrypted))return null;const n={};for(const e of Object.keys(t.encrypted)){const r=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);if(!r)continue;const o=t.encrypted[e];r.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(n[e]=r)}return Object.keys(n).length?n:null}))}request(e,t){const i=this.baseApis.makeTxnId(),n=(0,f.defer)();this.requests.set(i,{name:e,devices:t,deferred:n});const r={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:i,[p.ToDeviceMessageId]:(0,a.v4)()},o=new Map;for(const e of t)o.set(e,r);return c.logger.info(`Request secret ${e} from ${t}, id ${i}`),this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),o]])),{requestId:i,promise:n.promise,cancel:e=>{const r={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:i},o=new Map;for(const e of t)o.set(e,r);this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),o]])),n.reject(new Error(e||"Cancelled"))}}}onRequestReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getSender(),i=e.getContent();if(t!==this.baseApis.getUserId()||!(i.name&&i.action&&i.requesting_device_id&&i.request_id))return;const n=i.requesting_device_id;if("request_cancellation"===i.action);else if("request"===i.action){if(n===this.baseApis.deviceId)return;if(c.logger.info("received request for secret ("+t+", "+n+", "+i.request_id+")"),!this.cryptoCallbacks.onSecretRequested)return;const e=yield this.cryptoCallbacks.onSecretRequested(t,n,i.request_id,i.name,this.baseApis.checkDeviceTrust(t,n));if(e){c.logger.info(`Preparing ${i.name} secret for ${n}`);const r={type:"m.secret.send",content:{request_id:i.request_id,secret:e}},o={algorithm:d.OLM_ALGORITHM,sender_key:this.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{},[p.ToDeviceMessageId]:(0,a.v4)()};yield d.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice,this.baseApis,new Map([[t,[this.baseApis.getStoredDevice(t,n)]]])),yield d.encryptMessageForDevice(o.ciphertext,this.baseApis.getUserId(),this.baseApis.deviceId,this.baseApis.crypto.olmDevice,t,this.baseApis.getStoredDevice(t,n),r);const s=new Map([[t,new Map([[n,o]])]]);c.logger.info(`Sending ${i.name} secret for ${n}`),this.baseApis.sendToDevice("m.room.encrypted",s)}else c.logger.info(`Request denied for ${i.name} secret for ${n}`)}}))}onSecretReceived(e){if(e.getSender()!==this.baseApis.getUserId())return;if(!d.isOlmEncrypted(e))return void c.logger.error("secret event not properly encrypted");const t=e.getContent();if(this.baseApis.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,e.getSenderKey()||"")!==e.getSender())return void c.logger.error("sending device does not belong to the user it claims to be from");c.logger.log("got secret share for request",t.request_id);const i=this.requests.get(t.request_id);if(i){const n=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(d.OLM_ALGORITHM,e.getSenderKey());if(!n)return void c.logger.log("secret share from unknown device with key",e.getSenderKey());if(!i.devices.includes(n.deviceId))return void c.logger.log("unsolicited secret share from device",n.deviceId);if(!this.baseApis.crypto.checkDeviceInfoTrust(e.getSender(),n).isVerified())return void c.logger.log("secret share from unverified device");c.logger.log(`Successfully received secret ${i.name} from ${n.deviceId}`),i.deferred.resolve(t.secret)}}getSecretStorageKey(e,t){return s(this,void 0,void 0,(function*(){if(!this.cryptoCallbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const n=yield this.cryptoCallbacks.getSecretStorageKey({keys:e},t);if(!n)throw new Error("getSecretStorageKey callback returned falsey");if(n.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[r,o]=n;if(!e[r])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[r].algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){return[r,{encrypt:function(e){return(0,u.encryptAES)(e,o,t)},decrypt:function(e){return(0,u.decryptAES)(e,o,t)}}]}throw new Error("Unknown key type: "+e[r].algorithm)}))}}},{"../@types/event":306,"../client":321,"../logger":374,"../randomstring":398,"../utils":416,"./aes":331,"./olmlib":343,uuid:287}],331:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.calculateKeyCheck=i.decryptAES=i.encryptAES=void 0;const r=e("./olmlib"),o=e("./crypto"),s=new Uint8Array(8);function a(e,t,i,s){return n(this,void 0,void 0,(function*(){let n;s?n=(0,r.decodeBase64)(s):(n=new Uint8Array(16),o.crypto.getRandomValues(n),n[8]&=127);const[a,d]=yield c(t,i),l=(new o.TextEncoder).encode(e),u=yield o.subtleCrypto.encrypt({name:"AES-CTR",counter:n,length:64},a,l),h=yield o.subtleCrypto.sign({name:"HMAC"},d,u);return{iv:(0,r.encodeBase64)(n),ciphertext:(0,r.encodeBase64)(u),mac:(0,r.encodeBase64)(h)}}))}function c(e,t){return n(this,void 0,void 0,(function*(){const i=yield o.subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),n=yield o.subtleCrypto.deriveBits({name:"HKDF",salt:s,info:(new o.TextEncoder).encode(t),hash:"SHA-256"},i,512),r=n.slice(0,32),a=n.slice(32),c=o.subtleCrypto.importKey("raw",r,{name:"AES-CTR"},!1,["encrypt","decrypt"]),d=o.subtleCrypto.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([c,d])}))}i.encryptAES=a,i.decryptAES=function(e,t,i){return n(this,void 0,void 0,(function*(){const[n,s]=yield c(t,i),a=(0,r.decodeBase64)(e.ciphertext);if(!(yield o.subtleCrypto.verify({name:"HMAC"},s,(0,r.decodeBase64)(e.mac),a)))throw new Error(`Error decrypting secret ${i}: bad MAC`);const d=yield o.subtleCrypto.decrypt({name:"AES-CTR",counter:(0,r.decodeBase64)(e.iv),length:64},n,a);return(new TextDecoder).decode(new Uint8Array(d))}))};const d="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";i.calculateKeyCheck=function(e,t){return a(d,e,"",t)}},{"./crypto":338,"./olmlib":343}],332:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.registerAlgorithm=i.UnknownDeviceError=i.DecryptionError=i.DecryptionAlgorithm=i.EncryptionAlgorithm=i.DECRYPTION_CLASSES=i.ENCRYPTION_CLASSES=void 0,i.ENCRYPTION_CLASSES=new Map,i.DECRYPTION_CLASSES=new Map;i.EncryptionAlgorithm=class{constructor(e){this.userId=e.userId,this.deviceId=e.deviceId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}prepareToEncrypt(e){}onRoomMembership(e,t,i){}};i.DecryptionAlgorithm=class{constructor(e){this.userId=e.userId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}onRoomKeyEvent(e){return n(this,void 0,void 0,(function*(){}))}importRoomKey(e,t){return n(this,void 0,void 0,(function*(){}))}hasKeysForKeyRequest(e){return Promise.resolve(!1)}shareKeysWithDevice(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}retryDecryptionFromSender(e){return n(this,void 0,void 0,(function*(){return!1}))}};class r extends Error{constructor(e,t,i){super(t),this.code=e,this.code=e,this.name="DecryptionError",this.detailedString=function(e,t){let i=e.name+"[msg: "+e.message;t&&(i+=", "+Object.keys(t).map((e=>e+": "+t[e])).join(", "));return i+="]",i}(this,i)}}i.DecryptionError=r;class o extends Error{constructor(e,t,i){super(e),this.devices=t,this.event=i,this.name="UnknownDeviceError",this.devices=t}}i.UnknownDeviceError=o,i.registerAlgorithm=function(e,t,n){i.ENCRYPTION_CLASSES.set(e,t),i.DECRYPTION_CLASSES.set(e,n)}},{}],333:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),e("./olm"),e("./megolm"),r(e("./base"),i)},{"./base":332,"./megolm":334,"./olm":335}],334:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MegolmDecryption=i.MegolmEncryption=i.isRoomSharedHistory=void 0;const a=e("uuid"),c=e("../../logger"),d=o(e("../olmlib")),l=e("./base"),u=e("../OlmDevice"),h=e("../../@types/event"),f=e("../OutgoingRoomKeyRequestManager"),p=e("../../utils");function g(e){var t,i;const n=null===(t=null==e?void 0:e.currentState)||void 0===t?void 0:t.getStateEvents("m.room.history_visibility",""),r=null===(i=null==n?void 0:n.getContent())||void 0===i?void 0:i.history_visibility;return["world_readable","shared"].includes(r)}i.isRoomSharedHistory=g;const v=e=>"string"==typeof e.ciphertext?!!e.ciphertext.length:!!Object.keys(e.ciphertext).length;class m{constructor(e,t=!1){this.sessionId=e,this.sharedHistory=t,this.useCount=0,this.sharedWithDevices=new p.MapWithDefault((()=>new Map)),this.blockedDevicesNotified=new p.MapWithDefault((()=>new Map)),this.creationTime=(new Date).getTime()}needsRotation(e,t){const i=(new Date).getTime()-this.creationTime;return(this.useCount>=e||i>=t)&&(c.logger.log("Rotating megolm session after "+this.useCount+" messages, "+i+"ms"),!0)}markSharedWithDevice(e,t,i,n){this.sharedWithDevices.getOrCreate(e).set(t,{deviceKey:i,messageIndex:n})}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified.getOrCreate(e).set(t,!0)}sharedWithTooManyDevices(e){var t;for(const[i,n]of this.sharedWithDevices){if(!e.has(i))return c.logger.log("Starting new megolm session because we shared with "+i),!0;for(const[r]of n)if(!(null===(t=e.get(i))||void 0===t?void 0:t.get(r)))return c.logger.log("Starting new megolm session because we shared with "+i+":"+r),!0}return!1}}class y extends l.EncryptionAlgorithm{constructor(e){var t,i,n,r;super(e),this.setupPromise=Promise.resolve(null),this.outboundSessions={},this.roomId=e.roomId,this.prefixedLogger=c.logger.withPrefix(`[${this.roomId} encryption]`),this.sessionRotationPeriodMsgs=null!==(i=null===(t=e.config)||void 0===t?void 0:t.rotation_period_msgs)&&void 0!==i?i:100,this.sessionRotationPeriodMs=null!==(r=null===(n=e.config)||void 0===n?void 0:n.rotation_period_ms)&&void 0!==r?r:6048e5}ensureOutboundSession(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){const r=this.setupPromise.then((r=>s(this,void 0,void 0,(function*(){const o=g(e),s=yield this.prepareSession(t,o,r);return yield this.shareSession(t,o,n,i,s),s}))));return this.setupPromise=r.catch((e=>(this.prefixedLogger.error("Failed to setup outbound session",e),null))),r}))}prepareSession(e,t,i){return s(this,void 0,void 0,(function*(){return i&&t!==i.sharedHistory&&(i=null),(null==i?void 0:i.needsRotation(this.sessionRotationPeriodMsgs,this.sessionRotationPeriodMs))&&(this.prefixedLogger.log("Starting new megolm session because we need to rotate."),i=null),(null==i?void 0:i.sharedWithTooManyDevices(e))&&(i=null),i||(this.prefixedLogger.log("Starting new megolm session"),i=yield this.prepareNewSession(t),this.prefixedLogger.log(`Started new megolm session ${i.sessionId}`),this.outboundSessions[i.sessionId]=i),i}))}shareSession(e,t,i,n,r){var o;return s(this,void 0,void 0,(function*(){const a={};for(const[t,i]of e)for(const[e,n]of i){n.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&((null===(o=r.sharedWithDevices.get(t))||void 0===o?void 0:o.get(e))||(a[t]=a[t]||[],a[t].push(n)))}const c=this.olmDevice.getOutboundGroupSessionKey(r.sessionId),l={type:"m.room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:r.sessionId,session_key:c.key,chain_index:c.chain_index,"org.matrix.msc3061.shared_history":t}},[u,h]=yield d.getExistingOlmSessions(this.olmDevice,this.baseApis,a);yield Promise.all([(()=>s(this,void 0,void 0,(function*(){const e=Array.from(h.entries()).map((([e,t])=>Array.from(t.entries()).map((([t,i])=>`${e}/${t}: ${i.sessionId}`)))).flat(1);this.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:",e),yield this.shareKeyWithOlmSessions(r,c,l,h),this.prefixedLogger.debug("Shared keys with existing Olm sessions")})))(),(()=>s(this,void 0,void 0,(function*(){const e=Array.from(u.entries()).map((([e,t])=>t.map((t=>`${e}/${t.deviceId}`)))).flat(1);this.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:",e);const t=[],n=Date.now(),o=[];yield this.shareKeyWithDevices(r,c,l,u,t,i?1e4:2e3,o),this.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions"),!i&&Date.now()-n<1e4?(()=>{s(this,void 0,void 0,(function*(){const e=new p.MapWithDefault((()=>[])),i=new Set;for(const e of o)i.add(e);const n=[];for(const{userId:r,deviceInfo:o}of t){const t=r.slice(r.indexOf(":")+1);i.has(t)?e.getOrCreate(r).push(o):n.push({userId:r,deviceInfo:o})}const s=Array.from(e.entries()).map((([e,t])=>t.map((t=>`${e}/${t.deviceId}`)))).flat(1);s.length>0&&(this.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:",s),yield this.shareKeyWithDevices(r,c,l,e,n,3e4),this.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions")),yield this.notifyFailedOlmDevices(r,c,n)}))})():yield this.notifyFailedOlmDevices(r,c,t)})))(),(()=>s(this,void 0,void 0,(function*(){var e;this.prefixedLogger.debug(`There are ${n.size} blocked devices:`,Array.from(n.entries()).map((([e,t])=>Array.from(t.entries()).map((([t,i])=>`${e}/${t}`)))).flat(1));const t=new p.MapWithDefault((()=>new Map));let i=0;for(const[o,s]of n)for(const[n,a]of s)void 0===(null===(e=r.blockedDevicesNotified.get(o))||void 0===e?void 0:e.get(n))&&(t.getOrCreate(o).set(n,{device:a}),i++);i&&(this.prefixedLogger.debug(`Notifying ${i} newly blocked devices:`,Array.from(t.entries()).map((([e,t])=>Object.entries(t).map((([t,i])=>`${e}/${t}`)))).flat(1)),yield this.notifyBlockedDevices(r,t),this.prefixedLogger.debug(`Notified ${i} newly blocked devices`))})))()])}))}prepareNewSession(e){return s(this,void 0,void 0,(function*(){const t=this.olmDevice.createOutboundGroupSession(),i=this.olmDevice.getOutboundGroupSessionKey(t);return yield this.olmDevice.addInboundGroupSession(this.roomId,this.olmDevice.deviceCurve25519Key,[],t,i.key,{ed25519:this.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key,t),new m(t,e)}))}getDevicesWithoutSessions(e,t,i=[]){for(const[n,r]of t){const t=e.get(n);for(const e of r){const r=e.deviceId,o=null==t?void 0:t.get(r);(null==o?void 0:o.sessionId)||(i.push({userId:n,deviceInfo:e}),null==t||t.delete(r))}}return i}splitDevices(e){let t=[];const i=[t];for(const[n,r]of e){for(const e of r.values())t.push({userId:n,deviceInfo:e.device});t.length>20&&(t=[],i.push(t))}return 0===t.length&&i.pop(),i}encryptAndSendKeysToDevices(e,t,i,n){return this.crypto.encryptAndSendToDevices(i,n).then((()=>{for(const n of i)e.markSharedWithDevice(n.userId,n.deviceInfo.deviceId,n.deviceInfo.getIdentityKey(),t)})).catch((e=>{throw this.prefixedLogger.error("failed to encryptAndSendToDevices",e),e}))}sendBlockedNotificationsToDevices(e,t,i){return s(this,void 0,void 0,(function*(){const n=new p.MapWithDefault((()=>new Map));for(const e of t){const t=e.userId,r=e.deviceInfo,o=r.deviceInfo.deviceId,s=Object.assign(Object.assign({},i),{code:r.code,reason:r.reason,[h.ToDeviceMessageId]:(0,a.v4)()});"m.no_olm"===s.code&&(delete s.room_id,delete s.session_id),n.getOrCreate(t).set(o,s)}yield this.baseApis.sendToDevice("m.room_key.withheld",n);for(const[t,i]of n)for(const n of i.keys())e.markNotifiedBlockedDevice(t,n)}))}reshareKeyWithDevice(e,t,i,n){var r;return s(this,void 0,void 0,(function*(){const o=this.outboundSessions[t];if(!o)return void this.prefixedLogger.debug(`megolm session ${e}|${t} not found: not re-sharing keys`);if(!o.sharedWithDevices.has(i))return void this.prefixedLogger.debug(`megolm session ${e}|${t} never shared with user ${i}`);const s=null===(r=o.sharedWithDevices.get(i))||void 0===r?void 0:r.get(n.deviceId);if(void 0===s)return void this.prefixedLogger.debug(`megolm session ${e}|${t} never shared with device ${i}:${n.deviceId}`);if(s.deviceKey!==n.getIdentityKey())return void this.prefixedLogger.warn(`Megolm session ${e}|${t} has been shared with device ${n.deviceId} but with identity key ${s.deviceKey}. Key is now ${n.getIdentityKey()}!`);const c=yield this.olmDevice.getInboundGroupSessionKey(this.roomId,e,t,s.messageIndex);if(!c)return void this.prefixedLogger.warn(`No inbound session key found for megolm session ${e}|${t}: not re-sharing keys`);yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[i,[n]]]));const l={type:"m.forwarded_room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":c.shared_history||!1}},u={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};yield d.encryptMessageForDevice(u.ciphertext,this.userId,this.deviceId,this.olmDevice,i,n,l),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[n.deviceId,u]])]])),this.prefixedLogger.debug(`Re-shared key for megolm session ${e}|${t} with ${i}:${n.deviceId}`)}))}shareKeyWithDevices(e,t,i,n,r,o,a){return s(this,void 0,void 0,(function*(){const s=yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,n,!1,o,a,this.prefixedLogger);this.getDevicesWithoutSessions(s,n,r),yield this.shareKeyWithOlmSessions(e,t,i,s)}))}shareKeyWithOlmSessions(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=this.splitDevices(n);for(let n=0;n<r.length;n++){const o=`megolm keys for ${e.sessionId} (slice ${n+1}/${r.length})`;try{this.prefixedLogger.debug(`Sharing ${o}`,r[n].map((e=>`${e.userId}/${e.deviceInfo.deviceId}`))),yield this.encryptAndSendKeysToDevices(e,t.chain_index,r[n],i),this.prefixedLogger.debug(`Shared ${o}`)}catch(e){throw this.prefixedLogger.error(`Failed to share ${o}`),e}}}))}notifyFailedOlmDevices(e,t,i){return s(this,void 0,void 0,(function*(){this.prefixedLogger.debug(`Notifying ${i.length} devices we failed to create Olm sessions`);for(const{userId:n,deviceInfo:r}of i){const i=r.deviceId;e.markSharedWithDevice(n,i,r.getIdentityKey(),t.chain_index)}const n=yield this.olmDevice.filterOutNotifiedErrorDevices(i);this.prefixedLogger.debug(`Need to notify ${n.length} failed devices which haven't been notified before`);const r=new p.MapWithDefault((()=>new Map));for(const{userId:e,deviceInfo:t}of n)r.getOrCreate(e).set(t.deviceId,{device:{code:"m.no_olm",reason:u.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:t}});yield this.notifyBlockedDevices(e,r),this.prefixedLogger.debug(`Notified ${n.length} devices we failed to create Olm sessions`)}))}notifyBlockedDevices(e,t){return s(this,void 0,void 0,(function*(){const i={room_id:this.roomId,session_id:e.sessionId,algorithm:d.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key},n=this.splitDevices(t);for(let t=0;t<n.length;t++)try{yield this.sendBlockedNotificationsToDevices(e,n[t],i),this.prefixedLogger.log(`Completed blacklist notification for ${e.sessionId} (slice ${t+1}/${n.length})`)}catch(i){throw this.prefixedLogger.log(`blacklist notification for ${e.sessionId} (slice ${t+1}/${n.length}) failed`),i}}))}prepareToEncrypt(e){if(e.roomId!==this.roomId)throw new Error("MegolmEncryption.prepareToEncrypt called on unexpected room");if(null!=this.encryptionPreparation){const e=Date.now()-this.encryptionPreparation.startTime;return this.prefixedLogger.debug(`Already started preparing to encrypt for this room ${e}ms ago, skipping`),this.encryptionPreparation.cancel}this.prefixedLogger.debug("Preparing to encrypt events");let t=!1;const i=()=>t;return this.encryptionPreparation={startTime:Date.now(),promise:(()=>s(this,void 0,void 0,(function*(){try{const t=yield this.getDevicesInRoom(e,!1,i);if(null===t)return;const[n,r]=t;this.crypto.globalErrorOnUnknownDevices&&this.removeUnknownDevices(n),this.prefixedLogger.debug("Ensuring outbound megolm session"),yield this.ensureOutboundSession(e,n,r,!0),this.prefixedLogger.debug("Ready to encrypt events")}catch(e){this.prefixedLogger.error("Failed to prepare to encrypt events",e)}finally{delete this.encryptionPreparation}})))(),cancel:()=>{t=!0,delete this.encryptionPreparation}},this.encryptionPreparation.cancel}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){if(this.prefixedLogger.log("Starting to encrypt event"),null!=this.encryptionPreparation)try{yield this.encryptionPreparation.promise}catch(e){}const n=this.isVerificationEvent(t,i),[r,o]=yield this.getDevicesInRoom(e,n);this.crypto.globalErrorOnUnknownDevices&&this.checkForUnknownDevices(r);const s=yield this.ensureOutboundSession(e,r,o),a={room_id:this.roomId,type:t,content:i},c=this.olmDevice.encryptGroupMessage(s.sessionId,JSON.stringify(a)),l={algorithm:d.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:c,session_id:s.sessionId,device_id:this.deviceId};return s.useCount++,l}))}isVerificationEvent(e,t){switch(e){case h.EventType.KeyVerificationCancel:case h.EventType.KeyVerificationDone:case h.EventType.KeyVerificationMac:case h.EventType.KeyVerificationStart:case h.EventType.KeyVerificationKey:case h.EventType.KeyVerificationReady:case h.EventType.KeyVerificationAccept:return!0;case h.EventType.RoomMessage:return t.msgtype===h.MsgType.KeyVerificationRequest;default:return!1}}forceDiscardSession(){this.setupPromise=this.setupPromise.then((()=>null))}checkForUnknownDevices(e){const t=new p.MapWithDefault((()=>new Map));for(const[i,n]of e)for(const[e,r]of n)r.isUnverified()&&!r.isKnown()&&t.getOrCreate(i).set(e,r);if(t.size)throw new l.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)}removeUnknownDevices(e){for(const[t,i]of e){for(const[e,t]of i)t.isUnverified()&&!t.isKnown()&&i.delete(e);0===i.size&&e.delete(t)}}getDevicesInRoom(e,t=!1,i){return s(this,void 0,void 0,(function*(){const n=yield e.getEncryptionTargetMembers();this.prefixedLogger.debug(`Encrypting for users (shouldEncryptForInvitedMembers: ${e.shouldEncryptForInvitedMembers()}):`,n.map((e=>`${e.userId} (${e.membership})`)));const r=n.map((function(e){return e.userId}));let o=this.crypto.globalBlacklistUnverifiedDevices;const s=e.getBlacklistUnverifiedDevices();"boolean"==typeof s&&(o=s);const a=yield this.crypto.downloadKeys(r,!1);if(!0===(null==i?void 0:i()))return null;const c=new p.MapWithDefault((()=>new Map));for(const[e,n]of a)for(const[r,s]of n){if(void 0!==i&&(yield(0,p.immediate)()),!0===(null==i?void 0:i()))return null;const a=this.crypto.checkDeviceTrust(e,r);if(s.isBlocked()||!a.isVerified()&&o&&!t){const t=c.getOrCreate(e),i=s.isBlocked();t.set(r,{code:i?"m.blacklisted":"m.unverified",reason:u.WITHHELD_MESSAGES[i?"m.blacklisted":"m.unverified"],deviceInfo:s}),n.delete(r)}}return[a,c]}))}}i.MegolmEncryption=y;class b extends l.DecryptionAlgorithm{constructor(e){super(e),this.pendingEvents=new Map,this.olmlib=d,this.roomId=e.roomId,this.prefixedLogger=c.logger.withPrefix(`[${this.roomId} decryption]`)}decryptEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getWireContent();if(!t.sender_key||!t.session_id||!t.ciphertext)throw new l.DecryptionError("MEGOLM_MISSING_FIELDS","Missing fields in input");let i;this.addEventToPendingList(e);try{i=yield this.olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext,e.getId(),e.getTs())}catch(i){if("DecryptionError"===i.name)throw i;let n="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw"OLM.UNKNOWN_MESSAGE_INDEX"===(null==i?void 0:i.message)&&(this.requestKeysForEvent(e),n="OLM_UNKNOWN_MESSAGE_INDEX"),new l.DecryptionError(n,i instanceof Error?i.message:"Unknown Error: Error is undefined",{session:t.sender_key+"|"+t.session_id})}if(null===i){this.crypto.backupManager.queryKeyBackupRateLimited(e.getRoomId(),t.session_id).catch((()=>{})),this.requestKeysForEvent(e);const i=yield this.olmDevice.sessionMayHaveProblems(t.sender_key,e.getTs()-12e4);if(i){this.prefixedLogger.info(`When handling UISI from ${e.getSender()} (sender key ${t.sender_key}): recent session problem with that sender:`,i);let n=S[i.type]||S.unknown;throw i.fixed&&(n+=" Trying to create a new secure channel and re-requesting the keys."),new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",n,{session:t.sender_key+"|"+t.session_id})}throw new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID","The sender's device has not sent us the keys for this message.",{session:t.sender_key+"|"+t.session_id})}i.untrusted||this.removeEventFromPendingList(e);const n=JSON.parse(i.result);if(n.room_id!==e.getRoomId())throw new l.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+n.room_id);return{clearEvent:n,senderCurve25519Key:i.senderKey,claimedEd25519Key:i.keysClaimed.ed25519,forwardingCurve25519KeyChain:i.forwardingCurve25519KeyChain,untrusted:i.untrusted}}))}requestKeysForEvent(e){const t=e.getWireContent(),i=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},i)}addEventToPendingList(e){var t;const i=e.getWireContent(),n=i.sender_key,r=i.session_id;this.pendingEvents.has(n)||this.pendingEvents.set(n,new Map);const o=this.pendingEvents.get(n);o.has(r)||o.set(r,new Set),null===(t=o.get(r))||void 0===t||t.add(e)}removeEventFromPendingList(e){const t=e.getWireContent(),i=t.sender_key,n=t.session_id,r=this.pendingEvents.get(i),o=null==r?void 0:r.get(n);o&&(o.delete(e),0===o.size&&r.delete(n),0===r.size&&this.pendingEvents.delete(i))}roomKeyFromEvent(e){const t=e.getSenderKey(),i=e.getContent(),n={};if(!(i.room_id&&i.session_key&&i.session_id&&i.algorithm))return void this.prefixedLogger.error("key event is missing fields");if(!d.isOlmEncrypted(e))return void this.prefixedLogger.error("key event not properly encrypted");i["org.matrix.msc3061.shared_history"]&&(n.sharedHistory=!0);return{senderKey:t,sessionId:i.session_id,sessionKey:i.session_key,extraSessionData:n,exportFormat:!1,roomId:i.room_id,algorithm:i.algorithm,forwardingKeyChain:[],keysClaimed:e.getKeysClaimed()}}forwardedRoomKeyFromEvent(e){const t=this.roomKeyFromEvent(e);if(!t)return;const i=e.getSenderKey(),n=e.getContent(),r=this.baseApis.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,i),o=n.sender_key,s=n.sender_claimed_ed25519_key;let a=Array.isArray(n.forwarding_curve25519_key_chain)?n.forwarding_curve25519_key_chain:[];if(a=a.slice(),a.push(i),r!==e.getSender())return void this.prefixedLogger.error("sending device does not belong to the user it claims to be from");if(!o)return void this.prefixedLogger.error("forwarded_room_key event is missing sender_key field");if(!s)return void this.prefixedLogger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");const c={ed25519:s};return t.senderKey=o,t.keysClaimed=c,t.exportFormat=!0,t.forwardingKeyChain=a,t.extraSessionData.untrusted=!0,t}shouldAcceptForwardedKey(e,t){var i;return s(this,void 0,void 0,(function*(){const n=e.getSenderKey(),r=null!==(i=this.crypto.deviceList.getDeviceByIdentityKey(d.OLM_ALGORITHM,n))&&void 0!==i?i:void 0,o=this.crypto.checkDeviceInfoTrust(e.getSender(),r),s=e.getSender()===this.baseApis.getUserId(),a=o.isVerified()&&s,c=yield this.wasRoomKeyRequested(e,t),l=this.wasRoomKeyForwardedByInviter(e,t),u=this.wasRoomKeyForwardedAsHistory(t);return c&&a||l&&u}))}wasRoomKeyRequested(e,t){return s(this,void 0,void 0,(function*(){return(yield this.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e.getSender(),"*",[f.RoomKeyRequestState.Sent])).some((e=>e.requestBody.room_id===t.roomId&&e.requestBody.session_id===t.sessionId))}))}wasRoomKeyForwardedByInviter(e,t){var i,n,r;const o=this.baseApis.getRoom(t.roomId),s=e.getSenderKey();if(!s)return!1;const a=this.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,s);if(!a)return!1;const c=null===(i=null==o?void 0:o.getMember(this.userId))||void 0===i?void 0:i.events.member,l=(null==c?void 0:c.getSender())===a||(null===(n=null==c?void 0:c.getUnsigned())||void 0===n?void 0:n.prev_sender)===a&&"invite"===(null===(r=null==c?void 0:c.getPrevContent())||void 0===r?void 0:r.membership);return!(!o||!l)}wasRoomKeyForwardedAsHistory(e){return!(!this.baseApis.getRoom(e.roomId)||!e.extraSessionData.sharedHistory)}shouldParkForwardedKey(e){return!(this.baseApis.getRoom(e.roomId)||!e.extraSessionData.sharedHistory)}parkForwardedKey(e,t){return s(this,void 0,void 0,(function*(){const i={senderId:e.getSender(),senderKey:t.senderKey,sessionId:t.sessionId,sessionKey:t.sessionKey,keysClaimed:t.keysClaimed,forwardingCurve25519KeyChain:t.forwardingKeyChain};yield this.crypto.cryptoStore.doTxn("readwrite",["parked_shared_history"],(e=>this.crypto.cryptoStore.addParkedSharedHistory(t.roomId,i,e)),c.logger.withPrefix("[addParkedSharedHistory]"))}))}addRoomKey(e){return s(this,void 0,void 0,(function*(){try{yield this.olmDevice.addInboundGroupSession(e.roomId,e.senderKey,e.forwardingKeyChain,e.sessionId,e.sessionKey,e.keysClaimed,e.exportFormat,e.extraSessionData),(yield this.retryDecryption(e.senderKey,e.sessionId,!e.extraSessionData.untrusted))&&this.crypto.cancelRoomKeyRequest({algorithm:e.algorithm,room_id:e.roomId,session_id:e.sessionId,sender_key:e.senderKey}),yield this.crypto.backupManager.backupGroupSession(e.senderKey,e.sessionId)}catch(e){this.prefixedLogger.error(`Error handling m.room_key_event: ${e}`)}}))}onForwardedRoomKey(e){return s(this,void 0,void 0,(function*(){const t=this.forwardedRoomKeyFromEvent(e);t&&((yield this.shouldAcceptForwardedKey(e,t))?yield this.addRoomKey(t):this.shouldParkForwardedKey(t)&&(yield this.parkForwardedKey(e,t)))}))}onRoomKeyEvent(e){return s(this,void 0,void 0,(function*(){if("m.forwarded_room_key"==e.getType())yield this.onForwardedRoomKey(e);else{const t=this.roomKeyFromEvent(e);if(!t)return;yield this.addRoomKey(t)}}))}onRoomKeyWithheldEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),i=t.sender_key;"m.no_olm"===t.code?yield this.onNoOlmWithheldEvent(e):"m.unavailable"===t.code||(yield this.olmDevice.addInboundGroupSessionWithheld(t.room_id,i,t.session_id,t.code,t.reason)),t.session_id?yield this.retryDecryption(i,t.session_id):yield this.retryDecryptionFromSender(i)}))}onNoOlmWithheldEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),i=t.sender_key,n=e.getSender();if(this.prefixedLogger.warn(`${n}:${i} was unable to establish an olm session with us`),yield this.olmDevice.getSessionIdForDevice(i))return this.prefixedLogger.debug("New session already created. Not creating a new one."),void(yield this.olmDevice.recordSessionProblem(i,"no_olm",!0));let r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,i);if(!r&&(yield this.crypto.downloadKeys([n],!1),r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,i),!r))return this.prefixedLogger.info("Couldn't find device for identity key "+i+": not establishing session"),void(yield this.olmDevice.recordSessionProblem(i,"no_olm",!1));yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[n,[r]]]),!1);const o={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};yield d.encryptMessageForDevice(o.ciphertext,this.userId,void 0,this.olmDevice,n,r,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(i,"no_olm",!0),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[n,new Map([[r.deviceId,o]])]]))}))}hasKeysForKeyRequest(e){const t=e.requestBody;return this.olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)}shareKeysWithDevice(e){const t=e.userId,i=e.deviceId,n=this.crypto.getStoredDevice(t,i),r=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[t,[n]]])).then((e=>{var n;const o=null===(n=e.get(t))||void 0===n?void 0:n.get(i);return(null==o?void 0:o.sessionId)?(this.prefixedLogger.log("sharing keys for session "+r.sender_key+"|"+r.session_id+" with device "+t+":"+i),this.buildKeyForwardingMessage(r.room_id,r.sender_key,r.session_id)):null})).then((e=>{const r={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};return this.olmlib.encryptMessageForDevice(r.ciphertext,this.userId,void 0,this.olmDevice,t,n,e).then((()=>this.baseApis.sendToDevice("m.room.encrypted",new Map([[t,new Map([[i,r]])]]))))}))}buildKeyForwardingMessage(e,t,i){return s(this,void 0,void 0,(function*(){const n=yield this.olmDevice.getInboundGroupSessionKey(e,t,i);return{type:"m.forwarded_room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:e,sender_key:t,sender_claimed_ed25519_key:n.sender_claimed_ed25519_key,session_id:i,session_key:n.key,chain_index:n.chain_index,forwarding_curve25519_key_chain:n.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":n.shared_history||!1}}}))}importRoomKey(e,{untrusted:t,source:i}={}){const n={};return(t||e.untrusted)&&(n.untrusted=!0),e["org.matrix.msc3061.shared_history"]&&(n.sharedHistory=!0),this.olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0,n).then((()=>{"backup"!==i&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch((e=>{this.prefixedLogger.log("Failed to back up megolm session",e)})),this.retryDecryption(e.sender_key,e.session_id,!n.untrusted)}))}retryDecryption(e,t,i){var n;return s(this,void 0,void 0,(function*(){const r=this.pendingEvents.get(e);if(!r)return!0;const o=r.get(t);if(!o)return!0;const a=[...o];return this.prefixedLogger.debug("Retrying decryption on events:",a.map((e=>`${e.getId()}`))),yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto,{isRetry:!0,forceRedecryptIfUntrusted:i})}catch(e){}}))))),!(null===(n=this.pendingEvents.get(e))||void 0===n?void 0:n.has(t))}))}retryDecryptionFromSender(e){return s(this,void 0,void 0,(function*(){const t=this.pendingEvents.get(e);return!t||(this.pendingEvents.delete(e),yield Promise.all([...t].map((([e,t])=>s(this,void 0,void 0,(function*(){yield Promise.all([...t].map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto)}catch(e){}})))))}))))),!this.pendingEvents.has(e))}))}sendSharedHistoryInboundSessions(e){return s(this,void 0,void 0,(function*(){yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,e);const t=yield this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);this.prefixedLogger.log(`Sharing history in with users ${Array.from(e.keys())}`,t.map((([e,t])=>`${e}|${t}`)));for(const[i,n]of t){const t=yield this.buildKeyForwardingMessage(this.roomId,i,n),r=[],o=new Map;for(const[i,n]of e){const e=new Map;o.set(i,e);for(const o of n){const n={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};e.set(o.deviceId,n),r.push(d.encryptMessageForDevice(n.ciphertext,this.userId,void 0,this.olmDevice,i,o,t))}}yield Promise.all(r);for(const[e,t]of o){for(const[i,n]of t)v(n)||(this.prefixedLogger.log("No ciphertext for device "+e+":"+i+": pruning"),t.delete(i));0===t.size&&(this.prefixedLogger.log("Pruned all devices for user "+e),o.delete(e))}if(0===o.size)return void this.prefixedLogger.log("No users left to send to: aborting");yield this.baseApis.sendToDevice("m.room.encrypted",o)}}))}}i.MegolmDecryption=b;const S={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};(0,l.registerAlgorithm)(d.MEGOLM_ALGORITHM,y,b)},{"../../@types/event":306,"../../logger":374,"../../utils":416,"../OlmDevice":327,"../OutgoingRoomKeyRequestManager":328,"../olmlib":343,"./base":332,uuid:287}],335:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0});const a=e("../../logger"),c=o(e("../olmlib")),d=e("../deviceinfo"),l=e("./base"),u=d.DeviceInfo.DeviceVerification;class h extends l.EncryptionAlgorithm{constructor(){super(...arguments),this.sessionPrepared=!1,this.prepPromise=null}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then((()=>this.crypto.ensureOlmSessionsForUsers(e))).then((()=>{this.sessionPrepared=!0})).finally((()=>{this.prepPromise=null})),this.prepPromise)}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){const n=(yield e.getEncryptionTargetMembers()).map((function(e){return e.userId}));yield this.ensureSession(n);const r={room_id:e.roomId,type:t,content:i},o={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},s=[];for(const e of n){const t=this.crypto.getStoredDevicesForUser(e)||[];for(const i of t){i.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(i.verified!=u.BLOCKED&&s.push(c.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,e,i,r)))}}return Promise.all(s).then((()=>o))}))}}class f extends l.DecryptionAlgorithm{decryptEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getWireContent(),i=t.sender_key,n=t.ciphertext;if(!n)throw new l.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in n))throw new l.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const r=n[this.olmDevice.deviceCurve25519Key];let o;try{o=yield this.decryptMessage(i,r)}catch(e){throw new l.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:i,err:e})}const s=JSON.parse(o);if(s.recipient!=this.userId)throw new l.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+s.recipient);if(s.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new l.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:s.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});yield this.crypto.deviceList.downloadKeys([e.getSender()],!1);const a=this.crypto.deviceList.getUserByIdentityKey(c.OLM_ALGORITHM,i);if(a!==e.getSender()&&null!=a)throw new l.DecryptionError("OLM_BAD_SENDER","Message claimed to be from "+e.getSender(),{real_sender:a});if(s.sender!=e.getSender())throw new l.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+s.sender,{reported_sender:e.getSender()});if(s.room_id!==e.getRoomId())throw new l.DecryptionError("OLM_BAD_ROOM","Message intended for room "+s.room_id,{reported_room:e.getRoomId()||"ROOM_ID_UNDEFINED"});return{clearEvent:s,senderCurve25519Key:i,claimedEd25519Key:(s.keys||{}).ed25519||null}}))}decryptMessage(e,t){if(0!==t.type)return this.reallyDecryptMessage(e,t);{const i=this.olmDevice.olmPrekeyPromise.then((()=>this.reallyDecryptMessage(e,t)));return this.olmDevice.olmPrekeyPromise=i.catch((()=>{})),i}}reallyDecryptMessage(e,t){return s(this,void 0,void 0,(function*(){const i=yield this.olmDevice.getSessionIdsForDevice(e),n={};for(const r of i)try{const i=yield this.olmDevice.decryptMessage(e,r,t.type,t.body);return a.logger.log("Decrypted Olm message from "+e+" with session "+r),i}catch(i){if(yield this.olmDevice.matchesSession(e,r,t.type,t.body))throw new Error("Error decrypting prekey message with existing session id "+r+": "+i.message);n[r]=i.message}if(0!==t.type){if(0===i.length)throw new Error("No existing sessions");throw new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(n))}let r;try{r=yield this.olmDevice.createInboundSession(e,t.type,t.body)}catch(e){throw n["(new)"]=e.message,new Error("Error decrypting prekey message: "+JSON.stringify(n))}return a.logger.log("created new inbound Olm session ID "+r.session_id+" with "+e),r.payload}))}}(0,l.registerAlgorithm)(c.OLM_ALGORITHM,h,f)},{"../../logger":374,"../deviceinfo":340,"../olmlib":343,"./base":332}],336:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CrossSigningKey=void 0,function(e){e.Master="master",e.SelfSigning="self_signing",e.UserSigning="user_signing"}(i.CrossSigningKey||(i.CrossSigningKey={}))},{}],337:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.DefaultAlgorithm=i.algorithmsByName=i.Aes256=i.Curve25519=i.BackupManager=void 0;const r=e("../client"),o=e("../logger"),s=e("./olmlib"),a=e("./key_passphrase"),c=e("../utils"),d=e("./store/indexeddb-crypto-store"),l=e("./recoverykey"),u=e("./aes"),h=e("../NamespacedValue"),f=e("./index"),p=e("./crypto"),g=e("../http-api");class v{constructor(e,t){this.baseApis=e,this.getKey=t,this.sessionLastCheckAttemptedTime={},this.checkedForBackup=!1,this.sendingBackups=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){const t=i.algorithmsByName[e.algorithm];if(!t)throw new Error("Unknown backup algorithm: "+e.algorithm);if("object"!=typeof e.auth_data)throw new Error("Invalid backup data returned");return t.checkBackupVersion(e)}static makeAlgorithm(e,t){const n=i.algorithmsByName[e.algorithm];if(!n)throw new Error("Unknown backup algorithm");return n.init(e.auth_data,t)}enableKeyBackup(e){return n(this,void 0,void 0,(function*(){this.backupInfo=e,this.algorithm&&this.algorithm.free(),this.algorithm=yield v.makeAlgorithm(e,this.getKey),this.baseApis.emit(f.CryptoEvent.KeyBackupStatus,!0),this.scheduleKeyBackupSend()}))}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(f.CryptoEvent.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?Boolean(this.algorithm):null}prepareKeyBackupVersion(e,t){return n(this,void 0,void 0,(function*(){const n=t?i.algorithmsByName[t]:i.DefaultAlgorithm;if(!n)throw new Error("Unknown backup algorithm");const[r,o]=yield n.prepare(e),s=(0,l.encodeRecoveryKey)(r);return{algorithm:n.algorithmName,auth_data:o,recovery_key:s,privateKey:r}}))}createKeyBackupVersion(e){return n(this,void 0,void 0,(function*(){this.algorithm=yield v.makeAlgorithm(e,this.getKey)}))}checkAndStart(){var e;return n(this,void 0,void 0,(function*(){if(o.logger.log("Checking key backup status..."),this.baseApis.isGuest())return o.logger.log("Skipping key backup check since user is guest"),this.checkedForBackup=!0,null;let t;try{t=null!==(e=yield this.baseApis.getKeyBackupVersion())&&void 0!==e?e:void 0}catch(e){return o.logger.log("Error checking for active key backup",e),404===e.httpStatus&&(this.checkedForBackup=!0),null}this.checkedForBackup=!0;const i=yield this.isKeyBackupTrusted(t);return i.usable&&!this.backupInfo?(o.logger.log(`Found usable key backup v${t.version}: enabling key backups`),yield this.enableKeyBackup(t)):!i.usable&&this.backupInfo?(o.logger.log("No usable key backup: disabling key backup"),this.disableKeyBackup()):i.usable||this.backupInfo?i.usable&&this.backupInfo&&(t.version!==this.backupInfo.version?(o.logger.log(`On backup version ${this.backupInfo.version} but found version ${t.version}: switching.`),this.disableKeyBackup(),yield this.enableKeyBackup(t),yield this.scheduleAllGroupSessionsForBackup()):o.logger.log(`Backup version ${t.version} still current`)):o.logger.log("No usable key backup: not enabling key backup"),{backupInfo:t,trustInfo:i}}))}checkKeyBackup(){return n(this,void 0,void 0,(function*(){return this.checkedForBackup=!1,this.checkAndStart()}))}queryKeyBackupRateLimited(e,t){return n(this,void 0,void 0,(function*(){if(!this.backupInfo)return;const i=(new Date).getTime();(!this.sessionLastCheckAttemptedTime[t]||i-this.sessionLastCheckAttemptedTime[t]>5e3)&&(this.sessionLastCheckAttemptedTime[t]=i,yield this.baseApis.restoreKeyBackupWithCache(e,t,this.backupInfo,{}))}))}isKeyBackupTrusted(e){return n(this,void 0,void 0,(function*(){const t={usable:!1,trusted_locally:!1,sigs:[]};if(!(e&&e.algorithm&&e.auth_data&&e.auth_data.signatures))return o.logger.info("Key backup is absent or missing required data"),t;const i=this.baseApis.getUserId(),r=yield this.baseApis.crypto.getSessionBackupPrivateKey();if(r){let i=null;try{i=yield v.makeAlgorithm(e,(()=>n(this,void 0,void 0,(function*(){return r})))),(yield i.keyMatches(r))&&(o.logger.info("Backup is trusted locally"),t.trusted_locally=!0)}catch(e){}finally{null==i||i.free()}}const a=e.auth_data.signatures[i]||{};for(const n of Object.keys(a)){const r=n.split(":");if("ed25519"!==r[0]){o.logger.log("Ignoring unknown signature type: "+r[0]);continue}const a={deviceId:r[1]},c=this.baseApis.crypto.crossSigningInfo.getId();if(c===a.deviceId){a.crossSigningId=!0;try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,i,a.deviceId,c),a.valid=!0}catch(e){o.logger.warn("Bad signature from cross signing key "+c,e),a.valid=!1}t.sigs.push(a);continue}const d=this.baseApis.crypto.deviceList.getStoredDevice(i,a.deviceId);if(d){a.device=d,a.deviceTrust=this.baseApis.checkDeviceTrust(i,a.deviceId);try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,i,d.deviceId,d.getFingerprint()),a.valid=!0}catch(t){o.logger.info("Bad signature from key ID "+n+" userID "+this.baseApis.getUserId()+" device ID "+d.deviceId+" fingerprint: "+d.getFingerprint(),e.auth_data,t),a.valid=!1}}else a.valid=null,o.logger.info("Ignoring signature from unknown key "+n);t.sigs.push(a)}return t.usable=t.sigs.some((e=>{var t;return e.valid&&(e.device&&(null===(t=e.deviceTrust)||void 0===t?void 0:t.isVerified())||e.crossSigningId)})),t}))}scheduleKeyBackupSend(e=1e4){return n(this,void 0,void 0,(function*(){if(!this.sendingBackups){this.sendingBackups=!0;try{const t=Math.random()*e;yield(0,c.sleep)(t);let i=0;for(;;){if(!this.algorithm)return;try{if(0===(yield this.backupPendingKeys(200)))return;i=0}catch(e){if(i++,o.logger.log("Key backup request failed",e),e.data&&("M_NOT_FOUND"==e.data.errcode||"M_WRONG_ROOM_KEYS_VERSION"==e.data.errcode))throw yield this.checkKeyBackup(),this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupFailed,e.data.errcode),e}i&&(yield(0,c.sleep)(1e3*Math.pow(2,Math.min(i-1,4))))}}finally{this.sendingBackups=!1}}}))}backupPendingKeys(e){var t;return n(this,void 0,void 0,(function*(){const i=yield this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!i.length)return 0;let n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupSessionsRemaining,n);const r={};for(const e of i){const i=e.sessionData.room_id;(0,c.safeSet)(r,i,r[i]||{sessions:{}});const n=this.baseApis.crypto.olmDevice.exportInboundGroupSession(e.senderKey,e.sessionId,e.sessionData);n.algorithm=s.MEGOLM_ALGORITHM;const o=(n.forwarding_curve25519_key_chain||[]).length,a=this.baseApis.crypto.deviceList.getUserByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey),d=null!==(t=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey))&&void 0!==t?t:void 0,l=this.baseApis.crypto.checkDeviceInfoTrust(a,d).isVerified();(0,c.safeSet)(r[i].sessions,e.sessionId,{first_message_index:n.first_known_index,forwarded_count:o,is_verified:l,session_data:yield this.algorithm.encryptSession(n)})}return yield this.baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:r}),yield this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(i),n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupSessionsRemaining,n),i.length}))}backupGroupSession(e,t){return n(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),this.backupInfo&&this.scheduleKeyBackupSend()}))}scheduleAllGroupSessionsForBackup(){return n(this,void 0,void 0,(function*(){yield this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)}))}flagAllGroupSessionsForBackup(){return n(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.doTxn("readwrite",[d.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,d.IndexedDBCryptoStore.STORE_BACKUP],(e=>{this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(e,(t=>{null!==t&&this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([t],e)}))}));const e=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return this.baseApis.emit(f.CryptoEvent.KeyBackupSessionsRemaining,e),e}))}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}i.BackupManager=v;class m{constructor(e,t,i){this.authData=e,this.publicKey=t,this.getKey=i}static init(e,i){return n(this,void 0,void 0,(function*(){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");const n=new t.Olm.PkEncryption;return n.set_recipient_key(e.public_key),new m(e,n,i)}))}static prepare(e){return n(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;try{const n={};if(e)if(e instanceof Uint8Array)n.public_key=i.init_with_private_key(e);else{const t=yield(0,a.keyFromPassphrase)(e);n.private_key_salt=t.salt,n.private_key_iterations=t.iterations,n.public_key=i.init_with_private_key(t.key)}else n.public_key=i.generate_key();return(new t.Olm.PkEncryption).set_recipient_key(n.public_key),[i.get_private_key(),n]}finally{i.free()}}))}static checkBackupVersion(e){if(!("public_key"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}encryptSession(e){return n(this,void 0,void 0,(function*(){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,this.publicKey.encrypt(JSON.stringify(t))}))}decryptSessions(e){return n(this,void 0,void 0,(function*(){const i=yield this.getKey(),n=new t.Olm.PkDecryption;try{if(n.init_with_private_key(i)!==this.authData.public_key)throw new g.MatrixError({errcode:r.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY});const t=[];for(const[i,r]of Object.entries(e))try{const e=JSON.parse(n.decrypt(r.session_data.ephemeral,r.session_data.mac,r.session_data.ciphertext));e.session_id=i,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,r)}return t}finally{n.free()}}))}keyMatches(e){return n(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;let n;try{n=i.init_with_private_key(e)}finally{i.free()}return n===this.authData.public_key}))}free(){this.publicKey.free()}}i.Curve25519=m,m.algorithmName="m.megolm_backup.v1.curve25519-aes-sha2";const y=new h.UnstableValue("m.megolm_backup.v1.aes-hmac-sha2","org.matrix.msc3270.v1.aes-hmac-sha2");class b{constructor(e,t){this.authData=e,this.key=t}static init(e,t){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("auth_data missing");const i=yield t();if(e.mac){const{mac:t}=yield(0,u.calculateKeyCheck)(i,e.iv);if(e.mac.replace(/=+$/g,"")!==t.replace(/=+/g,""))throw new Error("Key does not match")}return new b(e,i)}))}static prepare(e){return n(this,void 0,void 0,(function*(){let t;const i={};if(e)if(e instanceof Uint8Array)t=new Uint8Array(e);else{const n=yield(0,a.keyFromPassphrase)(e);i.private_key_salt=n.salt,i.private_key_iterations=n.iterations,t=n.key}else t=function(e){const t=new Uint8Array(e);return p.crypto.getRandomValues(t),t}(32);const{iv:n,mac:r}=yield(0,u.calculateKeyCheck)(t);return i.iv=n,i.mac=r,[t,i]}))}static checkBackupVersion(e){if(!("iv"in e.auth_data)||!("mac"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(e){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,(0,u.encryptAES)(JSON.stringify(t),this.key,e.session_id)}decryptSessions(e){return n(this,void 0,void 0,(function*(){const t=[];for(const[i,n]of Object.entries(e))try{const e=JSON.parse(yield(0,u.decryptAES)(n.session_data,this.key,i));e.session_id=i,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,n)}return t}))}keyMatches(e){return n(this,void 0,void 0,(function*(){if(this.authData.mac){const{mac:t}=yield(0,u.calculateKeyCheck)(e,this.authData.iv);return this.authData.mac.replace(/=+$/g,"")===t.replace(/=+/g,"")}return!0}))}free(){this.key.fill(0)}}i.Aes256=b,b.algorithmName=y.name,i.algorithmsByName={[m.algorithmName]:m,[b.algorithmName]:b},i.DefaultAlgorithm=m}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../NamespacedValue":316,"../client":321,"../http-api":367,"../logger":374,"../utils":416,"./aes":331,"./crypto":338,"./index":341,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346}],338:[function(e,t,i){(function(t){(function(){"use strict";var n,r,o,s,a,c,d;Object.defineProperty(i,"__esModule",{value:!0}),i.setTextEncoder=i.setCrypto=i.TextEncoder=i.subtleCrypto=i.crypto=void 0;const l=e("../logger");if(i.crypto=null===(n=t.window)||void 0===n?void 0:n.crypto,i.subtleCrypto=null!==(s=null===(o=null===(r=t.window)||void 0===r?void 0:r.crypto)||void 0===o?void 0:o.subtle)&&void 0!==s?s:null===(c=null===(a=t.window)||void 0===a?void 0:a.crypto)||void 0===c?void 0:c.webkitSubtle,i.TextEncoder=null===(d=t.window)||void 0===d?void 0:d.TextEncoder,!i.crypto)try{i.crypto=e("crypto").webcrypto}catch(e){l.logger.error("Failed to load webcrypto",e)}if(i.subtleCrypto||(i.subtleCrypto=null===i.crypto||void 0===i.crypto?void 0:i.crypto.subtle),!i.TextEncoder)try{i.TextEncoder=e("util").TextEncoder}catch(e){l.logger.error("Failed to load TextEncoder util",e)}i.setCrypto=function(e){var t;i.crypto=e,i.subtleCrypto=null!==(t=e.subtle)&&void 0!==t?t:e.webkitSubtle},i.setTextEncoder=function(e){i.TextEncoder=e}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":374,crypto:78,util:286}],339:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.DehydrationManager=i.DEHYDRATION_ALGORITHM=void 0;const s=o(e("another-json")),a=e("./olmlib"),c=e("../crypto/store/indexeddb-crypto-store"),d=e("./aes"),l=e("../logger"),u=e("../http-api");i.DEHYDRATION_ALGORITHM="org.matrix.msc2697.v1.olm.libolm_pickle";const h=6048e5;i.DehydrationManager=class{constructor(e){this.crypto=e,this.inProgress=!1,this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){return this.crypto.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.getSecretStorePrivateKey(e,(e=>r(this,void 0,void 0,(function*(){if(e){const{key:r,keyInfo:o,deviceDisplayName:s,time:c}=e,l=n.from(this.crypto.olmDevice.pickleKey),u=yield(0,d.decryptAES)(r,l,i.DEHYDRATION_ALGORITHM);this.key=(0,a.decodeBase64)(u),this.keyInfo=o,this.deviceDisplayName=s;const f=Date.now(),p=Math.max(1,c+h-f);this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),p)}}))),"dehydration")}))}setKeyAndQueueDehydration(e,t={},i){return r(this,void 0,void 0,(function*(){(yield this.setKey(e,t,i))||this.dehydrateDevice()}))}setKey(e,i={},n){return r(this,void 0,void 0,(function*(){if(!e)return this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0),yield this.crypto.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",null)})),this.key=void 0,void(this.keyInfo=void 0);let r=!!this.key&&e.length==this.key.length;for(let t=0;r&&t<e.length;t++)e[t]!=this.key[t]&&(r=!1);return r||(this.key=e,this.keyInfo=i,this.deviceDisplayName=n),r}))}dehydrateDevice(){return r(this,void 0,void 0,(function*(){if(this.inProgress)l.logger.log("Dehydration already in progress -- not starting new dehydration");else{this.inProgress=!0,this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0);try{const e=n.from(this.crypto.olmDevice.pickleKey),r=yield(0,d.encryptAES)((0,a.encodeBase64)(this.key),e,i.DEHYDRATION_ALGORITHM);yield this.crypto.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",{keyInfo:this.keyInfo,key:r,deviceDisplayName:this.deviceDisplayName,time:Date.now()})})),l.logger.log("Attempting to dehydrate device"),l.logger.log("Creating account");const o=new t.Olm.Account;o.create();const f=JSON.parse(o.identity_keys()),p=o.max_number_of_one_time_keys();o.generate_one_time_keys(p/2),o.generate_fallback_key();const g=JSON.parse(o.one_time_keys()),v=JSON.parse(o.fallback_key());o.mark_keys_as_published();const m=o.pickle(new Uint8Array(this.key)),y={algorithm:i.DEHYDRATION_ALGORITHM,account:m};this.keyInfo.passphrase&&(y.passphrase=this.keyInfo.passphrase),l.logger.log("Uploading account to server");const b=(yield this.crypto.baseApis.http.authedRequest(u.Method.Put,"/dehydrated_device",void 0,{device_data:y,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;l.logger.log("Preparing device keys",b);const S={algorithms:this.crypto.supportedAlgorithms,device_id:b,user_id:this.crypto.userId,keys:{[`ed25519:${b}`]:f.ed25519,[`curve25519:${b}`]:f.curve25519}},_=o.sign(s.default.stringify(S));S.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:_}},this.crypto.crossSigningInfo.getId("self_signing")&&(yield this.crypto.crossSigningInfo.signObject(S,"self_signing")),l.logger.log("Preparing one-time keys");const E={};for(const[e,t]of Object.entries(g.curve25519)){const i={key:t},n=o.sign(s.default.stringify(i));i.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:n}},E[`signed_curve25519:${e}`]=i}l.logger.log("Preparing fallback keys");const w={};for(const[e,t]of Object.entries(v.curve25519)){const i={key:t,fallback:!0},n=o.sign(s.default.stringify(i));i.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:n}},w[`signed_curve25519:${e}`]=i}return l.logger.log("Uploading keys to server"),yield this.crypto.baseApis.http.authedRequest(u.Method.Post,"/keys/upload/"+encodeURI(b),void 0,{device_keys:S,one_time_keys:E,"org.matrix.msc2732.fallback_keys":w}),l.logger.log("Done dehydrating"),this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),h),b}finally{this.inProgress=!1}}}))}stop(){this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../crypto/store/indexeddb-crypto-store":346,"../http-api":367,"../logger":374,"./aes":331,"./olmlib":343,"another-json":1,buffer:68}],340:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceInfo=void 0,function(e){e[e.Blocked=-1]="Blocked",e[e.Unverified=0]="Unverified",e[e.Verified=1]="Verified"}(n||(n={}));class r{static fromStorage(e,t){const i=new r(t);for(const t in e)e.hasOwnProperty(t)&&(i[t]=e[t]);return i}constructor(e){this.deviceId=e,this.algorithms=[],this.keys={},this.verified=n.Unverified,this.known=!1,this.unsigned={},this.signatures={}}toStorage(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned,signatures:this.signatures}}getFingerprint(){return this.keys["ed25519:"+this.deviceId]}getIdentityKey(){return this.keys["curve25519:"+this.deviceId]}getDisplayName(){return this.unsigned.device_display_name||null}isBlocked(){return this.verified==n.Blocked}isVerified(){return this.verified==n.Verified}isUnverified(){return this.verified==n.Unverified}isKnown(){return!0===this.known}}i.DeviceInfo=r,r.DeviceVerification={VERIFIED:n.Verified,UNVERIFIED:n.Unverified,BLOCKED:n.Blocked}},{}],341:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return o(t,e),t},a=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.IncomingRoomKeyRequest=i.fixBackupKey=i.Crypto=i.CryptoEvent=i.isCryptoAvailable=i.verificationMethods=void 0;const d=c(e("another-json")),l=e("uuid"),u=e("../@types/event"),h=e("../ReEmitter"),f=e("../logger"),p=e("./OlmDevice"),g=s(e("./olmlib")),v=e("./DeviceList"),m=e("./deviceinfo"),y=s(e("./algorithms")),b=e("./CrossSigning"),S=e("./EncryptionSetup"),_=e("./SecretStorage"),E=e("./OutgoingRoomKeyRequestManager"),w=e("./store/indexeddb-crypto-store"),T=e("./verification/QRCode"),I=e("./verification/SAS"),R=e("./key_passphrase"),M=e("./recoverykey"),k=e("./verification/request/VerificationRequest"),C=e("./verification/request/InRoomChannel"),O=e("./verification/request/ToDeviceChannel"),A=e("./verification/IllegalMethod"),P=e("../errors"),D=e("./aes"),x=e("./dehydration"),L=e("./backup"),U=e("../models/room"),B=e("../models/room-member"),N=e("../models/event"),j=e("../client"),F=e("../models/typed-event-emitter"),K=e("../models/room-state"),q=e("../utils"),$=m.DeviceInfo.DeviceVerification,V={[T.ReciprocateQRCode.NAME]:T.ReciprocateQRCode,[I.SAS.NAME]:I.SAS,[T.SHOW_QR_CODE_METHOD]:A.IllegalMethod,[T.SCAN_QR_CODE_METHOD]:A.IllegalMethod};i.verificationMethods={RECIPROCATE_QR_CODE:T.ReciprocateQRCode.NAME,SAS:I.SAS.NAME},i.isCryptoAvailable=function(){return Boolean(t.Olm)};var H;!function(e){e.DeviceVerificationChanged="deviceVerificationChanged",e.UserTrustStatusChanged="userTrustStatusChanged",e.UserCrossSigningUpdated="userCrossSigningUpdated",e.RoomKeyRequest="crypto.roomKeyRequest",e.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",e.KeyBackupStatus="crypto.keyBackupStatus",e.KeyBackupFailed="crypto.keyBackupFailed",e.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",e.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",e.VerificationRequest="crypto.verification.request",e.Warning="crypto.warning",e.WillUpdateDevices="crypto.willUpdateDevices",e.DevicesUpdated="crypto.devicesUpdated",e.KeysChanged="crossSigning.keysChanged"}(H=i.CryptoEvent||(i.CryptoEvent={}));class W extends F.TypedEventEmitter{static getOlmVersion(){return p.OlmDevice.getOlmVersion()}constructor(e,t,i,n,r,o,s){if(super(),this.baseApis=e,this.userId=t,this.deviceId=i,this.clientStore=n,this.cryptoStore=r,this.roomList=o,this.trustCrossSignedDevices=!0,this.lastOneTimeKeyCheck=null,this.oneTimeKeyCheckInProgress=!1,this.roomEncryptors=new Map,this.roomDecryptors=new Map,this.deviceKeys={},this.globalBlacklistUnverifiedDevices=!1,this.globalErrorOnUnknownDevices=!0,this.receivedRoomKeyRequests=[],this.receivedRoomKeyRequestCancellations=[],this.processingRoomKeyRequests=!1,this.lazyLoadMembers=!1,this.roomDeviceTrackingState={},this.lastNewSessionForced=new q.MapWithDefault((()=>new q.MapWithDefault((()=>0)))),this.sendKeyRequestsImmediately=!1,this.onDeviceListUserCrossSigningUpdated=e=>a(this,void 0,void 0,(function*(){if(e===this.userId){const t=this.deviceList.getStoredCrossSigningForUser(e),i=t?t.getId():null,n=this.crossSigningInfo.getId();n&&i&&!(n!==i)?yield this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit(H.KeysChanged,{}),this.emit(H.UserTrustStatusChanged,this.userId,this.checkUserTrust(e)))}else{yield this.checkDeviceVerifications(e);const t=this.deviceList.getStoredCrossSigningForUser(e);t&&(t.updateCrossSigningVerifiedBefore(this.checkUserTrust(e).isCrossSigningVerified()),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage())),this.emit(H.UserTrustStatusChanged,e,this.checkUserTrust(e))}})),this.onMembership=(e,t,i)=>{try{this.onRoomMembership(e,t,i)}catch(e){f.logger.error("Error handling membership change:",e)}},this.onToDeviceEvent=e=>{try{f.logger.log(`received to-device ${e.getType()} from: ${e.getSender()} id: ${e.getContent()[u.ToDeviceMessageId]}`),"m.room_key"==e.getType()||"m.forwarded_room_key"==e.getType()?this.onRoomKeyEvent(e):"m.room_key_request"==e.getType()?this.onRoomKeyRequestEvent(e):"m.secret.request"===e.getType()?this.secretStorage.onRequestReceived(e):"m.secret.send"===e.getType()?this.secretStorage.onSecretReceived(e):"m.room_key.withheld"===e.getType()?this.onRoomKeyWithheldEvent(e):e.getContent().transaction_id?this.onKeyVerificationMessage(e):"m.bad.encrypted"===e.getContent().msgtype?this.onToDeviceBadEncrypted(e):(e.isBeingDecrypted()||e.shouldAttemptDecryption())&&(e.isBeingDecrypted()||e.attemptDecryption(this),e.once(N.MatrixEventEvent.Decrypted,(e=>{this.onToDeviceEvent(e)})))}catch(e){f.logger.error("Error handling toDeviceEvent:",e)}},this.onTimelineEvent=(e,t,i,n,{liveEvent:r=!0}={})=>{if(!C.InRoomChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.inRoomVerificationRequests,(e=>{const t=new C.InRoomChannel(this.baseApis,e.getRoomId());return new k.VerificationRequest(t,this.verificationMethods,this.baseApis)}),r)},this.reEmitter=new h.TypedReEmitter(this),s){this.verificationMethods=new Map;for(const e of s)"string"==typeof e?V[e]&&this.verificationMethods.set(e,V[e]):e.NAME?this.verificationMethods.set(e.NAME,e):f.logger.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=new Map(Object.entries(V));this.backupManager=new L.BackupManager(e,(()=>a(this,void 0,void 0,(function*(){const e=yield this.getSessionBackupPrivateKey();if(e)return e;const t=yield this.getSecret("m.megolm_backup.v1");if(t){const e=G(t);if(e){const t=yield this.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",e,[t[0]])}return g.decodeBase64(e||t)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})))),this.olmDevice=new p.OlmDevice(r),this.deviceList=new v.DeviceList(e,r,this.olmDevice),this.deviceList.on(H.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[H.DevicesUpdated,H.WillUpdateDevices]),this.supportedAlgorithms=Array.from(y.DECRYPTION_CLASSES.keys()),this.outgoingRoomKeyRequestManager=new E.OutgoingRoomKeyRequestManager(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new O.ToDeviceRequests,this.inRoomVerificationRequests=new C.InRoomRequests;const c=this.baseApis.cryptoCallbacks||{},d=(0,b.createCryptoStoreCacheCallbacks)(r,this.olmDevice);this.crossSigningInfo=new b.CrossSigningInfo(t,c,d),this.secretStorage=new _.SecretStorage(e,c,e),this.dehydrationManager=new x.DehydrationManager(this),!c.getCrossSigningKey&&c.getSecretStorageKey&&(c.getCrossSigningKey=e=>a(this,void 0,void 0,(function*(){return b.CrossSigningInfo.getFromSecretStorage(e,this.secretStorage)})))}init({exportedOlmDevice:e,pickleKey:i}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Crypto: initialising Olm..."),yield t.Olm.init(),f.logger.log(e?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield this.olmDevice.init({fromExportedDevice:e,pickleKey:i}),f.logger.log("Crypto: loading device list..."),yield this.deviceList.load(),this.deviceKeys["ed25519:"+this.deviceId]=this.olmDevice.deviceEd25519Key,this.deviceKeys["curve25519:"+this.deviceId]=this.olmDevice.deviceCurve25519Key,f.logger.log("Crypto: fetching own devices...");let n=this.deviceList.getRawStoredDevicesForUser(this.userId);if(n||(n={}),!n[this.deviceId]){f.logger.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:$.VERIFIED,known:!0};n[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,n),this.deviceList.saveIfDirty()}yield this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(f.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),f.logger.log("Crypto: checking for key backup..."),this.backupManager.checkAndStart()}))}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setCryptoTrustCrossSignedDevices(e){this.trustCrossSignedDevices=e;for(const e of this.deviceList.getKnownUserIds()){const t=this.deviceList.getRawStoredDevicesForUser(e);for(const i of Object.keys(t)){const t=this.checkDeviceTrust(e,i);if(!t.isLocallyVerified()&&t.isCrossSigningVerified()){const t=this.deviceList.getStoredDevice(e,i);this.emit(H.DeviceVerificationChanged,e,i,t)}}}}createRecoveryKeyFromPassphrase(e){return a(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;try{const t={};if(e){const n=yield(0,R.keyFromPassphrase)(e);t.passphrase={algorithm:"m.pbkdf2",iterations:n.iterations,salt:n.salt},t.pubkey=i.init_with_private_key(n.key)}else t.pubkey=i.generate_key();const n=i.get_private_key();return{keyInfo:t,encodedPrivateKey:(0,M.encodeRecoveryKey)(n),privateKey:n}}finally{null==i||i.free()}}))}userHasCrossSigningKeys(){return a(this,void 0,void 0,(function*(){return yield this.downloadKeys([this.userId]),null!==this.deviceList.getStoredCrossSigningForUser(this.userId)}))}isCrossSigningReady(){return a(this,void 0,void 0,(function*(){const e=this.crossSigningInfo.getId(),t=(yield this.crossSigningInfo.isStoredInKeyCache())||(yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage));return!(!e||!t)}))}isSecretStorageReady(){return a(this,void 0,void 0,(function*(){const e=yield this.secretStorage.hasKey(),t=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),i=!this.backupManager.getKeyBackupEnabled()||(yield this.baseApis.isKeyBackupKeyStored());return!!(e&&t&&i)}))}bootstrapCrossSigning({authUploadDeviceSigningKeys:e,setupNewCrossSigning:t}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Bootstrapping cross-signing");const i=this.baseApis.cryptoCallbacks,n=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,i),r=new b.CrossSigningInfo(this.userId,n.crossSigningCallbacks,n.crossSigningCallbacks),o=()=>a(this,void 0,void 0,(function*(){r.resetKeys(),yield this.signObject(r.keys.master),n.addCrossSigningKeys(e,r.keys);const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),i=yield r.signDevice(this.userId,t);n.addKeySignature(this.userId,this.deviceId,i),this.backupManager.backupInfo&&(yield r.signObject(this.backupManager.backupInfo.auth_data,"master"),n.addSessionBackup(this.backupManager.backupInfo))})),s=this.crossSigningInfo.getId(),c=yield this.crossSigningInfo.isStoredInKeyCache(),d=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),l=c||d;f.logger.log({setupNewCrossSigning:t,publicKeysOnDevice:s,privateKeysInCache:c,privateKeysInStorage:d,privateKeysExistSomewhere:l}),!l||t?(f.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield o()):s&&c?f.logger.log("Cross-signing public keys trusted and private keys found locally"):d&&(f.logger.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),yield this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const u=n.crossSigningCallbacks.privateKeys;if(u.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new _.SecretStorage(n.accountDataClientAdapter,n.ssssCryptoCallbacks,void 0);(yield e.hasKey())&&(f.logger.log("Storing new cross-signing private keys in secret storage"),yield b.CrossSigningInfo.storeInSecretStorage(u,e))}const h=n.buildOperation();yield h.apply(this),yield n.persist(this),f.logger.log("Cross-signing ready")}))}bootstrapSecretStorage({createSecretStorageKey:e=(()=>a(this,void 0,void 0,(function*(){return{}}))),keyBackupInfo:t,setupNewKeyBackup:i,setupNewSecretStorage:n,getKeyBackupPassphrase:r}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Bootstrapping Secure Secret Storage");const o=this.baseApis.cryptoCallbacks,s=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,o),c=new _.SecretStorage(s.accountDataClientAdapter,s.ssssCryptoCallbacks,void 0);let d=null;const l=(e,t)=>a(this,void 0,void 0,(function*(){t&&(e.key=t);const{keyId:i,keyInfo:n}=yield c.addKey(_.SECRET_STORAGE_ALGORITHM_V1_AES,e);return t&&s.ssssCryptoCallbacks.addPrivateKey(i,n,t),yield c.setDefaultKeyId(i),i})),u=(e,t)=>a(this,void 0,void 0,(function*(){var i,n;if(!t.mac){const r=yield null===(n=(i=this.baseApis.cryptoCallbacks).getSecretStorageKey)||void 0===n?void 0:n.call(i,{keys:{[e]:t}},"");if(r){const i=r[1];s.ssssCryptoCallbacks.addPrivateKey(e,t,i);const{iv:n,mac:o}=yield(0,D.calculateKeyCheck)(i);t.iv=n,t.mac=o,yield s.setAccountData(`m.secret_storage.key.${e}`,t)}}})),h=e=>a(this,void 0,void 0,(function*(){if(this.crossSigningInfo.getId()&&(yield this.crossSigningInfo.isStoredInKeyCache("master")))try{f.logger.log("Adding cross-signing signature to key backup"),yield this.crossSigningInfo.signObject(e,"master")}catch(e){f.logger.error("Signing key backup with cross-signing keys failed",e)}else f.logger.warn("Cross-signing keys not available, skipping signature on key backup")})),p=yield this.getSecretStorageKey(),[v,m]=p||[null,null],y=!n&&m&&m.algorithm===_.SECRET_STORAGE_ALGORITHM_V1_AES;if(f.logger.log({keyBackupInfo:t,setupNewKeyBackup:i,setupNewSecretStorage:n,storageExists:y,oldKeyInfo:m}),y||t)if(!y&&t){f.logger.log("Secret storage does not exist, using key backup key");const e=(yield this.getSessionBackupPrivateKey())||(yield null==r?void 0:r()),i={};t.auth_data.private_key_salt&&t.auth_data.private_key_iterations&&(i.passphrase={algorithm:"m.pbkdf2",iterations:t.auth_data.private_key_iterations,salt:t.auth_data.private_key_salt,bits:256}),d=yield l(i,e),yield c.store("m.megolm_backup.v1",g.encodeBase64(e),[d]),yield h(t.auth_data),s.addSessionBackup(t)}else f.logger.log("Secret storage exists"),m&&m.algorithm===_.SECRET_STORAGE_ALGORITHM_V1_AES&&(yield u(v,m));else{f.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:t={},privateKey:i}=yield e();d=yield l(t,i)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield this.isCrossSigningReady())&&(d||!(yield this.crossSigningInfo.isStoredInSecretStorage(c)))){f.logger.log("Copying cross-signing private keys from cache to secret storage");const e=yield this.crossSigningInfo.getCrossSigningKeysFromCache();yield b.CrossSigningInfo.storeInSecretStorage(e,c)}if(i&&!t){f.logger.log("Creating new message key backup version");const e=yield this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=(0,M.decodeRecoveryKey)(e.recovery_key);yield c.store("m.megolm_backup.v1",g.encodeBase64(t));const i={algorithm:e.algorithm,auth_data:e.auth_data};yield h(i.auth_data),yield this.signObject(i.auth_data),s.addSessionBackup(i)}const E=yield c.get("m.megolm_backup.v1");if(E){f.logger.info("Got session backup key from secret storage: caching");const e=G(E);if(e){const t=d||v;yield c.store("m.megolm_backup.v1",e,t?[t]:null)}const t=new Uint8Array(g.decodeBase64(e||E));s.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=(yield this.getSessionBackupPrivateKey())||(yield null==r?void 0:r());if(!e)return void f.logger.error("Key backup is enabled but couldn't get key backup key!");f.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),yield c.store("m.megolm_backup.v1",g.encodeBase64(e))}const w=s.buildOperation();yield w.apply(this),yield s.persist(this),f.logger.log("Secure Secret Storage ready")}))}addSecretStorageKey(e,t,i){return this.secretStorage.addKey(e,t,i)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,i){return this.secretStorage.store(e,t,i)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(e,i){let n=null;try{n=new t.Olm.PkDecryption;return n.init_with_private_key(e)===i}finally{null==n||n.free()}}getSessionBackupPrivateKey(){return a(this,void 0,void 0,(function*(){let e=yield new Promise((e=>{this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(g.decodeBase64(G(e)||e)),yield this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=n.from(this.olmDevice.pickleKey),i=yield(0,D.decryptAES)(e,t,"m.megolm_backup.v1");e=g.decodeBase64(i)}return e}))}storeSessionBackupPrivateKey(e){return a(this,void 0,void 0,(function*(){if(!(e instanceof Uint8Array))throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${e}`);const t=n.from(this.olmDevice.pickleKey),i=yield(0,D.encryptAES)(g.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeSecretStorePrivateKey(e,"m.megolm_backup.v1",i)}))}))}checkCrossSigningPrivateKey(e,i){let n=null;try{n=new t.Olm.PkSigning;return n.init_with_seed(e)===i}finally{null==n||n.free()}}afterCrossSigningLocalKeyChange(){return a(this,void 0,void 0,(function*(){f.logger.info("Starting cross-signing key change post-processing");const e=this.deviceList.getStoredDevice(this.userId,this.deviceId),t=yield this.crossSigningInfo.signDevice(this.userId,e);f.logger.info(`Starting background key sig upload for ${this.deviceId}`);const i=({shouldEmit:e=!1})=>this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:t}}).then((t=>{const{failures:n}=t||{};if(Object.keys(n||[]).length>0)throw e&&this.baseApis.emit(H.KeySignatureUploadFailure,n,"afterCrossSigningLocalKeyChange",i),new P.KeySignatureUploadError("Key upload failed",{failures:n});f.logger.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{f.logger.error(`Error during background key sig upload for ${this.deviceId}`,e)}));i({shouldEmit:!0});const n=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(n){f.logger.info("Starting device verification upgrade");const e={};for(const[t,i]of Object.entries(this.deviceList.crossSigningInfo)){const n=yield this.checkForDeviceVerificationUpgrade(t,b.CrossSigningInfo.fromStorage(i,t));n&&(e[t]=n)}if(Object.keys(e).length>0){f.logger.info(`Found ${Object.keys(e).length} verif users to upgrade`);try{const t=yield n({users:e});if(t)for(const i of t)i in e&&(yield this.baseApis.setDeviceVerified(i,e[i].crossSigningInfo.getId()))}catch(e){f.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}f.logger.info("Finished device verification upgrade")}f.logger.info("Finished cross-signing key change post-processing")}))}checkForDeviceVerificationUpgrade(e,t){return a(this,void 0,void 0,(function*(){const i=this.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!i.isVerified()){const i=this.deviceList.getRawStoredDevicesForUser(e),n=yield this.checkForValidDeviceSignature(e,t.keys.master,i);if(n.length)return{devices:n.map((e=>m.DeviceInfo.fromStorage(i[e],e))),crossSigningInfo:t}}}))}checkForValidDeviceSignature(e,t,i){return a(this,void 0,void 0,(function*(){const n=[];if(i&&t.signatures&&t.signatures[e])for(const r of Object.keys(t.signatures[e])){const[,o]=r.split(":",2);if(o in i&&i[o].verified===$.VERIFIED)try{yield g.verifySignature(this.olmDevice,t,e,o,i[o].keys[r]),n.push(o)}catch(e){}}return n}))}getCrossSigningId(e){return this.crossSigningInfo.getId(e)}getStoredCrossSigningForUser(e){return this.deviceList.getStoredCrossSigningForUser(e)}checkUserTrust(e){const t=this.deviceList.getStoredCrossSigningForUser(e);return t?this.crossSigningInfo.checkUserTrust(t):new b.UserTrustLevel(!1,!1,!1)}checkDeviceTrust(e,t){const i=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,i)}checkDeviceInfoTrust(e,t){const i=!!(null==t?void 0:t.isVerified()),n=this.deviceList.getStoredCrossSigningForUser(e);if(t&&n){const r=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(n,t,i,r)}return new b.DeviceTrustLevel(!1,!1,i,!1)}checkIfOwnDeviceCrossSigned(e){var t;const i=this.deviceList.getStoredDevice(this.userId,e);if(!i)return!1;const n=this.deviceList.getStoredCrossSigningForUser(this.userId);return null!==(t=null==n?void 0:n.checkDeviceTrust(n,i,!1,!0).isCrossSigningVerified())&&void 0!==t&&t}checkOwnCrossSigningTrust({allowPrivateKeyRequests:e=!1}={}){return a(this,void 0,void 0,(function*(){const t=this.userId;yield this.downloadKeys([this.userId]);const i=yield this.crossSigningInfo.getCrossSigningKeysFromCache(),n=this.deviceList.getStoredCrossSigningForUser(t);if(!n)return void f.logger.error("Got cross-signing update event for user "+t+" but no new cross-signing information found!");const r=n.getId(),o=this.crossSigningInfo.getId()!==r,s=n.getId()&&!i.has("master");if(o&&f.logger.info("Got new master public key",r),e&&(o||s)){f.logger.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("master",r))[1],f.logger.info("Got cross-signing master private key")}finally{null==e||e.free()}}const a=this.crossSigningInfo.getId("self_signing"),c=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(n.keys);const d=a!==n.getId("self_signing"),l=c!==n.getId("user_signing"),u=n.getId("self_signing")&&!i.has("self_signing"),h=n.getId("user_signing")&&!i.has("user_signing"),p={};if(d&&f.logger.info("Got new self-signing key",n.getId("self_signing")),e&&(d||u)){f.logger.info("Attempting to retrieve cross-signing self-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("self_signing",n.getId("self_signing")))[1],f.logger.info("Got cross-signing self-signing private key")}finally{null==e||e.free()}const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),i=yield this.crossSigningInfo.signDevice(this.userId,t);p[this.deviceId]=i}if(l&&f.logger.info("Got new user-signing key",n.getId("user_signing")),e&&(l||h)){f.logger.info("Attempting to retrieve cross-signing user-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("user_signing",n.getId("user_signing")))[1],f.logger.info("Got cross-signing user-signing private key")}finally{null==e||e.free()}}if(o){const e=this.crossSigningInfo.keys.master;yield this.signObject(e);const t=e.signatures[this.userId]["ed25519:"+this.deviceId];p[this.crossSigningInfo.getId()]=Object.assign({},e,{signatures:{[this.userId]:{["ed25519:"+this.deviceId]:t}}})}const g=Object.keys(p);if(g.length){const e=({shouldEmit:t=!1})=>(f.logger.info(`Starting background key sig upload for ${g}`),this.baseApis.uploadKeySignatures({[this.userId]:p}).then((i=>{const{failures:n}=i||{};if(f.logger.info(`Finished background key sig upload for ${g}`),Object.keys(n||[]).length>0)throw t&&this.baseApis.emit(H.KeySignatureUploadFailure,n,"checkOwnCrossSigningTrust",e),new P.KeySignatureUploadError("Key upload failed",{failures:n})})).catch((e=>{f.logger.error(`Error during background key sig upload for ${g}`,e)})));e({shouldEmit:!0})}this.emit(H.UserTrustStatusChanged,t,this.checkUserTrust(t)),o&&(this.emit(H.KeysChanged,{}),yield this.afterCrossSigningLocalKeyChange()),yield this.backupManager.checkKeyBackup()}))}storeTrustedSelfKeys(e){return a(this,void 0,void 0,(function*(){e?this.crossSigningInfo.setKeys(e):this.crossSigningInfo.clearKeys(),yield this.cryptoStore.doTxn("readwrite",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeCrossSigningKeys(e,this.crossSigningInfo.keys)}))}))}checkDeviceVerifications(e){return a(this,void 0,void 0,(function*(){const t=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(t){if(f.logger.info(`Starting device verification upgrade for ${e}`),this.crossSigningInfo.keys.user_signing){const i=this.deviceList.getStoredCrossSigningForUser(e);if(i){const n=yield this.checkForDeviceVerificationUpgrade(e,i);if(n){(yield t({users:{[e]:n}})).includes(e)&&(yield this.baseApis.setDeviceVerified(e,i.getId()))}}}f.logger.info(`Finished device verification upgrade for ${e}`)}}))}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(B.RoomMemberEvent.Membership,this.onMembership),e.on(j.ClientEvent.ToDeviceEvent,this.onToDeviceEvent),e.on(U.RoomEvent.Timeline,this.onTimelineEvent),e.on(N.MatrixEventEvent.Decrypted,this.onTimelineEvent)}start(){f.logger.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){const e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then((()=>this.baseApis.uploadKeysRequest({device_keys:e})))}updateOneTimeKeyCount(e){if(!isFinite(e))throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");this.oneTimeKeyCount=e}setNeedsNewFallback(e){this.needsNewFallback=e}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){if(this.oneTimeKeyCheckInProgress)return;const e=Date.now();if(null!==this.lastOneTimeKeyCheck&&e-this.lastOneTimeKeyCheck<6e4)return;this.lastOneTimeKeyCheck=e;const t=this.olmDevice.maxNumberOfOneTimeKeys(),i=Math.floor(t/2),n=e=>a(this,void 0,void 0,(function*(){for(;i>e||this.getNeedsNewFallback();){if(i>e){f.logger.info("generating oneTimeKeys");const t=Math.min(i-e,5);yield this.olmDevice.generateOneTimeKeys(t)}if(this.getNeedsNewFallback()){const e=yield this.olmDevice.getFallbackKey();e.curve25519&&0!=Object.keys(e.curve25519).length||(f.logger.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),yield this.olmDevice.generateFallbackKey())}f.logger.info("calling uploadOneTimeKeys");const t=yield this.uploadOneTimeKeys();if(!t.one_time_key_counts||!t.one_time_key_counts.signed_curve25519)throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519");e=t.one_time_key_counts.signed_curve25519}}));this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then((()=>void 0!==this.oneTimeKeyCount?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then((e=>e.one_time_key_counts.signed_curve25519||0)))).then((e=>n(e))).catch((e=>{f.logger.error("Error uploading one-time keys",e.stack||e)})).finally((()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1}))}uploadOneTimeKeys(){return a(this,void 0,void 0,(function*(){const e=[];let t;if(this.getNeedsNewFallback()){t={};const i=yield this.olmDevice.getFallbackKey();for(const[n,r]of Object.entries(i.curve25519)){const i={key:r,fallback:!0};t["signed_curve25519:"+n]=i,e.push(this.signObject(i))}this.setNeedsNewFallback(!1)}const i=yield this.olmDevice.getOneTimeKeys(),n={};for(const t in i.curve25519)if(i.curve25519.hasOwnProperty(t)){const r={key:i.curve25519[t]};n["signed_curve25519:"+t]=r,e.push(this.signObject(r))}yield Promise.all(e);const r={one_time_keys:n};t&&(r["org.matrix.msc2732.fallback_keys"]=t,r.fallback_keys=t);const o=yield this.baseApis.uploadKeysRequest(r);return t&&(this.fallbackCleanup=setTimeout((()=>{delete this.fallbackCleanup,this.olmDevice.forgetOldFallbackKey()}),36e5)),yield this.olmDevice.markKeysAsPublished(),o}))}downloadKeys(e,t){return this.deviceList.downloadKeys(e,!!t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}setDeviceVerification(e,t,i=null,n=null,r=null,o){return a(this,void 0,void 0,(function*(){const s=this.deviceList.getStoredCrossSigningForUser(e);if(s&&s.getId()===t){if(null!==n||null!==r)throw new Error("Cannot set blocked or known for a cross-signing key");if(!i)throw new Error("Cannot set a cross-signing key as unverified");const c=o?Object.values(o)[0]:null;if(o&&(1!==Object.values(o).length||c!==s.getId()))throw new Error(`Key did not match expected value: expected ${s.getId()}, got ${c}`);if(this.crossSigningInfo.getId()||e!==this.crossSigningInfo.userId||(this.storeTrustedSelfKeys(s.keys),this.emit(H.UserTrustStatusChanged,this.userId,this.checkUserTrust(e))),e!==this.userId){f.logger.info("Master key "+s.getId()+" for "+e+" marked verified. Signing...");const i=yield this.crossSigningInfo.signUser(s);if(i){const n=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){f.logger.info("Uploading signature for "+e+"...");const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:i}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(H.KeySignatureUploadFailure,s,"setDeviceVerification",n),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield n({shouldEmit:!0})}return i}return s}const c=this.deviceList.getRawStoredDevicesForUser(e);if(!c||!c[t])throw new Error("Unknown device "+e+":"+t);const d=c[t];let l=d.verified;if(i){if(o)for(const[e,t]of Object.entries(o))if(d.keys[e]!==t)throw new Error(`Key did not match expected value: expected ${t}, got ${d.keys[e]}`);l=$.VERIFIED}else null!==i&&l==$.VERIFIED&&(l=$.UNVERIFIED);n?l=$.BLOCKED:null!==n&&l==$.BLOCKED&&(l=$.UNVERIFIED);let u=d.known;if(null!==r&&(u=r),d.verified===l&&d.known===u||(d.verified=l,d.known=u,this.deviceList.storeDevicesForUser(e,c),this.deviceList.saveIfDirty()),i&&e===this.userId){let i;f.logger.info("Own device "+t+" marked verified: signing");if(this.checkDeviceTrust(e,t).isCrossSigningVerified()?f.logger.log(`Own device ${t} already cross-signing verified`):i=yield this.crossSigningInfo.signDevice(e,m.DeviceInfo.fromStorage(d,t)),i){const n=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){f.logger.info("Uploading signature for "+t);const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:i}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(H.KeySignatureUploadFailure,s,"setDeviceVerification",n),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield n({shouldEmit:!0})}}const h=m.DeviceInfo.fromStorage(d,t);return this.emit(H.DeviceVerificationChanged,e,t,h),h}))}findVerificationRequestDMInProgress(e){return this.inRoomVerificationRequests.findRequestInProgress(e)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){const i=this.inRoomVerificationRequests.findRequestInProgress(t);if(i)return Promise.resolve(i);const n=new C.InRoomChannel(this.baseApis,t,e);return this.requestVerificationWithChannel(e,n,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));const i=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(i)return Promise.resolve(i);const n=new O.ToDeviceChannel(this.baseApis,e,t,O.ToDeviceChannel.makeTransactionId());return this.requestVerificationWithChannel(e,n,this.toDeviceVerificationRequests)}requestVerificationWithChannel(e,t,i){return a(this,void 0,void 0,(function*(){let e=new k.VerificationRequest(t,this.verificationMethods,this.baseApis);t.transactionId&&i.setRequestByChannel(t,e),yield e.sendRequest();const n=i.getRequestByChannel(t);return n?e=n:(f.logger.log(`Crypto: adding new request to requestsByTxnId with id ${t.transactionId} ${t.roomId}`),i.setRequestByChannel(t,e)),e}))}beginKeyVerification(e,t,i,n=null){let r;if(n){if(r=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,n),!r)throw new Error(`No request found for user ${t} with transactionId ${n}`)}else{n=O.ToDeviceChannel.makeTransactionId();const e=new O.ToDeviceChannel(this.baseApis,t,[i],n,i);r=new k.VerificationRequest(e,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,n,r)}return r.beginKeyVerification(e,{userId:t,deviceId:i})}legacyDeviceVerification(e,t,i){return a(this,void 0,void 0,(function*(){const n=O.ToDeviceChannel.makeTransactionId(),r=new O.ToDeviceChannel(this.baseApis,e,[t],n,t),o=new k.VerificationRequest(r,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,n,o);const s=o.beginKeyVerification(i,{userId:e,deviceId:t});return yield Promise.race([s.verify(),o.waitFor((e=>e.started))]),o}))}getOlmSessionsForUser(e){return a(this,void 0,void 0,(function*(){const t=this.getStoredDevicesForUser(e)||[],i={};for(const e of t){const t=e.getIdentityKey(),n=yield this.olmDevice.getSessionInfoForDevice(t);i[e.deviceId]={deviceIdKey:t,sessions:n}}return i}))}getEventSenderDeviceInfo(e){const t=e.getSenderKey(),i=e.getWireContent().algorithm;if(!t||!i)return null;if(e.isKeySourceUntrusted())return null;const n=this.deviceList.getDeviceByIdentityKey(i,t);if(null===n)return null;const r=e.getClaimedEd25519Key();return r?r!==n.getFingerprint()?(f.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+" but sender device has key "+n.getFingerprint()),null):n:(f.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){var t,i;const n={};if(n.senderKey=null!==(t=e.getSenderKey())&&void 0!==t?t:void 0,n.algorithm=e.getWireContent().algorithm,!n.senderKey||!n.algorithm)return n.encrypted=!1,n;n.encrypted=!0,e.isKeySourceUntrusted()?n.authenticated=!1:n.authenticated=!0,n.sender=null!==(i=this.deviceList.getDeviceByIdentityKey(n.algorithm,n.senderKey))&&void 0!==i?i:void 0;const r=e.getClaimedEd25519Key();return r||(f.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),n.mismatchedSender=!0),n.sender&&r!==n.sender.getFingerprint()&&(f.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+"but sender device has key "+n.sender.getFingerprint()),n.mismatchedSender=!0),n}forceDiscardSession(e){const t=this.roomEncryptors.get(e);if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");return t.forceDiscardSession(),Promise.resolve()}setRoomEncryption(e,t,i){return a(this,void 0,void 0,(function*(){const n=this.clientStore.getRoom(e);if(!n)throw new Error(`Unable to enable encryption tracking devices in unknown room ${e}`);yield this.setRoomEncryptionImpl(n,t),this.lazyLoadMembers||i||this.deviceList.refreshOutdatedDeviceLists()}))}setRoomEncryptionImpl(e,t){return a(this,void 0,void 0,(function*(){const i=e.roomId;if(!t.algorithm)return void f.logger.log("Ignoring setRoomEncryption with no algorithm");const n=this.roomList.getRoomEncryption(i);if(n&&JSON.stringify(n)!=JSON.stringify(t))return void f.logger.error("Ignoring m.room.encryption event which requests a change of config in "+i);if(this.roomEncryptors.get(i))return;let r=null;n||(r=this.roomList.setRoomEncryption(i,t));const o=y.ENCRYPTION_CLASSES.get(t.algorithm);if(!o)throw new Error("Unable to encrypt with "+t.algorithm);const s=new o({userId:this.userId,deviceId:this.deviceId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:i,config:t});if(this.roomEncryptors.set(i,s),r&&(yield r),f.logger.log(`Enabling encryption in ${i}`),e.membersLoaded())yield this.trackRoomDevicesImpl(e);else{const t=n=>{e.off(K.RoomStateEvent.Update,t),e.membersLoaded()&&this.trackRoomDevicesImpl(e).catch((e=>{f.logger.error(`Error enabling device tracking in ${i}`,e)}))};e.on(K.RoomStateEvent.Update,t)}}))}trackRoomDevices(e){const t=this.clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);return this.trackRoomDevicesImpl(t)}trackRoomDevicesImpl(e){const t=e.roomId,i=()=>a(this,void 0,void 0,(function*(){if(!this.roomEncryptors.has(t))return;f.logger.log(`Starting to track devices for room ${t} ...`);(yield e.getEncryptionTargetMembers()).forEach((e=>{this.deviceList.startTrackingDeviceList(e.userId)}))}));let n=this.roomDeviceTrackingState[t];return n||(n=i(),this.roomDeviceTrackingState[t]=n.catch((e=>{throw delete this.roomDeviceTrackingState[t],e}))),n}ensureOlmSessionsForUsers(e,t){const i=new Map;for(const t of e){const e=[];i.set(t,e);const n=this.getStoredDevicesForUser(t)||[];for(const t of n){t.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(t.verified!=$.BLOCKED&&e.push(t))}}return g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,i,t)}exportRoomKeys(){return a(this,void 0,void 0,(function*(){const e=[];return yield this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],(t=>{this.cryptoStore.getAllEndToEndInboundGroupSessions(t,(t=>{if(null===t)return;const i=this.olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId,t.sessionData);delete i.first_known_index,i.algorithm=g.MEGOLM_ALGORITHM,e.push(i)}))})),e}))}importRoomKeys(e,t={}){let i=0,n=0;const r=e.length;function o(){var e;null===(e=t.progressCallback)||void 0===e||e.call(t,{stage:"load_keys",successes:i,failures:n,total:r})}return Promise.all(e.map((e=>{if(!e.room_id||!e.algorithm)return f.logger.warn("ignoring room key entry with missing fields",e),n++,t.progressCallback&&o(),null;return this.getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e,t).finally((()=>{i++,t.progressCallback&&o()}))}))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){const t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}encryptEvent(e,t){return a(this,void 0,void 0,(function*(){const i=e.getRoomId(),n=this.roomEncryptors.get(i);if(!n)throw new Error("Room "+i+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");yield this.trackRoomDevicesImpl(t);let r=e.getContent();const o=r["m.relates_to"];o&&(r=Object.assign({},r),delete r["m.relates_to"]);const s=r["io.element.performance_metrics"];s&&(r=Object.assign({},r),delete r["io.element.performance_metrics"]);const a=yield n.encryptMessage(t,e.getType(),r);o&&(a["m.relates_to"]=o),s&&(a["io.element.performance_metrics"]=s),e.makeEncrypted("m.room.encrypted",a,this.olmDevice.deviceCurve25519Key,this.olmDevice.deviceEd25519Key)}))}decryptEvent(e){return a(this,void 0,void 0,(function*(){if(e.isRedacted()){const t=new N.MatrixEvent(Object.assign({room_id:e.getRoomId()},e.getUnsigned().redacted_because));let i=e.getUnsigned().redacted_because;if(t.isEncrypted())try{i=(yield this.decryptEvent(t)).clearEvent}catch(e){f.logger.warn("Decryption of redaction failed. Falling back to unencrypted event.",e)}return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:i}}}}{const t=e.getWireContent();return this.getRoomDecryptor(e.getRoomId(),t.algorithm).decryptEvent(e)}}))}handleDeviceListChanges(e,t){return a(this,void 0,void 0,(function*(){e.oldSyncToken&&(yield this.evalDeviceListChanges(t))}))}requestRoomKey(e,t,i=!1){return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,i).then((()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()})).catch((e=>{f.logger.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{f.logger.warn("Error clearing pending room key requests",e)}))}cancelAndResendAllOutgoingKeyRequests(){return a(this,void 0,void 0,(function*(){yield this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}))}onCryptoEvent(e,t){return a(this,void 0,void 0,(function*(){const i=t.getContent();yield this.setRoomEncryptionImpl(e,i)}))}onSyncWillProcess(e){return a(this,void 0,void 0,(function*(){e.oldSyncToken||(f.logger.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}))}onSyncCompleted(e){var t;return a(this,void 0,void 0,(function*(){this.deviceList.setSyncToken(null!==(t=e.nextSyncToken)&&void 0!==t?t:null),this.deviceList.saveIfDirty(),this.deviceList.startTrackingDeviceList(this.userId),this.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(this.maybeUploadOneTimeKeys(),this.processReceivedRoomKeyRequests(),this.outgoingRoomKeyRequestManager.sendQueuedRequests(),this.sendKeyRequestsImmediately=!0)}))}evalDeviceListChanges(e){return a(this,void 0,void 0,(function*(){if(Array.isArray(null==e?void 0:e.changed)&&e.changed.forEach((e=>{this.deviceList.invalidateUserDeviceList(e)})),Array.isArray(null==e?void 0:e.left)&&e.left.length){const t=new Set(yield this.getTrackedE2eUsers());e.left.forEach((e=>{t.has(e)||this.deviceList.stopTrackingDeviceList(e)}))}}))}getTrackedE2eUsers(){return a(this,void 0,void 0,(function*(){const e=[];for(const t of this.getTrackedE2eRooms()){const i=yield t.getEncryptionTargetMembers();for(const t of i)e.push(t.userId)}return e}))}getTrackedE2eRooms(){return this.clientStore.getRooms().filter((e=>{if(!this.roomEncryptors.get(e.roomId))return!1;if(!this.roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t}))}encryptAndSendToDevices(e,t){return a(this,void 0,void 0,(function*(){const i={eventType:u.EventType.RoomMessageEncrypted,batch:[]};try{yield Promise.all(e.map((({userId:e,deviceInfo:n})=>a(this,void 0,void 0,(function*(){const r=n.deviceId,o={algorithm:g.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[u.ToDeviceMessageId]:(0,l.v4)()};i.batch.push({userId:e,deviceId:r,payload:o}),yield g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[e,[n]]])),yield g.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,e,n,t)}))))),i.batch=i.batch.filter((e=>Object.keys(e.payload.ciphertext).length>0||(f.logger.log(`No ciphertext for device ${e.userId}:${e.deviceId}: pruning`),!1)));try{yield this.baseApis.queueToDevice(i)}catch(e){throw f.logger.error("sendToDevice failed",e),e}}catch(e){throw f.logger.error("encryptAndSendToDevices promises failed",e),e}}))}preprocessToDeviceMessages(e){return a(this,void 0,void 0,(function*(){return e.filter((e=>{var t;return!(e.type===u.EventType.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes(null===(t=e.content)||void 0===t?void 0:t.algorithm))||(f.logger.log("Ignoring invalid encrypted to-device event from "+e.sender),!1)}))}))}preprocessOneTimeKeyCounts(e){const t=e.get("signed_curve25519")||0;return this.updateOneTimeKeyCount(t),Promise.resolve()}preprocessUnusedFallbackKeys(e){return this.setNeedsNewFallback(!e.has("signed_curve25519")),Promise.resolve()}onRoomKeyEvent(e){const t=e.getContent();if(!t.room_id||!t.algorithm)return void f.logger.error("key event is missing fields");this.backupManager.checkedForBackup||this.backupManager.checkAndStart();this.getRoomDecryptor(t.room_id,t.algorithm).onRoomKeyEvent(e)}onRoomKeyWithheldEvent(e){const t=e.getContent();if(!(("m.no_olm"===t.code||t.room_id&&t.session_id)&&t.algorithm&&t.sender_key))return void f.logger.error("key withheld event is missing fields");f.logger.info(`Got room key withheld event from ${e.getSender()} for ${t.algorithm} session ${t.sender_key}|${t.session_id} in room ${t.room_id} with code ${t.code} (${t.reason})`);const i=this.getRoomDecryptor(t.room_id,t.algorithm);if(i.onRoomKeyWithheldEvent&&i.onRoomKeyWithheldEvent(e),!t.room_id){const e=this.getRoomDecryptors(t.algorithm);for(const i of e)i.retryDecryptionFromSender(t.sender_key)}}onKeyVerificationMessage(e){if(!O.ToDeviceChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.toDeviceVerificationRequests,(e=>{if(!O.ToDeviceChannel.canCreateRequest(O.ToDeviceChannel.getEventType(e)))return;const t=e.getContent(),i=t&&t.from_device;if(!i)return;const n=e.getSender(),r=new O.ToDeviceChannel(this.baseApis,n,[i]);return new k.VerificationRequest(r,this.verificationMethods,this.baseApis)}))}handleVerificationEvent(e,t,i,n=!0){return a(this,void 0,void 0,(function*(){if(e.isSending()&&e.status!=N.EventStatus.SENT){let t,i;try{yield new Promise(((n,r)=>{t=n,i=()=>{e.status==N.EventStatus.CANCELLED&&r(new Error("Event status set to CANCELLED."))},e.once(N.MatrixEventEvent.LocalEventIdReplaced,t),e.on(N.MatrixEventEvent.Status,i)}))}catch(e){return void f.logger.error("error while waiting for the verification event to be sent: ",e)}finally{e.removeListener(N.MatrixEventEvent.LocalEventIdReplaced,t),e.removeListener(N.MatrixEventEvent.Status,i)}}let r=t.getRequest(e),o=!1;if(!r){if(r=i(e),!r)return void f.logger.log(`Crypto: could not find VerificationRequest for ${e.getType()}, and could not create one, so ignoring.`);o=!0,t.setRequest(e,r)}e.setVerificationRequest(r);try{yield r.channel.handleEvent(e,r,n)}catch(e){f.logger.error("error while handling verification event",e)}o&&!r.initiatedByMe&&!r.invalid&&!r.observeOnly&&this.baseApis.emit(H.VerificationRequest,r)}))}onToDeviceBadEncrypted(e){return a(this,void 0,void 0,(function*(){const t=e.getWireContent(),i=e.getSender(),n=t.algorithm,r=t.sender_key;this.baseApis.emit(j.ClientEvent.UndecryptableToDeviceEvent,e);const o=()=>{const e=this.getRoomDecryptors(g.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(r)};if(void 0===i||void 0===r||void 0===r)return;const s=this.lastNewSessionForced.getOrCreate(i),a=s.getOrCreate(r);if(a+36e5>Date.now())return f.logger.debug("New session already forced with device "+i+":"+r+" at "+a+": not forcing another"),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),void o();let c=this.deviceList.getDeviceByIdentityKey(n,r);if(!c&&(yield this.downloadKeys([i],!1),c=this.deviceList.getDeviceByIdentityKey(n,r),!c))return f.logger.info("Couldn't find device for identity key "+r+": not re-establishing session"),yield this.olmDevice.recordSessionProblem(r,"wedged",!1),void o();const d=new Map([[i,[c]]]);yield g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,d,!0),s.set(r,Date.now());const h={algorithm:g.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[u.ToDeviceMessageId]:(0,l.v4)()};yield g.encryptMessageForDevice(h.ciphertext,this.userId,this.deviceId,this.olmDevice,i,c,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),o(),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[c.deviceId,h]])]]));const p=yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(i,c.deviceId);for(const e of p)this.requestRoomKey(e.requestBody,e.recipients,!0)}))}onRoomMembership(e,t,i){var n;const r=t.roomId,o=this.roomEncryptors.get(r);o&&(r in this.roomDeviceTrackingState&&("join"==t.membership?(f.logger.log("Join event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&(null===(n=this.clientStore.getRoom(r))||void 0===n?void 0:n.shouldEncryptForInvitedMembers())&&(f.logger.log("Invite event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId))),o.onRoomMembership(e,t,i))}onRoomKeyRequestEvent(e){const t=e.getContent();if("request"===t.action){const t=new z(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new Y(e);this.receivedRoomKeyRequestCancellations.push(t)}}processReceivedRoomKeyRequests(){return a(this,void 0,void 0,(function*(){if(!this.processingRoomKeyRequests){this.processingRoomKeyRequests=!0;try{const e=this.receivedRoomKeyRequests;this.receivedRoomKeyRequests=[];const t=this.receivedRoomKeyRequestCancellations;this.receivedRoomKeyRequestCancellations=[],yield Promise.all(e.map((e=>this.processReceivedRoomKeyRequest(e)))),yield Promise.all(t.map((e=>this.processReceivedRoomKeyRequestCancellation(e))))}catch(e){f.logger.error(`Error processing room key requsts: ${e}`)}finally{this.processingRoomKeyRequests=!1}}}))}processReceivedRoomKeyRequest(e){return a(this,void 0,void 0,(function*(){const t=e.userId,i=e.deviceId,n=e.requestBody,r=n.room_id,o=n.algorithm;if(f.logger.log(`m.room_key_request from ${t}:${i} for ${r} / ${n.session_id} (id ${e.requestId})`),t!==this.userId){if(!this.roomEncryptors.get(r))return void f.logger.debug(`room key request for unencrypted room ${r}`);const e=this.roomEncryptors.get(r),o=this.deviceList.getStoredDevice(t,i);if(!o)return void f.logger.debug(`Ignoring keyshare for unknown device ${t}:${i}`);try{yield e.reshareKeyWithDevice(n.sender_key,n.session_id,t,o)}catch(e){f.logger.warn("Failed to re-share keys for session "+n.session_id+" with device "+t+":"+o.deviceId,e)}return}if(i===this.deviceId)return void f.logger.log("Ignoring room key request from ourselves");if(!this.roomDecryptors.has(r))return void f.logger.log(`room key request for unencrypted room ${r}`);const s=this.roomDecryptors.get(r).get(o);if(s)if(yield s.hasKeysForKeyRequest(e)){if(e.share=()=>{s.shareKeysWithDevice(e)},this.checkDeviceTrust(t,i).isVerified())return f.logger.log("device is already verified: sharing keys"),void e.share();this.emit(H.RoomKeyRequest,e)}else f.logger.log(`room key request for unknown session ${r} / `+n.session_id);else f.logger.log(`room key request for unknown alg ${o} in room ${r}`)}))}processReceivedRoomKeyRequestCancellation(e){return a(this,void 0,void 0,(function*(){f.logger.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit(H.RoomKeyRequestCancellation,e)}))}getRoomDecryptor(e,t){let i,n;if(e&&(i=this.roomDecryptors.get(e),i||(i=new Map,this.roomDecryptors.set(e,i)),n=i.get(t),n))return n;const r=y.DECRYPTION_CLASSES.get(t);if(!r)throw new y.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return n=new r({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:null!=e?e:void 0}),i&&i.set(t,n),n}getRoomDecryptors(e){const t=[];for(const i of this.roomDecryptors.values())i.has(e)&&t.push(i.get(e));return t}signObject(e){return a(this,void 0,void 0,(function*(){const t=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;const n=t.get(this.userId)||{};t.set(this.userId,n),n["ed25519:"+this.deviceId]=yield this.olmDevice.sign(d.default.stringify(e)),e.signatures=(0,q.recursiveMapToObject)(t),void 0!==i&&(e.unsigned=i)}))}}function G(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return g.encodeBase64(t)}i.Crypto=W,i.fixBackupKey=G;class z{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}i.IncomingRoomKeyRequest=z;class Y{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../@types/event":306,"../ReEmitter":317,"../client":321,"../errors":359,"../logger":374,"../models/event":383,"../models/room":392,"../models/room-member":389,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./DeviceList":325,"./EncryptionSetup":326,"./OlmDevice":327,"./OutgoingRoomKeyRequestManager":328,"./SecretStorage":330,"./aes":331,"./algorithms":333,"./backup":337,"./dehydration":339,"./deviceinfo":340,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346,"./verification/IllegalMethod":351,"./verification/QRCode":352,"./verification/SAS":353,"./verification/request/InRoomChannel":355,"./verification/request/ToDeviceChannel":356,"./verification/request/VerificationRequest":357,"another-json":1,buffer:68,uuid:287}],342:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.deriveKey=i.keyFromPassphrase=i.keyFromAuthData=void 0;const r=e("../randomstring"),o=e("./crypto"),s=5e5,a=256;function c(e,t,i,r=a){return n(this,void 0,void 0,(function*(){if(!o.subtleCrypto||!o.TextEncoder)throw new Error("Password-based backup is not available on this platform");const n=yield o.subtleCrypto.importKey("raw",(new o.TextEncoder).encode(e),{name:"PBKDF2"},!1,["deriveBits"]),s=yield o.subtleCrypto.deriveBits({name:"PBKDF2",salt:(new o.TextEncoder).encode(t),iterations:i,hash:"SHA-512"},n,r);return new Uint8Array(s)}))}i.keyFromAuthData=function(e,i){if(!t.Olm)throw new Error("Olm is not available");if(!e.private_key_salt||!e.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return c(i,e.private_key_salt,e.private_key_iterations,e.private_key_bits||a)},i.keyFromPassphrase=function(e){return n(this,void 0,void 0,(function*(){if(!t.Olm)throw new Error("Olm is not available");const i=(0,r.randomString)(32);return{key:yield c(e,i,s,a),salt:i,iterations:s}}))},i.deriveKey=c}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../randomstring":398,"./crypto":338}],343:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.decodeBase64=i.encodeUnpaddedBase64=i.encodeBase64=i.isOlmEncrypted=i.pkVerify=i.pkSign=i.verifySignature=i.ensureOlmSessionsForDevices=i.getExistingOlmSessions=i.encryptMessageForDevice=i.MEGOLM_BACKUP_ALGORITHM=i.MEGOLM_ALGORITHM=i.OLM_ALGORITHM=void 0;const s=o(e("another-json")),a=e("../logger"),c=e("../@types/event"),d=e("../utils");var l;function u(e,t,i,n){return r(this,void 0,void 0,(function*(){const r=n.deviceId;try{yield h(e,t,i,r,n.getFingerprint())}catch(e){return a.logger.error("Unable to verify signature on one-time key for device "+i+":"+r+":",e),null}let o;try{o=yield e.createOutboundSession(n.getIdentityKey(),t.key)}catch(e){return a.logger.error("Error starting olm session with device "+i+":"+r+": "+e),null}return a.logger.log("Started new olm sessionid "+o+" for device "+i+":"+r),o}))}function h(e,t,i,n,o){return r(this,void 0,void 0,(function*(){const r="ed25519:"+n,a=((t.signatures||{})[i]||{})[r];if(!a)throw Error("No signature");const c=Object.assign({},t);"unsigned"in c&&delete c.unsigned,delete c.signatures;const d=s.default.stringify(c);e.verifySignature(o,d,a)}))}function f(e){return n.from(e).toString("base64")}!function(e){e.Olm="m.olm.v1.curve25519-aes-sha2",e.Megolm="m.megolm.v1.aes-sha2",e.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2"}(l||(l={})),i.OLM_ALGORITHM=l.Olm,i.MEGOLM_ALGORITHM=l.Megolm,i.MEGOLM_BACKUP_ALGORITHM=l.MegolmBackup,i.encryptMessageForDevice=function(e,t,i,n,o,s,c){return r(this,void 0,void 0,(function*(){const r=s.getIdentityKey(),d=yield n.getSessionIdForDevice(r);if(null===d)return void a.logger.log(`[olmlib.encryptMessageForDevice] Unable to find Olm session for device ${o}:${s.deviceId}`);a.logger.log(`[olmlib.encryptMessageForDevice] Using Olm session ${d} for device ${o}:${s.deviceId}`);const l=Object.assign({sender:t,sender_device:i,keys:{ed25519:n.deviceEd25519Key},recipient:o,recipient_keys:{ed25519:s.getFingerprint()}},c);e[r]=yield n.encryptMessage(r,d,JSON.stringify(l))}))},i.getExistingOlmSessions=function(e,t,i){return r(this,void 0,void 0,(function*(){const t=new d.MapWithDefault((()=>[])),n=new d.MapWithDefault((()=>new Map)),o=[];for(const[s,a]of Object.entries(i))for(const i of a){const a=i.deviceId,c=i.getIdentityKey();o.push((()=>r(this,void 0,void 0,(function*(){const r=yield e.getSessionIdForDevice(c,!0);null===r?t.getOrCreate(s).push(i):n.getOrCreate(s).set(a,{device:i,sessionId:r})})))())}return yield Promise.all(o),[t,n]}))},i.ensureOlmSessionsForDevices=function(e,t,i,n=!1,o,s,c=a.logger){var d,l,h;return r(this,void 0,void 0,(function*(){const r=[],a=new Map,f=new Map;for(const t of i.values())for(const i of t){const t=i.getIdentityKey();t!==e.deviceCurve25519Key&&(e.sessionsInProgress[t]||(e.sessionsInProgress[t]=new Promise((i=>{f.set(t,(n=>{delete e.sessionsInProgress[t],i(n)}))}))))}for(const[t,o]of i){const i=new Map;a.set(t,i);for(const s of o){const o=s.deviceId,a=s.getIdentityKey();if(a===e.deviceCurve25519Key){c.info("Attempted to start session with ourself! Ignoring"),i.set(o,{device:s,sessionId:null});continue}const d=`for ${a} (${t}:${o})`,l=yield e.getSessionIdForDevice(a,!!f.get(a),c),u=f.get(a);null!==l&&u&&u(),(null===l||n)&&(n?c.info(`Forcing new Olm session ${d}`):c.info(`Making new Olm session ${d}`),r.push([t,o])),i.set(o,{device:s,sessionId:l})}}if(0===r.length)return a;const p="signed_curve25519";let g,v=`one-time keys for ${r.length} devices`;try{c.debug(`Claiming ${v}`),g=yield t.claimOneTimeKeys(r,p,o),c.debug(`Claimed ${v}`)}catch(e){for(const e of f.values())e();throw c.log(`Failed to claim ${v}`,e,r),e}s&&"failures"in g&&s.push(...Object.keys(g.failures));const m=g.one_time_keys||{},y=[];for(const[t,r]of i){const i=m[t]||{};for(const o of r){const r=o.deviceId,s=o.getIdentityKey();if(s===e.deviceCurve25519Key)continue;if((null===(l=null===(d=a.get(t))||void 0===d?void 0:d.get(r))||void 0===l?void 0:l.sessionId)&&!n)continue;const g=i[r]||{};let v=null;for(const e in g)0===e.indexOf(p+":")&&(v=g[e]);v?y.push(u(e,v,t,o).then((e=>{var i,n;null===(i=f.get(s))||void 0===i||i(null!=e?e:void 0);const o=null===(n=a.get(t))||void 0===n?void 0:n.get(r);o&&(o.sessionId=e)}),(e=>{var t;throw null===(t=f.get(s))||void 0===t||t(),e}))):(c.warn(`No one-time keys (alg=${p}) for device ${t}:${r}`),null===(h=f.get(s))||void 0===h||h())}}return v=`Olm sessions for ${y.length} devices`,c.debug(`Starting ${v}`),yield Promise.all(y),c.debug(`Started ${v}`),a}))},i.verifySignature=h,i.pkSign=function(e,i,n,r){let o=!1;if(i instanceof Uint8Array){const e=new t.Olm.PkSigning;r=e.init_with_seed(i),i=e,o=!0}const a=e.signatures||{};delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{const t=a[n]||{};return a[n]=t,t["ed25519:"+r]=i.sign(s.default.stringify(e))}finally{e.signatures=a,c&&(e.unsigned=c),o&&i.free()}},i.pkVerify=function(e,i,n){const r="ed25519:"+i;if(!(e.signatures&&e.signatures[n]&&e.signatures[n][r]))throw new Error("No signature");const o=e.signatures[n][r],a=new t.Olm.Utility,c=e.signatures;delete e.signatures;const d=e.unsigned;e.unsigned&&delete e.unsigned;try{a.ed25519_verify(i,s.default.stringify(e),o)}finally{e.signatures=c,d&&(e.unsigned=d),a.free()}},i.isOlmEncrypted=function(e){return e.getSenderKey()?!(e.getWireType()!==c.EventType.RoomMessageEncrypted||!["m.olm.v1.curve25519-aes-sha2"].includes(e.getWireContent().algorithm))||(a.logger.error("Event was not encrypted using an appropriate algorithm"),!1):(a.logger.error("Event has no sender key (not encrypted?)"),!1)},i.encodeBase64=f,i.encodeUnpaddedBase64=function(e){return f(e).replace(/=+$/g,"")},i.decodeBase64=function(e){return n.from(e,"base64")}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../@types/event":306,"../logger":374,"../utils":416,"another-json":1,buffer:68}],344:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return o(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.decodeRecoveryKey=i.encodeRecoveryKey=void 0;const a=s(e("bs58")),c=[139,1];i.encodeRecoveryKey=function(e){var t;const i=n.alloc(c.length+e.length+1);i.set(c,0),i.set(e,c.length);let r=0;for(let e=0;e<i.length-1;++e)r^=i[e];return i[i.length-1]=r,null===(t=a.encode(i).match(/.{1,4}/g))||void 0===t?void 0:t.join(" ")},i.decodeRecoveryKey=function(e){const i=a.decode(e.replace(/ /g,""));let n=0;for(const e of i)n^=e;if(0!==n)throw new Error("Incorrect parity");for(let e=0;e<c.length;++e)if(i[e]!==c[e])throw new Error("Incorrect prefix");if(i.length!==c.length+t.Olm.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");return Uint8Array.from(i.slice(c.length,c.length+t.Olm.PRIVATE_KEY_LENGTH))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{bs58:65,buffer:68}],345:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.upgradeDatabase=i.VERSION=i.Backend=void 0;const a=e("../../logger"),c=o(e("../../utils"));i.Backend=class{constructor(e){this.db=e,this.nextTxnId=0,e.onversionchange=()=>{a.logger.log(`versionchange for indexeddb ${this.db.name}: closing`),e.close()}}startup(){return s(this,void 0,void 0,(function*(){return this}))}deleteAllData(){return s(this,void 0,void 0,(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")}))}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return new Promise(((i,n)=>{const r=this.db.transaction("outgoingRoomKeyRequests","readwrite");r.onerror=n,this._getOutgoingRoomKeyRequest(r,t,(n=>{if(n)return a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),void i(n);a.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),r.oncomplete=()=>{i(e)};r.objectStore("outgoingRoomKeyRequests").add(e)}))}))}getOutgoingRoomKeyRequest(e){return new Promise(((t,i)=>{const n=this.db.transaction("outgoingRoomKeyRequests","readonly");n.onerror=i,this._getOutgoingRoomKeyRequest(n,e,(e=>{t(e)}))}))}_getOutgoingRoomKeyRequest(e,t,i){const n=e.objectStore("outgoingRoomKeyRequests").index("session").openCursor([t.room_id,t.session_id]);n.onsuccess=()=>{const e=n.result;if(!e)return void i(null);const r=e.value;c.deepCompare(r.requestBody,t)?i(r):e.continue()}}getOutgoingRoomKeyRequestByState(e){if(0===e.length)return Promise.resolve(null);let t,i=0;const n=this.db.transaction("outgoingRoomKeyRequests","readonly"),r=n.objectStore("outgoingRoomKeyRequests"),o=e[i];return r.index("state").openCursor(o).onsuccess=function n(){const r=this.result;if(r)return void(t=r.value);if(i++,i>=e.length)return;const o=e[i];this.source.openCursor(o).onsuccess=n},u(n).then((()=>t))}getAllOutgoingRoomKeyRequestsByState(e){return new Promise(((t,i)=>{const n=this.db.transaction("outgoingRoomKeyRequests","readonly").objectStore("outgoingRoomKeyRequests").index("state").getAll(e);n.onsuccess=()=>t(n.result),n.onerror=()=>i(n.error)}))}getOutgoingRoomKeyRequestsByTarget(e,t,i){let n=0;const r=[];const o=this.db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),a=i[n];return s.index("state").openCursor(a).onsuccess=function o(){const s=this.result;if(s){const i=s.value;i.recipients.some((i=>i.userId===e&&i.deviceId===t))&&r.push(i),s.continue()}else{if(n++,n>=i.length)return;const e=i[n];this.source.openCursor(e).onsuccess=o}},u(o).then((()=>r))}updateOutgoingRoomKeyRequest(e,t,i){let n=null;const r=this.db.transaction("outgoingRoomKeyRequests","readwrite");return r.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=function(){const e=this.result;if(!e)return;const r=e.value;r.state==t?(Object.assign(r,i),e.update(r),n=r):a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${r.state}`)},u(r).then((()=>n))}deleteOutgoingRoomKeyRequest(e,t){const i=this.db.transaction("outgoingRoomKeyRequests","readwrite"),n=i.objectStore("outgoingRoomKeyRequests").openCursor(e);return n.onsuccess=()=>{const e=n.result;if(!e)return;const i=e.value;i.state==t?e.delete():a.logger.warn(`Cannot delete room key request in state ${i.state} (expected ${t})`)},u(i)}getAccount(e,t){const i=e.objectStore("account").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const i=e.objectStore("account").get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}getSecretStorePrivateKey(e,t,i){const n=e.objectStore("account").get(`ssss_cache:${i}`);n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeCrossSigningKeys(e,t){e.objectStore("account").put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,i){e.objectStore("account").put(i,`ssss_cache:${t}`)}countEndToEndSessions(e,t){const i=e.objectStore("sessions").count();i.onsuccess=function(){try{t(i.result)}catch(t){l(e,t)}}}getEndToEndSessions(e,t,i){const n=t.objectStore("sessions").index("deviceKey").openCursor(e),r={};n.onsuccess=function(){const e=n.result;if(e)r[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{i(r)}catch(e){l(t,e)}}}getEndToEndSession(e,t,i,n){const r=i.objectStore("sessions").get([e,t]);r.onsuccess=function(){try{r.result?n({session:r.result.session,lastReceivedMessageTs:r.result.lastReceivedMessageTs}):n(null)}catch(e){l(i,e)}}}getAllEndToEndSessions(e,t){const i=e.objectStore("sessions").openCursor();i.onsuccess=function(){try{const e=i.result;e?(t(e.value),e.continue()):t(null)}catch(t){l(e,t)}}}storeEndToEndSession(e,t,i,n){n.objectStore("sessions").put({deviceKey:e,sessionId:t,session:i.session,lastReceivedMessageTs:i.lastReceivedMessageTs})}storeEndToEndSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){const n=this.db.transaction("session_problems","readwrite");n.objectStore("session_problems").put({deviceKey:e,type:t,fixed:i,time:Date.now()}),yield u(n)}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){let i=null;const n=this.db.transaction("session_problems","readwrite"),r=n.objectStore("session_problems").index("deviceKey").getAll(e);return r.onsuccess=()=>{const e=r.result;if(!e.length)return void(i=null);e.sort(((e,t)=>e.time-t.time));const n=e[e.length-1];for(const r of e)if(r.time>t)return void(i=Object.assign({},r,{fixed:n.fixed}));i=n.fixed?null:n},yield u(n),i}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),i=[];return yield Promise.all(e.map((e=>new Promise((n=>{const{userId:r,deviceInfo:o}=e,s=t.get([r,o.deviceId]);s.onsuccess=function(){s.result||(t.put({userId:r,deviceId:o.deviceId}),i.push(e)),n()}}))))),i}))}getEndToEndInboundGroupSession(e,t,i,n){let r=!1,o=!1;const s=i.objectStore("inbound_group_sessions").get([e,t]);s.onsuccess=function(){try{r=s.result?s.result.session:null,!1!==o&&n(r,o)}catch(e){l(i,e)}};const a=i.objectStore("inbound_group_sessions_withheld").get([e,t]);a.onsuccess=function(){try{o=a.result?a.result.session:null,!1!==r&&n(r,o)}catch(e){l(i,e)}}}getAllEndToEndInboundGroupSessions(e,t){const i=e.objectStore("inbound_group_sessions").openCursor();i.onsuccess=function(){const n=i.result;if(n){try{t({senderKey:n.value.senderCurve25519Key,sessionId:n.value.sessionId,sessionData:n.value.session})}catch(t){l(e,t)}n.continue()}else try{t(null)}catch(t){l(e,t)}}}addEndToEndInboundGroupSession(e,t,i,n){const r=n.objectStore("inbound_group_sessions").add({senderCurve25519Key:e,sessionId:t,session:i});r.onerror=i=>{var o;"ConstraintError"===(null===(o=r.error)||void 0===o?void 0:o.name)?(i.stopPropagation(),i.preventDefault(),a.logger.log("Ignoring duplicate inbound group session: "+e+" / "+t)):l(n,new Error("Failed to add inbound group session: "+r.error))}}storeEndToEndInboundGroupSession(e,t,i,n){n.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:i})}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){n.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:e,sessionId:t,session:i})}getEndToEndDeviceData(e,t){const i=e.objectStore("device_data").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}storeEndToEndDeviceData(e,t){t.objectStore("device_data").put(e,"-")}storeEndToEndRoom(e,t,i){i.objectStore("rooms").put(t,e)}getEndToEndRooms(e,t){const i={},n=e.objectStore("rooms").openCursor();n.onsuccess=function(){const r=n.result;if(r)i[r.key]=r.value,r.continue();else try{t(i)}catch(t){l(e,t)}}}getSessionsNeedingBackup(e){return new Promise(((t,i)=>{const n=[],r=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");r.onerror=i,r.oncomplete=function(){t(n)};const o=r.objectStore("sessions_needing_backup"),s=r.objectStore("inbound_group_sessions"),a=o.openCursor();a.onsuccess=function(){const t=a.result;if(t){const i=s.get(t.key);i.onsuccess=function(){n.push({senderKey:i.result.senderCurve25519Key,sessionId:i.result.sessionId,sessionData:i.result.session})},(!e||n.length<e)&&t.continue()}}}))}countSessionsNeedingBackup(e){e||(e=this.db.transaction("sessions_needing_backup","readonly"));const t=e.objectStore("sessions_needing_backup");return new Promise(((e,i)=>{const n=t.count();n.onerror=i,n.onsuccess=()=>e(n.result)}))}unmarkSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,n)=>{const r=i.delete([e.senderKey,e.sessionId]);r.onsuccess=t,r.onerror=n})))))}))}markSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,n)=>{const r=i.put({senderCurve25519Key:e.senderKey,sessionId:e.sessionId});r.onsuccess=t,r.onerror=n})))))}))}addSharedHistoryInboundGroupSession(e,t,i,n){n||(n=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));const r=n.objectStore("shared_history_inbound_group_sessions"),o=r.get([e]);o.onsuccess=()=>{const{sessions:n}=o.result||{sessions:[]};n.push([t,i]),r.put({roomId:e,sessions:n})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));const i=t.objectStore("shared_history_inbound_group_sessions").get([e]);return new Promise(((e,t)=>{i.onsuccess=()=>{const{sessions:t}=i.result||{sessions:[]};e(t)},i.onerror=t}))}addParkedSharedHistory(e,t,i){i||(i=this.db.transaction("parked_shared_history","readwrite"));const n=i.objectStore("parked_shared_history"),r=n.get([e]);r.onsuccess=()=>{const{parked:i}=r.result||{parked:[]};i.push(t),n.put({roomId:e,parked:i})}}takeParkedSharedHistory(e,t){t||(t=this.db.transaction("parked_shared_history","readwrite"));const i=t.objectStore("parked_shared_history").openCursor(e);return new Promise(((e,t)=>{i.onsuccess=()=>{const t=i.result;if(!t)return void e([]);const n=t.value;t.delete(),e(n)},i.onerror=t}))}doTxn(e,t,i,n=a.logger){const r=this.db.transaction(t,e),o=u(r),s=i(r);return o.then((()=>s))}};const d=[e=>{!function(e){const t=e.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});t.createIndex("session",["requestBody.room_id","requestBody.session_id"]),t.createIndex("state","state")}(e)},e=>{e.createObjectStore("account")},e=>{e.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")},e=>{e.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("device_data")},e=>{e.createObjectStore("rooms")},e=>{e.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),e.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},e=>{e.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},e=>{e.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}];function l(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function u(e){return new Promise(((t,i)=>{e.oncomplete=()=>{void 0!==e._mx_abortexception&&i(e._mx_abortexception),t(null)},e.onerror=t=>{void 0!==e._mx_abortexception?i(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),i(e.error))},e.onabort=t=>{void 0!==e._mx_abortexception?i(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),i(e.error))}}))}i.VERSION=d.length,i.upgradeDatabase=function(e,t){a.logger.log(`Upgrading IndexedDBCryptoStore from version ${t} to ${i.VERSION}`),d.forEach(((i,n)=>{t<=n&&i(e)}))}},{"../../logger":374,"../../utils":416}],346:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.IndexedDBCryptoStore=void 0;const s=e("../../logger"),a=e("./localStorage-crypto-store"),c=e("./memory-crypto-store"),d=o(e("./indexeddb-crypto-store-backend")),l=e("../../errors"),u=o(e("../../indexeddb-helpers"));class h{static exists(e,t){return u.exists(e,t)}constructor(e,t){this.indexedDB=e,this.dbName=t}startup(){return this.backendPromise||(this.backendPromise=new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`connecting to indexeddb ${this.dbName}`);const i=this.indexedDB.open(this.dbName,d.VERSION);i.onupgradeneeded=e=>{const t=i.result,n=e.oldVersion;d.upgradeDatabase(t,n)},i.onblocked=()=>{s.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},i.onerror=e=>{s.logger.log("Error connecting to indexeddb",e),t(i.error)},i.onsuccess=()=>{const t=i.result;s.logger.log(`connected to indexeddb ${this.dbName}`),e(new d.Backend(t))}})).then((e=>e.doTxn("readonly",[h.STORE_INBOUND_GROUP_SESSIONS,h.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(t=>{e.getEndToEndInboundGroupSession("","",t,(()=>{}))})).then((()=>e)))).catch((e=>{if("VersionError"===e.name)throw s.logger.warn("Crypto DB is too new for us to use!",e),new l.InvalidCryptoStoreError(l.InvalidCryptoStoreState.TooNew);s.logger.warn(`unable to connect to indexeddb ${this.dbName}: falling back to localStorage store: ${e}`);try{return new a.LocalStorageCryptoStore(t.localStorage)}catch(e){return s.logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`),new c.MemoryCryptoStore}})).then((e=>(this.backend=e,e)))),this.backendPromise}deleteAllData(){return new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`Removing indexeddb instance: ${this.dbName}`);const i=this.indexedDB.deleteDatabase(this.dbName);i.onblocked=()=>{s.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},i.onerror=e=>{s.logger.log("Error deleting data from indexeddb",e),t(i.error)},i.onsuccess=()=>{s.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}})).catch((e=>{s.logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`)}))}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,i){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,i)}updateOutgoingRoomKeyRequest(e,t,i){return this.backend.updateOutgoingRoomKeyRequest(e,t,i)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,i){this.backend.getSecretStorePrivateKey(e,t,i)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,i){this.backend.storeSecretStorePrivateKey(e,t,i)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,i,n){this.backend.getEndToEndSession(e,t,i,n)}getEndToEndSessions(e,t,i){this.backend.getEndToEndSessions(e,t,i)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,i,n){this.backend.storeEndToEndSession(e,t,i,n)}storeEndToEndSessionProblem(e,t,i){return this.backend.storeEndToEndSessionProblem(e,t,i)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}getEndToEndInboundGroupSession(e,t,i,n){this.backend.getEndToEndInboundGroupSession(e,t,i,n)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,i,n){this.backend.addEndToEndInboundGroupSession(e,t,i,n)}storeEndToEndInboundGroupSession(e,t,i,n){this.backend.storeEndToEndInboundGroupSession(e,t,i,n)}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,i,n)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,i){this.backend.storeEndToEndRoom(e,t,i)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,i,n){this.backend.addSharedHistoryInboundGroupSession(e,t,i,n)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}addParkedSharedHistory(e,t,i){this.backend.addParkedSharedHistory(e,t,i)}takeParkedSharedHistory(e,t){return this.backend.takeParkedSharedHistory(e,t)}doTxn(e,t,i,n){return this.backend.doTxn(e,t,i,n)}}i.IndexedDBCryptoStore=h,h.STORE_ACCOUNT="account",h.STORE_SESSIONS="sessions",h.STORE_INBOUND_GROUP_SESSIONS="inbound_group_sessions",h.STORE_INBOUND_GROUP_SESSIONS_WITHHELD="inbound_group_sessions_withheld",h.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS="shared_history_inbound_group_sessions",h.STORE_PARKED_SHARED_HISTORY="parked_shared_history",h.STORE_DEVICE_DATA="device_data",h.STORE_ROOMS="rooms",h.STORE_BACKUP="sessions_needing_backup"}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../errors":359,"../../indexeddb-helpers":372,"../../logger":374,"./indexeddb-crypto-store-backend":345,"./localStorage-crypto-store":347,"./memory-crypto-store":348}],347:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.LocalStorageCryptoStore=void 0;const r=e("../../logger"),o=e("./memory-crypto-store"),s=e("../../utils"),a="crypto.",c=a+"account",d=a+"cross_signing_keys",l=a+"notified_error_devices",u=a+"device_data",h=a+"inboundgroupsessions/",f=a+"inboundgroupsessions.withheld/",p=a+"rooms/",g=a+"sessionsneedingbackup";function v(e){return a+"sessions/"+e}function m(e){return a+"session.problems/"+e}function y(e,t){return h+e+"/"+t}function b(e,t){return f+e+"/"+t}function S(e){return p+e}class _ extends o.MemoryCryptoStore{static exists(e){var t;const i=e.length;for(let n=0;n<i;n++)if(null===(t=e.key(n))||void 0===t?void 0:t.startsWith(a))return!0;return!1}constructor(e){super(),this.store=e}countEndToEndSessions(e,t){var i;let n=0;for(let e=0;e<this.store.length;++e)(null===(i=this.store.key(e))||void 0===i?void 0:i.startsWith(v("")))&&++n;t(n)}_getEndToEndSessions(e){const t=E(this.store,v(e)),i={};for(const[e,n]of Object.entries(t||{}))i[e]="string"==typeof n?{session:n}:n;return i}getEndToEndSession(e,t,i,n){n(this._getEndToEndSessions(e)[t]||{})}getEndToEndSessions(e,t,i){i(this._getEndToEndSessions(e)||{})}getAllEndToEndSessions(e,t){var i;for(let e=0;e<this.store.length;++e)if(null===(i=this.store.key(e))||void 0===i?void 0:i.startsWith(v(""))){const i=this.store.key(e).split("/")[1];for(const e of Object.values(this._getEndToEndSessions(i)))t(e)}}storeEndToEndSession(e,t,i,n){const r=this._getEndToEndSessions(e)||{};r[t]=i,w(this.store,v(e),r)}storeEndToEndSessionProblem(e,t,i){return n(this,void 0,void 0,(function*(){const n=m(e),r=E(this.store,n)||[];r.push({type:t,fixed:i,time:Date.now()}),r.sort(((e,t)=>e.time-t.time)),w(this.store,n,r)}))}getEndToEndSessionProblem(e,t){return n(this,void 0,void 0,(function*(){const i=m(e),n=E(this.store,i)||[];if(!n.length)return null;const r=n[n.length-1];for(const e of n)if(e.time>t)return Object.assign({},e,{fixed:r.fixed});return r.fixed?null:r}))}filterOutNotifiedErrorDevices(e){return n(this,void 0,void 0,(function*(){const t=E(this.store,l)||{},i=[];for(const n of e){const{userId:e,deviceInfo:r}=n;e in t?r.deviceId in t[e]||(i.push(n),(0,s.safeSet)(t[e],r.deviceId,!0)):(i.push(n),(0,s.safeSet)(t,e,{[r.deviceId]:!0}))}return w(this.store,l,t),i}))}getEndToEndInboundGroupSession(e,t,i,n){n(E(this.store,y(e,t)),E(this.store,b(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(let e=0;e<this.store.length;++e){const i=this.store.key(e);(null==i?void 0:i.startsWith(h))&&t({senderKey:i.slice(h.length,h.length+43),sessionId:i.slice(h.length+44),sessionData:E(this.store,i)})}t(null)}addEndToEndInboundGroupSession(e,t,i,n){E(this.store,y(e,t))||this.storeEndToEndInboundGroupSession(e,t,i,n)}storeEndToEndInboundGroupSession(e,t,i,n){w(this.store,y(e,t),i)}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){w(this.store,b(e,t),i)}getEndToEndDeviceData(e,t){t(E(this.store,u))}storeEndToEndDeviceData(e,t){w(this.store,u,e)}storeEndToEndRoom(e,t,i){w(this.store,S(e),t)}getEndToEndRooms(e,t){const i={},n=S("");for(let e=0;e<this.store.length;++e){const t=this.store.key(e);if(null==t?void 0:t.startsWith(n)){i[t.slice(n.length)]=E(this.store,t)}}t(i)}getSessionsNeedingBackup(e){const t=E(this.store,g)||{},i=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const t=n.slice(0,43),r=n.slice(44);if(this.getEndToEndInboundGroupSession(t,r,null,(e=>{i.push({senderKey:t,sessionId:r,sessionData:e})})),e&&i.length>=e)break}return Promise.resolve(i)}countSessionsNeedingBackup(){const e=E(this.store,g)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=E(this.store,g)||{};for(const i of e)delete t[i.senderKey+"/"+i.sessionId];return w(this.store,g,t),Promise.resolve()}markSessionsNeedingBackup(e){const t=E(this.store,g)||{};for(const i of e)t[i.senderKey+"/"+i.sessionId]=!0;return w(this.store,g,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(c),Promise.resolve()}getAccount(e,t){t(E(this.store,c))}storeAccount(e,t){w(this.store,c,t)}getCrossSigningKeys(e,t){t(E(this.store,d))}getSecretStorePrivateKey(e,t,i){t(E(this.store,a+`ssss_cache.${i}`))}storeCrossSigningKeys(e,t){w(this.store,d,t)}storeSecretStorePrivateKey(e,t,i){w(this.store,a+`ssss_cache.${t}`,i)}doTxn(e,t,i){return Promise.resolve(i(null))}}function E(e,t){try{return JSON.parse(e.getItem(t))}catch(e){r.logger.log("Error: Failed to get key %s: %s",t,e.message),r.logger.log(e.stack)}return null}function w(e,t,i){e.setItem(t,JSON.stringify(i))}i.LocalStorageCryptoStore=_},{"../../logger":374,"../../utils":416,"./memory-crypto-store":348}],348:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MemoryCryptoStore=void 0;const a=e("../../logger"),c=o(e("../../utils")),d=e("../../utils");i.MemoryCryptoStore=class{constructor(){this.outgoingRoomKeyRequests=[],this.account=null,this.crossSigningKeys=null,this.privateKeys={},this.sessions={},this.sessionProblems={},this.notifiedErrorDevices={},this.inboundGroupSessions={},this.inboundGroupSessionsWithheld={},this.deviceData=null,this.rooms={},this.sessionsNeedingBackup={},this.sharedHistoryInboundGroupSessions={},this.parkedSharedHistory=new Map}startup(){return s(this,void 0,void 0,(function*(){return this}))}deleteAllData(){return Promise.resolve()}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return c.promiseTry((()=>{const i=this._getOutgoingRoomKeyRequest(t);return i?(a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),i):(a.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),this.outgoingRoomKeyRequests.push(e),e)}))}getOutgoingRoomKeyRequest(e){return Promise.resolve(this._getOutgoingRoomKeyRequest(e))}_getOutgoingRoomKeyRequest(e){for(const t of this.outgoingRoomKeyRequests)if(c.deepCompare(t.requestBody,e))return t;return null}getOutgoingRoomKeyRequestByState(e){for(const t of this.outgoingRoomKeyRequests)for(const i of e)if(t.state===i)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter((t=>t.state==e)))}getOutgoingRoomKeyRequestsByTarget(e,t,i){const n=[];for(const r of this.outgoingRoomKeyRequests)for(const o of i)r.state===o&&r.recipients.some((i=>i.userId===e&&i.deviceId===t))&&n.push(r);return Promise.resolve(n)}updateOutgoingRoomKeyRequest(e,t,i){for(const n of this.outgoingRoomKeyRequests)if(n.requestId===e)return n.state!==t?(a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${n.state}`),Promise.resolve(null)):(Object.assign(n,i),Promise.resolve(n));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(let i=0;i<this.outgoingRoomKeyRequests.length;i++){const n=this.outgoingRoomKeyRequests[i];if(n.requestId===e)return n.state!=t?(a.logger.warn(`Cannot delete room key request in state ${n.state} (expected ${t})`),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(i,1),Promise.resolve(n))}return Promise.resolve(null)}getAccount(e,t){t(this.account)}storeAccount(e,t){this.account=t}getCrossSigningKeys(e,t){t(this.crossSigningKeys)}getSecretStorePrivateKey(e,t,i){t(this.privateKeys[i]||null)}storeCrossSigningKeys(e,t){this.crossSigningKeys=t}storeSecretStorePrivateKey(e,t,i){this.privateKeys[t]=i}countEndToEndSessions(e,t){t(Object.keys(this.sessions).length)}getEndToEndSession(e,t,i,n){n((this.sessions[e]||{})[t]||null)}getEndToEndSessions(e,t,i){i(this.sessions[e]||{})}getAllEndToEndSessions(e,t){Object.entries(this.sessions).forEach((([e,i])=>{Object.entries(i).forEach((([i,n])=>{t(Object.assign(Object.assign({},n),{deviceKey:e,sessionId:i}))}))}))}storeEndToEndSession(e,t,i,n){let r=this.sessions[e];void 0===r&&(r={},this.sessions[e]=r),r[t]=i}storeEndToEndSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){const n=this.sessionProblems[e]=this.sessionProblems[e]||[];n.push({type:t,fixed:i,time:Date.now()}),n.sort(((e,t)=>e.time-t.time))}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){const i=this.sessionProblems[e]||[];if(!i.length)return null;const n=i[i.length-1];for(const e of i)if(e.time>t)return Object.assign({},e,{fixed:n.fixed});return n.fixed?null:n}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.notifiedErrorDevices,i=[];for(const n of e){const{userId:e,deviceInfo:r}=n;e in t?r.deviceId in t[e]||(i.push(n),(0,d.safeSet)(t[e],r.deviceId,!0)):(i.push(n),(0,d.safeSet)(t,e,{[r.deviceId]:!0}))}return i}))}getEndToEndInboundGroupSession(e,t,i,n){const r=e+"/"+t;n(this.inboundGroupSessions[r]||null,this.inboundGroupSessionsWithheld[r]||null)}getAllEndToEndInboundGroupSessions(e,t){for(const e of Object.keys(this.inboundGroupSessions))t({senderKey:e.slice(0,43),sessionId:e.slice(44),sessionData:this.inboundGroupSessions[e]});t(null)}addEndToEndInboundGroupSession(e,t,i,n){const r=e+"/"+t;void 0===this.inboundGroupSessions[r]&&(this.inboundGroupSessions[r]=i)}storeEndToEndInboundGroupSession(e,t,i,n){this.inboundGroupSessions[e+"/"+t]=i}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){const r=e+"/"+t;this.inboundGroupSessionsWithheld[r]=i}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,i){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){const t=[];for(const i in this.sessionsNeedingBackup)if(this.inboundGroupSessions[i]&&(t.push({senderKey:i.slice(0,43),sessionId:i.slice(44),sessionData:this.inboundGroupSessions[i]}),e&&i.length>=e))break;return Promise.resolve(t)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;delete this.sessionsNeedingBackup[e]}return Promise.resolve()}markSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;this.sessionsNeedingBackup[e]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(e,t,i){const n=this.sharedHistoryInboundGroupSessions[e]||[];n.push([t,i]),this.sharedHistoryInboundGroupSessions[e]=n}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}addParkedSharedHistory(e,t){var i;const n=null!==(i=this.parkedSharedHistory.get(e))&&void 0!==i?i:[];n.push(t),this.parkedSharedHistory.set(e,n)}takeParkedSharedHistory(e){var t;const i=null!==(t=this.parkedSharedHistory.get(e))&&void 0!==t?t:[];return this.parkedSharedHistory.delete(e),Promise.resolve(i)}doTxn(e,t,i){return Promise.resolve(i(null))}}},{"../../logger":374,"../../utils":416}],349:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.VerificationBase=i.VerificationEvent=i.SwitchStartEventError=void 0;const r=e("../../models/event"),o=e("../../@types/event"),s=e("../../logger"),a=e("../deviceinfo"),c=e("./Error"),d=e("../CrossSigning"),l=e("../../models/typed-event-emitter"),u=new Error("Verification timed out");class h extends Error{constructor(e){super(),this.startEvent=e}}var f;i.SwitchStartEventError=h,function(e){e.Cancel="cancel"}(f=i.VerificationEvent||(i.VerificationEvent={}));class p extends l.TypedEventEmitter{constructor(e,t,i,n,r,o){super(),this.channel=e,this.baseApis=t,this.userId=i,this.deviceId=n,this.startEvent=r,this.request=o,this.cancelled=!1,this._done=!1,this.promise=null,this.transactionTimeoutTimer=null}get initiatedByMe(){if(!this.startEvent)return!0;const e=this.startEvent.getSender(),t=this.startEvent.getContent();return e===this.baseApis.getUserId()&&t.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){s.logger.info("Refreshing/starting the verification transaction timeout timer"),null!==this.transactionTimeoutTimer&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout((()=>{this._done||this.cancelled||(s.logger.info("Triggering verification timeout"),this.cancel(u))}),6e5)}endTimer(){null!==this.transactionTimeoutTimer&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));const t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise(((e,t)=>{this.resolveEvent=e,this.rejectEvent=t})))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(s.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const t=this.rejectEvent;this.rejectEvent=void 0,t(new h(e))}else this.startEvent=e}handleEvent(e){var t;if(!this._done)if(e.getType()===this.expectedEvent)this.expectedEvent!==o.EventType.KeyVerificationDone&&(this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),null===(t=this.resolveEvent)||void 0===t||t.call(this,e));else if(e.getType()===o.EventType.KeyVerificationCancel){const t=this.reject;if(this.reject=void 0,t){const i=e.getContent(),{reason:n,code:r}=i;t(new Error(`Other side cancelled verification because ${n} (${r})`))}}else if(this.expectedEvent){const t=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+e.getType());if(this.expectedEvent=void 0,this.rejectEvent){const e=this.rejectEvent;this.rejectEvent=void 0,e(t)}this.cancel(t)}}done(){var e;return n(this,void 0,void 0,(function*(){if(this.endTimer(),!this._done)return this.request.onVerifierFinished(),null===(e=this.resolve)||void 0===e||e.call(this),(0,d.requestKeysDuringVerification)(this.baseApis,this.userId,this.deviceId)}))}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===u){const e=(0,c.newTimeoutError)();this.send(e.getType(),e.getContent())}else if(e instanceof r.MatrixEvent){if(e.getSender()!==this.userId){const t=e.getContent();e.getType()===o.EventType.KeyVerificationCancel?(t.code=t.code||"m.unknown",t.reason=t.reason||t.body||"Unknown reason",this.send(o.EventType.KeyVerificationCancel,t)):this.send(o.EventType.KeyVerificationCancel,{code:"m.unknown",reason:t.body||"Unknown reason"})}}else this.send(o.EventType.KeyVerificationCancel,{code:"m.unknown",reason:e.toString()});null!==this.promise?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(f.Cancel,e)}}verify(){return this.promise||(this.promise=new Promise(((e,t)=>{this.resolve=(...t)=>{this._done=!0,this.endTimer(),e(...t)},this.reject=e=>{this._done=!0,this.endTimer(),t(e)}})),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),new Promise(((e,t)=>{var i;(null===(i=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId))||void 0===i?void 0:i.getId())===this.deviceId&&t(new Error("Device ID is the same as the cross-signing ID")),e()})).then((()=>this.doVerification())).then(this.done.bind(this),this.cancel.bind(this)))),this.promise}verifyKeys(e,t,i){return n(this,void 0,void 0,(function*(){const n=[];for(const[r,o]of Object.entries(t)){const t=r.split(":",2)[1],c=this.baseApis.getStoredDevice(e,t);if(c)i(r,c,o),n.push([t,r,c.keys[r]]);else{const c=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);c&&c.getId()===t?(i(r,a.DeviceInfo.fromStorage({keys:{[r]:t}},t),o),n.push([t,r,t])):s.logger.warn(`verification: Could not find device ${t} to verify`)}}if(!n.length)throw new Error("No devices could be verified");s.logger.info("Verification completed! Marking devices verified: ",n);for(const[t,i,r]of n)yield this.baseApis.crypto.setDeviceVerification(e,t,!0,null,null,{[i]:r});e==this.baseApis.credentials.userId&&(yield this.baseApis.checkKeyBackup())}))}get events(){}}i.VerificationBase=p},{"../../@types/event":306,"../../logger":374,"../../models/event":383,"../../models/typed-event-emitter":395,"../CrossSigning":324,"../deviceinfo":340,"./Error":350}],350:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.errorFromEvent=i.newInvalidMessageError=i.newKeyMismatchError=i.newUnexpectedMessageError=i.newUnknownMethodError=i.newTimeoutError=i.newUserCancelledError=i.errorFactory=i.newVerificationError=void 0;const n=e("../../models/event"),r=e("../../@types/event");function o(e,t,i){const o=Object.assign({},{code:e,reason:t},i);return new n.MatrixEvent({type:r.EventType.KeyVerificationCancel,content:o})}function s(e,t){return function(i){return o(e,t,i)}}i.newVerificationError=o,i.errorFactory=s,i.newUserCancelledError=s("m.user","Cancelled by user"),i.newTimeoutError=s("m.timeout","Timed out"),i.newUnknownMethodError=s("m.unknown_method","Unknown method"),i.newUnexpectedMessageError=s("m.unexpected_message","Unexpected message"),i.newKeyMismatchError=s("m.key_mismatch","Key mismatch"),i.newInvalidMessageError=s("m.invalid_message","Invalid message"),i.errorFromEvent=function(e){const t=e.getContent();if(t){const{code:e,reason:i}=t;return{code:e,reason:i}}return{code:"Unknown error",reason:"m.unknown"}}},{"../../@types/event":306,"../../models/event":383}],351:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IllegalMethod=void 0;const r=e("./Base");class o extends r.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>n(this,void 0,void 0,(function*(){throw new Error("Verification is not possible with this method")}))}static factory(e,t,i,n,r,s){return new o(e,t,i,n,r,s)}static get NAME(){return"org.matrix.illegal_method"}}i.IllegalMethod=o},{"./Base":349}],352:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.QRCodeData=i.ReciprocateQRCode=i.QrCodeEvent=i.SCAN_QR_CODE_METHOD=i.SHOW_QR_CODE_METHOD=void 0;const o=e("./Base"),s=e("./Error"),a=e("../olmlib"),c=e("../../logger");var d;i.SHOW_QR_CODE_METHOD="m.qr_code.show.v1",i.SCAN_QR_CODE_METHOD="m.qr_code.scan.v1",function(e){e.ShowReciprocateQr="show_reciprocate_qr"}(d=i.QrCodeEvent||(i.QrCodeEvent={}));class l extends o.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>r(this,void 0,void 0,(function*(){if(!this.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");const{qrCodeData:e}=this.request;if(this.startEvent.getContent().secret!==(null==e?void 0:e.encodedSharedSecret))throw(0,s.newKeyMismatchError)();yield new Promise(((e,t)=>{this.reciprocateQREvent={confirm:e,cancel:()=>t((0,s.newUserCancelledError)())},this.emit(d.ShowReciprocateQr,this.reciprocateQREvent)}));const t={};switch(null==e?void 0:e.mode){case u.VerifyOtherUser:{const i=e.otherUserMasterKey;t[`ed25519:${i}`]=i;break}case u.VerifySelfTrusted:{const i=this.request.targetDevice.deviceId;t[`ed25519:${i}`]=e.otherDeviceKey;break}case u.VerifySelfUntrusted:{const i=e.myMasterKey;t[`ed25519:${i}`]=i;break}}yield this.verifyKeys(this.userId,t,((e,i,n)=>{const r=t[e];if(!r)throw(0,s.newKeyMismatchError)();if(n!==r)throw c.logger.error("key ID from key info does not match"),(0,s.newKeyMismatchError)();for(const e in i.keys){if(!e.startsWith("ed25519"))continue;const n=t[e];if(!n)throw(0,s.newKeyMismatchError)();if(i.keys[e]!==n)throw c.logger.error("master key does not match"),(0,s.newKeyMismatchError)()}}))}))}static factory(e,t,i,n,r,o){return new l(e,t,i,n,r,o)}static get NAME(){return"m.reciprocate.v1"}}i.ReciprocateQRCode=l;var u;!function(e){e[e.VerifyOtherUser=0]="VerifyOtherUser",e[e.VerifySelfTrusted=1]="VerifySelfTrusted",e[e.VerifySelfUntrusted=2]="VerifySelfUntrusted"}(u||(u={}));class h{constructor(e,t,i,n,r,o){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=i,this.otherDeviceKey=n,this.myMasterKey=r,this.buffer=o}static create(e,t){return r(this,void 0,void 0,(function*(){const i=h.generateSharedSecret(),n=h.determineMode(e,t);let r=null,o=null,s=null;if(n===u.VerifyOtherUser){r=t.getStoredCrossSigningForUser(e.otherUserId).getId("master")}else if(n===u.VerifySelfTrusted)o=yield h.getOtherDeviceKey(e,t);else if(n===u.VerifySelfUntrusted){const e=t.getUserId();s=t.getStoredCrossSigningForUser(e).getId("master")}const a=h.generateQrData(e,t,n,i,r,o,s),c=h.generateBuffer(a);return new h(n,i,r,o,s,c)}))}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){const e=new Uint8Array(11);return t.crypto.getRandomValues(e),(0,a.encodeUnpaddedBase64)(e)}static getOtherDeviceKey(e,t){return r(this,void 0,void 0,(function*(){const i=t.getUserId(),n=e.targetDevice,r=n.deviceId?t.getStoredDevice(i,n.deviceId):void 0;if(!r)throw new Error("could not find device "+(null==n?void 0:n.deviceId));return r.getFingerprint()}))}static determineMode(e,t){const i=t.getUserId(),n=e.otherUserId;let r=u.VerifyOtherUser;if(i===n){r=t.checkUserTrust(i).isCrossSigningVerified()?u.VerifySelfTrusted:u.VerifySelfUntrusted}return r}static generateQrData(e,t,i,n,r,o,s){const a=t.getUserId(),c={prefix:"MATRIX",version:2,mode:i,transactionId:e.channel.transactionId,firstKeyB64:"",secondKeyB64:"",secretB64:n},d=t.getStoredCrossSigningForUser(a);return i===u.VerifyOtherUser?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=r):i===u.VerifySelfTrusted?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=o):i===u.VerifySelfUntrusted&&(c.firstKeyB64=t.getDeviceEd25519Key(),c.secondKeyB64=s),c}static generateBuffer(e){let t=n.alloc(0);const i=e=>{const i=n.from([e]);t=n.concat([t,i])},r=(e,i,r=!0)=>{const o=n.from(e,i);r&&(e=>{const i=n.alloc(2);i.writeInt16BE(e,0),t=n.concat([t,i])})(o.byteLength),t=n.concat([t,o])},o=e=>{const i=(0,a.decodeBase64)(e),r=n.from(i);t=n.concat([t,r])};return r(e.prefix,"ascii",!1),i(e.version),i(e.mode),r(e.transactionId,"utf-8"),o(e.firstKeyB64),o(e.secondKeyB64),o(e.secretB64),t}}i.QRCodeData=h}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../../logger":374,"../olmlib":343,"./Base":349,"./Error":350,buffer:68}],353:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.SAS=i.SasEvent=void 0;const o=r(e("another-json")),s=e("./Base"),a=e("./Error"),c=e("../../logger"),d=e("./SASDecimal"),l=e("../../@types/event"),u=l.EventType.KeyVerificationStart,h=[l.EventType.KeyVerificationAccept,l.EventType.KeyVerificationKey,l.EventType.KeyVerificationMac];let f;const p=(0,a.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),g=(0,a.errorFactory)("m.mismatched_commitment","Mismatched commitment"),v=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["🙂","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓️","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]];const m={decimal:d.generateDecimalSas,emoji:function(e){return[e[0]>>2,(3&e[0])<<4|e[1]>>4,(15&e[1])<<2|e[2]>>6,63&e[2],e[3]>>2,(3&e[3])<<4|e[4]>>4,(15&e[4])<<2|e[5]>>6].map((e=>v[e]))}};function y(e,t){const i={};for(const n of t)n in m&&(i[n]=m[n](Array.from(e)));return i}const b={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hkdf-hmac-sha256.v2":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function S(e,t){return function(i,n){const r=e[b[t]](i,n);return c.logger.log("SAS calculateMAC:",t,[i,n],r),r}}const _={"curve25519-hkdf-sha256":function(e,t,i){const n=`${e.baseApis.getUserId()}|${e.baseApis.deviceId}|${e.ourSASPubKey}|`,r=`${e.userId}|${e.deviceId}|${e.theirSASPubKey}|`,o="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?n+r:r+n)+e.channel.transactionId;return t.generate_bytes(o,i)},curve25519:function(e,t,i){const n=`${e.baseApis.getUserId()}${e.baseApis.deviceId}`,r=`${e.userId}${e.deviceId}`,o="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?n+r:r+n)+e.channel.transactionId;return t.generate_bytes(o,i)}},E=["curve25519-hkdf-sha256","curve25519"],w=["sha256"],T=["hkdf-hmac-sha256.v2","org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],I=Object.keys(m),R=new Set(E),M=new Set(w),k=new Set(T),C=new Set(I);function O(e,t){return Array.isArray(e)?e.filter((e=>t.has(e))):[]}var A;!function(e){e.ShowSas="show_sas"}(A=i.SasEvent||(i.SasEvent={}));class P extends s.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>n(this,void 0,void 0,(function*(){yield t.Olm.init(),f=f||new t.Olm.Utility,yield this.baseApis.downloadKeys([this.userId]);let e=!1;do{try{return this.initiatedByMe?yield this.doSendVerification():yield this.doRespondVerification()}catch(t){if(!(t instanceof s.SwitchStartEventError))throw t;this.startEvent=t.startEvent,e=!0}}while(e)}))}static get NAME(){return"m.sas.v1"}get events(){return h}canSwitchStartEvent(e){if(e.getType()!==u)return!1;const t=e.getContent();return(null==t?void 0:t.method)===P.NAME&&!!this.waitingForAccept}sendStart(){return n(this,void 0,void 0,(function*(){const e=this.channel.completeContent(u,{method:P.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:E,hashes:w,message_authentication_codes:T,short_authentication_string:I});return yield this.channel.sendCompleted(u,e),e}))}verifyAndCheckMAC(e,t,i,r){return n(this,void 0,void 0,(function*(){const o=_[e](this,i,6),s=new Promise(((e,s)=>{this.sasEvent={sas:y(o,t),confirm:()=>n(this,void 0,void 0,(function*(){try{yield this.sendMAC(i,r),e()}catch(e){s(e)}})),cancel:()=>s((0,a.newUserCancelledError)()),mismatch:()=>s(p())},this.emit(A.ShowSas,this.sasEvent)})),[c]=yield Promise.all([this.waitForEvent(l.EventType.KeyVerificationMac).then((e=>(this.expectedEvent=l.EventType.KeyVerificationDone,e))),s]),d=c.getContent();yield this.checkMAC(i,d,r)}))}doSendVerification(){return n(this,void 0,void 0,(function*(){let e,i;if(this.waitingForAccept=!0,e=this.startEvent?this.channel.completedContentFromEvent(this.startEvent):yield this.sendStart(),!this.initiatedByMe)throw new s.SwitchStartEventError(this.startEvent);try{i=yield this.waitForEvent(l.EventType.KeyVerificationAccept)}finally{this.waitingForAccept=!1}let n=i.getContent();const r=O(n.short_authentication_string,C);if(!(R.has(n.key_agreement_protocol)&&M.has(n.hash)&&k.has(n.message_authentication_code)&&r.length))throw(0,a.newUnknownMethodError)();if("string"!=typeof n.commitment)throw(0,a.newInvalidMessageError)();const c=n.key_agreement_protocol,d=n.message_authentication_code,u=n.commitment,h=new t.Olm.SAS;try{this.ourSASPubKey=h.get_pubkey(),yield this.send(l.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),i=yield this.waitForEvent(l.EventType.KeyVerificationKey),n=i.getContent();const t=n.key+o.default.stringify(e);if(f.sha256(t)!==u)throw g();this.theirSASPubKey=n.key,h.set_their_key(n.key),yield this.verifyAndCheckMAC(c,r,h,d)}finally{h.free()}}))}doRespondVerification(){return n(this,void 0,void 0,(function*(){let e=this.channel.completedContentFromEvent(this.startEvent);const i=O(E,new Set(e.key_agreement_protocols))[0],n=O(w,new Set(e.hashes))[0],r=O(T,new Set(e.message_authentication_codes))[0],s=O(e.short_authentication_string,C);if(void 0===i||void 0===n||void 0===r||!s.length)throw(0,a.newUnknownMethodError)();const c=new t.Olm.SAS;try{const t=c.get_pubkey()+o.default.stringify(e);yield this.send(l.EventType.KeyVerificationAccept,{key_agreement_protocol:i,hash:n,message_authentication_code:r,short_authentication_string:s,commitment:f.sha256(t)});e=(yield this.waitForEvent(l.EventType.KeyVerificationKey)).getContent(),this.theirSASPubKey=e.key,c.set_their_key(e.key),this.ourSASPubKey=c.get_pubkey(),yield this.send(l.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),yield this.verifyAndCheckMAC(i,s,c,r)}finally{c.free()}}))}sendMAC(e,t){const i={},n=[],r="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,o=`ed25519:${this.baseApis.deviceId}`;i[o]=S(e,t)(this.baseApis.getDeviceEd25519Key(),r+o),n.push(o);const s=this.baseApis.getCrossSigningId();if(s){const o=`ed25519:${s}`;i[o]=S(e,t)(s,r+o),n.push(o)}const a=S(e,t)(n.sort().join(","),r+"KEY_IDS");return this.send(l.EventType.KeyVerificationMac,{mac:i,keys:a})}checkMAC(e,t,i){return n(this,void 0,void 0,(function*(){const n="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this.baseApis.getUserId()+this.baseApis.deviceId+this.channel.transactionId;if(t.keys!==S(e,i)(Object.keys(t.mac).sort().join(","),n+"KEY_IDS"))throw(0,a.newKeyMismatchError)();yield this.verifyKeys(this.userId,t.mac,((t,r,o)=>{if(o!==S(e,i)(r.keys[t],n+t))throw(0,a.newKeyMismatchError)()}))}))}}i.SAS=P}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../@types/event":306,"../../logger":374,"./Base":349,"./Error":350,"./SASDecimal":354,"another-json":1}],354:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateDecimalSas=void 0,i.generateDecimalSas=function(e){return[1e3+(e[0]<<5|e[1]>>3),1e3+((7&e[1])<<10|e[2]<<2|e[3]>>6),1e3+((63&e[3])<<7|e[4]>>1)]}},{}],355:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.InRoomRequests=i.InRoomChannel=void 0;const r=e("./VerificationRequest"),o=e("../../../logger"),s=e("../../../@types/event").EventType.RoomMessage,a="m.reference",c="m.relates_to";class d{constructor(e,t,i){this.client=e,this.roomId=t,this.userId=i}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){if(d.getEventType(e)!==r.REQUEST_TYPE)return;const i=t.getUserId(),n=e.getSender(),o=e.getContent().to;return n===i?o:o===i?n:void 0}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===r.REQUEST_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static getTransactionId(e){if(d.getEventType(e)===r.REQUEST_TYPE)return e.getId();{const t=e.getRelation();if((null==t?void 0:t.rel_type)===a)return t.event_id}}static validateEvent(e,t){const i=d.getTransactionId(e);if("string"!=typeof i||0===i.length)return!1;const n=d.getEventType(e),s=e.getContent();if(n===r.REQUEST_TYPE){if(!s||"string"!=typeof s.to||!s.to.length)return o.logger.log("InRoomChannel: validateEvent: no valid to "+(s&&s.to)),!1;if(!d.getOtherPartyUserId(e,t))return o.logger.log(`InRoomChannel: validateEvent: not directed to or sent by me: ${e.getSender()}, ${s&&s.to}`),!1}return r.VerificationRequest.validateEvent(n,e,t)}static getEventType(e){const t=e.getType();if(t===s){const t=e.getContent();if(t){const{msgtype:e}=t;if(e===r.REQUEST_TYPE)return r.REQUEST_TYPE}}return t&&t!==r.REQUEST_TYPE?t:""}handleEvent(e,t,i=!1){return n(this,void 0,void 0,(function*(){if(t.hasEventId(e.getId()))return;const n=d.getEventType(e);if(e.getRoomId()!==this.roomId)return;if(!this.userId){const t=d.getOtherPartyUserId(e,this.client);t&&(this.userId=t)}const r=this.client.getUserId(),s=e.getSender();if(this.userId&&s!==r&&s!==this.userId)return void o.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${s}`);this.requestEventId||(this.requestEventId=d.getTransactionId(e));const a=!!e.getUnsigned().transaction_id,c=e.getSender()===this.client.getUserId();return t.handleEvent(n,e,i,a,c)}))}completedContentFromEvent(e){const t=Object.assign({},e.getContent());return t[c]=e.getRelation(),t}completeContent(e,t){return t=Object.assign({},t),e!==r.REQUEST_TYPE&&e!==r.READY_TYPE&&e!==r.START_TYPE||(t.from_device=this.client.getDeviceId()),e===r.REQUEST_TYPE?t={body:this.client.getUserId()+" is requesting to verify your key, but your client does not support in-chat key verification. You will need to use legacy key verification to verify keys.",msgtype:r.REQUEST_TYPE,to:this.userId,from_device:t.from_device,methods:t.methods}:t[c]={rel_type:a,event_id:this.transactionId},t}send(e,t){const i=this.completeContent(e,t);return this.sendCompleted(e,i)}sendCompleted(e,t){return n(this,void 0,void 0,(function*(){let i=e;e===r.REQUEST_TYPE&&(i=s);const n=yield this.client.sendEvent(this.roomId,i,t);e===r.REQUEST_TYPE&&(this.requestEventId=n.event_id)}))}}i.InRoomChannel=d;i.InRoomRequests=class{constructor(){this.requestsByRoomId=new Map}getRequest(e){const t=e.getRoomId(),i=d.getTransactionId(e);return this.getRequestByTxnId(t,i)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){const i=this.requestsByRoomId.get(e);if(i)return i.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,i){let n=this.requestsByRoomId.get(e);n||(n=new Map,this.requestsByRoomId.set(e,n)),n.set(t,i)}removeRequest(e){const t=e.getRoomId(),i=this.requestsByRoomId.get(t);i&&(i.delete(d.getTransactionId(e)),0===i.size&&this.requestsByRoomId.delete(t))}findRequestInProgress(e){const t=this.requestsByRoomId.get(e);if(t)for(const e of t.values())if(e.pending)return e}}},{"../../../@types/event":306,"../../../logger":374,"./VerificationRequest":357}],356:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.ToDeviceRequests=i.ToDeviceChannel=void 0;const r=e("../../../randomstring"),o=e("../../../logger"),s=e("./VerificationRequest"),a=e("../Error"),c=e("../../../models/event");class d{constructor(e,t,i,n,r){this.client=e,this.userId=t,this.devices=i,this.transactionId=n,this.deviceId=r}isToDevices(e){if(e.length===this.devices.length){for(const t of e)if(!this.devices.includes(t))return!1;return!0}return!1}static getEventType(e){return e.getType()}static getTransactionId(e){const t=e.getContent();return t&&t.transaction_id}static canCreateRequest(e){return e===s.REQUEST_TYPE||e===s.START_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return o.logger.warn("Ignoring flagged verification request from "+e.getSender()),!1;const i=e.getContent();if(!i)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!i.transaction_id)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;const n=e.getType();if(n===s.REQUEST_TYPE){if(!Number.isFinite(i.timestamp))return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&i.from_device==t.getDeviceId())return o.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return s.VerificationRequest.validateEvent(n,e,t)}getTimestamp(e){const t=e.getContent();return t&&t.timestamp}handleEvent(e,t,i=!1){return n(this,void 0,void 0,(function*(){const n=e.getType(),r=e.getContent();if(n===s.REQUEST_TYPE||n===s.READY_TYPE||n===s.START_TYPE){this.transactionId||(this.transactionId=r.transaction_id);const e=r.from_device;if(!this.deviceId&&this.devices.includes(e)&&(this.deviceId=e),!this.deviceId||this.deviceId!==e){const t=this.completeContent(s.CANCEL_TYPE,(0,a.errorFromEvent)((0,a.newUnexpectedMessageError)()));return this.sendToDevices(s.CANCEL_TYPE,t,[e])}}const o=t.phase===s.PHASE_STARTED||t.phase===s.PHASE_READY;yield t.handleEvent(e.getType(),e,i,!1,!1);const c=t.phase===s.PHASE_STARTED||t.phase===s.PHASE_READY;if((n===s.START_TYPE||n===s.READY_TYPE)&&!o&&c&&this.deviceId){const e=this.devices.filter((e=>e!==this.deviceId&&e!==this.client.getDeviceId()));if(e.length){const t=this.completeContent(s.CANCEL_TYPE,{code:"m.accepted",reason:"Verification request accepted by another device"});yield this.sendToDevices(s.CANCEL_TYPE,t,e)}}}))}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),e!==s.REQUEST_TYPE&&e!==s.READY_TYPE&&e!==s.START_TYPE||(t.from_device=this.client.getDeviceId()),e===s.REQUEST_TYPE&&(t.timestamp=Date.now()),t}send(e,t={}){e!==s.REQUEST_TYPE&&e!==s.START_TYPE||this.transactionId||(this.transactionId=d.makeTransactionId());const i=this.completeContent(e,t);return this.sendCompleted(e,i)}sendCompleted(e,t){return n(this,void 0,void 0,(function*(){let i;i=e===s.REQUEST_TYPE||e===s.CANCEL_TYPE&&!this.deviceId?yield this.sendToDevices(e,t,this.devices):yield this.sendToDevices(e,t,[this.deviceId]);const n=new c.MatrixEvent({sender:this.client.getUserId(),content:t,type:e});return yield this.request.handleEvent(e,n,!0,!0,!0),i}))}sendToDevices(e,t,i){return n(this,void 0,void 0,(function*(){if(i.length){const n=new Map;for(const e of i)n.set(e,t);yield this.client.sendToDevice(e,new Map([[this.userId,n]]))}}))}static makeTransactionId(){return(0,r.randomString)(32)}}i.ToDeviceChannel=d;i.ToDeviceRequests=class{constructor(){this.requestsByUserId=new Map}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){const i=this.requestsByUserId.get(e);if(i)return i.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,i){let n=this.requestsByUserId.get(e);n||(n=new Map,this.requestsByUserId.set(e,n)),n.set(t,i)}removeRequest(e){const t=e.getSender(),i=this.requestsByUserId.get(t);i&&(i.delete(d.getTransactionId(e)),0===i.size&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){const i=this.requestsByUserId.get(e);if(i)for(const e of i.values())if(e.pending&&e.channel.isToDevices(t))return e}getRequestsInProgress(e){const t=this.requestsByUserId.get(e);return t?Array.from(t.values()).filter((e=>e.pending)):[]}}},{"../../../logger":374,"../../../models/event":383,"../../../randomstring":398,"../Error":350,"./VerificationRequest":357}],357:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.VerificationRequest=i.VerificationRequestEvent=i.PHASE_DONE=i.PHASE_CANCELLED=i.PHASE_STARTED=i.PHASE_READY=i.PHASE_REQUESTED=i.PHASE_UNSENT=i.Phase=i.READY_TYPE=i.DONE_TYPE=i.CANCEL_TYPE=i.START_TYPE=i.REQUEST_TYPE=i.EVENT_PREFIX=void 0;const r=e("../../../logger"),o=e("../Error"),s=e("../QRCode"),a=e("../../../@types/event"),c=e("../../../models/typed-event-emitter");var d,l;i.EVENT_PREFIX="m.key.verification.",i.REQUEST_TYPE=i.EVENT_PREFIX+"request",i.START_TYPE=i.EVENT_PREFIX+"start",i.CANCEL_TYPE=i.EVENT_PREFIX+"cancel",i.DONE_TYPE=i.EVENT_PREFIX+"done",i.READY_TYPE=i.EVENT_PREFIX+"ready",function(e){e[e.Unsent=1]="Unsent",e[e.Requested=2]="Requested",e[e.Ready=3]="Ready",e[e.Started=4]="Started",e[e.Cancelled=5]="Cancelled",e[e.Done=6]="Done"}(d=i.Phase||(i.Phase={})),i.PHASE_UNSENT=d.Unsent,i.PHASE_REQUESTED=d.Requested,i.PHASE_READY=d.Ready,i.PHASE_STARTED=d.Started,i.PHASE_CANCELLED=d.Cancelled,i.PHASE_DONE=d.Done,function(e){e.Change="change"}(l=i.VerificationRequestEvent||(i.VerificationRequestEvent={}));class u extends c.TypedEventEmitter{constructor(e,t,o){super(),this.channel=e,this.verificationMethods=t,this.client=o,this.eventsByUs=new Map,this.eventsByThem=new Map,this._observeOnly=!1,this.timeoutTimer=null,this._accepting=!1,this._declining=!1,this.verifierHasFinished=!1,this._cancelled=!1,this._chosenMethod=null,this._qrCodeData=null,this.requestReceivedAt=null,this.commonMethods=[],this.cancelOnTimeout=()=>n(this,void 0,void 0,(function*(){try{this.initiatedByMe?yield this.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):yield this.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(e){r.logger.error("Error while cancelling verification request",e)}})),this.channel.request=this,this.setPhase(i.PHASE_UNSENT,!1)}static validateEvent(e,t,n){const o=t.getContent();return!(!e||!e.startsWith(i.EVENT_PREFIX))&&(o?e!==i.REQUEST_TYPE&&e!==i.READY_TYPE||Array.isArray(o.methods)?e!==i.REQUEST_TYPE&&e!==i.READY_TYPE&&e!==i.START_TYPE||"string"==typeof o.from_device&&0!==o.from_device.length||(r.logger.log("VerificationRequest: validateEvent: fail because from_device"),!1):(r.logger.log("VerificationRequest: validateEvent: fail because methods"),!1):(r.logger.log("VerificationRequest: validateEvent: no content"),!1))}get invalid(){return this.phase===i.PHASE_UNSENT}get requested(){return this.phase===i.PHASE_REQUESTED}get cancelled(){return this.phase===i.PHASE_CANCELLED}get ready(){return this.phase===i.PHASE_READY}get started(){return this.phase===i.PHASE_STARTED}get done(){return this.phase===i.PHASE_DONE}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(e){let t=this.channel.getTimestamp(e)+6e5;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=i.PHASE_REQUESTED){const e=this.requestReceivedAt+12e4;t=Math.min(t,e)}return Math.max(0,t-Date.now())}get timeout(){const e=this.getEventByEither(i.REQUEST_TYPE);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(i.REQUEST_TYPE)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return this.phase<i.PHASE_READY&&!this._accepting&&!this._declining}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==i.PHASE_DONE&&this._phase!==i.PHASE_CANCELLED}get qrCodeData(){return this._qrCodeData}otherPartySupportsMethod(e,t=!1){if(!t&&!this.ready&&!this.started)return!1;const n=this.eventsByThem.get(i.REQUEST_TYPE)||this.eventsByThem.get(i.READY_TYPE);if(!n){if(this.started&&this.initiatedByMe){const t=this.eventsByUs.get(i.START_TYPE),n=t&&t.getContent();return e==(n&&n.method)}return!1}const r=n.getContent();if(!r)return!1;const{methods:o}=r;return!!Array.isArray(o)&&o.includes(e)}get initiatedByMe(){const e=this.eventsByUs.size+this.eventsByThem.size===0;if(this._phase===i.PHASE_UNSENT&&e)return!0;const t=this.eventsByUs.has(i.REQUEST_TYPE),n=this.eventsByThem.has(i.REQUEST_TYPE);if(t&&!n)return!0;if(!t&&n)return!1;const r=this.eventsByUs.has(i.START_TYPE),o=this.eventsByThem.has(i.START_TYPE);return!(!r||o)}get requestingUserId(){return this.initiatedByMe?this.client.getUserId():this.otherUserId}get receivingUserId(){return this.initiatedByMe?this.otherUserId:this.client.getUserId()}get otherUserId(){return this.channel.userId}get isSelfVerification(){return this.client.getUserId()===this.otherUserId}get cancellingUserId(){const e=this.eventsByUs.get(i.CANCEL_TYPE),t=this.eventsByThem.get(i.CANCEL_TYPE);return e&&(!t||e.getId()<t.getId())?e.getSender():t?t.getSender():void 0}get cancellationCode(){const e=this.getEventByEither(i.CANCEL_TYPE);return e?e.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){const e=this.eventsByThem.get(i.REQUEST_TYPE)||this.eventsByThem.get(i.READY_TYPE)||this.eventsByThem.get(i.START_TYPE),t=null==e?void 0:e.getContent(),n=null==t?void 0:t.from_device;return{userId:this.otherUserId,deviceId:n}}beginKeyVerification(e,t=null){if(!this.observeOnly&&!this._verifier){if(this.phase===i.PHASE_REQUESTED||this.phase===i.PHASE_READY||this.phase===i.PHASE_UNSENT&&this.channel.canCreateRequest(i.START_TYPE)){if(this.commonMethods.length&&!this.commonMethods.includes(e))throw(0,o.newUnknownMethodError)();if(this._verifier=this.createVerifier(e,null,t),!this._verifier)throw(0,o.newUnknownMethodError)();this._chosenMethod=e}}return this._verifier}sendRequest(){return n(this,void 0,void 0,(function*(){if(!this.observeOnly&&this._phase===i.PHASE_UNSENT){const e=[...this.verificationMethods.keys()];yield this.channel.send(i.REQUEST_TYPE,{methods:e})}}))}cancel({reason:e="User declined",code:t="m.user"}={}){return n(this,void 0,void 0,(function*(){if(!this.observeOnly&&this._phase!==i.PHASE_CANCELLED){if(this._declining=!0,this.emit(l.Change),this._verifier)return this._verifier.cancel((0,o.errorFactory)(t,e)());this._cancellingUserId=this.client.getUserId(),yield this.channel.send(i.CANCEL_TYPE,{code:t,reason:e})}}))}accept(){return n(this,void 0,void 0,(function*(){if(!this.observeOnly&&this.phase===i.PHASE_REQUESTED&&!this.initiatedByMe){const e=[...this.verificationMethods.keys()];this._accepting=!0,this.emit(l.Change),yield this.channel.send(i.READY_TYPE,{methods:e})}}))}waitFor(e){return new Promise(((t,i)=>{const n=()=>{let r=!1;return e(this)?(t(this),r=!0):this.cancelled&&(i(new Error("cancelled")),r=!0),r&&this.off(l.Change,n),r};n()||this.on(l.Change,n)}))}setPhase(e,t=!0){this._phase=e,t&&this.emit(l.Change)}getEventByEither(e){return this.eventsByThem.get(e)||this.eventsByUs.get(e)}getEventBy(e,t=!1){return t?this.eventsByThem.get(e):this.eventsByUs.get(e)}calculatePhaseTransitions(){const e=[{phase:i.PHASE_UNSENT}],t=()=>e[e.length-1].phase,n=this.eventsByThem.has(i.REQUEST_TYPE),r=this.getEventBy(i.REQUEST_TYPE,n);r&&e.push({phase:i.PHASE_REQUESTED,event:r});const o=r&&this.getEventBy(i.READY_TYPE,!n);let s;if(o&&t()===i.PHASE_REQUESTED&&e.push({phase:i.PHASE_READY,event:o}),o||!r){const e=this.eventsByThem.get(i.START_TYPE),t=this.eventsByUs.get(i.START_TYPE);s=e&&t?e.getSender()<t.getSender()?e:t:e||t}else s=this.getEventBy(i.START_TYPE,!n);if(s){const n=t()===i.PHASE_REQUESTED&&(null==r?void 0:r.getSender())!==s.getSender(),o=t()===i.PHASE_UNSENT&&this.channel.canCreateRequest(i.START_TYPE);(n||t()===i.PHASE_READY||o)&&e.push({phase:i.PHASE_STARTED,event:s})}const a=this.eventsByUs.get(i.DONE_TYPE);(this.verifierHasFinished||a&&t()===i.PHASE_STARTED)&&e.push({phase:i.PHASE_DONE});const c=this.getEventByEither(i.CANCEL_TYPE);return(this._cancelled||c)&&t()!==i.PHASE_DONE?(e.push({phase:i.PHASE_CANCELLED,event:c}),e):e}transitionToPhase(e){const{phase:t,event:n}=e;if((t===i.PHASE_REQUESTED||t===i.PHASE_READY)&&!this.wasSentByOwnDevice(n)){const e=n.getContent();this.commonMethods=e.methods.filter((e=>this.verificationMethods.has(e)))}if(this.observeOnly||t!==i.PHASE_REQUESTED&&t!==i.PHASE_STARTED&&t!==i.PHASE_READY||this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(n)&&!this.wasSentByOwnDevice(n)&&(this._observeOnly=!0),t===i.PHASE_STARTED){const{method:e}=n.getContent();this._verifier||this.observeOnly||(this._verifier=this.createVerifier(e,n),this._verifier?this._chosenMethod=e:this.cancel({code:"m.unknown_method",reason:`Unknown method: ${e}`}))}}applyPhaseTransitions(){const e=this.calculatePhaseTransitions(),t=e.findIndex((e=>e.phase===this.phase)),i=e.slice(t+1);for(const e of i)this.transitionToPhase(e);return i}isWinningStartRace(e){if(e.getType()!==i.START_TYPE)return!1;const t=this._verifier.startEvent;let n,r;if(this.isSelfVerification)if(t){const e=t.getContent();n=e&&e.from_device}else n=this.client.getDeviceId();else n=t?t.getSender():this.client.getUserId();if(this.isSelfVerification){const t=e.getContent();r=t&&t.from_device}else r=e.getSender();return r<n}hasEventId(e){for(const t of this.eventsByUs.values())if(t.getId()===e)return!0;for(const t of this.eventsByThem.values())if(t.getId()===e)return!0;return!1}handleEvent(e,t,o,a,c){var d;return n(this,void 0,void 0,(function*(){if(this.done||this.cancelled)return;const n=this._observeOnly;if(this.adjustObserveOnly(t,o),!this.observeOnly&&!a&&(yield this.cancelOnError(e,t)))return;if(c?this.eventsByUs.has(e):this.eventsByThem.has(e))return;const u=this.phase;this.addEvent(e,t,c);const h=this.applyPhaseTransitions();try{if(this._verifier&&!this.observeOnly){const n=this.isWinningStartRace(t);this._verifier.canSwitchStartEvent(t)&&n?this._verifier.switchStartEvent(t):a||(e===i.CANCEL_TYPE||(null===(d=this._verifier.events)||void 0===d?void 0:d.includes(e)))&&this._verifier.handleEvent(t)}if(h.length){if(o&&h.some((e=>e.phase===i.PHASE_READY))){this.otherPartySupportsMethod(s.SCAN_QR_CODE_METHOD,!0)&&(this._qrCodeData=yield s.QRCodeData.create(this,this.client))}const e=h[h.length-1],{phase:t}=e;this.setupTimeout(t),this.setPhase(t)}else this._observeOnly!==n&&this.emit(l.Change)}finally{r.logger.log(`Verification request ${this.channel.transactionId}: ${e} event with id:${t.getId()}, content:${JSON.stringify(t.getContent())} deviceId:${this.channel.deviceId}, sender:${t.getSender()}, isSentByUs:${c}, isLiveEvent:${o}, isRemoteEcho:${a}, phase:${u}=>${this.phase}, observeOnly:${n}=>${this._observeOnly}`)}}))}setupTimeout(e){if(!this.timeoutTimer&&!this.observeOnly&&e===i.PHASE_REQUESTED&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer){(e===i.PHASE_STARTED||e===i.PHASE_READY||e===i.PHASE_DONE||e===i.PHASE_CANCELLED)&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}}cancelOnError(e,t){return n(this,void 0,void 0,(function*(){if(e===i.START_TYPE){const e=t.getContent().method;if(!this.verificationMethods.has(e))return yield this.cancel((0,o.errorFromEvent)((0,o.newUnknownMethodError)())),!0}const n=e===i.REQUEST_TYPE&&this.phase!==i.PHASE_UNSENT,s=e===i.READY_TYPE&&this.phase!==i.PHASE_REQUESTED&&this.phase!==i.PHASE_STARTED;if(this.phase!==i.PHASE_UNSENT&&(n||s)){r.logger.warn(`Cancelling, unexpected ${e} verification event from ${t.getSender()}`);const i=`Unexpected ${e} event in phase ${this.phase}`;return yield this.cancel((0,o.errorFromEvent)((0,o.newUnexpectedMessageError)({reason:i}))),!0}return!1}))}adjustObserveOnly(e,t=!1){t||(this._observeOnly=!0),this.calculateEventTimeout(e)<3e3&&(this._observeOnly=!0)}addEvent(e,t,n=!1){if(n?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===i.REQUEST_TYPE){for(const[e,t]of this.eventsByThem.entries())t.getSender()!==this.otherUserId&&this.eventsByThem.delete(e);this.requestReceivedAt=Date.now()}}createVerifier(e,t=null,i=null){i||(i=this.targetDevice);const{userId:n,deviceId:o}=i,s=this.verificationMethods.get(e);if(s)return new s(this.channel,this.client,n,o,t,this);r.logger.warn("could not find verifier constructor for method",e)}wasSentByOwnUser(e){return(null==e?void 0:e.getSender())===this.client.getUserId()}wasSentByOwnDevice(e){if(!this.wasSentByOwnUser(e))return!1;const t=e.getContent();return!(!t||t.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}onVerifierFinished(){this.channel.send(a.EventType.KeyVerificationDone,{}),this.verifierHasFinished=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}i.VerificationRequest=u},{"../../../@types/event":306,"../../../logger":374,"../../../models/typed-event-emitter":395,"../Error":350,"../QRCode":352}],358:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomWidgetClient=void 0;const o=e("matrix-widget-api"),s=e("./models/event"),a=e("./@types/event"),c=e("./logger"),d=e("./client"),l=e("./sync"),u=e("./sliding-sync-sdk"),h=e("./models/event"),f=e("./models/user"),p=e("./utils");class g extends d.MatrixClient{constructor(e,t,i,r){var s,u,f,p,g,v,m,y,b,S;super(r),this.widgetApi=e,this.capabilities=t,this.roomId=i,this.widgetApiReady=new Promise((e=>this.widgetApi.once("ready",e))),this.syncState=null,this.onEvent=e=>n(this,void 0,void 0,(function*(){if(e.preventDefault(),e.detail.data.room_id===this.roomId){const t=new h.MatrixEvent(e.detail.data);yield this.syncApi.injectRoomEvents(this.room,[],[t]),this.emit(d.ClientEvent.Event,t),this.setSyncState(l.SyncState.Syncing),c.logger.info(`Received event ${t.getId()} ${t.getType()} ${t.getStateKey()}`)}else{const{event_id:t,room_id:i}=e.detail.data;c.logger.info(`Received event ${t} for a different room ${i}; discarding`)}yield this.ack(e)})),this.onToDevice=e=>n(this,void 0,void 0,(function*(){e.preventDefault();const t=new h.MatrixEvent({type:e.detail.data.type,sender:e.detail.data.sender,content:e.detail.data.content});e.detail.data.encrypted&&t.makeEncrypted(a.EventType.RoomMessageEncrypted,{},"",""),this.emit(d.ClientEvent.ToDeviceEvent,t),this.setSyncState(l.SyncState.Syncing),yield this.ack(e)})),((null===(s=t.sendEvent)||void 0===s?void 0:s.length)||(null===(u=t.receiveEvent)||void 0===u?void 0:u.length)||!0===t.sendMessage||Array.isArray(t.sendMessage)&&t.sendMessage.length||!0===t.receiveMessage||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(null===(f=t.sendState)||void 0===f?void 0:f.length)||(null===(p=t.receiveState)||void 0===p?void 0:p.length))&&e.requestCapabilityForRoomTimeline(i),null===(g=t.sendEvent)||void 0===g||g.forEach((t=>e.requestCapabilityToSendEvent(t))),null===(v=t.receiveEvent)||void 0===v||v.forEach((t=>e.requestCapabilityToReceiveEvent(t))),!0===t.sendMessage?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach((t=>e.requestCapabilityToSendMessage(t))),!0===t.receiveMessage?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach((t=>e.requestCapabilityToReceiveMessage(t))),null===(m=t.sendState)||void 0===m||m.forEach((({eventType:t,stateKey:i})=>e.requestCapabilityToSendState(t,i))),null===(y=t.receiveState)||void 0===y||y.forEach((({eventType:t,stateKey:i})=>e.requestCapabilityToReceiveState(t,i))),null===(b=t.sendToDevice)||void 0===b||b.forEach((t=>e.requestCapabilityToSendToDevice(t))),null===(S=t.receiveToDevice)||void 0===S||S.forEach((t=>e.requestCapabilityToReceiveToDevice(t))),t.turnServers&&e.requestCapability(o.MatrixCapabilities.MSC3846TurnServers),e.on(`action:${o.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),e.on(`action:${o.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),e.start()}startClient(e={}){var t,i;return n(this,void 0,void 0,(function*(){this.lifecycle=new AbortController;const r=this.getUserId();r&&this.store.storeUser(new f.User(r)),e.slidingSync?this.syncApi=new u.SlidingSyncSdk(e.slidingSync,this,e,this.buildSyncApiOptions()):this.syncApi=new l.SyncApi(this,e,this.buildSyncApiOptions()),this.room=this.syncApi.createRoom(this.roomId),this.store.storeRoom(this.room),yield this.widgetApiReady,yield Promise.all(null!==(i=null===(t=this.capabilities.receiveState)||void 0===t?void 0:t.map((({eventType:e,stateKey:t})=>n(this,void 0,void 0,(function*(){const i=(yield this.widgetApi.readStateEvents(e,void 0,t,[this.roomId])).map((e=>new h.MatrixEvent(e)));yield this.syncApi.injectRoomEvents(this.room,[],i),i.forEach((e=>{this.emit(d.ClientEvent.Event,e),c.logger.info(`Backfilled event ${e.getId()} ${e.getType()} ${e.getStateKey()}`)}))})))))&&void 0!==i?i:[]),this.setSyncState(l.SyncState.Syncing),c.logger.info("Finished backfilling events"),this.capabilities.turnServers&&this.watchTurnServers()}))}stopClient(){this.widgetApi.off(`action:${o.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),this.widgetApi.off(`action:${o.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),super.stopClient(),this.lifecycle.abort()}joinRoom(e){return n(this,void 0,void 0,(function*(){if(e===this.roomId)return this.room;throw new Error(`Unknown room: ${e}`)}))}encryptAndSendEvent(e,t){return n(this,void 0,void 0,(function*(){let i;try{i=yield this.widgetApi.sendRoomEvent(t.getType(),t.getContent(),e.roomId)}catch(i){throw this.updatePendingEventStatus(e,t,s.EventStatus.NOT_SENT),i}return e.updatePendingEvent(t,s.EventStatus.SENT,i.event_id),{event_id:i.event_id}}))}sendStateEvent(e,t,i,r=""){return n(this,void 0,void 0,(function*(){return yield this.widgetApi.sendStateEvent(t,r,i,e)}))}sendToDevice(e,t){return n(this,void 0,void 0,(function*(){return yield this.widgetApi.sendToDevice(e,!1,(0,p.recursiveMapToObject)(t)),{}}))}queueToDevice({eventType:e,batch:t}){return n(this,void 0,void 0,(function*(){const i=new p.MapWithDefault((()=>new Map));for(const{userId:e,deviceId:n,payload:r}of t)i.getOrCreate(e).set(n,r);yield this.widgetApi.sendToDevice(e,!1,(0,p.recursiveMapToObject)(i))}))}encryptAndSendToDevices(e,t){return n(this,void 0,void 0,(function*(){const i=new p.MapWithDefault((()=>new Map));for(const{userId:n,deviceInfo:{deviceId:r}}of e)i.getOrCreate(n).set(r,t);yield this.widgetApi.sendToDevice(t.type,!0,(0,p.recursiveMapToObject)(i))}))}checkTurnServers(){return n(this,void 0,void 0,(function*(){return this.turnServers.length>0}))}getSyncState(){return this.syncState}setSyncState(e){const t=this.syncState;this.syncState=e,this.emit(d.ClientEvent.Sync,e,t)}ack(e){return n(this,void 0,void 0,(function*(){yield this.widgetApi.transport.reply(e.detail,{})}))}watchTurnServers(){var e,t,i,o;return n(this,void 0,void 0,(function*(){const n=this.widgetApi.getTurnServers(),s=()=>{n.return(void 0)};this.lifecycle.signal.addEventListener("abort",s);try{try{for(var a,l=!0,u=r(n);a=yield u.next(),!(e=a.done);){o=a.value,l=!1;try{const e=o;this.turnServers=[{urls:e.uris,username:e.username,credential:e.password}],this.emit(d.ClientEvent.TurnServers,this.turnServers),c.logger.log(`Received TURN server: ${e.uris}`)}finally{l=!0}}}catch(e){t={error:e}}finally{try{l||e||!(i=u.return)||(yield i.call(u))}finally{if(t)throw t.error}}}catch(e){c.logger.warn("Error watching TURN servers",e)}finally{this.lifecycle.signal.removeEventListener("abort",s)}}))}}i.RoomWidgetClient=g},{"./@types/event":306,"./client":321,"./logger":374,"./models/event":383,"./models/user":396,"./sliding-sync-sdk":406,"./sync":414,"./utils":416,"matrix-widget-api":178}],359:[function(e,t,i){"use strict";var n,r;Object.defineProperty(i,"__esModule",{value:!0}),i.KeySignatureUploadError=i.InvalidCryptoStoreError=i.InvalidCryptoStoreState=i.InvalidStoreError=i.InvalidStoreState=void 0,function(e){e[e.ToggledLazyLoading=0]="ToggledLazyLoading"}(n=i.InvalidStoreState||(i.InvalidStoreState={}));class o extends Error{constructor(e,t){super(`Store is invalid because ${e}, please stop the client, delete all data and start the client again`),this.reason=e,this.value=t,this.name="InvalidStoreError"}}i.InvalidStoreError=o,o.TOGGLED_LAZY_LOADING=n.ToggledLazyLoading,function(e){e.TooNew="TOO_NEW"}(r=i.InvalidCryptoStoreState||(i.InvalidCryptoStoreState={}));class s extends Error{constructor(e){super(`Crypto store is invalid because ${e}, please stop the client, delete all data and start the client again`),this.reason=e,this.name="InvalidCryptoStoreError"}}i.InvalidCryptoStoreError=s,s.TOO_NEW=r.TooNew;class a extends Error{constructor(e,t){super(e),this.value=t}}i.KeySignatureUploadError=a},{}],360:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.eventMapperFor=void 0;const n=e("./models/event"),r=e("./@types/event");i.eventMapperFor=function(e,t){let i=Boolean(t.preventReEmit);const o=!1!==t.decrypt;return function s(a){t.toDevice&&delete a.room_id;const c=e.getRoom(a.room_id);let d;c&&void 0===a.state_key&&(d=c.findEventById(a.event_id)),!d||d.status?d=new n.MatrixEvent(a):(d.setUnsigned(Object.assign(Object.assign({},d.getUnsigned()),a.unsigned)),i=!0);const l=d.getServerAggregatedRelation(r.RelationType.Replace);if(null==l?void 0:l.content){const e=s(l);d.makeReplaced(e)}const u=null==c?void 0:c.findThreadForEvent(d);return u&&d.setThread(u),d.isEncrypted()&&(i||e.reEmitter.reEmit(d,[n.MatrixEventEvent.Decrypted]),o&&e.decryptEventIfNeeded(d)),i||(e.reEmitter.reEmit(d,[n.MatrixEventEvent.Replaced,n.MatrixEventEvent.VisibilityChange]),null==c||c.reEmitter.reEmit(d,[n.MatrixEventEvent.BeforeRedaction])),d}}},{"./@types/event":306,"./models/event":383}],361:[function(e,t,i){"use strict";function n(e){return null!=e}Object.defineProperty(i,"__esModule",{value:!0}),i.isOptionalAString=i.isProvided=void 0,i.isProvided=n,i.isOptionalAString=function(e){return n(e)&&"string"==typeof e}},{}],362:[function(e,t,i){"use strict";var n,r,o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.buildFeatureSupportMap=i.Feature=i.ServerSupport=void 0,function(e){e[e.Stable=0]="Stable",e[e.Unstable=1]="Unstable",e[e.Unsupported=2]="Unsupported"}(n=i.ServerSupport||(i.ServerSupport={})),function(e){e.Thread="Thread",e.ThreadUnreadNotifications="ThreadUnreadNotifications",e.LoginTokenRequest="LoginTokenRequest",e.RelationBasedRedactions="RelationBasedRedactions",e.AccountDataDeletion="AccountDataDeletion"}(r=i.Feature||(i.Feature={}));const s={[r.Thread]:{unstablePrefixes:["org.matrix.msc3440"],matrixVersion:"v1.3"},[r.ThreadUnreadNotifications]:{unstablePrefixes:["org.matrix.msc3771","org.matrix.msc3773"],matrixVersion:"v1.4"},[r.LoginTokenRequest]:{unstablePrefixes:["org.matrix.msc3882"]},[r.RelationBasedRedactions]:{unstablePrefixes:["org.matrix.msc3912"]},[r.AccountDataDeletion]:{unstablePrefixes:["org.matrix.msc3391"]}};i.buildFeatureSupportMap=function(e){var t,i,r,a;return o(this,void 0,void 0,(function*(){const o=new Map;for(const[c,d]of Object.entries(s)){const s=null!==(i=null===(t=e.versions)||void 0===t?void 0:t.includes(d.matrixVersion||""))&&void 0!==i&&i,l=null!==(a=null===(r=d.unstablePrefixes)||void 0===r?void 0:r.every((t=>{var i;return!0===(null===(i=e.unstable_features)||void 0===i?void 0:i[t])})))&&void 0!==a&&a;s?o.set(c,n.Stable):l?o.set(c,n.Unstable):o.set(c,n.Unsupported)}return o}))}},{}],363:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterComponent=void 0;const n=e("./models/thread");i.FilterComponent=class{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,i;const r=(null===(t=e.getUnsigned())||void 0===t?void 0:t["m.relations"])||{},o=Object.keys(r),s=[];return this.userId&&(null===(i=null==r?void 0:r[n.THREAD_RELATION_TYPE.name])||void 0===i?void 0:i.current_user_participated)&&s.push(this.userId),this.checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url,o,s)}toJSON(){return{types:this.filterJson.types||null,not_types:this.filterJson.not_types||[],rooms:this.filterJson.rooms||null,not_rooms:this.filterJson.not_rooms||[],senders:this.filterJson.senders||null,not_senders:this.filterJson.not_senders||[],contains_url:this.filterJson.contains_url||null,[n.FILTER_RELATED_BY_SENDERS.name]:this.filterJson[n.FILTER_RELATED_BY_SENDERS.name]||[],[n.FILTER_RELATED_BY_REL_TYPES.name]:this.filterJson[n.FILTER_RELATED_BY_REL_TYPES.name]||[]}}checkFields(e,t,i,r,o,s){const a={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return function(e,t){if(t.endsWith("*")){const i=t.slice(0,-1);return e.slice(0,i.length)===i}return e===t}(i,e)}};for(const e in a){const t=a[e],i="not_"+e,n=this.filterJson[i];if(null==n?void 0:n.some(t))return!1;const r=this.filterJson[e];if(r&&!r.some(t))return!1}const c=this.filterJson.contains_url;if(void 0!==c&&c!==r)return!1;const d=this.filterJson[n.FILTER_RELATED_BY_REL_TYPES.name];if(void 0!==d&&!this.arrayMatchesFilter(d,o))return!1;const l=this.filterJson[n.FILTER_RELATED_BY_SENDERS.name];return!(void 0!==l&&!this.arrayMatchesFilter(l,s))}arrayMatchesFilter(e,t){return t.length>0&&e.every((e=>t.includes(e)))}filter(e){return e.filter(this.check,this)}limit(){return void 0!==this.filterJson.limit?this.filterJson.limit:10}}},{"./models/thread":394}],364:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Filter=void 0;const n=e("./@types/sync"),r=e("./filter-component");function o(e,t,i){const n=t.split(".");let r=e;for(let e=0;e<n.length-1;e++)r[n[e]]||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=i}class s{static fromJson(e,t,i){const n=new s(e,t);return n.setDefinition(i),n}constructor(e,t){this.userId=e,this.filterId=t,this.definition={}}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;const t=e.room,i={};t&&(t.rooms&&(i.rooms=t.rooms),t.rooms&&(i.not_rooms=t.not_rooms)),this.roomFilter=new r.FilterComponent(i,this.userId),this.roomTimelineFilter=new r.FilterComponent((null==t?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomFilter&&(e=this.roomFilter.filter(e)),this.roomTimelineFilter&&(e=this.roomTimelineFilter.filter(e)),e}setTimelineLimit(e){o(this.definition,"room.timeline.limit",e)}setUnreadThreadNotifications(e){var t,i,r;this.definition=Object.assign(Object.assign({},this.definition),{room:Object.assign(Object.assign({},null===(t=this.definition)||void 0===t?void 0:t.room),{timeline:Object.assign(Object.assign({},null===(r=null===(i=this.definition)||void 0===i?void 0:i.room)||void 0===r?void 0:r.timeline),{[n.UNREAD_THREAD_NOTIFICATIONS.name]:e})})})}setLazyLoadMembers(e){o(this.definition,"room.state.lazy_load_members",e)}setIncludeLeaveRooms(e){o(this.definition,"room.include_leave",e)}}i.Filter=s,s.LAZY_LOADING_MESSAGES_FILTER={lazy_load_members:!0}},{"./@types/sync":314,"./filter-component":363}],365:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionError=i.MatrixError=i.HTTPError=void 0;class n extends Error{constructor(e,t){super(e),this.httpStatus=t}}i.HTTPError=n;i.MatrixError=class extends n{constructor(e={},t,i,n){let r=e.error||"Unknown message";t&&(r=`[${t}] ${r}`),i&&(r=`${r} (${i})`),super(`MatrixError: ${r}`,t),this.httpStatus=t,this.url=i,this.event=n,this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.data=e}};class r extends Error{constructor(e,t){super(e+(t?`: ${t.message}`:""))}get name(){return"ConnectionError"}}i.ConnectionError=r},{}],366:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.FetchHttpApi=void 0;const a=o(e("../utils")),c=e("./method"),d=e("./errors"),l=e("./interface"),u=e("./utils");i.FetchHttpApi=class{constructor(e,t){var i;this.eventEmitter=e,this.opts=t,this.abortController=new AbortController,a.checkObjectHasKeys(t,["baseUrl","prefix"]),t.onlyData=!!t.onlyData,t.useAuthorizationHeader=null===(i=t.useAuthorizationHeader)||void 0===i||i}abort(){this.abortController.abort(),this.abortController=new AbortController}fetch(e,i){return this.opts.fetchFn?this.opts.fetchFn(e,i):t.fetch(e,i)}setIdBaseUrl(e){this.opts.idBaseUrl=e}idServerRequest(e,t,i,n,r){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");let o,s;e===c.Method.Get?o=i:s=i;const a=this.getUrl(t,o,n,this.opts.idBaseUrl),d={json:!0,headers:{}};return r&&(d.headers.Authorization=`Bearer ${r}`),this.requestOtherUrl(e,a,s,d)}authedRequest(e,t,i,n,r={}){i||(i={}),this.opts.accessToken&&(this.opts.useAuthorizationHeader?(r.headers||(r.headers={}),r.headers.Authorization||(r.headers.Authorization="Bearer "+this.opts.accessToken),i.access_token&&delete i.access_token):i.access_token||(i.access_token=this.opts.accessToken));const o=this.request(e,t,i,n,r);return o.catch((e=>{"M_UNKNOWN_TOKEN"!=e.errcode||(null==r?void 0:r.inhibitLogoutEmit)?"M_CONSENT_NOT_GIVEN"==e.errcode&&this.eventEmitter.emit(l.HttpApiEvent.NoConsent,e.message,e.data.consent_uri):this.eventEmitter.emit(l.HttpApiEvent.SessionLoggedOut,e)})),o}request(e,t,i,n,r){const o=this.getUrl(t,i,null==r?void 0:r.prefix,null==r?void 0:r.baseUrl);return this.requestOtherUrl(e,o,n,r)}requestOtherUrl(e,t,i,n={}){var r,o,a,c;return s(this,void 0,void 0,(function*(){const s=Object.assign({},n.headers||{}),l=null===(r=n.json)||void 0===r||r,h=l&&(null===(o=null==i?void 0:i.constructor)||void 0===o?void 0:o.name)===Object.name;l&&(h&&!s["Content-Type"]&&(s["Content-Type"]="application/json"),s.Accept||(s.Accept="application/json"));const f=null!==(a=n.localTimeoutMs)&&void 0!==a?a:this.opts.localTimeoutMs,p=null!==(c=n.keepAlive)&&void 0!==c&&c,g=[this.abortController.signal];let v;void 0!==f&&g.push((0,u.timeoutSignal)(f)),n.abortSignal&&g.push(n.abortSignal),v=h?JSON.stringify(i):i;const{signal:m,cleanup:y}=(0,u.anySignal)(g);let b;try{b=yield this.fetch(t,{signal:m,method:e,body:v,headers:s,mode:"cors",redirect:"follow",referrer:"",referrerPolicy:"no-referrer",cache:"no-cache",credentials:"omit",keepalive:p})}catch(e){if("AbortError"===e.name)throw e;throw new d.ConnectionError("fetch failed",e)}finally{y()}if(!b.ok)throw(0,u.parseErrorResponse)(b,yield b.text());return this.opts.onlyData?l?b.json():b.text():b}))}getUrl(e,t,i,n){const r=new URL((null!=n?n:this.opts.baseUrl)+(null!=i?i:this.opts.prefix)+e);return t&&a.encodeParams(t,r.searchParams),r}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":416,"./errors":365,"./interface":368,"./method":369,"./utils":371}],367:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.MatrixHttpApi=void 0;const a=e("./fetch"),c=e("./prefix"),d=o(e("../utils")),l=o(e("../realtime-callbacks")),u=e("./method"),h=e("./errors"),f=e("./utils");s(e("./interface"),i),s(e("./prefix"),i),s(e("./errors"),i),s(e("./method"),i),s(e("./utils"),i);class p extends a.FetchHttpApi{constructor(){super(...arguments),this.uploads=[]}uploadContent(e,i={}){var n,r,o,s,a;const p=null===(n=i.includeFilename)||void 0===n||n,g=null!==(r=i.abortController)&&void 0!==r?r:new AbortController,v=null!==(s=null!==(o=i.type)&&void 0!==o?o:e.type)&&void 0!==s?s:"application/octet-stream",m=null!==(a=i.name)&&void 0!==a?a:e.name,y={loaded:0,total:0,abortController:g},b=d.defer();if(t.XMLHttpRequest){const n=new t.XMLHttpRequest,r=function(){n.abort(),b.reject(new Error("Timeout"))};let o=l.setTimeout(r,3e4);n.onreadystatechange=function(){if(n.readyState===t.XMLHttpRequest.DONE){l.clearTimeout(o);try{if(0===n.status)throw new DOMException(n.statusText,"AbortError");if(!n.responseText)throw new Error("No response body.");n.status>=400?b.reject((0,f.parseErrorResponse)(n,n.responseText)):b.resolve(JSON.parse(n.responseText))}catch(e){if("AbortError"===e.name)return void b.reject(e);b.reject(new h.ConnectionError("request failed",e))}}},n.upload.onprogress=e=>{var t;l.clearTimeout(o),y.loaded=e.loaded,y.total=e.total,o=l.setTimeout(r,3e4),null===(t=i.progressHandler)||void 0===t||t.call(i,{loaded:e.loaded,total:e.total})};const s=this.getUrl("/upload",void 0,c.MediaPrefix.R0);p&&m&&s.searchParams.set("filename",encodeURIComponent(m)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&s.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),n.open(u.Method.Post,s.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&n.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),n.setRequestHeader("Content-Type",v),n.send(e),g.signal.addEventListener("abort",(()=>{n.abort()}))}else{const t={};p&&m&&(t.filename=m);const i={"Content-Type":v};this.authedRequest(u.Method.Post,"/upload",t,e,{prefix:c.MediaPrefix.R0,headers:i,abortSignal:g.signal}).then((e=>this.opts.onlyData?e:e.json())).then(b.resolve,b.reject)}return y.promise=b.promise.finally((()=>{d.removeElement(this.uploads,(e=>e===y))})),g.signal.addEventListener("abort",(()=>{d.removeElement(this.uploads,(e=>e===y)),b.reject(new DOMException("Aborted","AbortError"))})),this.uploads.push(y),y.promise}cancelUpload(e){const t=this.uploads.find((t=>t.promise===e));return!!t&&(t.abortController.abort(),!0)}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:c.MediaPrefix.R0+"/upload",params:{access_token:this.opts.accessToken}}}}i.MatrixHttpApi=p}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../realtime-callbacks":399,"../utils":416,"./errors":365,"./fetch":366,"./interface":368,"./method":369,"./prefix":370,"./utils":371}],368:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.HttpApiEvent=void 0,function(e){e.SessionLoggedOut="Session.logged_out",e.NoConsent="no_consent"}(i.HttpApiEvent||(i.HttpApiEvent={}))},{}],369:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Method=void 0,function(e){e.Get="GET",e.Put="PUT",e.Post="POST",e.Delete="DELETE"}(i.Method||(i.Method={}))},{}],370:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaPrefix=i.IdentityPrefix=i.ClientPrefix=void 0,function(e){e.R0="/_matrix/client/r0",e.V1="/_matrix/client/v1",e.V3="/_matrix/client/v3",e.Unstable="/_matrix/client/unstable"}(i.ClientPrefix||(i.ClientPrefix={})),function(e){e.V2="/_matrix/identity/v2"}(i.IdentityPrefix||(i.IdentityPrefix={})),function(e){e.R0="/_matrix/media/r0"}(i.MediaPrefix||(i.MediaPrefix={}))},{}],371:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.retryNetworkOperation=i.parseErrorResponse=i.anySignal=i.timeoutSignal=void 0;const r=e("content-type"),o=e("../logger"),s=e("../utils"),a=e("./errors");function c(e){return"getResponseHeader"in e}i.timeoutSignal=function(e){const t=new AbortController;return setTimeout((()=>{t.abort()}),e),t.signal},i.anySignal=function(e){const t=new AbortController;function i(){for(const t of e)t.removeEventListener("abort",n)}function n(){t.abort(),i()}for(const t of e){if(t.aborted){n();break}t.addEventListener("abort",n)}return{signal:t.signal,cleanup:i}},i.parseErrorResponse=function(e,t){let i;try{i=function(e){let t;t=c(e)?e.getResponseHeader("Content-Type"):e.headers.get("Content-Type");if(!t)return null;try{return(0,r.parse)(t)}catch(e){throw new Error(`Error parsing Content-Type '${t}': ${e}`)}}(e)}catch(e){return e}return"application/json"===(null==i?void 0:i.type)&&t?new a.MatrixError(JSON.parse(t),e.status,c(e)?e.responseURL:e.url):"text/plain"===(null==i?void 0:i.type)?new a.HTTPError(`Server returned ${e.status} error: ${t}`,e.status):new a.HTTPError(`Server returned ${e.status} error`,e.status)},i.retryNetworkOperation=function(e,t){return n(this,void 0,void 0,(function*(){let i=0,n=null;for(;i<e;)try{if(i>0){const e=1e3*Math.pow(2,i);o.logger.log(`network operation failed ${i} times, retrying in ${e}ms...`),yield(0,s.sleep)(e)}return yield t()}catch(e){if(!(e instanceof a.ConnectionError))throw e;i+=1,n=e}throw n}))}},{"../logger":374,"../utils":416,"./errors":365,"content-type":72}],372:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.exists=void 0,i.exists=function(e,t){return new Promise(((i,n)=>{let r=!0;const o=e.open(t);o.onupgradeneeded=()=>{r=!1},o.onblocked=()=>n(o.error),o.onsuccess=()=>{o.result.close(),r||e.deleteDatabase(t),i(r)},o.onerror=()=>n(o.error)}))}},{}],373:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.InteractiveAuth=i.AuthType=void 0;const r=e("./logger"),o=e("./utils"),s="m.login.email.identity",a="m.login.msisdn";var c;!function(e){e.Password="m.login.password",e.Recaptcha="m.login.recaptcha",e.Terms="m.login.terms",e.Email="m.login.email.identity",e.Msisdn="m.login.msisdn",e.Sso="m.login.sso",e.SsoUnstable="org.matrix.login.sso",e.Dummy="m.login.dummy",e.RegistrationToken="m.login.registration_token",e.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token"}(c=i.AuthType||(i.AuthType={}));class d extends Error{constructor(e,t,i){super(e),this.required_stages=t,this.flows=i,this.name="NoAuthFlowFoundError"}}i.InteractiveAuth=class{constructor(e){this.requestingEmailToken=!1,this.attemptAuthDeferred=null,this.chosenFlow=null,this.currentStage=null,this.emailAttempt=1,this.submitPromise=null,this.requestEmailToken=()=>n(this,void 0,void 0,(function*(){if(this.requestingEmailToken)r.logger.warn("Could not request email token: Already requesting");else{r.logger.trace("Requesting email token. Attempt: "+this.emailAttempt),this.requestingEmailToken=!0;try{const e=yield this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,this.emailAttempt++,this.data.session);this.emailSid=e.sid,r.logger.trace("Email token request succeeded")}finally{this.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=e.emailSid}attemptAuth(){var e,t;this.attemptAuthDeferred=(0,o.defer)();const i=this.attemptAuthDeferred.promise;if(null===(e=this.data)||void 0===e?void 0:e.flows)this.startNextAuthStage();else{null===(t=this.busyChangedCallback)||void 0===t||t.call(this,!0);const e=this.data.session?{session:this.data.session}:null;this.doRequest(e).finally((()=>{var e;null===(e=this.busyChangedCallback)||void 0===e||e.call(this,!1)}))}return i}poll(){return n(this,void 0,void 0,(function*(){if(!this.data.session)return;if(!this.attemptAuthDeferred)return;if(this.submitPromise)return;let e={};if(this.currentStage==s&&this.emailSid){const t={sid:this.emailSid,client_secret:this.clientSecret};if(yield this.matrixClient.doesServerRequireIdServerParam()){const e=new URL(this.matrixClient.getIdentityServerUrl());t.id_server=e.host}e={type:s,threepid_creds:t,threepidCreds:t}}this.submitAuthDict(e,!0)}))}getSessionId(){var e;return null===(e=this.data)||void 0===e?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return null===(t=this.data.params)||void 0===t?void 0:t[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e,t=!1){var i,r;return n(this,void 0,void 0,(function*(){if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");for(t||null===(i=this.busyChangedCallback)||void 0===i||i.call(this,!0);this.submitPromise;)try{yield this.submitPromise}catch(e){}let n;this.data.session?(n={session:this.data.session},Object.assign(n,e)):n=e;try{this.submitPromise=this.doRequest(n,t),yield this.submitPromise}finally{this.submitPromise=null,t||null===(r=this.busyChangedCallback)||void 0===r||r.call(this,!1)}}))}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e,t=!1){var i,o,s,a;return n(this,void 0,void 0,(function*(){try{const i=yield this.requestCallback(e,t);this.attemptAuthDeferred.resolve(i),this.attemptAuthDeferred=null}catch(e){const n=null!==(o=null===(i=e.data)||void 0===i?void 0:i.flows)&&void 0!==o?o:null,d=this.data.flows||Boolean(n);401===e.httpStatus&&e.data&&d||(t?r.logger.log("Background poll request failed doing UI auth: ignoring",e):null===(s=this.attemptAuthDeferred)||void 0===s||s.reject(e)),e.data||(e.data={}),e.data.flows||e.data.completed||e.data.session||(e.data.flows=this.data.flows,e.data.completed=this.data.completed,e.data.session=this.data.session),this.data=e.data;try{this.startNextAuthStage()}catch(e){return this.attemptAuthDeferred.reject(e),void(this.attemptAuthDeferred=null)}if(!this.emailSid&&(null===(a=this.chosenFlow)||void 0===a?void 0:a.stages.includes(c.Email)))try{yield this.requestEmailToken()}catch(e){this.attemptAuthDeferred.reject(e),this.attemptAuthDeferred=null}}}))}startNextAuthStage(){var e,t,i,n;const r=this.chooseStage();if(!r)throw new Error("No incomplete flows from the server");this.currentStage=r,r!==c.Dummy?(null===(e=this.data)||void 0===e?void 0:e.errcode)||(null===(t=this.data)||void 0===t?void 0:t.error)?this.stateUpdatedCallback(r,{errcode:(null===(i=this.data)||void 0===i?void 0:i.errcode)||"",error:(null===(n=this.data)||void 0===n?void 0:n.error)||""}):this.stateUpdatedCallback(r,r===s?{emailSid:this.emailSid}:{}):this.submitAuthDict({type:"m.login.dummy"})}chooseStage(){null===this.chosenFlow&&(this.chosenFlow=this.chooseFlow()),r.logger.log("Active flow => %s",JSON.stringify(this.chosenFlow));const e=this.firstUncompletedStage(this.chosenFlow);return r.logger.log("Next stage: %s",e),e}chooseFlow(){const e=this.data.flows||[],t=Boolean(this.inputs.emailAddress)||Boolean(this.emailSid),i=Boolean(this.inputs.phoneCountry)&&Boolean(this.inputs.phoneNumber);for(const n of e){let e=!1,r=!1;for(const t of n.stages)t===s?e=!0:t==a&&(r=!0);if(e==t&&r==i)return n}const n=[];throw t&&n.push(s),i&&n.push(a),new d("No appropriate authentication flow found",n,e)}firstUncompletedStage(e){const t=this.data.completed||[];return e.stages.find((e=>!t.includes(e)))}}},{"./logger":374,"./utils":416}],374:[function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.logger=void 0;const r=n(e("loglevel")),o="matrix";function s(e){e.withPrefix=function(e){return function(e){const t=r.default.getLogger(`${o}-${e}`);t.prefix!==e&&(s(t),t.prefix=e,t.setLevel(r.default.levels.DEBUG,!1));return t}((this.prefix||"")+e)}}r.default.methodFactory=function(e,t,i){return function(...t){this.prefix&&t.unshift(this.prefix);return"error"===e||"warn"===e||"trace"===e||"info"===e?console[e](...t):console.log(...t)}},i.logger=r.default.getLogger(o),i.logger.setLevel(r.default.levels.DEBUG,!1),s(i.logger)},{loglevel:151}],375:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)},s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.createRoomWidgetClient=i.createClient=i.setCryptoStoreFactory=i.GroupCallType=i.GroupCallState=i.GroupCallIntent=i.GroupCallEvent=i.createNewMatrixCall=i.SecretStorage=i.ContentHelpers=void 0;const a=e("./crypto/store/memory-crypto-store"),c=e("./store/memory"),d=e("./scheduler"),l=e("./client"),u=e("./embedded");o(e("./client"),i),o(e("./embedded"),i),o(e("./http-api"),i),o(e("./autodiscovery"),i),o(e("./sync-accumulator"),i),o(e("./errors"),i),o(e("./models/beacon"),i),o(e("./models/event"),i),o(e("./models/room"),i),o(e("./models/event-timeline"),i),o(e("./models/event-timeline-set"),i),o(e("./models/poll"),i),o(e("./models/room-member"),i),o(e("./models/room-state"),i),o(e("./models/user"),i),o(e("./scheduler"),i),o(e("./filter"),i),o(e("./timeline-window"),i),o(e("./interactive-auth"),i),o(e("./service-types"),i),o(e("./store/memory"),i),o(e("./store/indexeddb"),i),o(e("./crypto/store/memory-crypto-store"),i),o(e("./crypto/store/indexeddb-crypto-store"),i),o(e("./content-repo"),i),o(e("./@types/event"),i),o(e("./@types/PushRules"),i),o(e("./@types/partials"),i),o(e("./@types/requests"),i),o(e("./@types/search"),i),o(e("./models/room-summary"),i),i.ContentHelpers=s(e("./content-helpers")),i.SecretStorage=s(e("./secret-storage"));var h=e("./webrtc/call");Object.defineProperty(i,"createNewMatrixCall",{enumerable:!0,get:function(){return h.createNewMatrixCall}});var f=e("./webrtc/groupCall");Object.defineProperty(i,"GroupCallEvent",{enumerable:!0,get:function(){return f.GroupCallEvent}}),Object.defineProperty(i,"GroupCallIntent",{enumerable:!0,get:function(){return f.GroupCallIntent}}),Object.defineProperty(i,"GroupCallState",{enumerable:!0,get:function(){return f.GroupCallState}}),Object.defineProperty(i,"GroupCallType",{enumerable:!0,get:function(){return f.GroupCallType}});let p=()=>new a.MemoryCryptoStore;function g(e){var i,n,r;return e.store=null!==(i=e.store)&&void 0!==i?i:new c.MemoryStore({localStorage:t.localStorage}),e.scheduler=null!==(n=e.scheduler)&&void 0!==n?n:new d.MatrixScheduler,e.cryptoStore=null!==(r=e.cryptoStore)&&void 0!==r?r:p(),e}i.setCryptoStoreFactory=function(e){p=e},i.createClient=function(e){return new l.MatrixClient(g(e))},i.createRoomWidgetClient=function(e,t,i,n){return new u.RoomWidgetClient(e,t,i,g(n))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":304,"./@types/event":306,"./@types/partials":309,"./@types/requests":312,"./@types/search":313,"./autodiscovery":319,"./client":321,"./content-helpers":322,"./content-repo":323,"./crypto/store/indexeddb-crypto-store":346,"./crypto/store/memory-crypto-store":348,"./embedded":358,"./errors":359,"./filter":364,"./http-api":367,"./interactive-auth":373,"./models/beacon":378,"./models/event":383,"./models/event-timeline":382,"./models/event-timeline-set":381,"./models/poll":385,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/room-summary":391,"./models/user":396,"./scheduler":403,"./secret-storage":404,"./service-types":405,"./store/indexeddb":410,"./store/memory":411,"./sync-accumulator":413,"./timeline-window":415,"./webrtc/call":418,"./webrtc/groupCall":422}],376:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MSC3089Branch=void 0;const r=e("../@types/event"),o=e("./event-timeline");i.MSC3089Branch=class{constructor(e,t,i){this.client=e,this.indexEvent=t,this.directory=i}get id(){const e=this.indexEvent.getStateKey();if(!e)throw new Error("State key not found for branch");return e}get isActive(){return!0===this.indexEvent.getContent().active}get version(){var e;return null!==(e=this.indexEvent.getContent().version)&&void 0!==e?e:1}get roomId(){return this.indexEvent.getRoomId()}delete(){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,{},this.id),yield this.client.redactEvent(this.roomId,this.id);const e=(yield this.getVersionHistory())[1];e&&(yield e.delete())}))}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{name:e}),this.id)}))}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{locked:e}),this.id)}))}getFileInfo(){return n(this,void 0,void 0,(function*(){const e=(yield this.getFileEvent()).getOriginalContent().file,t=this.client.mxcUrlToHttp(e.url);if(!t)throw new Error(`No HTTP URL available for ${e.url}`);return{info:e,httpUrl:t}}))}getFileEvent(){return n(this,void 0,void 0,(function*(){const e=this.client.getRoom(this.roomId);if(!e)throw new Error("Unknown room");let t=e.getUnfilteredTimelineSet().findEventById(this.id);for(;!t&&e.getLiveTimeline().getState(o.EventTimeline.BACKWARDS).paginationToken;)yield this.client.scrollback(e,100),t=e.getUnfilteredTimelineSet().findEventById(this.id);if(!t)throw new Error("Failed to find event");return yield this.client.decryptEventIfNeeded(t,{emit:!0,isRetry:!0}),t}))}createNewVersion(e,t,i,o){return n(this,void 0,void 0,(function*(){const n=yield this.directory.createFile(e,t,i,Object.assign(Object.assign({},null!=o?o:{}),{"m.new_content":!0,"m.relates_to":{rel_type:r.RelationType.Replace,event_id:this.id}}));return yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e,version:this.version+1},n.event_id),yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{active:!1}),this.id),n}))}getVersionHistory(){return n(this,void 0,void 0,(function*(){const e=[];e.push(this);const t=this.client.getRoom(this.roomId);if(!t)throw new Error("Invalid or unknown room");const i=[...t.getLiveTimeline().getEvents()].reverse();let n,r=yield this.getFileEvent();do{if(n=i.find((e=>e.replacingEventId()===r.getId())),n){const t=this.directory.getFile(n.getId());if(!t)break;e.push(t),r=n}}while(n);return e}))}}},{"../@types/event":306,"./event-timeline":382}],377:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.MSC3089TreeSpace=i.TreePermissions=i.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=void 0;const o=r(e("p-retry")),s=e("../@types/event"),a=e("../logger"),c=e("../utils"),d=e("./MSC3089Branch"),l=e("../crypto/algorithms/megolm");var u;i.DEFAULT_TREE_POWER_LEVELS_TEMPLATE={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[s.EventType.RoomPowerLevels]:100,[s.EventType.RoomHistoryVisibility]:100,[s.EventType.RoomTombstone]:100,[s.EventType.RoomEncryption]:100,[s.EventType.RoomName]:50,[s.EventType.RoomMessage]:50,[s.EventType.RoomMessageEncrypted]:50,[s.EventType.Sticker]:50},users:{}},function(e){e.Viewer="viewer",e.Editor="editor",e.Owner="owner"}(u=i.TreePermissions||(i.TreePermissions={}));i.MSC3089TreeSpace=class{constructor(e,t){if(this.client=e,this.roomId=t,this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){const e=this.room.currentState.getStateEvents(s.EventType.SpaceParent);return!(null==e?void 0:e.length)||e.every((e=>{var t;return!(null===(t=e.getContent())||void 0===t?void 0:t.via)}))}setName(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,s.EventType.RoomName,{name:e},"")}))}invite(e,t=!0,i=!0){return n(this,void 0,void 0,(function*(){const n=[this.retryInvite(e)];return t&&n.push(...this.getDirectories().map((n=>n.invite(e,t,i)))),Promise.all(n).then((()=>{i&&(0,l.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[e])}))}))}retryInvite(e){return(0,c.simpleRetryOperation)((()=>n(this,void 0,void 0,(function*(){yield this.client.invite(this.roomId,e).catch((e=>{if("M_FORBIDDEN"===(null==e?void 0:e.errcode))throw new o.default.AbortError(e);throw e}))}))))}setPermissions(e,t){var i;return n(this,void 0,void 0,(function*(){const n=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(n))throw new Error("Unexpected return type for power levels");const r=(null==n?void 0:n.getContent())||{},o=r.users_default||0,a=r.events_default||50,c=(null===(i=r.events)||void 0===i?void 0:i[s.EventType.RoomPowerLevels])||100,d=r.users||{};switch(t){case u.Viewer:d[e]=o;break;case u.Editor:d[e]=a;break;case u.Owner:d[e]=c;break;default:throw new Error("Invalid role: "+t)}r.users=d,yield this.client.sendStateEvent(this.roomId,s.EventType.RoomPowerLevels,r,"")}))}getPermissions(e){var t,i;const n=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(n))throw new Error("Unexpected return type for power levels");const r=(null==n?void 0:n.getContent())||{},o=r.users_default||0,a=r.events_default||50,c=(null===(t=r.events)||void 0===t?void 0:t[s.EventType.RoomPowerLevels])||100,d=(null===(i=r.users)||void 0===i?void 0:i[e])||o;return d>=c?u.Owner:d>=a?u.Editor:u.Viewer}createDirectory(e){return n(this,void 0,void 0,(function*(){const t=yield this.client.unstableCreateFileTree(e);return yield this.client.sendStateEvent(this.roomId,s.EventType.SpaceChild,{via:[this.client.getDomain()]},t.roomId),yield this.client.sendStateEvent(t.roomId,s.EventType.SpaceParent,{via:[this.client.getDomain()]},this.roomId),t}))}getDirectories(){const e=[],t=this.room.currentState.getStateEvents(s.EventType.SpaceChild);for(const i of t)try{const t=i.getStateKey();if(t){const i=this.client.unstableGetFileTreeSpace(t);i&&e.push(i)}}catch(e){a.logger.warn("Unable to create tree space instance for listing. Are we joined?",e)}return e}getDirectory(e){return this.getDirectories().find((t=>t.roomId===e))}delete(){return n(this,void 0,void 0,(function*(){const e=this.getDirectories();for(const t of e)yield t.delete();const t=["invite","knock","join"],i=this.room.currentState.getStateEvents(s.EventType.RoomMember);for(const e of i){if(e.getStateKey()!==this.client.getUserId()&&t.includes(e.getContent().membership)){const t=e.getStateKey();if(!t)throw new Error("State key not found for branch");yield this.client.kick(this.roomId,t,"Room deleted")}}yield this.client.leave(this.roomId)}))}getOrderedChildren(e){const t=e.map((e=>({roomId:e.getStateKey(),order:e.getContent().order}))).filter((e=>e.roomId));return t.sort(((e,t)=>{var i,n,r,o;if(e.order&&!t.order)return-1;if(!e.order&&t.order)return 1;if(e.order||t.order)return(0,c.lexicographicCompare)(e.order,t.order);{const a=this.client.getRoom(e.roomId),d=this.client.getRoom(t.roomId);if(!a||!d)return(0,c.lexicographicCompare)(e.roomId,t.roomId);const l=null!==(n=null===(i=a.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===i?void 0:i.getTs())&&void 0!==n?n:0,u=null!==(o=null===(r=d.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===r?void 0:r.getTs())&&void 0!==o?o:0;return l===u?(0,c.lexicographicCompare)(e.roomId,t.roomId):l-u}})),t}getParentRoom(){const e=this.room.currentState.getStateEvents(s.EventType.SpaceParent)[0];if(!e)throw new Error("Expected to have a parent in a non-top level space");const t=e.getStateKey();if(!t)throw new Error("No state key found for parent");const i=this.client.getRoom(t);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;const e=this.getParentRoom().currentState.getStateEvents(s.EventType.SpaceChild);return this.getOrderedChildren(e).findIndex((e=>e.roomId===this.roomId))}setOrder(e){var t,i;return n(this,void 0,void 0,(function*(){if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const n=this.getParentRoom(),r=n.currentState.getStateEvents(s.EventType.SpaceChild),o=this.getOrderedChildren(r);e=Math.max(Math.min(e,o.length-1),0);const a=this.getOrder()<e;a&&e===o.length-1?e--:a||0!==e||e++;const d=o[a?e:e-1],l=o[a?e+1:e];let u=c.DEFAULT_ALPHABET[0],h=!1;if(d)if(e===o.length-1)(null==l?void 0:l.order)&&(u=(0,c.nextString)(l.order));else{const e=null==d?void 0:d.order,t=null==l?void 0:l.order;e&&t?u=e===t?(0,c.nextString)(e):(0,c.averageBetweenStrings)(e,t):e?u=(0,c.nextString)(e):t?u=(0,c.prevString)(t):h=!0}else(null==l?void 0:l.order)&&(u=(0,c.prevString)(l.order));if(h){let i;for(let r=0;r<=e;r++){const e=o[r];if(0===r&&(i=e.order),e.order)i=e.order;else{i=i?(0,c.nextString)(i):c.DEFAULT_ALPHABET[0];const r=n.currentState.getStateEvents(s.EventType.SpaceChild,e.roomId),o=null!==(t=null==r?void 0:r.getContent())&&void 0!==t?t:{via:[this.client.getDomain()]};yield this.client.sendStateEvent(n.roomId,s.EventType.SpaceChild,Object.assign(Object.assign({},o),{order:i}),e.roomId)}}i&&(u=(0,c.nextString)(i))}const f=n.currentState.getStateEvents(s.EventType.SpaceChild,this.roomId),p=null!==(i=null==f?void 0:f.getContent())&&void 0!==i?i:{via:[this.client.getDomain()]};yield this.client.sendStateEvent(n.roomId,s.EventType.SpaceChild,Object.assign(Object.assign({},p),{order:u}),this.roomId)}))}createFile(e,t,i,r){return n(this,void 0,void 0,(function*(){const{content_uri:n}=yield this.client.uploadContent(t,{includeFilename:!1});i.url=n;const o={msgtype:s.MsgType.File,body:e,url:n,file:i};(r=null!=r?r:{})["m.new_content"]&&(r["m.new_content"]=o);const a=yield this.client.sendMessage(this.roomId,Object.assign(Object.assign(Object.assign({},r),o),{[s.UNSTABLE_MSC3089_LEAF.name]:{}}));return yield this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e},a.event_id),a}))}getFile(e){const t=this.room.currentState.getStateEvents(s.UNSTABLE_MSC3089_BRANCH.name,e);return t?new d.MSC3089Branch(this.client,t,this):null}listFiles(){return this.listAllFiles().filter((e=>e.isActive))}listAllFiles(){var e;return(null!==(e=this.room.currentState.getStateEvents(s.UNSTABLE_MSC3089_BRANCH.name))&&void 0!==e?e:[]).map((e=>new d.MSC3089Branch(this.client,e,this)))}}},{"../@types/event":306,"../crypto/algorithms/megolm":334,"../logger":374,"../utils":416,"./MSC3089Branch":376,"p-retry":225}],378:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Beacon=i.getBeaconInfoIdentifier=i.isTimestampInDuration=i.BeaconEvent=void 0;const n=e("../content-helpers"),r=e("../utils"),o=e("./typed-event-emitter");var s;!function(e){e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate"}(s=i.BeaconEvent||(i.BeaconEvent={}));i.isTimestampInDuration=(e,t,i)=>i>=e&&e+t>=i;i.getBeaconInfoIdentifier=e=>`${e.getRoomId()}_${e.getStateKey()}`;class a extends o.TypedEventEmitter{constructor(e){super(),this.rootEvent=e,this.clearLatestLocation=()=>{this._latestLocationEvent=void 0,this.emit(s.LocationUpdate,this.latestLocationState)},this.roomId=this.rootEvent.getRoomId(),this.setBeaconInfo(this.rootEvent)}get isLive(){return!!this._isLive}get identifier(){return(0,i.getBeaconInfoIdentifier)(this.rootEvent)}get beaconInfoId(){return this.rootEvent.getId()}get beaconInfoOwner(){return this.rootEvent.getStateKey()}get beaconInfoEventType(){return this.rootEvent.getType()}get beaconInfo(){return this._beaconInfo}get latestLocationState(){return this._latestLocationEvent&&(0,n.parseBeaconContent)(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if((0,i.getBeaconInfoIdentifier)(e)!==this.identifier)throw new Error("Invalid updating event");e.getTs()<this.rootEvent.getTs()||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(s.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(s.Destroy,this.identifier)}monitorLiveness(){if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),this.beaconInfo)if(this.isLive){const e=this.beaconInfo.timestamp+this.beaconInfo.timeout-Date.now();e>1&&(this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),e))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),this.beaconInfo.timestamp-Date.now()))}addLocations(e){var t;if(!this.isLive)return;const o=null===(t=e.filter((e=>{const t=e.getContent(),r=(0,n.parseBeaconContent)(t);if(!r.uri||!r.timestamp)return!1;const{timestamp:o}=r;return this._beaconInfo.timestamp&&(0,i.isTimestampInDuration)(this._beaconInfo.timestamp,this._beaconInfo.timeout,o)&&(!this.latestLocationState||o>this.latestLocationState.timestamp)})).sort(r.sortEventsByLatestContentTimestamp))||void 0===t?void 0:t[0];o&&(this._latestLocationEvent=o,this.emit(s.LocationUpdate,this.latestLocationState))}setBeaconInfo(e){this._beaconInfo=(0,n.parseBeaconInfoContent)(e.getContent()),this.checkLiveness()}checkLiveness(){const e=this.isLive;if(!this.beaconInfo)return;const t=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!this._beaconInfo.live&&!!t&&(0,i.isTimestampInDuration)(t,this._beaconInfo.timeout,Date.now()),e!==this.isLive&&this.emit(s.LivenessChange,this.isLive,this)}}i.Beacon=a},{"../content-helpers":322,"../utils":416,"./typed-event-emitter":395}],379:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventContext=void 0;const n=e("./event-timeline");i.EventContext=class{constructor(e){this.ourEvent=e,this.ourEventIndex=0,this.paginateTokens={[n.Direction.Backward]:null,[n.Direction.Forward]:null},this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(e=!1){return this.paginateTokens[e?n.Direction.Backward:n.Direction.Forward]}setPaginateToken(e,t=!1){this.paginateTokens[t?n.Direction.Backward:n.Direction.Forward]=null!=e?e:null}addEvents(e,t=!1){t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}},{"./event-timeline":382}],380:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventStatus=void 0,function(e){e.NOT_SENT="not_sent",e.ENCRYPTING="encrypting",e.SENDING="sending",e.QUEUED="queued",e.SENT="sent",e.CANCELLED="cancelled"}(i.EventStatus||(i.EventStatus={}))},{}],381:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventTimelineSet=i.DuplicateStrategy=void 0;const n=e("./event-timeline"),r=e("../logger"),o=e("./room"),s=e("./typed-event-emitter"),a=e("./relations-container");let c;var d;c=r.logger.log.bind(r.logger),function(e){e.Ignore="ignore",e.Replace="replace"}(d=i.DuplicateStrategy||(i.DuplicateStrategy={}));class l extends s.TypedEventEmitter{constructor(e,t={},i,r,o=null){var s,c,d;super(),this.room=e,this.thread=r,this.threadListType=o,this._eventIdToTimeline=new Map,this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new n.EventTimeline(this),this.displayPendingEvents=!1!==t.pendingEvents,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=t.filter,this.relations=null!==(c=null===(s=this.room)||void 0===s?void 0:s.relations)&&void 0!==c?c:new a.RelationsContainer(null!==(d=null==e?void 0:e.client)&&void 0!==d?d:i)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return this.room&&this.displayPendingEvents?this.room.getPendingEvents():[]}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){const i=this._eventIdToTimeline.get(e);i&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,i))}resetLiveTimeline(e,t){const i=!this.timelineSupport||!t,r=this.liveTimeline,s=i?r.forkLive(n.EventTimeline.FORWARDS):r.fork(n.EventTimeline.FORWARDS);i?(this.timelines=[s],this._eventIdToTimeline=new Map):this.timelines.push(s),t&&r.setPaginationToken(t,n.EventTimeline.FORWARDS),s.setPaginationToken(null!=e?e:null,n.EventTimeline.BACKWARDS),this.liveTimeline=s,this.emit(o.RoomEvent.TimelineReset,this.room,this,i)}getTimelineForEvent(e){if(null==e)return null;const t=this._eventIdToTimeline.get(e);return void 0===t?null:t}findEventById(e){const t=this.getTimelineForEvent(e);if(t)return t.getEvents().find((function(t){return t.getId()==e}))}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const e=new n.EventTimeline(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,i,o){if(!i)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&i==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(this.filter&&!(e=this.filter.filterRoomTimeline(e)).length)return;const s=t?n.EventTimeline.BACKWARDS:n.EventTimeline.FORWARDS,a=t?n.EventTimeline.FORWARDS:n.EventTimeline.BACKWARDS;let d=!1,l=!1;for(const o of e){const e=o.getId(),u=this._eventIdToTimeline.get(e);if(!u){this.addEventToTimeline(o,i,{toStartOfTimeline:t}),l=!0,d=!0;continue}if(l=!1,u==i){c("Event "+e+" already in timeline "+i);continue}const h=i.getNeighbouringTimeline(s);if(h){c(u==h?"Event "+e+" in neighbouring timeline - switching to "+u:"Event "+e+" already in a different timeline "+u),i=u;continue}r.logger.info("Already have timeline for "+e+" - joining timeline "+i+" to "+u);const f=u===this.liveTimeline,p=i===this.liveTimeline,g=s===n.EventTimeline.BACKWARDS&&f,v=s===n.EventTimeline.FORWARDS&&p;g||v?(g&&r.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+u+")"),v&&r.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+i+")")):(i.setNeighbouringTimeline(u,s),u.setNeighbouringTimeline(i,a),i=u,d=!0)}if(l||!d){if(s===n.EventTimeline.FORWARDS&&i===this.liveTimeline)return r.logger.warn({lastEventWasNew:l,didUpdate:d}),void r.logger.warn(`Refusing to set forwards pagination token of live timeline ${i} to ${o}`);i.setPaginationToken(null!=o?o:null,s)}}addLiveEvent(e,t,i=!1,o){let s,a=t||d.Ignore;if("object"==typeof t?({duplicateStrategy:a=d.Ignore,fromCache:i=!1,roomState:o,timelineWasEmpty:s}=t):void 0!==t&&r.logger.warn("Overload deprecated: `EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`"),this.filter){if(!this.filter.filterRoomTimeline([e]).length)return}const l=this._eventIdToTimeline.get(e.getId());if(l)if(a===d.Replace){c("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());const t=l.getEvents();for(let i=0;i<t.length;i++)if(t[i].getId()===e.getId()){o||(o=l.getState(n.EventTimeline.FORWARDS)),n.EventTimeline.setEventMetadata(e,o,!1),t[i]=e;break}}else c("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,fromCache:i,roomState:o,timelineWasEmpty:s})}addEventToTimeline(e,t,i,n=!1,s){var a,c;let d,l=!!i;if("object"==typeof i?({toStartOfTimeline:l,fromCache:n=!1,roomState:s,timelineWasEmpty:d}=i):void 0!==i&&r.logger.warn("Overload deprecated: `EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`"),t.getTimelineSet()!==this)throw new Error(`EventTimelineSet.addEventToTimeline: Timeline=${t.toString()} does not belong " +\n "in timelineSet(threadId=${null===(a=this.thread)||void 0===a?void 0:a.id})`);if(this.room&&!this.canContain(e)){let i=`event=${e.getId()}`;return e.threadRootId&&(i+=`(belongs to thread=${e.threadRootId})`),void r.logger.warn(`EventTimelineSet.addEventToTimeline: Ignoring ${i} that does not belong in timeline=${t.toString()} timelineSet(threadId=${null===(c=this.thread)||void 0===c?void 0:c.id})`)}const u=e.getId();t.addEvent(e,{toStartOfTimeline:l,roomState:s,timelineWasEmpty:d}),this._eventIdToTimeline.set(u,t),this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this);const h={timeline:t,liveEvent:!l&&t==this.liveTimeline&&!n};this.emit(o.RoomEvent.Timeline,e,this.room,Boolean(l),!1,h)}handleRemoteEcho(e,t,i){const n=this._eventIdToTimeline.get(t);n?(this._eventIdToTimeline.delete(t),this._eventIdToTimeline.set(i,n)):this.filter&&!this.filter.filterRoomTimeline([e]).length||this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1})}removeEvent(e){const t=this._eventIdToTimeline.get(e);if(!t)return null;const i=t.removeEvent(e);if(i){this._eventIdToTimeline.delete(e);const n={timeline:t};this.emit(o.RoomEvent.Timeline,i,this.room,void 0,!0,n)}return i}compareEventOrdering(e,t){if(e==t)return 0;const i=this._eventIdToTimeline.get(e),r=this._eventIdToTimeline.get(t);if(void 0===i)return null;if(void 0===r)return null;if(i===r){let n,r;const o=i.getEvents();for(let i=0;i<o.length&&(void 0===n||void 0===r);i++){const s=o[i].getId();s==e&&(n=i),s==t&&(r=i)}return n-r}let o=i;for(;o;){if(o===r)return-1;o=o.getNeighbouringTimeline(n.EventTimeline.FORWARDS)}for(o=i;o;){if(o===r)return 1;o=o.getNeighbouringTimeline(n.EventTimeline.BACKWARDS)}return null}canContain(e){if(!this.room)throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");const{threadId:t,shouldLiveInRoom:i}=this.room.eventShouldLiveIn(e);return this.thread?this.thread.id===t:i}}i.EventTimelineSet=l},{"../logger":374,"./event-timeline":382,"./relations-container":387,"./room":392,"./typed-event-emitter":395}],382:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventTimeline=i.Direction=void 0;const n=e("../logger"),r=e("./room-state"),o=e("../@types/event");var s;!function(e){e.Backward="b",e.Forward="f"}(s=i.Direction||(i.Direction={}));class a{static setEventMetadata(e,t,i){var n,r,s,a;(null===(r=null===(n=e.sender)||void 0===n?void 0:n.events)||void 0===r?void 0:r.member)||(e.sender=t.getSentinelMember(e.getSender())),(null===(a=null===(s=e.target)||void 0===s?void 0:s.events)||void 0===a?void 0:a.member)||e.getType()!==o.EventType.RoomMember||(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&i&&(e.forwardLooking=!1)}constructor(e){var t,i;this.eventTimelineSet=e,this.events=[],this.baseIndex=0,this.startToken=null,this.endToken=null,this.prevTimeline=null,this.nextTimeline=null,this.paginationRequests={[s.Backward]:null,[s.Forward]:null},this.roomId=null!==(i=null===(t=e.room)||void 0===t?void 0:t.roomId)&&void 0!==i?i:null,this.roomId&&(this.startState=new r.RoomState(this.roomId),this.endState=new r.RoomState(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}initialiseState(e,{timelineWasEmpty:t}={}){var i,n;if(this.events.length>0)throw new Error("Cannot initialise state after events are added");null===(i=this.startState)||void 0===i||i.setStateEvents(e,{timelineWasEmpty:t}),null===(n=this.endState)||void 0===n||n.setStateEvents(e,{timelineWasEmpty:t})}forkLive(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=t,this.endState=null==t?void 0:t.clone(),i}fork(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=null==t?void 0:t.clone(),i}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==a.BACKWARDS)return this.startState;if(e==a.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===s.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===s.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==a.BACKWARDS)return this.prevTimeline;if(e==a.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==a.BACKWARDS)this.prevTimeline=e;else{if(t!=a.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t,i){let r,s=!!t;"object"==typeof t?({toStartOfTimeline:s,roomState:i,timelineWasEmpty:r}=t):void 0!==t&&n.logger.warn("Overload deprecated: `EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"),i||(i=s?this.startState:this.endState);const c=this.getTimelineSet();let d;c.room&&(a.setEventMetadata(e,i,s),e.isState()&&c.room.getUnfilteredTimelineSet()===c&&(null==i||i.setStateEvents([e],{timelineWasEmpty:r}),e.sender&&(e.getType()!==o.EventType.RoomMember||s)||a.setEventMetadata(e,i,s))),d=s?0:this.events.length,this.events.splice(d,0,e),s&&this.baseIndex++}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const i=this.events[t];if(i.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,i}return null}toString(){return this.name}}i.EventTimeline=a,a.BACKWARDS=s.Backward,a.FORWARDS=s.Forward},{"../@types/event":306,"../logger":374,"./room-state":390}],383:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MatrixEvent=i.MatrixEventEvent=i.EventStatus=void 0;const r=e("matrix-events-sdk"),o=e("../logger"),s=e("../@types/event"),a=e("../utils"),c=e("./thread"),d=e("../ReEmitter"),l=e("./typed-event-emitter"),u=e("../crypto/algorithms"),h=e("../crypto/OlmDevice");var f=e("./event-status");Object.defineProperty(i,"EventStatus",{enumerable:!0,get:function(){return f.EventStatus}});const p=Object.freeze({visible:!0});var g;!function(e){e.Decrypted="Event.decrypted",e.BeforeRedaction="Event.beforeRedaction",e.VisibilityChange="Event.visibilityChange",e.LocalEventIdReplaced="Event.localEventIdReplaced",e.Status="Event.status",e.Replaced="Event.replaced",e.RelationsCreated="Event.relationsCreated"}(g=i.MatrixEventEvent||(i.MatrixEventEvent={}));class v extends l.TypedEventEmitter{constructor(e={}){var t;super(),this.event=e,this.pushActions=null,this._replacingEvent=null,this._localRedactionEvent=null,this._isCancelled=!1,this.visibility=p,this._hasCachedExtEv=!1,this._cachedExtEv=void 0,this.senderCurve25519Key=null,this.claimedEd25519Key=null,this.forwardingCurve25519KeyChain=[],this.untrusted=null,this.decryptionPromise=null,this.retryDecryption=!1,this.encryptedDisabledForUnverifiedDevices=!1,this.sender=null,this.target=null,this.status=null,this.error=null,this.forwardLooking=!0,["state_key","type","sender","room_id","membership"].forEach((t=>{"string"==typeof e[t]&&(e[t]=(0,a.internaliseString)(e[t]))})),["membership","avatar_url","displayname"].forEach((t=>{var i;"string"==typeof(null===(i=e.content)||void 0===i?void 0:i[t])&&(e.content[t]=(0,a.internaliseString)(e.content[t]))})),["rel_type"].forEach((t=>{var i,n;"string"==typeof(null===(n=null===(i=e.content)||void 0===i?void 0:i["m.relates_to"])||void 0===n?void 0:n[t])&&(e.content["m.relates_to"][t]=(0,a.internaliseString)(e.content["m.relates_to"][t]))})),this.txnId=e.txn_id,this.localTimestamp=Date.now()-(null!==(t=this.getAge())&&void 0!==t?t:0),this.reEmitter=new d.TypedReEmitter(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=r.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===s.EventType.RoomMessageEncrypted)for(const[t,i]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||void 0===e[t]&&(e[t]=i);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender||this.event.user_id}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getDetails(){let e=`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`;const t=this.getRoomId();t&&(e+=` room=${t}`);const i=this.getDate();return i&&(e+=` ts=${i.toISOString()}`),e}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e,t;const i=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];return(null==i?void 0:i.rel_type)===c.THREAD_RELATION_TYPE.name?i.event_id:(null===(t=this.getThread())||void 0===t?void 0:t.id)||this.threadId}get isThreadRoot(){var e;return!!this.getServerAggregatedRelation(c.THREAD_RELATION_TYPE.name)||(null===(e=this.getThread())||void 0===e?void 0:e.id)===this.getId()}get replyEventId(){var e,t;return null===(t=null===(e=this.getWireContent()["m.relates_to"])||void 0===e?void 0:e["m.in_reply_to"])||void 0===t?void 0:t.event_id}get relationEventId(){var e,t;return null===(t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"])||void 0===t?void 0:t.event_id}getPrevContent(){return this.getUnsigned().prev_content||this.event.prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age||this.event.age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return void 0!==this.event.state_key}makeEncrypted(e,t,i,n){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=i,this.claimedEd25519Key=n}isBeingDecrypted(){return null!=this.decryptionPromise}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){var e,t;return"m.bad.encrypted"===(null===(t=null===(e=this.clearEvent)||void 0===e?void 0:e.content)||void 0===t?void 0:t.msgtype)}get isEncryptedDisabledForUnverifiedDevices(){return this.isDecryptionFailure()&&this.encryptedDisabledForUnverifiedDevices}shouldAttemptDecryption(){return!this.isRedacted()&&(!this.isBeingDecrypted()&&(!this.clearEvent&&!!this.isEncrypted()))}attemptDecryption(e,t={}){return n(this,void 0,void 0,(function*(){if(!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");const i=this.clearEvent&&!this.isDecryptionFailure(),n=t.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(i&&!n)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(o.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this.decryptionPromise):(this.decryptionPromise=this.decryptionLoop(e,t),this.decryptionPromise)}))}cancelAndResendKeyRequest(e,t){const i=this.getWireContent();return e.requestRoomKey({algorithm:i.algorithm,room_id:this.getRoomId(),session_id:i.session_id,sender_key:i.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){return[{userId:e,deviceId:"*"}]}decryptionLoop(e,t={}){return n(this,void 0,void 0,(function*(){for(yield Promise.resolve();;){let i,n;this.retryDecryption=!1;try{e?(i=yield e.decryptEvent(this),!0===t.isRetry&&o.logger.info(`Decrypted event on retry (${this.getDetails()})`)):i=this.badEncryptedMessage("Encryption not enabled")}catch(e){const t=e instanceof u.DecryptionError?e.detailedString:String(e);if(n=e,this.retryDecryption){o.logger.log(`Error decrypting event (${this.getDetails()}), but retrying: ${t}`);continue}o.logger.warn(`Error decrypting event (${this.getDetails()}): ${t}`),i=this.badEncryptedMessage(String(e))}return this.decryptionPromise=null,this.retryDecryption=!1,this.setClearData(i),this.setPushActions(null),void(!1!==t.emit&&this.emit(g.Decrypted,this,n))}}))}badEncryptedMessage(e){return{clearEvent:{type:s.EventType.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}},encryptedDisabledForUnverifiedDevices:e===`DecryptionError: ${h.WITHHELD_MESSAGES["m.unverified"]}`}}setClearData(e){var t,i;this.clearEvent=e.clearEvent,this.senderCurve25519Key=null!==(t=e.senderCurve25519Key)&&void 0!==t?t:null,this.claimedEd25519Key=null!==(i=e.claimedEd25519Key)&&void 0!==i?i:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.encryptedDisabledForUnverifiedDevices=e.encryptedDisabledForUnverifiedDevices||!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===s.EventType.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return this.claimedEd25519Key?{ed25519:this.claimedEd25519Key}:{}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return!!this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(e){this.event.unsigned=e}unmarkLocallyRedacted(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(g.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,i;const n=null===(t=null==e?void 0:e.visible)||void 0===t||t,r=null!==(i=null==e?void 0:e.reason)&&void 0!==i?i:null;let o=!1;this.visibility.visible!==n?o=!0:this.visibility.visible||this.visibility.reason===r||(o=!0),o&&(this.visibility=n?p:Object.freeze({visible:!1,reason:r}),this.emit(g.VisibilityChange,this,n))}messageVisibility(){return this.visibility}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(g.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const e in this.event)this.event.hasOwnProperty(e)&&!m.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=void 0);const t=this.getType()in y?y[this.getType()]:{},i=this.getContent();for(const e in i)i.hasOwnProperty(e)&&!t[e]&&delete i[e];this.invalidateExtensibleEvent()}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===s.EventType.RoomRedaction}asVisibilityChange(){if(!s.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType()))return null;const e=this.getRelation();if(!e||"m.reference"!=e.rel_type)return null;const t=e.event_id;if(!t)return null;const i=this.getWireContent(),n=!!i.visible,r=i.reason;return r&&"string"!=typeof r?null:{visible:n,reason:r,eventId:t}}isVisibilityEvent(){return s.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())}getRedactionEvent(){var e,t,i,n;return this.isRedacted()?(null===(e=this.clearEvent)||void 0===e?void 0:e.unsigned)?null!==(i=null===(t=this.clearEvent)||void 0===t?void 0:t.unsigned.redacted_because)&&void 0!==i?i:null:(null===(n=this.event.unsigned)||void 0===n?void 0:n.redacted_because)?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),i=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==i&&this.emit(g.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(g.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(g.LocalEventIdReplaced,this)}isRelation(e){var t;const i=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return(!this.isState()||(null==i?void 0:i.rel_type)!==s.RelationType.Replace)&&!(!(null==i?void 0:i.rel_type)||!i.event_id||e&&i.rel_type!==e)}getRelation(){var e;return this.isRelation()&&null!==(e=this.getWireContent()["m.relates_to"])&&void 0!==e?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=null!=e?e:null,this.emit(g.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return null===(t=this.getUnsigned()["m.relations"])||void 0===t?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(s.RelationType.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e;const t=this.getServerAggregatedRelation(s.RelationType.Replace);if(t){const e=t.origin_server_ts;if(Number.isFinite(e))return new Date(e)}else if(this._replacingEvent)return null!==(e=this._replacingEvent.getDate())&&void 0!==e?e:void 0}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return this.replyEventId?this.replyEventId:e?e.event_id:this.isRedaction()?this.event.redacts:void 0}hasAssocation(){return!!this.getAssociatedId()}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(e=!0){this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new v(JSON.parse(JSON.stringify(this.event)));for(const[t,i]of Object.entries(this))"event"!==t&&(e[t]=i);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=(0,a.deepSortedObjectEntries)(this.event),i=(0,a.deepSortedObjectEntries)(e.event);return JSON.stringify(t)===JSON.stringify(i)}toJSON(){const e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.thread&&this.reEmitter.stopReEmitting(this.thread,[c.ThreadEvent.Update]),this.thread=e,this.setThreadId(null==e?void 0:e.id),e&&this.reEmitter.reEmit(e,[c.ThreadEvent.Update])}getThread(){return this.thread}setThreadId(e){this.threadId=e}}i.MatrixEvent=v;const m=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),y={[s.EventType.RoomMember]:{membership:1},[s.EventType.RoomCreate]:{creator:1},[s.EventType.RoomJoinRules]:{join_rule:1},[s.EventType.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}}},{"../@types/event":306,"../ReEmitter":317,"../crypto/OlmDevice":327,"../crypto/algorithms":333,"../logger":374,"../utils":416,"./event-status":380,"./thread":394,"./typed-event-emitter":395,"matrix-events-sdk":167}],384:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IgnoredInvites=i.PolicyScope=i.IGNORE_INVITES_ACCOUNT_EVENT_KEY=i.POLICIES_ACCOUNT_EVENT_TYPE=void 0;const r=e("matrix-events-sdk"),o=e("./event-timeline"),s=e("../@types/partials"),a=e("../utils");var c,d;i.POLICIES_ACCOUNT_EVENT_TYPE=new r.UnstableValue("m.policies","org.matrix.msc3847.policies"),i.IGNORE_INVITES_ACCOUNT_EVENT_KEY=new r.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),function(e){e.Ban="m.ban"}(c||(c={})),function(e){e.User="m.policy.user",e.Room="m.policy.room",e.Server="m.policy.server"}(d=i.PolicyScope||(i.PolicyScope={}));i.IgnoredInvites=class{constructor(e){this.client=e}addRule(e,t,i){return n(this,void 0,void 0,(function*(){const n=yield this.getOrCreateTargetRoom();return(yield this.client.sendStateEvent(n.roomId,e,{entity:t,reason:i,recommendation:c.Ban})).event_id}))}removeRule(e){return n(this,void 0,void 0,(function*(){yield this.client.redactEvent(e.getRoomId(),e.getId())}))}addSource(e){return n(this,void 0,void 0,(function*(){yield this.client.joinRoom(e);const t=(yield this.getOrCreateSourceRooms()).map((e=>e.roomId));return!t.includes(e)&&(t.push(e),yield this.withIgnoreInvitesPolicies((e=>{e.sources=t})),!0)}))}getRuleForInvite({sender:e,roomId:t}){return n(this,void 0,void 0,(function*(){const i=yield this.getOrCreateSourceRooms(),n=e.split(":")[1],r=t.split(":")[1];for(const s of i){const i=s.getUnfilteredTimelineSet().getLiveTimeline().getState(o.EventTimeline.FORWARDS);for(const{scope:o,entities:s}of[{scope:d.Room,entities:[t]},{scope:d.User,entities:[e]},{scope:d.Server,entities:[n,r]}]){const e=i.getStateEvents(o);for(const t of e){const e=t.getContent();if((null==e?void 0:e.recommendation)!=c.Ban)continue;const i=null==e?void 0:e.entity;if(!i)continue;let n;try{n=new RegExp((0,a.globToRegexp)(i,!1))}catch(e){continue}for(const e of s)if(e&&n.test(e))return t}}}return null}))}getOrCreateTargetRoom(){return n(this,void 0,void 0,(function*(){let e=this.getIgnoreInvitesPolicies().target;if("string"!=typeof e&&(e=null),e){const t=this.client.getRoom(e);if(t)return t;e=null}return e=(yield this.client.createRoom({name:"Individual Policy Room",preset:s.Preset.PrivateChat})).room_id,yield this.withIgnoreInvitesPolicies((t=>{t.target=e})),this.client.getRoom(e)}))}getOrCreateSourceRooms(){return n(this,void 0,void 0,(function*(){let e=this.getIgnoreInvitesPolicies().sources,t=!1;Array.isArray(e)||(t=!0,e=[]);let i=e.filter((e=>"string"==typeof e)).map((e=>this.client.getRoom(e))).filter((e=>!!e));if(i.length!=e.length&&(t=!0),0==i.length){t=!0,i=[yield this.getOrCreateTargetRoom()]}return t&&(yield this.withIgnoreInvitesPolicies((t=>{t.sources=e}))),i}))}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}withIgnoreInvitesPolicies(e){return n(this,void 0,void 0,(function*(){const{policies:t,ignoreInvitesPolicies:n}=this.getPoliciesAndIgnoreInvitesPolicies();e(n),t[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name]=n,yield this.client.setAccountData(i.POLICIES_ACCOUNT_EVENT_TYPE.name,t)}))}getPoliciesAndIgnoreInvitesPolicies(){var e;let t={};for(const n of[i.POLICIES_ACCOUNT_EVENT_TYPE.name,i.POLICIES_ACCOUNT_EVENT_TYPE.altName]){if(!n)continue;const i=null===(e=this.client.getAccountData(n))||void 0===e?void 0:e.getContent();if(i){t=i;break}}let n={},r=!1;for(const e of[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name,i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]){if(!e)continue;const i=t[e];if(i&&"object"==typeof i){n=i,r=!0;break}}return r||(t[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name]=n),{policies:t,ignoreInvitesPolicies:n}}}},{"../@types/partials":309,"../utils":416,"./event-timeline":382,"matrix-events-sdk":167}],385:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.Poll=i.PollEvent=void 0;const r=e("../@types/polls"),o=e("./relations"),s=e("./typed-event-emitter");var a;!function(e){e.New="Poll.new",e.End="Poll.end",e.Update="Poll.update",e.Responses="Poll.Responses",e.Destroy="Poll.Destroy",e.UndecryptableRelations="Poll.UndecryptableRelations"}(a=i.PollEvent||(i.PollEvent={}));const c=(e,t)=>({responseEvents:e.filter((e=>{if(!e.isDecryptionFailure())return r.M_POLL_RESPONSE.matches(e.getType())&&e.getTs()<=t}))});class d extends s.TypedEventEmitter{constructor(e,t,i){if(super(),this.rootEvent=e,this.matrixClient=t,this.room=i,this._isFetchingResponses=!1,this.responses=null,this.undecryptableRelationEventIds=new Set,this.countUndecryptableEvents=e=>{const t=e.filter((e=>e.isDecryptionFailure())).map((e=>e.getId())),i=this.undecryptableRelationsCount;this.undecryptableRelationEventIds=new Set([...this.undecryptableRelationEventIds,...t]),this.undecryptableRelationsCount!==i&&this.emit(a.UndecryptableRelations,this.undecryptableRelationsCount)},!this.rootEvent.getRoomId()||!this.rootEvent.getId())throw new Error("Invalid poll start event.");this.roomId=this.rootEvent.getRoomId(),this.pollEvent=this.rootEvent.unstableExtensibleEvent}get pollId(){return this.rootEvent.getId()}get endEventId(){var e;return null===(e=this.endEvent)||void 0===e?void 0:e.getId()}get isEnded(){return!!this.endEvent}get isFetchingResponses(){return this._isFetchingResponses}get undecryptableRelationsCount(){return this.undecryptableRelationEventIds.size}getResponses(){return n(this,void 0,void 0,(function*(){return this.responses||this.isFetchingResponses||(yield this.fetchResponses()),this.responses}))}onNewRelation(e){var t;if(r.M_POLL_END.matches(e.getType())&&this.validateEndEvent(e)&&(this.endEvent=e,this.refilterResponsesOnEnd(),this.emit(a.End)),!this.responses)return;const i=(null===(t=this.endEvent)||void 0===t?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:n}=c([e],i);this.countUndecryptableEvents([e]),n.length&&(n.forEach((e=>{this.responses.addEvent(e)})),this.emit(a.Responses,this.responses))}fetchResponses(){var e,t;return n(this,void 0,void 0,(function*(){this._isFetchingResponses=!0;const i=yield this.matrixClient.relations(this.roomId,this.rootEvent.getId(),"m.reference",void 0,{from:this.relationsNextBatch||void 0});yield Promise.all(i.events.map((e=>this.matrixClient.decryptEventIfNeeded(e))));const n=this.responses||new o.Relations("m.reference",r.M_POLL_RESPONSE.name,this.matrixClient,[r.M_POLL_RESPONSE.altName]),s=i.events.find((e=>r.M_POLL_END.matches(e.getType())));this.validateEndEvent(s)&&(this.endEvent=s,this.refilterResponsesOnEnd(),this.emit(a.End));const d=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:l}=c(i.events,d);l.forEach((e=>{n.addEvent(e)})),this.relationsNextBatch=null!==(t=i.nextBatch)&&void 0!==t?t:void 0,this.responses=n,this.countUndecryptableEvents(i.events),this.relationsNextBatch?this.fetchResponses():this._isFetchingResponses=!1,this.emit(a.Responses,this.responses)}))}refilterResponsesOnEnd(){var e;if(!this.responses)return;const t=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER;this.responses.getRelations().forEach((e=>{var i;e.getTs()>t&&(null===(i=this.responses)||void 0===i||i.removeEvent(e))})),this.emit(a.Responses,this.responses)}validateEndEvent(e){if(!e)return!1;if(this.endEvent&&this.endEvent.getTs()<e.getTs())return!1;const t=this.room.currentState,i=e.getSender();return!!i&&(i===this.rootEvent.getSender()||t.maySendRedactionForEvent(this.rootEvent,i))}}i.Poll=d},{"../@types/polls":310,"./relations":388,"./typed-event-emitter":395}],386:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.ReadReceipt=i.synthesizeReceipt=void 0;const s=e("../@types/read_receipts"),a=e("./typed-event-emitter"),c=o(e("../utils")),d=e("./event"),l=e("../@types/event"),u=e("../utils"),h=e("./room");function f(e,t,i){var n;return new d.MatrixEvent({content:{[t.getId()]:{[i]:{[e]:{ts:t.getTs(),thread_id:null!==(n=t.threadRootId)&&void 0!==n?n:s.MAIN_ROOM_TIMELINE}}}},type:l.EventType.Receipt,room_id:t.getRoomId()})}i.synthesizeReceipt=f;class p extends a.TypedEventEmitter{constructor(){super(...arguments),this.receipts=new u.MapWithDefault((()=>new Map)),this.receiptCacheByEventId=new Map}getReadReceiptForUserId(e,t=!1,i=s.ReceiptType.Read){var n,r;const[o,a]=null!==(r=null===(n=this.receipts.get(i))||void 0===n?void 0:n.get(e))&&void 0!==r?r:[null,null];return t?o:null!=a?a:o}getEventReadUpTo(e,t=!1){var i,n,r,o,a,c,d;const l=this.getUnfilteredTimelineSet(),u=this.getReadReceiptForUserId(e,t,s.ReceiptType.Read),h=this.getReadReceiptForUserId(e,t,s.ReceiptType.ReadPrivate);let f;return(null==u?void 0:u.eventId)&&(null==h?void 0:h.eventId)&&(f=l.compareEventOrdering(null==u?void 0:u.eventId,null==h?void 0:h.eventId)),!f&&(null===(i=null==u?void 0:u.data)||void 0===i?void 0:i.ts)&&(null===(n=null==h?void 0:h.data)||void 0===n?void 0:n.ts)&&(f=(null===(r=null==u?void 0:u.data)||void 0===r?void 0:r.ts)-(null===(o=null==h?void 0:h.data)||void 0===o?void 0:o.ts)),f?null!==(d=f<0?null==h?void 0:h.eventId:null==u?void 0:u.eventId)&&void 0!==d?d:null:null!==(c=null!==(a=null==h?void 0:h.eventId)&&void 0!==a?a:null==u?void 0:u.eventId)&&void 0!==c?c:null}addReceiptToStructure(e,t,i,n,r){var o,s,a;const c=this.receipts.getOrCreate(t);let d=c.get(i);d||(d=[null,null],c.set(i,d));let l=d[0];if(r&&(l=null!==(o=d[1])&&void 0!==o?o:d[0]),l){const t=this.getUnfilteredTimelineSet().compareEventOrdering(l.eventId,e);if(null!==t&&t>=0)return}const u={eventId:e,data:n},h=r?d[0]:u,f=r?u:d[1];let p=null;h&&f&&(p=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,f.eventId));const g=null===p||p<0,v=null!==(s=d[1])&&void 0!==s?s:d[0];r&&g?d[1]=u:r||(d[0]=u,g||(d[1]=null));if(v!==(null!==(a=d[1])&&void 0!==a?a:d[0])){if(v&&this.receiptCacheByEventId.get(v.eventId)){const e=v.eventId;this.receiptCacheByEventId.set(e,this.receiptCacheByEventId.get(e).filter((e=>e.type!==t||e.userId!==i))),this.receiptCacheByEventId.get(e).length<1&&this.receiptCacheByEventId.delete(e)}this.receiptCacheByEventId.get(e)||this.receiptCacheByEventId.set(e,[]),this.receiptCacheByEventId.get(e).push({userId:i,type:t,data:n})}}getReceiptsForEvent(e){return this.receiptCacheByEventId.get(e.getId())||[]}fixupNotifications(e){const t=this.getReadReceiptForUserId(e,!1),i=this.timeline[this.timeline.length-1];i&&(null==t?void 0:t.eventId)===i.getId()&&e===i.getSender()&&(this.setUnread(h.NotificationCountType.Total,0),this.setUnread(h.NotificationCountType.Highlight,0))}addLocalEchoReceipt(e,t,i){this.addReceipt(f(e,t,i),!0)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return c.isSupportedReceiptType(e.type)})).map((function(e){return e.userId}))}hasUserReadEvent(e,t){var i,n;const r=this.getEventReadUpTo(e,!1);if(r===t)return!0;if((null===(i=this.timeline)||void 0===i?void 0:i.length)&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===e)return!0;for(let e=(null===(n=this.timeline)||void 0===n?void 0:n.length)-1;e>=0;--e){const i=this.timeline[e];if(i.getId()===t)return!1;if(i.getId()===r)return!0}return!1}}i.ReadReceipt=p},{"../@types/event":306,"../@types/read_receipts":311,"../utils":416,"./event":383,"./room":392,"./typed-event-emitter":395}],387:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RelationsContainer=void 0;const n=e("./relations"),r=e("./event");i.RelationsContainer=class{constructor(e,t){this.client=e,this.room=t,this.relations=new Map}getChildEventsForEvent(e,t,i){var n,r;return null===(r=null===(n=this.relations.get(e))||void 0===n?void 0:n.get(t))||void 0===r?void 0:r.get(i)}getAllChildEventsForEvent(e){var t;const i=null!==(t=this.relations.get(e))&&void 0!==t?t:new Map,n=[];for(const e of i.values())for(const t of e.values())n.push(...t.getRelations());return n}aggregateParentEvent(e){const t=this.relations.get(e.getId());if(t)for(const i of t.values())for(const t of i.values())t.setTargetEvent(e)}aggregateChildEvent(e,t){var i,o,s;if(e.isRedacted()||e.status===r.EventStatus.CANCELLED)return;const a=e.getRelation();if(!a)return;const c=()=>{e.isDecryptionFailure()?e.once(r.MatrixEventEvent.Decrypted,c):this.aggregateChildEvent(e,t)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption())return void e.once(r.MatrixEventEvent.Decrypted,c);const{event_id:d,rel_type:l}=a,u=e.getType();let h=this.relations.get(d);h||(h=new Map,this.relations.set(d,h));let f=h.get(l);f||(f=new Map,h.set(l,f));let p=f.get(u);if(!p){p=new n.Relations(l,u,this.client),f.set(u,p);const e=null!==(i=this.room)&&void 0!==i?i:null==t?void 0:t.room,r=null!==(s=null!==(o=null==t?void 0:t.findEventById(d))&&void 0!==o?o:null==e?void 0:e.findEventById(d))&&void 0!==s?s:null==e?void 0:e.getPendingEvent(d);r&&p.setTargetEvent(r)}p.addEvent(e)}}},{"./event":383,"./relations":388}],388:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.Relations=i.RelationsEvent=void 0;const r=e("./event"),o=e("../logger"),s=e("../@types/event"),a=e("./typed-event-emitter"),c=e("./room");var d;!function(e){e.Add="Relations.add",e.Remove="Relations.remove",e.Redaction="Relations.redaction"}(d=i.RelationsEvent||(i.RelationsEvent={}));class l extends a.TypedEventEmitter{constructor(e,t,i,o){super(),this.relationType=e,this.eventType=t,this.altEventTypes=o,this.relationEventIds=new Set,this.relations=new Set,this.annotationsByKey={},this.annotationsBySender={},this.sortedAnnotationsByKey=[],this.targetEvent=null,this.creationEmitted=!1,this.onEventStatus=(e,t)=>{e.isSending()?t===r.EventStatus.CANCELLED&&(e.removeListener(r.MatrixEventEvent.Status,this.onEventStatus),this.removeEvent(e)):e.removeListener(r.MatrixEventEvent.Status,this.onEventStatus)},this.onBeforeRedaction=e=>n(this,void 0,void 0,(function*(){if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===s.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.removeListener(r.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Redaction,e)}})),this.client=i instanceof c.Room?i.client:i}addEvent(e){return n(this,void 0,void 0,(function*(){if(this.relationEventIds.has(e.getId()))return;const t=e.getRelation();if(!t)return void o.logger.error("Event must have relation info");const i=t.rel_type,n=e.getType();if(this.relationType===i&&((e,t,i=[])=>[t,...i].includes(e))(n,this.eventType,this.altEventTypes)){if(e.isSending()&&e.on(r.MatrixEventEvent.Status,this.onEventStatus),this.relations.add(e),this.relationEventIds.add(e.getId()),this.relationType===s.RelationType.Annotation)this.addAnnotationToAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.on(r.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Add,e),this.maybeEmitCreated()}else o.logger.error("Event relation info doesn't match this container")}))}removeEvent(e){return n(this,void 0,void 0,(function*(){if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===s.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}this.emit(d.Remove,e)}}))}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;let n=this.annotationsByKey[i];n||(n=this.annotationsByKey[i]=new Set,this.sortedAnnotationsByKey.push([i,n])),n.add(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const i=e[1];return t[1].size-i.size}));const r=e.getSender();let o=this.annotationsBySender[r];o||(o=this.annotationsBySender[r]=new Set),o.add(e)}removeAnnotationFromAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;const n=this.annotationsByKey[i];n&&(n.delete(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const i=e[1];return t[1].size-i.size})));const r=e.getSender(),o=this.annotationsBySender[r];o&&o.delete(e)}getSortedAnnotationsByKey(){return this.relationType!==s.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==s.RelationType.Annotation?null:this.annotationsBySender}getLastReplacement(){return n(this,void 0,void 0,(function*(){if(this.relationType!==s.RelationType.Replace)return null;if(!this.targetEvent)return null;const e=this.targetEvent.getServerAggregatedRelation(s.RelationType.Replace),t=null==e?void 0:e.origin_server_ts,i=this.getRelations().reduce(((e,i)=>i.getSender()!==this.targetEvent.getSender()||t&&t>i.getTs()||e&&e.getTs()>i.getTs()?e:i),null);return(null==i?void 0:i.shouldAttemptDecryption())&&this.client.isCryptoEnabled()?yield i.attemptDecryption(this.client.crypto):(null==i?void 0:i.isBeingDecrypted())&&(yield i.getDecryptionPromise()),i}))}setTargetEvent(e){return n(this,void 0,void 0,(function*(){if(!this.targetEvent){if(this.targetEvent=e,this.relationType===s.RelationType.Replace&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();e&&this.targetEvent.makeReplaced(e)}this.maybeEmitCreated()}}))}maybeEmitCreated(){this.creationEmitted||this.targetEvent&&this.relations.size&&(this.creationEmitted=!0,this.targetEvent.emit(r.MatrixEventEvent.RelationsCreated,this.relationType,this.eventType))}}i.Relations=l},{"../@types/event":306,"../logger":374,"./event":383,"./room":392,"./typed-event-emitter":395}],389:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomMember=i.RoomMemberEvent=void 0;const s=e("../content-repo"),a=o(e("../utils")),c=e("../logger"),d=e("./typed-event-emitter"),l=e("../@types/event");var u;!function(e){e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing"}(u=i.RoomMemberEvent||(i.RoomMemberEvent={}));class h extends d.TypedEventEmitter{constructor(e,t){super(),this.roomId=e,this.userId=t,this._isOutOfBand=!1,this.modified=-1,this.requestedProfileInfo=!1,this.typing=!1,this.powerLevel=0,this.powerLevelNorm=0,this.disambiguate=!1,this.events={},this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){var i,n;const r=null!==(i=e.getDirectionalContent().displayname)&&void 0!==i?i:"";if(e.getType()!==l.EventType.RoomMember)return;this._isOutOfBand=!1,this.events.member=e;const o=this.membership;this.membership=e.getDirectionalContent().membership,void 0===this.membership&&c.logger.trace(`membership event with membership undefined (forwardLooking: ${e.forwardLooking})!`,e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=function(e,t,i){if(!t||t===e)return!1;if(!a.removeHiddenChars(t))return!1;if(!i)return!1;if(f.test(t))return!0;if(p.test(t))return!0;const n=i.getUserIdsWithDisplayName(t);return!!n.some((t=>t!==e))}(this.userId,r,t);const s=this.name;this.name=function(e,t,i){return t&&t!==e?i?a.removeDirectionOverrideChars(t)+" ("+e+")":a.removeHiddenChars(t)?a.removeDirectionOverrideChars(t):e:e}(this.userId,r,this.disambiguate),this.rawDisplayName=a.removeDirectionOverrideChars(null!==(n=e.getDirectionalContent().displayname)&&void 0!==n?n:""),this.rawDisplayName&&a.removeHiddenChars(this.rawDisplayName)||(this.rawDisplayName=this.userId),o!==this.membership&&(this.updateModifiedTime(),this.emit(u.Membership,e,this,o)),s!==this.name&&(this.updateModifiedTime(),this.emit(u.Name,e,this,s))}setPowerLevelEvent(e){if(e.getType()!==l.EventType.RoomPowerLevels||""!==e.getStateKey())return;const t=e.getDirectionalContent();let i=t.users_default||0;const n=t.users||{};Object.values(n).forEach((e=>{i=Math.max(i,e)}));const r=this.powerLevel,o=this.powerLevelNorm;void 0!==n[this.userId]&&Number.isInteger(n[this.userId])?this.powerLevel=n[this.userId]:void 0!==t.users_default?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,i>0&&(this.powerLevelNorm=100*this.powerLevel/i),r===this.powerLevel&&o===this.powerLevelNorm||(this.updateModifiedTime(),this.emit(u.PowerLevel,e,this))}setTypingEvent(e){if("m.typing"!==e.getType())return;const t=this.typing;this.typing=!1;const i=e.getContent().user_ids;Array.isArray(i)&&(-1!==i.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(u.Typing,e,this)))}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return"leave"===this.membership&&void 0!==this.events.member&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),i=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),i=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return i}}getAvatarUrl(e,t,i,n,r=!0,o){const a=this.getMxcAvatarUrl();if(!a&&!r)return null;const c=(0,s.getHttpUriForMxc)(e,a,t,i,n,o);return c||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:void 0}}i.RoomMember=h;const f=/@.+:.+/,p=/[\u200E\u200F\u202A-\u202F]/},{"../@types/event":306,"../content-repo":323,"../logger":374,"../utils":416,"./typed-event-emitter":395}],390:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomState=i.RoomStateEvent=void 0;const a=e("./room-member"),c=e("../logger"),d=o(e("../utils")),l=e("../@types/event"),u=e("./event"),h=e("../@types/partials"),f=e("./typed-event-emitter"),p=e("./beacon"),g=e("../ReEmitter"),v=e("../@types/beacon");var m,y;!function(e){e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished"}(m||(m={})),function(e){e.Events="RoomState.events",e.Members="RoomState.members",e.NewMember="RoomState.newMember",e.Update="RoomState.update",e.BeaconLiveness="RoomState.BeaconLiveness",e.Marker="RoomState.Marker"}(y=i.RoomStateEvent||(i.RoomStateEvent={}));class b extends f.TypedEventEmitter{constructor(e,t={status:m.NotStarted}){super(),this.roomId=e,this.oobMemberFlags=t,this.reEmitter=new g.TypedReEmitter(this),this.sentinels={},this.displayNameToUserIds=new Map,this.userIdsToDisplayNames={},this.tokenToInvite={},this.joinedMemberCount=null,this.summaryJoinedMemberCount=null,this.invitedMemberCount=null,this.summaryInvitedMemberCount=null,this.modified=-1,this.members={},this.events=new Map,this.paginationToken=null,this.beacons=new Map,this._liveBeaconIds=[],this.updateModifiedTime()}getJoinedMemberCount(){return null!==this.summaryJoinedMemberCount?this.summaryJoinedMemberCount:(null===this.joinedMemberCount&&(this.joinedMemberCount=this.getMembers().reduce(((e,t)=>"join"===t.membership?e+1:e),0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return null!==this.summaryInvitedMemberCount?this.summaryInvitedMemberCount:(null===this.invitedMemberCount&&(this.invitedMemberCount=this.getMembers().reduce(((e,t)=>"invite"===t.membership?e+1:e),0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter((t=>!e.includes(t.userId)))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;let t=this.sentinels[e];if(void 0===t){t=new a.RoomMember(this.roomId,e);const i=this.members[e];(null==i?void 0:i.events.member)&&t.setMembershipEvent(i.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return void 0===t?[]:null;if(void 0===t)return Array.from(this.events.get(e).values());const i=this.events.get(e).get(t);return i||null}get hasLiveBeacons(){var e;return!!(null===(e=this.liveBeaconIds)||void 0===e?void 0:e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new b(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=m.NotStarted,Array.from(this.events.values()).forEach((t=>{e.setStateEvents(Array.from(t.values()))})),this.oobMemberFlags.status=t,null!==this.summaryInvitedMemberCount&&e.setInvitedMemberCount(this.getInvitedMemberCount()),null!==this.summaryJoinedMemberCount&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==m.Finished&&this.getMembers().forEach((t=>{var i;t.isOutOfBand()&&(null===(i=e.getMember(t.userId))||void 0===i||i.markOutOfBand())})),e}setUnknownStateEvents(e){const t=e.filter((e=>!this.events.has(e.getType())||!this.events.get(e.getType()).has(e.getStateKey())));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach((e=>{var t;if(e.getRoomId()!==this.roomId||!e.isState())return;v.M_BEACON_INFO.matches(e.getType())&&this.setBeacon(e);const i=this.getStateEventMatching(e);this.setStateEvent(e),e.getType()===l.EventType.RoomMember&&(this.updateDisplayNameCache(e.getStateKey(),null!==(t=e.getContent().displayname)&&void 0!==t?t:""),this.updateThirdPartyTokenCache(e)),this.emit(y.Events,e,this,i)})),this.onBeaconLivenessChange(),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===l.EventType.RoomMember){const t=e.getStateKey();"leave"!==e.getContent().membership&&"ban"!==e.getContent().membership||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);const i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),this.updateMember(i),this.emit(y.Members,e,this,i)}else if(e.getType()===l.EventType.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const i=t.getLastModifiedTime();t.setPowerLevelEvent(e),i!==t.getLastModifiedTime()&&this.emit(y.Members,e,this,t)})),this.sentinels={}}else l.UNSTABLE_MSC2716_MARKER.matches(e.getType())&&this.emit(y.Marker,e,t)})),this.emit(y.Update,this)}processBeaconEvents(e,t){var i;return s(this,void 0,void 0,(function*(){if(!e.length||!this.beacons.size)return;const n=[...this.beacons.values()].reduce(((e,t)=>(e[t.beaconInfoId]=t,e)),{}),r=(e,t)=>{if(!v.M_BEACON.matches(t.getType()))return;const i=n[e];i&&i.addLocations([t])};for(const o of e){const e=null===(i=o.getRelation())||void 0===i?void 0:i.event_id;if(!e||!n[e])return;if(!v.M_BEACON.matches(o.getType())&&!o.isEncrypted())return;try{yield t.decryptEventIfNeeded(o),r(e,o)}catch(t){o.isDecryptionFailure()&&o.once(u.MatrixEventEvent.Decrypted,(()=>s(this,void 0,void 0,(function*(){r(e,o)}))))}}}))}getOrCreateMember(e,t){let i=this.members[e];return i||(i=new a.RoomMember(this.roomId,e),this.members[e]=i,this.emit(y.NewMember,t,this,i)),i}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){var t;const i=(0,p.getBeaconInfoIdentifier)(e);if(this.beacons.has(i)){const n=this.beacons.get(i);return e.isRedacted()?void(n.beaconInfoId===(null===(t=e.getRedactionEvent())||void 0===t?void 0:t.redacts)&&(n.destroy(),this.beacons.delete(i))):n.update(e)}if(e.isRedacted())return;const n=new p.Beacon(e);this.reEmitter.reEmit(n,[p.BeaconEvent.New,p.BeaconEvent.Update,p.BeaconEvent.Destroy,p.BeaconEvent.LivenessChange]),this.emit(p.BeaconEvent.New,e,n),n.on(p.BeaconEvent.LivenessChange,this.onBeaconLivenessChange.bind(this)),n.on(p.BeaconEvent.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(n.identifier,n)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter((e=>e.isLive)).map((e=>e.identifier)),this.emit(y.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,i;return null!==(i=null===(t=this.events.get(e.getType()))||void 0===t?void 0:t.get(e.getStateKey()))&&void 0!==i?i:null}updateMember(e){const t=this.getStateEvents(l.EventType.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===m.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===m.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===m.NotStarted&&(this.oobMemberFlags.status=m.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===m.InProgress&&(this.oobMemberFlags.status=m.NotStarted)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach((t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])})),c.logger.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=m.NotStarted}setOutOfBandMembers(e){c.logger.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===m.InProgress&&(c.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=m.Finished,e.forEach((e=>this.setOutOfBandMember(e))),this.emit(y.Update,this))}setOutOfBandMember(e){if(e.getType()!==l.EventType.RoomMember)return;const t=e.getStateKey(),i=this.getMember(t);if(i&&!i.isOutOfBand())return;const n=this.getOrCreateMember(t,e);n.setMembershipEvent(e,this),n.markOutOfBand(),this.updateDisplayNameCache(n.userId,n.name),this.setStateEvent(e),this.updateMember(n),this.emit(y.Members,e,this,n)}setTypingEvent(e){Object.values(this.members).forEach((function(t){t.setTypingEvent(e)}))}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return null!==(t=this.displayNameToUserIds.get(d.removeHiddenChars(e)))&&void 0!==t?t:[]}maySendRedactionForEvent(e,t){const i=this.getMember(t);if(!i||"leave"===i.membership)return!1;if(e.status||e.isRedacted())return!1;const n=this.maySendEvent(l.EventType.RoomRedaction,t);return e.getSender()===t?n:this.hasSufficientPowerLevelFor("redact",i.powerLevel)}hasSufficientPowerLevelFor(e,t){const i=this.getStateEvents(l.EventType.RoomPowerLevels,"");let n={};i&&(n=i.getContent());let r=50;return d.isNumber(n[e])&&(r=n[e]),t>=r}maySendMessage(e){return this.maySendEventOfType(l.EventType.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!(t.isGuest()||!t.credentials.userId)&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,i){const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r,o={},s=0,a=0,c=0;if(n){r=n.getContent(),o=r.events||{},s=Number.isSafeInteger(r.state_default)?r.state_default:50;const e=r.users&&r.users[t];Number.isSafeInteger(e)?c=e:Number.isSafeInteger(r.users_default)&&(c=r.users_default),Number.isSafeInteger(r.events_default)&&(a=r.events_default)}let d=i?s:a;return Number.isSafeInteger(o[e])&&(d=o[e]),c>=d}mayTriggerNotifOfType(e,t){const i=this.getMember(t);if(!i)return!1;const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r=50;return n&&n.getContent()&&n.getContent().notifications&&d.isNumber(n.getContent().notifications[e])&&(r=n.getContent().notifications[e]),i.powerLevel>=r}getJoinRule(){var e;const t=this.getStateEvents(l.EventType.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||h.JoinRule.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(l.EventType.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||h.HistoryVisibility.Shared}getGuestAccess(){var e;const t=this.getStateEvents(l.EventType.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||h.GuestAccess.Forbidden}findPredecessor(e=!1){if(e){const e=this.getStateEvents(l.EventType.RoomPredecessor,"");if(e){const t=e.getContent(),i=t.predecessor_room_id;let n=t.last_known_event_id;"string"!=typeof n&&(n=void 0);let r=t.via_servers;if(Array.isArray(r)||(r=void 0),"string"==typeof i)return{roomId:i,eventId:n,viaServers:r}}}const t=this.getStateEvents(l.EventType.RoomCreate,"");if(t){const e=t.getContent().predecessor;if(e){const t=e.room_id;if("string"==typeof t){let i=e.event_id;return"string"==typeof i&&""!==i||(i=void 0),{roomId:t,eventId:i}}}}return null}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;if(!t)return;this.getStateEvents(l.EventType.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){var i;const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=d.removeHiddenChars(n),i=this.displayNameToUserIds.get(t);if(i){const n=i.filter((t=>t!==e));this.displayNameToUserIds.set(t,n)}}this.userIdsToDisplayNames[e]=t;const r=t&&d.removeHiddenChars(t);if(r){const t=null!==(i=this.displayNameToUserIds.get(r))&&void 0!==i?i:[];t.push(e),this.displayNameToUserIds.set(r,t)}}}i.RoomState=b},{"../@types/beacon":305,"../@types/event":306,"../@types/partials":309,"../ReEmitter":317,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./room-member":389,"./typed-event-emitter":395}],391:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RoomSummary=void 0;i.RoomSummary=class{constructor(e,t){this.roomId=e}}},{}],392:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomNameType=i.Room=i.RoomEvent=i.NotificationCountType=i.KNOWN_SAFE_ROOM_VERSION=void 0;const a=e("matrix-events-sdk"),c=e("./event-timeline-set"),d=e("./event-timeline"),l=e("../content-repo"),u=o(e("../utils")),h=e("../utils"),f=e("./event"),p=e("./event-status"),g=e("./room-member"),v=e("./room-summary"),m=e("../logger"),y=e("../ReEmitter"),b=e("../@types/event"),S=e("../client"),_=e("../filter"),E=e("./room-state"),w=e("./beacon"),T=e("./thread"),I=e("../@types/read_receipts"),R=e("./relations-container"),M=e("./read-receipt"),k=e("./poll");i.KNOWN_SAFE_ROOM_VERSION="9";const C=["1","2","3","4","5","6","7","8","9"];var O,A;!function(e){e.Highlight="highlight",e.Total="total"}(O=i.NotificationCountType||(i.NotificationCountType={})),function(e){e.MyMembership="Room.myMembership",e.Tags="Room.tags",e.AccountData="Room.accountData",e.Receipt="Room.receipt",e.Name="Room.name",e.Redaction="Room.redaction",e.RedactionCancelled="Room.redactionCancelled",e.LocalEchoUpdated="Room.localEchoUpdated",e.Timeline="Room.timeline",e.TimelineReset="Room.timelineReset",e.TimelineRefresh="Room.TimelineRefresh",e.OldStateUpdated="Room.OldStateUpdated",e.CurrentStateUpdated="Room.CurrentStateUpdated",e.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",e.UnreadNotifications="Room.UnreadNotifications"}(A=i.RoomEvent||(i.RoomEvent={}));class P extends M.ReadReceipt{constructor(e,t,i,n={}){super(),this.roomId=e,this.client=t,this.myUserId=i,this.opts=n,this.txnToEvent=new Map,this.notificationCounts={},this.threadNotifications=new Map,this.cachedThreadReadReceipts=new Map,this.oldestThreadedReceiptTs=1/0,this.unthreadedReceipts=new Map,this.polls=new Map,this.threadsTimelineSets=[],this.filteredTimelineSets={},this.timelineNeedsRefresh=!1,this.summaryHeroes=null,this.getTypeWarning=!1,this.getVersionWarning=!1,this.tags={},this.accountData=new Map,this.summary=null,this.relations=new R.RelationsContainer(this.client,this),this.threads=new Map,this.visibilityEvents=new Map,this.threadTimelineSetsPromise=null,this.threadsReady=!1,this.updateThreadRootEvents=(e,t,i)=>{var n,r;e.length&&(this.updateThreadRootEvent(null===(n=this.threadsTimelineSets)||void 0===n?void 0:n[0],e,t,i),e.hasCurrentUserParticipated&&this.updateThreadRootEvent(null===(r=this.threadsTimelineSets)||void 0===r?void 0:r[1],e,t,i))},this.updateThreadRootEvent=(e,t,i,n)=>{e&&t.rootEvent&&(n&&e.removeEvent(t.id),T.Thread.hasServerSideSupport?e.addLiveEvent(t.rootEvent,{duplicateStrategy:c.DuplicateStrategy.Replace,fromCache:!1,roomState:this.currentState}):e.addEventToTimeline(t.rootEvent,e.getLiveTimeline(),{toStartOfTimeline:i}))},this.applyRedaction=e=>{if(e.isRedaction()){const t=e.event.redacts,i=t?this.findEventById(t):void 0;if(i){if(i.makeRedacted(e),i.isState()){const e=this.currentState.getStateEvents(i.getType(),i.getStateKey());(null==e?void 0:e.getId())===i.getId()&&this.currentState.setStateEvents([i])}this.emit(A.Redaction,e,this),this.visibilityEvents.delete(t),i.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e)}}},this.setMaxListeners(100),this.reEmitter=new y.TypedReEmitter(this),n.pendingEventOrdering=n.pendingEventOrdering||S.PendingEventOrdering.Chronological,this.name=e,this.normalizedName=e,this.timelineSets=[new c.EventTimelineSet(this,n)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[A.Timeline,A.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===S.PendingEventOrdering.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then((e=>{const i=this.client.getEventMapper({toDevice:!1,decrypt:!1});e.forEach((e=>s(this,void 0,void 0,(function*(){const n=i(e);yield t.decryptEventIfNeeded(n),n.setStatus(p.EventStatus.NOT_SENT),this.addPendingEvent(n,n.getTxnId())}))))}))),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}createThreadsTimelineSets(){var e;return s(this,void 0,void 0,(function*(){if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if(null===(e=this.client)||void 0===e?void 0:e.supportsThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(T.ThreadFilterType.My)]);const e=yield this.threadTimelineSetsPromise;return this.threadsTimelineSets.push(...e),e}catch(e){return this.threadTimelineSetsPromise=null,null}return null}))}decryptCriticalEvents(){return s(this,void 0,void 0,(function*(){if(!this.client.isCryptoEnabled())return;const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),i=t.findIndex((t=>t.event.event_id===e)),n=t.slice(i).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));yield Promise.allSettled(n)}))}decryptAllEvents(){return s(this,void 0,void 0,(function*(){if(!this.client.isCryptoEnabled())return;const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));yield Promise.allSettled(e)}))}getCreator(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomCreate,"");return null!==(e=null==t?void 0:t.getContent().creator)&&void 0!==e?e:null}getVersion(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomCreate,"");return t?null!==(e=t.getContent().room_version)&&void 0!==e?e:"1":(this.getVersionWarning||(m.logger.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}shouldUpgradeToVersion(){return C.includes(this.getVersion())?null:i.KNOWN_SAFE_ROOM_VERSION}getRecommendedVersion(){return s(this,void 0,void 0,(function*(){let e=(yield this.client.getCapabilities())["m.room_versions"];if(!e){e={default:i.KNOWN_SAFE_ROOM_VERSION,available:{}};for(const t of C)e.available[t]=S.RoomVersionStability.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){m.logger.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");if(e=(yield this.client.getCapabilities(!0))["m.room_versions"],!e)return m.logger.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}))}checkVersionAgainstCapability(e){const t=this.getVersion();m.logger.log(`[${this.roomId}] Current version: ${t}`),m.logger.log(`[${this.roomId}] Version capability: `,e);const i={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return i;return Object.keys(e.available).filter((t=>"stable"===e.available[t])).includes(t)||(i.version=e.default,i.needsUpgrade=!0,i.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),i.urgent?m.logger.warn(`URGENT upgrade required on ${this.roomId}`):m.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),i}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(b.EventType.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=u.removeElement(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,i;return null!==(i=null===(t=this.pendingEventList)||void 0===t?void 0:t.some((t=>t.getId()===e)))&&void 0!==i&&i}getPendingEvent(e){var t,i;return null!==(i=null===(t=this.pendingEventList)||void 0===t?void 0:t.find((t=>t.getId()===e)))&&void 0!==i?i:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();if(e.length){return e[e.length-1].getTs()}return Number.MIN_SAFE_INTEGER}getMyMembership(){var e;return null!==(e=this.selfMembership)&&void 0!==e?e:"leave"}getDMInviter(){var e;const t=this.getMember(this.myUserId);if(t)return t.getDMInviter();if("invite"===this.selfMembership){if(2===this.getInvitedAndJoinedMemberCount())return null===(e=this.summaryHeroes)||void 0===e?void 0:e[0]}}guessDMUserId(){const e=this.getMember(this.myUserId);if(e){const t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];const t=this.currentState.getMembers().find((e=>e.userId!==this.myUserId));return t?t.userId:this.myUserId}getAvatarFallbackMember(){if(this.getInvitedAndJoinedMemberCount()>2)return;const e=Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length;if(e){const e=this.summaryHeroes.map((e=>this.getMember(e))).find((e=>!!e));if(e)return e}const t=this.currentState.getMembers();if(t.length<=2){const e=t.find((e=>e.userId!==this.myUserId));if(e)return e}if(e){const e=this.summaryHeroes.map((e=>this.client.getUser(e))).find((e=>!!e));if(e){const t=new g.RoomMember(this.roomId,e.userId);return t.user=e,t}}}updateMyMembership(e){const t=this.selfMembership;this.selfMembership=e,t!==e&&("leave"===e&&this.cleanupAfterLeaving(),this.emit(A.MyMembership,this,e,t))}loadMembersFromServer(){return s(this,void 0,void 0,(function*(){const e=this.client.store.getSyncToken();return(yield this.client.members(this.roomId,void 0,"leave",null!=e?e:void 0)).chunk}))}loadMembers(){return s(this,void 0,void 0,(function*(){let e=!1,t=yield this.client.store.getOutOfBandMembers(this.roomId);(null===t||this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId))&&(e=!0,t=yield this.loadMembersFromServer(),m.logger.log(`LL: got ${t.length} members from server for room ${this.roomId}`));return{memberEvents:t.filter(h.noUnsafeEventProps).map(this.client.getEventMapper()),fromServer:e}}))}membersLoaded(){return!this.opts.lazyLoadMembers||this.currentState.outOfBandMembersReady()}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then((e=>(this.currentState.setOutOfBandMembers(e.memberEvents),e.fromServer))).catch((e=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),e}));return e.then((e=>{if(e){const e=this.currentState.getMembers().filter((e=>e.isOutOfBand())).map((e=>{var t;return null===(t=e.events.member)||void 0===t?void 0:t.event}));m.logger.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{m.logger.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{m.logger.error(e)})),this.membersPromise=e,this.membersPromise}clearLoadedMembersIfNeeded(){return s(this,void 0,void 0,(function*(){this.opts.lazyLoadMembers&&this.membersPromise&&(yield this.loadMembersIfNeeded(),yield this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=void 0)}))}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch((e=>{m.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),m.logger.log(e)}))}refreshLiveTimeline(){return s(this,void 0,void 0,(function*(){const e=this.getLiveTimeline(),t=e.getPaginationToken(d.EventTimeline.FORWARDS),i=e.getPaginationToken(d.EventTimeline.BACKWARDS),n=e.getEvents(),r=n[n.length-1];m.logger.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${r&&r.getId()} liveTimelineBefore=${e.toString()} forwardPaginationToken=${t} backwardPaginationToken=${i}`);const o=this.getUnfilteredTimelineSet();let s;r?(this.resetLiveTimeline(null,null),this.emit(A.TimelineRefresh,this,o),s=yield this.client.getEventTimeline(o,r.getId())):s=yield this.client.getLatestTimeline(o);const a=o.getLiveTimeline();!a||null===a.getPaginationToken(d.Direction.Forward)&&null===a.getPaginationToken(d.Direction.Backward)&&0===a.getEvents().length?(m.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),s.setPaginationToken(t,d.EventTimeline.FORWARDS),o.setLiveTimeline(s),this.fixUpLegacyTimelineFields()):m.logger.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.`),this.setTimelineNeedsRefresh(!1),this.emit(A.TimelineRefresh,this,o)}))}resetLiveTimeline(e,t){for(const i of this.timelineSets)i.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);for(const i of this.threads.values())i.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const e=this.oldState,t=this.currentState;this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(d.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS),e!==this.oldState&&this.emit(A.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(A.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[E.RoomStateEvent.Events,E.RoomStateEvent.Members,E.RoomStateEvent.NewMember,E.RoomStateEvent.Update,E.RoomStateEvent.Marker,w.BeaconEvent.New,w.BeaconEvent.Update,w.BeaconEvent.Destroy,w.BeaconEvent.LivenessChange]),this.reEmitter.reEmit(this.currentState,[E.RoomStateEvent.Events,E.RoomStateEvent.Members,E.RoomStateEvent.NewMember,E.RoomStateEvent.Update,E.RoomStateEvent.Marker,w.BeaconEvent.New,w.BeaconEvent.Update,w.BeaconEvent.Destroy,w.BeaconEvent.LivenessChange]))}hasUnverifiedDevices(){return s(this,void 0,void 0,(function*(){if(!this.client.isRoomEncrypted(this.roomId))return!1;const e=yield this.getEncryptionTargetMembers();for(const t of e){if(this.client.getStoredDevicesForUser(t.userId).some((e=>e.isUnverified())))return!0}return!1}))}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){const t=this.findEventById(e),i=this.findThreadForEvent(t);return i?i.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const i=this.getThreads();for(let n=0;n<i.length;n++){if(t=i[n].findEventById(e),t)return t}}return t}getUnreadNotificationCount(e=O.Total){var t;let i=this.getRoomUnreadNotificationCount(e);for(const n of this.threadNotifications.values())i+=null!==(t=n[e])&&void 0!==t?t:0;return i}getUnreadCountForEventContext(e=O.Total,t){var i;return null!==(i=!!t.threadRootId&&!t.isThreadRoot?this.getThreadUnreadNotificationCount(t.threadRootId,e):this.getRoomUnreadNotificationCount(e))&&void 0!==i?i:0}getRoomUnreadNotificationCount(e=O.Total){var t;return null!==(t=this.notificationCounts[e])&&void 0!==t?t:0}getThreadUnreadNotificationCount(e,t=O.Total){var i,n;return null!==(n=null===(i=this.threadNotifications.get(e))||void 0===i?void 0:i[t])&&void 0!==n?n:0}hasThreadUnreadNotification(){var e,t;for(const i of this.threadNotifications.values())if((null!==(e=i.highlight)&&void 0!==e?e:0)>0||(null!==(t=i.total)&&void 0!==t?t:0)>0)return!0;return!1}setThreadUnreadNotificationCount(e,t,i){var n,r;const o=Object.assign({highlight:null===(n=this.threadNotifications.get(e))||void 0===n?void 0:n.highlight,total:null===(r=this.threadNotifications.get(e))||void 0===r?void 0:r.total},{[t]:i});this.threadNotifications.set(e,o),this.emit(A.UnreadNotifications,o,e)}get threadsAggregateNotificationType(){var e,t;let i=null;for(const n of this.threadNotifications.values()){if((null!==(e=n.highlight)&&void 0!==e?e:0)>0)return O.Highlight;(null!==(t=n.total)&&void 0!==t?t:0)>0&&!i&&(i=O.Total)}return i}resetThreadUnreadNotificationCount(e){if(e)for(const[t]of this.threadNotifications)e.includes(t)||this.threadNotifications.delete(t);else this.threadNotifications.clear();this.emit(A.UnreadNotifications)}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(A.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){const t=e["m.heroes"],i=e["m.joined_member_count"],n=e["m.invited_member_count"];Number.isInteger(i)&&this.currentState.setJoinedMemberCount(i),Number.isInteger(n)&&this.currentState.setInvitedMemberCount(n),Array.isArray(t)&&(this.summaryHeroes=t.filter((e=>e!==this.myUserId)))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return void 0===this.blacklistUnverifiedDevices?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,i,n,r=!0){const o=this.currentState.getStateEvents(b.EventType.RoomAvatar,"");if(!o&&!r)return null;const s=o?o.getContent().url:null;return s?(0,l.getHttpUriForMxc)(e,s,t,i,n):null}getMxcAvatarUrl(){var e,t;return(null===(t=null===(e=this.currentState.getStateEvents(b.EventType.RoomAvatar,""))||void 0===e?void 0:e.getContent())||void 0===t?void 0:t.url)||null}getCanonicalAlias(){const e=this.currentState.getStateEvents(b.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(b.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,i,n){i.getTimelineSet().addEventsToTimeline(e,t,i,n)}getThread(e){var t;return null!==(t=this.threads.get(e))&&void 0!==t?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter((function(t){return t.membership===e}))}getEncryptionTargetMembers(){return s(this,void 0,void 0,(function*(){yield this.loadMembersIfNeeded();let e=this.getMembersWithMembership("join");return this.shouldEncryptForInvitedMembers()&&(e=e.concat(this.getMembersWithMembership("invite"))),e}))}shouldEncryptForInvitedMembers(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomHistoryVisibility,"");return"joined"!==(null===(e=null==t?void 0:t.getContent())||void 0===e?void 0:e.history_visibility)}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){const i=this.getMember(e);return!!i&&i.membership===t}getOrCreateFilteredTimelineSet(e,{prepopulateTimeline:t=!0,useSyncEvents:i=!0,pendingEvents:n=!0}={}){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const r=Object.assign({filter:e,pendingEvents:n},this.opts),o=new c.EventTimelineSet(this,r);this.reEmitter.reEmit(o,[A.Timeline,A.TimelineReset]),i&&(this.filteredTimelineSets[e.filterId]=o,this.timelineSets.push(o));const s=this.getLiveTimeline();if(t){s.getEvents().forEach((function(e){o.addLiveEvent(e)}));let e=s;for(;e.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);)e=e.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);o.getLiveTimeline().setPaginationToken(e.getPaginationToken(d.EventTimeline.BACKWARDS),d.EventTimeline.BACKWARDS)}else if(i){const e=s.getPaginationToken(d.Direction.Forward);o.getLiveTimeline().setPaginationToken(e,d.Direction.Backward)}return o}getThreadListFilter(e=T.ThreadFilterType.All){return s(this,void 0,void 0,(function*(){const t=this.client.getUserId(),i=new _.Filter(t),n={room:{timeline:{[T.FILTER_RELATED_BY_REL_TYPES.name]:[T.THREAD_RELATION_TYPE.name]}}};e===T.ThreadFilterType.My&&(n.room.timeline[T.FILTER_RELATED_BY_SENDERS.name]=[t]),i.setDefinition(n);const r=yield this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,i);return i.filterId=r,i}))}createThreadTimelineSet(e){return s(this,void 0,void 0,(function*(){let t;if(T.Thread.hasServerSideListSupport)t=new c.EventTimelineSet(this,Object.assign(Object.assign({},this.opts),{pendingEvents:!1}),void 0,void 0,null!=e?e:T.ThreadFilterType.All),this.reEmitter.reEmit(t,[A.Timeline,A.TimelineReset]);else if(T.Thread.hasServerSideSupport){const i=yield this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(i,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new c.EventTimelineSet(this,{pendingEvents:!1}),Array.from(this.threads).forEach((([,i])=>{if(0===i.length)return;const n=i.timeline.some((e=>e.getSender()===this.client.getUserId()));(e!==T.ThreadFilterType.My||n)&&t.getLiveTimeline().addEvent(i.rootEvent,{toStartOfTimeline:!1})}));return t}))}processThreadRoots(e,t){for(const i of e)d.EventTimeline.setEventMetadata(i,this.currentState,t),this.getThread(i.getId())||this.createThread(i.getId(),i,[],t)}fetchRoomThreads(){var e,t;return s(this,void 0,void 0,(function*(){if(!this.threadsReady&&this.client.supportsThreads()){if(T.Thread.hasServerSideListSupport)yield Promise.all([this.fetchRoomThreadList(T.ThreadFilterType.All),this.fetchRoomThreadList(T.ThreadFilterType.My)]);else{const i=yield this.getThreadListFilter(),{chunk:n}=yield this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,d.Direction.Backward,i);if(!n.length)return;const r=n.map(this.client.getEventMapper()).sort(((e,t)=>{const i=e.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name),n=t.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name);return i.latest_event.origin_server_ts-n.latest_event.origin_server_ts}));let o;const s=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);for(const i of r){const n={duplicateStrategy:c.DuplicateStrategy.Ignore,fromCache:!1,roomState:s};null===(e=this.threadsTimelineSets[0])||void 0===e||e.addLiveEvent(i,n);const r=i.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name);(null==r?void 0:r.current_user_participated)&&(null===(t=this.threadsTimelineSets[1])||void 0===t||t.addLiveEvent(i,n),o=i)}this.processThreadRoots(r,!0),this.client.decryptEventIfNeeded(r[r.length-1]),o&&this.client.decryptEventIfNeeded(o)}this.on(T.ThreadEvent.NewReply,this.onThreadNewReply),this.on(T.ThreadEvent.Delete,this.onThreadDelete),this.threadsReady=!0}}))}processPollEvents(e){return s(this,void 0,void 0,(function*(){const t=e=>{if(a.M_POLL_START.matches(e.getType()))try{const t=new k.Poll(e,this.client,this);this.polls.set(e.getId(),t),this.emit(k.PollEvent.New,t)}catch(e){}},i=e=>{const t=e.relationEventId;if(t&&this.polls.has(t)){const i=this.polls.get(t);null==i||i.onNewRelation(e)}},n=e=>{t(e),i(e)};for(const t of e)try{yield this.client.decryptEventIfNeeded(t),n(t)}catch(e){}}))}fetchRoomThreadList(e){return s(this,void 0,void 0,(function*(){const t=e===T.ThreadFilterType.My?this.threadsTimelineSets[1]:this.threadsTimelineSets[0],{chunk:i,end:n}=yield this.client.createThreadListMessagesRequest(this.roomId,null,void 0,d.Direction.Backward,t.threadListType,t.getFilter());if(t.getLiveTimeline().setPaginationToken(null!=n?n:null,d.Direction.Backward),!i.length)return;const r=i.map(this.client.getEventMapper());this.processThreadRoots(r,!0);const o=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);for(const e of r)t.addLiveEvent(e,{duplicateStrategy:c.DuplicateStrategy.Replace,fromCache:!1,roomState:o})}))}onThreadNewReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);const i=this.getTimelineForEvent(e.id),n=null===(t=null==i?void 0:i.getEvents())||void 0===t?void 0:t.find((t=>t.getId()===e.id));n?e.clearEventMetadata(n):m.logger.debug("onThreadDelete: Could not find root event in room timeline");for(const t of this.threadsTimelineSets)t.removeEvent(e.id)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const i=this.timelineSets.indexOf(t);i>-1&&this.timelineSets.splice(i,1)}eventShouldLiveIn(e,t,i){var n,r;if(!(null===(n=this.client)||void 0===n?void 0:n.supportsThreads()))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||(null==i?void 0:i.has(e.getId())))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};if(e.isRelation(T.THREAD_RELATION_TYPE.name))return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:e.threadRootId};const o=e.getAssociatedId();let s;return o&&(s=null!==(r=this.findEventById(o))&&void 0!==r?r:null==t?void 0:t.find((e=>e.getId()===o))),s&&(e.isRelation()||e.isRedaction())?this.eventShouldLiveIn(s,t,i):(null==i?void 0:i.has(e.relationEventId))?{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.relationEventId}:{shouldLiveInRoom:!0,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;const{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t,i=!1){var n;let r=this.getThread(e);if(!r){const o=null!==(n=this.findEventById(e))&&void 0!==n?n:t.find((t=>t.getId()===e));r=this.createThread(e,o,t,i)}r.addEvents(t,i)}processThreadedEvents(e,t){var i;e.forEach(this.applyRedaction);const n={};for(const t of e){const{threadId:e,shouldLiveInThread:r}=this.eventShouldLiveIn(t);r&&!n[e]&&(n[e]=[]),null===(i=n[e])||void 0===i||i.push(t)}Object.entries(n).map((([e,i])=>this.addThreadedEvents(e,i,t)))}createThread(e,t,i=[],n){var r,o,s;if(this.threads.has(e))return this.threads.get(e);if(t){const e=this.relations.getAllChildEventsForEvent(t.getId());(null==e?void 0:e.length)&&(i=i.concat(e.filter((e=>!e.isRelation(b.RelationType.Replace)))))}const a=new T.Thread(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:null!==(r=this.cachedThreadReadReceipts.get(e))&&void 0!==r?r:[]});this.cachedThreadReadReceipts.delete(e),this.threads.set(a.id,a),a.addEvents(i,!1),this.reEmitter.reEmit(a,[T.ThreadEvent.Delete,T.ThreadEvent.Update,T.ThreadEvent.NewReply,A.Timeline,A.TimelineReset]);const c=(null===(o=this.lastThread)||void 0===o?void 0:o.rootEvent)&&(null==t?void 0:t.localTimestamp)&&(null===(s=this.lastThread.rootEvent)||void 0===s?void 0:s.localTimestamp)<(null==t?void 0:t.localTimestamp);return this.lastThread&&!c||(this.lastThread=a),this.threadsReady&&this.updateThreadRootEvents(a,n,!1),this.emit(T.ThreadEvent.New,a,n),a}processLiveEvent(e){this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);if(!e.getUnsigned().transaction_id&&e.getSender()===this.myUserId)for(const[t,i]of this.txnToEvent)if(i.getId()===e.getId()){m.logger.debug("processLiveEvent: found sent event without txn ID: ",t,e.getId());const i=e.getUnsigned();i.transaction_id=t,e.setUnsigned(i);break}}addLiveEvent(e,t){const{duplicateStrategy:i,timelineWasEmpty:n,fromCache:r}=t;for(const t of this.timelineSets)t.addLiveEvent(e,{duplicateStrategy:i,fromCache:r,timelineWasEmpty:n});e.sender&&e.getType()!==b.EventType.RoomRedaction&&this.addReceipt((0,M.synthesizeReceipt)(e.sender.userId,e,I.ReceiptType.Read),!0)}addPendingEvent(e,t){if(e.status!==p.EventStatus.SENDING&&e.status!==p.EventStatus.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(d.EventTimeline.setEventMetadata(e,this.getLiveTimeline().getState(d.EventTimeline.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some((e=>e.status===p.EventStatus.NOT_SENT))&&(m.logger.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(p.EventStatus.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let i=this.pendingEventList.find((e=>e.getId()===t));!i&&t&&(i=this.findEventById(t)),i&&(i.markLocallyRedacted(e),this.emit(A.Redaction,e,this))}}else for(const t of this.timelineSets)t.getFilter()?t.getFilter().filterRoomTimeline([e]).length&&t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1}):t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(A.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){const e=this.pendingEventList.map((e=>Object.assign(Object.assign({},e.event),{txn_id:e.getTxnId()}))).filter((e=>{const t=e.type===b.EventType.RoomMessageEncrypted,i=this.client.isRoomEncrypted(this.roomId);return t||!i}));this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){const i=t.getId(),n=e.getId(),r=t.status;m.logger.debug(`Got remote echo for event ${i} -> ${n} old status ${r}`),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(i),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:o,threadId:s}=this.eventShouldLiveIn(e),a=s?this.getThread(s):null;if(null==a||a.setEventMetadata(t),null==a||a.timelineSet.handleRemoteEcho(t,i,n),o)for(const e of this.timelineSets)e.handleRemoteEcho(t,i,n);this.emit(A.LocalEchoUpdated,t,this,i,r)}updatePendingEvent(e,t,i){if(m.logger.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${i}`),t==p.EventStatus.SENT&&!i)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==p.EventStatus.SENT){if(this.getTimelineForEvent(i)){const t=this.findEventById(i);if(!(null==t?void 0:t.getUnsigned().transaction_id)&&t){const i=t.getUnsigned();i.transaction_id=e.getTxnId(),t.setUnsigned(i),this.removeEvent(t.getId()),this.handleRemoteEcho(t,e)}return}}const n=e.status,r=e.getId();if(!n)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const o=D[n];if(!(null==o?void 0:o.includes(t)))throw new Error(`Invalid EventStatus transition ${n}->${t}`);if(e.setStatus(t),t==p.EventStatus.SENT){e.replaceLocalEventId(i);const{shouldLiveInRoom:t,threadId:n}=this.eventShouldLiveIn(e),o=n?this.getThread(n):void 0;if(null==o||o.setEventMetadata(e),null==o||o.timelineSet.replaceEventId(r,i),t)for(const e of this.timelineSets)e.replaceEventId(r,i)}else if(t==p.EventStatus.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(r);this.removePendingEvent(r),(null==e?void 0:e.isRedaction())&&this.revertRedactionLocalEcho(e)}this.removeEvent(r)}this.savePendingEvents(),this.emit(A.LocalEchoUpdated,e,this,r,n)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const i=this.getUnfilteredTimelineSet().findEventById(t);i&&(i.unmarkLocallyRedacted(),this.emit(A.RedactionCancelled,e,this),i.isRelation()&&this.aggregateNonLiveRelation(i))}addLiveEvents(e,t,i=!1){var n;let r=t,o=!1;if("object"==typeof t?({duplicateStrategy:r,fromCache:i=!1,timelineWasEmpty:o}=t):void 0!==t&&m.logger.warn("Overload deprecated: `Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"),r&&-1===["replace","ignore"].indexOf(r))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(let e=0;e<this.timelineSets.length;e++){const t=this.timelineSets[e].getLiveTimeline();if(t.getPaginationToken(d.EventTimeline.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(d.EventTimeline.FORWARDS)+")");if(t.getNeighbouringTimeline(d.EventTimeline.FORWARDS))throw new Error(`live timeline ${e} is no longer live - it has a neighbouring timeline`)}const s=this.findThreadRoots(e),a={},c={duplicateStrategy:r,fromCache:i,timelineWasEmpty:o};for(const t of e){if(this.processLiveEvent(t),t.getUnsigned().transaction_id){const e=this.txnToEvent.get(t.getUnsigned().transaction_id);if(e){this.handleRemoteEcho(t,e);continue}}const{shouldLiveInRoom:i,shouldLiveInThread:r,threadId:o}=this.eventShouldLiveIn(t,e,s);r&&!a[null!=o?o:""]&&(a[null!=o?o:""]=[]),null===(n=a[null!=o?o:""])||void 0===n||n.push(t),i&&this.addLiveEvent(t,c)}Object.entries(a).forEach((([e,t])=>{this.addThreadedEvents(e,t,!1)}))}partitionThreadedEvents(e){if(this.client.supportsThreads()){const t=this.findThreadRoots(e);return e.reduce(((i,n)=>{const{shouldLiveInRoom:r,shouldLiveInThread:o,threadId:s}=this.eventShouldLiveIn(n,e,t);return r&&i[0].push(n),o&&(n.setThreadId(null!=s?s:""),i[1].push(n)),i}),[[],[]])}return[e,[]]}findThreadRoots(e){var t;const i=new Set;for(const n of e)n.isRelation(T.THREAD_RELATION_TYPE.name)&&i.add(null!==(t=n.relationEventId)&&void 0!==t?t:"");return i}addReceipt(e,t=!1){const i=e.getContent();Object.keys(i).forEach((e=>{Object.keys(i[e]).forEach((n=>{Object.keys(i[e][n]).forEach((r=>{var o,s,a,c;const d=i[e][n][r],l=!d.thread_id||d.thread_id===I.MAIN_ROOM_TIMELINE,u=l?this:this.threads.get(null!==(o=d.thread_id)&&void 0!==o?o:"");if(u){if(u.addReceiptToStructure(e,n,r,d,t),this.client.isInitialSyncComplete()&&r===this.client.getUserId()){const t=u.timeline[u.timeline.length-1];t&&e===t.getId()&&r===t.getSender()&&(u.setUnread(O.Total,0),u.setUnread(O.Highlight,0))}}else this.cachedThreadReadReceipts.set(d.thread_id,[...null!==(s=this.cachedThreadReadReceipts.get(d.thread_id))&&void 0!==s?s:[],{eventId:e,receiptType:n,userId:r,receipt:d,synthetic:t}]);r===this.client.getUserId()&&!l&&d.ts<this.oldestThreadedReceiptTs&&(this.oldestThreadedReceiptTs=d.ts),!d.thread_id&&d.ts>(null!==(c=null===(a=this.unthreadedReceipts.get(r))||void 0===a?void 0:a.ts)&&void 0!==c?c:0)&&this.unthreadedReceipts.set(r,d)}))}))})),this.emit(A.Receipt,e,this)}addEphemeralEvents(e){for(const t of e)t.getType()===b.EventType.Typing?this.currentState.setTypingEvent(t):t.getType()===b.EventType.Receipt&&this.addReceipt(t)}removeEvents(e){for(const t of e)this.removeEvent(t)}removeEvent(e){let t=!1;for(const i of this.timelineSets){const n=i.removeEvent(e);n&&(n.isRedaction()&&this.revertRedactionLocalEcho(n),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(b.EventType.RoomMember,this.myUserId);if(e){const t=e.getContent().membership;if(this.updateMyMembership(t),"invite"===t){(e.getUnsigned().invite_room_state||[]).forEach((e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new f.MatrixEvent({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])}))}}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,h.normalize)(this.name),this.summary=new v.RoomSummary(this.roomId,{title:this.name}),t!==this.name&&this.emit(A.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(A.Tags,e,this)}addAccountData(e){for(const t of e){"m.tag"===t.getType()&&this.addTags(t);const e=t.getType(),i=this.accountData.get(e);this.accountData.set(e,t),this.emit(A.AccountData,t,this,i)}}getAccountData(e){return this.accountData.get(e)}maySendMessage(){return"join"===this.getMyMembership()&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(b.EventType.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(b.EventType.RoomMessage,this.myUserId))}canInvite(e){let t="join"===this.getMyMembership();const i=this.currentState.getStateEvents(b.EventType.RoomPowerLevels,""),n=i&&i.getContent(),r=this.getMember(e);return n&&r&&n.invite>r.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){const e=this.currentState.getStateEvents(b.EventType.RoomCreate,"");if(e)return e.getContent()[b.RoomCreateTypeField];this.getTypeWarning||(m.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===b.RoomType.Space}isCallRoom(){return this.getType()===b.RoomType.UnstableCall}isElementVideoRoom(){return this.getType()===b.RoomType.ElementVideo}findPredecessor(e=!1){const t=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){const t=this.client.roomNameGenerator(this.roomId,e);if(null!==t)return t}switch(e.type){case x.Actual:return e.name;case x.Generated:return"Inviting"===e.subtype?`Inviting ${L(e.names,e.count)}`:L(e.names,e.count);case x.EmptyRoom:return e.oldName?`Empty room (was ${e.oldName})`:"Empty room"}}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(b.EventType.RoomName,"");if(null==e?void 0:e.getContent().name)return this.roomNameGenerator({type:x.Actual,name:e.getContent().name})}const i=this.getCanonicalAlias();if(i)return this.roomNameGenerator({type:x.Actual,name:i});let n=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,r=[];const o=this.currentState.getStateEvents(b.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,"");Array.isArray(null==o?void 0:o.getContent().service_members)&&(r=o.getContent().service_members);let s=[];if(this.summaryHeroes)this.summaryHeroes.forEach((e=>{if(r.includes(e))return void n--;const t=this.getMember(e);s.push(t?t.name:e)}));else{let t=this.currentState.getMembers().filter((t=>t.userId!==e&&("invite"===t.membership||"join"===t.membership)));t=t.filter((({userId:e})=>!r.includes(e)||(n--,!1))),t.sort(((e,t)=>u.compare(e.userId,t.userId))),t=t.slice(0,5),s=t.map((e=>e.name))}if(n)return this.roomNameGenerator({type:x.Generated,names:s,count:n});if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(b.EventType.RoomThirdPartyInvite);if(null==e?void 0:e.length){const t=e.map((e=>e.getContent().display_name));return this.roomNameGenerator({type:x.Generated,subtype:"Inviting",names:t,count:t.length+1})}}let a,c=s;return c.length||(c=this.currentState.getMembers().filter((t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership)).map((e=>e.name))),c.length&&(a=this.roomNameGenerator({type:x.Generated,names:c,count:c.length+1})),this.roomNameGenerator({type:x.EmptyRoom,oldName:a})}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const i=e.getSender();if(!i)return;if(!(b.EVENT_VISIBILITY_CHANGE_TYPE.name&&this.currentState.maySendStateEvent(b.EVENT_VISIBILITY_CHANGE_TYPE.name,i)||b.EVENT_VISIBILITY_CHANGE_TYPE.altName&&this.currentState.maySendStateEvent(b.EVENT_VISIBILITY_CHANGE_TYPE.altName,i)))return;const n=this.visibilityEvents.get(t.eventId);if(n){let t=n.length-1;const i=Math.max(0,n.length-30);for(;t>=i;--t){if(n[t].getTs()<e.getTs())break}-1===t?n.unshift(e):n.splice(t+1,0,e)}else this.visibilityEvents.set(t.eventId,[e]);const r=this.findEventById(t.eventId);r&&r.applyVisibilityEvent(t)}redactVisibilityChangeEvent(e){if(!e.isVisibilityEvent)throw new Error("expected a visibility change event");const t=e.getRelation(),i=null==t?void 0:t.event_id,n=this.visibilityEvents.get(i);if(!n)return;const r=n.findIndex((t=>t.getId()===e.getId()));if(-1!==r&&(n.splice(r,1),r===n.length)){const e=this.findEventById(i);if(!e)return;if(0===r)this.visibilityEvents.delete(i),e.applyVisibilityEvent();else{const t=n[n.length-1].asVisibilityChange();if(!t)throw new Error("at this stage, visibility changes should be well-formed");e.applyVisibilityEvent(t)}}}applyPendingVisibilityEvents(e){const t=this.visibilityEvents.get(e.getId());if(!t||0==t.length)return;const i=t[t.length-1],n=i.asVisibilityChange();n&&(n.visible,i.getTs()<e.getTs()||e.applyVisibilityEvent(n))}getOldestThreadedReceiptTs(){return this.oldestThreadedReceiptTs}getLastUnthreadedReceiptFor(e){return this.unthreadedReceipts.get(e)}fixupNotifications(e){super.fixupNotifications(e);const t=this.getThreads().filter((e=>this.getThreadUnreadNotificationCount(e.id,O.Total)>0));for(const i of t)i.fixupNotifications(e)}}i.Room=P;const D={[p.EventStatus.ENCRYPTING]:[p.EventStatus.SENDING,p.EventStatus.NOT_SENT,p.EventStatus.CANCELLED],[p.EventStatus.SENDING]:[p.EventStatus.ENCRYPTING,p.EventStatus.QUEUED,p.EventStatus.NOT_SENT,p.EventStatus.SENT],[p.EventStatus.QUEUED]:[p.EventStatus.SENDING,p.EventStatus.NOT_SENT,p.EventStatus.CANCELLED],[p.EventStatus.SENT]:[],[p.EventStatus.NOT_SENT]:[p.EventStatus.SENDING,p.EventStatus.QUEUED,p.EventStatus.CANCELLED],[p.EventStatus.CANCELLED]:[]};var x;function L(e,t){const i=t-1;if(e.length){if(1===e.length&&i<=1)return e[0];if(2===e.length&&i<=2)return`${e[0]} and ${e[1]}`;return i>1?`${e[0]} and ${i} others`:`${e[0]} and 1 other`}return"Empty room"}!function(e){e[e.EmptyRoom=0]="EmptyRoom",e[e.Generated=1]="Generated",e[e.Actual=2]="Actual"}(x=i.RoomNameType||(i.RoomNameType={}))},{"../@types/event":306,"../@types/read_receipts":311,"../ReEmitter":317,"../client":321,"../content-repo":323,"../filter":364,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./event-status":380,"./event-timeline":382,"./event-timeline-set":381,"./poll":385,"./read-receipt":386,"./relations-container":387,"./room-member":389,"./room-state":390,"./room-summary":391,"./thread":394,"matrix-events-sdk":167}],393:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SearchResult=void 0;const n=e("./event-context");class r{static fromJson(e,t){const i=e.context||{};let o=(i.events_before||[]).map(t),s=(i.events_after||[]).map(t);const a=new n.EventContext(t(e.result)),c=a.ourEvent.threadRootId;return o=o.filter((e=>e.threadRootId===c)),s=s.filter((e=>e.threadRootId===c)),a.setPaginateToken(i.start,!0),a.addEvents(o,!0),a.addEvents(s,!1),a.setPaginateToken(i.end,!1),new r(e.rank,a)}constructor(e,t){this.rank=e,this.context=t}}i.SearchResult=r},{"./event-context":379}],394:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.threadFilterTypeToFilter=i.ThreadFilterType=i.THREAD_RELATION_TYPE=i.FILTER_RELATED_BY_REL_TYPES=i.FILTER_RELATED_BY_SENDERS=i.Thread=i.determineFeatureSupport=i.FeatureSupport=i.ThreadEvent=void 0;const r=e("../client"),o=e("../ReEmitter"),s=e("../@types/event"),a=e("./event"),c=e("./event-timeline"),d=e("./event-timeline-set"),l=e("./room"),u=e("../NamespacedValue"),h=e("../logger"),f=e("./read-receipt"),p=e("../@types/read_receipts");var g,v,m;!function(e){e.New="Thread.new",e.Update="Thread.update",e.NewReply="Thread.newReply",e.ViewThread="Thread.viewThread",e.Delete="Thread.delete"}(g=i.ThreadEvent||(i.ThreadEvent={})),function(e){e[e.None=0]="None",e[e.Experimental=1]="Experimental",e[e.Stable=2]="Stable"}(v=i.FeatureSupport||(i.FeatureSupport={})),i.determineFeatureSupport=function(e,t){return e?v.Stable:t?v.Experimental:v.None};class y extends f.ReadReceipt{constructor(e,t,s){var c;if(super(),this.id=e,this.rootEvent=t,this.timeline=[],this._currentUserParticipated=!1,this.replyCount=0,this.pendingReplyCount=0,this.initialEventsFetched=!y.hasServerSideSupport,this.replayEvents=[],this.onBeforeRedaction=(e,t)=>{(null==e?void 0:e.isRelation(i.THREAD_RELATION_TYPE.name))&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(g.Update,this))},this.onRedaction=e=>n(this,void 0,void 0,(function*(){if(e.threadRootId===this.id)if(this.replyCount<=0){for(const e of this.timeline)this.clearEventMetadata(e);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit(g.Delete,this)}else yield this.updateThreadMetadata()})),this.onTimelineEvent=(e,t,i)=>{i||t.addLocalEchoReceipt(e.getSender(),e,p.ReceiptType.Read),this.onEcho(e,null!=i&&i)},this.onLocalEcho=e=>{this.onEcho(e,!1)},this.onEcho=(e,t)=>n(this,void 0,void 0,(function*(){e.threadRootId===this.id&&this.lastEvent!==e&&(yield this.updateThreadMetadata(),e.isRelation(i.THREAD_RELATION_TYPE.name)&&(t||this.emit(g.NewReply,this,e)))})),!(null==s?void 0:s.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=s.room,this.client=s.client,this.pendingEventOrdering=null!==(c=s.pendingEventOrdering)&&void 0!==c?c:r.PendingEventOrdering.Chronological,this.timelineSet=new d.EventTimelineSet(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new o.TypedReEmitter(this),this.reEmitter.reEmit(this.timelineSet,[l.RoomEvent.Timeline,l.RoomEvent.TimelineReset]),this.room.on(a.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.room.on(l.RoomEvent.Redaction,this.onRedaction),this.room.on(l.RoomEvent.LocalEchoUpdated,this.onLocalEcho),this.timelineSet.on(l.RoomEvent.Timeline,this.onTimelineEvent),this.processReceipts(s.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}fetchRootEvent(){return n(this,void 0,void 0,(function*(){this.rootEvent=this.room.findEventById(this.id);try{const e=yield this.client.fetchRoomEvent(this.roomId,this.id),t=this.client.getEventMapper();this.rootEvent=t(e)}catch(e){h.logger.error("Failed to fetch thread root to construct thread with",e)}yield this.processEvent(this.rootEvent)}))}static setServerSideSupport(e){y.hasServerSideSupport=e,e!==v.Stable&&(i.FILTER_RELATED_BY_SENDERS.setPreferUnstable(!0),i.FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(!0),i.THREAD_RELATION_TYPE.setPreferUnstable(!0))}static setServerSideListSupport(e){y.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){y.hasServerSideFwdPaginationSupport=e}get roomState(){return this.room.getLiveTimeline().getState(c.EventTimeline.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||(this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState}),this.timeline=this.events)}addEvents(e,t){e.forEach((e=>this.addEvent(e,t,!1))),this.updateThreadMetadata()}addEvent(e,t,r=!0){var o,a,c;return n(this,void 0,void 0,(function*(){this.setEventMetadata(e);const n=this.lastReply(),d=!n||e.localTimestamp>=n.localTimestamp;if(y.hasServerSideSupport){if(!t&&this.initialEventsFetched&&d)this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e);else if(e.isRelation(s.RelationType.Annotation)||e.isRelation(s.RelationType.Replace))return this.initialEventsFetched?this.addEventToTimeline(e,t):null===(o=this.replayEvents)||void 0===o||o.push(e),null===(a=this.timelineSet.relations)||void 0===a||a.aggregateParentEvent(e),void(null===(c=this.timelineSet.relations)||void 0===c||c.aggregateChildEvent(e,this.timelineSet))}else this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e,{});y.hasServerSideSupport&&this.rootEvent||!e.isRelation(i.THREAD_RELATION_TYPE.name)||this.replyCount++,r&&(this.emit(g.NewReply,this,e),this.updateThreadMetadata())}))}processEvent(e){return n(this,void 0,void 0,(function*(){e&&(this.setEventMetadata(e),yield this.fetchEditsWhereNeeded(e)),this.timeline=this.events}))}processReceipts(e=[]){for(const{eventId:t,receiptType:i,userId:n,receipt:r,synthetic:o}of e)this.addReceiptToStructure(t,i,n,r,o)}getRootEventBundledRelationship(e=this.rootEvent){return null==e?void 0:e.getServerAggregatedRelation(i.THREAD_RELATION_TYPE.name)}processRootEvent(){return n(this,void 0,void 0,(function*(){const e=this.getRootEventBundledRelationship();if(y.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=!!e.current_user_participated;const t=this.client.getEventMapper();this.lastEvent=t(Object.assign(Object.assign({},e.latest_event),{room_id:this.roomId})),this.updatePendingReplyCount(),yield this.processEvent(this.lastEvent)}}))}updatePendingReplyCount(){const e=(this.pendingEventOrdering===r.PendingEventOrdering.Detached?this.room.getPendingEvents():this.events).filter((e=>{var t;return e.threadRootId===this.id&&e.isRelation(i.THREAD_RELATION_TYPE.name)&&null!==e.status&&e.getId()!==(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())}));this.lastPendingEvent=e.length?e[e.length-1]:void 0,this.pendingReplyCount=e.length}resetLiveTimeline(e,t){return n(this,void 0,void 0,(function*(){const i=this.liveTimeline;this.timelineSet.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);const n=this.liveTimeline;let r,o;if(e){r=(yield this.client.createMessagesRequest(this.roomId,e,1,c.Direction.Forward)).end}if(t){o=(yield this.client.createMessagesRequest(this.roomId,t,1,c.Direction.Backward)).start}t&&i.getPaginationToken(c.Direction.Forward)===t&&i.setPaginationToken(null!=o?o:null,c.Direction.Forward),e&&n.getPaginationToken(c.Direction.Backward)===e&&n.setPaginationToken(null!=r?r:null,c.Direction.Backward)}))}updateThreadMetadata(){return n(this,void 0,void 0,(function*(){if(this.updatePendingReplyCount(),y.hasServerSideSupport&&(this.initialEventsFetched||(yield this.processRootEvent()),yield this.fetchRootEvent()),yield this.processRootEvent(),!this.initialEventsFetched){this.initialEventsFetched=!0;try{0===this.replyCount&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,c.Direction.Backward)):yield this.client.paginateEventTimeline(this.liveTimeline,{backwards:!0,limit:Math.max(1,this.length)});for(const e of this.replayEvents)this.addEvent(e,!1);this.replayEvents=null,this.emit(l.RoomEvent.TimelineReset,this.room,this.timelineSet,!0)}catch(e){h.logger.error("Failed to load start of newly created thread: ",e),this.initialEventsFetched=!1}}this.emit(g.Update,this)}))}fetchEditsWhereNeeded(...e){return n(this,void 0,void 0,(function*(){return Promise.all(e.filter((e=>e.isEncrypted())).map((e=>{if(!e.isRelation())return this.client.relations(this.roomId,e.getId(),s.RelationType.Replace,e.getType(),{limit:1}).then((t=>{t.events.length&&e.makeReplaced(t.events[0])})).catch((e=>{h.logger.error("Failed to load edits for encrypted thread event",e)}))})))}))}setEventMetadata(e){e&&(c.EventTimeline.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){var t,n,r;e&&(e.setThread(void 0),null===(r=null===(n=null===(t=e.event)||void 0===t?void 0:t.unsigned)||void 0===n?void 0:n["m.relations"])||void 0===r||delete r[i.THREAD_RELATION_TYPE.name])}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(e=(()=>!0)){for(let t=this.timeline.length-1;t>=0;t--){const i=this.timeline[t];if(e(i))return i}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return null!==(t=null!==(e=this.lastPendingEvent)&&void 0!==e?e:this.lastEvent)&&void 0!==t?t:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof a.MatrixEvent}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){var i,n;const r=e===this.client.getUserId(),o=this.timeline[this.timeline.length-1];if(r&&o){const e=o.getTs()<this.room.getOldestThreadedReceiptTs(),t=o.getId();if(e&&t)return t}const s=super.getEventReadUpTo(e,t);if(o){const t=this.room.getLastUnthreadedReceiptFor(e);if(!t)return s;for(let e=(null===(i=this.timeline)||void 0===i?void 0:i.length)-1;e>=0;--e){const i=this.timeline[e];if(i.getId()===s)return s;if(i.getTs()<t.ts)return null!==(n=i.getId())&&void 0!==n?n:s}}return s}hasUserReadEvent(e,t){var i,n,r,o,s,a;if(e===this.client.getUserId()){const t=(null!==(n=null===(i=this.lastReply())||void 0===i?void 0:i.getTs())&&void 0!==n?n:0)<this.room.getOldestThreadedReceiptTs(),c=null!==(o=null===(r=this.room.getLastUnthreadedReceiptFor(e))||void 0===r?void 0:r.ts)&&void 0!==o?o:0,d=(null!==(a=null===(s=null==this?void 0:this.lastReply())||void 0===s?void 0:s.getTs())&&void 0!==a?a:0)<c;if(t||d)return!0}return super.hasUserReadEvent(e,t)}setUnread(e,t){return this.room.setThreadUnreadNotificationCount(this.id,e,t)}}i.Thread=y,y.hasServerSideSupport=v.None,y.hasServerSideListSupport=v.None,y.hasServerSideFwdPaginationSupport=v.None,i.FILTER_RELATED_BY_SENDERS=new u.ServerControlledNamespacedValue("related_by_senders","io.element.relation_senders"),i.FILTER_RELATED_BY_REL_TYPES=new u.ServerControlledNamespacedValue("related_by_rel_types","io.element.relation_types"),i.THREAD_RELATION_TYPE=new u.ServerControlledNamespacedValue("m.thread","io.element.thread"),function(e){e[e.My=0]="My",e[e.All=1]="All"}(m=i.ThreadFilterType||(i.ThreadFilterType={})),i.threadFilterTypeToFilter=function(e){return e===m.My?"participated":"all"}},{"../@types/event":306,"../@types/read_receipts":311,"../NamespacedValue":316,"../ReEmitter":317,"../client":321,"../logger":374,"./event":383,"./event-timeline":382,"./event-timeline-set":381,"./read-receipt":386,"./room":392}],395:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=i.EventEmitterEvents=void 0;const n=e("events");!function(e){e.NewListener="newListener",e.RemoveListener="removeListener",e.Error="error"}(i.EventEmitterEvents||(i.EventEmitterEvents={}));class r extends n.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e,...t){return super.emit(e,...t)}eventNames(){return super.eventNames()}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}off(e,t){return super.off(e,t)}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}prependListener(e,t){return super.prependListener(e,t)}prependOnceListener(e,t){return super.prependOnceListener(e,t)}removeAllListeners(e){return super.removeAllListeners(e)}removeListener(e,t){return super.removeListener(e,t)}rawListeners(e){return super.rawListeners(e)}}i.TypedEventEmitter=r},{events:105}],396:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.User=i.UserEvent=void 0;const n=e("./typed-event-emitter");var r;!function(e){e.DisplayName="User.displayName",e.AvatarUrl="User.avatarUrl",e.Presence="User.presence",e.CurrentlyActive="User.currentlyActive",e.LastPresenceTs="User.lastPresenceTs"}(r=i.UserEvent||(i.UserEvent={}));class o extends n.TypedEventEmitter{constructor(e){super(),this.userId=e,this.modified=-1,this.presence="offline",this.lastActiveAgo=0,this.lastPresenceTs=0,this.currentlyActive=!1,this.events={},this.displayName=e,this.rawDisplayName=e,this.updateModifiedTime()}setPresenceEvent(e){if("m.presence"!==e.getType())return;const t=null===this.events.presence;this.events.presence=e;const i=[];(e.getContent().presence!==this.presence||t)&&i.push(r.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&i.push(r.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&i.push(r.DisplayName),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&i.push(r.CurrentlyActive),this.presence=e.getContent().presence,i.push(r.LastPresenceTs),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this.updateModifiedTime();for(const t of i)this.emit(t,e,this)}setDisplayName(e){const t=this.displayName;this.displayName=e,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName=e}setAvatarUrl(e){const t=this.avatarUrl;this.avatarUrl=e,e!==t&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}i.User=o},{"./typed-event-emitter":395}],397:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PushProcessor=void 0;const n=e("./utils"),r=e("./logger"),o=e("./@types/PushRules"),s=e("./@types/event"),a=[o.PushRuleKind.Override,o.PushRuleKind.ContentSpecific,o.PushRuleKind.RoomSpecific,o.PushRuleKind.SenderSpecific,o.PushRuleKind.Underride],c=[{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:"m.reaction"}],actions:[o.PushRuleActionName.DontNotify]},{rule_id:o.RuleId.IsUserMention,default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventPropertyContains,key:"content.org\\.matrix\\.msc3952\\.mentions.user_ids",value:""}],actions:[o.PushRuleActionName.Notify,{set_tweak:o.TweakName.Highlight}]},{rule_id:o.RuleId.IsRoomMention,default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventPropertyIs,key:"content.org\\.matrix\\.msc3952\\.mentions.room",value:!0},{kind:o.ConditionKind.SenderNotificationPermission,key:"room"}],actions:[o.PushRuleActionName.Notify,{set_tweak:o.TweakName.Highlight}]},{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:s.EventType.RoomServerAcl},{kind:o.ConditionKind.EventMatch,key:"state_key",pattern:""}],actions:[]}],d=[{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:o.ConditionKind.CallStarted}],actions:[o.PushRuleActionName.Notify,{set_tweak:o.TweakName.Sound,value:"default"}]}];class l{constructor(e){this.client=e,this.parsedKeys=new Map}static actionListToActionsObject(e){const t={notify:!1,tweaks:{}};for(const i of e)i===o.PushRuleActionName.Notify?t.notify=!0:"object"==typeof i&&(void 0===i.value&&(i.value=!0),t.tweaks[i.set_tweak]=i.value);return t}static rewriteDefaultRules(e,t=undefined){var i;let n=JSON.parse(JSON.stringify(e));n||(n={}),n.global||(n.global={}),n.global.override||(n.global.override=[]),n.global.underride||(n.global.underride=[]);const s=n.global.override;for(const e of c){const i=s.find((t=>t.rule_id===e.rule_id));let n;if(e.rule_id===o.RuleId.IsUserMention){if(!t)continue;n=JSON.parse(JSON.stringify(e)),n.conditions[0].value=t}else n=e;if(i)i.default=n.default,i.conditions=n.conditions,i.actions=n.actions;else{const e=n.rule_id;r.logger.warn(`Adding default global override for ${e}`),s.push(n)}}const a=null!==(i=n.global.underride)&&void 0!==i?i:[];for(const e of d){const t=a.find((t=>t.rule_id===e.rule_id));if(t)t.default=e.default,t.conditions=e.conditions,t.actions=e.actions;else{const t=e.rule_id;r.logger.warn(`Adding default global underride for ${t}`),a.push(e)}}return n}updateCachedPushRuleKeys(e){e||(e={}),e.global||(e.global={}),e.global.override||(e.global.override=[]),e.global.room||(e.global.room=[]),e.global.sender||(e.global.sender=[]),e.global.underride||(e.global.underride=[]);const t=new Set(this.parsedKeys.keys());for(const i of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(const e of i)if(e.conditions)for(const i of e.conditions)i.kind===o.ConditionKind.EventMatch&&(t.delete(i.key),this.parsedKeys.set(i.key,l.partsForDottedKey(i.key)));t.forEach((e=>this.parsedKeys.delete(e)))}matchingRuleFromKindSet(e,t){for(const i of a){const n=t[i];if(n)for(const t of n){if(!t.enabled)continue;const n=this.templateRuleToRaw(i,t);if(n&&this.ruleMatchesEvent(n,e))return Object.assign(Object.assign({},t),{kind:i})}}return null}templateRuleToRaw(e,t){const i={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case o.PushRuleKind.Underride:case o.PushRuleKind.Override:i.conditions=t.conditions;break;case o.PushRuleKind.RoomSpecific:if(!t.rule_id)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"room_id",value:t.rule_id});break;case o.PushRuleKind.SenderSpecific:if(!t.rule_id)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"user_id",value:t.rule_id});break;case o.PushRuleKind.ContentSpecific:if(!t.pattern)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"content.body",pattern:t.pattern})}return i}eventFulfillsCondition(e,t){switch(e.kind){case o.ConditionKind.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case o.ConditionKind.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case o.ConditionKind.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case o.ConditionKind.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case o.ConditionKind.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case o.ConditionKind.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case o.ConditionKind.CallStarted:case o.ConditionKind.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){const i=e.key;if(!i)return!1;const n=this.client.getRoom(t.getRoomId());return!!(null==n?void 0:n.currentState)&&n.currentState.mayTriggerNotifOfType(i,t.getSender())}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;const i=this.client.getRoom(t.getRoomId());if(!i||!i.currentState||!i.currentState.members)return!1;const n=i.currentState.getJoinedMemberCount(),r=e.is.match(/^([=<>]*)(\d*)$/);if(!r)return!1;const o=r[1],s=parseInt(r[2]);if(isNaN(s))return!1;switch(o){case"":case"==":return n==s;case"<":return n<s;case">":return n>s;case"<=":return n<=s;case">=":return n>=s;default:return!1}}eventFulfillsDisplayNameCondition(e,t){var i;let r=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(r=t.getClearContent()),!r||!r.body||"string"!=typeof r.body)return!1;const o=this.client.getRoom(t.getRoomId()),s=null===(i=null==o?void 0:o.currentState)||void 0===i?void 0:i.getMember(this.client.credentials.userId);if(!s)return!1;const a=s.name,c=new RegExp("(^|\\W)"+(0,n.escapeRegExp)(a)+"(\\W|$)","i");return r.body.search(c)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;const i=this.valueForDottedKey(e.key,t);if("string"!=typeof i)return!1;if(e.value)return e.value===i;if("string"!=typeof e.pattern)return!1;const n="content.body"===e.key?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!i.match(n)}eventFulfillsEventPropertyIsCondition(e,t){return!(!e.key||void 0===e.value)&&e.value===this.valueForDottedKey(e.key,t)}eventFulfillsEventPropertyContains(e,t){if(!e.key||void 0===e.value)return!1;const i=this.valueForDottedKey(e.key,t);return!!Array.isArray(i)&&i.includes(e.value)}eventFulfillsCallStartedCondition(e,t){return["m.ring","m.prompt"].includes(t.getContent()["m.intent"])&&!("m.terminated"in t.getContent())&&(t.getPrevContent()["m.terminated"]!==t.getContent()["m.terminated"]||(0,n.deepCompare)(t.getPrevContent(),{}))}createCachedRegex(e,t,i){return l.cachedGlobToRegex[t]||(l.cachedGlobToRegex[t]=new RegExp(e+(0,n.globToRegexp)(t)+i,"i")),l.cachedGlobToRegex[t]}static partsForDottedKey(e){const t=[];let i="",n=!1;for(const r of e)n?(i+="\\"===r||"."===r?r:"\\"+r,n=!1):"."==r?(t.push(i),i=""):"\\"==r?n=!0:i+=r;return n&&(i+="\\"),t.push(i),t}valueForDottedKey(e,t){let i,r=this.parsedKeys.get(e);void 0===r&&(r=l.partsForDottedKey(e),this.parsedKeys.set(e,r));const o=r[0];let s=0;for("content"===o?(i=t.getContent(),++s):"type"===o?(i=t.getType(),++s):i=t.event;s<r.length;++s){if((0,n.isNullOrUndefined)(i))return;i=i[r[s]]}return i}matchingRuleForEventWithRulesets(e,t){return t?e.getSender()===this.client.credentials.userId?null:this.matchingRuleFromKindSet(e,t.global):null}pushActionsForEventAndRulesets(e,t){const i=this.matchingRuleForEventWithRulesets(e,t);if(!i)return{};const n=l.actionListToActionsObject(i.actions);return void 0===n.tweaks.highlight&&(n.tweaks.highlight=i.kind==o.PushRuleKind.ContentSpecific),n}ruleMatchesEvent(e,t){var i;return(!this.client.supportsIntentionalMentions()||void 0===t.getContent()["org.matrix.msc3952.mentions"]||e.rule_id!==o.RuleId.ContainsUserName&&e.rule_id!==o.RuleId.ContainsDisplayName&&e.rule_id!==o.RuleId.AtRoomNotification)&&!(null===(i=e.conditions)||void 0===i?void 0:i.some((e=>!this.eventFulfillsCondition(e,t))))}actionsForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var t;const i=this.getPushRuleAndKindById(e);return null!==(t=null==i?void 0:i.rule)&&void 0!==t?t:null}getPushRuleAndKindById(e){var t;for(const i of["global"])if(void 0!==(null===(t=this.client.pushRules)||void 0===t?void 0:t[i]))for(const t of a)if(void 0!==this.client.pushRules[i][t])for(const n of this.client.pushRules[i][t])if(n.rule_id===e)return{rule:n,kind:t};return null}}i.PushProcessor=l,l.cachedGlobToRegex={}},{"./@types/PushRules":304,"./@types/event":306,"./logger":374,"./utils":416}],398:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.randomUppercaseString=i.randomLowercaseString=i.randomString=void 0;const n="abcdefghijklmnopqrstuvwxyz",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="0123456789";function s(e,t){let i="";for(let n=0;n<e;++n)i+=t.charAt(Math.floor(Math.random()*t.length));return i}i.randomString=function(e){return s(e,r+n+o)},i.randomLowercaseString=function(e){return s(e,n)},i.randomUppercaseString=function(e){return s(e,r)}},{}],399:[function(e,t,i){(function(t){(function(){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.clearTimeout=i.setTimeout=void 0;const n=e("./logger"),r=1e3;let o,s=0;const a=[],c=function(...e){};function d(){o&&t.clearTimeout(o);const e=a[0];if(!e)return void c("scheduleRealCallback: no more callbacks, not rescheduling");const i=Date.now(),n=Math.min(e.runAt-i,r);c("scheduleRealCallback: now:",i,"delay:",n),o=t.setTimeout(l,n)}function l(){const e=Date.now();c("runCallbacks: now:",e);const i=[];for(;;){const t=a[0];if(!t||t.runAt>e)break;const n=a.shift();c("runCallbacks: popping",n.key),i.push(n)}d();for(const e of i)try{e.func.apply(t,e.params)}catch(e){n.logger.error("Uncaught exception in callback function",e)}}i.setTimeout=function(e,t,...i){(t=t||0)<0&&(t=0);const n=Date.now()+t,r=s++;c("setTimeout: scheduling cb",r,"at",n,"(delay",t,")");const o={runAt:n,func:e,params:i,key:r},l=function(e,t){let i=0,n=e.length;for(;i<n;){const r=i+n>>1;t(e[r])>0?n=r:i=r+1}return i}(a,(function(e){return e.runAt-n}));return a.splice(l,0,o),d(),r},i.clearTimeout=function(e){if(0===a.length)return;let t;for(t=0;t<a.length;t++){if(a[t].key==e){a.splice(t,1);break}}0===t&&d()}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./logger":374}],400:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.initRustCrypto=void 0,i.initRustCrypto=function(e,t,i){return n(this,void 0,void 0,(function*(){throw new Error("Rust crypto is not supported under browserify.")}))}},{}],401:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RUST_SDK_STORE_PREFIX=void 0,i.RUST_SDK_STORE_PREFIX="matrix-js-sdk"},{}],402:[function(e,t,i){t.exports=e("/home/runner/work/matrix-js-sdk/matrix-js-sdk/src/rust-crypto/browserify-index.ts")},{"/home/runner/work/matrix-js-sdk/matrix-js-sdk/src/rust-crypto/browserify-index.ts":400}],403:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.MatrixScheduler=void 0;const s=o(e("./utils")),a=e("./logger"),c=e("./@types/event"),d=e("./http-api"),l=!1;class u{static RETRY_BACKOFF_RATELIMIT(e,t,i){if(400===i.httpStatus||403===i.httpStatus||401===i.httpStatus)return-1;if(i instanceof d.ConnectionError)return-1;if("M_TOO_LARGE"===i.name)return-1;if("M_LIMIT_EXCEEDED"===i.name){const e=i.data.retry_after_ms;if(e>0)return e}return t>4?-1:1e3*Math.pow(2,t)}static QUEUE_MESSAGES(e){return e.getType()===c.EventType.RoomMessage||e.hasAssociation()?"message":null}constructor(e=u.RETRY_BACKOFF_RATELIMIT,t=u.QUEUE_MESSAGES){this.retryAlgorithm=e,this.queueAlgorithm=t,this.queues={},this.activeQueues=[],this.procFn=null,this.processQueue=e=>{const t=this.peekNextEvent(e);t?(h("Queue '%s' has %s pending events",e,this.queues[e].length),Promise.resolve().then((()=>this.procFn(t.event))).then((i=>{this.removeNextEvent(e),h("Queue '%s' sent event %s",e,t.event.getId()),t.defer.resolve(i),this.processQueue(e)}),(i=>{t.attempts+=1;const n=this.retryAlgorithm(t.event,t.attempts,i);h("retry(%s) err=%s event_id=%s waitTime=%s",t.attempts,i,t.event.getId(),n),-1===n?(h("Queue '%s' giving up on event %s",e,t.event.getId()),this.clearQueue(e,i)):setTimeout(this.processQueue,n,e)}))):this.disableQueue(e)}}getQueueForEvent(e){const t=this.queueAlgorithm(e);return t&&this.queues[t]?this.queues[t].map((function(e){return e.event})):null}removeEventFromQueue(e){const t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;let i=!1;return s.removeElement(this.queues[t],(t=>t.event.getId()===e.getId()&&(i=!0,!0))),i}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){const t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);const i=s.defer();return this.queues[t].push({event:e,defer:i,attempts:0}),h("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),this.startProcessingQueues(),i.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter((e=>-1===this.activeQueues.indexOf(e)&&this.queues[e].length>0)).forEach((e=>{this.activeQueues.push(e),h("Spinning up queue: '%s'",e),this.processQueue(e)}))}disableQueue(e){const t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),h("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){let i;for(h("clearing queue '%s'",e);i=this.removeNextEvent(e);)i.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t.shift()}}function h(...e){l&&a.logger.log(...e)}i.MatrixScheduler=u},{"./@types/event":306,"./http-api":367,"./logger":374,"./utils":416}],404:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0})},{}],405:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SERVICE_TYPES=void 0,function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"}(i.SERVICE_TYPES||(i.SERVICE_TYPES={}))},{}],406:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SlidingSyncSdk=void 0;const a=e("./models/room"),c=e("./logger"),d=o(e("./utils")),l=e("./models/event-timeline"),u=e("./client"),h=e("./sync"),f=e("./http-api"),p=e("./sliding-sync"),g=e("./@types/event"),v=e("./models/room-state"),m=e("./models/room-member");class y{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return p.ExtensionState.PreProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){return s(this,void 0,void 0,(function*(){if(e.device_lists&&(yield this.crypto.handleDeviceListChanges({oldSyncToken:"yep"},e.device_lists)),e.device_one_time_keys_count){const t=e.device_one_time_keys_count.signed_curve25519||0;this.crypto.updateOneTimeKeyCount(t)}if(e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]){const t=e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"];this.crypto.setNeedsNewFallback(Array.isArray(t)&&!t.includes("signed_curve25519"))}this.crypto.onSyncCompleted({})}))}}class b{constructor(e,t){this.client=e,this.cryptoCallbacks=t,this.nextBatch=null}name(){return"to_device"}when(){return p.ExtensionState.PreProcess}onRequest(e){const t={since:null!==this.nextBatch?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}onResponse(e){return s(this,void 0,void 0,(function*(){const t=[];let i=e.events||[];i.length>0&&this.cryptoCallbacks&&(i=yield this.cryptoCallbacks.preprocessToDeviceMessages(i)),i.map(this.client.getEventMapper()).map((e=>{if("m.key.verification.cancel"===e.getType()){const i=e.getContent().transaction_id;i&&t.push(i)}return e})).forEach((e=>{const i=e.getContent();if("m.room.message"!=e.getType()||"m.bad.encrypted"!=i.msgtype){if("m.key.verification.start"===e.getType()||"m.key.verification.request"===e.getType()){const n=i.transaction_id;t.includes(n)&&e.flagCancelled()}this.client.emit(u.ClientEvent.ToDeviceEvent,e)}else c.logger.log("Ignoring undecryptable to-device event from "+e.getSender())})),this.nextBatch=e.next_batch}))}}class S{constructor(e){this.client=e}name(){return"account_data"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){e.global&&e.global.length>0&&this.processGlobalAccountData(e.global);for(const t in e.rooms){const i=w(this.client,t,e.rooms[t]),n=this.client.getRoom(t);n?(n.addAccountData(i),i.forEach((e=>{this.client.emit(u.ClientEvent.Event,e)}))):c.logger.warn("got account data for room but room doesn't exist on client:",t)}}processGlobalAccountData(e){const t=w(this.client,void 0,e),i=t.reduce(((e,t)=>(e[t.getType()]=this.client.store.getAccountData(t.getType()),e)),{});this.client.store.storeAccountDataEvents(t),t.forEach((e=>{if(e.getType()===g.EventType.PushRules){const t=e.getContent();this.client.setPushRules(t)}const t=i[e.getType()];return this.client.emit(u.ClientEvent.AccountData,e,t),e}))}}class _{constructor(e){this.client=e}name(){return"typing"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){if(null==e?void 0:e.rooms)for(const t in e.rooms)T(this.client,t,[e.rooms[t]])}}class E{constructor(e){this.client=e}name(){return"receipts"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){if(null==e?void 0:e.rooms)for(const t in e.rooms)T(this.client,t,[e.rooms[t]])}}function w(e,t,i,n=!0){const r=e.getEventMapper({decrypt:n});return i.map((function(e){return e.room_id=t,r(e)}))}function T(e,t,i){const n=w(e,t,i),r=e.getRoom(t);r?(r.addEphemeralEvents(n),n.forEach((t=>{e.emit(u.ClientEvent.Event,t)}))):c.logger.warn("got ephemeral events for room but room doesn't exist on client:",t)}i.SlidingSyncSdk=class{constructor(e,t,i,n){this.slidingSync=e,this.client=t,this.syncState=null,this.lastPos=null,this.failCount=0,this.notifEvents=[],this.opts=(0,h.defaultClientOpts)(i),this.syncOpts=(0,h.defaultSyncApiOpts)(n),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[a.RoomEvent.Timeline,a.RoomEvent.TimelineReset]),this.slidingSync.on(p.SlidingSyncEvent.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(p.SlidingSyncEvent.RoomData,this.onRoomData.bind(this));const r=[new b(this.client,this.syncOpts.cryptoCallbacks),new S(this.client),new _(this.client),new E(this.client)];this.syncOpts.crypto&&r.push(new y(this.syncOpts.crypto)),r.forEach((e=>{this.slidingSync.registerExtension(e)}))}onRoomData(e,t){let i=this.client.store.getRoom(e);if(!i){if(!t.initial)return void c.logger.debug("initial flag not set but no stored room exists for room ",e,t);i=(0,h._createAndReEmitRoom)(this.client,e,this.opts)}this.processRoomData(this.client,i,t)}onLifecycle(e,t,i){switch(i&&c.logger.debug("onLifecycle",e,i),e){case p.SlidingSyncState.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(h.SyncState.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(h.SyncState.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case p.SlidingSyncState.RequestFinished:if(i){if(this.failCount+=1,this.updateSyncState(this.failCount>3?h.SyncState.Error:h.SyncState.Reconnecting,{error:new f.MatrixError(i)}),this.shouldAbortSync(new f.MatrixError(i)))return}else this.failCount=0}}syncLeftRooms(){return s(this,void 0,void 0,(function*(){return[]}))}peek(e){return s(this,void 0,void 0,(function*(){return null}))}stopPeeking(){}getSyncState(){return this.syncState}getSyncStateData(){var e;return null!==(e=this.syncStateData)&&void 0!==e?e:null}createRoom(e){const{timelineSupport:t}=this.client,i=new a.Room(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(i,[a.RoomEvent.Name,a.RoomEvent.Redaction,a.RoomEvent.RedactionCancelled,a.RoomEvent.Receipt,a.RoomEvent.Tags,a.RoomEvent.LocalEchoUpdated,a.RoomEvent.AccountData,a.RoomEvent.MyMembership,a.RoomEvent.Timeline,a.RoomEvent.TimelineReset]),this.registerStateListeners(i),i}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[v.RoomStateEvent.Events,v.RoomStateEvent.Members,v.RoomStateEvent.NewMember,v.RoomStateEvent.Update]),e.currentState.on(v.RoomStateEvent.NewMember,((e,t,i)=>{var n;i.user=null!==(n=this.client.getUser(i.userId))&&void 0!==n?n:void 0,this.client.reEmitter.reEmit(i,[m.RoomMemberEvent.Name,m.RoomMemberEvent.Typing,m.RoomMemberEvent.PowerLevel,m.RoomMemberEvent.Membership])}))}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(c.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(h.SyncState.Error,{error:e}),!0)}processRoomData(e,t,i){var n;return s(this,void 0,void 0,(function*(){i=function(e,t,i){if(!i.name)return i;for(const e of i.required_state)if(e.type===g.EventType.RoomName&&""===e.state_key)return e.content={name:i.name},i;return i.required_state.push({event_id:"$fake-sliding-sync-name-event-"+t,state_key:"",type:g.EventType.RoomName,content:{name:i.name},sender:e.getUserId(),origin_server_ts:(new Date).getTime()}),i}(e,t.roomId,i);const r=w(this.client,t.roomId,i.required_state);let o=w(this.client,t.roomId,i.timeline,!1);const c=[];if(i.initial){const e=new Set;t.getLiveTimeline().getEvents().forEach((t=>{e.add(t.getId())}));const n=[],r=[];let s=!1;for(let t=o.length-1;t>=0;t--){const i=o[t];e.has(i.getId())?s=!0:s?n.push(i):r.unshift(i)}o=r,n.length>0&&t.addEventsToTimeline(n,!0,t.getLiveTimeline(),i.prev_batch)}const h=this.client.isRoomEncrypted(t.roomId);if(null!=i.notification_count&&t.setUnreadNotificationCount(a.NotificationCountType.Total,i.notification_count),null!=i.highlight_count&&(!h||h&&t.getUnreadNotificationCount(a.NotificationCountType.Highlight)<=0)&&t.setUnreadNotificationCount(a.NotificationCountType.Highlight,i.highlight_count),Number.isInteger(i.invited_count)&&t.currentState.setInvitedMemberCount(i.invited_count),Number.isInteger(i.joined_count)&&t.currentState.setJoinedMemberCount(i.joined_count),i.invite_state){const e=w(this.client,t.roomId,i.invite_state);return this.injectRoomEvents(t,e),i.initial&&(t.recalculate(),this.client.store.storeRoom(t),this.client.emit(u.ClientEvent.Room,t)),e.forEach((e=>{this.client.emit(u.ClientEvent.Event,e)})),void t.updateMyMembership("invite")}i.initial&&t.getLiveTimeline().setPaginationToken(null!==(n=i.prev_batch)&&void 0!==n?n:null,l.EventTimeline.BACKWARDS),this.injectRoomEvents(t,r,o,i.num_live),t.addEphemeralEvents(c),t.updateMyMembership("join"),t.recalculate(),i.initial&&(e.store.storeRoom(t),e.emit(u.ClientEvent.Room,t)),this.addNotifications(o);const f=i=>s(this,void 0,void 0,(function*(){e.emit(u.ClientEvent.Event,i),i.isState()&&i.getType()==g.EventType.RoomEncryption&&this.syncOpts.cryptoCallbacks&&(yield this.syncOpts.cryptoCallbacks.onCryptoEvent(t,i))}));yield d.promiseMapSeries(r,f),yield d.promiseMapSeries(o,f),c.forEach((function(t){e.emit(u.ClientEvent.Event,t)})),t.decryptCriticalEvents()}))}injectRoomEvents(e,t,i,n){i=i||[],t=t||[],n=n||0;const r=e.getLiveTimeline(),o=0==r.getEvents().length;if(o){for(const e of t)this.client.getPushActionsForEvent(e);r.initialiseState(t)}o||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));let s=[];n>0&&(s=i.slice(-1*n),i=i.slice(0,-1*s.length)),e.addLiveEvents(i,{fromCache:!0}),s.length>0&&e.addLiveEvents(s,{fromCache:!1}),e.recalculate(),this.resolveInvites(e)}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(i){if(i.requestedProfileInfo)return;i.requestedProfileInfo=!0;const n=t.getUser(i.userId);let r;r=n?Promise.resolve({avatar_url:n.avatarUrl,displayname:n.displayName}):t.getProfileInfo(i.userId),r.then((function(t){const n=i.events.member;"invite"===n.getContent().membership&&(n.getContent().avatar_url=t.avatar_url,n.getContent().displayname=t.displayname,i.setMembershipEvent(n,e.currentState))}),(function(e){}))}))}retryImmediately(){return!0}sync(){return s(this,void 0,void 0,(function*(){for(c.logger.debug("Sliding sync init loop");!this.client.isGuest();)try{c.logger.debug("Getting push rules...");const e=yield this.client.getPushRules();c.logger.debug("Got push rules"),this.client.pushRules=e;break}catch(e){if(c.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return}yield this.slidingSync.start()}))}stop(){c.logger.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){const i=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(u.ClientEvent.Sync,this.syncState,i,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(const t of e){const e=this.client.getPushActionsForEvent(t);e&&e.notify&&e.tweaks&&e.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((e=>{var t;null===(t=this.client.getNotifTimelineSet())||void 0===t||t.addLiveEvent(e)})),this.notifEvents=[]}}},{"./@types/event":306,"./client":321,"./http-api":367,"./logger":374,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./sliding-sync":407,"./sync":414,"./utils":416}],407:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SlidingSync=i.SlidingSyncEvent=i.ExtensionState=i.SlidingSyncState=i.MSC3575_STATE_KEY_LAZY=i.MSC3575_STATE_KEY_ME=i.MSC3575_WILDCARD=void 0;const r=e("./logger"),o=e("./models/typed-event-emitter"),s=e("./utils");var a,c,d;i.MSC3575_WILDCARD="*",i.MSC3575_STATE_KEY_ME="$ME",i.MSC3575_STATE_KEY_LAZY="$LAZY",function(e){e.RequestFinished="FINISHED",e.Complete="COMPLETE"}(a=i.SlidingSyncState||(i.SlidingSyncState={}));class l{constructor(e){this.roomIndexToRoomId={},this.joinedCount=0,this.replaceList(e)}setModified(e){this.isModified=e}updateListRange(e){this.list.ranges=JSON.parse(JSON.stringify(e))}replaceList(e){e.filters=e.filters||{},e.ranges=e.ranges||[],this.list=JSON.parse(JSON.stringify(e)),this.isModified=!0,this.roomIndexToRoomId={},this.joinedCount=0}getList(e){let t={ranges:JSON.parse(JSON.stringify(this.list.ranges))};return(this.isModified||e)&&(t=JSON.parse(JSON.stringify(this.list))),t}isIndexInRange(e){for(const t of this.list.ranges)if(t[0]<=e&&e<=t[1])return!0;return!1}}!function(e){e.PreProcess="ExtState.PreProcess",e.PostProcess="ExtState.PostProcess"}(c=i.ExtensionState||(i.ExtensionState={})),function(e){e.RoomData="SlidingSync.RoomData",e.Lifecycle="SlidingSync.Lifecycle",e.List="SlidingSync.List"}(d=i.SlidingSyncEvent||(i.SlidingSyncEvent={}));class u extends o.TypedEventEmitter{constructor(e,t,i,n,r){super(),this.proxyBaseUrl=e,this.roomSubscriptionInfo=i,this.client=n,this.timeoutMS=r,this.listModifiedCount=0,this.terminated=!1,this.needsResend=!1,this.txnId=null,this.txnIdDefers=[],this.extensions={},this.desiredRoomSubscriptions=new Set,this.confirmedRoomSubscriptions=new Set,this.customSubscriptions=new Map,this.roomIdToCustomSubscription=new Map,this.lists=new Map,t.forEach(((e,t)=>{this.lists.set(t,new l(e))}))}addCustomSubscription(e,t){this.customSubscriptions.has(e)?r.logger.warn(`addCustomSubscription: ${e} already exists as a custom subscription, ignoring.`):this.customSubscriptions.set(e,t)}useCustomSubscription(e,t){this.roomIdToCustomSubscription.get(e)!==t&&(this.roomIdToCustomSubscription.set(e,t),this.confirmedRoomSubscriptions.delete(e))}getListData(e){const t=this.lists.get(e);return t?{joinedCount:t.joinedCount,roomIndexToRoomId:Object.assign({},t.roomIndexToRoomId)}:null}getListParams(e){const t=this.lists.get(e);return t?t.getList(!0):null}setListRanges(e,t){const i=this.lists.get(e);return i?(i.updateListRange(t),this.resend()):Promise.reject(new Error("no list with key "+e))}setList(e,t){const i=this.lists.get(e);return i?(i.replaceList(t),this.lists.set(e,i)):this.lists.set(e,new l(t)),this.listModifiedCount+=1,this.resend()}getRoomSubscriptions(){return new Set(Array.from(this.desiredRoomSubscriptions))}modifyRoomSubscriptions(e){return this.desiredRoomSubscriptions=e,this.resend()}modifyRoomSubscriptionInfo(e){return this.roomSubscriptionInfo=e,this.confirmedRoomSubscriptions=new Set,this.resend()}registerExtension(e){if(this.extensions[e.name()])throw new Error(`registerExtension: ${e.name()} already exists as an extension`);this.extensions[e.name()]=e}getExtensionRequest(e){const t={};return Object.keys(this.extensions).forEach((i=>{t[i]=this.extensions[i].onRequest(e)})),t}onPreExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==c.PreProcess&&this.extensions[t].onResponse(e[t])}))}onPostExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==c.PostProcess&&this.extensions[t].onResponse(e[t])}))}invokeRoomDataListeners(e,t){t.required_state||(t.required_state=[]),t.timeline||(t.timeline=[]),this.emit(d.RoomData,e,t)}invokeLifecycleListeners(e,t,i){this.emit(d.Lifecycle,e,t,i)}shiftRight(e,t,i){const n=this.lists.get(e);if(n)for(let e=t;e>i;e--)n.isIndexInRange(e)&&(n.roomIndexToRoomId[e]=n.roomIndexToRoomId[e-1])}shiftLeft(e,t,i){const n=this.lists.get(e);if(n)for(let e=i;e<t;e++)n.isIndexInRange(e)&&(n.roomIndexToRoomId[e]=n.roomIndexToRoomId[e+1])}removeEntry(e,t){const i=this.lists.get(e);if(!i)return;let n=-1;for(const e in i.roomIndexToRoomId)Number(e)>n&&(n=Number(e));n<0||t>n||(this.shiftLeft(e,n,t),delete i.roomIndexToRoomId[n])}addEntry(e,t){const i=this.lists.get(e);if(!i)return;let n=-1;for(const e in i.roomIndexToRoomId)Number(e)>n&&(n=Number(e));n<0||t>n||this.shiftRight(e,n+1,t)}processListOps(e,t){let i=-1;const n=this.lists.get(t);n&&(e.ops.forEach((e=>{if(n)switch(e.op){case"DELETE":r.logger.debug("DELETE",t,e.index,";"),delete n.roomIndexToRoomId[e.index],-1!==i&&this.removeEntry(t,i),i=e.index;break;case"INSERT":r.logger.debug("INSERT",t,e.index,e.room_id,";"),n.roomIndexToRoomId[e.index]&&(i<0?this.addEntry(t,e.index):i>e.index?this.shiftRight(t,i,e.index):i<e.index&&this.shiftLeft(t,e.index,i)),i=-1,n.roomIndexToRoomId[e.index]=e.room_id;break;case"INVALIDATE":for(let t=e.range[0];t<=e.range[1];t++)delete n.roomIndexToRoomId[t];r.logger.debug("INVALIDATE",t,e.range[0],e.range[1],";");break;case"SYNC":{const i=e.range[0];for(let t=i;t<=e.range[1];t++){const r=e.room_ids[t-i];if(!r)break;n.roomIndexToRoomId[t]=r}r.logger.debug("SYNC",t,e.range[0],e.range[1],(e.room_ids||[]).join(" "),";");break}}})),-1!==i&&this.removeEntry(t,i))}resend(){var e;if(this.needsResend&&this.txnIdDefers.length>0)return this.txnIdDefers[this.txnIdDefers.length-1].promise;this.needsResend=!0,this.txnId=this.client.makeTxnId();const t=(0,s.defer)();return this.txnIdDefers.push(Object.assign(Object.assign({},t),{txnId:this.txnId})),null===(e=this.abortController)||void 0===e||e.abort(),this.abortController=new AbortController,t.promise}resolveTransactionDefers(e){if(!e)return;let t=-1;for(let i=0;i<this.txnIdDefers.length;i++)if(this.txnIdDefers[i].txnId===e){t=i;break}if(-1!==t){for(let e=0;e<t;e++)this.txnIdDefers[e].reject(this.txnIdDefers[e].txnId);this.txnIdDefers[t].resolve(e),this.txnIdDefers=this.txnIdDefers.slice(t+1)}else r.logger.warn(`resolveTransactionDefers: seen ${e} but it isn't a pending txn, ignoring.`)}stop(){var e;this.terminated=!0,null===(e=this.abortController)||void 0===e||e.abort(),this.removeAllListeners(d.Lifecycle),this.removeAllListeners(d.List),this.removeAllListeners(d.RoomData)}resetup(){var e;r.logger.warn("SlidingSync: resetting connection info"),this.txnIdDefers.forEach((e=>{e.reject(e.txnId)})),this.txnIdDefers=[],this.lists.forEach((e=>{e.setModified(!0)})),this.confirmedRoomSubscriptions=new Set,this.needsResend=!0,null===(e=this.abortController)||void 0===e||e.abort(),this.abortController=new AbortController}start(){return n(this,void 0,void 0,(function*(){let e;for(this.abortController=new AbortController;!this.terminated;){this.needsResend=!1;let t,i=!1;try{const n=this.listModifiedCount,o={};this.lists.forEach(((e,t)=>{o[t]=e.getList(!1)}));const s={lists:o,pos:e,timeout:this.timeoutMS,clientTimeout:this.timeoutMS+1e4,extensions:this.getExtensionRequest(void 0===e)},c=h(this.desiredRoomSubscriptions,this.confirmedRoomSubscriptions),d=h(this.confirmedRoomSubscriptions,this.desiredRoomSubscriptions);if(d.size>0&&(s.unsubscribe_rooms=Array.from(d)),c.size>0){s.room_subscriptions={};for(const e of c){const t=this.roomIdToCustomSubscription.get(e);let i=this.roomSubscriptionInfo;t&&this.customSubscriptions.has(t)&&(i=this.customSubscriptions.get(t)),s.room_subscriptions[e]=i}}this.txnId&&(s.txn_id=this.txnId,this.txnId=null),this.pendingReq=this.client.slidingSync(s,this.proxyBaseUrl,this.abortController.signal),t=yield this.pendingReq,e=t.pos;for(const e of c)this.confirmedRoomSubscriptions.add(e);for(const e of d)this.confirmedRoomSubscriptions.delete(e);n!==this.listModifiedCount&&(r.logger.debug("list modified during await call, not updating list"),i=!0),this.lists.forEach((e=>{e.setModified(!1)})),t.lists=t.lists||{},t.rooms=t.rooms||{},t.extensions=t.extensions||{},Object.keys(t.lists).forEach((e=>{const i=this.lists.get(e);i&&t&&(i.joinedCount=t.lists[e].count)})),this.invokeLifecycleListeners(a.RequestFinished,t)}catch(t){if(t.httpStatus){if(this.invokeLifecycleListeners(a.RequestFinished,null,t),400===t.httpStatus){this.resetup(),e=void 0,yield(0,s.sleep)(50);continue}}else if(this.needsResend||"AbortError"===t.name)continue;r.logger.error(t),yield(0,s.sleep)(5e3)}if(!t)continue;this.onPreExtensionsResponse(t.extensions),Object.keys(t.rooms).forEach((e=>{this.invokeRoomDataListeners(e,t.rooms[e])}));const n=new Set;if(!i)for(const[e,i]of Object.entries(t.lists))i.ops=i.ops||[],i.ops.length>0&&n.add(e),this.processListOps(i,e);this.invokeLifecycleListeners(a.Complete,t),this.onPostExtensionsResponse(t.extensions),n.forEach((e=>{const t=this.lists.get(e);t&&this.emit(d.List,e,t.joinedCount,Object.assign({},t.roomIndexToRoomId))})),this.resolveTransactionDefers(t.txn_id)}}))}}i.SlidingSync=u;const h=(e,t)=>{const i=new Set(e);for(const e of t)i.delete(e);return i}},{"./logger":374,"./models/typed-event-emitter":395,"./utils":416}],408:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.LocalIndexedDBStoreBackend=void 0;const a=e("../sync-accumulator"),c=o(e("../utils")),d=o(e("../indexeddb-helpers")),l=e("../logger"),u=[e=>{e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})},e=>{e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")},e=>{e.createObjectStore("client_options",{keyPath:["clobber"]})},e=>{e.createObjectStore("to_device_queue",{autoIncrement:!0})}],h=u.length;function f(e,t,i){const n=e.openCursor(t);return new Promise(((e,t)=>{const r=[];n.onerror=()=>{t(new Error("Query failed: "+n.error))},n.onsuccess=()=>{const t=n.result;t?(r.push(i(t)),t.continue()):e(r)}}))}function p(e){return new Promise(((t,i)=>{e.oncomplete=function(e){t(e)},e.onerror=function(){i(e.error)}}))}function g(e){return new Promise(((t,i)=>{e.onsuccess=function(e){t(e)},e.onerror=function(){i(e.error)}}))}function v(e){return g(e).then((t=>e.result))}i.LocalIndexedDBStoreBackend=class{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),d.exists(e,t)}constructor(e,t="default"){this.indexedDB=e,this.disconnected=!0,this._isNewlyCreated=!1,this.pendingUserPresenceData=[],this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new a.SyncAccumulator}connect(e){if(!this.disconnected)return l.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,l.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const t=this.indexedDB.open(this.dbName,h);return t.onupgradeneeded=e=>{const i=t.result,n=e.oldVersion;l.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${n}`),n<1&&(this._isNewlyCreated=!0),u.forEach(((e,t)=>{n<=t&&e(i)}))},t.onblocked=()=>{l.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},l.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),g(t).then((()=>s(this,void 0,void 0,(function*(){l.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=t.result,this.db.onversionchange=()=>{var t;null===(t=this.db)||void 0===t||t.close(),this.disconnected=!0,this.db=void 0,null==e||e()},this.db.onclose=()=>{this.disconnected=!0,this.db=void 0,null==e||e()},yield this.init()}))))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then((([e,t])=>{l.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,account_data:{events:e}},!0)}))}getOutOfBandMembers(e){return new Promise(((t,i)=>{const n=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),r=IDBKeyRange.only(e),o=n.openCursor(r),s=[];let a=!1;o.onsuccess=()=>{const e=o.result;if(!e)return s.length||a?t(s):t(null);const i=e.value;i.oob_written?a=!0:s.push(i),e.continue()},o.onerror=e=>{i(e)}})).then((t=>(l.logger.log(`LL: got ${null==t?void 0:t.length} membershipEvents from storage for room ${e} ...`),t)))}setOutOfBandMembers(e,t){return s(this,void 0,void 0,(function*(){l.logger.log(`LL: backend about to store ${t.length} members for ${e}`);const i=this.db.transaction(["oob_membership_events"],"readwrite"),n=i.objectStore("oob_membership_events");t.forEach((e=>{n.put(e)}));const r={room_id:e,oob_written:!0,state_key:0};n.put(r),yield p(i),l.logger.log(`LL: backend done storing for ${e}!`)}))}clearOutOfBandMembers(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),i=IDBKeyRange.only(e),n=v(t.openKeyCursor(i,"next")).then((e=>(null==e?void 0:e.primaryKey)[1])),r=v(t.openKeyCursor(i,"prev")).then((e=>(null==e?void 0:e.primaryKey)[1])),[o,s]=yield Promise.all([n,r]),a=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),c=IDBKeyRange.bound([e,o],[e,s]);var d;l.logger.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,o],[e,s]),yield(d=a.delete(c),new Promise(((e,t)=>{d.onsuccess=()=>e(d),d.onerror=e=>t(e)})))}))}clearDatabase(){return new Promise((e=>{l.logger.log(`Removing indexeddb instance: ${this.dbName}`);const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{l.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{l.logger.warn(`unable to delete js-sdk store indexeddb: ${t.error}`),e()},t.onsuccess=()=>{l.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}}))}getSavedSync(e=!0){const t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(c.deepCopy(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then((()=>{this.syncAccumulator.accumulate(e)}))}syncToDatabase(e){return s(this,void 0,void 0,(function*(){return this.syncToDatabasePromise?(l.logger.warn("Skipping syncToDatabase() as persist already in flight"),this.pendingUserPresenceData.push(...e),this.syncToDatabasePromise):(e.unshift(...this.pendingUserPresenceData),this.syncToDatabasePromise=this.doSyncToDatabase(e),this.syncToDatabasePromise)}))}doSyncToDatabase(e){return s(this,void 0,void 0,(function*(){try{const t=this.syncAccumulator.getJSON(!0);yield Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData)])}finally{this.syncToDatabasePromise=void 0}}))}persistSyncData(e,t){return l.logger.log("Persisting sync data up to",e),c.promiseTry((()=>{const i=this.db.transaction(["sync"],"readwrite");return i.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t}),p(i).then((()=>{l.logger.log("Persisted sync data up to",e)}))}))}persistAccountData(e){return c.promiseTry((()=>{const t=this.db.transaction(["accountData"],"readwrite"),i=t.objectStore("accountData");for(const t of e)i.put(t);return p(t).then()}))}persistUserPresenceEvents(e){return c.promiseTry((()=>{const t=this.db.transaction(["users"],"readwrite"),i=t.objectStore("users");for(const t of e)i.put({userId:t[0],event:t[1]});return p(t).then()}))}getUserPresenceEvents(){return c.promiseTry((()=>f(this.db.transaction(["users"],"readonly").objectStore("users"),void 0,(e=>[e.value.userId,e.value.event]))))}loadAccountData(){return l.logger.log("LocalIndexedDBStoreBackend: loading account data..."),c.promiseTry((()=>f(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))))}loadSyncData(){return l.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),c.promiseTry((()=>f(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&l.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))))}getClientOptions(){return Promise.resolve().then((()=>f(this.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,(e=>{var t;return null===(t=e.value)||void 0===t?void 0:t.options})).then((e=>e[0]))))}storeClientOptions(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["client_options"],"readwrite");t.objectStore("client_options").put({clobber:"-",options:e}),yield p(t)}))}saveToDeviceBatches(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["to_device_queue"],"readwrite"),i=t.objectStore("to_device_queue");for(const t of e)i.add(t);yield p(t)}))}getOldestToDeviceBatch(){return s(this,void 0,void 0,(function*(){const e=this.db.transaction(["to_device_queue"],"readonly").objectStore("to_device_queue"),t=yield v(e.openCursor());if(!t)return null;const i=t.value;return{id:t.key,txnId:i.txnId,eventType:i.eventType,batch:i.batch}}))}removeToDeviceBatch(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["to_device_queue"],"readwrite");t.objectStore("to_device_queue").delete(e),yield p(t)}))}}},{"../indexeddb-helpers":372,"../logger":374,"../sync-accumulator":413,"../utils":416}],409:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RemoteIndexedDBStoreBackend=void 0;const r=e("../logger"),o=e("../utils");i.RemoteIndexedDBStoreBackend=class{constructor(e,t){this.workerFactory=e,this.dbName=t,this.nextSeq=0,this.inFlight={},this.onWorkerMessage=e=>{var t;const i=e.data;if("closed"==i.command)null===(t=this.onClose)||void 0===t||t.call(this);else if("cmd_success"==i.command||"cmd_fail"==i.command){if(void 0===i.seq)return void r.logger.error("Got reply from worker with no seq");const e=this.inFlight[i.seq];if(void 0===e)return void r.logger.error("Got reply for unknown seq "+i.seq);if(delete this.inFlight[i.seq],"cmd_success"==i.command)e.resolve(i.result);else{const t=new Error(i.error.message);t.name=i.error.name,e.reject(t)}}else r.logger.warn("Unrecognised message from worker: ",i)}}connect(e){return this.onClose=e,this.ensureStarted().then((()=>this.doCmd("connect")))}clearDatabase(){return this.ensureStarted().then((()=>this.doCmd("clearDatabase")))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}saveToDeviceBatches(e){return n(this,void 0,void 0,(function*(){return this.doCmd("saveToDeviceBatches",[e])}))}getOldestToDeviceBatch(){return n(this,void 0,void 0,(function*(){return this.doCmd("getOldestToDeviceBatch")}))}removeToDeviceBatch(e){return n(this,void 0,void 0,(function*(){return this.doCmd("removeToDeviceBatch",[e])}))}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then((()=>{r.logger.log("IndexedDB worker is ready")}))),this.startPromise}doCmd(e,t){return Promise.resolve().then((()=>{var i;const n=this.nextSeq++,r=(0,o.defer)();return this.inFlight[n]=r,null===(i=this.worker)||void 0===i||i.postMessage({command:e,seq:n,args:t}),r.promise}))}}},{"../logger":374,"../utils":416}],410:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IndexedDBStore=void 0;const r=e("./memory"),o=e("./indexeddb-local-backend"),s=e("./indexeddb-remote-backend"),a=e("../models/user"),c=e("../models/event"),d=e("../logger"),l=e("../models/typed-event-emitter");class u extends r.MemoryStore{static exists(e,t){return o.LocalIndexedDBStoreBackend.exists(e,t)}constructor(e){if(super(e),this.startedUp=!1,this.syncTs=0,this.userModifiedMap={},this.emitter=new l.TypedEventEmitter,this.on=this.emitter.on.bind(this.emitter),this.onClose=()=>{this.emitter.emit("closed")},this.getSavedSync=this.degradable((()=>this.backend.getSavedSync()),"getSavedSync"),this.isNewlyCreated=this.degradable((()=>this.backend.isNewlyCreated()),"isNewlyCreated"),this.getSavedSyncToken=this.degradable((()=>this.backend.getNextBatchToken()),"getSavedSyncToken"),this.deleteAllData=this.degradable((()=>(super.deleteAllData(),this.backend.clearDatabase().then((()=>{d.logger.log("Deleted indexeddb data.")}),(e=>{throw d.logger.error(`Failed to delete indexeddb data: ${e}`),e}))))),this.reallySave=this.degradable((()=>{this.syncTs=Date.now();const e=[];for(const t of this.getUsers())this.userModifiedMap[t.userId]!==t.getLastModifiedTime()&&t.events.presence&&(e.push([t.userId,t.events.presence.event]),this.userModifiedMap[t.userId]=t.getLastModifiedTime());return this.backend.syncToDatabase(e)})),this.setSyncData=this.degradable((e=>this.backend.setSyncData(e)),"setSyncData"),this.getOutOfBandMembers=this.degradable((e=>this.backend.getOutOfBandMembers(e)),"getOutOfBandMembers"),this.setOutOfBandMembers=this.degradable(((e,t)=>(super.setOutOfBandMembers(e,t),this.backend.setOutOfBandMembers(e,t))),"setOutOfBandMembers"),this.clearOutOfBandMembers=this.degradable((e=>(super.clearOutOfBandMembers(e),this.backend.clearOutOfBandMembers(e))),"clearOutOfBandMembers"),this.getClientOptions=this.degradable((()=>this.backend.getClientOptions()),"getClientOptions"),this.storeClientOptions=this.degradable((e=>(super.storeClientOptions(e),this.backend.storeClientOptions(e))),"storeClientOptions"),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new s.RemoteIndexedDBStoreBackend(e.workerFactory,e.dbName):this.backend=new o.LocalIndexedDBStoreBackend(e.indexedDB,e.dbName)}startup(){return this.startedUp?(d.logger.log("IndexedDBStore.startup: already started"),Promise.resolve()):(d.logger.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then((()=>(d.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents()))).then((e=>{d.logger.log("IndexedDBStore.startup: processing presence events"),e.forEach((([e,t])=>{const i=new a.User(e);t&&i.setPresenceEvent(new c.MatrixEvent(t)),this.userModifiedMap[i.userId]=i.getLastModifiedTime(),this.storeUser(i)})),this.startedUp=!0})))}wantsSave(){return Date.now()-this.syncTs>3e5}save(e=!1){return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){const i=t?super[t]:null;return(...t)=>n(this,void 0,void 0,(function*(){try{return yield e.call(this,...t)}catch(e){d.logger.error("IndexedDBStore failure, degrading to MemoryStore",e),this.emitter.emit("degraded",e);try{d.logger.log("IndexedDBStore trying to delete degraded data"),yield this.backend.clearDatabase(),d.logger.log("IndexedDBStore delete after degrading succeeded")}catch(e){d.logger.warn("IndexedDBStore delete after degrading failed",e)}if(i)return i.call(this,...t)}}))}getPendingEvents(e){const t=Object.create(null,{getPendingEvents:{get:()=>super.getPendingEvents}});return n(this,void 0,void 0,(function*(){if(!this.localStorage)return t.getPendingEvents.call(this,e);const i=this.localStorage.getItem(h(e));if(i)try{return JSON.parse(i)}catch(e){d.logger.error("Could not parse persisted pending events",e)}return[]}))}setPendingEvents(e,t){const i=Object.create(null,{setPendingEvents:{get:()=>super.setPendingEvents}});return n(this,void 0,void 0,(function*(){if(!this.localStorage)return i.setPendingEvents.call(this,e,t);t.length>0?this.localStorage.setItem(h(e),JSON.stringify(t)):this.localStorage.removeItem(h(e))}))}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function h(e){return`mx_pending_events_${e}`}i.IndexedDBStore=u},{"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"../models/user":396,"./indexeddb-local-backend":408,"./indexeddb-remote-backend":409,"./memory":411}],411:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MemoryStore=void 0;const r=e("../models/user"),o=e("../models/room-state"),s=e("../utils");function a(e){return"string"==typeof e&&!!e&&"undefined"!==e&&"null"!==e||"number"==typeof e}i.MemoryStore=class{constructor(e={}){this.rooms={},this.users={},this.syncToken=null,this.filters=new s.MapWithDefault((()=>new Map)),this.accountData=new Map,this.oobMembers=new Map,this.pendingEvents={},this.pendingToDeviceBatches=[],this.nextToDeviceBatchId=0,this.onRoomMember=(e,t,i)=>{if("invite"===i.membership)return;const n=this.users[i.userId]||new r.User(i.userId);i.name&&(n.setDisplayName(i.name),i.events.member&&n.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&n.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[n.userId]=n},this.localStorage=e.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(e){this.syncToken=e}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on(o.RoomStateEvent.Members,this.onRoomMember),e.currentState.getMembers().forEach((t=>{this.onRoomMember(null,e.currentState,t)}))}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(o.RoomStateEvent.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map((function(e){return e.summary}))}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,i,n){}storeFilter(e){(null==e?void 0:e.userId)&&(null==e?void 0:e.filterId)&&this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var i;return(null===(i=this.filters.get(e))||void 0===i?void 0:i.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;const t="mxjssdk_memory_filter_"+e;try{const e=this.localStorage.getItem(t);if(a(e))return e}catch(e){}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const i="mxjssdk_memory_filter_"+e;try{a(t)?this.localStorage.setItem(i,t):this.localStorage.removeItem(i)}catch(e){}}storeAccountDataEvents(e){e.forEach((e=>{!Object.keys(e.getContent()).length?this.accountData.delete(e.getType()):this.accountData.set(e.getType(),e)}))}getAccountData(e){return this.accountData.get(e)}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters=new s.MapWithDefault((()=>new Map)),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,t){return this.oobMembers.set(e,t),Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers.delete(e),Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}getPendingEvents(e){var t;return n(this,void 0,void 0,(function*(){return null!==(t=this.pendingEvents[e])&&void 0!==t?t:[]}))}setPendingEvents(e,t){return n(this,void 0,void 0,(function*(){this.pendingEvents[e]=t}))}saveToDeviceBatches(e){for(const t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}getOldestToDeviceBatch(){return n(this,void 0,void 0,(function*(){return 0===this.pendingToDeviceBatches.length?null:this.pendingToDeviceBatches[0]}))}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter((t=>t.id!==e)),Promise.resolve()}}},{"../models/room-state":390,"../models/user":396,"../utils":416}],412:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.StubStore=void 0;i.StubStore=class{constructor(){this.accountData=new Map,this.fromToken=null}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(e){this.fromToken=e}storeRoom(e){}getRoom(e){return null}getRooms(){return[]}removeRoom(e){}getRoomSummaries(){return[]}storeUser(e){}getUser(e){return null}getUsers(){return[]}scrollback(e,t){return[]}storeEvents(e,t,i,n){}storeFilter(e){}getFilter(e,t){return null}getFilterIdByName(e){return null}setFilterIdByName(e,t){}storeAccountDataEvents(e){}getAccountData(e){}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(e,t){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve(void 0)}storeClientOptions(e){return Promise.resolve()}getPendingEvents(e){return n(this,void 0,void 0,(function*(){return[]}))}setPendingEvents(e,t){return Promise.resolve()}saveToDeviceBatches(e){return n(this,void 0,void 0,(function*(){return Promise.resolve()}))}getOldestToDeviceBatch(){return Promise.resolve(null)}removeToDeviceBatch(e){return n(this,void 0,void 0,(function*(){return Promise.resolve()}))}}},{}],413:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SyncAccumulator=i.Category=void 0;const n=e("./logger"),r=e("./utils"),o=e("./@types/event"),s=e("./@types/read_receipts"),a=e("./@types/sync");var c;!function(e){e.Invite="invite",e.Leave="leave",e.Join="join"}(c=i.Category||(i.Category={}));function d(e,t){null!==t.state_key&&void 0!==t.state_key&&t.type&&(e[t.type]||(e[t.type]=Object.create(null)),e[t.type][t.state_key]=t)}i.SyncAccumulator=class{constructor(e={}){this.opts=e,this.accountData={},this.inviteRooms={},this.joinRooms={},this.nextBatch=null,this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e,t=!1){this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){e.account_data&&e.account_data.events&&e.account_data.events.forEach((e=>{this.accountData[e.type]=e}))}accumulateRooms(e,t=!1){e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach((i=>{this.accumulateRoom(i,c.Invite,e.rooms.invite[i],t)})),e.rooms.join&&Object.keys(e.rooms.join).forEach((i=>{this.accumulateRoom(i,c.Join,e.rooms.join[i],t)})),e.rooms.leave&&Object.keys(e.rooms.leave).forEach((i=>{this.accumulateRoom(i,c.Leave,e.rooms.leave[i],t)})))}accumulateRoom(e,t,i,r=!1){switch(t){case c.Invite:this.accumulateInviteState(e,i);break;case c.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,i,r);break;case c.Leave:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:n.logger.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!t.invite_state||!t.invite_state.events)return;if(!this.inviteRooms[e])return void(this.inviteRooms[e]={invite_state:t.invite_state});const i=this.inviteRooms[e];t.invite_state.events.forEach((e=>{let t=!1;for(let n=0;n<i.invite_state.events.length;n++){const r=i.invite_state.events[n];r.type===e.type&&r.state_key==e.state_key&&(i.invite_state.events[n]=e,t=!0)}t||i.invite_state.events.push(e)}))}accumulateJoinState(e,t,i=!1){var n,c,l,u,h,f,p,g;this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_readReceipts:{},_threadReadReceipts:{}});const v=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach((e=>{v._accountData[e.type]=e})),t.unread_notifications&&(v._unreadNotifications=t.unread_notifications),v._unreadThreadNotifications=null!==(c=null!==(n=t[a.UNREAD_THREAD_NOTIFICATIONS.stable])&&void 0!==n?n:t[a.UNREAD_THREAD_NOTIFICATIONS.unstable])&&void 0!==c?c:void 0,t.summary){const e="m.heroes",i="m.invited_member_count",n="m.joined_member_count",r=v._summary,o=t.summary;r[e]=o[e]||r[e],r[n]=o[n]||r[n],r[i]=o[i]||r[i]}if(null===(u=null===(l=t.ephemeral)||void 0===l?void 0:l.events)||void 0===u||u.forEach((e=>{e.type===o.EventType.Receipt&&e.content&&Object.keys(e.content).forEach((t=>{Object.entries(e.content[t]).forEach((([i,n])=>{var o;if((0,r.isSupportedReceiptType)(i))for(const r of Object.keys(n)){const n=e.content[t][i][r],a={data:e.content[t][i][r],type:i,eventId:t};n.thread_id&&n.thread_id!==s.MAIN_ROOM_TIMELINE?v._threadReadReceipts=Object.assign(Object.assign({},v._threadReadReceipts),{[n.thread_id]:Object.assign(Object.assign({},null!==(o=v._threadReadReceipts[n.thread_id])&&void 0!==o?o:{}),{[r]:a})}):v._readReceipts[r]=a}}))}))})),t.timeline&&t.timeline.limited&&(v._timeline=[]),null===(f=null===(h=t.state)||void 0===h?void 0:h.events)||void 0===f||f.forEach((e=>{d(v._currentState,e)})),null===(g=null===(p=t.timeline)||void 0===p?void 0:p.events)||void 0===g||g.forEach(((e,n)=>{var r;let o;if(d(v._currentState,e),i)o=e;else{o=Object.assign({},e),void 0!==o.unsigned&&(o.unsigned=Object.assign({},o.unsigned));const t=e.unsigned?e.unsigned.age:e.age;void 0!==t&&(o._localTs=Date.now()-t)}v._timeline.push({event:o,token:0===n&&null!==(r=t.timeline.prev_batch)&&void 0!==r?r:null})})),v._timeline.length>this.opts.maxTimelineEntries){for(let e=v._timeline.length-this.opts.maxTimelineEntries;e<v._timeline.length;e++)if(v._timeline[e].token){v._timeline=v._timeline.slice(e,v._timeline.length);break}}}getJSON(e=!1){const t={join:{},invite:{},leave:{}};Object.keys(this.inviteRooms).forEach((e=>{t.invite[e]=this.inviteRooms[e]})),Object.keys(this.joinRooms).forEach((i=>{const n=this.joinRooms[i],s={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:n._unreadNotifications,unread_thread_notifications:n._unreadThreadNotifications,summary:n._summary};Object.keys(n._accountData).forEach((e=>{s.account_data.events.push(n._accountData[e])}));const a={type:o.EventType.Receipt,room_id:i,content:{}},c=new r.MapWithDefault((()=>new r.MapWithDefault((()=>new Map))));for(const[e,t]of Object.entries(n._readReceipts))c.getOrCreate(t.eventId).getOrCreate(t.type).set(e,t.data);for(const e of Object.values(n._threadReadReceipts))for(const[t,i]of Object.entries(e))c.getOrCreate(i.eventId).getOrCreate(i.type).set(t,i.data);a.content=(0,r.recursiveMapToObject)(c),c.size>0&&s.ephemeral.events.push(a),n._timeline.forEach((t=>{if(!s.timeline.prev_batch){if(!t.token)return;s.timeline.prev_batch=t.token}let i;var n;!e&&("_localTs"in(n=t.event)&&void 0!==n._localTs)?(i=Object.assign({},t.event),void 0!==i.unsigned&&(i.unsigned=Object.assign({},i.unsigned)),delete i._localTs,i.unsigned=i.unsigned||{},i.unsigned.age=Date.now()-t.event._localTs):i=t.event,s.timeline.events.push(i)}));const l=Object.create(null);for(let e=s.timeline.events.length-1;e>=0;e--){const t=s.timeline.events[e];if(null===t.state_key||void 0===t.state_key)continue;const i=(0,r.deepCopy)(t);i.unsigned&&(i.unsigned.prev_content&&(i.content=i.unsigned.prev_content),i.unsigned.prev_sender&&(i.sender=i.unsigned.prev_sender)),d(l,i)}Object.keys(n._currentState).forEach((e=>{Object.keys(n._currentState[e]).forEach((t=>{let i=n._currentState[e][t];l[e]&&l[e][t]&&(i=l[e][t]),s.state.events.push(i)}))})),t.join[i]=s}));const i=[];return Object.keys(this.accountData).forEach((e=>{i.push(this.accountData[e])})),{nextBatch:this.nextBatch,roomsData:t,accountData:i}}getNextBatchToken(){return this.nextBatch}}},{"./@types/event":306,"./@types/read_receipts":311,"./@types/sync":314,"./logger":374,"./utils":416}],414:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i._createAndReEmitRoom=i.SyncApi=i.defaultSyncApiOpts=i.defaultClientOpts=i.SyncState=void 0;const a=e("./models/user"),c=e("./models/room"),d=o(e("./utils")),l=e("./utils"),u=e("./filter"),h=e("./models/event-timeline"),f=e("./logger"),p=e("./errors"),g=e("./client"),v=e("./http-api"),m=e("./@types/event"),y=e("./models/room-state"),b=e("./models/room-member"),S=e("./models/beacon"),_=e("./@types/sync"),E=e("./feature"),w=!0;var T;!function(e){e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING"}(T=i.SyncState||(i.SyncState={}));const I=["org.matrix.msc2716v3"];function R(e,t){return`FILTER_SYNC_${e}`+(t?"_"+t:"")}function M(...e){w&&f.logger.log(...e)}var k;function C(e){return Object.assign({initialSyncLimit:8,resolveInvitesToProfiles:!1,pollTimeout:3e4,pendingEventOrdering:g.PendingEventOrdering.Chronological,threadSupport:!1},e)}function O(e){return Object.assign({canResetEntireTimeline:e=>!1},e)}!function(e){e.Offline="offline",e.Online="online",e.Unavailable="unavailable"}(k||(k={})),i.defaultClientOpts=C,i.defaultSyncApiOpts=O;function A(e,t){const i=new a.User(t);return e.reEmitter.reEmit(i,[a.UserEvent.AvatarUrl,a.UserEvent.DisplayName,a.UserEvent.Presence,a.UserEvent.CurrentlyActive,a.UserEvent.LastPresenceTs]),i}function P(e,t,i){const{timelineSupport:n}=e,r=new c.Room(t,e,e.getUserId(),{lazyLoadMembers:i.lazyLoadMembers,pendingEventOrdering:i.pendingEventOrdering,timelineSupport:n});return e.reEmitter.reEmit(r,[c.RoomEvent.Name,c.RoomEvent.Redaction,c.RoomEvent.RedactionCancelled,c.RoomEvent.Receipt,c.RoomEvent.Tags,c.RoomEvent.LocalEchoUpdated,c.RoomEvent.AccountData,c.RoomEvent.MyMembership,c.RoomEvent.Timeline,c.RoomEvent.TimelineReset,y.RoomStateEvent.Events,y.RoomStateEvent.Members,y.RoomStateEvent.NewMember,y.RoomStateEvent.Update,S.BeaconEvent.New,S.BeaconEvent.Update,S.BeaconEvent.Destroy,S.BeaconEvent.LivenessChange]),r.on(y.RoomStateEvent.NewMember,((t,i,n)=>{var r;n.user=null!==(r=e.getUser(n.userId))&&void 0!==r?r:void 0,e.reEmitter.reEmit(n,[b.RoomMemberEvent.Name,b.RoomMemberEvent.Typing,b.RoomMemberEvent.PowerLevel,b.RoomMemberEvent.Membership])})),r}i.SyncApi=class{constructor(e,t,i){this.client=e,this._peekRoom=null,this.syncState=null,this.catchingUp=!1,this.running=!1,this.notifEvents=[],this.failedSyncCount=0,this.storeIsInvalid=!1,this.getPushRules=()=>s(this,void 0,void 0,(function*(){try{M("Getting push rules...");const e=yield this.client.getPushRules();M("Got push rules"),this.client.pushRules=e}catch(e){if(f.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return M("Waiting for saved sync before retrying push rules..."),yield this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getPushRules()}})),this.buildDefaultFilter=()=>{const e=new u.Filter(this.client.credentials.userId);return this.client.canSupport.get(E.Feature.ThreadUnreadNotifications)!==E.ServerSupport.Unsupported&&e.setUnreadThreadNotifications(!0),e},this.checkLazyLoadStatus=()=>s(this,void 0,void 0,(function*(){var e;if(M("Checking lazy load status..."),this.opts.lazyLoadMembers&&this.client.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers){M("Checking server lazy load support...");(yield this.client.doesServerSupportLazyLoading())?(M("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=this.buildDefaultFilter()),this.opts.filter.setLazyLoadMembers(!0)):(M("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)}M("Checking whether lazy loading has changed in store...");if(yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const e=new p.InvalidStoreError(p.InvalidStoreState.ToggledLazyLoading,!!this.opts.lazyLoadMembers);return this.updateSyncState(T.Error,{error:e}),void f.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&(null===(e=this.syncOpts.crypto)||void 0===e||e.enableLazyLoading());try{M("Storing client options..."),yield this.client.storeClientOptions(),M("Stored client options")}catch(e){throw f.logger.error("Storing client options failed",e),e}})),this.getFilter=()=>s(this,void 0,void 0,(function*(){let e,t;M("Getting filter..."),e=this.opts.filter?this.opts.filter:this.buildDefaultFilter();try{t=yield this.client.getOrCreateFilter(R(this.client.credentials.userId),e)}catch(e){return f.logger.error("Getting filter failed",e),this.shouldAbortSync(e)?{}:(M("Waiting for saved sync before retrying filter..."),yield this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getFilter())}return{filter:e,filterId:t}})),this.onOnline=()=>{M("Browser thinks we are back online"),this.startKeepAlives(0)},this.opts=C(t),this.syncOpts=O(i),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[c.RoomEvent.Timeline,c.RoomEvent.TimelineReset])}createRoom(e){const t=P(this.client,e,this.opts);return t.on(y.RoomStateEvent.Marker,((e,i)=>{this.onMarkerStateEvent(t,e,i)})),t}onMarkerStateEvent(e,t,{timelineWasEmpty:i}={}){if(i)return void f.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because the timeline was empty before the marker arrived which means there is nothing to refresh.`);I.includes(e.getVersion())||t.getSender()===e.getCreator()?(f.logger.debug(`MarkerState: Timeline needs to be refreshed because a new markerEventId=${t.getId()} was sent in roomId=${e.roomId}`),e.setTimelineNeedsRefresh(!0),e.emit(c.RoomEvent.HistoryImportedWithinTimeline,t,e)):f.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.`)}syncLeftRooms(){var e;return s(this,void 0,void 0,(function*(){const t=this.client,i=new u.Filter(this.client.credentials.userId);i.setTimelineLimit(1),i.setIncludeLeaveRooms(!0);const n=this.opts.pollTimeout+8e4,r={timeout:0,filter:yield t.getOrCreateFilter(R(t.credentials.userId,"LEFT_ROOMS"),i)},o=yield t.http.authedRequest(v.Method.Get,"/sync",r,void 0,{localTimeoutMs:n});let a=[];(null===(e=o.rooms)||void 0===e?void 0:e.leave)&&(a=this.mapSyncResponseToRoomArray(o.rooms.leave));return(yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){const i=e.room;if(!e.isBrandNewRoom)return;e.timeline=e.timeline||{prev_batch:null,events:[]};const n=this.mapSyncEventsFormat(e.timeline,i),r=this.mapSyncEventsFormat(e.state,i);return i.getLiveTimeline().setPaginationToken(e.timeline.prev_batch,h.EventTimeline.BACKWARDS),yield this.injectRoomEvents(i,r,n),i.recalculate(),t.store.storeRoom(i),t.emit(g.ClientEvent.Room,i),this.processEventsForNotifs(i,n),i})))))).filter(Boolean)}))}peek(e){var t;if((null===(t=this._peekRoom)||void 0===t?void 0:t.roomId)===e)return Promise.resolve(this._peekRoom);const i=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,20).then((e=>{e.messages=e.messages||{chunk:[]},e.messages.chunk=e.messages.chunk||[],e.state=e.state||[];const t=d.deepCopy(e.state).map(i.getEventMapper()),n=e.state.map(i.getEventMapper()),r=e.messages.chunk.map(i.getEventMapper());return Array.isArray(e.presence)&&e.presence.map(i.getEventMapper()).forEach((function(e){let t=i.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=A(i,e.getContent().user_id),t.setPresenceEvent(e),i.store.storeUser(t)),i.emit(g.ClientEvent.Event,e)})),e.messages.start&&(this._peekRoom.oldState.paginationToken=e.messages.start),this._peekRoom.oldState.setStateEvents(t),this._peekRoom.currentState.setStateEvents(n),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(r.reverse(),!0,this._peekRoom.getLiveTimeline(),e.messages.start),i.store.storeRoom(this._peekRoom),i.emit(g.ClientEvent.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom}))}stopPeeking(){this._peekRoom=null}peekPoll(e,t){var i;this._peekRoom===e?this.client.http.authedRequest(v.Method.Get,"/events",{room_id:e.roomId,timeout:String(3e4),from:t},void 0,{localTimeoutMs:5e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal}).then((t=>{if(this._peekRoom!==e)return void M("Stopped peeking in room %s",e.roomId);t.chunk.filter((function(e){return"m.presence"===e.type})).map(this.client.getEventMapper()).forEach((e=>{let t=this.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=A(this.client,e.getContent().user_id),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit(g.ClientEvent.Event,e)}));const i=t.chunk.filter((function(t){return t.room_id===e.roomId&&t.event_id})).map(this.client.getEventMapper());e.addLiveEvents(i),this.peekPoll(e,t.end)}),(i=>{f.logger.error("[%s] Peek poll failed: %s",e.roomId,i),setTimeout((()=>{this.peekPoll(e,t)}),3e4)})):M("Stopped peeking in room %s",e.roomId)}getSyncState(){return this.syncState}getSyncStateData(){var e;return null!==(e=this.syncStateData)&&void 0!==e?e:null}recoverFromSyncStartupError(e,t){return s(this,void 0,void 0,(function*(){yield e;const i=this.startKeepAlives();this.updateSyncState(T.Error,{error:t}),yield i}))}wasLazyLoadingToggled(e=!1){return s(this,void 0,void 0,(function*(){let t=!1;if(!(yield this.client.store.isNewlyCreated())){const i=yield this.client.store.getClientOptions();return i&&(t=!!i.lazyLoadMembers),t!==e}return!1}))}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(f.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(T.Error,{error:e}),!0)}sync(){var e,i;return s(this,void 0,void 0,(function*(){if(this.running=!0,this.abortController=new AbortController,null===(i=null===(e=t.window)||void 0===e?void 0:e.addEventListener)||void 0===i||i.call(e,"online",this.onOnline,!1),this.client.isGuest())return this.doSync({});M("Getting saved sync token...");const n=this.client.store.getSavedSyncToken().then((e=>(M("Got saved sync token"),e)));this.savedSyncPromise=this.client.store.getSavedSync().then((e=>{if(M(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)})).catch((e=>{f.logger.error("Getting saved sync failed",e)})),yield this.getPushRules(),yield this.checkLazyLoadStatus();const{filterId:r,filter:o}=yield this.getFilter();if(o){if(this.client.resetNotifTimelineSet(),!this.currentSyncRequest){let e=r;const t=yield n;if(t)M("Sending first sync request...");else{M("Sending initial sync request...");const t=this.buildDefaultFilter();t.setDefinition(o.getDefinition()),t.setTimelineLimit(this.opts.initialSyncLimit),e=JSON.stringify(t.getDefinition())}this.currentSyncRequest=this.doSyncRequest({filter:e},t)}return M("Waiting for saved sync before starting sync processing..."),yield this.savedSyncPromise,this.doSync({filter:r})}}))}stop(){var e,i,n;M("SyncApi.stop"),null===(i=null===(e=t.window)||void 0===e?void 0:e.removeEventListener)||void 0===i||i.call(e,"online",this.onOnline,!1),this.running=!1,null===(n=this.abortController)||void 0===n||n.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return!!this.connectionReturnedDefer&&(this.startKeepAlives(0),!0)}syncFromCache(e){return s(this,void 0,void 0,(function*(){M("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const i={nextSyncToken:t,catchingUp:!1,fromCache:!0},n={next_batch:t,rooms:e.roomsData,account_data:{events:e.accountData}};try{yield this.processSyncResponse(i,n)}catch(e){f.logger.error("Error processing cached sync",e)}this.storeIsInvalid||this.updateSyncState(T.Prepared,i)}))}doSync(e){return s(this,void 0,void 0,(function*(){for(;this.running;){const t=this.client.store.getSyncToken();let i;try{this.currentSyncRequest||(this.currentSyncRequest=this.doSyncRequest(e,t)),i=yield this.currentSyncRequest}catch(e){if(yield this.onSyncError(e))return;continue}finally{this.currentSyncRequest=void 0}this.client.store.setSyncToken(i.next_batch),this.failedSyncCount=0,yield this.client.store.setSyncData(i);const n={oldSyncToken:null!=t?t:void 0,nextSyncToken:i.next_batch,catchingUp:this.catchingUp};this.syncOpts.crypto&&(yield this.syncOpts.crypto.onSyncWillProcess(n));try{yield this.processSyncResponse(n,i)}catch(e){f.logger.error("Caught /sync error",e),this.client.emit(g.ClientEvent.SyncUnexpectedError,e)}n.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(T.Prepared,n),e.hasSyncedBefore=!0),this.syncOpts.cryptoCallbacks&&(yield this.syncOpts.cryptoCallbacks.onSyncCompleted(n)),this.updateSyncState(T.Syncing,n),this.client.store.wantsSave()&&(this.syncOpts.crypto&&(yield this.syncOpts.crypto.saveDeviceList(0)),this.client.store.save())}this.running||(M("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(T.Stopped))}))}doSyncRequest(e,t){var i;const n=this.getSyncParams(e,t);return this.client.http.authedRequest(v.Method.Get,"/sync",n,void 0,{localTimeoutMs:n.timeout+8e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal})}getSyncParams(e,t){let i=this.opts.pollTimeout;(this.getSyncState()!==T.Syncing||this.catchingUp)&&(this.catchingUp=!0,i=0);let n=e.filter;this.client.isGuest()&&!n&&(n=this.getGuestFilter());const r={filter:n,timeout:i};return this.opts.disablePresence&&(r.set_presence=k.Offline),t?r.since=t:r._cacheBuster=Date.now(),[T.Reconnecting,T.Error].includes(this.getSyncState())&&(r.timeout=0),r}onSyncError(e){return s(this,void 0,void 0,(function*(){if(!this.running)return M("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(T.Stopped),!0;if(f.logger.error("/sync error %s",e),this.shouldAbortSync(e))return!0;this.failedSyncCount++,f.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),M("Starting keep-alive");const t=this.startKeepAlives();this.currentSyncRequest=void 0,this.updateSyncState(this.failedSyncCount>=3?T.Error:T.Reconnecting,{error:e});return(yield t)&&this.getSyncState()===T.Error&&this.updateSyncState(T.Catchup,{catchingUp:!0}),!1}))}processSyncResponse(e,t){var i,n,r,o;return s(this,void 0,void 0,(function*(){const a=this.client;if(Array.isArray(null===(i=t.presence)||void 0===i?void 0:i.events)&&t.presence.events.filter(l.noUnsafeEventProps).map(a.getEventMapper()).forEach((function(e){let t=a.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=A(a,e.getSender()),t.setPresenceEvent(e),a.store.storeUser(t)),a.emit(g.ClientEvent.Event,e)})),Array.isArray(null===(n=t.account_data)||void 0===n?void 0:n.events)){const e=t.account_data.events.filter(l.noUnsafeEventProps).map(a.getEventMapper()),i=e.reduce(((e,t)=>(e[t.getType()]=a.store.getAccountData(t.getType()),e)),{});a.store.storeAccountDataEvents(e),e.forEach((function(e){if(e.getType()===m.EventType.PushRules){const t=e.getContent();a.setPushRules(t)}const t=i[e.getType()];return a.emit(g.ClientEvent.AccountData,e,t),e}))}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){let e=t.to_device.events.filter(l.noUnsafeEventProps);this.syncOpts.cryptoCallbacks&&(e=yield this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(e));const i=[];e.map(a.getEventMapper({toDevice:!0})).map((e=>{if("m.key.verification.cancel"===e.getType()){const t=e.getContent().transaction_id;t&&i.push(t)}return e})).forEach((function(e){const t=e.getContent();if("m.room.message"!=e.getType()||"m.bad.encrypted"!=t.msgtype){if("m.key.verification.start"===e.getType()||"m.key.verification.request"===e.getType()){const n=t.transaction_id;i.includes(n)&&e.flagCancelled()}a.emit(g.ClientEvent.ToDeviceEvent,e)}else f.logger.log("Ignoring undecryptable to-device event from "+e.getSender())}))}else this.catchingUp=!1;let u=[],p=[],v=[];if(t.rooms&&(t.rooms.invite&&(u=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(p=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(v=this.mapSyncResponseToRoomArray(t.rooms.leave))),this.notifEvents=[],yield d.promiseMapSeries(u,(e=>s(this,void 0,void 0,(function*(){var t;const i=e.room,n=this.mapSyncEventsFormat(e.invite_state,i);yield this.injectRoomEvents(i,n);const r=null===(t=i.currentState.getStateEvents(m.EventType.RoomMember,a.getUserId()))||void 0===t?void 0:t.getSender(),o=a.crypto;if(o){const e=yield o.cryptoStore.takeParkedSharedHistory(i.roomId);for(const t of e)t.senderId===r&&(yield o.olmDevice.addInboundGroupSession(i.roomId,t.senderKey,t.forwardingCurve25519KeyChain,t.sessionId,t.sessionKey,t.keysClaimed,!0,{sharedHistory:!0,untrusted:!0}))}e.isBrandNewRoom?(i.recalculate(),a.store.storeRoom(i),a.emit(g.ClientEvent.Room,i)):i.recalculate(),n.forEach((function(e){a.emit(g.ClientEvent.Event,e)}))})))),yield d.promiseMapSeries(p,(t=>s(this,void 0,void 0,(function*(){var i,n,r,o,s,d;const l=t.room,u=this.mapSyncEventsFormat(t.state,l),p=this.mapSyncEventsFormat(t.timeline,l,!1),v=this.mapSyncEventsFormat(t.ephemeral),y=this.mapSyncEventsFormat(t.account_data),b=a.isRoomEncrypted(l.roomId);t.unread_notifications&&(b&&0!==t.unread_notifications.notification_count||l.setUnreadNotificationCount(c.NotificationCountType.Total,null!==(i=t.unread_notifications.notification_count)&&void 0!==i?i:0),(!b||l.getUnreadNotificationCount(c.NotificationCountType.Highlight)<=0)&&l.setUnreadNotificationCount(c.NotificationCountType.Highlight,null!==(n=t.unread_notifications.highlight_count)&&void 0!==n?n:0));const S=null!==(r=t[_.UNREAD_THREAD_NOTIFICATIONS.name])&&void 0!==r?r:t[_.UNREAD_THREAD_NOTIFICATIONS.altName];if(S){l.resetThreadUnreadNotificationCount(Object.keys(S));for(const[e,t]of Object.entries(S)){b&&0!==t.notification_count||l.setThreadUnreadNotificationCount(e,c.NotificationCountType.Total,null!==(o=t.notification_count)&&void 0!==o?o:0);const i=l.getThreadUnreadNotificationCount(e,c.NotificationCountType.Highlight)<=0;(!b||b&&i)&&l.setThreadUnreadNotificationCount(e,c.NotificationCountType.Highlight,null!==(s=t.highlight_count)&&void 0!==s?s:0)}}else l.resetThreadUnreadNotificationCount();if(t.timeline=t.timeline||{},t.isBrandNewRoom)null!==t.timeline.prev_batch&&l.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,h.EventTimeline.BACKWARDS);else if(t.timeline.limited){let i=!0;for(let e=p.length-1;e>=0;e--){const t=p[e].getId();if(l.getTimelineForEvent(t)){M(`Already have event ${t} in limited sync - not resetting`),i=!1,p.splice(0,e);break}}i&&(l.resetLiveTimeline(t.timeline.prev_batch,this.syncOpts.canResetEntireTimeline(l.roomId)?null:null!==(d=e.oldSyncToken)&&void 0!==d?d:null),a.resetNotifTimelineSet())}if(this.syncOpts.cryptoCallbacks)for(const e of u.concat(p))e.isState()&&e.getType()===m.EventType.RoomEncryption&&""===e.getStateKey()&&(yield this.syncOpts.cryptoCallbacks.onCryptoEvent(l,e));try{yield this.injectRoomEvents(l,u,p,e.fromCache)}catch(e){f.logger.error(`Failed to process events on room ${l.roomId}:`,e)}t.summary&&l.setSummary(t.summary),l.addEphemeralEvents(v),l.addAccountData(y),l.recalculate(),t.isBrandNewRoom&&(a.store.storeRoom(l),a.emit(g.ClientEvent.Room,l)),this.processEventsForNotifs(l,p);const E=e=>a.emit(g.ClientEvent.Event,e);u.forEach(E),p.forEach(E),v.forEach(E),y.forEach(E),l.decryptCriticalEvents()})))),yield d.promiseMapSeries(v,(e=>s(this,void 0,void 0,(function*(){const t=e.room,i=this.mapSyncEventsFormat(e.state,t),n=this.mapSyncEventsFormat(e.timeline,t),r=this.mapSyncEventsFormat(e.account_data);yield this.injectRoomEvents(t,i,n),t.addAccountData(r),t.recalculate(),e.isBrandNewRoom&&(a.store.storeRoom(t),a.emit(g.ClientEvent.Room,t)),this.processEventsForNotifs(t,n),i.forEach((function(e){a.emit(g.ClientEvent.Event,e)})),n.forEach((function(e){a.emit(g.ClientEvent.Event,e)})),r.forEach((function(e){a.emit(g.ClientEvent.Event,e)}))})))),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((function(e){var t;null===(t=a.getNotifTimelineSet())||void 0===t||t.addLiveEvent(e)}))),t.device_lists&&this.syncOpts.crypto&&(yield this.syncOpts.crypto.handleDeviceListChanges(e,t.device_lists)),t.device_one_time_keys_count){const e=new Map(Object.entries(t.device_one_time_keys_count));null===(r=this.syncOpts.cryptoCallbacks)||void 0===r||r.preprocessOneTimeKeyCounts(e)}if(t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"]){const e=t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"];null===(o=this.syncOpts.cryptoCallbacks)||void 0===o||o.preprocessUnusedFallbackKeys(new Set(e||null))}}))}startKeepAlives(e){return void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this.keepAliveTimer&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=d.defer()),this.connectionReturnedDefer.promise}pokeKeepAlive(e=!1){var t;const i=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(e),this.connectionReturnedDefer=void 0)};this.client.http.request(v.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3,abortSignal:null===(t=this.abortController)||void 0===t?void 0:t.signal}).then((()=>{i()}),(t=>{400==t.httpStatus||404==t.httpStatus?this.keepAliveTimer=setTimeout(i,2e3):(e=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,e),5e3+Math.floor(5e3*Math.random())),this.updateSyncState(T.Error,{error:t}))}))}mapSyncResponseToRoomArray(e){const t=this.client;return Object.keys(e).filter((e=>!(0,l.unsafeProp)(e))).map((i=>{const n=e[i];let r=t.store.getRoom(i),o=!1;return r||(r=this.createRoom(i),o=!0),n.room=r,n.isBrandNewRoom=o,n}))}mapSyncEventsFormat(e,t,i=!0){if(!e||!Array.isArray(e.events))return[];const n=this.client.getEventMapper({decrypt:i});return e.events.filter(l.noUnsafeEventProps).map((function(e){return t&&(e.room_id=t.roomId),n(e)}))}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(i){if(i.requestedProfileInfo)return;i.requestedProfileInfo=!0;const n=t.getUser(i.userId);let r;r=n?Promise.resolve({avatar_url:n.avatarUrl,displayname:n.displayName}):t.getProfileInfo(i.userId),r.then((function(t){const n=i.events.member;"invite"===(null==n?void 0:n.getContent().membership)&&(n.getContent().avatar_url=t.avatar_url,n.getContent().displayname=t.displayname,i.setMembershipEvent(n,e.currentState))}),(function(e){}))}))}injectRoomEvents(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){const r=e.getLiveTimeline(),o=0==r.getEvents().length;if(o){for(const e of t)this.client.getPushActionsForEvent(e);r.initialiseState(t,{timelineWasEmpty:o})}this.resolveInvites(e),e.recalculate(),o||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(i||[],{fromCache:n,timelineWasEmpty:o}),this.client.processBeaconEvents(e,i)}))}processEventsForNotifs(e,t){var i;if(this.client.getNotifTimelineSet())for(const e of t){const t=this.client.getPushActionsForEvent(e);(null==t?void 0:t.notify)&&(null===(i=t.tweaks)||void 0===i?void 0:i.highlight)&&this.notifEvents.push(e)}}getGuestFilter(){return"{}"}updateSyncState(e,t){const i=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(g.ClientEvent.Sync,this.syncState,i,t)}},i._createAndReEmitRoom=P}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/event":306,"./@types/sync":314,"./client":321,"./errors":359,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/beacon":378,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/user":396,"./utils":416}],415:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineIndex=i.TimelineWindow=void 0;const r=e("./models/event-timeline"),o=(e("./logger"),function(){});i.TimelineWindow=class{constructor(e,t,i={}){this.client=e,this.timelineSet=t,this.eventCount=0,this.windowLimit=i.windowLimit||1e3}load(e,t=20){const i=i=>{if(!i)throw new Error("No timeline given to initFields");let n;const r=i.getEvents();if(e){if(n=r.findIndex((t=>t.getId()===e)),n<0)throw new Error("getEventTimeline result didn't include requested event")}else n=r.length;const o=Math.min(r.length,n+Math.ceil(t/2)),a=Math.max(0,o-t);this.start=new s(i,a-i.getBaseIndex()),this.end=new s(i,o-i.getBaseIndex()),this.eventCount=o-a};return this.timelineSet.getTimelineForEvent(e)?(i(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(i):(i(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){var t,i;if(e==r.EventTimeline.BACKWARDS)return null!==(t=this.start)&&void 0!==t?t:null;if(e==r.EventTimeline.FORWARDS)return null!==(i=this.end)&&void 0!==i?i:null;throw new Error("Invalid direction '"+e+"'")}extend(e,t){const i=this.getTimelineIndex(e);if(!i)return o("TimelineWindow: no timeline yet"),!1;const n=e==r.EventTimeline.BACKWARDS?i.retreat(t):i.advance(t);if(n){this.eventCount+=n,o("TimelineWindow: increased cap by "+n+" (now "+this.eventCount+")");const t=this.eventCount-this.windowLimit;return t>0&&this.unpaginate(t,e!=r.EventTimeline.BACKWARDS),!0}return!1}canPaginate(e){const t=this.getTimelineIndex(e);if(!t)return o("TimelineWindow: no timeline yet"),!1;if(e==r.EventTimeline.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;const i=t.timeline.getNeighbouringTimeline(e),n=t.timeline.getPaginationToken(e);return Boolean(i)||Boolean(n)}paginate(e,t,i=!0,s=5){return n(this,void 0,void 0,(function*(){const n=this.getTimelineIndex(e);if(!n)return o("TimelineWindow: no timeline yet"),!1;if(n.pendingPaginate)return n.pendingPaginate;if(this.extend(e,t))return!0;if(!i||0===s)return!1;if(!n.timeline.getPaginationToken(e))return o("TimelineWindow: no token"),!1;o("TimelineWindow: starting request");const a=this.client.paginateEventTimeline(n.timeline,{backwards:e==r.EventTimeline.BACKWARDS,limit:t}).finally((function(){n.pendingPaginate=void 0})).then((i=>(o("TimelineWindow: request completed with result "+i),i?this.paginate(e,t,!0,s-1):this.paginate(e,t,!1,0))));return n.pendingPaginate=a,a}))}unpaginate(e,t){const i=t?this.start:this.end;if(!i)throw new Error(`Attempting to unpaginate startOfTimeline=${t} but don't have this direction`);if(e>this.eventCount||e<0)throw new Error(`Attemting to unpaginate ${e} events, but only have ${this.eventCount} in the timeline`);for(;e>0;){const n=t?i.advance(e):i.retreat(e);if(n<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=n,this.eventCount-=n,o("TimelineWindow.unpaginate: dropped "+n+" (now "+this.eventCount+")")}}getEvents(){var e,t;if(!this.start)return[];const i=[];let n=this.start.timeline;for(;;){const o=n.getEvents();let s=0,a=o.length;n===this.start.timeline&&(s=this.start.index+n.getBaseIndex()),n===(null===(e=this.end)||void 0===e?void 0:e.timeline)&&(a=this.end.index+n.getBaseIndex());for(let e=s;e<a;e++)i.push(o[e]);if(n===(null===(t=this.end)||void 0===t?void 0:t.timeline))break;n=n.getNeighbouringTimeline(r.EventTimeline.FORWARDS)}return i}};class s{constructor(e,t){this.timeline=e,this.index=t}minIndex(){return-1*this.timeline.getBaseIndex()}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;let t;if(e<0){if(t=Math.max(e,this.minIndex()-this.index),t<0)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;const i=this.timeline.getNeighbouringTimeline(e<0?r.EventTimeline.BACKWARDS:r.EventTimeline.FORWARDS);return i?(this.timeline=i,this.index=e<0?this.maxIndex():this.minIndex(),o("paginate: switched to new neighbour"),this.advance(e)):0}retreat(e){return-1*this.advance(-1*e)}}i.TimelineIndex=s},{"./logger":374,"./models/event-timeline":382}],416:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.MapWithDefault=i.noUnsafeEventProps=i.safeSet=i.unsafeProp=i.recursiveMapToObject=i.mapsEqual=i.isSupportedReceiptType=i.sortEventsByLatestContentTimestamp=i.recursivelyAssign=i.compare=i.lexicographicCompare=i.prevString=i.nextString=i.averageBetweenStrings=i.stringToBase=i.baseToString=i.alphabetPad=i.DEFAULT_ALPHABET=i.simpleRetryOperation=i.chunkPromises=i.promiseTry=i.promiseMapSeries=i.defer=i.isNullOrUndefined=i.immediate=i.sleep=i.ensureNoTrailingSlash=i.globToRegexp=i.escapeRegExp=i.normalize=i.removeDirectionOverrideChars=i.removeHiddenChars=i.isNumber=i.deepSortedObjectEntries=i.deepCompare=i.deepCopy=i.checkObjectHasKeys=i.isFunction=i.removeElement=i.encodeUri=i.decodeParams=i.replaceParam=i.encodeParams=i.internaliseString=void 0;const o=r(e("unhomoglyph")),s=r(e("p-retry")),a=e("./@types/location"),c=e("./@types/read_receipts"),d=new Map;function l(e){return"string"==typeof e?(0,o.default)(e.normalize("NFD").replace(u,"")):""}i.internaliseString=function(e){return e instanceof String&&(e=e.toString()),d.has(e)||d.set(e,e),d.get(e)},i.encodeParams=function(e,t){const i=null!=t?t:new URLSearchParams;for(const[t,n]of Object.entries(e))null!=n&&(Array.isArray(n)?n.forEach((e=>{i.append(t,String(e))})):i.append(t,String(n)));return i},i.replaceParam=function(e,t,i){const n=Object.assign(Object.assign({},i),{[t]:i[e]});return delete n[e],n},i.decodeParams=function(e){const t={},i=new URLSearchParams(e);for(const e of i.keys()){const n=i.getAll(e);t[e]=1===n.length?n[0]:n}return t},i.encodeUri=function(e,t){for(const i in t){if(!t.hasOwnProperty(i))continue;const n=t[i];null!=n&&(e=e.replace(i,encodeURIComponent(n)))}return e},i.removeElement=function(e,t,i){let n;if(i){for(n=e.length-1;n>=0;n--)if(t(e[n],n,e))return e.splice(n,1),!0}else for(n=0;n<e.length;n++)if(t(e[n],n,e))return e.splice(n,1),!0;return!1},i.isFunction=function(e){return"[object Function]"===Object.prototype.toString.call(e)},i.checkObjectHasKeys=function(e,t){for(const i of t)if(!e.hasOwnProperty(i))throw new Error("Missing required key: "+i)},i.deepCopy=function(e){return JSON.parse(JSON.stringify(e))},i.deepCompare=function e(t,i){if(t===i)return!0;if(typeof t!=typeof i)return!1;if("number"==typeof t&&isNaN(t)&&isNaN(i))return!0;if(null===t||null===i)return t===i;if(!(t instanceof Object))return!1;if(t.constructor!==i.constructor||t.prototype!==i.prototype)return!1;if(t instanceof RegExp||t instanceof Date)return t.toString()===i.toString();if(Array.isArray(t)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!e(t[n],i[n]))return!1}else{for(const e in i)if(i.hasOwnProperty(e)!==t.hasOwnProperty(e))return!1;for(const n in t)if(i.hasOwnProperty(n)!==t.hasOwnProperty(n)||!e(t[n],i[n]))return!1}return!0},i.deepSortedObjectEntries=function e(t){if("object"!=typeof t)return t;if(null==t||Array.isArray(t))return t;const i=[];for(const[n,r]of Object.entries(t))i.push([n,e(r)]);return i.sort(((e,t)=>v(e[0],t[0]))),i},i.isNumber=function(e){return"number"==typeof e&&isFinite(e)},i.removeHiddenChars=l,i.removeDirectionOverrideChars=function(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""},i.normalize=function(e){return l(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()};const u=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function h(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(e,t,n=i.DEFAULT_ALPHABET){return e.padEnd(t,n[0])}function p(e,t=i.DEFAULT_ALPHABET){var n;const r=BigInt(t.length);if(e<=r)return null!==(n=t[Number(e)-1])&&void 0!==n?n:"";let o=e/r,s=Number(e%r)-1;return s<0&&(o-=BigInt(Math.abs(s)),s=Number(r)-1),p(o,t)+t[s]}function g(e,t=i.DEFAULT_ALPHABET){const n=BigInt(t.length);let r=BigInt(0);for(let i=e.length-1,o=BigInt(0);i>=0;i--,o++){const s=e.charCodeAt(i)-t.charCodeAt(0);r+=BigInt(1+s)*n**o}return r}function v(e,t){return e<t?-1:e>t?1:0}i.escapeRegExp=h,i.globToRegexp=function(e,t=!1){const i=[[/\\\*/g,".*"],[/\?/g,"."]];return t||i.push([/\\\[(!|)(.*)\\]/g,(e,t,i)=>["[",t?"^":"",i.replace(/\\-/,"-"),"]"].join("")]),i.reduce(((e,t)=>t?e.replace(t[0],t[1]):e),h(e))},i.ensureNoTrailingSlash=function(e){return(null==e?void 0:e.endsWith("/"))?e.slice(0,-1):e},i.sleep=function(e,t){return new Promise((i=>{setTimeout(i,e,t)}))},i.immediate=function(){return new Promise(t)},i.isNullOrUndefined=function(e){return null==e},i.defer=function(){let e,t;const i=new Promise(((i,n)=>{e=i,t=n}));return{resolve:e,reject:t,promise:i}},i.promiseMapSeries=function(e,t){return n(this,void 0,void 0,(function*(){for(const i of e)yield t(yield i)}))},i.promiseTry=function(e){return Promise.resolve(e())},i.chunkPromises=function(e,t){return n(this,void 0,void 0,(function*(){const i=[];for(let n=0;n<e.length;n+=t)i.push(...yield Promise.all(e.slice(n,n+t).map((e=>e()))));return i}))},i.simpleRetryOperation=function(e){return(0,s.default)((t=>e(t)),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})},i.DEFAULT_ALPHABET=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})(),i.alphabetPad=f,i.baseToString=p,i.stringToBase=g,i.averageBetweenStrings=function(e,t,n=i.DEFAULT_ALPHABET){const r=Math.max(e.length,t.length),o=g(f(e,r,n),n),s=g(f(t,r,n),n),a=(o+s)/BigInt(2);return a===o||a==s?p(a,n)+n[0]:p(a,n)},i.nextString=function(e,t=i.DEFAULT_ALPHABET){return p(g(e,t)+BigInt(1),t)},i.prevString=function(e,t=i.DEFAULT_ALPHABET){return p(g(e,t)-BigInt(1),t)},i.lexicographicCompare=v;const m=new Intl.Collator;function y(e){var t;return null!==(t=a.M_TIMESTAMP.findIn(e.getContent()))&&void 0!==t?t:-1}function b(e){return e instanceof Map?S(e):Array.isArray(e)?e.map((e=>b(e))):e}function S(e){const t=new Map;for(const[i,n]of e)t.set(i,b(n));return Object.fromEntries(t.entries())}function _(e){return"__proto__"===e||"prototype"===e||"constructor"===e}i.compare=function(e,t){return m.compare(e,t)},i.recursivelyAssign=function e(t,i,n=!1){for(const[r,o]of Object.entries(i))t[r]instanceof Object&&o?e(t[r],o):null==o&&n||(t[r]=o);return t},i.sortEventsByLatestContentTimestamp=function(e,t){return y(t)-y(e)},i.isSupportedReceiptType=function(e){return[c.ReceiptType.Read,c.ReceiptType.ReadPrivate].includes(e)},i.mapsEqual=function(e,t,i=((e,t)=>e===t)){if(e.size!==t.size)return!1;for(const[n,r]of e){const e=t.get(n);if(void 0===e||!i(r,e))return!1}return!0},i.recursiveMapToObject=S,i.unsafeProp=_,i.safeSet=function(e,t,i){if(_(t))throw new Error("Trying to modify prototype or constructor");e[t]=i},i.noUnsafeEventProps=function(e){return!(_(e.room_id)||_(e.sender)||_(e.user_id)||_(e.event_id))};class E extends Map{constructor(e){super(),this.createDefault=e}getOrCreate(e){return this.has(e)||this.set(e,this.createDefault()),this.get(e)}}i.MapWithDefault=E}).call(this)}).call(this,e("timers").setImmediate)},{"./@types/location":308,"./@types/read_receipts":311,"p-retry":225,timers:280,unhomoglyph:282}],417:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.releaseContext=i.acquireContext=void 0;let n=null,r=0;i.acquireContext=()=>(null===n&&(n=new AudioContext),r++,n);i.releaseContext=()=>{r--,0===r&&(null==n||n.close(),n=null)}},{}],418:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.createNewMatrixCall=i.supportsMatrixCall=i.setTracksEnabled=i.MatrixCall=i.genCallID=i.CallError=i.CallErrorCode=i.CallEvent=i.CallParty=i.CallDirection=i.CallType=i.CallState=void 0;const a=e("uuid"),c=e("sdp-transform"),d=e("../logger"),l=o(e("../utils")),u=e("../@types/event"),h=e("../randomstring"),f=e("./callEventTypes"),p=e("./callFeed"),g=e("../models/typed-event-emitter"),v=e("../crypto/deviceinfo"),m=e("./groupCall"),y=e("../http-api");var b,S,_,E,w,T,I,R;!function(e){e.AUDIO="audio",e.VIDEO="video"}(b||(b={})),function(e){e.OPUS="opus"}(S||(S={})),function(e){e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended"}(_=i.CallState||(i.CallState={})),function(e){e.Voice="voice",e.Video="video"}(E=i.CallType||(i.CallType={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(w=i.CallDirection||(i.CallDirection={})),function(e){e.Local="local",e.Remote="remote"}(T=i.CallParty||(i.CallParty={})),function(e){e.Hangup="hangup",e.State="state",e.Error="error",e.Replaced="replaced",e.LocalHoldUnhold="local_hold_unhold",e.RemoteHoldUnhold="remote_hold_unhold",e.HoldUnhold="hold_unhold",e.FeedsChanged="feeds_changed",e.AssertedIdentityChanged="asserted_identity_changed",e.LengthChanged="length_changed",e.DataChannel="datachannel",e.SendVoipEvent="send_voip_event"}(I=i.CallEvent||(i.CallEvent={})),function(e){e.UserHangup="user_hangup",e.LocalOfferFailed="local_offer_failed",e.NoUserMedia="no_user_media",e.UnknownDevices="unknown_devices",e.SendInvite="send_invite",e.CreateAnswer="create_answer",e.CreateOffer="create_offer",e.SendAnswer="send_answer",e.SetRemoteDescription="set_remote_description",e.SetLocalDescription="set_local_description",e.AnsweredElsewhere="answered_elsewhere",e.IceFailed="ice_failed",e.InviteTimeout="invite_timeout",e.Replaced="replaced",e.SignallingFailed="signalling_timeout",e.UserBusy="user_busy",e.Transferred="transferred",e.NewSession="new_session"}(R=i.CallErrorCode||(i.CallErrorCode={}));class M extends Error{constructor(e,t,i){super(t+": "+i),this.code=e}}function k(){return Date.now().toString()+(0,h.randomString)(16)}function C(e){return[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:e?12e3:void 0}]}function O(e,t){return e+":"+t}i.CallError=M,i.genCallID=k;class A extends g.TypedEventEmitter{constructor(e){var t;if(super(),this.toDeviceSeq=0,this.isPtt=!1,this._state=_.Fledgling,this.candidateSendQueue=[],this.candidateSendTries=0,this.candidatesEnded=!1,this.feeds=[],this.transceivers=new Map,this.inviteOrAnswerSent=!1,this.waitForLocalAVStream=!1,this.removeTrackListeners=new Map,this.remoteOnHold=!1,this.makingOffer=!1,this.ignoreOffer=!1,this.remoteCandidateBuffer=new Map,this.gotLocalIceCandidate=e=>{if(e.candidate){if(this.candidatesEnded)return void d.logger.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended - ignoring!`);if(d.logger.debug(`Call ${this.callId} got local ICE ${e.candidate.sdpMid} ${e.candidate.candidate}`),this.callHasEnded())return;""===e.candidate.candidate?this.queueCandidate(null):this.queueCandidate(e.candidate)}},this.onIceGatheringStateChange=e=>{var t;d.logger.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`),"complete"===(null===(t=this.peerConn)||void 0===t?void 0:t.iceGatheringState)&&this.queueCandidate(null)},this.getLocalOfferFailed=e=>{d.logger.error(`Call ${this.callId} getLocalOfferFailed() running`,e),this.emit(I.Error,new M(R.LocalOfferFailed,"Failed to get local offer!",e),this),this.terminate(T.Local,R.LocalOfferFailed,!1)},this.getUserMediaFailed=e=>{this.successor?this.successor.getUserMediaFailed(e):(d.logger.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`,e),this.emit(I.Error,new M(R.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e),this),this.terminate(T.Local,R.NoUserMedia,!1))},this.onIceConnectionStateChanged=()=>{var e,t,i,n,r,o;if(!this.callHasEnded()&&(d.logger.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.iceConnectionState})`),["connected","completed"].includes(null!==(i=null===(t=this.peerConn)||void 0===t?void 0:t.iceConnectionState)&&void 0!==i?i:"")?(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.state=_.Connected,this.callLengthInterval||this.callStartTime||(this.callStartTime=Date.now(),this.callLengthInterval=setInterval((()=>{this.emit(I.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)}),1e3))):"failed"==(null===(n=this.peerConn)||void 0===n?void 0:n.iceConnectionState)?(null===(r=this.peerConn)||void 0===r?void 0:r.restartIce)?(this.candidatesEnded=!1,this.peerConn.restartIce()):(d.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`),this.hangup(R.IceFailed,!1)):"disconnected"==(null===(o=this.peerConn)||void 0===o?void 0:o.iceConnectionState)&&(this.iceDisconnectedTimeout=setTimeout((()=>{d.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`),this.hangup(R.IceFailed,!1)}),3e4),this.state=_.Connecting),this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState)))for(const e of this.getRemoteFeeds())e.setAudioVideoMuted(!0,!0)},this.onSignallingStateChanged=()=>{var e;d.logger.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.signalingState})`)},this.onTrack=e=>{if(0===e.streams.length)return void d.logger.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${e.track.kind})`);const t=e.streams[0];if(this.pushRemoteFeed(t),!this.removeTrackListeners.has(t)){const e=()=>{0===t.getTracks().length&&(d.logger.info(`Call ${this.callId} onTrack() removing track (streamId=${t.id})`),this.deleteFeedByStream(t),t.removeEventListener("removetrack",e),this.removeTrackListeners.delete(t))};t.addEventListener("removetrack",e),this.removeTrackListeners.set(t,e)}},this.onDataChannel=e=>{this.emit(I.DataChannel,e.channel,this)},this.onNegotiationNeeded=()=>s(this,void 0,void 0,(function*(){d.logger.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`),this.state===_.CreateOffer||0!==this.opponentVersion?this.queueGotLocalOffer():d.logger.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`)})),this.onHangupReceived=e=>{d.logger.debug(`Call ${this.callId} onHangupReceived() running`),this.partyIdMatches(e)||this.state===_.Ringing?this.terminate(T.Remote,e.reason||R.UserHangup,!0):d.logger.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)},this.onRejectReceived=e=>{d.logger.debug(`Call ${this.callId} onRejectReceived() running`);[_.InviteSent,_.Ringing].includes(this.state)||this.state===_.Fledgling&&this.direction===w.Inbound?this.terminate(T.Remote,e.reason||R.UserHangup,!0):d.logger.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`)},this.onAnsweredElsewhere=e=>{d.logger.debug(`Call ${this.callId} onAnsweredElsewhere() running`),this.terminate(T.Remote,R.AnsweredElsewhere,!0)},this.roomId=e.roomId,this.invitee=e.invitee,this.client=e.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=null!==(t=e.forceTURN)&&void 0!==t&&t,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=e.opponentDeviceId,this.opponentSessionId=e.opponentSessionId,this.groupCallId=e.groupCallId,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:["stun:turn.matrix.org"]});for(const e of this.turnServers)l.checkObjectHasKeys(e,["urls"]);this.callId=k(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){return s(this,void 0,void 0,(function*(){yield this.placeCall(!0,!1)}))}placeVideoCall(){return s(this,void 0,void 0,(function*(){yield this.placeCall(!0,!0)}))}createDataChannel(e,t){const i=this.peerConn.createDataChannel(e,t);return this.emit(I.DataChannel,i,this),i}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(I.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?E.Video:E.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some((e=>{var t;return e.purpose===f.SDPStreamMetadataPurpose.Usermedia&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoTracks().length)}))}get hasLocalUserMediaAudioTrack(){var e;return!!(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some((e=>{var t;return e.purpose===f.SDPStreamMetadataPurpose.Usermedia&&!!(null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks().length)}))}get hasUserMediaAudioSender(){var e;return Boolean(null===(e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"audio")))||void 0===e?void 0:e.sender)}get hasUserMediaVideoSender(){var e;return Boolean(null===(e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===e?void 0:e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Usermedia))}get localScreensharingFeed(){return this.getLocalFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Screenshare))}get localUsermediaStream(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.stream}get localScreensharingStream(){var e;return null===(e=this.localScreensharingFeed)||void 0===e?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Usermedia))}get remoteScreensharingFeed(){return this.getRemoteFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Screenshare))}get remoteUsermediaStream(){var e;return null===(e=this.remoteUsermediaFeed)||void 0===e?void 0:e.stream}get remoteScreensharingStream(){var e;return null===(e=this.remoteScreensharingFeed)||void 0===e?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find((t=>t.stream.id===e))}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter((e=>e.isLocal()))}getRemoteFeeds(){return this.feeds.filter((e=>!e.isLocal()))}initOpponentCrypto(){var e,t;return s(this,void 0,void 0,(function*(){if(!this.opponentDeviceId)return;if(!this.client.getUseE2eForGroupCall())return;if(!this.client.isCryptoEnabled())return void(this.opponentDeviceInfo=new v.DeviceInfo(this.opponentDeviceId));if(!this.client.crypto)throw new Error("Crypto is not initialised.");const i=this.invitee||(null===(e=this.getOpponentMember())||void 0===e?void 0:e.userId);if(!i)throw new Error("Couldn't find opponent user ID to init crypto");const n=yield this.client.crypto.deviceList.downloadKeys([i],!1);if(this.opponentDeviceInfo=null===(t=n.get(i))||void 0===t?void 0:t.get(this.opponentDeviceId),void 0===this.opponentDeviceInfo)throw new m.GroupCallUnknownDeviceError(i)}))}getLocalSDPStreamMetadata(e=!1){const t={};for(const i of this.getLocalFeeds())e&&(i.sdpMetadataStreamId=i.stream.id),t[i.sdpMetadataStreamId]={purpose:i.purpose,audio_muted:i.isAudioMuted(),video_muted:i.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some((e=>!e.isLocal()))}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,i=this.remoteSDPStreamMetadata[e.id].purpose,n=this.remoteSDPStreamMetadata[e.id].audio_muted,r=this.remoteSDPStreamMetadata[e.id].video_muted;i?this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new p.CallFeed({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i,audioMuted:n,videoMuted:r})),this.emit(I.FeedsChanged,this.feeds,this),d.logger.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${e.id}, active=${e.active}, purpose=${i})`)):d.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${e.id})`)}pushRemoteFeedWithoutMetadata(e){var t;const i=this.getOpponentMember().userId,n=f.SDPStreamMetadataPurpose.Usermedia,r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;r&&e.id!==r.id?d.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${e.id})`):this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new p.CallFeed({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:n})),this.emit(I.FeedsChanged,this.feeds,this),d.logger.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${e.id}, active=${e.active})`))}pushNewLocalFeed(e,t,i=!0){const n=this.client.getUserId();P(e.getAudioTracks(),!0),P(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):this.pushLocalFeed(new p.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),i)}pushLocalFeed(e,t=!0){if(this.feeds.some((t=>e.stream.id===t.stream.id)))d.logger.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${e.stream.id})`);else{if(this.feeds.push(e),t)for(const t of e.stream.getTracks()){d.logger.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.stream.id}, streamPurpose=${e.purpose}, enabled=${t.enabled})`);const i=O(e.purpose,t.kind);if(this.transceivers.has(i)){const e=this.transceivers.get(i);e.sender.replaceTrack(t),e.direction="inactive"===e.direction?"sendonly":"sendrecv"}else{const n=this.peerConn.addTrack(t,e.stream),r=this.peerConn.getTransceivers().find((e=>e.sender===n));r?this.transceivers.set(i,r):d.logger.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`)}}d.logger.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${e.stream.id}, active=${e.stream.active}, purpose=${e.purpose})`),this.emit(I.FeedsChanged,this.feeds,this)}}removeLocalFeed(e){const t=O(e.purpose,"audio"),i=O(e.purpose,"video");for(const e of[t,i])if(this.transceivers.has(e)){const t=this.transceivers.get(e);t.sender&&this.peerConn.removeTrack(t.sender)}e.purpose===f.SDPStreamMetadataPurpose.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(e.stream),this.deleteFeed(e)}deleteAllFeeds(){for(const e of this.feeds)e.isLocal()&&this.groupCallId||e.dispose();this.feeds=[],this.emit(I.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){const t=this.getFeedByStreamId(e.id);t?this.deleteFeed(t):d.logger.warn(`Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${e.id})`)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(I.FeedsChanged,this.feeds,this)}getCurrentCallStats(){return s(this,void 0,void 0,(function*(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}))}collectCallStats(){return s(this,void 0,void 0,(function*(){if(!this.peerConn)return;const e=yield this.peerConn.getStats(),t=[];return e.forEach((e=>{t.push(e)})),t}))}initWithInvite(e){var t;return s(this,void 0,void 0,(function*(){const i=e.getContent();this.direction=w.Inbound;(yield this.client.checkTurnServers())||d.logger.warn(`Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`);const n=i[f.SDPStreamMetadataKey];n?this.updateRemoteSDPStreamMetadata(n):d.logger.debug(`Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`),this.peerConn=this.createPeerConnection(),this.chooseOpponent(e),yield this.initOpponentCrypto();try{yield this.peerConn.setRemoteDescription(i.offer),yield this.addBufferedIceCandidates()}catch(e){return d.logger.debug(`Call ${this.callId} initWithInvite() failed to set remote description`,e),void this.terminate(T.Local,R.SetRemoteDescription,!1)}const r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;if(!(this.isOnlyDataChannelAllowed||r&&0!==r.getTracks().length))return d.logger.error(`Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`),void this.terminate(T.Local,R.SetRemoteDescription,!1);if(this.state=_.Ringing,e.getLocalAge()){const t=setTimeout((()=>{var e;this.state==_.Ringing&&(d.logger.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`),this.hangupParty=T.Remote,this.state=_.Ended,this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),null===(e=this.stats)||void 0===e||e.removeStatsReportGatherer(this.callId),this.emit(I.Hangup,this))}),i.lifetime-e.getLocalAge()),n=e=>{e!==_.Ringing&&(clearTimeout(t),this.off(I.State,n))};this.on(I.State,n)}}))}initWithHangup(e){this.state=_.Ended}shouldAnswerWithMediaType(e,t,i){return e&&!t?(d.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i} because the other side isn't sending it either.`),!1):l.isNullOrUndefined(e)||e===t||this.opponentSupportsSDPStreamMetadata()?null!=e?e:t:(d.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i}=${e} because the other side doesn't support it. Answering with ${i}=${t}.`),t)}answer(e,t){var i;return s(this,void 0,void 0,(function*(){if(!this.inviteOrAnswerSent){if(!1===e&&!1===t)throw new Error("You CANNOT answer a call without media");if(this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&(this.state=_.WaitLocalMedia);else{const n=this.state,r=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),o=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.state=_.WaitLocalMedia,this.waitForLocalAVStream=!0;try{const e=yield this.client.getMediaHandler().getUserMediaStream(r,o);this.waitForLocalAVStream=!1;const t=[new p.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(i=this.client.getDeviceId())&&void 0!==i?i:void 0,stream:e,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&t.push(this.localScreensharingFeed),this.answerWithCallFeeds(t)}catch(e){if(!o)return void this.getUserMediaFailed(e);d.logger.warn(`Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`),this.state=n,this.waitForLocalAVStream=!1,yield this.answer(r,!1)}}}}))}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){d.logger.debug(`Call ${this.callId} replacedBy() running (newCallId=${e.callId})`),this.state===_.WaitLocalMedia?(d.logger.debug(`Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${e.callId})`),e.waitForLocalAVStream=!0):[_.CreateOffer,_.InviteSent].includes(this.state)&&(e.direction===w.Outbound?e.queueGotCallFeedsForAnswer([]):(d.logger.debug(`Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${e.callId})`),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map((e=>e.clone()))))),this.successor=e,this.emit(I.Replaced,e,this),this.hangup(R.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(d.logger.debug(`Call ${this.callId} hangup() ending call (reason=${e})`),this.terminate(T.Local,e,!t),[_.Fledgling,_.WaitLocalMedia].includes(this.state))return;const i={};(this.opponentVersion&&0!==this.opponentVersion||e!==R.UserHangup)&&(i.reason=e),this.sendVoipEvent(u.EventType.CallHangup,i)}reject(){if(this.state!==_.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(0===this.opponentVersion)return d.logger.info(`Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`),void this.hangup(R.UserHangup,!0);d.logger.debug("Rejecting call: "+this.callId),this.terminate(T.Local,R.UserHangup,!0),this.sendVoipEvent(u.EventType.CallReject,{})}upgradeCall(e,t){return s(this,void 0,void 0,(function*(){if((e||t)&&this.opponentSupportsSDPStreamMetadata())try{d.logger.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${e}, video=${t})`);const i=e||this.hasLocalUserMediaAudioTrack,n=t||this.hasLocalUserMediaVideoTrack,r=yield this.client.getMediaHandler().getUserMediaStream(i,n,!1);yield this.updateLocalUsermediaStream(r,e,t)}catch(e){d.logger.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`,e),this.emit(I.Error,new M(R.NoUserMedia,"Failed to get camera access: ",e),this)}}))}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}setScreensharingEnabled(e,t){return s(this,void 0,void 0,(function*(){if(e&&this.isScreensharing())return d.logger.warn(`Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`),!0;if(!e&&!this.isScreensharing())return d.logger.warn(`Call ${this.callId} setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!`),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(d.logger.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${e})`),!e){const e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"audio")),t=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"video"));for(const i of[e,t])i&&i.sender&&this.peerConn.removeTrack(i.sender);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=yield this.client.getMediaHandler().getScreensharingStream(t);return!!e&&(this.pushNewLocalFeed(e,f.SDPStreamMetadataPurpose.Screenshare),!0)}catch(e){return d.logger.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`,e),!1}}))}setScreensharingEnabledWithoutMetadataSupport(e,t){var i,n,r;return s(this,void 0,void 0,(function*(){if(d.logger.debug(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${e})`),!e){const e=null===(n=this.localUsermediaStream)||void 0===n?void 0:n.getTracks().find((e=>"video"===e.kind)),t=null===(r=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===r?void 0:r.sender;return null==t||t.replaceTrack(null!=e?e:null),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=yield this.client.getMediaHandler().getScreensharingStream(t);if(!e)return!1;const n=e.getTracks().find((e=>"video"===e.kind)),r=null===(i=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===i?void 0:i.sender;return null==r||r.replaceTrack(null!=n?n:null),this.pushNewLocalFeed(e,f.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(e){return d.logger.error(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`,e),!1}}))}updateLocalUsermediaStream(e,t=!1,i=!1){return s(this,void 0,void 0,(function*(){const n=this.localUsermediaFeed,r=t||!n.isAudioMuted()&&!this.remoteOnHold,o=i||!n.isVideoMuted()&&!this.remoteOnHold;d.logger.log(`Call ${this.callId} updateLocalUsermediaStream() running (streamId=${e.id}, audio=${r}, video=${o})`),P(e.getAudioTracks(),r),P(e.getVideoTracks(),o);for(const e of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(e),e.stop();for(const t of e.getTracks())this.localUsermediaStream.addTrack(t);for(const t of e.getTracks()){const i=O(f.SDPStreamMetadataPurpose.Usermedia,t.kind),r=this.transceivers.get(i),o=null==r?void 0:r.sender;let s=!1;if(o)try{d.logger.info(`Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${n.purpose})`),yield o.replaceTrack(t),r.direction="inactive"===r.direction?"sendonly":"sendrecv",s=!0}catch(e){d.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`,e)}if(!s){d.logger.info(`Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${n.purpose})`);const r=this.peerConn.addTrack(t,this.localUsermediaStream),o=this.peerConn.getTransceivers().find((e=>e.sender===r));o?this.transceivers.set(i,o):d.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`)}}}))}setLocalVideoMuted(e){var t,i;return s(this,void 0,void 0,(function*(){if(d.logger.log(`Call ${this.callId} setLocalVideoMuted() running ${e}`),e||void 0===this.stopVideoTrackTimer||(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0),!(yield this.client.getMediaHandler().hasVideoDevice()))return this.isLocalVideoMuted();if(!this.hasUserMediaVideoSender&&!e)return null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(null,e),yield this.upgradeCall(!1,!0),this.isLocalVideoMuted();if(!e&&0===this.localUsermediaStream.getVideoTracks().length){const e=yield this.client.getMediaHandler().getUserMediaStream(!0,!0);yield this.updateLocalUsermediaStream(e)}return null===(i=this.localUsermediaFeed)||void 0===i||i.setAudioVideoMuted(null,e),this.updateMuteStatus(),yield this.sendMetadataUpdate(),e&&(this.stopVideoTrackTimer=setTimeout((()=>{for(const e of this.localUsermediaStream.getVideoTracks())e.stop(),this.localUsermediaStream.removeTrack(e)}),120)),this.isLocalVideoMuted()}))}isLocalVideoMuted(){var e,t;return null!==(t=null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isVideoMuted())&&void 0!==t&&t}setMicrophoneMuted(e){var t;return s(this,void 0,void 0,(function*(){return d.logger.log(`Call ${this.callId} setMicrophoneMuted() running ${e}`),(yield this.client.getMediaHandler().hasAudioDevice())?e||this.hasUserMediaAudioSender&&this.hasLocalUserMediaAudioTrack?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(e,null),this.updateMuteStatus(),yield this.sendMetadataUpdate(),this.isMicrophoneMuted()):(yield this.upgradeCall(!0,!1),this.isMicrophoneMuted()):this.isMicrophoneMuted()}))}isMicrophoneMuted(){var e,t;return null!==(t=null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted())&&void 0!==t&&t}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(const t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(I.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==_.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers()){["inactive","recvonly"].includes(t.currentDirection)||(e=!1)}return e}sendDtmfDigit(e){var t;for(const i of this.peerConn.getSenders())if("audio"===(null===(t=i.track)||void 0===t?void 0:t.kind)&&i.dtmf)return void i.dtmf.insertDTMF(e);throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;d.logger.log(`Call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${e} vidShouldBeMuted ${t}`),P(this.localUsermediaStream.getAudioTracks(),!e),P(this.localUsermediaStream.getVideoTracks(),!t)}sendMetadataUpdate(){return s(this,void 0,void 0,(function*(){yield this.sendVoipEvent(u.EventType.CallSDPStreamMetadataChangedPrefix,{[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}))}gotCallFeedsForInvite(e,t=!1){if(this.successor)this.successor.queueGotCallFeedsForAnswer(e);else if(this.callHasEnded())this.stopAllMedia();else{for(const t of e)this.pushLocalFeed(t);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=_.CreateOffer,d.logger.debug(`Call ${this.callId} gotUserMediaForInvite() run`)}}sendAnswer(){return s(this,void 0,void 0,(function*(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1};const t=this.discardDuplicateCandidates();d.logger.info(`Call ${this.callId} sendAnswer() discarding ${t} candidates that will be sent in answer`);try{yield this.sendVoipEvent(u.EventType.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.state=_.Ringing,e instanceof y.MatrixError&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SendAnswer,i="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(I.Error,new M(t,i,e),this),e}this.sendCandidateQueue()}))}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then((()=>this.gotCallFeedsForAnswer(e))):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){const i=(0,c.parse)(e.sdp);i.media.forEach((e=>{const i=new Map,n=new Map;for(const t of e.rtp)i.set(t.payload,t.codec),n.set(t.codec,t.payload);for(const r of t){if(r.mediaType!==e.type)continue;if(!n.has(r.codec)){d.logger.info(`Call ${this.callId} mungeSdp() ignoring SDP modifications for ${r.codec} as it's not present.`);continue}const t=[];void 0!==r.enableDtx&&t.push("usedtx="+(r.enableDtx?"1":"0")),void 0!==r.maxAverageBitrate&&t.push(`maxaveragebitrate=${r.maxAverageBitrate}`);let o=!1;for(const n of e.fmtp)i.get(n.payload)===r.codec&&(o=!0,n.config+=";"+t.join(";"));o||e.fmtp.push({payload:n.get(r.codec),config:t.join(";")})}})),e.sdp=(0,c.write)(i)}createOffer(){return s(this,void 0,void 0,(function*(){const e=yield this.peerConn.createOffer();return this.mungeSdp(e,C(this.isPtt)),e}))}createAnswer(){return s(this,void 0,void 0,(function*(){const e=yield this.peerConn.createAnswer();return this.mungeSdp(e,C(this.isPtt)),e}))}gotCallFeedsForAnswer(e){return s(this,void 0,void 0,(function*(){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const t of e)this.pushLocalFeed(t);let t;this.state=_.CreateAnswer;try{this.getRidOfRTXCodecs(),t=yield this.createAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `,e),void this.terminate(T.Local,R.CreateAnswer,!0)}try{if(yield this.peerConn.setLocalDescription(t),this.callHasEnded())return;if(this.state=_.Connecting,yield new Promise((e=>{setTimeout(e,200)})),this.callHasEnded())return;this.sendAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`,e),void this.terminate(T.Local,R.SetLocalDescription,!0)}}))}onRemoteIceCandidatesReceived(e){return s(this,void 0,void 0,(function*(){if(this.callHasEnded())return;const t=e.getContent(),i=t.candidates;if(!i)return void d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`);const n=0===t.version?null:t.party_id||null;if(void 0!==this.opponentPartyId)this.partyIdMatches(t)?yield this.addIceCandidates(i):d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`);else if(n){d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${i.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(n)||[];e.push(...i),this.remoteCandidateBuffer.set(n,e)}}))}onAnswerReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent();if(d.logger.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${t.party_id})`),this.callHasEnded())return void d.logger.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`);if(void 0!==this.opponentPartyId)return void d.logger.info(`Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);this.chooseOpponent(e),yield this.addBufferedIceCandidates(),this.state=_.Connecting;const i=t[f.SDPStreamMetadataKey];i?this.updateRemoteSDPStreamMetadata(i):d.logger.warn(`Call ${this.callId} onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams`);try{yield this.peerConn.setRemoteDescription(t.answer)}catch(e){return d.logger.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`,e),void this.terminate(T.Local,R.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{yield this.sendVoipEvent(u.EventType.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){d.logger.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`,e)}}))}onSelectAnswerReceived(e){return s(this,void 0,void 0,(function*(){if(this.direction!==w.Inbound)return void d.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`);const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(d.logger.info(`Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),yield this.terminate(T.Remote,R.AnsweredElsewhere,!0)):d.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`)}))}onNegotiateReceived(e){var t;return s(this,void 0,void 0,(function*(){const i=e.getContent(),n=i.description;if(!n||!n.sdp||!n.type)return void d.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`);const r=this.direction===w.Inbound,o="offer"===n.type&&(this.makingOffer||"stable"!==this.peerConn.signalingState);if(this.ignoreOffer=!r&&o,this.ignoreOffer)return void d.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`);const s=this.isLocalOnHold(),a=i[f.SDPStreamMetadataKey];a?this.updateRemoteSDPStreamMetadata(a):d.logger.warn(`Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`);try{if(yield this.peerConn.setRemoteDescription(n),"offer"===n.type){let e;try{this.getRidOfRTXCodecs(),e=yield this.createAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `,e),void this.terminate(T.Local,R.CreateAnswer,!0)}yield this.peerConn.setLocalDescription(e),this.sendVoipEvent(u.EventType.CallNegotiate,{description:null===(t=this.peerConn.localDescription)||void 0===t?void 0:t.toJSON(),[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)})}}catch(e){d.logger.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`,e)}const c=this.isLocalOnHold();s!==c&&(this.emit(I.LocalHoldUnhold,c,this),this.emit(I.HoldUnhold,c))}))}updateRemoteSDPStreamMetadata(e){var t;this.remoteSDPStreamMetadata=l.recursivelyAssign(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){const i=e.stream.id,n=this.remoteSDPStreamMetadata[i];e.setAudioVideoMuted(null==n?void 0:n.audio_muted,null==n?void 0:n.video_muted),e.purpose=null===(t=this.remoteSDPStreamMetadata[i])||void 0===t?void 0:t.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[f.SDPStreamMetadataKey];this.updateRemoteSDPStreamMetadata(t)}onAssertedIdentityReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent();t.asserted_identity&&(this.remoteAssertedIdentity={id:t.asserted_identity.id,displayName:t.asserted_identity.display_name},this.emit(I.AssertedIdentityChanged,this))}))}callHasEnded(){return this.state===_.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then((()=>this.wrappedGotLocalOffer())):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){return s(this,void 0,void 0,(function*(){this.makingOffer=!0;try{yield this.gotLocalOffer()}catch(e){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}))}gotLocalOffer(){var e,t;return s(this,void 0,void 0,(function*(){if(d.logger.debug(`Call ${this.callId} gotLocalOffer() running`),this.callHasEnded())return void d.logger.debug(`Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended"`);let i;try{this.getRidOfRTXCodecs(),i=yield this.createOffer()}catch(e){return d.logger.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `,e),void this.terminate(T.Local,R.CreateOffer,!0)}try{yield this.peerConn.setLocalDescription(i)}catch(e){return d.logger.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`,e),void this.terminate(T.Local,R.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&(yield new Promise((e=>{setTimeout(e,200)}))),this.callHasEnded())return;const n=this.state===_.CreateOffer?u.EventType.CallInvite:u.EventType.CallNegotiate,r={lifetime:6e4};n===u.EventType.CallInvite&&this.invitee&&(r.invitee=this.invitee),this.state===_.CreateOffer?r.offer=null===(e=this.peerConn.localDescription)||void 0===e?void 0:e.toJSON():r.description=null===(t=this.peerConn.localDescription)||void 0===t?void 0:t.toJSON(),r.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},r[f.SDPStreamMetadataKey]=this.getLocalSDPStreamMetadata(!0);const o=this.discardDuplicateCandidates();d.logger.info(`Call ${this.callId} gotLocalOffer() discarding ${o} candidates that will be sent in offer`);try{yield this.sendVoipEvent(n,r)}catch(e){d.logger.error(`Call ${this.callId} gotLocalOffer() failed to send invite`,e),e instanceof y.MatrixError&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SignallingFailed,i="Signalling failed";return this.state===_.CreateOffer&&(t=R.SendInvite,i="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(I.Error,new M(t,i,e),this),void this.terminate(T.Local,t,!1)}this.sendCandidateQueue(),this.state===_.CreateOffer&&(this.inviteOrAnswerSent=!0,this.state=_.InviteSent,this.inviteTimeout=setTimeout((()=>{this.inviteTimeout=void 0,this.state===_.InviteSent&&this.hangup(R.InviteTimeout,!1)}),6e4))}))}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=RTCRtpReceiver.getCapabilities("video").codecs,t=[...RTCRtpSender.getCapabilities("video").codecs,...e];for(const e of t)if("video/rtx"===e.mimeType){const i=t.indexOf(e);t.splice(i,1)}const i=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"video"));i&&i.setCodecPreferences(t)}sendVoipEvent(e,t){var i,n;return s(this,void 0,void 0,(function*(){const r=Object.assign({},t,{version:"1",call_id:this.callId,party_id:this.ourPartyId,conf_id:this.groupCallId});if(this.opponentDeviceId){const t=this.toDeviceSeq++,n=Object.assign(Object.assign({},r),{device_id:this.client.deviceId,sender_session_id:this.client.getSessionId(),dest_session_id:this.opponentSessionId,seq:t,[u.ToDeviceMessageId]:(0,a.v4)()});this.emit(I.SendVoipEvent,{type:"toDevice",eventType:e,userId:this.invitee||(null===(i=this.getOpponentMember())||void 0===i?void 0:i.userId),opponentDeviceId:this.opponentDeviceId,content:n},this);const o=this.invitee||this.getOpponentMember().userId;if(this.client.getUseE2eForGroupCall()){if(!this.opponentDeviceInfo)return void d.logger.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`);yield this.client.encryptAndSendToDevices([{userId:o,deviceInfo:this.opponentDeviceInfo}],{type:e,content:n})}else yield this.client.sendToDevice(e,new Map([[o,new Map([[this.opponentDeviceId,n]])]]))}else this.emit(I.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:this.roomId,content:r,userId:this.invitee||(null===(n=this.getOpponentMember())||void 0===n?void 0:n.userId)},this),yield this.client.sendEvent(this.roomId,e,r)}))}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,this.state===_.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===w.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout((()=>{this.sendCandidateQueue()}),t)}discardDuplicateCandidates(){let e=0;const t=[];for(let i=0;i<this.candidateSendQueue.length;i++){const n=this.candidateSendQueue[i];""===n.candidate?t.push(n):e++}return this.candidateSendQueue=t,e}transfer(e){return s(this,void 0,void 0,(function*(){const t=yield this.client.getProfileInfo(e),i=k(),n={replacement_id:k(),target_user:{id:e,display_name:t.displayname,avatar_url:t.avatar_url},create_call:i};yield this.sendVoipEvent(u.EventType.CallReplaces,n),yield this.terminate(T.Local,R.Transferred,!0)}))}transferToCall(e){var t,i;return s(this,void 0,void 0,(function*(){const n=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId,r=n?yield this.client.getProfileInfo(n):void 0,o=null===(i=this.getOpponentMember())||void 0===i?void 0:i.userId,s=o?yield this.client.getProfileInfo(o):void 0,a=k(),c={replacement_id:k(),target_user:{id:o,display_name:null==s?void 0:s.displayname,avatar_url:null==s?void 0:s.avatar_url},await_call:a};yield e.sendVoipEvent(u.EventType.CallReplaces,c);const d={replacement_id:k(),target_user:{id:n,display_name:null==r?void 0:r.displayname,avatar_url:null==r?void 0:r.avatar_url},create_call:a};yield this.sendVoipEvent(u.EventType.CallReplaces,d),yield this.terminate(T.Local,R.Transferred,!0),yield e.terminate(T.Local,R.Transferred,!0)}))}terminate(e,t,i){var n;return s(this,void 0,void 0,(function*(){if(!this.callHasEnded()){this.hangupParty=e,this.hangupReason=t,this.state=_.Ended,this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=void 0),void 0!==this.iceDisconnectedTimeout&&(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=void 0),void 0!==this.stopVideoTrackTimer&&(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0);for(const[e,t]of this.removeTrackListeners)e.removeEventListener("removetrack",t);this.removeTrackListeners.clear(),this.callStatsAtEnd=yield this.collectCallStats(),this.stopAllMedia(),this.deleteAllFeeds(),this.peerConn&&"closed"!==this.peerConn.signalingState&&this.peerConn.close(),null===(n=this.stats)||void 0===n||n.removeStatsReportGatherer(this.callId),i&&this.emit(I.Hangup,this),this.client.callEventHandler.calls.delete(this.callId)}}))}stopAllMedia(){d.logger.debug(`Call ${this.callId} stopAllMedia() running`);for(const e of this.feeds)if(e.isLocal()&&e.purpose===f.SDPStreamMetadataPurpose.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===f.SDPStreamMetadataPurpose.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){d.logger.debug(`Call ${this.callId} stopAllMedia() stopping stream (streamId=${e.stream.id})`);for(const t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(0===this.listeners(g.EventEmitterEvents.Error).length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}sendCandidateQueue(){return s(this,void 0,void 0,(function*(){if(0===this.candidateSendQueue.length||this.callHasEnded())return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e.map((e=>e.toJSON()))};this.candidatesEnded&&t.candidates.push({candidate:""}),d.logger.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${e.length} candidates`);try{yield this.sendVoipEvent(u.EventType.CallCandidates,t),this.candidateSendTries=0,this.sendCandidateQueue()}catch(t){if(t instanceof y.MatrixError&&t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){d.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,t);const e=R.SignallingFailed,i="Signalling failed";return this.emit(I.Error,new M(e,i,t),this),void this.hangup(e,!1)}const i=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,d.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${i}ms`,t),setTimeout((()=>{this.sendCandidateQueue()}),i)}}))}placeCall(e,t){var i;return s(this,void 0,void 0,(function*(){if(!e)throw new Error("You CANNOT start a call without audio");this.state=_.WaitLocalMedia;try{const n=yield this.client.getMediaHandler().getUserMediaStream(e,t);P(n.getAudioTracks(),!0),P(n.getVideoTracks(),!0);const r=new p.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(i=this.client.getDeviceId())&&void 0!==i?i:void 0,stream:n,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1});yield this.placeCallWithCallFeeds([r])}catch(e){return void this.getUserMediaFailed(e)}}))}placeCallWithCallFeeds(e,t=!1){return s(this,void 0,void 0,(function*(){this.checkForErrorListener(),this.direction=w.Outbound,yield this.initOpponentCrypto(),this.client.callEventHandler.calls.set(this.callId,this);(yield this.client.checkTurnServers())||d.logger.warn(`Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`),this.peerConn=this.createPeerConnection(),this.gotCallFeedsForInvite(e,t)}))}createPeerConnection(){var e;const t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});return t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel),null===(e=this.stats)||void 0===e||e.addStatsReportGatherer(this.callId,"unknown",t),t}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){var t;const i=e.getContent();d.logger.debug(`Call ${this.callId} chooseOpponent() running (partyId=${i.party_id})`),this.opponentVersion=i.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=i.party_id||null,this.opponentCaps=i.capabilities||{},this.opponentMember=null!==(t=this.client.getRoom(this.roomId).getMember(e.getSender()))&&void 0!==t?t:void 0}addBufferedIceCandidates(){return s(this,void 0,void 0,(function*(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(d.logger.info(`Call ${this.callId} addBufferedIceCandidates() adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),yield this.addIceCandidates(e)),this.remoteCandidateBuffer.clear()}))}addIceCandidates(e){return s(this,void 0,void 0,(function*(){for(const t of e){null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex?d.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${t.sdpMid}, candidate=${t.candidate})`):d.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`);try{yield this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer||d.logger.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`,e)}}}))}get hasPeerConnection(){return Boolean(this.peerConn)}initStats(e,t="unknown"){this.stats=e,this.stats.start()}}function P(e,t){for(const i of e)i.enabled=t}function D(){if("undefined"==typeof window||"undefined"==typeof document)return!1;try{if(!Boolean(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices))return"test"!==t.env.NODE_ENV&&d.logger.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return d.logger.error("Exception thrown when trying to access WebRTC",e),!1}return!0}i.MatrixCall=A,i.setTracksEnabled=P,i.supportsMatrixCall=D,i.createNewMatrixCall=function(e,t,i){if(!D())return null;const n=!!i&&i.forceTURN,r={client:e,roomId:t,invitee:null==i?void 0:i.invitee,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||n,opponentDeviceId:null==i?void 0:i.opponentDeviceId,opponentSessionId:null==i?void 0:i.opponentSessionId,groupCallId:null==i?void 0:i.groupCallId},o=new A(r);return e.reEmitter.reEmit(o,Object.values(I)),o}}).call(this)}).call(this,e("_process"))},{"../@types/event":306,"../crypto/deviceinfo":340,"../http-api":367,"../logger":374,"../models/typed-event-emitter":395,"../randomstring":398,"../utils":416,"./callEventTypes":420,"./callFeed":421,"./groupCall":422,_process:237,"sdp-transform":253,uuid:287}],419:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.CallEventHandler=i.CallEventHandlerEvent=void 0;const r=e("../logger"),o=e("./call"),s=e("../@types/event"),a=e("../client"),c=e("./groupCall"),d=e("../models/room");var l;!function(e){e.Incoming="Call.incoming"}(l=i.CallEventHandlerEvent||(i.CallEventHandlerEvent={}));i.CallEventHandler=class{constructor(e){this.nextSeqByCall=new Map,this.toDeviceEventBuffers=new Map,this.onSync=()=>{const e=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then((()=>this.evaluateEventBuffer(e))):this.eventBufferPromiseChain=this.evaluateEventBuffer(e)},this.onRoomTimeline=e=>{this.callEventBuffer.push(e)},this.onToDeviceEvent=e=>{const t=e.getContent();if(!t.call_id)return void this.callEventBuffer.push(e);if(this.nextSeqByCall.has(t.call_id)||this.nextSeqByCall.set(t.call_id,0),void 0===t.seq)return void this.callEventBuffer.push(e);const i=this.nextSeqByCall.get(t.call_id)||0;if(t.seq!==i){this.toDeviceEventBuffers.has(t.call_id)||this.toDeviceEventBuffers.set(t.call_id,[]);const i=this.toDeviceEventBuffers.get(t.call_id),n=i.findIndex((e=>e.getContent().seq>t.seq));-1===n?i.push(e):i.splice(n,0,e)}else{const i=t.call_id;this.callEventBuffer.push(e),this.nextSeqByCall.set(i,t.seq+1);const n=this.toDeviceEventBuffers.get(i);let r=n&&n.shift();for(;r&&r.getContent().seq===this.nextSeqByCall.get(i);)this.callEventBuffer.push(r),this.nextSeqByCall.set(i,r.getContent().seq+1),r=n.shift()}},this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(a.ClientEvent.Sync,this.onSync),this.client.on(d.RoomEvent.Timeline,this.onRoomTimeline),this.client.on(a.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(a.ClientEvent.Sync,this.onSync),this.client.removeListener(d.RoomEvent.Timeline,this.onRoomTimeline),this.client.removeListener(a.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){return n(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.client.decryptEventIfNeeded(e))));const t=e.filter((e=>{const t=e.getType();return t.startsWith("m.call.")||t.startsWith("org.matrix.call.")})),i=new Set;for(const e of t){const t=e.getType();t!==s.EventType.CallAnswer&&t!==s.EventType.CallHangup||i.add(e.getContent().call_id)}for(const e of t){const t=e.getType(),n=e.getContent().call_id;if(t!==s.EventType.CallInvite||!i.has(n))try{yield this.handleCallEvent(e)}catch(e){r.logger.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",e)}}}))}handleCallEvent(e){var t,i,d,u,h,f;return n(this,void 0,void 0,(function*(){this.client.emit(a.ClientEvent.ReceivedVoipEvent,e);const n=e.getContent(),p=e.getRoomId()||(null===(i=null===(t=this.client.groupCallEventHandler.getGroupCallById(n.conf_id))||void 0===t?void 0:t.room)||void 0===i?void 0:i.roomId),g=n.conf_id,v=e.getType(),m=e.getSender();let y,b,S=n.call_id?this.calls.get(n.call_id):void 0;if(g){if(b=this.client.groupCallEventHandler.getGroupCallById(g),!b)return void r.logger.warn(`CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${g}, type=${v})`);if(y=n.device_id,!y)return r.logger.warn(`CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${m})`),void b.emit(c.GroupCallEvent.Error,new c.GroupCallUnknownDeviceError(m));if(n.dest_session_id!==this.client.getSessionId())return void r.logger.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring")}const _=m===this.client.credentials.userId&&(void 0===y||y===this.client.getDeviceId());if(p)if(v!==s.EventType.CallInvite)if(v!==s.EventType.CallCandidates)if([s.EventType.CallHangup,s.EventType.CallReject].includes(v))S?S.state!==o.CallState.Ended&&(v===s.EventType.CallHangup?S.onHangupReceived(n):S.onRejectReceived(n),S.state===o.CallState.Ended&&this.calls.delete(n.call_id)):(S=null!==(f=(0,o.createNewMatrixCall)(this.client,p,{opponentDeviceId:y,opponentSessionId:n.sender_session_id}))&&void 0!==f?f:void 0,S&&(S.callId=n.call_id,S.initWithHangup(e),this.calls.set(n.call_id,S)));else if(S&&S.hasPeerConnection){if(e.getContent().party_id!==S.ourPartyId)switch(v){case s.EventType.CallAnswer:_?S.state===o.CallState.Ringing&&S.onAnsweredElsewhere(n):S.onAnswerReceived(e);break;case s.EventType.CallSelectAnswer:S.onSelectAnswerReceived(e);break;case s.EventType.CallNegotiate:S.onNegotiateReceived(e);break;case s.EventType.CallAssertedIdentity:case s.EventType.CallAssertedIdentityPrefix:S.onAssertedIdentityReceived(e);break;case s.EventType.CallSDPStreamMetadataChanged:case s.EventType.CallSDPStreamMetadataChangedPrefix:S.onSDPStreamMetadataChangedReceived(e)}}else r.logger.info(`CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${v})`);else{if(_)return;S?S.onRemoteIceCandidatesReceived(e):(this.candidateEventsByCall.has(n.call_id)||this.candidateEventsByCall.set(n.call_id,[]),this.candidateEventsByCall.get(n.call_id).push(e))}else{if(_)return;if(e.getLocalAge()>n.lifetime-3e3)return;if(S&&S.state===o.CallState.Ended)return;if(S&&r.logger.warn(`CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${n.call_id})`),n.invitee&&n.invitee!==this.client.getUserId())return;const t=(null!==(d=this.client.getTurnServersExpiry())&&void 0!==d?d:0)-Date.now();if(r.logger.info("CallEventHandler handleCallEvent() current turn creds expire in "+t+" ms"),S=null!==(u=(0,o.createNewMatrixCall)(this.client,p,{forceTURN:this.client.forceTURN,opponentDeviceId:y,groupCallId:g,opponentSessionId:n.sender_session_id}))&&void 0!==u?u:void 0,!S)return void r.logger.log(`CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${n.call_id})`);S.callId=n.call_id;const i=null==b?void 0:b.getGroupCallStats();i&&S.initStats(i);try{yield S.initWithInvite(e)}catch(e){e instanceof o.CallError&&(e.code===c.GroupCallErrorCode.UnknownDevice?null==b||b.emit(c.GroupCallEvent.Error,e):r.logger.error(e))}if(this.calls.set(S.callId,S),this.candidateEventsByCall.get(S.callId))for(const e of this.candidateEventsByCall.get(S.callId))S.onRemoteIceCandidatesReceived(e);let s;for(const e of this.calls.values()){const t=[o.CallState.WaitLocalMedia,o.CallState.CreateOffer,o.CallState.InviteSent].includes(e.state);if(S.roomId===e.roomId&&e.direction===o.CallDirection.Outbound&&(null===(h=S.getOpponentMember())||void 0===h?void 0:h.userId)===e.invitee&&t){s=e;break}}s?s.callId>S.callId?(r.logger.log(`CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${S.callId}, outgoingId=${s.callId})`),s.replacedBy(S)):(r.logger.log(`CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${S.callId}, outgoingId=${s.callId})`),S.hangup(o.CallErrorCode.Replaced,!0)):this.client.emit(l.Incoming,S)}}))}}},{"../@types/event":306,"../client":321,"../logger":374,"../models/room":392,"./call":418,"./groupCall":422}],420:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SDPStreamMetadataPurpose=i.SDPStreamMetadataKey=void 0,i.SDPStreamMetadataKey="org.matrix.msc3077.sdp_stream_metadata",function(e){e.Usermedia="m.usermedia",e.Screenshare="m.screenshare"}(i.SDPStreamMetadataPurpose||(i.SDPStreamMetadataPurpose={}))},{}],421:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CallFeed=i.CallFeedEvent=i.SPEAKING_THRESHOLD=void 0;const n=e("./callEventTypes"),r=e("./audioContext"),o=e("../logger"),s=e("../models/typed-event-emitter"),a=e("./call");i.SPEAKING_THRESHOLD=-60;var c;!function(e){e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.LocalVolumeChanged="local_volume_changed",e.VolumeChanged="volume_changed",e.ConnectedChanged="connected_changed",e.Speaking="speaking",e.Disposed="disposed"}(c=i.CallFeedEvent||(i.CallFeedEvent={}));class d extends s.TypedEventEmitter{constructor(e){super(),this.localVolume=1,this.measuringVolumeActivity=!1,this.speakingThreshold=i.SPEAKING_THRESHOLD,this.speaking=!1,this._disposed=!1,this._connected=!1,this.onAddTrack=()=>{this.emit(c.NewStream,this.stream)},this.onCallState=e=>{e===a.CallState.Connected?this.connected=!0:e===a.CallState.Connecting&&(this.connected=!1)},this.volumeLooper=()=>{if(!this.analyser)return;if(!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let e=-1/0;for(const t of this.frequencyBinCount)t>e&&(e=t);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(e),this.emit(c.VolumeChanged,e);let t=!1;for(const e of this.speakingVolumeSamples)if(e>this.speakingThreshold){t=!0;break}this.speaking!==t&&(this.speaking=t,this.emit(c.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,200)},this.client=e.client,this.call=e.call,this.roomId=e.roomId,this.userId=e.userId,this.deviceId=e.deviceId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(8).fill(-1/0),this.sdpMetadataStreamId=e.stream.id,this.updateStream(null,e.stream),this.stream=e.stream,this.hasAudioTrack&&this.initVolumeMeasuring(),e.call&&(e.call.addListener(a.CallEvent.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(c.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){t!==e&&(e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?this.initVolumeMeasuring():this.measureVolumeActivity(!1),this.emit(c.NewStream,this.stream))}initVolumeMeasuring(){if(!this.hasAudioTrack)return;this.audioContext||(this.audioContext=(0,r.acquireContext)()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1;this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}getMember(){var e;const t=this.client.getRoom(this.roomId);return null!==(e=null==t?void 0:t.getMember(this.userId))&&void 0!==e?e:null}isLocal(){return this.userId===this.client.getUserId()&&(void 0===this.deviceId||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return 0===this.stream.getAudioTracks().length||this.audioMuted}isVideoMuted(){return 0===this.stream.getVideoTracks().length||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){null!==e&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),null!==t&&(this.videoMuted=t),this.emit(c.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(c.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){const e=this.client.getMediaHandler(),t=this.stream.clone();return o.logger.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${t.id})`),this.purpose===n.SDPStreamMetadataPurpose.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new d({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:t,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,t;clearTimeout(this.volumeLooperTimeout),null===(e=this.stream)||void 0===e||e.removeEventListener("addtrack",this.onAddTrack),null===(t=this.call)||void 0===t||t.removeListener(a.CallEvent.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,(0,r.releaseContext)()),this._disposed=!0,this.emit(c.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(c.LocalVolumeChanged,e)}}i.CallFeed=d},{"../logger":374,"../models/typed-event-emitter":395,"./audioContext":417,"./call":418,"./callEventTypes":420}],422:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCall=i.GroupCallState=i.OtherUserSpeakingError=i.GroupCallUnknownDeviceError=i.GroupCallError=i.GroupCallErrorCode=i.GroupCallStatsReportEvent=i.GroupCallEvent=i.GroupCallTerminationReason=i.GroupCallType=i.GroupCallIntent=void 0;const r=e("../models/typed-event-emitter"),o=e("./callFeed"),s=e("./call"),a=e("../models/room-state"),c=e("../logger"),d=e("../ReEmitter"),l=e("./callEventTypes"),u=e("../@types/event"),h=e("./callEventHandler"),f=e("./groupCallEventHandler"),p=e("../utils"),g=e("./stats/groupCallStats"),v=e("./stats/statsReport");var m,y,b,S,_,E;!function(e){e.Ring="m.ring",e.Prompt="m.prompt",e.Room="m.room"}(i.GroupCallIntent||(i.GroupCallIntent={})),function(e){e.Video="m.video",e.Voice="m.voice"}(m=i.GroupCallType||(i.GroupCallType={})),function(e){e.CallEnded="call_ended"}(y=i.GroupCallTerminationReason||(i.GroupCallTerminationReason={})),function(e){e.GroupCallStateChanged="group_call_state_changed",e.ActiveSpeakerChanged="active_speaker_changed",e.CallsChanged="calls_changed",e.UserMediaFeedsChanged="user_media_feeds_changed",e.ScreenshareFeedsChanged="screenshare_feeds_changed",e.LocalScreenshareStateChanged="local_screenshare_state_changed",e.LocalMuteStateChanged="local_mute_state_changed",e.ParticipantsChanged="participants_changed",e.Error="group_call_error"}(b=i.GroupCallEvent||(i.GroupCallEvent={})),function(e){e.ConnectionStats="GroupCall.connection_stats",e.ByteSentStats="GroupCall.byte_sent_stats"}(S=i.GroupCallStatsReportEvent||(i.GroupCallStatsReportEvent={})),function(e){e.NoUserMedia="no_user_media",e.UnknownDevice="unknown_device",e.PlaceCallFailed="place_call_failed"}(_=i.GroupCallErrorCode||(i.GroupCallErrorCode={}));class w extends Error{constructor(e,t,i){super(i?t+": "+i:t),this.code=e}}i.GroupCallError=w;i.GroupCallUnknownDeviceError=class extends w{constructor(e){super(_.UnknownDevice,"No device found for "+e),this.userId=e}};class T extends Error{constructor(){super("Cannot unmute: another user is speaking")}}i.OtherUserSpeakingError=T,function(e){e.LocalCallFeedUninitialized="local_call_feed_uninitialized",e.InitializingLocalCallFeed="initializing_local_call_feed",e.LocalCallFeedInitialized="local_call_feed_initialized",e.Entered="entered",e.Ended="ended"}(E=i.GroupCallState||(i.GroupCallState={}));const I=36e5;function R(e){var t;return(null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId)||e.invitee||null}class M extends r.TypedEventEmitter{constructor(e,t,i,n,r,l,h,f,p){var m,y;super(),this.client=e,this.room=t,this.type=i,this.isPtt=n,this.intent=r,this.dataChannelsEnabled=h,this.dataChannelOptions=f,this.activeSpeakerInterval=1e3,this.retryCallInterval=5e3,this.participantTimeout=15e3,this.pttMaxTransmitTime=2e4,this.userMediaFeeds=[],this.screenshareFeeds=[],this.calls=new Map,this.callHandlers=new Map,this.retryCallCounts=new Map,this.transmitTimer=null,this.participantsExpirationTimer=null,this.resendMemberStateTimer=null,this.initWithAudioMuted=!1,this.initWithVideoMuted=!1,this.onConnectionStats=e=>{this.emit(S.ConnectionStats,{report:e})},this.onByteSentStats=e=>{this.emit(S.ByteSentStats,{report:e})},this._state=E.LocalCallFeedUninitialized,this._participants=new Map,this._creationTs=null,this._enteredViaAnotherSession=!1,this.onIncomingCall=e=>{var t,i;if(e.roomId!==this.room.roomId)return;if(e.state!==s.CallState.Ringing)return void c.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`);if(!e.groupCallId||e.groupCallId!==this.groupCallId)return c.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`),void e.reject();const n=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId;if(void 0===n)return void c.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`);const r=null!==(i=this.calls.get(n))&&void 0!==i?i:new Map,o=r.get(e.getOpponentDeviceId());if((null==o?void 0:o.callId)===e.callId)return;c.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${n}, callId=${e.callId})`),o&&o.hangup(s.CallErrorCode.Replaced,!1),this.initCall(e);const a=this.getLocalFeeds().map((e=>e.clone()));if(!this.callExpected(e))for(const e of a)(0,s.setTracksEnabled)(e.stream.getAudioTracks(),!1),(0,s.setTracksEnabled)(e.stream.getVideoTracks(),!1);e.answerWithCallFeeds(a),r.set(e.getOpponentDeviceId(),e),this.calls.set(n,r),this.emit(b.CallsChanged,this.calls)},this.onRetryCallLoop=()=>{var e;let t=!1;for(const[{userId:i},n]of this.participants){const r=this.calls.get(i);let o=this.retryCallCounts.get(i);for(const[s,a]of n){const n=null==r?void 0:r.get(s),c=null!==(e=null==o?void 0:o.get(s))&&void 0!==e?e:0;(null==n?void 0:n.getOpponentSessionId())!==a.sessionId&&this.wantsOutgoingCall(i,s)&&c<3&&(void 0===o&&(o=new Map,this.retryCallCounts.set(i,o)),o.set(s,c+1),t=!0)}}t&&this.placeOutgoingCalls()},this.onCallFeedsChanged=e=>{const t=R(e),i=e.getOpponentDeviceId();if(!t)throw new Error("Cannot change call feeds without user id");const n=this.getUserMediaFeed(t,i),r=e.remoteUsermediaFeed;r!==n&&(!n&&r?this.addUserMediaFeed(r):n&&r?this.replaceUserMediaFeed(n,r):n&&!r&&this.removeUserMediaFeed(n));const o=this.getScreenshareFeed(t,i),s=e.remoteScreensharingFeed;s!==o&&(!o&&s?this.addScreenshareFeed(s):o&&s?this.replaceScreenshareFeed(o,s):o&&!s&&this.removeScreenshareFeed(o))},this.onCallStateChanged=(e,t,i)=>{var n;if(t===s.CallState.Ended)return;const r=this.localCallFeed.isAudioMuted();e.localUsermediaStream&&e.isMicrophoneMuted()!==r&&e.setMicrophoneMuted(r);const o=this.localCallFeed.isVideoMuted();e.localUsermediaStream&&e.isLocalVideoMuted()!==o&&e.setLocalVideoMuted(o);const a=null===(n=e.getOpponentMember())||void 0===n?void 0:n.userId;if(t===s.CallState.Connected&&a){const t=this.retryCallCounts.get(a);null==t||t.delete(e.getOpponentDeviceId()),0===(null==t?void 0:t.size)&&this.retryCallCounts.delete(a)}},this.onCallHangup=e=>{var t,i;if(e.hangupReason===s.CallErrorCode.Replaced)return;const n=null!==(i=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId)&&void 0!==i?i:this.room.getMember(e.invitee).userId,r=this.calls.get(n);(null==r?void 0:r.get(e.getOpponentDeviceId()))===e&&(this.disposeCall(e,e.hangupReason),r.delete(e.getOpponentDeviceId()),0===r.size&&this.calls.delete(n),this.emit(b.CallsChanged,this.calls))},this.onCallReplaced=(e,t)=>{const i=e.getOpponentMember().userId;let n=this.calls.get(i);void 0===n&&(n=new Map,this.calls.set(i,n)),e.hangup(s.CallErrorCode.Replaced,!1),this.initCall(t),n.set(e.getOpponentDeviceId(),t),this.emit(b.CallsChanged,this.calls)},this.onActiveSpeakerLoop=()=>{let e,t;for(const i of this.userMediaFeeds){if(i.isLocal()&&this.userMediaFeeds.length>1)continue;const n=i.speakingVolumeSamples.reduce(((e,t)=>e+Math.max(t,o.SPEAKING_THRESHOLD)))/i.speakingVolumeSamples.length;(!e||n>e)&&(e=n,t=i)}t&&this.activeSpeaker!==t&&e&&e>o.SPEAKING_THRESHOLD&&(this.activeSpeaker=t,this.emit(b.ActiveSpeakerChanged,this.activeSpeaker))},this.onRoomState=()=>this.updateParticipants(),this.onParticipantsChanged=()=>{this.forEachCall((e=>{const t=this.callExpected(e);for(const i of e.getLocalFeeds())(0,s.setTracksEnabled)(i.stream.getAudioTracks(),!i.isAudioMuted()&&t),(0,s.setTracksEnabled)(i.stream.getVideoTracks(),!i.isVideoMuted()&&t)})),this.state===E.Entered&&this.placeOutgoingCalls()},this.onStateChanged=(e,t)=>{e!==E.Entered&&t!==E.Entered&&e!==E.Ended||(this.updateParticipants(),this.updateMemberState().catch((e=>c.logger.error(`GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices"`,e))))},this.onLocalFeedsChanged=()=>{this.state===E.Entered&&this.updateMemberState().catch((e=>c.logger.error(`GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`,e)))},this.reEmitter=new d.ReEmitter(this),this.groupCallId=null!=l?l:(0,s.genCallID)(),this.creationTs=null!==(y=null===(m=t.currentState.getStateEvents(u.EventType.GroupCallPrefix,this.groupCallId))||void 0===m?void 0:m.getTs())&&void 0!==y?y:null,this.updateParticipants(),t.on(a.RoomStateEvent.Update,this.onRoomState),this.on(b.ParticipantsChanged,this.onParticipantsChanged),this.on(b.GroupCallStateChanged,this.onStateChanged),this.on(b.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!p;const _=this.client.getUserId()||"unknown";this.stats=new g.GroupCallStats(this.groupCallId,_),this.stats.reports.on(v.StatsReport.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(v.StatsReport.BYTE_SENT_STATS,this.onByteSentStats)}create(){return n(this,void 0,void 0,(function*(){this.creationTs=Date.now(),this.client.groupCallEventHandler.groupCalls.set(this.room.roomId,this),this.client.emit(f.GroupCallEventHandlerEvent.Outgoing,this);const e={"m.intent":this.intent,"m.type":this.type,"io.element.ptt":this.isPtt,dataChannelsEnabled:this.dataChannelsEnabled,dataChannelOptions:this.dataChannelsEnabled?this.dataChannelOptions:void 0};return yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallPrefix,e,this.groupCallId),this}))}get state(){return this._state}set state(e){const t=this._state;e!==t&&(this._state=e,this.emit(b.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){const t=this._participants,i=(e,t)=>e.sessionId===t.sessionId&&e.screensharing===t.screensharing;(0,p.mapsEqual)(e,t,((e,t)=>(0,p.mapsEqual)(e,t,i)))||(this._participants=e,this.emit(b.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(const t of this.calls.values())for(const i of t.values())e(i)}getLocalFeeds(){const e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return null!==(t=null===(e=this.participants.get(this.room.getMember(this.client.getUserId())))||void 0===e?void 0:e.has(this.client.getDeviceId()))&&void 0!==t&&t}callExpected(e){var t;const i=R(e),n=null===i?null:this.room.getMember(i),r=e.getOpponentDeviceId();return null!==n&&void 0!==r&&void 0!==(null===(t=this.participants.get(n))||void 0===t?void 0:t.get(r))}initLocalCallFeed(){return n(this,void 0,void 0,(function*(){if(this.state!==E.LocalCallFeedUninitialized)throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`);if(this.state=E.InitializingLocalCallFeed,this.initCallFeedPromise)return this.initCallFeedPromise;try{this.initCallFeedPromise=this.initLocalCallFeedInternal(),yield this.initCallFeedPromise}finally{this.initCallFeedPromise=void 0}}))}initLocalCallFeedInternal(){return n(this,void 0,void 0,(function*(){let e;c.logger.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`);try{e=yield this.client.getMediaHandler().getUserMediaStream(!0,this.type===m.Video)}catch(t){if(!this.allowCallWithoutVideoAndAudio)throw this.state=E.LocalCallFeedUninitialized,t;e=new MediaStream}if(this._state!==E.InitializingLocalCallFeed)throw this.client.getMediaHandler().stopUserMediaStream(e),new Error("Group call disposed while gathering media stream");const t=new o.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:l.SDPStreamMetadataPurpose.Usermedia,audioMuted:this.initWithAudioMuted||0===e.getAudioTracks().length||this.isPtt,videoMuted:this.initWithVideoMuted||0===e.getVideoTracks().length});(0,s.setTracksEnabled)(e.getAudioTracks(),!t.isAudioMuted()),(0,s.setTracksEnabled)(e.getVideoTracks(),!t.isVideoMuted()),this.localCallFeed=t,this.addUserMediaFeed(t),this.state=E.LocalCallFeedInitialized}))}updateLocalUsermediaStream(e){return n(this,void 0,void 0,(function*(){if(this.localCallFeed){const t=this.localCallFeed.stream;this.localCallFeed.setNewStream(e);const i=this.localCallFeed.isAudioMuted(),n=this.localCallFeed.isVideoMuted();c.logger.log(`GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${t.id}, newStreamId=${e.id}, micShouldBeMuted=${i}, vidShouldBeMuted=${n})`),(0,s.setTracksEnabled)(e.getAudioTracks(),!i),(0,s.setTracksEnabled)(e.getVideoTracks(),!n),this.client.getMediaHandler().stopUserMediaStream(t)}}))}enter(){return n(this,void 0,void 0,(function*(){if(this.state===E.LocalCallFeedUninitialized)yield this.initLocalCallFeed();else if(this.state!==E.LocalCallFeedInitialized)throw new Error(`Cannot enter call in the "${this.state}" state`);c.logger.log(`GroupCall ${this.groupCallId} enter() running`),this.state=E.Entered,this.client.on(h.CallEventHandlerEvent.Incoming,this.onIncomingCall);for(const e of this.client.callEventHandler.calls.values())this.onIncomingCall(e);this.retryCallLoopInterval=setInterval(this.onRetryCallLoop,this.retryCallInterval),this.activeSpeaker=void 0,this.onActiveSpeakerLoop(),this.activeSpeakerLoopInterval=setInterval(this.onActiveSpeakerLoop,this.activeSpeakerInterval)}))}dispose(){this.localCallFeed&&(this.removeUserMediaFeed(this.localCallFeed),this.localCallFeed=void 0),this.localScreenshareFeed&&(this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0),this.client.getMediaHandler().stopAllStreams(),null!==this.transmitTimer&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),void 0!==this.retryCallLoopInterval&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===E.Entered&&(this.forEachCall((e=>e.hangup(s.CallErrorCode.UserHangup,!1))),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(h.CallEventHandlerEvent.Incoming,this.onIncomingCall),this.stats.stop())}leave(){this.dispose(),this.state=E.LocalCallFeedUninitialized}terminate(e=!0){return n(this,void 0,void 0,(function*(){if(this.dispose(),this.room.off(a.RoomStateEvent.Update,this.onRoomState),this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId),this.client.emit(f.GroupCallEventHandlerEvent.Ended,this),this.state=E.Ended,e){const e=this.room.currentState.getStateEvents(u.EventType.GroupCallPrefix,this.groupCallId);yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallPrefix,Object.assign(Object.assign({},e.getContent()),{"m.terminated":y.CallEnded}),this.groupCallId)}}))}isLocalVideoMuted(){return!this.localCallFeed||this.localCallFeed.isVideoMuted()}isMicrophoneMuted(){return!this.localCallFeed||this.localCallFeed.isAudioMuted()}setMicrophoneMuted(e){return n(this,void 0,void 0,(function*(){if(!e&&!(yield this.client.getMediaHandler().hasAudioDevice()))return!1;const t=!e&&this.isPtt;this.isPtt&&(!e&&this.isMicrophoneMuted()?this.transmitTimer=setTimeout((()=>{this.setMicrophoneMuted(!0)}),this.pttMaxTransmitTime):e&&!this.isMicrophoneMuted()&&(null!==this.transmitTimer&&clearTimeout(this.transmitTimer),this.transmitTimer=null)),this.forEachCall((t=>{var i;return null===(i=t.localUsermediaFeed)||void 0===i?void 0:i.setAudioVideoMuted(e,null)}));const i=()=>n(this,void 0,void 0,(function*(){const e=[];this.forEachCall((t=>e.push(t.sendMetadataUpdate()))),yield Promise.all(e).catch((e=>c.logger.info(`GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`,e)))}));if(t&&(yield i()),this.localCallFeed){c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${e})`);try{if(!e){if(null===(yield this.client.getMediaHandler().getUserMediaStream(!0,!this.localCallFeed.isVideoMuted())))return c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${e}`),!1}}catch(t){return c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device or permission to receive local stream, muted=${e}`),!1}this.localCallFeed.setAudioVideoMuted(e,null),(0,s.setTracksEnabled)(this.localCallFeed.stream.getAudioTracks(),!e)}else c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${e})`),this.initWithAudioMuted=e;return this.forEachCall((t=>(0,s.setTracksEnabled)(t.localUsermediaFeed.stream.getAudioTracks(),!e&&this.callExpected(t)))),this.emit(b.LocalMuteStateChanged,e,this.isLocalVideoMuted()),t||(yield i()),!0}))}setLocalVideoMuted(e){return n(this,void 0,void 0,(function*(){if(!e&&!(yield this.client.getMediaHandler().hasVideoDevice()))return!1;if(this.localCallFeed){c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${e})`);try{const t=yield this.client.getMediaHandler().getUserMediaStream(!0,!e);yield this.updateLocalUsermediaStream(t),this.localCallFeed.setAudioVideoMuted(null,e),(0,s.setTracksEnabled)(this.localCallFeed.stream.getVideoTracks(),!e)}catch(t){return c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${e}`),!1}}else c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${e})`),this.initWithVideoMuted=e;const t=[];return this.forEachCall((i=>t.push(i.setLocalVideoMuted(e)))),yield Promise.all(t),this.forEachCall((t=>(0,s.setTracksEnabled)(t.localUsermediaFeed.stream.getVideoTracks(),!e&&this.callExpected(t)))),this.emit(b.LocalMuteStateChanged,this.isMicrophoneMuted(),e),!0}))}setScreensharingEnabled(e,t={}){return n(this,void 0,void 0,(function*(){if(e===this.isScreensharing())return e;if(!e)return this.forEachCall((e=>{e.localScreensharingFeed&&e.removeLocalFeed(e.localScreensharingFeed)})),this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0,this.emit(b.LocalScreenshareStateChanged,!1,void 0,void 0),!1;try{c.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`);const e=yield this.client.getMediaHandler().getScreensharingStream(t);for(const t of e.getTracks()){const e=()=>{this.setScreensharingEnabled(!1),t.removeEventListener("ended",e)};t.addEventListener("ended",e)}return c.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`),this.localDesktopCapturerSourceId=t.desktopCapturerSourceId,this.localScreenshareFeed=new o.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:l.SDPStreamMetadataPurpose.Screenshare,audioMuted:!1,videoMuted:!1}),this.addScreenshareFeed(this.localScreenshareFeed),this.emit(b.LocalScreenshareStateChanged,!0,this.localScreenshareFeed,this.localDesktopCapturerSourceId),this.forEachCall((e=>e.pushLocalFeed(this.localScreenshareFeed.clone()))),!0}catch(e){if(t.throwOnFail)throw e;return c.logger.error(`GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`,e),this.emit(b.Error,new w(_.NoUserMedia,"Failed to get screen-sharing stream: ",e)),!1}}))}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){const i=this.client.getUserId(),n=this.client.getDeviceId();return e>=i&&(e!==i||t>n)}placeOutgoingCalls(){var e;let t=!1;for(const[{userId:i},n]of this.participants){const r=null!==(e=this.calls.get(i))&&void 0!==e?e:new Map;for(const[e,o]of n){const n=r.get(e);if((null==n?void 0:n.getOpponentSessionId())!==o.sessionId&&this.wantsOutgoingCall(i,e)){t=!0,void 0!==n&&(c.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${i}, deviceId=${e}, callId=${n.callId})`),n.hangup(s.CallErrorCode.NewSession,!1));const a=(0,s.createNewMatrixCall)(this.client,this.room.roomId,{invitee:i,opponentDeviceId:e,opponentSessionId:o.sessionId,groupCallId:this.groupCallId});null===a?(c.logger.error(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${i}, device=${e})`),r.delete(e)):(this.initCall(a),r.set(e,a),c.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${i}, deviceId=${e}, sessionId=${o.sessionId})`),a.placeCallWithCallFeeds(this.getLocalFeeds().map((e=>e.clone())),o.screensharing).then((()=>{this.dataChannelsEnabled&&a.createDataChannel("datachannel",this.dataChannelOptions)})).catch((t=>{c.logger.warn(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${i})`,t),t instanceof s.CallError&&t.code===_.UnknownDevice?this.emit(b.Error,t):this.emit(b.Error,new w(_.PlaceCallFailed,`Failed to place call to ${i}`)),a.hangup(s.CallErrorCode.SignallingFailed,!1),r.get(e)===a&&r.delete(e)})))}}r.size>0?this.calls.set(i,r):this.calls.delete(i)}t&&this.emit(b.CallsChanged,this.calls)}getMemberStateEvents(e){return void 0===e?this.room.currentState.getStateEvents(u.EventType.GroupCallMemberPrefix):this.room.currentState.getStateEvents(u.EventType.GroupCallMemberPrefix,e)}initCall(e){const t=R(e);if(!t)throw new Error("Cannot init call without user id");const i=()=>this.onCallFeedsChanged(e),n=(t,i)=>this.onCallStateChanged(e,t,i),r=this.onCallHangup,o=t=>this.onCallReplaced(e,t);let a=this.callHandlers.get(t);void 0===a&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:i,onCallStateChanged:n,onCallHangup:r,onCallReplaced:o}),e.on(s.CallEvent.FeedsChanged,i),e.on(s.CallEvent.State,n),e.on(s.CallEvent.Hangup,r),e.on(s.CallEvent.Replaced,o),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(s.CallEvent)),e.initStats(this.stats),i()}disposeCall(e,t){const i=R(e),n=e.getOpponentDeviceId();if(!i)throw new Error("Cannot dispose call without user id");const r=this.callHandlers.get(i),{onCallFeedsChanged:o,onCallStateChanged:a,onCallHangup:c,onCallReplaced:d}=r.get(n);if(e.removeListener(s.CallEvent.FeedsChanged,o),e.removeListener(s.CallEvent.State,a),e.removeListener(s.CallEvent.Hangup,c),e.removeListener(s.CallEvent.Replaced,d),r.delete(i),0===r.size&&this.callHandlers.delete(i),e.hangupReason===s.CallErrorCode.Replaced)return;const l=this.getUserMediaFeed(i,n);l&&this.removeUserMediaFeed(l);const u=this.getScreenshareFeed(i,n);u&&this.removeScreenshareFeed(u)}getUserMediaFeed(e,t){return this.userMediaFeeds.find((i=>i.userId===e&&i.deviceId===t))}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){const i=this.userMediaFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===i)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(i,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){const t=this.userMediaFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===t)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(b.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find((i=>i.userId===e&&i.deviceId===t))}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){const i=this.screenshareFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===i)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(i,1,t),e.dispose(),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){const t=this.screenshareFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===t)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){const e=this.room.getMember(this.client.getUserId());if(!e)return void c.logger.warn(`GroupCall ${this.groupCallId} updateParticipants() tried to update participants before local room member is available`);if(null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===E.Ended)return void(this.participants=new Map);const t=new Map,i=Date.now(),n=this.state===E.Entered||this.enteredViaAnotherSession;let r=1/0;for(const e of this.getMemberStateEvents()){const o=this.room.getMember(e.getStateKey()),s=e.getContent(),a=(Array.isArray(s["m.calls"])?s["m.calls"]:[]).find((e=>e["m.call_id"]===this.groupCallId));let c=(Array.isArray(null==a?void 0:a["m.devices"])?a["m.devices"]:[]).filter((e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>i&&Array.isArray(e.feeds)));if(n||(null==o?void 0:o.userId)!==this.client.getUserId()||(c=c.filter((e=>e.device_id!==this.client.getDeviceId()))),c.length>0&&"join"===(null==o?void 0:o.membership)){const e=new Map;t.set(o,e);for(const t of c)e.set(t.device_id,{sessionId:t.session_id,screensharing:t.feeds.some((e=>e.purpose===l.SDPStreamMetadataPurpose.Screenshare))}),t.expires_ts<r&&(r=t.expires_ts)}}if(n){let i=t.get(e);void 0===i&&(i=new Map,t.set(e,i)),i.has(this.client.getDeviceId())||i.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some((e=>e.purpose===l.SDPStreamMetadataPurpose.Screenshare))})}this.participants=t,r<1/0&&(this.participantsExpirationTimer=setTimeout((()=>this.updateParticipants()),r-i))}updateDevices(e,t=!1){var i;return n(this,void 0,void 0,(function*(){const n=Date.now(),r=this.client.getUserId(),o=this.getMemberStateEvents(r),s=null!==(i=null==o?void 0:o.getContent())&&void 0!==i?i:{},a=Array.isArray(s["m.calls"])?s["m.calls"]:[];let c=null;const d=[];for(const e of a)e["m.call_id"]===this.groupCallId?c=e:d.push(e);null===c&&(c={});const l=(Array.isArray(c["m.devices"])?c["m.devices"]:[]).filter((e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>n&&Array.isArray(e.feeds))),h=e(l);if(null===h)return;const f=[...d];h.length>0&&f.push(Object.assign(Object.assign({},c),{"m.call_id":this.groupCallId,"m.devices":h}));const p={"m.calls":f};yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallMemberPrefix,p,r,{keepAlive:t})}))}addDeviceToMemberState(){return n(this,void 0,void 0,(function*(){yield this.updateDevices((e=>[...e.filter((e=>e.device_id!==this.client.getDeviceId())),{device_id:this.client.getDeviceId(),session_id:this.client.getSessionId(),expires_ts:Date.now()+I,feeds:this.getLocalFeeds().map((e=>({purpose:e.purpose})))}]))}))}updateMemberState(){return n(this,void 0,void 0,(function*(){null!==this.resendMemberStateTimer&&(clearInterval(this.resendMemberStateTimer),this.resendMemberStateTimer=null),this.state===E.Entered?(yield this.addDeviceToMemberState(),this.resendMemberStateTimer=setInterval((()=>n(this,void 0,void 0,(function*(){c.logger.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state"`);try{yield this.addDeviceToMemberState()}catch(e){c.logger.error(`GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`,e)}}))),27e5)):yield this.updateDevices((e=>e.filter((e=>e.device_id!==this.client.getDeviceId()))),!0)}))}cleanMemberState(){return n(this,void 0,void 0,(function*(){const{devices:e}=yield this.client.getDevices(),t=new Map(e.map((e=>[e.device_id,e])));yield this.updateDevices((e=>{const i=e.filter((e=>{const i=t.get(e.device_id);return void 0!==(null==i?void 0:i.last_seen_ts)&&!(e.device_id===this.client.getDeviceId()&&this.state!==E.Entered&&!this.enteredViaAnotherSession)}));return i.length===e.length?null:i}))}))}getGroupCallStats(){return this.stats}}i.GroupCall=M},{"../@types/event":306,"../ReEmitter":317,"../logger":374,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./call":418,"./callEventHandler":419,"./callEventTypes":420,"./callFeed":421,"./groupCallEventHandler":423,"./stats/groupCallStats":427,"./stats/statsReport":432}],423:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCallEventHandler=i.GroupCallEventHandlerEvent=void 0;const r=e("../client"),o=e("./groupCall"),s=e("../models/room-state"),a=e("../logger"),c=e("../@types/event"),d=e("../sync");var l;!function(e){e.Incoming="GroupCall.incoming",e.Outgoing="GroupCall.outgoing",e.Ended="GroupCall.ended",e.Participants="GroupCall.participants"}(l=i.GroupCallEventHandlerEvent||(i.GroupCallEventHandlerEvent={}));i.GroupCallEventHandler=class{constructor(e){this.client=e,this.groupCalls=new Map,this.roomDeferreds=new Map,this.onRoomsChanged=e=>{this.createGroupCallForRoom(e)},this.onRoomStateChanged=(e,t)=>{if(e.getType()===c.EventType.GroupCallPrefix){const i=e.getStateKey(),n=e.getContent(),r=this.groupCalls.get(t.roomId);r||n["m.terminated"]||e.isRedacted()?r&&r.groupCallId===i?n["m.terminated"]||e.isRedacted()?r.terminate(!1):n["m.type"]!==r.type&&a.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=${t.roomId})`):r&&r.groupCallId!==i&&a.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=${t.roomId})`):this.createGroupCallFromRoomStateEvent(e)}}}start(){return n(this,void 0,void 0,(function*(){this.client.getSyncState()!==d.SyncState.Syncing&&(a.logger.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise((e=>{const t=()=>{if(this.client.getSyncState()===d.SyncState.Syncing)return this.client.off(r.ClientEvent.Sync,t),e()};this.client.on(r.ClientEvent.Sync,t)})));const e=this.client.getRooms();for(const t of e)this.createGroupCallForRoom(t);this.client.on(r.ClientEvent.Room,this.onRoomsChanged),this.client.on(s.RoomStateEvent.Events,this.onRoomStateChanged)}))}stop(){this.client.removeListener(s.RoomStateEvent.Events,this.onRoomStateChanged)}getRoomDeferred(e){let t=this.roomDeferreds.get(e);if(void 0===t){let i;t={prom:new Promise((e=>{i=e}))},t.resolve=i,this.roomDeferreds.set(e,t)}return t}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find((t=>t.groupCallId===e))}createGroupCallForRoom(e){const t=e.currentState.getStateEvents(c.EventType.GroupCallPrefix),i=t.sort(((e,t)=>t.getTs()-e.getTs()));for(const n of i){if(!n.getContent()["m.terminated"]&&!n.isRedacted()){a.logger.debug(`GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=${n.getStateKey()}, ts=${n.getTs()}, roomId=${e.roomId}, numOfPossibleCalls=${t.length})`),this.createGroupCallFromRoomStateEvent(n);break}}a.logger.info(`GroupCallEventHandler createGroupCallForRoom() processed room (roomId=${e.roomId})`),this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){const t=e.getRoomId(),i=e.getContent(),n=this.client.getRoom(t);if(!n)return void a.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=${t})`);const r=e.getStateKey(),s=i["m.type"];if(!Object.values(o.GroupCallType).includes(s))return void a.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=${s}, roomId=${t})`);const c=i["m.intent"];if(!Object.values(o.GroupCallIntent).includes(c))return void a.logger.warn(`Received invalid group call intent (type=${s}, roomId=${t})`);const d=Boolean(i["io.element.ptt"]);let u;if((null==i?void 0:i.dataChannelsEnabled)&&(null==i?void 0:i.dataChannelOptions)){const{ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:r}=i.dataChannelOptions;u={ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:r}}const h=new o.GroupCall(this.client,n,s,d,c,r,(null==i?void 0:i.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,u,this.client.isVoipWithNoMediaAllowed);return this.groupCalls.set(n.roomId,h),this.client.emit(l.Incoming,h),h}}},{"../@types/event":306,"../client":321,"../logger":374,"../models/room-state":390,"../sync":414,"./groupCall":422}],424:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MediaHandler=i.MediaHandlerEvent=void 0;const r=e("../models/typed-event-emitter"),o=e("../webrtc/groupCall"),s=e("../logger");var a;!function(e){e.LocalStreamsChanged="local_streams_changed"}(a=i.MediaHandlerEvent||(i.MediaHandlerEvent={}));class c extends r.TypedEventEmitter{constructor(e){super(),this.client=e,this.userMediaStreams=[],this.screensharingStreams=[]}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}setAudioInput(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setAudioInput() running (deviceId=${e})`),this.audioInput!==e&&(this.audioInput=e,yield this.updateLocalUsermediaStreams())}))}setAudioSettings(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(e)})`),this.audioSettings=Object.assign({},e),yield this.updateLocalUsermediaStreams()}))}setVideoInput(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setVideoInput() running (deviceId=${e})`),this.videoInput!==e&&(this.videoInput=e,yield this.updateLocalUsermediaStreams())}))}setMediaInputs(e,t){return n(this,void 0,void 0,(function*(){s.logger.log(`MediaHandler setMediaInputs() running (audioInput: ${e} videoInput: ${t})`),this.audioInput=e,this.videoInput=t,yield this.updateLocalUsermediaStreams()}))}updateLocalUsermediaStreams(){return n(this,void 0,void 0,(function*(){if(0===this.userMediaStreams.length)return;const e=new Map;for(const t of this.client.callEventHandler.calls.values())e.set(t.callId,{audio:t.hasLocalUserMediaAudioTrack,video:t.hasLocalUserMediaVideoTrack});for(const e of this.userMediaStreams){s.logger.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${e.id})`);for(const t of e.getTracks())t.stop()}this.userMediaStreams=[],this.localUserMediaStream=void 0;for(const t of this.client.callEventHandler.calls.values()){if(t.callHasEnded()||!e.has(t.callId))continue;const{audio:i,video:n}=e.get(t.callId);s.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${t.callId})`);const r=yield this.getUserMediaStream(i,n);t.callHasEnded()||(yield t.updateLocalUsermediaStream(r))}for(const e of this.client.groupCallEventHandler.groupCalls.values()){if(!e.localCallFeed)continue;s.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${e.groupCallId})`);const t=yield this.getUserMediaStream(!0,e.type===o.GroupCallType.Video);e.state!==o.GroupCallState.Ended&&(yield e.updateLocalUsermediaStream(t))}this.emit(a.LocalStreamsChanged)}))}hasAudioDevice(){return n(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind)).length>0}catch(e){return s.logger.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}))}hasVideoDevice(){return n(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).length>0}catch(e){return s.logger.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}))}getUserMediaStream(e,t,i=!0){return n(this,void 0,void 0,(function*(){return this.getMediaStreamPromise?this.getMediaStreamPromise=this.getMediaStreamPromise.then((()=>this.getUserMediaStreamInternal(e,t,i))):this.getMediaStreamPromise=this.getUserMediaStreamInternal(e,t,i),this.getMediaStreamPromise}))}getUserMediaStreamInternal(e,t,i){var r,o,c,d,l;return n(this,void 0,void 0,(function*(){const n=e&&(yield this.hasAudioDevice()),u=t&&(yield this.hasVideoDevice());let h,f=!0;if(this.localUserMediaStream?(n!==this.localUserMediaStream.getAudioTracks().length>0&&(f=!1),u!==this.localUserMediaStream.getVideoTracks().length>0&&(f=!1),n&&(null===(o=null===(r=this.localUserMediaStream.getAudioTracks()[0])||void 0===r?void 0:r.getSettings())||void 0===o?void 0:o.deviceId)!==this.audioInput&&(f=!1),u&&(null===(d=null===(c=this.localUserMediaStream.getVideoTracks()[0])||void 0===c?void 0:c.getSettings())||void 0===d?void 0:d.deviceId)!==this.videoInput&&(f=!1)):f=!1,f){if(h=this.localUserMediaStream.clone(),s.logger.log(`MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${null===(l=this.localUserMediaStream)||void 0===l?void 0:l.id} newStreamId=${h.id} shouldRequestAudio=${n} shouldRequestVideo=${u})`),!n)for(const e of h.getAudioTracks())h.removeTrack(e);if(!u)for(const e of h.getVideoTracks())h.removeTrack(e)}else{const e=this.getUserMediaContraints(n,u);h=yield navigator.mediaDevices.getUserMedia(e),s.logger.log(`MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${h.id}, shouldRequestAudio=${n}, shouldRequestVideo=${u}, constraints=${JSON.stringify(e)})`);for(const e of h.getTracks()){const t=e.getSettings();"audio"===e.kind?this.audioInput=t.deviceId:"video"===e.kind&&(this.videoInput=t.deviceId)}i&&(this.localUserMediaStream=h)}return i&&this.userMediaStreams.push(h),this.emit(a.LocalStreamsChanged),h}))}stopUserMediaStream(e){s.logger.log(`MediaHandler stopUserMediaStream() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.userMediaStreams.indexOf(e);-1!==t&&(s.logger.debug(`MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${e.id})`,e.id),this.userMediaStreams.splice(t,1)),this.emit(a.LocalStreamsChanged),this.localUserMediaStream===e&&(this.localUserMediaStream=void 0)}getScreensharingStream(e={},t=!0){return n(this,void 0,void 0,(function*(){let i;if(0===this.screensharingStreams.length){const t=this.getScreenshareContraints(e);e.desktopCapturerSourceId?(s.logger.debug(`MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(e)})`),i=yield navigator.mediaDevices.getUserMedia(t)):(s.logger.debug(`MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(e)})`),i=yield navigator.mediaDevices.getDisplayMedia(t))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];s.logger.log(`MediaHandler getScreensharingStream() cloning (streamId=${e.id})`),i=e.clone()}return t&&this.screensharingStreams.push(i),this.emit(a.LocalStreamsChanged),i}))}stopScreensharingStream(e){s.logger.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.screensharingStreams.indexOf(e);-1!==t&&(s.logger.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${e.id})`),this.screensharingStreams.splice(t,1)),this.emit(a.LocalStreamsChanged)}stopAllStreams(){for(const e of this.userMediaStreams){s.logger.log(`MediaHandler stopAllStreams() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop()}for(const e of this.screensharingStreams)for(const t of e.getTracks())t.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(a.LocalStreamsChanged)}getUserMediaContraints(e,t){const i=!!navigator.webkitGetUserMedia;return{audio:!!e&&{deviceId:this.audioInput?{ideal:this.audioInput}:void 0,autoGainControl:this.audioSettings?{ideal:this.audioSettings.autoGainControl}:void 0,echoCancellation:this.audioSettings?{ideal:this.audioSettings.echoCancellation}:void 0,noiseSuppression:this.audioSettings?{ideal:this.audioSettings.noiseSuppression}:void 0},video:!!t&&{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:i?{exact:640}:{ideal:640},height:i?{exact:360}:{ideal:360}}}}getScreenshareContraints(e){const{desktopCapturerSourceId:t,audio:i}=e;return t?{audio:null!=i&&i,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:null!=i&&i,video:!0}}}i.MediaHandler=c},{"../logger":374,"../models/typed-event-emitter":395,"../webrtc/groupCall":422}],425:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionStats=void 0;i.ConnectionStats=class{constructor(){this.bandwidth={},this.bitrate={},this.packetLoss={},this.transport=[]}}},{}],426:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionStatsReporter=void 0;i.ConnectionStatsReporter=class{static buildBandwidthReport(e){const t=e.availableIncomingBitrate,i=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:i?Math.round(i/1e3):0}}}},{}],427:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCallStats=void 0;const n=e("./statsReportGatherer"),r=e("./statsReportEmitter");i.GroupCallStats=class{constructor(e,t,i=1e4){this.groupCallId=e,this.userId=t,this.interval=i,this.gatherers=new Map,this.reports=new r.StatsReportEmitter}start(){void 0===this.timer&&(this.timer=setInterval((()=>{this.processStats()}),this.interval))}stop(){void 0!==this.timer&&(clearInterval(this.timer),this.gatherers.forEach((e=>e.stopProcessingStats())))}hasStatsReportGatherer(e){return this.gatherers.has(e)}addStatsReportGatherer(e,t,i){return!this.hasStatsReportGatherer(e)&&(this.gatherers.set(e,new n.StatsReportGatherer(e,t,i,this.reports)),!0)}removeStatsReportGatherer(e){return this.gatherers.delete(e)}getStatsReportGatherer(e){return this.hasStatsReportGatherer(e)?this.gatherers.get(e):void 0}processStats(){this.gatherers.forEach((e=>e.processStats(this.groupCallId,this.userId)))}}},{"./statsReportEmitter":434,"./statsReportGatherer":435}],428:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaSsrcHandler=void 0;const n=e("sdp-transform");i.MediaSsrcHandler=class{constructor(){this.ssrcToMid={local:new Map,remote:new Map}}findMidBySsrc(e,t){let i;return this.ssrcToMid[t].forEach(((t,n)=>{t.find((t=>t==e))&&(i=n)})),i}parse(e,t){const i=(0,n.parse)(e),r=new Map;i.media.forEach((e=>{var t;if(e.mid&&"video"===e.type||"audio"===e.type){const i=[];null===(t=e.ssrcs)||void 0===t||t.forEach((e=>{"cname"===e.attribute&&i.push(`${e.id}`)})),r.set(`${e.mid}`,i)}})),this.ssrcToMid[t]=r}getSsrcToMidMap(e){return this.ssrcToMid[e]}}},{"sdp-transform":253}],429:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackHandler=void 0;i.MediaTrackHandler=class{constructor(e){this.pc=e}getLocalTracks(e){return this.pc.getTransceivers().filter((e=>"sendonly"===e.currentDirection||"sendrecv"===e.currentDirection)).filter((e=>null!==e.sender)).map((e=>e.sender)).map((e=>e.track)).filter((t=>null!==t&&t.kind===e))}getTackById(e){return this.pc.getTransceivers().map((t=>null!==(null==t?void 0:t.sender.track)&&t.sender.track.id===e?t.sender.track:null!==(null==t?void 0:t.receiver.track)&&t.receiver.track.id===e?t.receiver.track:void 0)).find((e=>void 0!==e))}getLocalTrackIdByMid(e){const t=this.pc.getTransceivers().find((t=>t.mid===e));if(void 0!==t&&t.sender&&t.sender.track)return t.sender.track.id}getRemoteTrackIdByMid(e){const t=this.pc.getTransceivers().find((t=>t.mid===e));if(void 0!==t&&t.receiver&&t.receiver.track)return t.receiver.track.id}getActiveSimulcastStreams(){return 3}}},{}],430:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackStats=void 0;i.MediaTrackStats=class{constructor(e,t,i){this.trackId=e,this.type=t,this.kind=i,this.loss={packetsTotal:0,packetsLost:0,isDownloadStream:!1},this.bitrate={download:0,upload:0},this.resolution={width:-1,height:-1},this.framerate=0,this.codec=""}getType(){return this.type}setLoss(e){this.loss=e}getLoss(){return this.loss}setResolution(e){this.resolution=e}getResolution(){return this.resolution}setFramerate(e){this.framerate=e}getFramerate(){return this.framerate}setBitrate(e){this.bitrate=e}getBitrate(){return this.bitrate}setCodec(e){return this.codec=e,!0}getCodec(){return this.codec}resetBitrate(){this.bitrate={download:0,upload:0}}}},{}],431:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackStatsHandler=void 0;const n=e("./mediaTrackStats");i.MediaTrackStatsHandler=class{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,this.track2stats=new Map}findTrack2Stats(e,t){let i;if(e.trackIdentifier)i=e.trackIdentifier;else if(e.mid)i="remote"===t?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){if(!this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t))return;i="remote"===t?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(!i)return;let r=this.track2stats.get(i);if(!r){const e=this.mediaTrackHandler.getTackById(i);if(void 0===e)return;{const o="audio"===e.kind?e.kind:"video";r=new n.MediaTrackStats(i,t,o),this.track2stats.set(i,r)}}return r}findLocalVideoTrackStats(e){if(0!==this.mediaTrackHandler.getLocalTracks("video").length)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}}},{"./mediaTrackStats":430}],432:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReport=void 0,function(e){e.CONNECTION_STATS="StatsReport.connection_stats",e.BYTE_SENT_STATS="StatsReport.byte_sent_stats"}(i.StatsReport||(i.StatsReport={}))},{}],433:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportBuilder=void 0;class n{static build(e){const t={},i={download:0,upload:0},r={download:0,upload:0};let o=0,s=0;const a={local:new Map,remote:new Map},c={local:new Map,remote:new Map},d={local:new Map,remote:new Map};let l=0,u=0,h=0,f=0;for(const[t,n]of e){const e=n.getLoss(),p=e.isDownloadStream?"download":"upload";i[p]+=e.packetsTotal,r[p]+=e.packetsLost,o+=n.getBitrate().download,s+=n.getBitrate().upload,"audio"===n.kind?(l+=n.getBitrate().download,u+=n.getBitrate().upload):(h+=n.getBitrate().download,f+=n.getBitrate().upload),a[n.getType()].set(t,n.getResolution()),c[n.getType()].set(t,n.getFramerate()),d[n.getType()].set(t,n.getCodec()),n.resetBitrate()}return t.bitrate={upload:s,download:o},t.bitrate.audio={upload:u,download:l},t.bitrate.video={upload:f,download:h},t.packetLoss={total:n.calculatePacketLoss(r.download+r.upload,i.download+i.upload),download:n.calculatePacketLoss(r.download,i.download),upload:n.calculatePacketLoss(r.upload,i.upload)},t.framerate=c,t.resolution=a,t.codec=d,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}i.StatsReportBuilder=n},{}],434:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportEmitter=void 0;const n=e("../../models/typed-event-emitter"),r=e("./statsReport");class o extends n.TypedEventEmitter{emitByteSendReport(e){this.emit(r.StatsReport.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(r.StatsReport.CONNECTION_STATS,e)}}i.StatsReportEmitter=o},{"../../models/typed-event-emitter":395,"./statsReport":432}],435:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportGatherer=void 0;const r=e("./connectionStats"),o=e("./connectionStatsReporter"),s=e("./transportStatsReporter"),a=e("./media/mediaSsrcHandler"),c=e("./media/mediaTrackHandler"),d=e("./media/mediaTrackStatsHandler"),l=e("./trackStatsReporter"),u=e("./statsReportBuilder"),h=e("./statsValueFormatter");i.StatsReportGatherer=class{constructor(e,t,i,n,o=!0){this.callId=e,this.remoteUserId=t,this.pc=i,this.emitter=n,this.isFocus=o,this.isActive=!0,this.connectionStats=new r.ConnectionStats,i.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new d.MediaTrackStatsHandler(new a.MediaSsrcHandler,new c.MediaTrackHandler(i))}processStats(e,t){return n(this,void 0,void 0,(function*(){if(this.isActive){const i=this.pc.getStats();if("function"==typeof(null==i?void 0:i.then))return i.then((i=>{this.currentStatsReport="function"==typeof(null==i?void 0:i.result)?i.result():i;try{this.processStatsReport(e,t)}catch(e){return this.isActive=!1,!1}return this.previousStatsReport=this.currentStatsReport,!0})).catch((e=>(this.handleError(e),!1)));this.isActive=!1}return Promise.resolve(!1)}))}processStatsReport(e,t){var i;const n=new Map;null===(i=this.currentStatsReport)||void 0===i||i.forEach((e=>{const t=this.previousStatsReport?this.previousStatsReport.get(e.id):null;if("candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state)this.connectionStats.bandwidth=o.ConnectionStatsReporter.buildBandwidthReport(e),this.connectionStats.transport=s.TransportStatsReporter.buildReport(this.currentStatsReport,e,this.connectionStats.transport,this.isFocus);else if("inbound-rtp"===e.type||"outbound-rtp"===e.type){const i=this.trackStats.findTrack2Stats(e,"inbound-rtp"===e.type?"remote":"local");if(!i)return;t&&l.TrackStatsReporter.buildPacketsLost(i,e,t),"inbound-rtp"===e.type?(l.TrackStatsReporter.buildFramerateResolution(i,e),t&&l.TrackStatsReporter.buildBitrateReceived(i,e,t)):t&&(n.set(i.trackId,h.StatsValueFormatter.getNonNegativeValue(e.bytesSent)),l.TrackStatsReporter.buildBitrateSend(i,e,t)),l.TrackStatsReporter.buildCodec(this.currentStatsReport,i,e)}else if("track"===e.type&&"video"===e.kind&&!e.remoteSource){const i=this.trackStats.findLocalVideoTrackStats(e);if(!i)return;l.TrackStatsReporter.buildFramerateResolution(i,e),l.TrackStatsReporter.calculateSimulcastFramerate(i,e,t,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}})),this.emitter.emitByteSendReport(n),this.processAndEmitReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1}processAndEmitReport(){const e=u.StatsReportBuilder.build(this.trackStats.getTrack2stats());this.connectionStats.bandwidth=e.bandwidth,this.connectionStats.bitrate=e.bitrate,this.connectionStats.packetLoss=e.packetLoss,this.emitter.emitConnectionStatsReport(Object.assign(Object.assign({},e),{transport:this.connectionStats.transport})),this.connectionStats.transport=[]}stopProcessingStats(){}onSignalStateChange(){"stable"===this.pc.signalingState&&(this.pc.currentRemoteDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp,"remote"),this.pc.currentLocalDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp,"local"))}}},{"./connectionStats":425,"./connectionStatsReporter":426,"./media/mediaSsrcHandler":428,"./media/mediaTrackHandler":429,"./media/mediaTrackStatsHandler":431,"./statsReportBuilder":433,"./statsValueFormatter":436,"./trackStatsReporter":437,"./transportStatsReporter":438}],436:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsValueFormatter=void 0;i.StatsValueFormatter=class{static getNonNegativeValue(e){let t=e;return"number"!=typeof t&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}},{}],437:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackStatsReporter=void 0;const n=e("./statsValueFormatter");class r{static buildFramerateResolution(e,t){const i={height:t.frameHeight,width:t.frameWidth},n=t.framesPerSecond;i.height&&i.width&&e.setResolution(i),e.setFramerate(Math.round(n||0))}static calculateSimulcastFramerate(e,t,i,n){let r=e.getFramerate();if(!r){if(i){const e=t.timestamp-i.timestamp;if(e>0&&t.framesSent){r=(t.framesSent-i.framesSent)/e*1e3}}if(!r)return}r=n?Math.round(r/n):0,e.setFramerate(r)}static buildCodec(e,t,i){const n=null==e?void 0:e.get(i.codecId);if(n){const e=n.mimeType.split("/")[1];e&&t.setCodec(e)}}static buildBitrateReceived(e,t,i){e.setBitrate({download:r.calculateBitrate(t.bytesReceived,i.bytesReceived,t.timestamp,i.timestamp),upload:0})}static buildBitrateSend(e,t,i){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,i.bytesSent,t.timestamp,i.timestamp)})}static buildPacketsLost(e,t,i){const r="outbound-rtp"===t.type?"packetsSent":"packetsReceived";let o=t[r];(!o||o<0)&&(o=0);const s=n.StatsValueFormatter.getNonNegativeValue(i[r]),a=Math.max(0,o-s),c=n.StatsValueFormatter.getNonNegativeValue(t.packetsLost),d=n.StatsValueFormatter.getNonNegativeValue(i.packetsLost),l=Math.max(0,c-d);e.setLoss({packetsTotal:a+l,packetsLost:l,isDownloadStream:"outbound-rtp"!==t.type})}static calculateBitrate(e,t,i,r){const o=n.StatsValueFormatter.getNonNegativeValue(e),s=n.StatsValueFormatter.getNonNegativeValue(t),a=Math.max(0,o-s),c=i-r;let d=0;return c>0&&(d=Math.round(8*a/c)),d}}i.TrackStatsReporter=r},{"./statsValueFormatter":436}],438:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TransportStatsReporter=void 0;i.TransportStatsReporter=class{static buildReport(e,t,i,n){const r=null==e?void 0:e.get(t.localCandidateId),o=null==e?void 0:e.get(t.remoteCandidateId);if(o&&r){const e=`${void 0!==o.ip?o.ip:o.address}:${o.port}`,s=`${void 0!==r.ip?r.ip:r.address}:${r.port}`,a=o.protocol;i.some((t=>t.ip===e&&t.type===a&&t.localIp===s))||i.push({ip:e,type:a,localIp:s,isFocus:n,localCandidateType:r.candidateType,remoteCandidateType:o.candidateType,networkType:r.networkType,rtt:t.currentRoundTripTime?1e3*t.currentRoundTripTime:NaN})}return i}}},{}]},{},[320]);
\ No newline at end of file |