123456789101112131415161718 |
- !function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var d=n[s]={exports:{}};t[s][0].call(d.exports,(function(e){return r(t[s][1][e]||e)}),d,d.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<i.length;s++)r(i[s]);return r}({1:[function(e,t,n){t.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},t.exports.__esModule=!0,t.exports.default=t.exports},{}],2:[function(e,t,n){t.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.exports.__esModule=!0,t.exports.default=t.exports},{}],3:[function(e,t,n){var i=e("./setPrototypeOf.js"),r=e("./isNativeReflectConstruct.js");function o(e,n,s){return r()?(t.exports=o=Reflect.construct.bind(),t.exports.__esModule=!0,t.exports.default=t.exports):(t.exports=o=function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&i(o,n.prototype),o},t.exports.__esModule=!0,t.exports.default=t.exports),o.apply(null,arguments)}t.exports=o,t.exports.__esModule=!0,t.exports.default=t.exports},{"./isNativeReflectConstruct.js":9,"./setPrototypeOf.js":11}],4:[function(e,t,n){function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}t.exports=function(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e},t.exports.__esModule=!0,t.exports.default=t.exports},{}],5:[function(e,t,n){function i(e){return t.exports=i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},t.exports.__esModule=!0,t.exports.default=t.exports,i(e)}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},{}],6:[function(e,t,n){var i=e("./setPrototypeOf.js");t.exports=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&&i(e,t)},t.exports.__esModule=!0,t.exports.default=t.exports},{"./setPrototypeOf.js":11}],7:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],8:[function(e,t,n){t.exports=function(e){return-1!==Function.toString.call(e).indexOf("[native code]")},t.exports.__esModule=!0,t.exports.default=t.exports},{}],9:[function(e,t,n){t.exports=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}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],10:[function(e,t,n){var i=e("./typeof.js").default,r=e("./assertThisInitialized.js");t.exports=function(e,t){if(t&&("object"===i(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return r(e)},t.exports.__esModule=!0,t.exports.default=t.exports},{"./assertThisInitialized.js":1,"./typeof.js":12}],11:[function(e,t,n){function i(e,n){return t.exports=i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},t.exports.__esModule=!0,t.exports.default=t.exports,i(e,n)}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},{}],12:[function(e,t,n){function i(e){return t.exports=i="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},t.exports.__esModule=!0,t.exports.default=t.exports,i(e)}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},{}],13:[function(e,t,n){var i=e("./getPrototypeOf.js"),r=e("./setPrototypeOf.js"),o=e("./isNativeFunction.js"),s=e("./construct.js");function a(e){var n="function"==typeof Map?new Map:void 0;return t.exports=a=function(e){if(null===e||!o(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return s(e,arguments,i(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),r(t,e)},t.exports.__esModule=!0,t.exports.default=t.exports,a(e)}t.exports=a,t.exports.__esModule=!0,t.exports.default=t.exports},{"./construct.js":3,"./getPrototypeOf.js":5,"./isNativeFunction.js":8,"./setPrototypeOf.js":11}],14:[function(e,t,n){"use strict";for(var i=/[\\\"\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 i.lastIndex=0,e.replace(i,(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="[",n="",i=0;i<e.length;++i)n+=t,t=",",n+=a(e[i]);return","!=t?"[]":n+"]"}(e):function(e){var t="{",n="",i=Object.keys(e);i.sort();for(var r=0;r<i.length;++r){var o=i[r];n+=t+'"'+s(o)+'":',t=",",n+=a(e[o])}return","!=t?"{}":n+"}"}(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}},{}],15:[function(e,t,n){"use strict";var i=e("safe-buffer").Buffer;t.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var r=0;r<e.length;r++){var o=e.charAt(r),s=o.charCodeAt(0);if(255!==t[s])throw new TypeError(o+" is ambiguous");t[s]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return i.alloc(0);for(var n=0,r=0,o=0;e[n]===c;)r++,n++;for(var s=(e.length-n)*l+1>>>0,d=new Uint8Array(s);e[n];){var u=t[e.charCodeAt(n)];if(255===u)return;for(var h=0,g=s-1;(0!==u||h<o)&&-1!==g;g--,h++)u+=a*d[g]>>>0,d[g]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");o=h,n++}for(var p=s-o;p!==s&&0===d[p];)p++;var f=i.allocUnsafe(r+(s-p));f.fill(0,0,r);for(var v=r;p!==s;)f[v++]=d[p++];return f}return{encode:function(t){if((Array.isArray(t)||t instanceof Uint8Array)&&(t=i.from(t)),!i.isBuffer(t))throw new TypeError("Expected Buffer");if(0===t.length)return"";for(var n=0,r=0,o=0,s=t.length;o!==s&&0===t[o];)o++,n++;for(var l=(s-o)*d+1>>>0,u=new Uint8Array(l);o!==s;){for(var h=t[o],g=0,p=l-1;(0!==h||g<r)&&-1!==p;p--,g++)h+=256*u[p]>>>0,u[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=g,o++}for(var f=l-r;f!==l&&0===u[f];)f++;for(var v=c.repeat(n);f<l;++f)v+=e.charAt(u[f]);return v},decodeUnsafe:u,decode:function(e){var t=u(e);if(t)return t;throw new Error("Non-base"+a+" character")}}}},{"safe-buffer":66}],16:[function(e,t,n){"use strict";n.byteLength=function(e){var t=l(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=l(e),s=i[0],a=i[1],c=new o(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),d=0,u=a>0?s-4:s;for(n=0;n<u;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===a&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,c[d++]=255&t);1===a&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(d(e,a,a+s>c?c:a+s));1===r?(t=e[n-1],o.push(i[t>>2]+i[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(i[t>>10]+i[t>>4&63]+i[t<<2&63]+"="));return o.join("")};for(var i=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a<c;++a)i[a]=s[a],r[s.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e,t,n){for(var r,o,s=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(i[(o=r)>>18&63]+i[o>>12&63]+i[o>>6&63]+i[63&o]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],17:[function(e,t,n){var i,r;i=this,r=function(){var e=XMLHttpRequest;if(!e)throw new Error("missing XMLHttpRequest");function t(o,s){if("function"!=typeof s)throw new Error("Bad callback given: "+s);if(!o)throw new Error("No options given");var a=o.onResponse;if((o="string"==typeof o?{uri:o}:JSON.parse(JSON.stringify(o))).onResponse=a,o.verbose&&(t.log=function(){var e,t,n={},o=["trace","debug","info","warn","error"];for(t=0;t<o.length;t++)n[e=o[t]]=i,"undefined"!=typeof console&&console&&console[e]&&(n[e]=r(console,e));return n}()),o.url&&(o.uri=o.url,delete o.url),!o.uri&&""!==o.uri)throw new Error("options.uri is a required argument");if("string"!=typeof o.uri)throw new Error("options.uri must be a string");for(var c=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],l=0;l<c.length;l++)if(o[c[l]])throw new Error("options."+c[l]+" is not supported");if(o.callback=s,o.method=o.method||"GET",o.headers=o.headers||{},o.body=o.body||null,o.timeout=o.timeout||t.DEFAULT_TIMEOUT,o.headers.host)throw new Error("Options.headers.host is not supported");o.json&&(o.headers.accept=o.headers.accept||"application/json","GET"!==o.method&&(o.headers["content-type"]="application/json"),"boolean"!=typeof o.json?o.body=JSON.stringify(o.json):"string"!=typeof o.body&&(o.body=JSON.stringify(o.body)));var d=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")};if(o.qs){var u="string"==typeof o.qs?o.qs:d(o.qs);-1!==o.uri.indexOf("?")?o.uri=o.uri+"&"+u:o.uri=o.uri+"?"+u}if(o.form){if("string"==typeof o.form)throw"form name unsupported";if("POST"===o.method){var h=(o.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(o.headers["content-type"]=h,h){case"application/x-www-form-urlencoded":o.body=d(o.form).replace(/%20/g,"+");break;case"multipart/form-data":var g=function(e){var t={};t.boundry="-------------------------------"+Math.floor(1e9*Math.random());var n=[];for(var i in e)e.hasOwnProperty(i)&&n.push("--"+t.boundry+'\nContent-Disposition: form-data; name="'+i+'"\n\n'+e[i]+"\n");return n.push("--"+t.boundry+"--"),t.body=n.join(""),t.length=t.body.length,t.type="multipart/form-data; boundary="+t.boundry,t}(o.form);o.body=g.body,o.headers["content-type"]=g.type;break;default:throw new Error("unsupported encoding:"+h)}}}return o.onResponse=o.onResponse||i,!0===o.onResponse&&(o.onResponse=s,o.callback=i),!o.headers.authorization&&o.auth&&(o.headers.authorization="Basic "+function(e){var t,n,i,r,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,l="",d=[];if(!e)return e;do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,n=o>>12&63,i=o>>6&63,r=63&o,d[c++]=s.charAt(t)+s.charAt(n)+s.charAt(i)+s.charAt(r)}while(a<e.length);switch(l=d.join(""),e.length%3){case 1:l=l.slice(0,-2)+"==";break;case 2:l=l.slice(0,-1)+"="}return l}(o.auth.username+":"+o.auth.password)),function(i){var r=new e,o=!1,s=function(e){var t,n=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;try{t=location.href}catch(e){(t=document.createElement("a")).href="",t=t.href}var i=n.exec(t.toLowerCase())||[],r=n.exec(e.toLowerCase());return!(!r||r[1]==i[1]&&r[2]==i[2]&&(r[3]||("http:"===r[1]?80:443))==(i[3]||("http:"===i[1]?80:443)))}(i.uri),a="withCredentials"in r;if(n+=1,r.seq_id=n,r.id=n+": "+i.method+" "+i.uri,r._id=r.id,s&&!a){var c=new Error("Browser does not support cross-origin request: "+i.uri);return c.cors="unsupported",i.callback(c,r)}function l(){o=!0;var e=new Error("ETIMEDOUT");return e.code="ETIMEDOUT",e.duration=i.timeout,t.log.error("Timeout",{id:r._id,milliseconds:i.timeout}),i.callback(e,r)}r.timeoutTimer=setTimeout(l,i.timeout);var d={response:!1,loading:!1,end:!1};return r.onreadystatechange=u,r.open(i.method,i.uri,!0),s&&(r.withCredentials=!!i.withCredentials),r.send(i.body),r;function u(n){if(o)return t.log.debug("Ignoring timed out state change",{state:r.readyState,id:r.id});if(t.log.debug("State change",{state:r.readyState,id:r.id,timed_out:o}),r.readyState===e.OPENED)for(var s in t.log.debug("Request started",{id:r.id}),i.headers)r.setRequestHeader(s,i.headers[s]);else r.readyState===e.HEADERS_RECEIVED?h():r.readyState===e.LOADING?(h(),g()):r.readyState===e.DONE&&(h(),g(),p())}function h(){if(!d.response){if(d.response=!0,t.log.debug("Got response",{id:r.id,status:r.status}),clearTimeout(r.timeoutTimer),r.statusCode=r.status,s&&0==r.statusCode){var e=new Error("CORS request rejected: "+i.uri);return e.cors="rejected",d.loading=!0,d.end=!0,i.callback(e,r)}i.onResponse(null,r)}}function g(){d.loading||(d.loading=!0,t.log.debug("Response body loading",{id:r.id}))}function p(){if(!d.end){if(d.end=!0,t.log.debug("Request done",{id:r.id}),r.body=r.responseText,i.json)try{r.body=JSON.parse(r.responseText)}catch(e){return i.callback(e,r)}i.callback(null,r,r.body)}}}(o)}t.log={trace:i,debug:i,info:i,warn:i,error:i};var n=0;function i(){}function r(e,t){return function(n,i){return"object"==typeof i&&(n+=" "+JSON.stringify(i)),e[t].call(e,n)}}return t.withCredentials=!1,t.DEFAULT_TIMEOUT=18e4,t.defaults=function(e,n){var i=function(t){return function(n,i){for(var r in n="string"==typeof n?{uri:n}:JSON.parse(JSON.stringify(n)),e)void 0===n[r]&&(n[r]=e[r]);return t(n,i)}},r=i(t);return r.get=i(t.get),r.post=i(t.post),r.put=i(t.put),r.head=i(t.head),r},["get","put","post","head"].forEach((function(e){var n=e.toUpperCase();t[e.toLowerCase()]=function(e){"string"==typeof e?e={method:n,uri:e}:(e=JSON.parse(JSON.stringify(e))).method=n;var i=[e].concat(Array.prototype.slice.apply(arguments,[1]));return t.apply(this,i)}})),t.couch=function(e,n){return"string"==typeof e&&(e={uri:e}),e.json=!0,e.body&&(e.json=e.body),delete e.body,n=n||i,t(e,(function(e,t,i){if(e)return n(e,t,i);if((t.statusCode<200||t.statusCode>299)&&i.error){for(var r in e=new Error("CouchDB error: "+(i.error.reason||i.error.error)),i)e[r]=i[r];return n(e,t,i)}return n(e,t,i)}))},t},"function"==typeof define&&define.amd?define([],r):"object"==typeof n?t.exports=r():i.returnExports=r()},{}],18:[function(e,t,n){},{}],19:[function(e,t,n){var i=e("base-x");t.exports=i("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},{"base-x":15}],20:[function(e,t,n){(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"),i=e("ieee754");n.Buffer=s,n.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},n.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,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){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 n=0|h(e,t),i=o(n),r=i.write(e,t);r!==n&&(i=i.slice(0,r));return i}(e,t);if(ArrayBuffer.isView(e))return d(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(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return function(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return i.__proto__=s.prototype,i}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return s.from(i,t,n);var r=function(e){if(s.isBuffer(e)){var t=0|u(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||F(e.length)?o(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(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,n);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 l(e){return c(e),o(e<0?0:0|u(e))}function d(e){for(var t=e.length<0?0:0|u(e.length),n=o(t),i=0;i<t;i+=1)n[i]=255&e[i];return n}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)||j(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 n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return B(e).length;default:if(r)return i?-1:L(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return O(this,t,n);case"utf8":case"utf-8":return w(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function p(e,t,n){var i=e[t];e[t]=e[n],e[n]=i}function f(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),F(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=s.from(t,i)),s.isBuffer(t))return 0===t.length?-1:v(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):v(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,n,i,r){var o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var d=-1;for(o=n;o<a;o++)if(l(e,o)===l(t,-1===d?0:o-d)){if(-1===d&&(d=o),o-d+1===c)return d*s}else-1!==d&&(o-=o-d),d=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){for(var u=!0,h=0;h<c;h++)if(l(e,o+h)!==l(t,h)){u=!1;break}if(u)return o}return-1}function y(e,t,n,i){n=Number(n)||0;var r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;var o=t.length;i>o/2&&(i=o/2);for(var s=0;s<i;++s){var a=parseInt(t.substr(2*s,2),16);if(F(a))return s;e[n+s]=a}return s}function m(e,t,n,i){return K(L(t,e.length-n),e,n,i)}function E(e,t,n,i){return K(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function S(e,t,n,i){return E(e,t,n,i)}function b(e,t,n,i){return K(B(t),e,n,i)}function _(e,t,n,i){return K(function(e,t){for(var n,i,r,o=[],s=0;s<e.length&&!((t-=2)<0);++s)i=(n=e.charCodeAt(s))>>8,r=n%256,o.push(r),o.push(i);return o}(t,e.length-n),e,n,i)}function T(e,n,i){return 0===n&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,i))}function w(e,t,n){n=Math.min(e.length,n);for(var i=[],r=t;r<n;){var o,s,a,c,l=e[r],d=null,u=l>239?4:l>223?3:l>191?2:1;if(r+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(o=e[r+1]))&&(c=(31&l)<<6|63&o)>127&&(d=c);break;case 3:o=e[r+1],s=e[r+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=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&l)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d),r+=u}return function(e){var t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);var n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=I));return n}(i)}n.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,n){return a(e,t,n)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(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 n=e.length,i=t.length,r=0,o=Math.min(n,i);r<o;++r)if(e[r]!==t[r]){n=e[r],i=t[r];break}return n<i?-1:i<n?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 n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var i=s.allocUnsafe(t),r=0;for(n=0;n<e.length;++n){var o=e[n];if(j(o,Uint8Array)&&(o=s.from(o)),!s.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,r),r+=o.length}return i},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?w(this,0,e):g.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=n.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,n,i,r){if(j(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===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(r>>>=0)-(i>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(o,a),l=this.slice(i,r),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){o=l[u],a=d[u];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return f(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return f(this,e,t,n,!1)},s.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}var r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return m(this,e,t,n);case"ascii":return E(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return b(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).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,n){var i="";n=Math.min(e.length,n);for(var r=t;r<n;++r)i+=String.fromCharCode(127&e[r]);return i}function k(e,t,n){var i="";n=Math.min(e.length,n);for(var r=t;r<n;++r)i+=String.fromCharCode(e[r]);return i}function O(e,t,n){var i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);for(var r="",o=t;o<n;++o)r+=N(e[o]);return r}function C(e,t,n){for(var i=e.slice(t,n),r="",o=0;o<i.length;o+=2)r+=String.fromCharCode(i[o]+256*i[o+1]);return r}function P(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,n,i,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(n+i>e.length)throw new RangeError("Index out of range")}function D(e,t,n,i,r,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function A(e,t,n,r,o){return t=+t,n>>>=0,o||D(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function x(e,t,n,r,o){return t=+t,n>>>=0,o||D(e,0,n,8),i.write(e,t,n,r,52,8),n+8}s.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var i=this.subarray(e,t);return i.__proto__=s.prototype,i},s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var i=this[e],r=1,o=0;++o<t&&(r*=256);)i+=this[e+o]*r;return i},s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var i=this[e+--t],r=1;t>0&&(r*=256);)i+=this[e+--t]*r;return i},s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(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||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var i=this[e],r=1,o=0;++o<t&&(r*=256);)i+=this[e+o]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*t)),i},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var i=t,r=1,o=this[e+--i];i>0&&(r*=256);)o+=this[e+--i]*r;return o>=(r*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(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||P(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||P(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||M(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,o=0;for(this[t]=255&e;++o<n&&(r*=256);)this[t+o]=e/r&255;return t+n},s.prototype.writeUIntBE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||M(this,e,t,n,Math.pow(2,8*n)-1,0);var r=n-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+n},s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||M(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,n){return e=+e,t>>>=0,n||M(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,n,i){if(e=+e,t>>>=0,!i){var r=Math.pow(2,8*n-1);M(this,e,t,n,r-1,-r)}var o=0,s=1,a=0;for(this[t]=255&e;++o<n&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+n},s.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var r=Math.pow(2,8*n-1);M(this,e,t,n,r-1,-r)}var o=n-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+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||M(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||M(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,n){return e=+e,t>>>=0,n||M(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,n){return A(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return A(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return x(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return x(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,i){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var r=i-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,i);else if(this===e&&n<t&&t<i)for(var o=r-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,i),t);return r},s.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!s.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){var r=e.charCodeAt(0);("utf8"===i&&r<128||"latin1"===i)&&(e=r)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var a=s.isBuffer(e)?e:s.from(e,i),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=a[o%c]}return this};var U=/[^+/0-9A-Za-z-_]/g;function N(e){return e<16?"0"+e.toString(16):e.toString(16)}function L(e,t){var n;t=t||1/0;for(var i=e.length,r=null,o=[],s=0;s<i;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function B(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,i){for(var r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function F(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":16,buffer:20,ieee754:31}],21:[function(e,t,n){"use strict";var i=e("get-intrinsic"),r=e("./"),o=r(i("String.prototype.indexOf"));t.exports=function(e,t){var n=i(e,!!t);return"function"==typeof n&&o(e,".prototype.")>-1?r(n):n}},{"./":22,"get-intrinsic":27}],22:[function(e,t,n){"use strict";var i=e("function-bind"),r=e("get-intrinsic"),o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||i.call(s,o),c=r("%Object.getOwnPropertyDescriptor%",!0),l=r("%Object.defineProperty%",!0),d=r("%Math.max%");if(l)try{l({},"a",{value:1})}catch(e){l=null}t.exports=function(e){var t=a(i,s,arguments);if(c&&l){var n=c(t,"length");n.configurable&&l(t,"length",{value:1+d(0,e.length-(arguments.length-1))})}return t};var u=function(){return a(i,o,arguments)};l?l(t.exports,"apply",{value:u}):t.exports.apply=u},{"function-bind":26,"get-intrinsic":27}],23:[function(e,t,n){
- /*!
- * content-type
- * Copyright(c) 2015 Douglas Christopher Wilson
- * MIT Licensed
- */
- "use strict";var i=/; *([!#$%&'*+.^_`|~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 l(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 d(e){this.parameters=Object.create(null),this.type=e}n.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,n=e.type;if(!n||!c.test(n))throw new TypeError("invalid type");var i=n;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");i+="; "+r+"="+l(t[r])}return i},n.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 n=t.indexOf(";"),r=-1!==n?t.substr(0,n).trim():t.trim();if(!c.test(r))throw new TypeError("invalid media type");var o=new d(r.toLowerCase());if(-1!==n){var a,l,u;for(i.lastIndex=n;l=i.exec(t);){if(l.index!==n)throw new TypeError("invalid parameter format");n+=l[0].length,a=l[1].toLowerCase(),'"'===(u=l[2])[0]&&(u=u.substr(1,u.length-2).replace(s,"$1")),o.parameters[a]=u}if(n!==t.length)throw new TypeError("invalid parameter format")}return o}},{}],24:[function(e,t,n){"use strict";var i,r="object"==typeof Reflect?Reflect:null,o=r&&"function"==typeof r.apply?r.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};i=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(n,i){function r(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}y(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&y(e,"error",t,n)}(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 l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function d(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,n,i){var r,o,s,a;if(l(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=i?[n,s]:[s,n]:i?s.unshift(n):s.push(n),(r=d(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 g(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=h.bind(i);return r.listener=n,i.wrapFn=r,r}function p(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):v(r,r.length)}function f(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function v(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function y(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);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){i.once&&e.removeEventListener(t,r),n(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 d(this)},a.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,r=this._events;if(void 0!==r)i=i&&void 0===r.error;else if(!i)return!1;if(i){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 l=c.length,d=v(c,l);for(n=0;n<l;++n)o(d[n],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 l(t),this.on(e,g(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,g(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,i,r,o,s;if(l(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,r=o;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,s||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var r,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(r=o[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);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):f.call(e,t)},a.prototype.listenerCount=f,a.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},{}],25:[function(e,t,n){"use strict";var i="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(i+t);for(var n,a=r.call(arguments,1),c=function(){if(this instanceof n){var i=t.apply(this,a.concat(r.call(arguments)));return Object(i)===i?i:this}return t.apply(e,a.concat(r.call(arguments)))},l=Math.max(0,t.length-a.length),d=[],u=0;u<l;u++)d.push("$"+u);if(n=Function("binder","return function ("+d.join(",")+"){ return binder.apply(this,arguments); }")(c),t.prototype){var h=function(){};h.prototype=t.prototype,n.prototype=new h,h.prototype=null}return n}},{}],26:[function(e,t,n){"use strict";var i=e("./implementation");t.exports=Function.prototype.bind||i},{"./implementation":25}],27:[function(e,t,n){"use strict";var i,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 l=function(){throw new s},d=c?function(){try{return l}catch(e){try{return c(arguments,"callee").get}catch(e){return l}}}():l,u=e("has-symbols")(),h=Object.getPrototypeOf||function(e){return e.__proto__},g={},p="undefined"==typeof Uint8Array?i:h(Uint8Array),f={"%AggregateError%":"undefined"==typeof AggregateError?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?i:ArrayBuffer,"%ArrayIteratorPrototype%":u?h([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":g,"%AsyncGenerator%":g,"%AsyncGeneratorFunction%":g,"%AsyncIteratorPrototype%":g,"%Atomics%":"undefined"==typeof Atomics?i:Atomics,"%BigInt%":"undefined"==typeof BigInt?i:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?i:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?i:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?i:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":g,"%Int8Array%":"undefined"==typeof Int8Array?i:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?i:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":u?h(h([][Symbol.iterator]())):i,"%JSON%":"object"==typeof JSON?JSON:i,"%Map%":"undefined"==typeof Map?i:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&u?h((new Map)[Symbol.iterator]()):i,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?i:Promise,"%Proxy%":"undefined"==typeof Proxy?i:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?i:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?i:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&u?h((new Set)[Symbol.iterator]()):i,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":u?h(""[Symbol.iterator]()):i,"%Symbol%":u?Symbol:i,"%SyntaxError%":r,"%ThrowTypeError%":d,"%TypedArray%":p,"%TypeError%":s,"%Uint8Array%":"undefined"==typeof Uint8Array?i:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?i:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?i:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?i:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?i:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?i:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?i:WeakSet},v=function e(t){var n;if("%AsyncFunction%"===t)n=a("async function () {}");else if("%GeneratorFunction%"===t)n=a("function* () {}");else if("%AsyncGeneratorFunction%"===t)n=a("async function* () {}");else if("%AsyncGenerator%"===t){var i=e("%AsyncGeneratorFunction%");i&&(n=i.prototype)}else if("%AsyncIteratorPrototype%"===t){var r=e("%AsyncGenerator%");r&&(n=h(r.prototype))}return f[t]=n,n},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"]},m=e("function-bind"),E=e("has"),S=m.call(Function.call,Array.prototype.concat),b=m.call(Function.apply,Array.prototype.splice),_=m.call(Function.call,String.prototype.replace),T=m.call(Function.call,String.prototype.slice),w=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,R=function(e){var t=T(e,0,1),n=T(e,-1);if("%"===t&&"%"!==n)throw new r("invalid intrinsic syntax, expected closing `%`");if("%"===n&&"%"!==t)throw new r("invalid intrinsic syntax, expected opening `%`");var i=[];return _(e,w,(function(e,t,n,r){i[i.length]=n?_(r,I,"$1"):t||e})),i},k=function(e,t){var n,i=e;if(E(y,i)&&(i="%"+(n=y[i])[0]+"%"),E(f,i)){var o=f[i];if(o===g&&(o=v(i)),void 0===o&&!t)throw new s("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:i,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');var n=R(e),i=n.length>0?n[0]:"",o=k("%"+i+"%",t),a=o.name,l=o.value,d=!1,u=o.alias;u&&(i=u[0],b(n,S([0,1],u)));for(var h=1,g=!0;h<n.length;h+=1){var p=n[h],v=T(p,0,1),y=T(p,-1);if(('"'===v||"'"===v||"`"===v||'"'===y||"'"===y||"`"===y)&&v!==y)throw new r("property names with quotes must have matching quotes");if("constructor"!==p&&g||(d=!0),E(f,a="%"+(i+="."+p)+"%"))l=f[a];else if(null!=l){if(!(p in l)){if(!t)throw new s("base intrinsic for "+e+" exists, but the property is not available.");return}if(c&&h+1>=n.length){var m=c(l,p);l=(g=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:l[p]}else g=E(l,p),l=l[p];g&&!d&&(f[a]=l)}}return l}},{"function-bind":26,has:30,"has-symbols":28}],28:[function(e,t,n){"use strict";var i="undefined"!=typeof Symbol&&Symbol,r=e("./shams");t.exports=function(){return"function"==typeof i&&("function"==typeof Symbol&&("symbol"==typeof i("foo")&&("symbol"==typeof Symbol("bar")&&r())))}},{"./shams":29}],29:[function(e,t,n){"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"),n=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(n))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 i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[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}},{}],30:[function(e,t,n){"use strict";var i=e("function-bind");t.exports=i.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":26}],31:[function(e,t,n){
- /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
- n.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,c=(1<<a)-1,l=c>>1,d=-7,u=n?r-1:0,h=n?-1:1,g=e[t+u];for(u+=h,o=g&(1<<-d)-1,g>>=-d,d+=a;d>0;o=256*o+e[t+u],u+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,i),o-=l}return(g?-1:1)*s*Math.pow(2,o-i)},n.write=function(e,t,n,i,r,o){var s,a,c,l=8*o-r-1,d=(1<<l)-1,u=d>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,g=i?0:o-1,p=i?1:-1,f=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=d):(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>=d?(a=0,s=d):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[n+g]=255&a,g+=p,a/=256,r-=8);for(s=s<<r|a,l+=r;l>0;e[n+g]=255&s,g+=p,s/=256,l-=8);e[n+g-p]|=128*f}},{}],32:[function(e,t,n){!function(e,n){"use strict";"function"==typeof define&&define.amd?define(n):"object"==typeof t&&t.exports?t.exports=n():e.log=n()}(this,(function(){"use strict";var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function r(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[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(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?r(console,i):void 0!==console.log?r(console,"log"):e)}function a(t,n){for(var r=0;r<i.length;r++){var o=i[r];this[o]=r<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function c(e,n,i){return function(){typeof console!==t&&(a.call(this,n,i),this[e].apply(this,arguments))}}function l(e,t,n){return s(e)||c.apply(this,arguments)}function d(e,n,r){var o,s=this;n=null==n?"WARN":n;var c="loglevel";function d(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(c)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===s.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),s.name=e,s.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},s.methodFactory=r||l,s.getLevel=function(){return o},s.setLevel=function(n,r){if("string"==typeof n&&void 0!==s.levels[n.toUpperCase()]&&(n=s.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=s.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==r&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+n+";"}catch(e){}}}(n),a.call(s,n,e),typeof console===t&&n<s.levels.SILENT)return"No console available for logging"},s.setDefaultLevel=function(e){n=e,d()||s.setLevel(e,!1)},s.resetLevel=function(){s.setLevel(n,!1),function(){if(typeof window!==t&&c){try{return void window.localStorage.removeItem(c)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},s.enableAll=function(e){s.setLevel(s.levels.TRACE,e)},s.disableAll=function(e){s.setLevel(s.levels.SILENT,e)};var u=d();null==u&&(u=n),s.setLevel(u,!1)}var u=new d,h={};u.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=h[e];return t||(t=h[e]=new d(e,u.getLevel(),u.methodFactory)),t};var g=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=g),u},u.getLoggers=function(){return h},u.default=u,u}))},{}],33:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.ExtensibleEvents=void 0;var i=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"),l=e("./interpreters/modern/MPoll");function d(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,r=function(){};return{s:r,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},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(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function h(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function g(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,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),g(this,"interpreters",new i.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,l.parseMPoll],[c.M_POLL_RESPONSE,l.parseMPoll],[c.M_POLL_END,l.parseMPoll]])),g(this,"_unknownInterpretOrder",[a.M_MESSAGE])}var t,n,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,n){e.defaultInstance.registerInterpreter(t,n)}},{key:"parse",value:function(t){return e.defaultInstance.parse(t)}}],(n=[{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,n=d(this.unknownInterpretOrder);try{for(n.s();!(t=n.n()).done;){var i=t.value;if(this.interpreters.has(i)){var o=this.interpreters.get(i)(e);if(o)return o}}}catch(e){n.e(e)}finally{n.f()}return null}catch(e){if(e instanceof r.InvalidEventError)return null;throw e}}}])&&h(t.prototype,n),u&&h(t,u),Object.defineProperty(t,"prototype",{writable:!1}),e}();n.ExtensibleEvents=p,g(p,"_defaultInstance",new p)},{"./InvalidEventError":35,"./NamespacedMap":36,"./events/message_types":45,"./events/poll_types":46,"./interpreters/legacy/MRoomMessage":49,"./interpreters/modern/MMessage":50,"./interpreters/modern/MPoll":51}],34:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0})},{}],35:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}function r(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function o(e,t){if(t&&("object"===i(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)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;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,i)}function i(){return a(e,arguments,d(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),l(i,e)},s(e)}function a(e,t,n){return a=c()?Reflect.construct:function(e,t,n){var i=[null];i.push.apply(i,t);var r=new(Function.bind.apply(e,i));return n&&l(r,n.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 l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function d(e){return d=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},d(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.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&&l(e,t)}(h,e);var t,n,i,s,a,u=(t=h,n=c(),function(){var e,i=d(t);if(n){var r=d(this).constructor;e=Reflect.construct(i,arguments,r)}else e=i.apply(this,arguments);return o(this,e)});function h(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,h),u.call(this,e)}return i=h,s&&r(i.prototype,s),a&&r(i,a),Object.defineProperty(i,"prototype",{writable:!1}),i}(s(Error));n.InvalidEventError=u},{}],36:[function(e,t,n){"use strict";function i(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},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(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}Object.defineProperty(n,"__esModule",{value:!0}),n.NamespacedMap=void 0;var s=function(){function e(t){var n,r,o;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),n=this,r="internalMap",o=new Map,r in n?Object.defineProperty(n,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):n[r]=o,t){var s,a=i(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,n,r;return t=e,(n=[{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,n),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();n.NamespacedMap=s},{}],37:[function(e,t,n){"use strict";function i(e){return i="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},i(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 n,i=a(e);if(t){var r=a(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return s(this,n)}}function s(e,t){if(t&&("object"===i(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)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function d(e,t,n){return t&&l(e.prototype,t),n&&l(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(n,"__esModule",{value:!0}),n.UnstableValue=n.NamespacedValue=void 0;var u=function(){function e(t,n){if(c(this,e),this.stable=t,this.unstable=n,!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}();n.NamespacedValue=u;var h=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)}(n,e);var t=o(n);function n(e,i){var r;if(c(this,n),!(r=t.call(this,e,i)).unstable)throw new Error("Unstable value must be supplied");return r}return d(n,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),n}(u);n.UnstableValue=h},{}],38:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.EmoteEvent=void 0;var r=e("./MessageEvent"),o=e("./message_types"),s=e("../utility/events");function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function l(){return l="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=d(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(arguments.length<3?e:n):r.value}},l.apply(this,arguments)}function d(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=p(e)););return e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function h(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 n,i=p(e);if(t){var r=p(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return g(this,n)}}function g(e,t){if(t&&("object"===i(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)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(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&&u(e,t)}(d,e);var t,n,i,r=h(d);function d(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,d),r.call(this,e)}return t=d,i=[{key:"from",value:function(e,t){var n;return new d({type:o.M_EMOTE.name,content:(n={},a(n,o.M_TEXT.name,e),a(n,o.M_HTML.name,t),n)})}}],(n=[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,s.isEventTypeSame)(e,o.M_EMOTE)||l(p(d.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=l(p(d.prototype),"serialize",this).call(this);return e.content.msgtype="m.emote",e}}])&&c(t.prototype,n),i&&c(t,i),Object.defineProperty(t,"prototype",{writable:!1}),d}(r.MessageEvent);n.EmoteEvent=f},{"../utility/events":54,"./MessageEvent":40,"./message_types":45}],39:[function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}Object.defineProperty(n,"__esModule",{value:!0}),n.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,n,r;return t=e,(n=[{key:"wireContent",get:function(){return this.wireFormat.content}}])&&i(t.prototype,n),r&&i(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();n.ExtensibleEvent=r},{}],40:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.MessageEvent=void 0;var r=e("./ExtensibleEvent"),o=e("../types"),s=e("../InvalidEventError"),a=e("./message_types"),c=e("../utility/events");function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l(Object(n),!0).forEach((function(t){y(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function u(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function h(e,t){return h=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},h(e,t)}function g(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 n,i=v(e);if(t){var r=v(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return p(this,n)}}function p(e,t){if(t&&("object"===i(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return f(e)}function f(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 y(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,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)}(l,e);var t,n,i,r=g(l);function l(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,l),y(f(t=r.call(this,e)),"text",void 0),y(f(t),"html",void 0),y(f(t),"renderings",void 0);var n=a.M_MESSAGE.findIn(t.wireContent),i=a.M_TEXT.findIn(t.wireContent),c=a.M_HTML.findIn(t.wireContent);if((0,o.isProvided)(n)){if(!Array.isArray(n))throw new s.InvalidEventError("m.message contents must be an array");var d=n.find((function(e){return!(0,o.isProvided)(e.mimetype)||"text/plain"===e.mimetype})),u=n.find((function(e){return"text/html"===e.mimetype}));if(!d)throw new s.InvalidEventError("m.message is missing a plain text representation");t.text=d.body,t.html=null==u?void 0:u.body,t.renderings=n}else{if(!(0,o.isOptionalAString)(i))throw new s.InvalidEventError("Missing textual representation for event");t.text=i,t.html=c,t.renderings=[{body:i,mimetype:"text/plain"}],t.html&&t.renderings.push({body:t.html,mimetype:"text/html"})}return t}return t=l,i=[{key:"from",value:function(e,t){var n;return new l({type:a.M_MESSAGE.name,content:(n={},y(n,a.M_TEXT.name,e),y(n,a.M_HTML.name,t),n)})}}],(n=[{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=y({},a.M_MESSAGE.name,this.renderings);if(1===this.renderings.length){var t=this.renderings[0].mimetype;void 0!==t&&"text/plain"!==t||(e=y({},a.M_TEXT.name,this.renderings[0].body))}return e}},{key:"serialize",value:function(){var e;return{type:"m.room.message",content:d(d({},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,n),i&&u(t,i),Object.defineProperty(t,"prototype",{writable:!1}),l}(r.ExtensibleEvent);n.MessageEvent=m},{"../InvalidEventError":35,"../types":52,"../utility/events":54,"./ExtensibleEvent":39,"./message_types":45}],41:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.NoticeEvent=void 0;var r=e("./MessageEvent"),o=e("./message_types"),s=e("../utility/events");function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function l(){return l="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=d(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(arguments.length<3?e:n):r.value}},l.apply(this,arguments)}function d(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=p(e)););return e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function h(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 n,i=p(e);if(t){var r=p(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return g(this,n)}}function g(e,t){if(t&&("object"===i(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)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(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&&u(e,t)}(d,e);var t,n,i,r=h(d);function d(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,d),r.call(this,e)}return t=d,i=[{key:"from",value:function(e,t){var n;return new d({type:o.M_NOTICE.name,content:(n={},a(n,o.M_TEXT.name,e),a(n,o.M_HTML.name,t),n)})}}],(n=[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,s.isEventTypeSame)(e,o.M_NOTICE)||l(p(d.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=l(p(d.prototype),"serialize",this).call(this);return e.content.msgtype="m.notice",e}}])&&c(t.prototype,n),i&&c(t,i),Object.defineProperty(t,"prototype",{writable:!1}),d}(r.MessageEvent);n.NoticeEvent=f},{"../utility/events":54,"./MessageEvent":40,"./message_types":45}],42:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.PollEndEvent=void 0;var r=e("./poll_types"),o=e("../InvalidEventError"),s=e("./relationship_types"),a=e("./MessageEvent"),c=e("./message_types"),l=e("../utility/events");function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?d(Object(n),!0).forEach((function(t){m(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function h(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function g(e,t){return g=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},g(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 n,i=y(e);if(t){var r=y(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return f(this,n)}}function f(e,t){if(t&&("object"===i(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return v(e)}function v(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function y(e){return y=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},y(e)}function m(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var E=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&&g(e,t)}(f,e);var t,n,i,d=p(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),m(v(t=d.call(this,e)),"pollEventId",void 0),m(v(t),"closingMessage",void 0);var n=t.wireContent["m.relates_to"];if(!s.REFERENCE_RELATION.matches(null==n?void 0:n.rel_type)||"string"!=typeof(null==n?void 0:n.event_id))throw new o.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=n.event_id,t.closingMessage=new a.MessageEvent(t.wireFormat),t}return t=f,i=[{key:"from",value:function(e,t){var n;return new f({type:r.M_POLL_END.name,content:(n={"m.relates_to":{rel_type:s.REFERENCE_RELATION.name,event_id:e}},m(n,r.M_POLL_END.name,{}),m(n,c.M_TEXT.name,t),n)})}}],(n=[{key:"isEquivalentTo",value:function(e){return(0,l.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,n),i&&h(t,i),Object.defineProperty(t,"prototype",{writable:!1}),f}(e("./ExtensibleEvent").ExtensibleEvent);n.PollEndEvent=E},{"../InvalidEventError":35,"../utility/events":54,"./ExtensibleEvent":39,"./MessageEvent":40,"./message_types":45,"./poll_types":46,"./relationship_types":47}],43:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.PollResponseEvent=void 0;var r=e("./ExtensibleEvent"),o=e("./poll_types"),s=e("../InvalidEventError"),a=e("./relationship_types"),c=e("../utility/events");function l(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(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 n,i=p(e);if(t){var r=p(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return h(this,n)}}function h(e,t){if(t&&("object"===i(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return g(e)}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}function f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var v=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)}(h,e);var t,n,i,r=u(h);function h(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,h),f(g(t=r.call(this,e)),"internalAnswerIds",void 0),f(g(t),"internalSpoiled",void 0),f(g(t),"pollEventId",void 0);var n=t.wireContent["m.relates_to"];if(!a.REFERENCE_RELATION.matches(null==n?void 0:n.rel_type)||"string"!=typeof(null==n?void 0:n.event_id))throw new s.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=n.event_id,t.validateAgainst(null),t}return t=h,i=[{key:"from",value:function(e,t){return new h({type:o.M_POLL_RESPONSE.name,content:f({"m.relates_to":{rel_type:a.REFERENCE_RELATION.name,event_id:t}},o.M_POLL_RESPONSE.name,{answers:e})})}}],(n=[{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 n=t.answers;if(n.some((function(e){return"string"!=typeof e}))||0===n.length)return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);if(e){if(n.some((function(t){return!e.answers.some((function(e){return e.id===t}))})))return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);n=n.slice(0,e.maxSelections)}this.internalAnswerIds=n,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:f({"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})}}}])&&l(t.prototype,n),i&&l(t,i),Object.defineProperty(t,"prototype",{writable:!1}),h}(r.ExtensibleEvent);n.PollResponseEvent=v},{"../InvalidEventError":35,"../utility/events":54,"./ExtensibleEvent":39,"./poll_types":46,"./relationship_types":47}],44:[function(e,t,n){"use strict";function i(e){return i="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},i(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.PollStartEvent=n.PollAnswerSubevent=void 0;var r=e("./poll_types"),o=e("./MessageEvent"),s=e("./message_types"),a=e("../InvalidEventError"),c=e("../NamespacedValue"),l=e("../utility/events"),d=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 n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))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 n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?g(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function f(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function y(e,t,n){return t&&v(e.prototype,t),n&&v(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function m(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)}function E(e,t){return E=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},E(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 n,i=T(e);if(t){var r=T(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return b(this,n)}}function b(e,t){if(t&&("object"===i(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _(e)}function _(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var I=function(e){m(n,e);var t=S(n);function n(e){var i;f(this,n),w(_(i=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 i.id=r,i}return y(n,[{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 n({type:"org.matrix.sdk.poll.answer",content:w({id:e},s.M_TEXT.name,t)})}}]),n}(o.MessageEvent);n.PollAnswerSubevent=I;var R=function(e){m(n,e);var t=S(n);function n(e){var i;f(this,n),w(_(i=t.call(this,e)),"question",void 0),w(_(i),"kind",void 0),w(_(i),"rawKind",void 0),w(_(i),"maxSelections",void 0),w(_(i),"answers",void 0);var s=r.M_POLL_START.findIn(i.wireContent);if(!s.question)throw new a.InvalidEventError("A question is required");if(i.question=new o.MessageEvent({type:"org.matrix.sdk.poll.question",content:s.question}),i.rawKind=s.kind,r.M_POLL_KIND_DISCLOSED.matches(i.rawKind)?i.kind=r.M_POLL_KIND_DISCLOSED:i.kind=r.M_POLL_KIND_UNDISCLOSED,i.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 I({type:"org.matrix.sdk.poll.answer",content:e})}));if(c.length<=0)throw new a.InvalidEventError("No answers available");return i.answers=c,i}return y(n,[{key:"isEquivalentTo",value:function(e){return(0,l.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,i){var o,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return new n({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:i instanceof c.NamespacedValue?i.name:i,max_selections:a,answers:t.map((function(e){return w({id:O()},s.M_TEXT.name,e)}))}),o)})}}]),n}(d.ExtensibleEvent);n.PollStartEvent=R;var k="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function O(){return u(Array(16)).map((function(){return k.charAt(Math.floor(Math.random()*k.length))})).join("")}},{"../InvalidEventError":35,"../NamespacedValue":37,"../utility/events":54,"./ExtensibleEvent":39,"./MessageEvent":40,"./message_types":45,"./poll_types":46}],45:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.M_TEXT=n.M_NOTICE=n.M_MESSAGE=n.M_HTML=n.M_EMOTE=void 0;var i=e("../NamespacedValue"),r=new i.UnstableValue("m.message","org.matrix.msc1767.message");n.M_MESSAGE=r;var o=new i.UnstableValue("m.text","org.matrix.msc1767.text");n.M_TEXT=o;var s=new i.UnstableValue("m.html","org.matrix.msc1767.html");n.M_HTML=s;var a=new i.UnstableValue("m.emote","org.matrix.msc1767.emote");n.M_EMOTE=a;var c=new i.UnstableValue("m.notice","org.matrix.msc1767.notice");n.M_NOTICE=c},{"../NamespacedValue":37}],46:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.M_POLL_START=n.M_POLL_RESPONSE=n.M_POLL_KIND_UNDISCLOSED=n.M_POLL_KIND_DISCLOSED=n.M_POLL_END=void 0;var i=e("../NamespacedValue"),r=new i.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");n.M_POLL_KIND_DISCLOSED=r;var o=new i.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");n.M_POLL_KIND_UNDISCLOSED=o;var s=new i.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");n.M_POLL_START=s;var a=new i.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");n.M_POLL_RESPONSE=a;var c=new i.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");n.M_POLL_END=c},{"../NamespacedValue":37}],47:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.REFERENCE_RELATION=void 0;var i=new(e("../NamespacedValue").NamespacedValue)("m.reference");n.REFERENCE_RELATION=i},{"../NamespacedValue":37}],48:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var i=e("./ExtensibleEvents");Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===i[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return i[e]}}))}));var r=e("./IPartialEvent");Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===r[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return r[e]}}))}));var o=e("./InvalidEventError");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===o[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return o[e]}}))}));var s=e("./NamespacedValue");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===s[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return s[e]}}))}));var a=e("./NamespacedMap");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===a[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=e("./types");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===c[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=e("./utility/MessageMatchers");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===l[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return l[e]}}))}));var d=e("./utility/events");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===d[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return d[e]}}))}));var u=e("./interpreters/legacy/MRoomMessage");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===u[e]||Object.defineProperty(n,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 n&&n[e]===h[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return h[e]}}))}));var g=e("./interpreters/modern/MPoll");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===g[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return g[e]}}))}));var p=e("./events/relationship_types");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===p[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return p[e]}}))}));var f=e("./events/ExtensibleEvent");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===f[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return f[e]}}))}));var v=e("./events/message_types");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===v[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return v[e]}}))}));var y=e("./events/MessageEvent");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===y[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return y[e]}}))}));var m=e("./events/EmoteEvent");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===m[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return m[e]}}))}));var E=e("./events/NoticeEvent");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===E[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return E[e]}}))}));var S=e("./events/poll_types");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===S[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return S[e]}}))}));var b=e("./events/PollStartEvent");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===b[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return b[e]}}))}));var _=e("./events/PollResponseEvent");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===_[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return _[e]}}))}));var T=e("./events/PollEndEvent");Object.keys(T).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in n&&n[e]===T[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return T[e]}}))}))},{"./ExtensibleEvents":33,"./IPartialEvent":34,"./InvalidEventError":35,"./NamespacedMap":36,"./NamespacedValue":37,"./events/EmoteEvent":38,"./events/ExtensibleEvent":39,"./events/MessageEvent":40,"./events/NoticeEvent":41,"./events/PollEndEvent":42,"./events/PollResponseEvent":43,"./events/PollStartEvent":44,"./events/message_types":45,"./events/poll_types":46,"./events/relationship_types":47,"./interpreters/legacy/MRoomMessage":49,"./interpreters/modern/MMessage":50,"./interpreters/modern/MPoll":51,"./types":52,"./utility/MessageMatchers":53,"./utility/events":54}],49:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.LEGACY_M_ROOM_MESSAGE=void 0,n.parseMRoomMessage=function(e){var t,n,s;if(a.M_MESSAGE.findIn(e.content)||a.M_TEXT.findIn(e.content))return new i.MessageEvent(e);var c,u=null===(t=e.content)||void 0===t?void 0:t.msgtype,h=null===(n=e.content)||void 0===n?void 0:n.body,g="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 i.MessageEvent(l(l({},e),{},{content:l(l({},e.content),{},(c={},d(c,a.M_TEXT.name,h),d(c,a.M_HTML.name,g),c))})):"m.notice"===u?new r.NoticeEvent(l(l({},e),{},{content:l(l({},e.content),{},(p={},d(p,a.M_TEXT.name,h),d(p,a.M_HTML.name,g),p))})):"m.emote"===u?new o.EmoteEvent(l(l({},e),{},{content:l(l({},e.content),{},(f={},d(f,a.M_TEXT.name,h),d(f,a.M_HTML.name,g),f))})):null;var p,f};var i=e("../../events/MessageEvent"),r=e("../../events/NoticeEvent"),o=e("../../events/EmoteEvent"),s=e("../../NamespacedValue"),a=e("../../events/message_types");function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){d(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function d(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var u=new s.NamespacedValue("m.room.message");n.LEGACY_M_ROOM_MESSAGE=u},{"../../NamespacedValue":37,"../../events/EmoteEvent":38,"../../events/MessageEvent":40,"../../events/NoticeEvent":41,"../../events/message_types":45}],50:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.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 i.MessageEvent(e)};var i=e("../../events/MessageEvent"),r=e("../../events/message_types"),o=e("../../events/EmoteEvent"),s=e("../../events/NoticeEvent")},{"../../events/EmoteEvent":38,"../../events/MessageEvent":40,"../../events/NoticeEvent":41,"../../events/message_types":45}],51:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.parseMPoll=function(e){if(i.M_POLL_START.matches(e.type))return new r.PollStartEvent(e);if(i.M_POLL_RESPONSE.matches(e.type))return new o.PollResponseEvent(e);if(i.M_POLL_END.matches(e.type))return new s.PollEndEvent(e);return null};var i=e("../../events/poll_types"),r=e("../../events/PollStartEvent"),o=e("../../events/PollResponseEvent"),s=e("../../events/PollEndEvent")},{"../../events/PollEndEvent":42,"../../events/PollResponseEvent":43,"../../events/PollStartEvent":44,"../../events/poll_types":46}],52:[function(e,t,n){"use strict";function i(e){return null!=e}Object.defineProperty(n,"__esModule",{value:!0}),n.isOptionalAString=function(e){return i(e)&&"string"==typeof e},n.isProvided=i},{}],53:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.LegacyMsgType=void 0,n.isEventLike=function(e,t){var n=e.content;if(t===i.Text)return r.M_MESSAGE.matches(e.type)||"m.room.message"===e.type&&"m.text"===(null==n?void 0:n.msgtype);if(t===i.Emote)return r.M_EMOTE.matches(e.type)||"m.room.message"===e.type&&"m.emote"===(null==n?void 0:n.msgtype);if(t===i.Notice)return r.M_NOTICE.matches(e.type)||"m.room.message"===e.type&&"m.notice"===(null==n?void 0:n.msgtype);return!1};var i,r=e("../events/message_types");n.LegacyMsgType=i,function(e){e.Text="m.text",e.Notice="m.notice",e.Emote="m.emote"}(i||(n.LegacyMsgType=i={}))},{"../events/message_types":45}],54:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.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 n=t,i=e;return n.matches(i.name)||n.matches(i.altName)}},{}],55:[function(e,t,n){var i="function"==typeof Map&&Map.prototype,r=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,o=i&&r&&"function"==typeof r.get?r.get:null,s=i&&Map.prototype.forEach,a="function"==typeof Set&&Set.prototype,c=Object.getOwnPropertyDescriptor&&a?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,l=a&&c&&"function"==typeof c.get?c.get:null,d=a&&Set.prototype.forEach,u="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,g="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,p=Boolean.prototype.valueOf,f=Object.prototype.toString,v=Function.prototype.toString,y=String.prototype.match,m=String.prototype.slice,E=String.prototype.replace,S=String.prototype.toUpperCase,b=String.prototype.toLowerCase,_=RegExp.prototype.test,T=Array.prototype.concat,w=Array.prototype.join,I=Array.prototype.slice,R=Math.floor,k="function"==typeof BigInt?BigInt.prototype.valueOf:null,O=Object.getOwnPropertySymbols,C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,P="function"==typeof Symbol&&"object"==typeof Symbol.iterator,M="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===P||"symbol")?Symbol.toStringTag:null,D=Object.prototype.propertyIsEnumerable,A=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function x(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||_.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var i=e<0?-R(-e):R(e);if(i!==e){var r=String(i),o=m.call(t,r.length+1);return E.call(r,n,"$&_")+"."+E.call(E.call(o,/([0-9]{3})/g,"$&_"),/_$/,"")}}return E.call(t,n,"$&_")}var U=e("./util.inspect").custom,N=U&&j(U)?U:null;function L(e,t,n){var i="double"===(n.quoteStyle||t)?'"':"'";return i+e+i}function B(e){return E.call(String(e),/"/g,""")}function K(e){return!("[object Array]"!==V(e)||M&&"object"==typeof e&&M in e)}function j(e){if(P)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!C)return!1;try{return C.call(e),!0}catch(e){}return!1}t.exports=function e(t,n,i,r){var a=n||{};if(q(a,"quoteStyle")&&"single"!==a.quoteStyle&&"double"!==a.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(q(a,"maxStringLength")&&("number"==typeof a.maxStringLength?a.maxStringLength<0&&a.maxStringLength!==1/0:null!==a.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var c=!q(a,"customInspect")||a.customInspect;if("boolean"!=typeof c&&"symbol"!==c)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(q(a,"indent")&&null!==a.indent&&"\t"!==a.indent&&!(parseInt(a.indent,10)===a.indent&&a.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(q(a,"numericSeparator")&&"boolean"!=typeof a.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var f=a.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return G(t,a);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var S=String(t);return f?x(t,S):S}if("bigint"==typeof t){var _=String(t)+"n";return f?x(t,_):_}var R=void 0===a.depth?5:a.depth;if(void 0===i&&(i=0),i>=R&&R>0&&"object"==typeof t)return K(t)?"[Array]":"[Object]";var O=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=w.call(Array(e.indent+1)," ")}return{base:n,prev:w.call(Array(t+1),n)}}(a,i);if(void 0===r)r=[];else if($(r,t)>=0)return"[Circular]";function U(t,n,o){if(n&&(r=I.call(r)).push(n),o){var s={depth:a.depth};return q(a,"quoteStyle")&&(s.quoteStyle=a.quoteStyle),e(t,s,i+1,r)}return e(t,a,i+1,r)}if("function"==typeof t){var F=function(e){if(e.name)return e.name;var t=y.call(v.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),H=z(t,U);return"[Function"+(F?": "+F:" (anonymous)")+"]"+(H.length>0?" { "+w.call(H,", ")+" }":"")}if(j(t)){var X=P?E.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):C.call(t);return"object"!=typeof t||P?X:W(X)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var Z="<"+b.call(String(t.nodeName)),ee=t.attributes||[],te=0;te<ee.length;te++)Z+=" "+ee[te].name+"="+L(B(ee[te].value),"double",a);return Z+=">",t.childNodes&&t.childNodes.length&&(Z+="..."),Z+="</"+b.call(String(t.nodeName))+">"}if(K(t)){if(0===t.length)return"[]";var ne=z(t,U);return O&&!function(e){for(var t=0;t<e.length;t++)if($(e[t],"\n")>=0)return!1;return!0}(ne)?"["+J(ne,O)+"]":"[ "+w.call(ne,", ")+" ]"}if(function(e){return!("[object Error]"!==V(e)||M&&"object"==typeof e&&M in e)}(t)){var ie=z(t,U);return"cause"in t&&!D.call(t,"cause")?"{ ["+String(t)+"] "+w.call(T.call("[cause]: "+U(t.cause),ie),", ")+" }":0===ie.length?"["+String(t)+"]":"{ ["+String(t)+"] "+w.call(ie,", ")+" }"}if("object"==typeof t&&c){if(N&&"function"==typeof t[N])return t[N]();if("symbol"!==c&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!o||!e||"object"!=typeof e)return!1;try{o.call(e);try{l.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var re=[];return s.call(t,(function(e,n){re.push(U(n,t,!0)+" => "+U(e,t))})),Q("Map",o.call(t),re,O)}if(function(e){if(!l||!e||"object"!=typeof e)return!1;try{l.call(e);try{o.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var oe=[];return d.call(t,(function(e){oe.push(U(e,t))})),Q("Set",l.call(t),oe,O)}if(function(e){if(!u||!e||"object"!=typeof e)return!1;try{u.call(e,u);try{h.call(e,h)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Y("WeakMap");if(function(e){if(!h||!e||"object"!=typeof e)return!1;try{h.call(e,h);try{u.call(e,u)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Y("WeakSet");if(function(e){if(!g||!e||"object"!=typeof e)return!1;try{return g.call(e),!0}catch(e){}return!1}(t))return Y("WeakRef");if(function(e){return!("[object Number]"!==V(e)||M&&"object"==typeof e&&M in e)}(t))return W(U(Number(t)));if(function(e){if(!e||"object"!=typeof e||!k)return!1;try{return k.call(e),!0}catch(e){}return!1}(t))return W(U(k.call(t)));if(function(e){return!("[object Boolean]"!==V(e)||M&&"object"==typeof e&&M in e)}(t))return W(p.call(t));if(function(e){return!("[object String]"!==V(e)||M&&"object"==typeof e&&M in e)}(t))return W(U(String(t)));if(!function(e){return!("[object Date]"!==V(e)||M&&"object"==typeof e&&M in e)}(t)&&!function(e){return!("[object RegExp]"!==V(e)||M&&"object"==typeof e&&M in e)}(t)){var se=z(t,U),ae=A?A(t)===Object.prototype:t instanceof Object||t.constructor===Object,ce=t instanceof Object?"":"null prototype",le=!ae&&M&&Object(t)===t&&M in t?m.call(V(t),8,-1):ce?"Object":"",de=(ae||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(le||ce?"["+w.call(T.call([],le||[],ce||[]),": ")+"] ":"");return 0===se.length?de+"{}":O?de+"{"+J(se,O)+"}":de+"{ "+w.call(se,", ")+" }"}return String(t)};var F=Object.prototype.hasOwnProperty||function(e){return e in this};function q(e,t){return F.call(e,t)}function V(e){return f.call(e)}function $(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,i=e.length;n<i;n++)if(e[n]===t)return n;return-1}function G(e,t){if(e.length>t.maxStringLength){var n=e.length-t.maxStringLength,i="... "+n+" more character"+(n>1?"s":"");return G(m.call(e,0,t.maxStringLength),t)+i}return L(E.call(E.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,H),"single",t)}function H(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(t<16?"0":"")+S.call(t.toString(16))}function W(e){return"Object("+e+")"}function Y(e){return e+" { ? }"}function Q(e,t,n,i){return e+" ("+t+") {"+(i?J(n,i):w.call(n,", "))+"}"}function J(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+w.call(e,","+n)+"\n"+t.prev}function z(e,t){var n=K(e),i=[];if(n){i.length=e.length;for(var r=0;r<e.length;r++)i[r]=q(e,r)?t(e[r],e):""}var o,s="function"==typeof O?O(e):[];if(P){o={};for(var a=0;a<s.length;a++)o["$"+s[a]]=s[a]}for(var c in e)q(e,c)&&(n&&String(Number(c))===c&&c<e.length||P&&o["$"+c]instanceof Symbol||(_.call(/[^\w$]/,c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof O)for(var l=0;l<s.length;l++)D.call(e,s[l])&&i.push("["+t(s[l])+"]: "+t(e[s[l]],e));return i}},{"./util.inspect":18}],56:[function(e,t,n){"use strict";const i=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(((n,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=i.operation(t);a.attempt((async i=>{try{n(await e(i))}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,n)=>{const i=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=i})(e,i,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:63}],57:[function(e,t,n){var i,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(i===setTimeout)return setTimeout(e,0);if((i===s||!i)&&setTimeout)return i=setTimeout,setTimeout(e,0);try{return i(e,0)}catch(t){try{return i.call(null,e,0)}catch(t){return i.call(this,e,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:s}catch(e){i=s}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var l,d=[],u=!1,h=-1;function g(){u&&l&&(u=!1,l.length?d=l.concat(d):h=-1,d.length&&p())}function p(){if(!u){var e=c(g);u=!0;for(var t=d.length;t;){for(l=d,d=[];++h<t;)l&&l[h].run();h=-1,t=d.length}l=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(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 n=1;n<arguments.length;n++)t[n-1]=arguments[n];d.push(new f(e,t)),1!==d.length||u||c(p)},f.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}},{}],58:[function(e,t,n){"use strict";var i=String.prototype.replace,r=/%20/g,o="RFC1738",s="RFC3986";t.exports={default:s,formatters:{RFC1738:function(e){return i.call(e,r,"+")},RFC3986:function(e){return String(e)}},RFC1738:o,RFC3986:s}},{}],59:[function(e,t,n){"use strict";var i=e("./stringify"),r=e("./parse"),o=e("./formats");t.exports={formats:o,parse:r,stringify:i}},{"./formats":58,"./parse":60,"./stringify":61}],60:[function(e,t,n){"use strict";var i=e("./utils"),r=Object.prototype.hasOwnProperty,o=Array.isArray,s={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:i.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},a=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},c=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},l=function(e,t,n,i){if(e){var o=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,s=/(\[[^[\]]*])/g,a=n.depth>0&&/(\[[^[\]]*])/.exec(o),l=a?o.slice(0,a.index):o,d=[];if(l){if(!n.plainObjects&&r.call(Object.prototype,l)&&!n.allowPrototypes)return;d.push(l)}for(var u=0;n.depth>0&&null!==(a=s.exec(o))&&u<n.depth;){if(u+=1,!n.plainObjects&&r.call(Object.prototype,a[1].slice(1,-1))&&!n.allowPrototypes)return;d.push(a[1])}return a&&d.push("["+o.slice(a.index)+"]"),function(e,t,n,i){for(var r=i?t:c(t,n),o=e.length-1;o>=0;--o){var s,a=e[o];if("[]"===a&&n.parseArrays)s=[].concat(r);else{s=n.plainObjects?Object.create(null):{};var l="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(l,10);n.parseArrays||""!==l?!isNaN(d)&&a!==l&&String(d)===l&&d>=0&&n.parseArrays&&d<=n.arrayLimit?(s=[])[d]=r:"__proto__"!==l&&(s[l]=r):s={0:r}}r=s}return r}(d,t,n,i)}};t.exports=function(e,t){var n=function(e){if(!e)return s;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?s.charset:e.charset;return{allowDots:void 0===e.allowDots?s.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:s.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||i.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var d="string"==typeof e?function(e,t){var n,l={},d=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,u=t.parameterLimit===1/0?void 0:t.parameterLimit,h=d.split(t.delimiter,u),g=-1,p=t.charset;if(t.charsetSentinel)for(n=0;n<h.length;++n)0===h[n].indexOf("utf8=")&&("utf8=%E2%9C%93"===h[n]?p="utf-8":"utf8=%26%2310003%3B"===h[n]&&(p="iso-8859-1"),g=n,n=h.length);for(n=0;n<h.length;++n)if(n!==g){var f,v,y=h[n],m=y.indexOf("]="),E=-1===m?y.indexOf("="):m+1;-1===E?(f=t.decoder(y,s.decoder,p,"key"),v=t.strictNullHandling?null:""):(f=t.decoder(y.slice(0,E),s.decoder,p,"key"),v=i.maybeMap(c(y.slice(E+1),t),(function(e){return t.decoder(e,s.decoder,p,"value")}))),v&&t.interpretNumericEntities&&"iso-8859-1"===p&&(v=a(v)),y.indexOf("[]=")>-1&&(v=o(v)?[v]:v),r.call(l,f)?l[f]=i.combine(l[f],v):l[f]=v}return l}(e,n):e,u=n.plainObjects?Object.create(null):{},h=Object.keys(d),g=0;g<h.length;++g){var p=h[g],f=l(p,d[p],n,"string"==typeof e);u=i.merge(u,f,n)}return!0===n.allowSparse?u:i.compact(u)}},{"./utils":62}],61:[function(e,t,n){"use strict";var i=e("side-channel"),r=e("./utils"),o=e("./formats"),s=Object.prototype.hasOwnProperty,a={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},c=Array.isArray,l=String.prototype.split,d=Array.prototype.push,u=function(e,t){d.apply(e,c(t)?t:[t])},h=Date.prototype.toISOString,g=o.default,p={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:r.encode,encodeValuesOnly:!1,format:g,formatter:o.formatters[g],indices:!1,serializeDate:function(e){return h.call(e)},skipNulls:!1,strictNullHandling:!1},f={},v=function e(t,n,o,s,a,d,h,g,v,y,m,E,S,b,_){for(var T,w=t,I=_,R=0,k=!1;void 0!==(I=I.get(f))&&!k;){var O=I.get(t);if(R+=1,void 0!==O){if(O===R)throw new RangeError("Cyclic object value");k=!0}void 0===I.get(f)&&(R=0)}if("function"==typeof h?w=h(n,w):w instanceof Date?w=y(w):"comma"===o&&c(w)&&(w=r.maybeMap(w,(function(e){return e instanceof Date?y(e):e}))),null===w){if(s)return d&&!S?d(n,p.encoder,b,"key",m):n;w=""}if("string"==typeof(T=w)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||r.isBuffer(w)){if(d){var C=S?n:d(n,p.encoder,b,"key",m);if("comma"===o&&S){for(var P=l.call(String(w),","),M="",D=0;D<P.length;++D)M+=(0===D?"":",")+E(d(P[D],p.encoder,b,"value",m));return[E(C)+"="+M]}return[E(C)+"="+E(d(w,p.encoder,b,"value",m))]}return[E(n)+"="+E(String(w))]}var A,x=[];if(void 0===w)return x;if("comma"===o&&c(w))A=[{value:w.length>0?w.join(",")||null:void 0}];else if(c(h))A=h;else{var U=Object.keys(w);A=g?U.sort(g):U}for(var N=0;N<A.length;++N){var L=A[N],B="object"==typeof L&&void 0!==L.value?L.value:w[L];if(!a||null!==B){var K=c(w)?"function"==typeof o?o(n,L):n:n+(v?"."+L:"["+L+"]");_.set(t,R);var j=i();j.set(f,_),u(x,e(B,K,o,s,a,d,h,g,v,y,m,E,S,b,j))}}return x};t.exports=function(e,t){var n,r=e,l=function(e){if(!e)return p;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||p.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=o.default;if(void 0!==e.format){if(!s.call(o.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var i=o.formatters[n],r=p.filter;return("function"==typeof e.filter||c(e.filter))&&(r=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:p.addQueryPrefix,allowDots:void 0===e.allowDots?p.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:p.charsetSentinel,delimiter:void 0===e.delimiter?p.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:p.encode,encoder:"function"==typeof e.encoder?e.encoder:p.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:p.encodeValuesOnly,filter:r,format:n,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:p.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:p.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:p.strictNullHandling}}(t);"function"==typeof l.filter?r=(0,l.filter)("",r):c(l.filter)&&(n=l.filter);var d,h=[];if("object"!=typeof r||null===r)return"";d=t&&t.arrayFormat in a?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var g=a[d];n||(n=Object.keys(r)),l.sort&&n.sort(l.sort);for(var f=i(),y=0;y<n.length;++y){var m=n[y];l.skipNulls&&null===r[m]||u(h,v(r[m],m,g,l.strictNullHandling,l.skipNulls,l.encode?l.encoder:null,l.filter,l.sort,l.allowDots,l.serializeDate,l.format,l.formatter,l.encodeValuesOnly,l.charset,f))}var E=h.join(l.delimiter),S=!0===l.addQueryPrefix?"?":"";return l.charsetSentinel&&("iso-8859-1"===l.charset?S+="utf8=%26%2310003%3B&":S+="utf8=%E2%9C%93&"),E.length>0?S+E:""}},{"./formats":58,"./utils":62,"side-channel":67}],62:[function(e,t,n){"use strict";var i=e("./formats"),r=Object.prototype.hasOwnProperty,o=Array.isArray,s=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),a=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(n[i]=e[i]);return n};t.exports={arrayToObject:a,assign:function(e,t){return Object.keys(t).reduce((function(e,n){return e[n]=t[n],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],n=[],i=0;i<t.length;++i)for(var r=t[i],s=r.obj[r.prop],a=Object.keys(s),c=0;c<a.length;++c){var l=a[c],d=s[l];"object"==typeof d&&null!==d&&-1===n.indexOf(d)&&(t.push({obj:s,prop:l}),n.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),n=t.obj[t.prop];if(o(n)){for(var i=[],r=0;r<n.length;++r)void 0!==n[r]&&i.push(n[r]);t.obj[t.prop]=i}}}(t),e},decode:function(e,t,n){var i=e.replace(/\+/g," ");if("iso-8859-1"===n)return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch(e){return i}},encode:function(e,t,n,r,o){if(0===e.length)return e;var a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===n)return escape(a).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var c="",l=0;l<a.length;++l){var d=a.charCodeAt(l);45===d||46===d||95===d||126===d||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===i.RFC1738&&(40===d||41===d)?c+=a.charAt(l):d<128?c+=s[d]:d<2048?c+=s[192|d>>6]+s[128|63&d]:d<55296||d>=57344?c+=s[224|d>>12]+s[128|d>>6&63]+s[128|63&d]:(l+=1,d=65536+((1023&d)<<10|1023&a.charCodeAt(l)),c+=s[240|d>>18]+s[128|d>>12&63]+s[128|d>>6&63]+s[128|63&d])}return c},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(o(e)){for(var n=[],i=0;i<e.length;i+=1)n.push(t(e[i]));return n}return t(e)},merge:function e(t,n,i){if(!n)return t;if("object"!=typeof n){if(o(t))t.push(n);else{if(!t||"object"!=typeof t)return[t,n];(i&&(i.plainObjects||i.allowPrototypes)||!r.call(Object.prototype,n))&&(t[n]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(n);var s=t;return o(t)&&!o(n)&&(s=a(t,i)),o(t)&&o(n)?(n.forEach((function(n,o){if(r.call(t,o)){var s=t[o];s&&"object"==typeof s&&n&&"object"==typeof n?t[o]=e(s,n,i):t.push(n)}else t[o]=n})),t):Object.keys(n).reduce((function(t,o){var s=n[o];return r.call(t,o)?t[o]=e(t[o],s,i):t[o]=s,t}),s)}}},{"./formats":58}],63:[function(e,t,n){t.exports=e("./lib/retry")},{"./lib/retry":64}],64:[function(e,t,n){var i=e("./retry_operation");n.operation=function(e){var t=n.timeouts(e);return new i(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},n.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 n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],r=0;r<t.retries;r++)i.push(this.createTimeout(r,t));return e&&e.forever&&!i.length&&i.push(this.createTimeout(r,t)),i.sort((function(e,t){return e-t})),i},n.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,i=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return i=Math.min(i,t.maxTimeout)},n.wrap=function(e,t,i){if(t instanceof Array&&(i=t,t=null),!i)for(var r in i=[],e)"function"==typeof e[r]&&i.push(r);for(var o=0;o<i.length;o++){var s=i[o],a=e[s];e[s]=function(i){var r=n.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(){i.apply(e,o)}))}.bind(e,a),e[s].options=t}}},{"./retry_operation":65}],65:[function(e,t,n){function i(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=i,i.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},i.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},i.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 n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var i=this;return this._timer=setTimeout((function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout((function(){i._operationTimeoutCb(i._attempts)}),i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)}),n),this._options.unref&&this._timer.unref(),!0},i.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){n._operationTimeoutCb()}),n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},i.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},i.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},i.prototype.start=i.prototype.try,i.prototype.errors=function(){return this._errors},i.prototype.attempts=function(){return this._attempts},i.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,i=0;i<this._errors.length;i++){var r=this._errors[i],o=r.message,s=(e[o]||0)+1;e[o]=s,s>=n&&(t=r,n=s)}return t}},{}],66:[function(e,t,n){
- /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
- var i=e("buffer"),r=i.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=i:(o(i,n),n.Buffer=s),s.prototype=Object.create(r.prototype),o(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},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 i.SlowBuffer(e)}},{buffer:20}],67:[function(e,t,n){"use strict";var i=e("get-intrinsic"),r=e("call-bind/callBound"),o=e("object-inspect"),s=i("%TypeError%"),a=i("%WeakMap%",!0),c=i("%Map%",!0),l=r("WeakMap.prototype.get",!0),d=r("WeakMap.prototype.set",!0),u=r("WeakMap.prototype.has",!0),h=r("Map.prototype.get",!0),g=r("Map.prototype.set",!0),p=r("Map.prototype.has",!0),f=function(e,t){for(var n,i=e;null!==(n=i.next);i=n)if(n.key===t)return i.next=n.next,n.next=e.next,e.next=n,n};t.exports=function(){var e,t,n,i={assert:function(e){if(!i.has(e))throw new s("Side channel does not contain "+o(e))},get:function(i){if(a&&i&&("object"==typeof i||"function"==typeof i)){if(e)return l(e,i)}else if(c){if(t)return h(t,i)}else if(n)return function(e,t){var n=f(e,t);return n&&n.value}(n,i)},has:function(i){if(a&&i&&("object"==typeof i||"function"==typeof i)){if(e)return u(e,i)}else if(c){if(t)return p(t,i)}else if(n)return function(e,t){return!!f(e,t)}(n,i);return!1},set:function(i,r){a&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new a),d(e,i,r)):c?(t||(t=new c),g(t,i,r)):(n||(n={key:{},next:null}),function(e,t,n){var i=f(e,t);i?i.value=n:e.next={key:t,next:e.next,value:n}}(n,i,r))}};return i}},{"call-bind/callBound":21,"get-intrinsic":27,"object-inspect":55}],68:[function(e,t,n){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","ᙱ":"ᖖᒋ","ᙲ":"ᖖᒌ","ᙴ":"ᖖᒎ","ᙵ":"ᖖᒐ","ᙶ":"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ","ˡ":"ᣳ","ʳ":"ᣴ","ˢ":"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ","ᛡ":"ᚼ","⍿":"ᚽ","ᛂ":"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥","ㄱ":"ᄀ","ᆨ":"ᄀ","ᄁ":"ᄀᄀ","ㄲ":"ᄀᄀ","ᆩ":"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ","ᇃ":"ᄀᄅ","ᇻ":"ᄀᄇ","ᆪ":"ᄀᄉ","ㄳ":"ᄀᄉ","ᇄ":"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ","ㄴ":"ᄂ","ᆫ":"ᄂ","ᄓ":"ᄂᄀ","ᇅ":"ᄂᄀ","ᄔ":"ᄂᄂ","ㅥ":"ᄂᄂ","ᇿ":"ᄂᄂ","ᄕ":"ᄂᄃ","ㅦ":"ᄂᄃ","ᇆ":"ᄂᄃ","ퟋ":"ᄂᄅ","ᄖ":"ᄂᄇ","ᅛ":"ᄂᄉ","ᇇ":"ᄂᄉ","ㅧ":"ᄂᄉ","ᅜ":"ᄂᄌ","ᆬ":"ᄂᄌ","ㄵ":"ᄂᄌ","ퟌ":"ᄂᄎ","ᇉ":"ᄂᄐ","ᅝ":"ᄂᄒ","ᆭ":"ᄂᄒ","ㄶ":"ᄂᄒ","ᇈ":"ᄂᅀ","ㅨ":"ᄂᅀ","ㄷ":"ᄃ","ᆮ":"ᄃ","ᄗ":"ᄃᄀ","ᇊ":"ᄃᄀ","ᄄ":"ᄃᄃ","ㄸ":"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ","ᇋ":"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ","ㄹ":"ᄅ","ᆯ":"ᄅ","ꥤ":"ᄅᄀ","ᆰ":"ᄅᄀ","ㄺ":"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ","ᇌ":"ᄅᄀᄉ","ㅩ":"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ","ᄘ":"ᄅᄂ","ᇍ":"ᄅᄂ","ꥦ":"ᄅᄃ","ᇎ":"ᄅᄃ","ㅪ":"ᄅᄃ","ꥧ":"ᄅᄃᄃ","ᇏ":"ᄅᄃᄒ","ᄙ":"ᄅᄅ","ᇐ":"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ","ᆱ":"ᄅᄆ","ㄻ":"ᄅᄆ","ᇑ":"ᄅᄆᄀ","ᇒ":"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ","ᆲ":"ᄅᄇ","ㄼ":"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ","ᇓ":"ᄅᄇᄉ","ㅫ":"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ","ᇕ":"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ","ᇔ":"ᄅᄇᄒ","ꥬ":"ᄅᄉ","ᆳ":"ᄅᄉ","ㄽ":"ᄅᄉ","ᇖ":"ᄅᄉᄉ","ᄛ":"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ","ᇘ":"ᄅᄏ","ᆴ":"ᄅᄐ","ㄾ":"ᄅᄐ","ᆵ":"ᄅᄑ","ㄿ":"ᄅᄑ","ᄚ":"ᄅᄒ","ㅀ":"ᄅᄒ","ᄻ":"ᄅᄒ","ᆶ":"ᄅᄒ","ퟲ":"ᄅᄒ","ᇗ":"ᄅᅀ","ㅬ":"ᄅᅀ","ퟛ":"ᄅᅌ","ᇙ":"ᄅᅙ","ㅭ":"ᄅᅙ","ퟜ":"ᄅᅙᄒ","ㅁ":"ᄆ","ᆷ":"ᄆ","ꥯ":"ᄆᄀ","ᇚ":"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ","ᇛ":"ᄆᄅ","ퟠ":"ᄆᄆ","ᄜ":"ᄆᄇ","ㅮ":"ᄆᄇ","ᇜ":"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ","ᇝ":"ᄆᄉ","ㅯ":"ᄆᄉ","ᇞ":"ᄆᄉᄉ","ᄝ":"ᄆᄋ","ㅱ":"ᄆᄋ","ᇢ":"ᄆᄋ","ퟢ":"ᄆᄌ","ᇠ":"ᄆᄎ","ᇡ":"ᄆᄒ","ᇟ":"ᄆᅀ","ㅰ":"ᄆᅀ","ㅂ":"ᄇ","ᆸ":"ᄇ","ᄞ":"ᄇᄀ","ㅲ":"ᄇᄀ","ᄟ":"ᄇᄂ","ᄠ":"ᄇᄃ","ㅳ":"ᄇᄃ","ퟣ":"ᄇᄃ","ᇣ":"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ","ᄈ":"ᄇᄇ","ㅃ":"ᄇᄇ","ퟦ":"ᄇᄇ","ᄬ":"ᄇᄇᄋ","ㅹ":"ᄇᄇᄋ","ᄡ":"ᄇᄉ","ㅄ":"ᄇᄉ","ᆹ":"ᄇᄉ","ᄢ":"ᄇᄉᄀ","ㅴ":"ᄇᄉᄀ","ᄣ":"ᄇᄉᄃ","ㅵ":"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ","ᄤ":"ᄇᄉᄇ","ᄥ":"ᄇᄉᄉ","ᄦ":"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ","ᄫ":"ᄇᄋ","ㅸ":"ᄇᄋ","ᇦ":"ᄇᄋ","ᄧ":"ᄇᄌ","ㅶ":"ᄇᄌ","ퟨ":"ᄇᄌ","ᄨ":"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ","ᄩ":"ᄇᄐ","ㅷ":"ᄇᄐ","ᄪ":"ᄇᄑ","ᇤ":"ᄇᄑ","ꥴ":"ᄇᄒ","ᇥ":"ᄇᄒ","ㅅ":"ᄉ","ᆺ":"ᄉ","ᄭ":"ᄉᄀ","ㅺ":"ᄉᄀ","ᇧ":"ᄉᄀ","ᄮ":"ᄉᄂ","ㅻ":"ᄉᄂ","ᄯ":"ᄉᄃ","ㅼ":"ᄉᄃ","ᇨ":"ᄉᄃ","ᄰ":"ᄉᄅ","ᇩ":"ᄉᄅ","ᄱ":"ᄉᄆ","ퟪ":"ᄉᄆ","ᄲ":"ᄉᄇ","ㅽ":"ᄉᄇ","ᇪ":"ᄉᄇ","ᄳ":"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ","ᄊ":"ᄉᄉ","ㅆ":"ᄉᄉ","ᆻ":"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ","ᄴ":"ᄉᄉᄉ","ᄵ":"ᄉᄋ","ᄶ":"ᄉᄌ","ㅾ":"ᄉᄌ","ퟯ":"ᄉᄌ","ᄷ":"ᄉᄎ","ퟰ":"ᄉᄎ","ᄸ":"ᄉᄏ","ᄹ":"ᄉᄐ","ퟱ":"ᄉᄐ","ᄺ":"ᄉᄑ","ퟮ":"ᄉᅀ","ㅇ":"ᄋ","ᆼ":"ᄋ","ᅁ":"ᄋᄀ","ᇬ":"ᄋᄀ","ᇭ":"ᄋᄀᄀ","ᅂ":"ᄋᄃ","ꥶ":"ᄋᄅ","ᅃ":"ᄋᄆ","ᅄ":"ᄋᄇ","ᅅ":"ᄋᄉ","ᇱ":"ᄋᄉ","ㆂ":"ᄋᄉ","ᅇ":"ᄋᄋ","ㆀ":"ᄋᄋ","ᇮ":"ᄋᄋ","ᅈ":"ᄋᄌ","ᅉ":"ᄋᄎ","ᇯ":"ᄋᄏ","ᅊ":"ᄋᄐ","ᅋ":"ᄋᄑ","ꥷ":"ᄋᄒ","ᅆ":"ᄋᅀ","ᇲ":"ᄋᅀ","ㆃ":"ᄋᅀ","ㅈ":"ᄌ","ᆽ":"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ","ᅍ":"ᄌᄋ","ᄍ":"ᄌᄌ","ㅉ":"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ","ㅊ":"ᄎ","ᆾ":"ᄎ","ᅒ":"ᄎᄏ","ᅓ":"ᄎᄒ","ㅋ":"ᄏ","ᆿ":"ᄏ","ㅌ":"ᄐ","ᇀ":"ᄐ","ꥹ":"ᄐᄐ","ㅍ":"ᄑ","ᇁ":"ᄑ","ᅖ":"ᄑᄇ","ᇳ":"ᄑᄇ","ퟺ":"ᄑᄉ","ᅗ":"ᄑᄋ","ㆄ":"ᄑᄋ","ᇴ":"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ","ㅎ":"ᄒ","ᇂ":"ᄒ","ᇵ":"ᄒᄂ","ᇶ":"ᄒᄅ","ᇷ":"ᄒᄆ","ᇸ":"ᄒᄇ","ꥻ":"ᄒᄉ","ᅘ":"ᄒᄒ","ㆅ":"ᄒᄒ","ᄽ":"ᄼᄼ","ᄿ":"ᄾᄾ","ㅿ":"ᅀ","ᇫ":"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ","ㆁ":"ᅌ","ᇰ":"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ","ᅏ":"ᅎᅎ","ᅑ":"ᅐᅐ","ㆆ":"ᅙ","ᇹ":"ᅙ","ꥼ":"ᅙᅙ","ㅤ":"ᅠ","ㅏ":"ᅡ","ᆣ":"ᅡー","ᅶ":"ᅡᅩ","ᅷ":"ᅡᅮ","ᅢ":"ᅡ丨","ㅐ":"ᅡ丨","ㅑ":"ᅣ","ᅸ":"ᅣᅩ","ᅹ":"ᅣᅭ","ᆤ":"ᅣᅮ","ᅤ":"ᅣ丨","ㅒ":"ᅣ丨","ㅓ":"ᅥ","ᅼ":"ᅥー","ᅺ":"ᅥᅩ","ᅻ":"ᅥᅮ","ᅦ":"ᅥ丨","ㅔ":"ᅥ丨","ㅕ":"ᅧ","ᆥ":"ᅧᅣ","ᅽ":"ᅧᅩ","ᅾ":"ᅧᅮ","ᅨ":"ᅧ丨","ㅖ":"ᅧ丨","ㅗ":"ᅩ","ᅪ":"ᅩᅡ","ㅘ":"ᅩᅡ","ᅫ":"ᅩᅡ丨","ㅙ":"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨","ᅿ":"ᅩᅥ","ᆀ":"ᅩᅥ丨","ힰ":"ᅩᅧ","ᆁ":"ᅩᅧ丨","ᆂ":"ᅩᅩ","ힱ":"ᅩᅩ丨","ᆃ":"ᅩᅮ","ᅬ":"ᅩ丨","ㅚ":"ᅩ丨","ㅛ":"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨","ᆄ":"ᅭᅣ","ㆇ":"ᅭᅣ","ᆆ":"ᅭᅣ","ᆅ":"ᅭᅣ丨","ㆈ":"ᅭᅣ丨","ힴ":"ᅭᅥ","ᆇ":"ᅭᅩ","ᆈ":"ᅭ丨","ㆉ":"ᅭ丨","ㅜ":"ᅮ","ᆉ":"ᅮᅡ","ᆊ":"ᅮᅡ丨","ᅯ":"ᅮᅥ","ㅝ":"ᅮᅥ","ᆋ":"ᅮᅥー","ᅰ":"ᅮᅥ丨","ㅞ":"ᅮᅥ丨","ힵ":"ᅮᅧ","ᆌ":"ᅮᅧ丨","ᆍ":"ᅮᅮ","ᅱ":"ᅮ丨","ㅟ":"ᅮ丨","ힶ":"ᅮ丨丨","ㅠ":"ᅲ","ᆎ":"ᅲᅡ","ힷ":"ᅲᅡ丨","ᆏ":"ᅲᅥ","ᆐ":"ᅲᅥ丨","ᆑ":"ᅲᅧ","ㆊ":"ᅲᅧ","ᆒ":"ᅲᅧ丨","ㆋ":"ᅲᅧ丨","ힸ":"ᅲᅩ","ᆓ":"ᅲᅮ","ᆔ":"ᅲ丨","ㆌ":"ᅲ丨","ㆍ":"ᆞ","ퟅ":"ᆞᅡ","ᆟ":"ᆞᅥ","ퟆ":"ᆞᅥ丨","ᆠ":"ᆞᅮ","ᆢ":"ᆞᆞ","ᆡ":"ᆞ丨","ㆎ":"ᆞ丨","ヘ":"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄","不":"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨","ᅵ":"丨","ㅣ":"丨","⼁":"丨","ᆜ":"丨ー","ᆘ":"丨ᅡ","ᆙ":"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨","ᆚ":"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ","ᆛ":"丨ᅮ","ퟃ":"丨ᅲ","ᆝ":"丨ᆞ","ퟄ":"丨丨","串":"串","丸":"丸","丹":"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀","亂":"亂","㇚":"亅","⼅":"亅","了":"了","ニ":"二","⼆":"二","𠄢":"𠄢","⼇":"亠","亮":"亮","⼈":"人","イ":"亻","⺅":"亻","什":"什","仌":"仌","令":"令","你":"你","倂":"併","倂":"併","侀":"侀","來":"來","例":"例","侮":"侮","侮":"侮","侻":"侻","便":"便","值":"値","倫":"倫","偺":"偺","備":"備","像":"像","僚":"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿","兀":"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全","兩":"兩","ハ":"八","⼋":"八","六":"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况","冷":"冷","凉":"凉","凌":"凌","凜":"凜","凞":"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃","切":"切","切":"切","列":"列","利":"利","㓟":"㓟","刺":"刺","刻":"刻","剆":"剆","割":"割","剷":"剷","劉":"劉","𠠄":"𠠄","カ":"力","力":"力","⼒":"力","劣":"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉","勒":"勒","勞":"勞","勤":"勤","勤":"勤","勵":"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕","北":"北","北":"北","⼕":"匚","⼖":"匸","匿":"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博","ト":"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即","卵":"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶","參":"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣","ロ":"口","⼝":"口","囗":"口","⼞":"口","句":"句","叫":"叫","叱":"叱","吆":"吆","吏":"吏","吝":"吝","吸":"吸","呂":"呂","呈":"呈","周":"周","咞":"咞","咢":"咢","咽":"咽","䎛":"㖈","哶":"哶","唐":"唐","啓":"啓","啟":"啓","啕":"啕","啣":"啣","善":"善","善":"善","喇":"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳","嗀":"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器","囹":"囹","圖":"圖","圗":"圗","⼟":"土","士":"土","⼠":"土","型":"型","城":"城","㦳":"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀","塚":"塚","塚":"塚","塞":"塞","填":"塡","壿":"墫","墬":"墬","墳":"墳","壘":"壘","壟":"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊","タ":"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄","奈":"奈","契":"契","奔":"奔","奢":"奢","女":"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦","嬀":"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀","宅":"宅","𡧈":"𡧈","寃":"寃","寘":"寘","寧":"寧","寧":"寧","寧":"寧","寮":"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸","尿":"尿","屠":"屠","屢":"屢","層":"層","履":"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦","崙":"崙","嵃":"嵃","嵐":"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲","嶺":"嶺","⼮":"巛","巢":"巢","エ":"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾","帲":"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干","年":"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广","度":"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶","廊":"廊","廊":"廊","廉":"廉","廒":"廒","廓":"廓","廙":"廙","廬":"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱","弄":"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳","律":"律","㣣":"㣣","徚":"徚","復":"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志","念":"念","忹":"忹","怒":"怒","怜":"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘","惡":"惡","𢛔":"𢛔","愈":"愈","慨":"慨","慄":"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎","憐":"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲","懶":"懶","懶":"懶","戀":"戀","⼽":"戈","成":"成","戛":"戛","戮":"戮","戴":"戴","⼾":"戶","戸":"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱","拉":"拉","拏":"拏","拓":"拓","拔":"拔","拼":"拼","拾":"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨","捻":"捻","掃":"掃","掠":"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮","搉":"㩁","撚":"撚","撝":"撝","擄":"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬","數":"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗","料":"料","⽄":"斤","⽅":"方","旅":"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日","易":"易","曶":"㫚","㫤":"㫤","晉":"晉","晩":"晚","晴":"晴","晴":"晴","暑":"暑","暑":"暑","暈":"暈","㬈":"㬈","暜":"暜","暴":"暴","曆":"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰","更":"更","書":"書","⽉":"月","𣍟":"𣍟","肦":"朌","胐":"朏","胊":"朐","脁":"朓","胶":"㬵","朗":"朗","朗":"朗","朗":"朗","脧":"朘","望":"望","望":"望","幐":"㬺","䐠":"㬻","𣎓":"𣎓","膧":"朣","𣎜":"𣎜","⽊":"木","李":"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃","柿":"杮","杻":"杻","枅":"枅","林":"林","㭉":"㭉","𣏕":"𣏕","柳":"柳","柺":"柺","栗":"栗","栟":"栟","桒":"桒","𣑭":"𣑭","梁":"梁","梅":"梅","梅":"梅","梎":"梎","梨":"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝","槩":"㮣","樧":"榝","榣":"榣","槪":"槪","樂":"樂","樂":"樂","樂":"樂","樓":"樓","𣚣":"𣚣","檨":"檨","櫓":"櫓","櫛":"櫛","欄":"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲","歷":"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟","殮":"殮","⽎":"殳","殺":"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧","沈":"沈","沿":"沿","泌":"泌","泍":"泍","泥":"泥","𣲼":"𣲼","洛":"洛","洞":"洞","洴":"洴","派":"派","流":"流","流":"流","流":"流","洖":"洖","浩":"浩","浪":"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞","淋":"淋","淚":"淚","淪":"淪","淹":"淹","渚":"渚","港":"港","湮":"湮","潙":"溈","滋":"滋","滋":"滋","溜":"溜","溺":"溺","滇":"滇","滑":"滑","滛":"滛","㴳":"㴳","漏":"漏","漢":"漢","漢":"漢","漣":"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆","濫":"濫","濾":"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災","炙":"炙","炭":"炭","烈":"烈","烙":"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅","煉":"煉","𤋮":"𤋮","熜":"熜","燎":"燎","燐":"燐","𤎫":"𤎫","爐":"爐","爛":"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛","牢":"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯","狀":"狀","𤜵":"𤜵","狼":"狼","猪":"猪","猪":"猪","𤠔":"𤠔","獵":"獵","獺":"獺","⽞":"玄","率":"率","率":"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥","玲":"玲","㺸":"㺸","㺸":"㺸","珞":"珞","琉":"琉","理":"理","琢":"琢","瑇":"瑇","瑜":"瑜","瑩":"瑩","瑱":"瑱","瑱":"瑱","璅":"璅","璉":"璉","璘":"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶","留":"留","略":"略","異":"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒","痢":"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝","療":"療","癩":"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼","益":"益","益":"益","盛":"盛","盧":"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳","省":"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹","晣":"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝","硏":"研","硎":"硎","硫":"硫","碌":"碌","碌":"碌","碑":"碑","磊":"磊","磌":"磌","磌":"磌","磻":"磻","䃣":"䃣","礪":"礪","⽰":"示","⺭":"礻","礼":"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝","神":"神","祥":"祥","視":"視","視":"視","祿":"祿","𥚚":"𥚚","禍":"禍","禎":"禎","福":"福","福":"福","𥛅":"𥛅","禮":"禮","⽱":"禸","⽲":"禾","秊":"秊","䄯":"䄯","秫":"秫","稜":"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱","立":"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹","笠":"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐","簾":"簾","籠":"籠","⽶":"米","类":"类","粒":"粒","精":"精","糒":"糒","糖":"糖","糨":"糨","䊠":"䊠","糣":"糣","糧":"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀","紐":"紐","索":"索","累":"累","絶":"絕","絣":"絣","絛":"絛","綠":"綠","綾":"綾","緇":"緇","練":"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉","縷":"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙","罹":"罹","罺":"罺","羅":"羅","𦌾":"𦌾","⽺":"羊","羕":"羕","羚":"羚","羽":"羽","⽻":"羽","翺":"翺","老":"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳","聆":"聆","聠":"聠","𦖨":"𦖨","聯":"聯","聰":"聰","聾":"聾","⾀":"聿","⺺":"肀","⾁":"肉","肋":"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙","腁":"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵","朦":"䑃","臘":"臘","⾂":"臣","臨":"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮","良":"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽","若":"若","若":"若","苦":"苦","𦬼":"𦬼","茶":"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓","菉":"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華","菱":"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭","落":"落","葉":"葉","蔿":"蒍","𦳕":"𦳕","𦵫":"𦵫","蓮":"蓮","蓱":"蓱","蓳":"蓳","蓼":"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬","藍":"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡","藺":"藺","蘆":"蘆","䕫":"䕫","蘒":"蘒","蘭":"蘭","𧃒":"𧃒","虁":"蘷","蘿":"蘿","⾌":"虍","⻁":"虎","虐":"虐","虜":"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊","螺":"螺","蠁":"蠁","䗹":"䗹","蠟":"蠟","⾎":"血","行":"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤","裂":"裂","𧙧":"𧙧","裏":"裏","裗":"裗","裞":"裞","裡":"裡","裸":"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁","襤":"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆","見":"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦","詽":"訮","訞":"䚶","䚾":"䚾","䛇":"䛇","誠":"誠","說":"說","說":"說","調":"調","請":"請","諒":"諒","論":"論","諭":"諭","諭":"諭","諸":"諸","諸":"諸","諾":"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹","識":"識","讀":"讀","讏":"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆","豈":"豈","豕":"豕","⾗":"豕","豣":"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁","賂":"賂","賈":"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起","趆":"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼","跺":"跥","路":"路","跰":"跰","躛":"躗","⾝":"身","車":"車","⾞":"車","軔":"軔","輧":"軿","輦":"輦","輪":"輪","輸":"輸","輸":"輸","輻":"輻","轢":"轢","⻋":"车","⾟":"辛","辞":"辞","辰":"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡","連":"連","逸":"逸","逸":"逸","遲":"遲","遼":"遼","𨗒":"𨗒","𨗭":"𨗭","邏":"邏","⾢":"邑","邔":"邔","郎":"郎","郞":"郎","郞":"郎","郱":"郱","都":"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉","酪":"酪","醙":"醙","醴":"醴","⾤":"釆","里":"里","⾥":"里","量":"量","金":"金","⾦":"金","鈴":"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼","錄":"錄","鍊":"鍊","鎮":"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕","閭":"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝","阮":"阮","陋":"陋","降":"降","陵":"陵","陸":"陸","陼":"陼","隆":"隆","隣":"隣","䧦":"䧦","⾪":"隶","隷":"隷","隸":"隷","隸":"隷","⾫":"隹","雃":"雃","離":"離","難":"難","難":"難","⾬":"雨","零":"零","雷":"雷","霣":"霣","𩅅":"𩅅","露":"露","靈":"靈","⾭":"靑","⻘":"青","靖":"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋","領":"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻","類":"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢","飯":"飯","飼":"飼","䬳":"䬳","館":"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂","駱":"駱","駾":"駾","驪":"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚","魯":"魯","鱀":"鱀","鱗":"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎","鶴":"鶴","𪄅":"𪄅","䳸":"䳸","鷺":"鷺","𪈎":"𪈎","鸞":"鸞","鹃":"鹂","⿄":"鹵","鹿":"鹿","⿅":"鹿","𪊑":"𪊑","麗":"麗","麟":"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍","黎":"黎","䵖":"䵖","⿊":"黑","黒":"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿","龍":"龍","⿓":"龍","龎":"龎","⻰":"龙","龜":"龜","龜":"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"}},{}],69:[function(e,t,n){"use strict";var i=e("./data.json");var r=RegExp(Object.keys(i).map((function(e){return e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")})).join("|"),"g");function o(e){return i[e]}t.exports=function(e){return e.replace(r,o)}},{"./data.json":68}],70:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.RuleId=n.PushRuleKind=n.ConditionKind=n.isDmMemberCountCondition=n.DMMemberCountCondition=n.ConditionOperator=n.TweakName=n.PushRuleActionName=void 0,function(e){e.DontNotify="dont_notify",e.Notify="notify",e.Coalesce="coalesce"}(n.PushRuleActionName||(n.PushRuleActionName={})),function(e){e.Highlight="highlight",e.Sound="sound"}(n.TweakName||(n.TweakName={})),function(e){e.ExactEquals="==",e.LessThan="<",e.GreaterThan=">",e.GreaterThanOrEqual=">=",e.LessThanOrEqual="<="}(n.ConditionOperator||(n.ConditionOperator={})),n.DMMemberCountCondition="2",n.isDmMemberCountCondition=function(e){return"==2"===e||"2"===e},function(e){e.EventMatch="event_match",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission"}(n.ConditionKind||(n.ConditionKind={})),function(e){e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride"}(n.PushRuleKind||(n.PushRuleKind={})),function(e){e.Master=".m.rule.master",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"}(n.RuleId||(n.RuleId={}))},{}],71:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.M_BEACON=n.M_BEACON_INFO=void 0;const i=e("../NamespacedValue");n.M_BEACON_INFO=new i.UnstableValue("m.beacon_info","org.matrix.msc3672.beacon_info"),n.M_BEACON=new i.UnstableValue("m.beacon","org.matrix.msc3672.beacon")},{"../NamespacedValue":80}],72:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.EVENT_VISIBILITY_CHANGE_TYPE=n.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=n.UNSTABLE_MSC3089_BRANCH=n.UNSTABLE_MSC3089_LEAF=n.UNSTABLE_MSC3089_TREE_SUBTYPE=n.UNSTABLE_MSC3088_ENABLED=n.UNSTABLE_MSC3088_PURPOSE=n.RoomType=n.RoomCreateTypeField=n.MsgType=n.RelationType=n.EventType=void 0;const i=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.RoomAliases="m.room.aliases",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.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",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"}(n.EventType||(n.EventType={})),function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"}(n.RelationType||(n.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"}(n.MsgType||(n.MsgType={})),n.RoomCreateTypeField="type",function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"}(n.RoomType||(n.RoomType={})),n.UNSTABLE_MSC3088_PURPOSE=new i.UnstableValue("m.room.purpose","org.matrix.msc3088.purpose"),n.UNSTABLE_MSC3088_ENABLED=new i.UnstableValue("m.enabled","org.matrix.msc3088.enabled"),n.UNSTABLE_MSC3089_TREE_SUBTYPE=new i.UnstableValue("m.data_tree","org.matrix.msc3089.data_tree"),n.UNSTABLE_MSC3089_LEAF=new i.UnstableValue("m.leaf","org.matrix.msc3089.leaf"),n.UNSTABLE_MSC3089_BRANCH=new i.UnstableValue("m.branch","org.matrix.msc3089.branch"),n.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=new i.UnstableValue("io.element.functional_members","io.element.functional_members"),n.EVENT_VISIBILITY_CHANGE_TYPE=new i.UnstableValue("m.visibility","org.matrix.msc3531.visibility")},{"../NamespacedValue":80}],73:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TEXT_NODE_TYPE=void 0;const i=e("../NamespacedValue");n.TEXT_NODE_TYPE=new i.UnstableValue("m.text","org.matrix.msc1767.text")},{"../NamespacedValue":80}],74:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.M_LOCATION=n.M_TIMESTAMP=n.M_ASSET=n.LocationAssetType=void 0;const i=e("../NamespacedValue");e("./extensible_events");!function(e){e.Self="m.self",e.Pin="m.pin"}(n.LocationAssetType||(n.LocationAssetType={})),n.M_ASSET=new i.UnstableValue("m.asset","org.matrix.msc3488.asset"),n.M_TIMESTAMP=new i.UnstableValue("m.ts","org.matrix.msc3488.ts"),n.M_LOCATION=new i.UnstableValue("m.location","org.matrix.msc3488.location")},{"../NamespacedValue":80,"./extensible_events":73}],75:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.HistoryVisibility=n.GuestAccess=n.RestrictedAllowType=n.JoinRule=n.Preset=n.Visibility=void 0,function(e){e.Public="public",e.Private="private"}(n.Visibility||(n.Visibility={})),function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"}(n.Preset||(n.Preset={})),function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"}(n.JoinRule||(n.JoinRule={})),function(e){e.RoomMembership="m.room_membership"}(n.RestrictedAllowType||(n.RestrictedAllowType={})),function(e){e.CanJoin="can_join",e.Forbidden="forbidden"}(n.GuestAccess||(n.GuestAccess={})),function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"}(n.HistoryVisibility||(n.HistoryVisibility={}))},{}],76:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.ReceiptType=void 0,function(e){e.Read="m.read",e.FullyRead="m.fully_read",e.ReadPrivate="org.matrix.msc2285.read.private"}(n.ReceiptType||(n.ReceiptType={}))},{}],77:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0})},{}],78:[function(e,t,n){"use strict";var i;Object.defineProperty(n,"__esModule",{value:!0}),n.SearchOrderBy=void 0,function(e){e.RoomId="room_id",e.Sender="sender"}(i||(i={})),function(e){e.Recent="recent",e.Rank="rank"}(n.SearchOrderBy||(n.SearchOrderBy={}))},{}],79:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.M_TOPIC=void 0;const i=e("../NamespacedValue");n.M_TOPIC=new i.UnstableValue("m.topic","org.matrix.msc3765.topic")},{"../NamespacedValue":80}],80:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.UnstableValue=n.ServerControlledNamespacedValue=n.NamespacedValue=void 0;class i{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}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}}n.NamespacedValue=i;n.ServerControlledNamespacedValue=class extends i{constructor(){super(...arguments),this.preferUnstable=!1}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}};n.UnstableValue=class extends i{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}}},{}],81:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TypedReEmitter=n.ReEmitter=void 0;class i{constructor(e){this.target=e}reEmit(e,t){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)}}}n.ReEmitter=i;n.TypedReEmitter=class extends i{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}}},{}],82:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.AutoDiscovery=n.AutoDiscoveryAction=void 0;const r=e("./logger");var o;!function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"}(o=n.AutoDiscoveryAction||(n.AutoDiscoveryAction={}));class s{static fromDiscoveryConfig(e){return i(this,void 0,void 0,(function*(){const t={"m.homeserver":{state:s.FAIL_ERROR,error:s.ERROR_INVALID,base_url:null},"m.identity_server":{state:s.PROMPT,error:null,base_url:null}};if(!e||!e["m.homeserver"])return r.logger.error("No m.homeserver key in config"),t["m.homeserver"].state=s.FAIL_PROMPT,t["m.homeserver"].error=s.ERROR_INVALID,Promise.resolve(t);if(!e["m.homeserver"].base_url)return r.logger.error("No m.homeserver base_url in config"),t["m.homeserver"].state=s.FAIL_PROMPT,t["m.homeserver"].error=s.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const n=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!n)return r.logger.error("Invalid base_url for m.homeserver"),t["m.homeserver"].error=s.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const i=yield this.fetchWellKnownObject(`${n}/_matrix/client/versions`);if(!i||!i.raw.versions)return r.logger.error("Invalid /versions response"),t["m.homeserver"].error=s.ERROR_INVALID_HOMESERVER,t["m.homeserver"].base_url=n,Promise.resolve(t);t["m.homeserver"]={state:s.SUCCESS,error:null,base_url:n};let a="";if(e["m.identity_server"]){const n={"m.homeserver":t["m.homeserver"],"m.identity_server":{state:s.FAIL_PROMPT,error:s.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"),n["m.identity_server"].error=s.ERROR_INVALID_IS_BASE_URL,Promise.resolve(n);const i=yield this.fetchWellKnownObject(`${a}/_matrix/identity/api/v1`);if(!i||!i.raw||i.action!==o.SUCCESS)return r.logger.error("Invalid /api/v1 response"),n["m.identity_server"].error=s.ERROR_INVALID_IDENTITY_SERVER,n["m.identity_server"].base_url=a,Promise.resolve(n)}return a&&a.toString().length>0&&(t["m.identity_server"]={state:s.SUCCESS,error:null,base_url:a}),Object.keys(e).forEach((n=>{if("m.homeserver"===n||"m.identity_server"===n){const i=["error","state","base_url"];for(const r of Object.keys(e[n]))i.includes(r)||(t[n][r]=e[n][r])}else t[n]=e[n]})),Promise.resolve(t)}))}static findClientConfig(e){return i(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:s.FAIL_ERROR,error:s.ERROR_INVALID,base_url:null},"m.identity_server":{state:s.PROMPT,error:null,base_url:null}},n=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return n&&n.action===o.SUCCESS?s.fromDiscoveryConfig(n.raw):(r.logger.error("No response or error when parsing .well-known"),n.reason&&r.logger.error(n.reason),n.action===o.IGNORE?t["m.homeserver"]={state:s.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=s.FAIL_PROMPT,t["m.homeserver"].error=s.ERROR_INVALID),Promise.resolve(t))}))}static getRawClientConfig(e){return i(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=null;try{t=new URL(e)}catch(e){r.logger.error("Could not parse url",e)}if(!t||!t.hostname)return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const n=t.port?`:${t.port}`:"",i=t.pathname?t.pathname:"";let o=`${t.protocol}//${t.hostname}${n}${i}`;return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(e){return r.logger.error(e),!1}}static fetchWellKnownObject(t){return new Promise((function(n){const i=e("./matrix").getRequest();if(!i)throw new Error("No request library available");i({method:"GET",uri:t,timeout:5e3},((e,t,i)=>{if(e||t&&(t.statusCode<200||t.statusCode>=300)){let i=o.FAIL_PROMPT,r=(e?e.message:null)||"General failure";return t&&404===t.statusCode&&(i=o.IGNORE,r=s.ERROR_MISSING_WELLKNOWN),void n({raw:{},action:i,reason:r,error:e})}try{n({raw:JSON.parse(i),action:o.SUCCESS})}catch(e){let t=s.ERROR_INVALID;"SyntaxError"===e.name&&(t=s.ERROR_INVALID_JSON),n({raw:{},action:o.FAIL_PROMPT,reason:t,error:e})}}))}))}}n.AutoDiscovery=s,s.ERROR_INVALID="Invalid homeserver discovery response",s.ERROR_GENERIC_FAILURE="Failed to get autodiscovery configuration from server",s.ERROR_INVALID_HS_BASE_URL="Invalid base_url for m.homeserver",s.ERROR_INVALID_HOMESERVER="Homeserver URL does not appear to be a valid Matrix homeserver",s.ERROR_INVALID_IS_BASE_URL="Invalid base_url for m.identity_server",s.ERROR_INVALID_IDENTITY_SERVER="Identity server URL does not appear to be a valid identity server",s.ERROR_INVALID_IS="Invalid identity server discovery response",s.ERROR_MISSING_WELLKNOWN="No .well-known JSON file found",s.ERROR_INVALID_JSON="Invalid JSON",s.ALL_ERRORS=[s.ERROR_INVALID,s.ERROR_GENERIC_FAILURE,s.ERROR_INVALID_HS_BASE_URL,s.ERROR_INVALID_HOMESERVER,s.ERROR_INVALID_IS_BASE_URL,s.ERROR_INVALID_IDENTITY_SERVER,s.ERROR_INVALID_IS,s.ERROR_MISSING_WELLKNOWN,s.ERROR_INVALID_JSON],s.FAIL_ERROR=o.FAIL_ERROR,s.FAIL_PROMPT=o.FAIL_PROMPT,s.PROMPT=o.PROMPT,s.SUCCESS=o.SUCCESS},{"./logger":126,"./matrix":127}],83:[function(e,t,n){(function(t){(function(){"use strict";var i=e("@babel/runtime/helpers/interopRequireDefault"),r=e("@babel/runtime/helpers/typeof");Object.defineProperty(n,"__esModule",{value:!0});var o={};n.default=void 0;var s,a=i(e("browser-request")),c=i(e("qs")),l=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!==r(e)&&"function"!=typeof e)return{default:e};var n=d(t);if(n&&n.has(e))return n.get(e);var i={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var a=o?Object.getOwnPropertyDescriptor(e,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=e[s]}i.default=e,n&&n.set(e,i);return i}(e("./matrix"));function d(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(d=function(e){return e?n:t})(e)}if(Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(o,e)||e in n&&n[e]===l[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return l[e]}}))})),l.getRequest())throw new Error("Multiple matrix-js-sdk entrypoints detected!");l.request((function(e,t){return e.qs=c.default.stringify(e.qs||{},e.qsStringifyOptions),(0,a.default)(e,t)}));try{s=t.indexedDB}catch(e){}s&&l.setCryptoStoreFactory((function(){return new l.IndexedDBCryptoStore(s,"matrix-js-sdk:crypto")}));var u=l;n.default=u,t.matrixcs=l}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./matrix":127,"@babel/runtime/helpers/interopRequireDefault":7,"@babel/runtime/helpers/typeof":12,"browser-request":17,qs:59}],84:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.MatrixClient=n.ClientEvent=n.RoomVersionStability=n.PendingEventOrdering=n.CRYPTO_ENABLED=void 0;const a=e("matrix-events-sdk"),c=e("./sync"),l=e("./models/event"),d=e("./store/stub"),u=e("./webrtc/call"),h=e("./filter"),g=e("./webrtc/callEventHandler"),p=o(e("./utils")),f=e("./utils"),v=e("./models/event-timeline"),y=e("./pushprocessor"),m=e("./autodiscovery"),E=o(e("./crypto/olmlib")),S=e("./crypto/olmlib"),b=e("./ReEmitter"),_=e("./crypto/RoomList"),T=e("./logger"),w=e("./service-types"),I=e("./http-api"),R=e("./crypto"),k=e("./crypto/recoverykey"),O=e("./crypto/key_passphrase"),C=e("./models/user"),P=e("./content-repo"),M=e("./models/search-result"),D=e("./crypto/dehydration"),A=e("./matrix"),x=e("./crypto/api"),U=o(e("./content-helpers")),N=e("./@types/event"),L=e("./@types/partials"),B=e("./event-mapper"),K=e("./randomstring"),j=e("./crypto/backup"),F=e("./models/MSC3089TreeSpace"),q=e("./@types/search"),V=e("./@types/PushRules"),$=e("./webrtc/mediaHandler"),G=e("./models/typed-event-emitter"),H=e("./@types/read_receipts"),W=e("./models/thread"),Y=e("./@types/beacon");n.CRYPTO_ENABLED=(0,R.isCryptoAvailable)();const Q=6e5;var J;!function(e){e.Chronological="chronological",e.Detached="detached"}(n.PendingEventOrdering||(n.PendingEventOrdering={})),function(e){e.Stable="stable",e.Unstable="unstable"}(n.RoomVersionStability||(n.RoomVersionStability={})),function(e){e.MasterKey="master_key",e.SelfSigningKey="self_signing_key",e.UserSigningKey="user_signing_key"}(J||(J={}));const z="$";var X;!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"}(X=n.ClientEvent||(n.ClientEvent={}));class Z extends G.TypedEventEmitter{constructor(e){super(),this.reEmitter=new b.TypedReEmitter(this),this.olmVersion=null,this.usingExternalCrypto=!1,this.clientRunning=!1,this.timelineSupport=!1,this.urlPreviewCache={},this.unstableClientRelationAggregation=!1,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.pushProcessor=new y.PushProcessor(this),this.turnServers=[],this.turnServersExpiry=0,this.txnCtr=0,this.mediaHandler=new $.MediaHandler(this),this.pendingEventEncryption=new Map,this.startCallEventHandler=()=>{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.off(X.Sync,this.startCallEventHandler))},e.baseUrl=p.ensureNoTrailingSlash(e.baseUrl),e.idBaseUrl=p.ensureNoTrailingSlash(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.usingExternalCrypto=e.usingExternalCrypto,this.store=e.store||new d.StubStore,this.deviceId=e.deviceId||null;const t=e.userId||null;this.credentials={userId:t},this.http=new I.MatrixHttpApi(this,{baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:I.PREFIX_R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?T.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?T.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):T.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!==l.EventStatus.SENDING&&this.updatePendingEventStatus(t,e,l.EventStatus.SENDING);const n=yield this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,l.EventStatus.SENT,n.event_id),n})))),(0,u.supportsMatrixCall)()&&(this.callEventHandler=new g.CallEventHandler(this),this.canSupportVoip=!0,this.on(X.Sync,this.startCallEventHandler)),this.timelineSupport=Boolean(e.timelineSupport),this.unstableClientRelationAggregation=!!e.unstableClientRelationAggregation,this.cryptoStore=e.cryptoStore,this.sessionStore=e.sessionStore,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.roomList=new _.RoomList(this.cryptoStore),this.on(l.MatrixEventEvent.Decrypted,(e=>{var t,n;const i=e.getPushActions(),r=this.getPushActionsForEvent(e,!0),o=this.getRoom(e.getRoomId());if(!o)return;const s=o.getUnreadNotificationCount(A.NotificationCountType.Highlight),a=!!(null===(t=null==i?void 0:i.tweaks)||void 0===t?void 0:t.highlight),c=!!(null===(n=null==r?void 0:r.tweaks)||void 0===n?void 0:n.highlight);if((a!==c||s>0)&&!o.hasUserReadEvent(this.getUserId(),e.getId())){let e=s;c&&!a&&e++,!c&&a&&e--,o.setUnreadNotificationCount(A.NotificationCountType.Highlight,e);o.getUnreadNotificationCount(A.NotificationCountType.Total)<e&&o.setUnreadNotificationCount(A.NotificationCountType.Total,e)}})),this.on(A.RoomEvent.Receipt,((e,t)=>{if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter((e=>{const t=n[e][H.ReceiptType.Read];if(t&&Object.keys(t).includes(this.getUserId()))return!0;const i=n[e][H.ReceiptType.ReadPrivate];return!(!i||!Object.keys(i).includes(this.getUserId()))})).length>0))return;const i=20,r=t.getLiveTimeline().getEvents();let o=0;for(let e=r.length-1;e>=0;e--){if(e===r.length-i)return;const n=r[e];if(t.hasUserReadEvent(this.getUserId(),n.getId()))break;const s=this.getPushActionsForEvent(n);o+=s.tweaks&&s.tweaks.highlight?1:0}t.setUnreadNotificationCount(A.NotificationCountType.Highlight,o)}}))}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.crypto&&(this.crypto.uploadDeviceKeys(),this.crypto.start()),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),Q),this.checkTurnServers()),this.syncApi&&(T.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{const{serverSupport:e,stable:t}=yield this.doesServerSupportThread();W.Thread.setServerSideSupport(e,t)}catch(e){W.Thread.setServerSideSupport(!1,!0)}this.clientOpts=Object.assign({},e),this.clientOpts.crypto=this.crypto,this.clientOpts.canResetEntireTimeline=e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e),this.syncApi=new c.SyncApi(this,this.clientOpts),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval((()=>{this.fetchClientWellKnown()}),1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown())}))}stopClient(){var e,n,i,r;null===(e=this.crypto)||void 0===e||e.stop(),this.clientRunning&&(T.logger.log("stopping MatrixClient"),this.clientRunning=!1,null===(n=this.syncApi)||void 0===n||n.stop(),this.syncApi=null,null===(i=this.peekSync)||void 0===i||i.stopPeeking(),null===(r=this.callEventHandler)||void 0===r||r.stop(),this.callEventHandler=null,t.clearInterval(this.checkTurnServersIntervalID),void 0!==this.clientWellKnownIntervalID&&t.clearInterval(this.clientWellKnownIntervalID))}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 T.logger.info("no dehydrated device found");const n=new t.Olm.Account;try{const t=e.device_data;if(t.algorithm!==D.DEHYDRATION_ALGORITHM)return void T.logger.warn("Wrong algorithm for dehydrated device");T.logger.log("unpickling dehydrated device");const i=yield this.cryptoCallbacks.getDehydrationKey(t,(e=>{n.unpickle(new Uint8Array(e),t.account)}));n.unpickle(i,t.account),T.logger.log("unpickled device");if(!0===(yield this.http.authedRequest(void 0,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,T.logger.info("using dehydrated device");const t=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:n.pickle(t),sessions:[],pickleKey:t},n.free(),this.deviceId}return n.free(),void T.logger.info("not using dehydrated device")}catch(e){n.free(),T.logger.warn("could not unpickle",e)}}))}getDehydratedDevice(){return s(this,void 0,void 0,(function*(){try{return yield this.http.authedRequest(void 0,I.Method.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void T.logger.info("could not get dehydrated device",e.toString())}}))}setDehydrationKey(e,t,n){if(this.crypto)return this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n);T.logger.warn("not dehydrating device if crypto is not enabled")}createDehydratedDevice(e,t,n){return s(this,void 0,void 0,(function*(){if(this.crypto)return yield this.crypto.dehydrationManager.setKey(e,t,n),this.crypto.dehydrationManager.dehydrateDevice();T.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()};T.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=[];return e.push(this.store.deleteAllData()),this.cryptoStore&&e.push(this.cryptoStore.deleteAllData()),Promise.all(e).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}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}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}createCall(e){return(0,u.createNewMatrixCall)(this,e)}getSyncState(){return this.syncApi?this.syncApi.getSyncState():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(){return this.syncApi.retryImmediately()}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?(T.logger.log("Returning cached capabilities"),Promise.resolve(this.cachedCapabilities.capabilities)):this.http.authedRequest(void 0,I.Method.Get,"/capabilities").catch((e=>{T.logger.error(e)})).then(((e={})=>{const n=e.capabilities||{},i=Object.keys(n).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:n,expiration:t+i},T.logger.log("Caching capabilities: ",n),n}))}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.crypto)return void T.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.sessionStore)throw new Error("Cannot enable encryption: no sessionStore provided");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");T.logger.log("Crypto: Starting up crypto store..."),yield this.cryptoStore.startup(),T.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,this.sessionStore,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]),T.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.crypto=t}))}isCryptoEnabled(){return!!this.crypto}getDeviceEd25519Key(){return this.crypto?this.crypto.getDeviceEd25519Key():null}getDeviceCurve25519Key(){return this.crypto?this.crypto.getDeviceCurve25519Key():null}uploadKeys(){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.uploadDeviceKeys()}))}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,n=!0){const i=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),i}setDeviceBlocked(e,t,n=!0){return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t,n=!0){return this.setDeviceVerification(e,t,null,null,n)}setDeviceVerification(e,t,n,i,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,n,i,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,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,n)}checkSecretStorageKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalBlacklistUnverifiedDevices(e)}getGlobalBlacklistUnverifiedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalBlacklistUnverifiedDevices()}setGlobalErrorOnUnknownDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalErrorOnUnknownDevices(e)}getGlobalErrorOnUnknownDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalErrorOnUnknownDevices()}getCrossSigningId(e=x.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.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.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,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.prepareToEncrypt(e)}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");return this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.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,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,n)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,n)}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()}))}cancelAndResendEventRoomKeyRequest(e){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(N.EventType.RoomEncryption,"")||this.roomList.isRoomEncrypted(e)}forceDiscardSession(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");this.crypto.forceDiscardSession(e)}exportRoomKeys(){return this.crypto?this.crypto.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(){return this.crypto.backupManager.checkKeyBackup()}getKeyBackupVersion(){return s(this,void 0,void 0,(function*(){let e;try{e=yield this.http.authedRequest(void 0,I.Method.Get,"/room_keys/version",void 0,void 0,{prefix:I.PREFIX_UNSTABLE})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}return j.BackupManager.checkBackupVersion(e),e}))}isKeyBackupTrusted(e){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:n,auth_data:i,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)),T.logger.info("Key backup private key stored in secret storage")),{algorithm:n,auth_data:i,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 n=yield this.http.authedRequest(void 0,I.Method.Post,"/room_keys/version",void 0,t,{prefix:I.PREFIX_UNSTABLE});return yield this.checkKeyBackup(),this.getKeyBackupEnabled()||T.logger.error("Key backup not usable even though we just created it"),n}))}deleteKeyBackupVersion(e){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});return this.http.authedRequest(void 0,I.Method.Delete,t,void 0,void 0,{prefix:I.PREFIX_UNSTABLE})}makeKeyBackupPath(e,t,n){let i;i=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:i,queryData:void 0===n?void 0:{version:n}}}sendKeyBackup(e,t,n,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,I.Method.Put,r.path,r.queryData,i,{prefix:I.PREFIX_UNSTABLE})}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,k.decodeRecoveryKey)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return(0,O.keyFromAuthData)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return(0,k.decodeRecoveryKey)(e)}restoreKeyBackupWithPassword(e,t,n,i,r){return s(this,void 0,void 0,(function*(){const o=yield(0,O.keyFromAuthData)(i.auth_data,e);return this.restoreKeyBackup(o,t,n,i,r)}))}restoreKeyBackupWithSecretStorage(e,t,n,i){return s(this,void 0,void 0,(function*(){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])}const s=(0,S.decodeBase64)(o||r);return this.restoreKeyBackup(s,t,n,e,i)}))}restoreKeyBackupWithRecoveryKey(e,t,n,i,r){const o=(0,k.decodeRecoveryKey)(e);return this.restoreKeyBackup(o,t,n,i,r)}restoreKeyBackupWithCache(e,t,n,i){return s(this,void 0,void 0,(function*(){const r=yield this.crypto.getSessionBackupPrivateKey();if(!r)throw new Error("Couldn't get key");return this.restoreKeyBackup(r,e,t,n,i)}))}restoreKeyBackup(e,t,n,i,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,l=[];const d=this.makeKeyBackupPath(t,n,i.version),u=yield j.BackupManager.makeAlgorithm(i,(()=>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:Z.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{T.logger.warn("Error caching session backup key:",e)})).then(o),a&&a({stage:"fetch"});const i=yield this.http.authedRequest(void 0,I.Method.Get,d.path,d.queryData,void 0,{prefix:I.PREFIX_UNSTABLE});if(i.rooms){const e=i.rooms;for(const[t,n]of Object.entries(e)){if(!n.sessions)continue;c+=Object.keys(n.sessions).length;const e=yield u.decryptSessions(n.sessions);for(const n of e)n.room_id=t,l.push(n)}}else if(i.sessions){const e=i.sessions;c=Object.keys(e).length,l=yield u.decryptSessions(e);for(const e of l)e.room_id=t}else{c=1;try{const[e]=yield u.decryptSessions({[n]:i});e.room_id=t,e.session_id=n,l.push(e)}catch(e){T.logger.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return yield this.importRoomKeys(l,{progressCallback:a,untrusted:h,source:"backup"}),yield this.checkKeyBackup(),{total:c,imported:l.length}}))}deleteKeysFromBackup(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,I.Method.Delete,i.path,i.queryData,void 0,{prefix:I.PREFIX_UNSTABLE})}sendSharedHistoryKeys(e,t){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.roomList.getRoomEncryption(e);if(!n)return void T.logger.error("Unknown room. Not sharing decryption keys");const i=yield this.crypto.downloadKeys(t),r={};for(const[e,t]of Object.entries(i))r[e]=Object.values(t);const o=this.crypto.getRoomDecryptor(e,n.algorithm);o.sendSharedHistoryInboundSessions?yield o.sendSharedHistoryInboundSessions(r):T.logger.warn("Algorithm does not support sharing previous keys",n.algorithm)}))}getMediaConfig(e){return this.http.authedRequest(e,I.Method.Get,"/config",void 0,void 0,{prefix:I.PREFIX_MEDIA_R0})}getRoom(e){return this.store.getRoom(e)}getRooms(){return this.store.getRooms()}getVisibleRooms(){const e=this.store.getRooms(),t=new Set;for(const n of e){const e=n.currentState.getStateEvents(N.EventType.RoomCreate,"");if(e){const n=e.getContent().predecessor;n&&n.room_id&&t.add(n.room_id)}}return e.filter((e=>!e.currentState.getStateEvents(N.EventType.RoomTombstone,"")||!t.has(e.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t,n){const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e}),r=(0,I.retryNetworkOperation)(5,(()=>this.http.authedRequest(void 0,I.Method.Put,i,void 0,t)));return n&&r.then((e=>n(null,e)),n),r}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 n=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return yield this.http.authedRequest(void 0,I.Method.Get,n)}catch(e){if("M_NOT_FOUND"===(null===(t=e.data)||void 0===t?void 0:t.errcode))return null;throw e}}))}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,t){const n={ignored_users:{}};return e.forEach((e=>{n.ignored_users[e]={}})),this.setAccountData("m.ignored_user_list",n,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e,t,n){return s(this,void 0,void 0,(function*(){if(p.isFunction(t))throw new Error("Expected 'opts' object, got function.");void 0===(t=t||{}).syncRoom&&(t.syncRoom=!0);const i=this.getRoom(e);if(i&&i.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(i);let r=Promise.resolve();t.inviteSignUrl&&(r=this.http.requestOtherUrl(void 0,I.Method.Post,t.inviteSignUrl,{mxid:this.credentials.userId}));const o={};t.viaServers&&(o.server_name=t.viaServers);const s={qsStringifyOptions:{arrayFormat:"repeat"}};try{const i={},a=yield r;a&&(i.third_party_signed=a);const l=p.encodeUri("/join/$roomid",{$roomid:e}),d=(yield this.http.authedRequest(void 0,I.Method.Post,l,o,i,s)).room_id,u=new c.SyncApi(this,this.clientOpts).createRoom(d);return t.syncRoom,null==n||n(null,u),u}catch(e){throw null==n||n(e),e}}))}resendEvent(e,t){return this.updatePendingEventStatus(t,e,l.EventStatus.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![l.EventStatus.QUEUED,l.EventStatus.NOT_SENT,l.EventStatus.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===l.EventStatus.ENCRYPTING?this.pendingEventEncryption.delete(e.getId()):this.scheduler&&e.status===l.EventStatus.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,l.EventStatus.CANCELLED)}setRoomName(e,t,n){return this.sendStateEvent(e,N.EventType.RoomName,{name:t},void 0,n)}setRoomTopic(e,t,n){const i="function"==typeof n,r=i?void 0:n,o=i?n:void 0,s=U.makeTopicContent(t,r);return this.sendStateEvent(e,N.EventType.RoomTopic,s,void 0,o)}getRoomTags(e,t){const n=p.encodeUri("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(t,I.Method.Get,n)}setRoomTag(e,t,n,i){const r=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(i,I.Method.Put,r,void 0,n)}deleteRoomTag(e,t,n){const i=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(n,I.Method.Delete,i)}setRoomAccountData(e,t,n,i){const r=p.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(i,I.Method.Put,r,void 0,n)}setPowerLevel(e,t,n,i,r){let o={users:{}};(null==i?void 0:i.getType())===N.EventType.RoomPowerLevels&&(o=p.deepCopy(i.getContent())),o.users[t]=n;const s=p.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(r,I.Method.Put,s,void 0,o)}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*(){const n=this.getUserId();return this.sendStateEvent(e,Y.M_BEACON_INFO.name,t,n)}))}sendEvent(e,t,n,i,r,o){var s,a,c;if((null==t?void 0:t.startsWith(z))||null===t||(o=r,r=i,i=n,n=t,t=null),t&&!(null===(s=i["m.relates_to"])||void 0===s?void 0:s.rel_type)){i["m.relates_to"]=Object.assign(Object.assign({},i["m.relates_to"]),{rel_type:W.THREAD_RELATION_TYPE.name,event_id:t});const n=null===(a=this.getRoom(e))||void 0===a?void 0:a.getThread(t);n&&(i["m.relates_to"]["m.in_reply_to"]={event_id:null===(c=n.lastReply((e=>e.isRelation(W.THREAD_RELATION_TYPE.name)&&!e.status)))||void 0===c?void 0:c.getId()})}return this.sendCompleteEvent(e,t,{type:n,content:i},r,o)}sendCompleteEvent(e,t,n,i,r){p.isFunction(i)&&(r=i,i=void 0),i||(i=this.makeTxnId());const o=new l.MatrixEvent(Object.assign(n,{event_id:"~"+e+":"+i,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),s=this.getRoom(e),a=null==s?void 0:s.getThread(t);a&&o.setThread(a),this.reEmitter.reEmit(o,[l.MatrixEventEvent.Replaced,l.MatrixEventEvent.VisibilityChange]),null==s||s.reEmitter.reEmit(o,[l.MatrixEventEvent.BeforeRedaction]);const c=o.getAssociatedId();if(null==c?void 0:c.startsWith("~")){const e=s.getPendingEvents().find((e=>e.getId()===c));e.once(l.MatrixEventEvent.LocalEventIdReplaced,(()=>{o.updateAssociatedId(e.getId())}))}const d=o.getType();return T.logger.log(`sendEvent of type ${d} in ${e} with txnId ${i}`),o.setTxnId(i),o.setStatus(l.EventStatus.SENDING),null==s||s.addPendingEvent(o,i),o.status===l.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(s,o,r)}encryptAndSendEvent(e,t,n){let i=!1;return Promise.resolve().then((()=>{const n=this.encryptEventIfNeeded(t,e);return n?(this.pendingEventEncryption.set(t.getId(),n),this.updatePendingEventStatus(e,t,l.EventStatus.ENCRYPTING),n.then((()=>{this.pendingEventEncryption.has(t.getId())?this.updatePendingEventStatus(e,t,l.EventStatus.SENDING):i=!0}))):null})).then((()=>{if(i)return{};let n;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,l.EventStatus.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then((n=>(e.updatePendingEvent(t,l.EventStatus.SENT,n.event_id),n))))),n})).then((e=>(null==n||n(null,e),e))).catch((i=>{T.logger.error("Error sending event",i.stack||i);try{t.error=i,this.updatePendingEventStatus(e,t,l.EventStatus.NOT_SENT),i.event=t,null==n||n(i)}catch(e){T.logger.error("Exception in error handler!",e.stack||i)}throw i}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(e.isRedaction())return null;if(!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.crypto&&this.usingExternalCrypto)return null;if(e.getType()===N.EventType.Reaction)return null;if(!this.crypto)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.crypto.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===N.EventType.Reaction?t:this.isRoomEncrypted(e)?N.EventType.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,n){e?e.updatePendingEvent(t,n):t.setStatus(n)}sendEventHttpRequest(e){let t=e.getTxnId();t||(t=this.makeTxnId(),e.setTxnId(t));const n={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:t};let i;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),i=p.encodeUri(t,n)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";i=p.encodeUri(t,Object.assign({$redactsEventId:e.event.redacts},n))}else i=p.encodeUri("/rooms/$roomId/send/$eventType/$txnId",n);return this.http.authedRequest(void 0,I.Method.Put,i,void 0,e.getWireContent()).then((t=>(T.logger.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,n,i,r){(null==n?void 0:n.startsWith(z))||(r=i,i=n,n=t,t=null);const o=("object"==typeof r?r:{}).reason,s="function"==typeof r?r:void 0;return this.sendCompleteEvent(e,t,{type:N.EventType.RoomRedaction,content:{reason:o},redacts:n},i,s)}sendMessage(e,t,n,i,r){"string"!=typeof t&&null!==t&&(r=i,i=n,n=t,t=null),p.isFunction(i)&&(r=i,i=void 0);let o=N.EventType.RoomMessage,s=n;const c=(e={},t=!0)=>{let n=null;if(e.msgtype===N.MsgType.Text?n=a.MessageEvent.from(e.body,e.formatted_body).serialize():e.msgtype===N.MsgType.Emote?n=a.EmoteEvent.from(e.body,e.formatted_body).serialize():e.msgtype===N.MsgType.Notice&&(n=a.NoticeEvent.from(e.body,e.formatted_body).serialize()),n&&e["m.new_content"]&&t){const t=c(e["m.new_content"],!1);t&&(n.content["m.new_content"]=t.content)}if(n)for(const[t,i]of Object.entries(e))n.content.hasOwnProperty(t)||(n.content[t]=i);return n},l=c(s);return l&&(o=l.type,s=l.content),this.sendEvent(e,t,o,s,i,r)}sendTextMessage(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeTextMessage(n);return this.sendMessage(e,t,o,i,r)}sendNotice(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeNotice(n);return this.sendMessage(e,t,o,i,r)}sendEmoteMessage(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeEmoteMessage(n);return this.sendMessage(e,t,o,i,r)}sendImageMessage(e,t,n,i,r="Image",o){(null==t?void 0:t.startsWith(z))||null===t||(o=r,r=i||"Image",i=n,n=t,t=null),p.isFunction(r)&&(o=r,r=void 0);const s={msgtype:N.MsgType.Image,url:n,info:i,body:r};return this.sendMessage(e,t,s,void 0,o)}sendStickerMessage(e,t,n,i,r="Sticker",o){(null==t?void 0:t.startsWith(z))||null===t||(o=r,r=i||"Sticker",i=n,n=t,t=null),p.isFunction(r)&&(o=r,r=void 0);const s={url:n,info:i,body:r};return this.sendEvent(e,t,N.EventType.Sticker,s,void 0,o)}sendHtmlMessage(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeHtmlMessage(n,i);return this.sendMessage(e,t,o,void 0,r)}sendHtmlNotice(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeHtmlNotice(n,i);return this.sendMessage(e,t,o,void 0,r)}sendHtmlEmote(e,t,n,i,r){(null==t?void 0:t.startsWith(z))||null===t||(r=i,i=n,n=t,t=null);const o=U.makeHtmlEmote(n,i);return this.sendMessage(e,t,o,void 0,r)}sendReceipt(e,t,n,i){if("function"==typeof n&&(i=n,n={}),this.isGuest())return Promise.resolve({});const r=p.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),o=this.http.authedRequest(i,I.Method.Post,r,void 0,n||{}),s=this.getRoom(e.getRoomId());return s&&s.addLocalEchoReceipt(this.credentials.userId,e,t),o}sendReadReceipt(e,t=H.ReceiptType.Read,n){return s(this,void 0,void 0,(function*(){const i=e.getId(),r=this.getRoom(e.getRoomId());if(r&&r.hasPendingEvent(i))throw new Error(`Cannot set read receipt to a pending event (${i})`);return this.sendReceipt(e,t,{},n)}))}setRoomReadMarkers(e,t,n,i){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(n){if(o=n.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,n,H.ReceiptType.Read)}if(i){if(s=i.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,i,H.ReceiptType.ReadPrivate)}return this.setRoomReadMarkersHttpRequest(e,t,o,s)}))}getUrlPreview(e,t,n){t=6e4*Math.floor(t/6e4);const i=new URL(e);i.hash="";const r=t+"_"+(e=i.toString()),o=this.urlPreviewCache[r];if(o)return n&&o.then(n).catch(n),o;const s=this.http.authedRequest(n,I.Method.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:I.PREFIX_MEDIA_R0});return this.urlPreviewCache[r]=s,s}sendTyping(e,t,n,i){if(this.isGuest())return Promise.resolve({});const r=p.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),o={typing:t};return t&&(o.timeout=n||2e4),this.http.authedRequest(i,I.Method.Put,r,void 0,o)}getRoomUpgradeHistory(e,t=!1){let n=this.getRoom(e);if(!n)return[];const i=[n];let r=n.currentState.getStateEvents(N.EventType.RoomCreate,"");for(;r;){const e=r.getContent().predecessor;if(!e||!e.room_id)break;{const n=this.getRoom(e.room_id);if(!n)break;if(t){const e=n.currentState.getStateEvents(N.EventType.RoomTombstone,"");if(!e||e.getContent().replacement_room!==n.roomId)break}i.splice(0,0,n),r=n.currentState.getStateEvents(N.EventType.RoomCreate,"")}}let o=n.currentState.getStateEvents(N.EventType.RoomTombstone,"");for(;o;){const e=this.getRoom(o.getContent().replacement_room);if(!e)break;if(e.roomId===n.roomId)break;if(t){if(r=e.currentState.getStateEvents(N.EventType.RoomCreate,""),!r||!r.getContent().predecessor)break;if(r.getContent().predecessor.room_id!==n.roomId)break}i.push(e);if(new Set(i.map((e=>e.roomId))).size<i.length)return i.slice(0,i.length-1);n=e,o=n.currentState.getStateEvents(N.EventType.RoomTombstone,"")}return i}invite(e,t,n,i){return this.membershipChange(e,t,"invite",i,n)}inviteByEmail(e,t,n){return this.inviteByThreePid(e,"email",t,n)}inviteByThreePid(e,t,n,i){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:n};if(this.identityServer&&this.identityServer.getAccessToken&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(s.id_access_token=e)}return this.http.authedRequest(i,I.Method.Post,r,void 0,s)}))}leave(e,t){return this.membershipChange(e,void 0,"leave",void 0,t)}leaveRoomChain(e,t=!0){const n=this.getRoomUpgradeHistory(e);let i=n;if(!t){i=[];for(const t of n)if(i.push(t),t.roomId===e)break}const r={},o=[],s=e=>this.leave(e).then((()=>{r[e]=null})).catch((t=>(r[e]=t,null)));for(const e of i)o.push(s(e.roomId));return Promise.all(o).then((()=>r))}ban(e,t,n,i){return this.membershipChange(e,t,"ban",n,i)}forget(e,t,n){void 0===t&&(t=!0);const i=this.membershipChange(e,void 0,"forget",void 0,n);return t?i.then((t=>(this.store.removeRoom(e),this.emit(X.DeleteRoom,e),t))):i}unban(e,t,n){const i=p.encodeUri("/rooms/$roomId/unban",{$roomId:e}),r={user_id:t};return this.http.authedRequest(n,I.Method.Post,i,void 0,r)}kick(e,t,n,i){const r=p.encodeUri("/rooms/$roomId/kick",{$roomId:e}),o={user_id:t,reason:n};return this.http.authedRequest(i,I.Method.Post,r,void 0,o)}membershipChange(e,t,n,i,r){p.isFunction(i)&&(r=i,i=void 0);const o=p.encodeUri("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(r,I.Method.Post,o,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e,t=!1){return e.getPushActions()&&!t||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t,n){const i=p.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(n,I.Method.Put,i,void 0,t)}setDisplayName(e,t){return s(this,void 0,void 0,(function*(){const n=yield this.setProfileInfo("displayname",{displayname:e},t),i=this.getUser(this.getUserId());return i&&(i.displayName=e,i.emit(C.UserEvent.DisplayName,i.events.presence,i)),n}))}setAvatarUrl(e,t){return s(this,void 0,void 0,(function*(){const n=yield this.setProfileInfo("avatar_url",{avatar_url:e},t),i=this.getUser(this.getUserId());return i&&(i.avatarUrl=e,i.emit(C.UserEvent.AvatarUrl,i.events.presence,i)),n}))}mxcUrlToHttp(e,t,n,i,r){return(0,P.getHttpUriForMxc)(this.baseUrl,e,t,n,i,r)}setPresence(e,t){const n=p.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});"string"==typeof e&&(e={presence:e});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);return this.http.authedRequest(t,I.Method.Put,n,void 0,e)}getPresence(e,t){const n=p.encodeUri("/presence/$userId/status",{$userId:e});return this.http.authedRequest(t,I.Method.Get,n)}scrollback(e,t=30,n){p.isFunction(t)&&(n=t,t=void 0);let i=0,r=this.ongoingScrollbacks[e.roomId]||{};if(r.promise)return r.promise;if(r.errorTs){const e=Date.now()-r.errorTs;i=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const o=this.store.scrollback(e,t).length;if(o===t)return Promise.resolve(e);t-=o;const s=new Promise(((r,o)=>{(0,f.sleep)(i).then((()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,v.Direction.Backward))).then((t=>{const i=t.chunk.map(this.getEventMapper());if(t.state){const n=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(n)}const[o,s]=e.partitionThreadedEvents(i);this.processBeaconEvents(e,o),e.addEventsToTimeline(o,!0,e.getLiveTimeline()),this.processThreadEvents(e,s,!0),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,i,t.end,!0),this.ongoingScrollbacks[e.roomId]=null,null==n||n(null,e),r(e)})).catch((t=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},null==n||n(t),o(t)}))}));return r={promise:s,errorTs:null},this.ongoingScrollbacks[e.roomId]=r,s}getEventMapper(e){return(0,B.eventMapperFor)(this,e||{})}getEventTimeline(e,t){var n,i,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.getTimelineForEvent(t))return e.getTimelineForEvent(t);const o=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let s;this.clientOpts.lazyLoadMembers&&(s={filter:JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER)});const a=yield this.http.authedRequest(void 0,I.Method.Get,o,s);if(!a.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const c=this.getEventMapper(),l=c(a.event),d=[...a.events_after.reverse().map(c),l,...a.events_before.map(c)];if(W.Thread.hasServerSideSupport&&this.supportsExperimentalThreads()&&l.isRelation(W.THREAD_RELATION_TYPE.name)){const[,n]=e.room.partitionThreadedEvents(d);let i=e.room.getThread(l.threadRootId);i||(i=e.room.createThread(l.threadRootId,void 0,n,!0));const r={direction:v.Direction.Backward,limit:50};yield i.fetchInitialEvents();let o=i.liveTimeline.getPaginationToken(v.Direction.Backward);for(;!i.findEventById(t)&&(o&&(r.from=o),({nextBatch:o}=yield i.fetchEvents(r)),o););return i.liveTimeline}let u=e.getTimelineForEvent(d[0].getId());u?u.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(a.state.map(c)):(u=e.addTimeline(),u.initialiseState(a.state.map(c)),u.getState(v.EventTimeline.FORWARDS).paginationToken=a.end);const[g,f]=e.room.partitionThreadedEvents(d);return e.addEventsToTimeline(g,!0,u,a.start),this.processThreadEvents(e.room,f,!0),this.processBeaconEvents(e.room,g),null!==(r=null!==(n=e.getTimelineForEvent(t))&&void 0!==n?n:null===(i=e.room.findThreadForEvent(l))||void 0===i?void 0:i.liveTimeline)&&void 0!==r?r:u}))}createMessagesRequest(e,t,n=30,i,r){var o;const s=p.encodeUri("/rooms/$roomId/messages",{$roomId:e}),a={limit:n.toString(),dir:i};t&&(a.from=t);let c=null;return this.clientOpts.lazyLoadMembers&&(c=Object.assign({},h.Filter.LAZY_LOADING_MESSAGES_FILTER)),r&&(c=c||{},Object.assign(c,null===(o=r.getRoomTimelineFilterComponent())||void 0===o?void 0:o.toJSON())),c&&(a.filter=JSON.stringify(c)),this.http.authedRequest(void 0,I.Method.Get,s,a)}paginateEventTimeline(e,t){var n;const i=e.getTimelineSet()===this.notifTimelineSet,r=(t=t||{}).backwards||!1;if(i&&!r)throw new Error("paginateNotifTimeline can only paginate backwards");const o=r?v.EventTimeline.BACKWARDS:v.EventTimeline.FORWARDS,a=e.getPaginationToken(o),c=e.paginationRequests[o];if(c)return c;let l,d,u;if(i)l="/notifications",d={limit:(null!==(n=t.limit)&&void 0!==n?n:30).toString(),only:"highlight"},"end"!==a&&(d.from=a),u=this.http.authedRequest(void 0,I.Method.Get,"/notifications",d).then((t=>s(this,void 0,void 0,(function*(){const n=t.next_token,i=[];for(let e=0;e<t.notifications.length;e++){const n=t.notifications[e],r=this.getEventMapper()(n.event);r.setPushActions(y.PushProcessor.actionListToActionsObject(n.actions)),r.event.room_id=n.room_id,i[e]=r}const s=e.getTimelineSet();return s.addEventsToTimeline(i,r,e,n),this.processBeaconEvents(s.room,i),r&&!t.next_token&&e.setPaginationToken(null,o),!!t.next_token})))).finally((()=>{e.paginationRequests[o]=null})),e.paginationRequests[o]=u;else{const n=this.getRoom(e.getRoomId());if(!n)throw new Error("Unknown room "+e.getRoomId());u=this.createMessagesRequest(e.getRoomId(),a,t.limit,o,e.getFilter()).then((t=>{if(t.state){const n=e.getState(o),i=t.state.map(this.getEventMapper());n.setUnknownStateEvents(i)}const i=t.end,s=t.chunk.map(this.getEventMapper()),a=e.getTimelineSet(),[c,l]=a.room.partitionThreadedEvents(s);return a.addEventsToTimeline(c,r,e,i),this.processBeaconEvents(a.room,c),this.processThreadEvents(n,l,r),r&&t.end==t.start&&e.setPaginationToken(null,o),t.end!=t.start})).finally((()=>{e.paginationRequests[o]=null})),e.paginationRequests[o]=u}return u}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end",null)}peekInRoom(e){return this.peekSync&&this.peekSync.stopPeeking(),this.peekSync=new c.SyncApi(this,this.clientOpts),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const n=this.sendStateEvent(e,N.EventType.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let i=Promise.resolve(void 0);return t.allowRead&&(i=this.sendStateEvent(e,N.EventType.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([i,n]).then()}requestRegisterEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestRegisterMsisdnToken(e,t,n,i,r){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:r})}requestAdd3pidEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestAdd3pidMsisdnToken(e,t,n,i,r){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:r})}requestPasswordEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestPasswordMsisdnToken(e,t,n,i,r){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:r})}requestTokenFromEndpoint(e,t){var n;return s(this,void 0,void 0,(function*(){const i=Object.assign({},t);if(!(yield this.doesServerSupportSeparateAddAndBind())&&this.idBaseUrl){const e=new URL(this.idBaseUrl);if(i.id_server=e.host,(null===(n=this.identityServer)||void 0===n?void 0:n.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(i.id_access_token=e)}}return this.http.request(void 0,I.Method.Post,e,void 0,i)}))}getRoomPushRule(e,t){if(!this.pushRules)throw new Error("SyncApi.sync() must be done before accessing to push rules.");for(let n=0;n<this.pushRules[e].room.length;n++){const i=this.pushRules[e].room[n];if(i.rule_id===t)return i}}setRoomMutePushRule(e,t,n){let i,r=!1;const o=this.getRoomPushRule(e,t);if((null==o?void 0:o.actions.includes(A.PushRuleActionName.DontNotify))&&(r=!0),n)if(o){if(!r){const n=p.defer();this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id).then((()=>{this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[A.PushRuleActionName.DontNotify]}).then((()=>{n.resolve()})).catch((e=>{n.reject(e)}))})).catch((e=>{n.reject(e)})),i=n.promise}}else i=this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[A.PushRuleActionName.DontNotify]});else r&&(i=this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id));if(i)return new Promise(((e,t)=>{i.then((()=>{this.getPushRules().then((t=>{this.pushRules=t,e()})).catch((e=>{t(e)}))})).catch((e=>{this.getPushRules().then((n=>{this.pushRules=n,t(e)})).catch((n=>{t(e)}))}))}))}searchMessageText(e,t){const n={search_term:e.query};return"keys"in e&&(n.keys=e.keys),this.search({body:{search_categories:{room_events:n}}},t)}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:q.SearchOrderBy.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then((e=>this.processRoomEventsSearch(n,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},n=this.search(t).then((t=>this.processRoomEventsSearch(e,t))).finally((()=>{e.pendingRequest=null}));return e.pendingRequest=n,n}processRoomEventsSearch(e,t){var n,i;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!==(i=null===(n=r.results)||void 0===n?void 0:n.length)&&void 0!==i?i:0;for(let t=0;t<a;t++){const n=M.SearchResult.fromJson(r.results[t],s),i=this.getRoom(n.context.getEvent().getRoomId());if(i)for(const e of n.context.getTimeline()){const t=i.getMember(e.getSender());!e.sender&&t&&(e.sender=t)}e.results.push(n)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new c.SyncApi(this,this.clientOpts);return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then((()=>{T.logger.log("Marking success of sync left room request"),this.syncedLeftRooms=!0})).finally((()=>{this.syncLeftRoomsPromise=null})),this.syncLeftRoomsPromise}createFilter(e){const t=p.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(void 0,I.Method.Post,t,void 0,e).then((t=>{const n=h.Filter.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(n),n}))}getFilter(e,t,n){if(n){const n=this.store.getFilter(e,t);if(n)return Promise.resolve(n)}const i=p.encodeUri("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(void 0,I.Method.Get,i).then((n=>{const i=h.Filter.fromJson(e,t,n);return this.store.storeFilter(i),i}))}getOrCreateFilter(e,t){return s(this,void 0,void 0,(function*(){const n=this.store.getFilterIdByName(e);let i;if(n){try{const e=yield this.getFilter(this.credentials.userId,n,!0);if(e){const r=e.getDefinition(),o=t.getDefinition();p.deepCompare(r,o)&&(i=n)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}i||this.store.setFilterIdByName(e,void 0)}if(i)return i;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(void 0,I.Method.Post,e,void 0,{})}turnServer(e){return this.http.authedRequest(e,I.Method.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}checkTurnServers(){return s(this,void 0,void 0,(function*(){if(!this.canSupportVoip)return;let e=!1;const n=this.turnServersExpiry-Date.now();if(n>Q)T.logger.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),e=!0;else{T.logger.debug("Fetching new TURN credentials");try{const t=yield this.turnServer();if(t.uris){T.logger.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const n={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[n],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0}}catch(e){T.logger.error("Failed to get TURN URIs",e),403===e.httpStatus&&(T.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=null)}}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(void 0,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(void 0,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(void 0,I.Method.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){return s(this,void 0,void 0,(function*(){this.clientWellKnownPromise=m.AutoDiscovery.getRawClientConfig(this.getDomain()),this.clientWellKnown=yield this.clientWellKnownPromise,this.emit(X.ClientWellKnown,this.clientWellKnown)}))}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter((([t,n])=>e.includes(typeof n))).reduce(((e,[t,n])=>(e[t]=n,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"),n=yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!t&&!n)throw Error("Server does not support mutual_rooms API");const i=p.encodeUri(`/uk.half-shot.msc2666/user/${n?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e});return(yield this.http.authedRequest(void 0,I.Method.Get,i,void 0,void 0,{prefix:I.PREFIX_UNSTABLE})).joined}))}getVersions(){return this.serverVersionsPromise||(this.serverVersionsPromise=this.http.request(void 0,I.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch((e=>{throw this.serverVersionsPromise=null,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,n=e.unstable_features;return t&&t.includes("r0.5.0")||n&&n["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 n=e.unstable_features;return!n||(void 0===n["m.require_identity_server"]||n["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,n=e.unstable_features;return t&&t.includes("r0.6.0")||n&&n["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,n=e.unstable_features;return(null==t?void 0:t.includes("r0.6.0"))||(null==n?void 0:n["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 n=t.unstable_features;return n&&!!n[e]}))}doesServerForceEncryptionForPreset(e){return s(this,void 0,void 0,(function*(){const t=yield this.getVersions();if(!t)return!1;const n=t.unstable_features,i=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return n&&!!n[`io.element.e2ee_forced.${i}`]}))}doesServerSupportThread(){return s(this,void 0,void 0,(function*(){try{const e=yield this.doesServerSupportUnstableFeature("org.matrix.msc3440"),t=yield this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable");return{serverSupport:e||t,stable:t}}catch(e){return null}}))}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){return!!this.clientOpts.lazyLoadMembers}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,n,i,r={direction:v.Direction.Backward}){return s(this,void 0,void 0,(function*(){const o=this.getEncryptedIfNeededEventType(e,i),s=yield this.fetchRelations(e,t,n,o,r),a=this.getEventMapper(),c=s.original_event?a(s.original_event):void 0;let l=s.chunk.map(a);if(o===N.EventType.RoomMessageEncrypted){const e=c?l.concat(c):l;yield Promise.all(e.map((e=>this.decryptEventIfNeeded(e)))),null!==i&&(l=l.filter((e=>e.getType()===i)))}return c&&n===N.RelationType.Replace&&(l=l.filter((e=>e.getSender()===c.getSender()))),{originalEvent:c,events:l,nextBatch:s.next_batch,prevBatch:s.prev_batch}}))}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,K.randomString)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&e.attemptDecryption(this.crypto,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case w.SERVICE_TYPES.IS:return t+I.PREFIX_IDENTITY_V2+"/terms";case w.SERVICE_TYPES.IM:return t+"/_matrix/integrations/v1/terms";default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){return e&&(this.idBaseUrl.startsWith("http://")||this.idBaseUrl.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(void 0,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,n,i,r,o,s,a){!0===r?r={email:!0}:null!=r&&!1!==r||(r={}),"function"==typeof s&&(a=s,s=void 0),n&&(i.session=n);const c={auth:i,refresh_token:!0};return null!=e&&(c.username=e),null!=t&&(c.password=t),r.email&&(c.bind_email=!0),r.msisdn&&(c.bind_msisdn=!0),null!=o&&(c.guest_access_token=o),null!=s&&(c.inhibit_login=s),null!=t&&(c.x_show_msisdn=!0),this.registerRequest(c,void 0,a)}registerGuest(e,t){return(e=e||{}).body=e.body||{},this.registerRequest(e.body,"guest",t)}registerRequest(e,t,n){const i={};return t&&(i.kind=t),this.http.request(n,I.Method.Post,"/register",i,e)}refreshToken(e){return this.http.authedRequest(void 0,I.Method.Post,"/refresh",void 0,{refresh_token:e},{prefix:I.PREFIX_V1,inhibitLogoutEmit:!0})}loginFlows(e){return this.http.request(e,I.Method.Get,"/login")}login(e,t,n){const i={type:e};return Object.assign(i,t),this.http.authedRequest(((e,t)=>{t&&t.access_token&&t.user_id&&(this.http.opts.accessToken=t.access_token,this.credentials={userId:t.user_id}),n&&n(e,t)}),I.Method.Post,"/login",void 0,i)}loginWithPassword(e,t,n){return this.login("m.login.password",{user:e,password:t},n)}loginWithSAML2(e,t){return this.login("m.login.saml2",{relay_state:e},t)}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",n){let i="/login/"+t+"/redirect";return n&&(i+="/"+n),this.http.getUrl(i,{redirectUrl:e},I.PREFIX_R0)}loginWithToken(e,t){return this.login("m.login.token",{token:e},t)}logout(e,t=!1){var n,i;return s(this,void 0,void 0,(function*(){if(null===(i=null===(n=this.crypto)||void 0===n?void 0:n.backupManager)||void 0===i?void 0:i.getKeyBackupEnabled())try{for(;(yield this.crypto.backupManager.backupPendingKeys(200))>0;);}catch(e){T.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",e)}return t&&this.stopClient(),this.http.authedRequest(e,I.Method.Post,"/logout")}))}deactivateAccount(e,t){if("function"==typeof t)throw new Error("deactivateAccount no longer accepts a callback parameter");const n={};return e&&(n.auth=e),void 0!==t&&(n.erase=t),this.http.authedRequest(void 0,I.Method.Post,"/account/deactivate",void 0,n)}getFallbackAuthUrl(e,t){const n=p.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t},I.PREFIX_R0)}createRoom(e,t){return s(this,void 0,void 0,(function*(){const n=(e.invite_3pid||[]).filter((e=>!e.id_access_token));if(n.length>0&&this.identityServer&&this.identityServer.getAccessToken&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();if(e)for(const t of n)t.id_access_token=e}return this.http.authedRequest(t,I.Method.Post,"/createRoom",void 0,e)}))}fetchRelations(e,t,n,i,r={direction:v.Direction.Backward}){const o=p.encodeParams(r);let s="/rooms/$roomId/relations/$eventId";null!==n?(s+="/$relationType",null!==i&&(s+="/$eventType")):null!==i&&(T.logger.warn(`eventType: ${i} ignored when fetching\n relations as relationType is null`),i=null);const a=p.encodeUri(s+"?"+o,{$roomId:e,$eventId:t,$relationType:n,$eventType:i});return this.http.authedRequest(void 0,I.Method.Get,a,null,null,{prefix:I.PREFIX_UNSTABLE})}roomState(e,t){const n=p.encodeUri("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(t,I.Method.Get,n)}fetchRoomEvent(e,t,n){const i=p.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(n,I.Method.Get,i)}members(e,t,n,i,r){const o={};t&&(o.membership=t),n&&(o.not_membership=n),i&&(o.at=i);const s=p.encodeParams(o),a=p.encodeUri("/rooms/$roomId/members?"+s,{$roomId:e});return this.http.authedRequest(r,I.Method.Get,a)}upgradeRoom(e,t){const n=p.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(void 0,I.Method.Post,n,void 0,{new_version:t})}getStateEvent(e,t,n,i){const r={$roomId:e,$eventType:t,$stateKey:n};let o=p.encodeUri("/rooms/$roomId/state/$eventType",r);return void 0!==n&&(o=p.encodeUri(o+"/$stateKey",r)),this.http.authedRequest(i,I.Method.Get,o)}sendStateEvent(e,t,n,i="",r){const o={$roomId:e,$eventType:t,$stateKey:i};let s=p.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==i&&(s=p.encodeUri(s+"/$stateKey",o)),this.http.authedRequest(r,I.Method.Put,s,void 0,n)}roomInitialSync(e,t,n){var i;p.isFunction(t)&&(n=t,t=void 0);const r=p.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(n,I.Method.Get,r,{limit:null!==(i=null==t?void 0:t.toString())&&void 0!==i?i:"30"})}setRoomReadMarkersHttpRequest(e,t,n,i){const r=p.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),o={[H.ReceiptType.FullyRead]:t,[H.ReceiptType.Read]:n,[H.ReceiptType.ReadPrivate]:i};return this.http.authedRequest(void 0,I.Method.Post,r,void 0,o)}getJoinedRooms(){const e=p.encodeUri("/joined_rooms",{});return this.http.authedRequest(void 0,I.Method.Get,e)}getJoinedRoomMembers(e){const t=p.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(void 0,I.Method.Get,t)}publicRooms(e,t){"function"==typeof e&&(t=e,e={}),void 0===e&&(e={});const n={};return e.server&&(n.server=e.server,delete e.server),0===Object.keys(e).length&&0===Object.keys(n).length?this.http.authedRequest(t,I.Method.Get,"/publicRooms"):this.http.authedRequest(t,I.Method.Post,"/publicRooms",n,e)}createAlias(e,t,n){const i=p.encodeUri("/directory/room/$alias",{$alias:e}),r={room_id:t};return this.http.authedRequest(n,I.Method.Put,i,void 0,r)}deleteAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,I.Method.Delete,n)}getLocalAliases(e){const t=p.encodeUri("/rooms/$roomId/aliases",{$roomId:e}),n=I.PREFIX_V3;return this.http.authedRequest(void 0,I.Method.Get,t,null,null,{prefix:n})}getRoomIdForAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,I.Method.Get,n)}resolveRoomAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.request(t,I.Method.Get,n)}getRoomDirectoryVisibility(e,t){const n=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(t,I.Method.Get,n)}setRoomDirectoryVisibility(e,t,n){const i=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(n,I.Method.Put,i,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,n,i){const r=p.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(i,I.Method.Put,r,void 0,{visibility:n})}searchUserDirectory(e){const t={search_term:e.term};return void 0!==e.limit&&(t.limit=e.limit),this.http.authedRequest(void 0,I.Method.Post,"/user_directory/search",void 0,t)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t,n){p.isFunction(t)&&(n=t,t=void 0);const i=t?p.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):p.encodeUri("/profile/$userId",{$userId:e});return this.http.authedRequest(n,I.Method.Get,i)}getThreePids(e){return this.http.authedRequest(e,I.Method.Get,"/account/3pid")}addThreePid(e,t,n){const i={threePidCreds:e,bind:t};return this.http.authedRequest(n,I.Method.Post,"/account/3pid",null,i)}addThreePidOnly(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.PREFIX_R0:I.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,I.Method.Post,"/account/3pid/add",null,e,{prefix:t})}))}bindThreePid(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.PREFIX_R0:I.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,I.Method.Post,"/account/3pid/bind",null,e,{prefix:t})}))}unbindThreePid(e,t){return s(this,void 0,void 0,(function*(){const n={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},i=(yield this.isVersionSupported("r0.6.0"))?I.PREFIX_R0:I.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,I.Method.Post,"/account/3pid/unbind",null,n,{prefix:i})}))}deleteThreePid(e,t){return this.http.authedRequest(void 0,I.Method.Post,"/account/3pid/delete",null,{medium:e,address:t})}setPassword(e,t,n,i){"function"==typeof n&&(i=n),"boolean"!=typeof n&&(n=void 0);const r={auth:e,new_password:t,logout_devices:n};return this.http.authedRequest(i,I.Method.Post,"/account/password",null,r)}getDevices(){return this.http.authedRequest(void 0,I.Method.Get,"/devices")}getDevice(e){const t=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,I.Method.Get,t)}setDeviceDetails(e,t){const n=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,I.Method.Put,n,void 0,t)}deleteDevice(e,t){const n=p.encodeUri("/devices/$device_id",{$device_id:e}),i={};return t&&(i.auth=t),this.http.authedRequest(void 0,I.Method.Delete,n,void 0,i)}deleteMultipleDevices(e,t){const n={devices:e};t&&(n.auth=t);return this.http.authedRequest(void 0,I.Method.Post,"/delete_devices",void 0,n)}getPushers(e){return this.http.authedRequest(e,I.Method.Get,"/pushers")}setPusher(e,t){return this.http.authedRequest(t,I.Method.Post,"/pushers/set",null,e)}getPushRules(e){return this.http.authedRequest(e,I.Method.Get,"/pushrules/").then((e=>y.PushProcessor.rewriteDefaultRules(e)))}addPushRule(e,t,n,i,r){const o=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(r,I.Method.Put,o,void 0,i)}deletePushRule(e,t,n,i){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(i,I.Method.Delete,r)}setPushRuleEnabled(e,t,n,i,r){const o=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(r,I.Method.Put,o,void 0,{enabled:i})}setPushRuleActions(e,t,n,i,r){const o=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(r,I.Method.Put,o,void 0,{actions:i})}search(e,t){const n={};return e.next_batch&&(n.next_batch=e.next_batch),this.http.authedRequest(t,I.Method.Post,"/search",n,e.body)}uploadKeysRequest(e,t,n){return this.http.authedRequest(n,I.Method.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(void 0,I.Method.Post,"/keys/signatures/upload",void 0,e,{prefix:I.PREFIX_UNSTABLE})}downloadKeysForUsers(e,t){if(p.isFunction(t))throw new Error("downloadKeysForUsers no longer accepts a callback parameter");const n={device_keys:{}};return"token"in(t=t||{})&&(n.token=t.token),e.forEach((e=>{n.device_keys[e]=[]})),this.http.authedRequest(void 0,I.Method.Post,"/keys/query",void 0,n)}claimOneTimeKeys(e,t="signed_curve25519",n){const i={};void 0===t&&(t="signed_curve25519");for(let n=0;n<e.length;++n){const r=e[n][0],o=e[n][1],s=i[r]||{};i[r]=s,s[o]=t}const r={one_time_keys:i};n&&(r.timeout=n);return this.http.authedRequest(void 0,I.Method.Post,"/keys/claim",void 0,r)}getKeyChanges(e,t){const n={from:e,to:t};return this.http.authedRequest(void 0,I.Method.Get,"/keys/changes",n)}uploadDeviceSigningKeys(e,t){const n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(void 0,I.Method.Post,"/keys/device_signing/upload",void 0,n,{prefix:I.PREFIX_UNSTABLE})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.idBaseUrl+I.PREFIX_IDENTITY_V2+"/account/register";return this.http.requestOtherUrl(void 0,I.Method.Post,t,null,e)}requestEmailToken(e,t,n,i,r,o){const s={client_secret:t,email:e,send_attempt:null==n?void 0:n.toString(),next_link:i};return this.http.idServerRequest(r,I.Method.Post,"/validate/email/requestToken",s,I.PREFIX_IDENTITY_V2,o)}requestMsisdnToken(e,t,n,i,r,o,s){const a={client_secret:n,country:e,phone_number:t,send_attempt:null==i?void 0:i.toString(),next_link:r};return this.http.idServerRequest(o,I.Method.Post,"/validate/msisdn/requestToken",a,I.PREFIX_IDENTITY_V2,s)}submitMsisdnToken(e,t,n,i){const r={sid:e,client_secret:t,token:n};return this.http.idServerRequest(void 0,I.Method.Post,"/validate/msisdn/submitToken",r,I.PREFIX_IDENTITY_V2,i)}submitMsisdnTokenOtherUrl(e,t,n,i){const r={sid:t,client_secret:n,token:i};return this.http.requestOtherUrl(void 0,I.Method.Post,e,void 0,r)}getIdentityHashDetails(e){return this.http.idServerRequest(void 0,I.Method.Get,"/hash_details",null,I.PREFIX_IDENTITY_V2,e)}identityHashedLookup(e,n){return s(this,void 0,void 0,(function*(){const i={},r=yield this.getIdentityHashDetails(n);if(!r||!r.lookup_pepper||!r.algorithms)throw new Error("Unsupported identity server: bad response");i.pepper=r.lookup_pepper;const o={};if(r.algorithms.includes("sha256")){const n=new t.Olm.Utility;i.addresses=e.map((e=>{const t=e[0].toLowerCase(),r=e[1].toLowerCase(),s=n.sha256(`${t} ${r} ${i.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return o[s]=e[0],s})),i.algorithm="sha256"}else{if(!r.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");i.addresses=e.map((e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return o[t]=e[0],t})),i.algorithm="none"}const s=yield this.http.idServerRequest(void 0,I.Method.Post,"/lookup",i,I.PREFIX_IDENTITY_V2,n);if(!s||!s.mappings)return[];const a=[];for(const e of Object.keys(s.mappings)){const t=s.mappings[e],n=o[e];if(!n)throw new Error("Identity server returned more results than expected");a.push({address:n,mxid:t})}return a}))}lookupThreePid(e,t,n,i){return s(this,void 0,void 0,(function*(){const r=(yield this.identityHashedLookup([[t,e]],i)).find((e=>e.address===t));if(!r)return n&&n(null,{}),{};const o={address:t,medium:e,mxid:r.mxid};return n&&n(null,o),o}))}bulkLookupThreePids(e,t){return s(this,void 0,void 0,(function*(){const n=yield this.identityHashedLookup(e.map((e=>[e[1],e[0]])),t),i=[];for(const t of n){const n=e.find((e=>e[1]===t.address));if(!n)throw new Error("Identity sever returned unexpected results");i.push([n[0],t.address,t.mxid])}return{threepids:i}}))}getIdentityAccount(e){return this.http.idServerRequest(void 0,I.Method.Get,"/account",void 0,I.PREFIX_IDENTITY_V2,e)}sendToDevice(e,t,n){const i=p.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),r={messages:t},o=Object.keys(t).reduce(((e,n)=>(e[n]=Object.keys(t[n]),e)),{});return T.logger.log(`PUT ${i}`,o),this.http.authedRequest(void 0,I.Method.Put,i,void 0,r)}getThirdpartyProtocols(){return this.http.authedRequest(void 0,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 n=p.encodeUri("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(void 0,I.Method.Get,n,t)}getThirdpartyUser(e,t){const n=p.encodeUri("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(void 0,I.Method.Get,n,t)}getTerms(e,t){const n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(void 0,I.Method.Get,n)}agreeToTerms(e,t,n,i){const r=this.termsUrlForService(e,t),o={Authorization:"Bearer "+n};return this.http.requestOtherUrl(void 0,I.Method.Post,r,null,{user_accepts:i},{headers:o})}reportEvent(e,t,n,i){const r=p.encodeUri("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(void 0,I.Method.Post,r,null,{score:n,reason:i})}getRoomHierarchy(e,t,n,i=!1,r){const o=p.encodeUri("/rooms/$roomId/hierarchy",{$roomId:e}),s={suggested_only:String(i),max_depth:null==n?void 0:n.toString(),from:r,limit:null==t?void 0:t.toString()};return this.http.authedRequest(void 0,I.Method.Get,o,s,void 0,{prefix:I.PREFIX_V1}).catch((e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(void 0,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:L.Preset.PrivateChat,power_level_content_override:Object.assign(Object.assign({},F.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{users:{[this.getUserId()]:100}}),creation_content:{[N.RoomCreateTypeField]:N.RoomType.Space},initial_state:[{type:N.UNSTABLE_MSC3088_PURPOSE.name,state_key:N.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[N.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:N.EventType.RoomEncryption,state_key:"",content:{algorithm:E.MEGOLM_ALGORITHM}}]});return new F.MSC3089TreeSpace(this,t)}))}unstableGetFileTreeSpace(e){var t,n;const i=this.getRoom(e);if("join"!==(null==i?void 0:i.getMyMembership()))return null;const r=i.currentState.getStateEvents(N.EventType.RoomCreate,""),o=i.currentState.getStateEvents(N.UNSTABLE_MSC3088_PURPOSE.name,N.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[N.UNSTABLE_MSC3088_ENABLED.name])?(null===(n=r.getContent())||void 0===n?void 0:n[N.RoomCreateTypeField])!==N.RoomType.Space?null:new F.MSC3089TreeSpace(this,e):null}supportsExperimentalThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.experimentalThreadSupport)||!1}getRoomSummary(e,t){return s(this,void 0,void 0,(function*(){const n=p.encodeUri("/rooms/$roomid/summary",{$roomid:e});return this.http.authedRequest(void 0,I.Method.Get,n,{via:t},null,{qsStringifyOptions:{arrayFormat:"repeat"},prefix:"/_matrix/client/unstable/im.nheko.summary"})}))}processThreadEvents(e,t,n){e.processThreadedEvents(t,n)}processBeaconEvents(e,t){(null==t?void 0:t.length)&&e.currentState.processBeaconEvents(t,this)}whoami(){return s(this,void 0,void 0,(function*(){return this.http.authedRequest(void 0,I.Method.Get,"/account/whoami")}))}timestampToEvent(e,t,n){const i=p.encodeUri("/rooms/$roomId/timestamp_to_event",{$roomId:e});return this.http.authedRequest(void 0,I.Method.Get,i,{ts:t.toString(),dir:n},void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"})}}n.MatrixClient=Z,Z.RESTORE_BACKUP_ERROR_BAD_KEY="RESTORE_BACKUP_ERROR_BAD_KEY"}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":70,"./@types/beacon":71,"./@types/event":72,"./@types/partials":75,"./@types/read_receipts":76,"./@types/search":78,"./ReEmitter":81,"./autodiscovery":82,"./content-helpers":85,"./content-repo":86,"./crypto":103,"./crypto/RoomList":92,"./crypto/api":99,"./crypto/backup":100,"./crypto/dehydration":101,"./crypto/key_passphrase":104,"./crypto/olmlib":105,"./crypto/recoverykey":106,"./event-mapper":120,"./filter":122,"./http-api":123,"./logger":126,"./matrix":127,"./models/MSC3089TreeSpace":129,"./models/event":135,"./models/event-timeline":134,"./models/search-result":141,"./models/thread":142,"./models/typed-event-emitter":143,"./models/user":144,"./pushprocessor":145,"./randomstring":146,"./service-types":149,"./store/stub":155,"./sync":157,"./utils":159,"./webrtc/call":160,"./webrtc/callEventHandler":161,"./webrtc/mediaHandler":164,"matrix-events-sdk":48}],85:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.parseBeaconContent=n.makeBeaconContent=n.parseBeaconInfoContent=n.makeBeaconInfoContent=n.parseTopicContent=n.makeTopicContent=n.parseLocationEvent=n.makeLocationContent=n.getTextForLocationEvent=n.makeEmoteMessage=n.makeNotice=n.makeTextMessage=n.makeHtmlEmote=n.makeHtmlNotice=n.makeHtmlMessage=void 0;const i=e("matrix-events-sdk"),r=e("./@types/event"),o=e("./@types/extensible_events"),s=e("./@types/location"),a=e("./@types/topic");n.makeHtmlMessage=function(e,t){return{msgtype:r.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeHtmlNotice=function(e,t){return{msgtype:r.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeHtmlEmote=function(e,t){return{msgtype:r.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeTextMessage=function(e){return{msgtype:r.MsgType.Text,body:e}},n.makeNotice=function(e){return{msgtype:r.MsgType.Notice,body:e}},n.makeEmoteMessage=function(e){return{msgtype:r.MsgType.Emote,body:e}};n.getTextForLocationEvent=(e,t,n,i)=>{const r=`at ${new Date(n).toISOString()}`;return[t===s.LocationAssetType.Self?"User":void 0,"Location",i?`"${i}"`:void 0,e,r].filter(Boolean).join(" ")};n.makeLocationContent=(e,t,i,a,c)=>{const l=null!=e?e:(0,n.getTextForLocationEvent)(t,c||s.LocationAssetType.Self,i,a),d=i?{[s.M_TIMESTAMP.name]:i}:{};return Object.assign({msgtype:r.MsgType.Location,body:l,geo_uri:t,[s.M_LOCATION.name]:{description:a,uri:t},[s.M_ASSET.name]:{type:c||s.LocationAssetType.Self},[o.TEXT_NODE_TYPE.name]:l},d)};n.parseLocationEvent=e=>{var t,i;const r=s.M_LOCATION.findIn(e),a=s.M_ASSET.findIn(e),c=s.M_TIMESTAMP.findIn(e),l=o.TEXT_NODE_TYPE.findIn(e),d=null!==(t=null==r?void 0:r.uri)&&void 0!==t?t:null==e?void 0:e.geo_uri,u=null==r?void 0:r.description,h=null!==(i=null==a?void 0:a.type)&&void 0!==i?i:s.LocationAssetType.Self,g=null!=l?l:e.body;return(0,n.makeLocationContent)(g,d,c,u,h)};n.makeTopicContent=(e,t)=>{const n=[{body:e,mimetype:"text/plain"}];return(0,i.isProvided)(t)&&n.push({body:t,mimetype:"text/html"}),{topic:e,[a.M_TOPIC.name]:n}};n.parseTopicContent=e=>{var t,n,r;const o=a.M_TOPIC.findIn(e);return{text:null!==(n=null===(t=null==o?void 0:o.find((e=>!(0,i.isProvided)(e.mimetype)||"text/plain"===e.mimetype)))||void 0===t?void 0:t.body)&&void 0!==n?n:e.topic,html:null===(r=null==o?void 0:o.find((e=>"text/html"===e.mimetype)))||void 0===r?void 0:r.body}};n.makeBeaconInfoContent=(e,t,n,i,r)=>({description:n,timeout:e,live:t,[s.M_TIMESTAMP.name]:r||Date.now(),[s.M_ASSET.name]:{type:null!=i?i:s.LocationAssetType.Self}});n.parseBeaconInfoContent=e=>{const{description:t,timeout:n,live:i}=e,{type:r}=s.M_ASSET.findIn(e);return{description:t,timeout:n,live:i,assetType:r,timestamp:s.M_TIMESTAMP.findIn(e)}};n.makeBeaconContent=(e,t,n,r)=>({[s.M_LOCATION.name]:{description:r,uri:e},[s.M_TIMESTAMP.name]:t,"m.relates_to":{rel_type:i.REFERENCE_RELATION.name,event_id:n}});n.parseBeaconContent=e=>{const{description:t,uri:n}=s.M_LOCATION.findIn(e);return{description:t,uri:n,timestamp:s.M_TIMESTAMP.findIn(e)}}},{"./@types/event":72,"./@types/extensible_events":73,"./@types/location":74,"./@types/topic":79,"matrix-events-sdk":48}],86:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.getHttpUriForMxc=void 0;const s=o(e("./utils"));n.getHttpUriForMxc=function(e,t,n,i,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 l={};n&&(l.width=Math.round(n).toString()),i&&(l.height=Math.round(i).toString()),r&&(l.method=r),Object.keys(l).length>0&&(c="/_matrix/media/r0/thumbnail/");const d=a.indexOf("#");let u="";return d>=0&&(u=a.slice(d),a=a.slice(0,d)),e+c+a+(0===Object.keys(l).length?"":"?"+s.encodeParams(l))+u}},{"./utils":159}],87:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.requestKeysDuringVerification=n.createCryptoStoreCacheCallbacks=n.DeviceTrustLevel=n.UserTrustLevel=n.CrossSigningLevel=n.CrossSigningInfo=void 0;const o=e("./olmlib"),s=e("../logger"),a=e("../crypto/store/indexeddb-crypto-store"),c=e("./aes");function l(e){return Object.values(e.keys)[0]}class d{constructor(e,t={},n={}){this.userId=e,this.callbacks=t,this.cacheCallbacks=n,this.keys={},this.firstUse=!0,this.crossSigningVerifiedBefore=!1}static fromStorage(e,t){const n=new d(t);for(const t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}getCrossSigningKey(e,n){return r(this,void 0,void 0,(function*(){const i=["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 i=new t.Olm.PkSigning,r=i.init_with_seed(e);if(r===n)return[r,i];i.free()}let o;void 0===n&&(n=this.getId(e)),this.cacheCallbacks.getCrossSigningKeyCache&&i&&(o=yield this.cacheCallbacks.getCrossSigningKeyCache(e,n));const s=r(o);if(s)return s;o=yield this.callbacks.getCrossSigningKey(e,n);const a=r(o);if(a)return this.cacheCallbacks.storeCrossSigningKeyCache&&i&&(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 n(e){for(const n of Object.keys(t))e[n]||delete t[n]}for(const t of["self_signing","user_signing"])n((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[n,i]of e){const e=(0,o.encodeBase64)(i);yield t.store(`m.cross_signing.${n}`,e)}}))}static getFromSecretStorage(e,t){return r(this,void 0,void 0,(function*(){const n=yield t.get(`m.cross_signing.${e}`);return n?(0,o.decodeBase64)(n):null}))}isStoredInKeyCache(e){return r(this,void 0,void 0,(function*(){const t=this.cacheCallbacks;if(!t)return!1;const n=e?[e]:["master","self_signing","user_signing"];for(const e of n)if(!(yield t.getCrossSigningKeyCache(e)))return!1;return!0}))}getCrossSigningKeysFromCache(){return r(this,void 0,void 0,(function*(){const e=new Map,t=this.cacheCallbacks;if(!t)return e;for(const n of["master","self_signing","user_signing"]){const i=yield t.getCrossSigningKeyCache(n);i&&e.set(n,i)}return e}))}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&u.MASTER||!this.keys.master)e=u.MASTER|u.USER_SIGNING|u.SELF_SIGNING;else if(0===e)return;const n={},i={};let r,s;try{if(e&u.MASTER?(r=new t.Olm.PkSigning,n.master=r.generate_seed(),s=r.init_with_seed(n.master),i.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+s]:s}}):[s,r]=yield this.getCrossSigningKey("master"),e&u.SELF_SIGNING){const e=new t.Olm.PkSigning;try{n.self_signing=e.generate_seed();const t=e.init_with_seed(n.self_signing);i.self_signing={user_id:this.userId,usage:["self_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(i.self_signing,r,this.userId,s)}finally{e.free()}}if(e&u.USER_SIGNING){const e=new t.Olm.PkSigning;try{n.user_signing=e.generate_seed();const t=e.init_with_seed(n.user_signing);i.user_signing={user_id:this.userId,usage:["user_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(i.user_signing,r,this.userId,s)}finally{e.free()}}Object.assign(this.keys,i),this.callbacks.saveCrossSigningKeys(n)}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 n=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,n,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,n,this.userId)}catch(e){throw s.logger.error("invalid signature on self-signing key"),e}}e.master&&(this.keys.master=e.master,this.keys.self_signing=null,this.keys.user_signing=null),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[n,i]=yield this.getCrossSigningKey(t);try{return(0,o.pkSign)(e,i,this.userId,n),e}finally{i.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 h(!0,!0,this.firstUse);if(!this.keys.user_signing)return new h(!1,!1,e.firstUse);let t;const n=e.keys.master,i=this.getId("user_signing");try{(0,o.pkVerify)(n,i,this.userId),t=!0}catch(e){t=!1}return new h(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,n,i){const r=this.checkUserTrust(e),s=e.keys.self_signing;if(!s)return new g(!1,!1,n,i);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),g.fromUserTrustLevel(r,n,i)}catch(e){return new g(!1,!1,n,i)}}getCacheCallbacks(){return this.cacheCallbacks}}var u;n.CrossSigningInfo=d,function(e){e[e.MASTER=4]="MASTER",e[e.USER_SIGNING=2]="USER_SIGNING",e[e.SELF_SIGNING=1]="SELF_SIGNING"}(u=n.CrossSigningLevel||(n.CrossSigningLevel={}));class h{constructor(e,t,n){this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=n}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}n.UserTrustLevel=h;class g{constructor(e,t,n,i){this.crossSigningVerified=e,this.tofu=t,this.localVerified=n,this.trustCrossSignedDevices=i}static fromUserTrustLevel(e,t,n){return new g(e.isCrossSigningVerified(),e.isTofu(),t,n)}isVerified(){return Boolean(this.isLocallyVerified()||this.trustCrossSignedDevices&&this.isCrossSigningVerified())}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}n.DeviceTrustLevel=g,n.createCryptoStoreCacheCallbacks=function(e,t){return{getCrossSigningKeyCache:function(n,s){return r(this,void 0,void 0,(function*(){const r=yield new Promise((t=>e.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(i=>{e.getSecretStorePrivateKey(i,t,n)}))));if(r&&r.ciphertext){const e=i.from(t.pickleKey),s=yield(0,c.decryptAES)(r,e,n);return(0,o.decodeBase64)(s)}return r}))},storeCrossSigningKeyCache:function(n,s){return r(this,void 0,void 0,(function*(){if(!(s instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${s}`);const r=i.from(t.pickleKey),l=yield(0,c.encryptAES)((0,o.encodeBase64)(s),r,n);return e.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.storeSecretStorePrivateKey(t,n,l)}))}))}}},n.requestKeysDuringVerification=function(e,t,n){if(e.getUserId()===t)return s.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise(((t,i)=>{const a=e,c=a.crypto.crossSigningInfo,l=new d(c.userId,{getCrossSigningKey:e=>r(this,void 0,void 0,(function*(){s.logger.debug("Cross-signing: requesting secret",e,n);const{promise:t}=a.requestSecret(`m.cross_signing.${e}`,[n]),i=yield t,r=(0,o.decodeBase64)(i);return Uint8Array.from(r)}))},c.getCacheCallbacks());l.keys=c.keys;const u=new Promise((e=>{setTimeout(e,6e4,new Error("Timeout"))})),h=(()=>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",[n]),t=yield e.promise;s.logger.info("Got key backup key, decoding...");const i=(0,o.decodeBase64)(t);s.logger.info("Decoded backup key, storing..."),yield a.crypto.storeSessionBackupPrivateKey(Uint8Array.from(i)),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"),h]),u]).then(t,i)})).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":108,"../logger":126,"./aes":94,"./olmlib":105,buffer:20}],88:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.DeviceList=n.TrackingStatus=void 0;const a=e("../logger"),c=e("./deviceinfo"),l=e("./CrossSigning"),d=o(e("./olmlib")),u=e("./store/indexeddb-crypto-store"),h=e("../utils"),g=e("../models/typed-event-emitter"),p=e("./index");var f;!function(e){e[e.NotTracked=0]="NotTracked",e[e.PendingDownload=1]="PendingDownload",e[e.DownloadInProgress=2]="DownloadInProgress",e[e.UpToDate=3]="UpToDate"}(f=n.TrackingStatus||(n.TrackingStatus={}));class v extends g.TypedEventEmitter{constructor(e,t,n,i=250){super(),this.cryptoStore=t,this.keyDownloadChunkSize=i,this.devices={},this.crossSigningInfo={},this.userByIdentityKey={},this.deviceTrackingStatus={},this.syncToken=null,this.keyDownloadsInProgressByUser={},this.dirty=!1,this.savePromise=null,this.resolveSavePromise=null,this.savePromiseTime=null,this.saveTimer=null,this.hasFetched=null,this.serialiser=new y(e,n,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=>{this.hasFetched=Boolean(e&&e.devices),this.devices=e?e.devices:{},this.crossSigningInfo=e&&e.crossSigningInfo||{},this.deviceTrackingStatus=e?e.trackingStatus:{},this.syncToken=e?e.syncToken:null,this.userByIdentityKey={};for(const e of Object.keys(this.devices)){const t=this.devices[e];for(const n of Object.keys(t)){const i=t[n].keys["curve25519:"+n];void 0!==i&&(this.userByIdentityKey[i]=e)}}}))}));for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]==f.DownloadInProgress&&(this.deviceTrackingStatus[e]=f.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 n=this.savePromise;if(null===n&&(n=new Promise((e=>{this.resolveSavePromise=e})),this.savePromise=n),null===this.saveTimer){const n=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=>{this.cryptoStore.storeEndToEndDeviceData({devices:this.devices,crossSigningInfo:this.crossSigningInfo,trackingStatus:this.deviceTrackingStatus,syncToken:this.syncToken},e)})).then((()=>{this.dirty=!1,n(!0)}),(e=>{a.logger.error("Failed to save device tracking data",this.syncToken),a.logger.error(e)}))}),e)}return n}))}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){const n=[],i=[];if(e.forEach((e=>{const r=this.deviceTrackingStatus[e];this.keyDownloadsInProgressByUser[e]?(a.logger.log(`downloadKeys: already have a download in progress for ${e}: awaiting its result`),i.push(this.keyDownloadsInProgressByUser[e])):(t||r!=f.UpToDate)&&n.push(e)})),0!=n.length){a.logger.log("downloadKeys: downloading for",n);const e=this.doKeyDownload(n);i.push(e)}return 0===i.length&&a.logger.log("downloadKeys: already have all necessary keys"),Promise.all(i).then((()=>this.getDevicesFromStore(e)))}getDevicesFromStore(e){const t={};return e.forEach((e=>{t[e]={};(this.getStoredDevicesForUser(e)||[]).forEach((function(n){t[e][n.deviceId]=n}))})),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){const t=this.devices[e];if(!t)return null;const n=[];for(const e in t)t.hasOwnProperty(e)&&n.push(c.DeviceInfo.fromStorage(t[e],e));return n}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?l.CrossSigningInfo.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){const n=this.devices[e];if(n&&n[t])return c.DeviceInfo.fromStorage(n[t],t)}getUserByIdentityKey(e,t){return e!==d.OLM_ALGORITHM&&e!==d.MEGOLM_ALGORITHM?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){const n=this.getUserByIdentityKey(e,t);if(!n)return null;const i=this.devices[n];if(!i)return null;for(const e in i){if(!i.hasOwnProperty(e))continue;const n=i[e];for(const i in n.keys){if(!n.keys.hasOwnProperty(i))continue;if(0!==i.indexOf("curve25519:"))continue;if(n.keys[i]==t)return c.DeviceInfo.fromStorage(n,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]=f.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=f.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=f.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=f.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this.deviceTrackingStatus)){this.deviceTrackingStatus[t]==f.PendingDownload&&e.push(t)}return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(void 0!==this.devices[e])for(const[t,n]of Object.entries(this.devices[e])){const e=n.keys["curve25519:"+t];delete this.userByIdentityKey[e]}this.devices[e]=t;for(const[n,i]of Object.entries(t)){const t=i.keys["curve25519:"+n];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((()=>{n(!0)}),(t=>{throw a.logger.error("Error downloading keys for "+e+":",t),n(!1),t}));e.forEach((e=>{this.keyDownloadsInProgressByUser[e]=t;this.deviceTrackingStatus[e]==f.PendingDownload&&(this.deviceTrackingStatus[e]=f.DownloadInProgress)}));const n=n=>{this.emit(p.CryptoEvent.WillUpdateDevices,e,!this.hasFetched),e.forEach((e=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser[e]!==t)return void a.logger.log("Another update in the queue for",e,"- not marking up-to-date");delete this.keyDownloadsInProgressByUser[e];this.deviceTrackingStatus[e]==f.DownloadInProgress&&(n?(this.deviceTrackingStatus[e]=f.UpToDate,a.logger.log("Device list for",e,"now up to date")):this.deviceTrackingStatus[e]=f.PendingDownload)})),this.saveIfDirty(),this.emit(p.CryptoEvent.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}n.DeviceList=v;class y{constructor(e,t,n){this.baseApis=e,this.olmDevice=t,this.deviceList=n,this.downloadInProgress=!1,this.keyDownloadsQueuedByUser={},this.queuedQueryDeferred=null,this.syncToken=null}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=null,a.logger.log("Starting key download for",e),this.downloadInProgress=!0;const n={};this.syncToken&&(n.token=this.syncToken);const i=[];for(let t=0;t<e.length;t+=this.deviceList.keyDownloadChunkSize){const r=e.slice(t,t+this.deviceList.keyDownloadChunkSize);i.push((()=>this.baseApis.downloadKeysForUsers(r,n)))}return(0,h.chunkPromises)(i,3).then((t=>s(this,void 0,void 0,(function*(){const n=Object.assign({},...t.map((e=>e.device_keys||{}))),i=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,n[t],{master:i[t],self_signing:r[t],user_signing: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,t.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()}),(n=>{a.logger.warn("Error downloading keys for "+e+":",n),this.downloadInProgress=!1,t.reject(n)})),t.promise}processQueryResponseForUser(e,t,n){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+":",n);{const n={},i=this.deviceList.getRawStoredDevicesForUser(e);i&&Object.keys(i).forEach((e=>{const t=c.DeviceInfo.fromStorage(i[e],e);n[e]=t})),yield function(e,t,n,i,r,o){return s(this,void 0,void 0,(function*(){let s=!1;for(const e in n)if(n.hasOwnProperty(e)&&!(e in i)){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 n[e],s=!0}for(const r in i){if(!i.hasOwnProperty(r))continue;const o=i[r];o.user_id===t?o.device_id===r?(yield m(e,n,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,n,t||{},this.baseApis.getUserId(),this.baseApis.deviceId);const r={};Object.keys(n).forEach((e=>{r[e]=n[e].toStorage()})),this.deviceList.setRawStoredDevicesForUser(e,r)}if(n&&(n.master||n.self_signing||n.user_signing)){const t=this.deviceList.getStoredCrossSigningForUser(e)||new l.CrossSigningInfo(e);t.setKeys(n),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage()),this.deviceList.emit(p.CryptoEvent.UserCrossSigningUpdated,e)}}))}}function m(e,t,n){return s(this,void 0,void 0,(function*(){if(!n.keys)return!1;const i=n.device_id,r=n.user_id,o="ed25519:"+i,s=n.keys[o];if(!s)return a.logger.warn("Device "+r+":"+i+" has no ed25519 key"),!1;const l=n.unsigned||{},u=n.signatures||{};try{yield d.verifySignature(e,n,r,i,s)}catch(e){return a.logger.warn("Unable to verify signature on device "+r+":"+i+":"+e),!1}let h;if(i in t){if(h=t[i],h.getFingerprint()!=s)return a.logger.warn("Ed25519 key for device "+r+":"+i+" has changed"),!1}else t[i]=h=new c.DeviceInfo(i);return h.keys=n.keys||{},h.algorithms=n.algorithms||[],h.unsigned=l,h.signatures=u,!0}))}},{"../logger":126,"../models/typed-event-emitter":143,"../utils":159,"./CrossSigning":87,"./deviceinfo":102,"./index":103,"./olmlib":105,"./store/indexeddb-crypto-store":108}],89:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.EncryptionSetupOperation=n.EncryptionSetupBuilder=void 0;const r=e("../logger"),o=e("../models/event"),s=e("./CrossSigning"),a=e("./store/indexeddb-crypto-store"),c=e("../http-api"),l=e("../matrix"),d=e("../models/typed-event-emitter");n.EncryptionSetupBuilder=class{constructor(e,t){this.crossSigningKeys=null,this.keySignatures=null,this.keyBackupInfo=null,this.accountDataClientAdapter=new h(e),this.crossSigningCallbacks=new g,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,n){this.keySignatures||(this.keySignatures={});const i=this.keySignatures[e]||{};this.keySignatures[e]=i,i[t]=n}setAccountData(e,t){return i(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){return i(this,void 0,void 0,(function*(){if(this.crossSigningKeys){const t=(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 t.storeCrossSigningKeyCache(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,n,i){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=n,this.keySignatures=i}apply(e){return i(this,void 0,void 0,(function*(){const t=e.baseApis;if(this.crossSigningKeys){const n={};for(const[e,t]of Object.entries(this.crossSigningKeys.keys))n[e+"_key"]=t;yield this.crossSigningKeys.authUpload((e=>t.uploadDeviceSigningKeys(e,n))),e.crossSigningInfo.setKeys(this.crossSigningKeys.keys)}if(this.accountData)for(const[e,n]of this.accountData)yield t.setAccountData(e,n);this.keySignatures&&(yield t.uploadKeySignatures(this.keySignatures)),this.keyBackupInfo&&(this.keyBackupInfo.version?yield t.http.authedRequest(void 0,c.Method.Put,"/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:c.PREFIX_UNSTABLE}):yield t.http.authedRequest(void 0,c.Method.Post,"/room_keys/version",void 0,this.keyBackupInfo,{prefix:c.PREFIX_UNSTABLE}))}))}}n.EncryptionSetupOperation=u;class h extends d.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 n=this.existingValues[e];return n?n.getContent():null}setAccountData(e,t){const n=this.values.get(e);return this.values.set(e,t),Promise.resolve().then((()=>{const i=new o.MatrixEvent({type:e,content:t});return this.emit(l.ClientEvent.AccountData,i,n),{}}))}}class g{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){return Promise.resolve(this.privateKeys.get(e))}saveCrossSigningKeys(e){for(const[t,n]of Object.entries(e))this.privateKeys.set(t,n)}}class p{constructor(e){this.delegateCryptoCallbacks=e,this.privateKeys=new Map}getSecretStorageKey({keys:e},t){var n;return i(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===(n=null==this?void 0:this.delegateCryptoCallbacks)||void 0===n?void 0:n.getSecretStorageKey){const n=yield this.delegateCryptoCallbacks.getSecretStorageKey({keys:e},t);if(n){const[e,t]=n;this.privateKeys.set(e,t)}return n}return null}))}addPrivateKey(e,t,n){var i,r;this.privateKeys.set(e,n),null===(r=null===(i=this.delegateCryptoCallbacks)||void 0===i?void 0:i.cacheSecretStorageKey)||void 0===r||r.call(i,e,t,n)}}},{"../http-api":123,"../logger":126,"../matrix":127,"../models/event":135,"../models/typed-event-emitter":143,"./CrossSigning":87,"./store/indexeddb-crypto-store":108}],90:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.WITHHELD_MESSAGES=n.OlmDevice=void 0;const a=e("../logger"),c=e("./store/indexeddb-crypto-store"),l=o(e("./algorithms"));function d(e){if(void 0===e)throw new Error("payloadString undefined");if(e.length>49152){const t=new Error("Message too long ("+e.length+" bytes). The maximum for an encrypted message is 49152 bytes.");throw t.data={errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"},t}}function u(e){return e.code&&e.code in n.WITHHELD_MESSAGES?n.WITHHELD_MESSAGES[e.code]:e.reason?e.reason:"decryption key withheld"}n.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:n}={}){return s(this,void 0,void 0,(function*(){let i;const r=new t.Olm.Account;try{n?(e&&a.logger.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),this.pickleKey=n.pickleKey,yield this.initialiseFromExportedDevice(n,r)):(e&&(this.pickleKey=e),yield this.initialiseAccount(r)),i=JSON.parse(r.identity_keys()),this.maxOneTimeKeys=r.max_number_of_one_time_keys()}finally{r.free()}this.deviceCurve25519Key=i.curve25519,this.deviceEd25519Key=i.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:n,sessionId:i}=e,r={session:e.session,lastReceivedMessageTs:e.lastReceivedMessageTs};this.cryptoStore.storeEndToEndSession(n,i,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,(n=>{null!==n?e.unpickle(this.pickleKey,n):(e.create(),n=e.pickle(this.pickleKey),this.cryptoStore.storeAccount(t,n))}))}))}))}getAccount(e,n){this.cryptoStore.getAccount(e,(e=>{const i=new t.Olm.Account;try{i.unpickle(this.pickleKey,e),n(i)}finally{i.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,n,i){this.cryptoStore.getEndToEndSession(e,t,n,(e=>{this.unpickleSession(e,i)}))}unpickleSession(e,n){const i=new t.Olm.Session;try{i.unpickle(this.pickleKey,e.session);n(Object.assign({},e,{session:i}))}finally{i.free()}}saveSession(e,t,n){const i=t.session.session_id(),r=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,i,r,n)}getUtility(e){const n=new t.Olm.Utility;try{return e(n)}finally{n.free()}}sign(e){return s(this,void 0,void 0,(function*(){let t;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(n=>{this.getAccount(n,(n=>{t=n.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(){return this.maxOneTimeKeys}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,(n=>{n.generate_one_time_keys(e),this.storeAccount(t,n)}))}))}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,n){return s(this,void 0,void 0,(function*(){let i;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,n),i=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]")),i}))}createInboundSession(e,n,i){return s(this,void 0,void 0,(function*(){if(0!==n)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,i),s.remove_one_time_keys(a),this.storeAccount(o,s);const t=a.decrypt(n,i),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(this.sessionsInProgress[e]){t.debug(`Waiting for Olm session for ${e} to be created`);try{yield this.sessionsInProgress[e]}catch(e){}}let n;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{n=Object.keys(e)}))}),t),n}))}getSessionIdForDevice(e,t=!1,n){return s(this,void 0,void 0,(function*(){const i=yield this.getSessionInfoForDevice(e,t,n);if(0===i.length)return null;let r=0;for(let e=1;e<i.length;e++){const t=i[e],n=void 0===t.lastReceivedMessageTs?0:t.lastReceivedMessageTs,o=i[r],s=void 0===o.lastReceivedMessageTs?0:o.lastReceivedMessageTs;(n>s||n===s&&t.sessionId<o.sessionId)&&(r=e)}return i[r].sessionId}))}getSessionInfoForDevice(e,t=!1,n=a.logger){return s(this,void 0,void 0,(function*(){if(n=n.withPrefix("[getSessionInfoForDevice]"),this.sessionsInProgress[e]&&!t){n.debug(`Waiting for Olm session for ${e} to be created`);try{yield this.sessionsInProgress[e]}catch(e){}}const i=[];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 n of t)this.unpickleSession(e[n],(e=>{i.push({lastReceivedMessageTs:e.lastReceivedMessageTs,hasReceivedMessage:e.session.has_received_message(),sessionId:n})}))}))}),n),i}))}encryptMessage(e,t,n){return s(this,void 0,void 0,(function*(){let i;return d(n),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),i=o.session.encrypt(n),this.saveSession(e,o,r)}))}),a.logger.withPrefix("[encryptMessage]")),i}))}decryptMessage(e,t,n,i){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(n,i),s.lastReceivedMessageTs=Date.now(),this.saveSession(e,s,o)}))}),a.logger.withPrefix("[decryptMessage]")),r}))}matchesSession(e,t,n,i){return s(this,void 0,void 0,(function*(){if(0!==n)return!1;let r;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(n=>{this.getSession(e,t,n,(e=>{r=e.session.matches_inbound(i)}))}),a.logger.withPrefix("[matchesSession]")),r}))}recordSessionProblem(e,t,n){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.storeEndToEndSessionProblem(e,t,n)}))}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,n){const i=this.outboundGroupSessionStore[e];if(void 0===i)throw new Error("Unknown outbound group session "+e);const r=new t.Olm.OutboundGroupSession;try{return r.unpickle(this.pickleKey,i),n(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}`),d(t),this.getOutboundGroupSession(e,(e=>{const n=e.encrypt(t);return this.saveOutboundGroupSession(e),n}))}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,(function(e){return{chain_index:e.message_index(),key:e.session_key()}}))}unpickleInboundGroupSession(e,n){const i=new t.Olm.InboundGroupSession;try{return i.unpickle(this.pickleKey,e.session),n(i)}finally{i.free()}}getInboundGroupSession(e,t,n,i,r){this.cryptoStore.getEndToEndInboundGroupSession(t,n,i,((t,n)=>{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,n)}))}else r(null,null,n)}))}addInboundGroupSession(e,n,i,r,o,l,d,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,n,r,s,((c,h)=>{const g=new t.Olm.InboundGroupSession;try{if(d?g.import_session(o):g.create(o),r!=g.session_id())throw new Error("Mismatched group session ID from senderKey: "+n);if(c&&(a.logger.log("Update for megolm session "+n+"/"+r),c.first_known_index()<=g.first_known_index()&&(c.first_known_index()!=g.first_known_index()||u.untrusted||!h.untrusted)))return void a.logger.log(`Keeping existing megolm session ${r}`);a.logger.info("Storing megolm session "+n+"/"+r+" with first index "+g.first_known_index());const t=Object.assign({},u,{room_id:e,session:g.pickle(this.pickleKey),keysClaimed:l,forwardingCurve25519KeyChain:i});this.cryptoStore.storeEndToEndInboundGroupSession(n,r,t,s),!c&&u.sharedHistory&&this.cryptoStore.addSharedHistoryInboundGroupSession(e,n,r,s)}finally{g.free()}}))}),a.logger.withPrefix("[addInboundGroupSession]"))}))}addInboundGroupSessionWithheld(e,t,n,i,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,n,{room_id:e,code:i,reason:r},o)}))}))}decryptGroupMessage(e,t,n,i,r,o){return s(this,void 0,void 0,(function*(){let s,d;if(yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(a=>{this.getInboundGroupSession(e,t,n,a,((e,c,h)=>{if(null===e)return h&&(d=new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",u(h),{session:t+"|"+n})),void(s=null);let g;try{g=e.decrypt(i)}catch(e){return void(d=e&&"OLM.UNKNOWN_MESSAGE_INDEX"===e.message&&h?new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",u(h),{session:t+"|"+n}):e)}let p=g.plaintext;if(void 0===p)p=g;else{const e=t+"|"+n+"|"+g.message_index;if(e in this.inboundGroupSessionMessageIndexes){const t=this.inboundGroupSessionMessageIndexes[e];if(t.id!==r||t.timestamp!==o)return void(d=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,n,c,a),s={result:p,keysClaimed:c.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:c.forwardingCurve25519KeyChain||[],untrusted:c.untrusted}}))}),a.logger.withPrefix("[decryptGroupMessage]")),d)throw d;return s}))}hasInboundSessionKeys(e,t,n){return s(this,void 0,void 0,(function*(){let i;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(r=>{this.cryptoStore.getEndToEndInboundGroupSession(t,n,r,(r=>{null!==r?e!==r.room_id?(a.logger.warn(`requested keys for inbound group session ${t}|${n}, with incorrect room_id (expected ${r.room_id}, was ${e})`),i=!1):i=!0:i=!1}))}),a.logger.withPrefix("[hasInboundSessionKeys]")),i}))}getInboundGroupSessionKey(e,t,n,i){return s(this,void 0,void 0,(function*(){let r;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(o=>{this.getInboundGroupSession(e,t,n,o,((e,t)=>{if(null===e)return void(r=null);void 0===i&&(i=e.first_known_index());const n=e.export_session(i),o=(t.keysClaimed||{}).ed25519||null;r={chain_index:i,key:n,forwarding_curve25519_key_chain:t.forwardingCurve25519KeyChain||[],sender_claimed_ed25519_key:o,shared_history:t.sharedHistory||!1}}))}),a.logger.withPrefix("[getInboundGroupSessionKey]")),r}))}exportInboundGroupSession(e,t,n){return this.unpickleInboundGroupSession(n,(i=>{const r=i.first_known_index();return{sender_key:e,sender_claimed_keys:n.keysClaimed,room_id:n.room_id,session_id:t,session_key:i.export_session(r),forwarding_curve25519_key_chain:n.forwardingCurve25519KeyChain||[],first_known_index:i.first_known_index(),"org.matrix.msc3061.shared_history":n.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],(n=>{t=this.cryptoStore.getSharedHistoryInboundGroupSessions(e,n)}),a.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")),t}))}verifySignature(e,t,n){this.getUtility((function(i){i.ed25519_verify(e,t,n)}))}},n.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":126,"./algorithms":96,"./store/indexeddb-crypto-store":108}],91:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.OutgoingRoomKeyRequestManager=n.RoomKeyRequestState=void 0;const r=e("../logger"),o=e("../@types/event");var s;!function(e){e[e.Unsent=0]="Unsent",e[e.Sent=1]="Sent",e[e.CancellationPending=2]="CancellationPending",e[e.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend"}(s=n.RoomKeyRequestState||(n.RoomKeyRequestState={}));function a(e){return e.room_id+" / "+e.session_id}function c(e){return"["+e.map((e=>`${e.userId}:${e.deviceId}`)).join(",")+"]"}n.OutgoingRoomKeyRequestManager=class{constructor(e,t,n){this.baseApis=e,this.deviceId=t,this.cryptoStore=n,this.sendOutgoingRoomKeyRequestsTimer=null,this.sendOutgoingRoomKeyRequestsRunning=!1,this.clientRunning=!1}start(){this.clientRunning=!0}stop(){r.logger.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}queueRoomKeyRequest(e,t,n=!1){return i(this,void 0,void 0,(function*(){const i=yield this.cryptoStore.getOutgoingRoomKeyRequest(e);if(i)switch(i.state){case s.CancellationPendingAndWillResend:case s.Unsent:return;case s.CancellationPending:{const e=n?s.CancellationPendingAndWillResend:s.Sent;yield this.cryptoStore.updateOutgoingRoomKeyRequest(i.requestId,s.CancellationPending,{state:e,cancellationTxnId:this.baseApis.makeTxnId()});break}case s.Sent:if(n){const o=s.CancellationPendingAndWillResend,a=yield this.cryptoStore.updateOutgoingRoomKeyRequest(i.requestId,s.Sent,{state:o,cancellationTxnId:this.baseApis.makeTxnId(),requestTxnId:this.baseApis.makeTxnId()});if(!a)return this.queueRoomKeyRequest(e,t,n);try{yield this.sendOutgoingRoomKeyRequestCancellation(a,!0)}catch(e){r.logger.error("Error sending room key request cancellation; will retry later.",e)}}break;default:throw new Error("unhandled state: "+i.state)}else yield this.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:this.baseApis.makeTxnId(),state:s.Unsent})}))}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then((t=>{if(t)switch(t.state){case s.CancellationPending:case s.CancellationPendingAndWillResend:return;case s.Unsent:return r.logger.log("deleting unnecessary room key request for "+a(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,s.Unsent);case s.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,s.Sent,{state:s.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then((t=>{t?this.sendOutgoingRoomKeyRequestCancellation(t).catch((e=>{r.logger.error("Error sending room key request cancellation; will retry later.",e),this.startTimer()})):r.logger.log("Tried to cancel room key request for "+a(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,[s.Sent])}cancelAndResendAllOutgoingRequests(){return i(this,void 0,void 0,(function*(){const e=yield this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(s.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=>{r.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`)}))}),500)}sendOutgoingRoomKeyRequests(){return this.clientRunning?this.cryptoStore.getOutgoingRoomKeyRequestByState([s.CancellationPending,s.CancellationPendingAndWillResend,s.Unsent]).then((e=>{if(!e)return void(this.sendOutgoingRoomKeyRequestsTimer=null);let t;switch(e.state){case s.Unsent:t=this.sendOutgoingRoomKeyRequest(e);break;case s.CancellationPending:t=this.sendOutgoingRoomKeyRequestCancellation(e);break;case s.CancellationPendingAndWillResend:t=this.sendOutgoingRoomKeyRequestCancellation(e,!0)}return t.then((()=>this.sendOutgoingRoomKeyRequests())).catch((e=>{r.logger.error("Error sending room key request; will retry later.",e),this.sendOutgoingRoomKeyRequestsTimer=null}))})):(this.sendOutgoingRoomKeyRequestsTimer=null,Promise.resolve())}sendOutgoingRoomKeyRequest(e){r.logger.log(`Requesting keys for ${a(e.requestBody)} from ${c(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,s.Unsent,{state:s.Sent})))}sendOutgoingRoomKeyRequestCancellation(e,t=!1){r.logger.log(`Sending cancellation for key request for ${a(e.requestBody)} to ${c(e.recipients)} (cancellation id ${e.cancellationTxnId})`);const n={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then((()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,s.CancellationPendingAndWillResend,{state:s.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,s.CancellationPending)))}sendMessageToDevices(e,t,n){const i={};for(const n of t)i[n.userId]||(i[n.userId]={}),i[n.userId][n.deviceId]=e;return this.baseApis.sendToDevice(o.EventType.RoomKeyRequest,i,n)}}},{"../@types/event":72,"../logger":126}],92:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.RoomList=void 0;const r=e("./store/indexeddb-crypto-store");n.RoomList=class{constructor(e){this.cryptoStore=e,this.roomEncryption={}}init(){return i(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 i(this,void 0,void 0,(function*(){this.roomEncryption[e]=t,yield this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],(n=>{this.cryptoStore.storeEndToEndRoom(e,t,n)}))}))}}},{"./store/indexeddb-crypto-store":108}],93:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.SecretStorage=n.SECRET_STORAGE_ALGORITHM_V1_AES=void 0;const a=e("../logger"),c=o(e("./olmlib")),l=e("./olmlib"),d=e("../randomstring"),u=e("./aes"),h=e("../matrix");n.SECRET_STORAGE_ALGORITHM_V1_AES="m.secret_storage.v1.aes-hmac-sha2";n.SecretStorage=class{constructor(e,t,n){this.accountDataAdapter=e,this.cryptoCallbacks=t,this.baseApis=n,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,n)=>{const i=n=>{"m.secret_storage.default_key"===n.getType()&&n.getContent().key===e&&(this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,i),t())};this.accountDataAdapter.on(h.ClientEvent.AccountData,i),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch((e=>{this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,i),n(e)}))}))}addKey(e,t,i){return s(this,void 0,void 0,(function*(){const r={algorithm:e};if(t||(t={}),t.name&&(r.name=t.name),e!==n.SECRET_STORAGE_ALGORITHM_V1_AES)throw new Error(`Unknown key algorithm ${e}`);if(t.passphrase&&(r.passphrase=t.passphrase),t.key){const{iv:e,mac:n}=yield(0,u.calculateKeyCheck)(t.key);r.iv=e,r.mac=n}if(!i)do{i=(0,d.randomString)(32)}while(yield this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${i}`));return yield this.accountDataAdapter.setAccountData(`m.secret_storage.key.${i}`,r),{keyId:i,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===n.SECRET_STORAGE_ALGORITHM_V1_AES){if(t.mac){const{mac:n}=yield(0,u.calculateKeyCheck)(e,t.iv);return t.mac.replace(/=+$/g,"")===n.replace(/=+$/g,"")}return!0}throw new Error("Unknown algorithm")}))}store(e,t,i){return s(this,void 0,void 0,(function*(){const r={};if(!i){const e=yield this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");i=[e]}if(0===i.length)throw new Error("Zero keys given to encrypt with!");for(const o of i){const i=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o);if(!i)throw new Error("Unknown key: "+o);if(i.algorithm===n.SECRET_STORAGE_ALGORITHM_V1_AES){const n={[o]:i},[,s]=yield this.getSecretStorageKey(n,e);r[o]=yield s.encrypt(t)}else a.logger.warn("unknown algorithm for secret storage key "+o+": "+i.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 i={};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===n.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(i[e]=r)}if(0===Object.keys(i).length)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);let r,o;try{[r,o]=yield this.getSecretStorageKey(i,e);const n=t.encrypted[r];return n.passthrough?(0,l.encodeBase64)(o.get_private_key()):o.decrypt(n)}finally{o&&o.free&&o.free()}}))}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 i={};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===n.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(i[e]=r)}return Object.keys(i).length?i:null}))}request(e,t){const n=this.baseApis.makeTxnId();let i,r;const o=new Promise(((e,t)=>{i=e,r=t}));this.requests.set(n,{name:e,devices:t,resolve:i,reject:r});const s={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:n},c={};for(const e of t)c[e]=s;return a.logger.info(`Request secret ${e} from ${t}, id ${n}`),this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:c}),{requestId:n,promise:o,cancel:e=>{const i={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:n},o={};for(const e of t)o[e]=i;this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:o}),r(new Error(e||"Cancelled"))}}}onRequestReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getSender(),n=e.getContent();if(t!==this.baseApis.getUserId()||!(n.name&&n.action&&n.requesting_device_id&&n.request_id))return;const i=n.requesting_device_id;if("request_cancellation"===n.action);else if("request"===n.action){if(i===this.baseApis.deviceId)return;if(a.logger.info("received request for secret ("+t+", "+i+", "+n.request_id+")"),!this.cryptoCallbacks.onSecretRequested)return;const e=yield this.cryptoCallbacks.onSecretRequested(t,i,n.request_id,n.name,this.baseApis.checkDeviceTrust(t,i));if(e){a.logger.info(`Preparing ${n.name} secret for ${i}`);const r={type:"m.secret.send",content:{request_id:n.request_id,secret:e}},o={algorithm:c.OLM_ALGORITHM,sender_key:this.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{}};yield c.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice,this.baseApis,{[t]:[this.baseApis.getStoredDevice(t,i)]}),yield c.encryptMessageForDevice(o.ciphertext,this.baseApis.getUserId(),this.baseApis.deviceId,this.baseApis.crypto.olmDevice,t,this.baseApis.getStoredDevice(t,i),r);const s={[t]:{[i]:o}};a.logger.info(`Sending ${n.name} secret for ${i}`),this.baseApis.sendToDevice("m.room.encrypted",s)}else a.logger.info(`Request denied for ${n.name} secret for ${i}`)}}))}onSecretReceived(e){if(e.getSender()!==this.baseApis.getUserId())return;const t=e.getContent();a.logger.log("got secret share for request",t.request_id);const n=this.requests.get(t.request_id);if(n){const i=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(c.OLM_ALGORITHM,e.getSenderKey());if(!i)return void a.logger.log("secret share from unknown device with key",e.getSenderKey());if(!n.devices.includes(i.deviceId))return void a.logger.log("unsolicited secret share from device",i.deviceId);a.logger.log(`Successfully received secret ${n.name} from ${i.deviceId}`),n.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 i=yield this.cryptoCallbacks.getSecretStorageKey({keys:e},t);if(!i)throw new Error("getSecretStorageKey callback returned falsey");if(i.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[r,o]=i;if(!e[r])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[r].algorithm===n.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)}))}}},{"../logger":126,"../matrix":127,"../randomstring":146,"./aes":94,"./olmlib":105}],94:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.calculateKeyCheck=n.decryptAES=n.encryptAES=void 0;const r=e("../utils"),o=e("./olmlib"),s="undefined"!=typeof window&&window.crypto?window.crypto.subtle||window.crypto.webkitSubtle:null,a=new Uint8Array(8);function c(e,n){const i=(0,r.getCrypto)(),o=i.createHmac("sha256",a).update(e).digest(),s=t.alloc(1,1),c=i.createHmac("sha256",o).update(n,"utf8").update(s).digest();s[0]=2;return[c,i.createHmac("sha256",o).update(c).update(n,"utf8").update(s).digest()]}function l(e,t){return i(this,void 0,void 0,(function*(){const n=yield s.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),i=yield s.deriveBits({name:"HKDF",salt:a,info:(new TextEncoder).encode(t),hash:"SHA-256"},n,512),r=i.slice(0,32),o=i.slice(32),c=s.importKey("raw",r,{name:"AES-CTR"},!1,["encrypt","decrypt"]),l=s.importKey("raw",o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([c,l])}))}function d(e,n,a,d){return s?function(e,t,n,r){return i(this,void 0,void 0,(function*(){let i;r?i=(0,o.decodeBase64)(r):(i=new Uint8Array(16),window.crypto.getRandomValues(i),i[8]&=127);const[a,c]=yield l(t,n),d=(new TextEncoder).encode(e),u=yield s.encrypt({name:"AES-CTR",counter:i,length:64},a,d),h=yield s.sign({name:"HMAC"},c,u);return{iv:(0,o.encodeBase64)(i),ciphertext:(0,o.encodeBase64)(u),mac:(0,o.encodeBase64)(h)}}))}(e,n,a,d):function(e,n,s,a){return i(this,void 0,void 0,(function*(){const i=(0,r.getCrypto)();if(!i)throw new Error("No usable crypto implementation");let l;a?l=(0,o.decodeBase64)(a):(l=i.randomBytes(16),l[8]&=127);const[d,u]=c(n,s),h=i.createCipheriv("aes-256-ctr",d,l),g=t.concat([h.update(e,"utf8"),h.final()]),p=i.createHmac("sha256",u).update(g).digest("base64");return{iv:(0,o.encodeBase64)(l),ciphertext:g.toString("base64"),mac:p}}))}(e,n,a,d)}n.encryptAES=d,n.decryptAES=function(e,n,a){return s?function(e,t,n){return i(this,void 0,void 0,(function*(){const[i,r]=yield l(t,n),a=(0,o.decodeBase64)(e.ciphertext);if(!(yield s.verify({name:"HMAC"},r,(0,o.decodeBase64)(e.mac),a)))throw new Error(`Error decrypting secret ${n}: bad MAC`);const c=yield s.decrypt({name:"AES-CTR",counter:(0,o.decodeBase64)(e.iv),length:64},i,a);return(new TextDecoder).decode(new Uint8Array(c))}))}(e,n,a):function(e,n,s){return i(this,void 0,void 0,(function*(){const i=(0,r.getCrypto)();if(!i)throw new Error("No usable crypto implementation");const[a,l]=c(n,s);if(i.createHmac("sha256",l).update(t.from(e.ciphertext,"base64")).digest("base64").replace(/=+$/g,"")!==e.mac.replace(/=+$/g,""))throw new Error(`Error decrypting secret ${s}: bad MAC`);const d=i.createDecipheriv("aes-256-ctr",a,(0,o.decodeBase64)(e.iv));return d.update(e.ciphertext,"base64","utf8")+d.final("utf8")}))}(e,n,a)};n.calculateKeyCheck=function(e,t){return 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",e,"",t)}}).call(this)}).call(this,e("buffer").Buffer)},{"../utils":159,"./olmlib":105,buffer:20}],95:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.registerAlgorithm=n.UnknownDeviceError=n.DecryptionError=n.DecryptionAlgorithm=n.EncryptionAlgorithm=n.DECRYPTION_CLASSES=n.ENCRYPTION_CLASSES=void 0,n.ENCRYPTION_CLASSES={},n.DECRYPTION_CLASSES={};n.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,n){}};n.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){}importRoomKey(e,t){return i(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 i(this,void 0,void 0,(function*(){return!1}))}};class r extends Error{constructor(e,t,n){super(t),this.code=e,this.code=e,this.name="DecryptionError",this.detailedString=function(e,t){let n=e.name+"[msg: "+e.message;t&&(n+=", "+Object.keys(t).map((e=>e+": "+t[e])).join(", "));return n+="]",n}(this,n)}}n.DecryptionError=r;class o extends Error{constructor(e,t){super(e),this.devices=t,this.name="UnknownDeviceError",this.devices=t}}n.UnknownDeviceError=o,n.registerAlgorithm=function(e,t,i){n.ENCRYPTION_CLASSES[e]=t,n.DECRYPTION_CLASSES[e]=i}},{}],96:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),e("./olm"),e("./megolm"),r(e("./base"),n)},{"./base":95,"./megolm":97,"./olm":98}],97:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.isRoomSharedHistory=void 0;const a=e("../../logger"),c=o(e("../olmlib")),l=e("./base"),d=e("../OlmDevice");function u(e){var t,n;const i=null===(t=null==e?void 0:e.currentState)||void 0===t?void 0:t.getStateEvents("m.room.history_visibility",""),r=null===(n=null==i?void 0:i.getContent())||void 0===n?void 0:n.history_visibility;return["world_readable","shared"].includes(r)}n.isRoomSharedHistory=u;class h{constructor(e,t=!1){this.sessionId=e,this.sharedHistory=t,this.useCount=0,this.sharedWithDevices={},this.blockedDevicesNotified={},this.creationTime=(new Date).getTime()}needsRotation(e,t){const n=(new Date).getTime()-this.creationTime;return(this.useCount>=e||n>=t)&&(a.logger.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0)}markSharedWithDevice(e,t,n,i){this.sharedWithDevices[e]||(this.sharedWithDevices[e]={}),this.sharedWithDevices[e][t]={deviceKey:n,messageIndex:i}}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified[e]||(this.blockedDevicesNotified[e]={}),this.blockedDevicesNotified[e][t]=!0}sharedWithTooManyDevices(e){for(const t in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(t)){if(!e.hasOwnProperty(t))return a.logger.log("Starting new megolm session because we shared with "+t),!0;for(const n in this.sharedWithDevices[t])if(this.sharedWithDevices[t].hasOwnProperty(n)&&!e[t].hasOwnProperty(n))return a.logger.log("Starting new megolm session because we shared with "+t+":"+n),!0}}}class g extends l.EncryptionAlgorithm{constructor(e){var t,n,i,r;super(e),this.setupPromise=Promise.resolve(void 0),this.outboundSessions={},this.sessionRotationPeriodMsgs=null!==(n=null===(t=e.config)||void 0===t?void 0:t.rotation_period_msgs)&&void 0!==n?n:100,this.sessionRotationPeriodMs=null!==(r=null===(i=e.config)||void 0===i?void 0:i.rotation_period_ms)&&void 0!==r?r:6048e5}ensureOutboundSession(e,t,n,i=!1){return s(this,void 0,void 0,(function*(){let r;function o(){return r}const l=this.setupPromise.then((o=>s(this,void 0,void 0,(function*(){r=o;const l=u(e);r&&l!==r.sharedHistory&&(r=null),r&&r.needsRotation(this.sessionRotationPeriodMsgs,this.sessionRotationPeriodMs)&&(a.logger.log("Starting new megolm session because we need to rotate."),r=null),r&&r.sharedWithTooManyDevices(t)&&(r=null),r||(a.logger.log(`Starting new megolm session for room ${this.roomId}`),r=yield this.prepareNewSession(l),a.logger.log(`Started new megolm session ${r.sessionId} for room ${this.roomId}`),this.outboundSessions[r.sessionId]=r);const d={};for(const[e,n]of Object.entries(t))for(const[t,i]of Object.entries(n)){i.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(r.sharedWithDevices[e]&&void 0!==r.sharedWithDevices[e][t]||(d[e]=d[e]||[],d[e].push(i)))}const h=this.olmDevice.getOutboundGroupSessionKey(r.sessionId),g={type:"m.room_key",content:{algorithm:c.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:r.sessionId,session_key:h.key,chain_index:h.chain_index,"org.matrix.msc3061.shared_history":l}},[p,f]=yield c.getExistingOlmSessions(this.olmDevice,this.baseApis,d);yield Promise.all([(()=>s(this,void 0,void 0,(function*(){a.logger.debug(`Sharing keys with existing Olm sessions in ${this.roomId}`,f),yield this.shareKeyWithOlmSessions(r,h,g,f),a.logger.debug(`Shared keys with existing Olm sessions in ${this.roomId}`)})))(),(()=>s(this,void 0,void 0,(function*(){a.logger.debug(`Sharing keys (start phase 1) with new Olm sessions in ${this.roomId}`,p);const e=[],t=Date.now(),n=[];yield this.shareKeyWithDevices(r,h,g,p,e,i?1e4:2e3,n),a.logger.debug(`Shared keys (end phase 1) with new Olm sessions in ${this.roomId}`),!i&&Date.now()-t<1e4?(()=>{s(this,void 0,void 0,(function*(){const t={},i=new Set;for(const e of n)i.add(e);const o=[];for(const{userId:n,deviceInfo:r}of e){const e=n.slice(n.indexOf(":")+1);i.has(e)?(t[n]=t[n]||[],t[n].push(r)):o.push({userId:n,deviceInfo:r})}a.logger.debug(`Sharing keys (start phase 2) with new Olm sessions in ${this.roomId}`),yield this.shareKeyWithDevices(r,h,g,t,o,3e4),a.logger.debug(`Shared keys (end phase 2) with new Olm sessions in ${this.roomId}`),yield this.notifyFailedOlmDevices(r,h,o)}))})():yield this.notifyFailedOlmDevices(r,h,e),a.logger.debug(`Shared keys (all phases done) with new Olm sessions in ${this.roomId}`)})))(),(()=>s(this,void 0,void 0,(function*(){a.logger.debug(`There are ${Object.entries(n).length} blocked devices in ${this.roomId}`,Object.entries(n)),a.logger.debug(`Notifying newly blocked devices in ${this.roomId}`);const e={};let t=0;for(const[i,o]of Object.entries(n))for(const[n,s]of Object.entries(o))r.blockedDevicesNotified[i]&&void 0!==r.blockedDevicesNotified[i][n]||(e[i]=e[i]||{},e[i][n]={device:s},t++);yield this.notifyBlockedDevices(r,e),a.logger.debug(`Notified ${t} newly blocked devices in ${this.roomId}`,e)})))()])}))));return l.catch((e=>{a.logger.error(`Failed to ensure outbound session in ${this.roomId}`,e)})),this.setupPromise=l.then(o,o),l.then(o)}))}prepareNewSession(e){return s(this,void 0,void 0,(function*(){const t=this.olmDevice.createOutboundGroupSession(),n=this.olmDevice.getOutboundGroupSessionKey(t);return yield this.olmDevice.addInboundGroupSession(this.roomId,this.olmDevice.deviceCurve25519Key,[],t,n.key,{ed25519:this.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key,t),new h(t,e)}))}getDevicesWithoutSessions(e,t,n=[]){for(const[i,r]of Object.entries(t)){const t=e[i];for(const e of r){const r=e.deviceId;t[r].sessionId||(n.push({userId:i,deviceInfo:e}),delete t[r])}}return n}splitDevices(e){let t=[];const n=[t];for(const[i,r]of Object.entries(e)){for(const e of Object.values(r))t.push({userId:i,deviceInfo:e.device});t.length>20&&(t=[],n.push(t))}return 0===t.length&&n.pop(),n}encryptAndSendKeysToDevices(e,t,n,i){const r={},o=new Map,s=[];for(let e=0;e<n.length;e++){const t={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},a=n[e],l=a.userId,d=a.deviceInfo,u=d.deviceId;o.set(u,d),r[l]||(r[l]={}),r[l][u]=t,s.push(c.encryptMessageForDevice(t.ciphertext,this.userId,this.deviceId,this.olmDevice,l,d,i))}return Promise.all(s).then((()=>{for(const e of Object.keys(r)){for(const t of Object.keys(r[e]))0===Object.keys(r[e][t].ciphertext).length&&(a.logger.log("No ciphertext for device "+e+":"+t+": pruning"),delete r[e][t]);0===Object.keys(r[e]).length&&(a.logger.log("Pruned all devices for user "+e),delete r[e])}if(0!==Object.keys(r).length)return this.baseApis.sendToDevice("m.room.encrypted",r).then((()=>{for(const n of Object.keys(r))for(const i of Object.keys(r[n]))e.markSharedWithDevice(n,i,o.get(i).getIdentityKey(),t)}));a.logger.log("No users left to send to: aborting")}))}sendBlockedNotificationsToDevices(e,t,n){return s(this,void 0,void 0,(function*(){const i={};for(const e of t){const t=e.userId,r=e.deviceInfo,o=r.deviceInfo.deviceId,s=Object.assign({},n);s.code=r.code,s.reason=r.reason,"m.no_olm"===s.code&&(delete s.room_id,delete s.session_id),i[t]||(i[t]={}),i[t][o]=s}yield this.baseApis.sendToDevice("org.matrix.room_key.withheld",i),yield this.baseApis.sendToDevice("m.room_key.withheld",i);for(const t of Object.keys(i))for(const n of Object.keys(i[t]))e.markNotifiedBlockedDevice(t,n)}))}reshareKeyWithDevice(e,t,n,i){return s(this,void 0,void 0,(function*(){const r=this.outboundSessions[t];if(!r)return void a.logger.debug(`megolm session ${t} not found: not re-sharing keys`);if(void 0===r.sharedWithDevices[n])return void a.logger.debug(`megolm session ${t} never shared with user ${n}`);const o=r.sharedWithDevices[n][i.deviceId];if(void 0===o)return void a.logger.debug("megolm session ID "+t+" never shared with device "+n+":"+i.deviceId);if(o.deviceKey!==i.getIdentityKey())return void a.logger.warn(`Session has been shared with device ${i.deviceId} but with identity key ${o.deviceKey}. Key is now ${i.getIdentityKey()}!`);const s=yield this.olmDevice.getInboundGroupSessionKey(this.roomId,e,t,o.messageIndex);if(!s)return void a.logger.warn(`No inbound session key found for megolm ${t}: not re-sharing keys`);yield c.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[n]:[i]});const l={type:"m.forwarded_room_key",content:{algorithm:c.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:t,session_key:s.key,chain_index:s.chain_index,sender_key:e,sender_claimed_ed25519_key:s.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:s.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":s.shared_history||!1}},d={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};yield c.encryptMessageForDevice(d.ciphertext,this.userId,this.deviceId,this.olmDevice,n,i,l),yield this.baseApis.sendToDevice("m.room.encrypted",{[n]:{[i.deviceId]:d}}),a.logger.debug(`Re-shared key for megolm session ${t} with ${n}:${i.deviceId}`)}))}shareKeyWithDevices(e,t,n,i,r,o,l){return s(this,void 0,void 0,(function*(){a.logger.debug(`Ensuring Olm sessions for devices in ${this.roomId}`);const s=yield c.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,i,!1,o,l,a.logger.withPrefix(`[${this.roomId}]`));a.logger.debug(`Ensured Olm sessions for devices in ${this.roomId}`),this.getDevicesWithoutSessions(s,i,r),a.logger.debug(`Sharing keys with newly created Olm sessions in ${this.roomId}`),yield this.shareKeyWithOlmSessions(e,t,n,s),a.logger.debug(`Shared keys with newly created Olm sessions in ${this.roomId}`)}))}shareKeyWithOlmSessions(e,t,n,i){return s(this,void 0,void 0,(function*(){const r=this.splitDevices(i);for(let i=0;i<r.length;i++){const o=`megolm keys for ${e.sessionId} in ${this.roomId} (slice ${i+1}/${r.length})`;try{a.logger.debug(`Sharing ${o}`,r[i].map((e=>`${e.userId}/${e.deviceInfo.deviceId}`))),yield this.encryptAndSendKeysToDevices(e,t.chain_index,r[i],n),a.logger.debug(`Shared ${o}`)}catch(e){throw a.logger.error(`Failed to share ${o}`),e}}}))}notifyFailedOlmDevices(e,t,n){return s(this,void 0,void 0,(function*(){a.logger.debug(`Notifying ${n.length} devices we failed to create Olm sessions in ${this.roomId}`);for(const{userId:i,deviceInfo:r}of n){const n=r.deviceId;e.markSharedWithDevice(i,n,r.getIdentityKey(),t.chain_index)}const i=yield this.olmDevice.filterOutNotifiedErrorDevices(n);a.logger.debug(`Need to notify ${i.length} failed devices which haven't been notified before in ${this.roomId}`);const r={};for(const{userId:e,deviceInfo:t}of i)r[e]=r[e]||{},r[e][t.deviceId]={device:{code:"m.no_olm",reason:d.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:t}};yield this.notifyBlockedDevices(e,r),a.logger.debug(`Notified ${i.length} devices we failed to create Olm sessions in ${this.roomId}`)}))}notifyBlockedDevices(e,t){return s(this,void 0,void 0,(function*(){const n={room_id:this.roomId,session_id:e.sessionId,algorithm:c.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key},i=this.splitDevices(t);for(let t=0;t<i.length;t++)try{yield this.sendBlockedNotificationsToDevices(e,i[t],n),a.logger.log(`Completed blacklist notification for ${e.sessionId} in ${this.roomId} (slice ${t+1}/${i.length})`)}catch(n){throw a.logger.log(`blacklist notification for ${e.sessionId} in ${this.roomId} (slice ${t+1}/${i.length}) failed`),n}}))}prepareToEncrypt(e){if(this.encryptionPreparation){const e=Date.now()-this.encryptionPreparationMetadata.startTime;a.logger.debug(`Already started preparing to encrypt for ${this.roomId} ${e} ms ago, skipping`)}else a.logger.debug(`Preparing to encrypt events for ${this.roomId}`),this.encryptionPreparationMetadata={startTime:Date.now()},this.encryptionPreparation=(()=>s(this,void 0,void 0,(function*(){try{a.logger.debug(`Getting devices in ${this.roomId}`);const[t,n]=yield this.getDevicesInRoom(e);this.crypto.getGlobalErrorOnUnknownDevices()&&this.removeUnknownDevices(t),a.logger.debug(`Ensuring outbound session in ${this.roomId}`),yield this.ensureOutboundSession(e,t,n,!0),a.logger.debug(`Ready to encrypt events for ${this.roomId}`)}catch(e){a.logger.error(`Failed to prepare to encrypt events for ${this.roomId}`,e)}finally{delete this.encryptionPreparationMetadata,delete this.encryptionPreparation}})))()}encryptMessage(e,t,n){return s(this,void 0,void 0,(function*(){if(a.logger.log(`Starting to encrypt event for ${this.roomId}`),this.encryptionPreparation)try{yield this.encryptionPreparation}catch(e){}const[i,r]=yield this.getDevicesInRoom(e);this.crypto.getGlobalErrorOnUnknownDevices()&&this.checkForUnknownDevices(i);const o=yield this.ensureOutboundSession(e,i,r),s={room_id:this.roomId,type:t,content:n},l=this.olmDevice.encryptGroupMessage(o.sessionId,JSON.stringify(s)),d={algorithm:c.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:l,session_id:o.sessionId,device_id:this.deviceId};return o.useCount++,d}))}forceDiscardSession(){this.setupPromise=this.setupPromise.then((()=>null))}checkForUnknownDevices(e){const t={};if(Object.keys(e).forEach((n=>{Object.keys(e[n]).forEach((i=>{const r=e[n][i];r.isUnverified()&&!r.isKnown()&&(t[n]||(t[n]={}),t[n][i]=r)}))})),Object.keys(t).length)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,n]of Object.entries(e)){for(const[e,t]of Object.entries(n))t.isUnverified()&&!t.isKnown()&&delete n[e];0===Object.keys(n).length&&delete e[t]}}getDevicesInRoom(e){return s(this,void 0,void 0,(function*(){const t=(yield e.getEncryptionTargetMembers()).map((function(e){return e.userId}));let n=this.crypto.getGlobalBlacklistUnverifiedDevices();"boolean"==typeof e.getBlacklistUnverifiedDevices()&&(n=e.getBlacklistUnverifiedDevices());const i=yield this.crypto.downloadKeys(t,!1),r={};for(const e in i){if(!i.hasOwnProperty(e))continue;const t=i[e];for(const i in t){if(!t.hasOwnProperty(i))continue;const o=this.crypto.checkDeviceTrust(e,i);if(t[i].isBlocked()||!o.isVerified()&&n){r[e]||(r[e]={});const n=t[i].isBlocked();r[e][i]={code:n?"m.blacklisted":"m.unverified",reason:d.WITHHELD_MESSAGES[n?"m.blacklisted":"m.unverified"],deviceInfo:t[i]},delete t[i]}}}return[i,r]}))}}class p extends l.DecryptionAlgorithm{constructor(){super(...arguments),this.pendingEvents={},this.olmlib=c}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 n;this.addEventToPendingList(e);try{n=yield this.olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext,e.getId(),e.getTs())}catch(n){if("DecryptionError"===n.name)throw n;let i="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw n&&"OLM.UNKNOWN_MESSAGE_INDEX"===n.message&&(this.requestKeysForEvent(e),i="OLM_UNKNOWN_MESSAGE_INDEX"),new l.DecryptionError(i,n?n.toString():"Unknown Error: Error is undefined",{session:t.sender_key+"|"+t.session_id})}if(null===n){this.requestKeysForEvent(e);const n=yield this.olmDevice.sessionMayHaveProblems(t.sender_key,e.getTs()-12e4);if(n){let e=f[n.type]||f.unknown;throw n.fixed&&(e+=" Trying to create a new secure channel and re-requesting the keys."),new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",e,{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})}this.removeEventFromPendingList(e);const i=JSON.parse(n.result);if(i.room_id!==e.getRoomId())throw new l.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+i.room_id);return{clearEvent:i,senderCurve25519Key:n.senderKey,claimedEd25519Key:n.keysClaimed.ed25519,forwardingCurve25519KeyChain:n.forwardingCurve25519KeyChain,untrusted:n.untrusted}}))}requestKeysForEvent(e){const t=e.getWireContent(),n=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},n)}addEventToPendingList(e){const t=e.getWireContent(),n=t.sender_key,i=t.session_id;this.pendingEvents[n]||(this.pendingEvents[n]=new Map);const r=this.pendingEvents[n];r.has(i)||r.set(i,new Set),r.get(i).add(e)}removeEventFromPendingList(e){const t=e.getWireContent(),n=t.sender_key,i=t.session_id,r=this.pendingEvents[n],o=null==r?void 0:r.get(i);o&&(o.delete(e),0===o.size&&r.delete(i),0===r.size&&delete this.pendingEvents[n])}onRoomKeyEvent(e){const t=e.getContent(),n=t.session_id;let i,r=e.getSenderKey(),o=[],s=!1;if(!t.room_id||!n||!t.session_key)return void a.logger.error("key event is missing fields");if(!r)return void a.logger.error("key event has no sender key (not encrypted?)");if("m.forwarded_room_key"==e.getType()){if(s=!0,o=t.forwarding_curve25519_key_chain,Array.isArray(o)||(o=[]),o=o.slice(),o.push(r),r=t.sender_key,!r)return void a.logger.error("forwarded_room_key event is missing sender_key field");const e=t.sender_claimed_ed25519_key;if(!e)return void a.logger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");i={ed25519:e}}else i=e.getKeysClaimed();const c={};return t["org.matrix.msc3061.shared_history"]&&(c.sharedHistory=!0),this.olmDevice.addInboundGroupSession(t.room_id,r,o,n,t.session_key,i,s,c).then((()=>{this.retryDecryption(r,n).then((e=>{e&&this.crypto.cancelRoomKeyRequest({algorithm:t.algorithm,room_id:t.room_id,session_id:t.session_id,sender_key:r})}))})).then((()=>{this.crypto.backupManager.backupGroupSession(r,t.session_id)})).catch((e=>{a.logger.error(`Error handling m.room_key_event: ${e}`)}))}onRoomKeyWithheldEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),n=t.sender_key;if("m.no_olm"===t.code){const i=e.getSender();if(a.logger.warn(`${i}:${n} was unable to establish an olm session with us`),yield this.olmDevice.getSessionIdForDevice(n))return a.logger.debug("New session already created. Not creating a new one."),yield this.olmDevice.recordSessionProblem(n,"no_olm",!0),void this.retryDecryptionFromSender(n);let r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,n);if(!r&&(yield this.crypto.downloadKeys([i],!1),r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,n),!r))return a.logger.info("Couldn't find device for identity key "+n+": not establishing session"),yield this.olmDevice.recordSessionProblem(n,"no_olm",!1),void this.retryDecryptionFromSender(n);yield c.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[i]:[r]},!1);const o={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};yield c.encryptMessageForDevice(o.ciphertext,this.userId,void 0,this.olmDevice,i,r,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(n,"no_olm",!0),this.retryDecryptionFromSender(n),yield this.baseApis.sendToDevice("m.room.encrypted",{[i]:{[r.deviceId]:o}})}else yield this.olmDevice.addInboundGroupSessionWithheld(t.room_id,n,t.session_id,t.code,t.reason)}))}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,n=e.deviceId,i=this.crypto.getStoredDevice(t,n),r=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[t]:[i]}).then((e=>e[t][n].sessionId?(a.logger.log("sharing keys for session "+r.sender_key+"|"+r.session_id+" with device "+t+":"+n),this.buildKeyForwardingMessage(r.room_id,r.sender_key,r.session_id)):null)).then((e=>{const r={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};return this.olmlib.encryptMessageForDevice(r.ciphertext,this.userId,void 0,this.olmDevice,t,i,e).then((()=>{const e={[t]:{[n]:r}};return this.baseApis.sendToDevice("m.room.encrypted",e)}))}))}buildKeyForwardingMessage(e,t,n){return s(this,void 0,void 0,(function*(){const i=yield this.olmDevice.getInboundGroupSessionKey(e,t,n);return{type:"m.forwarded_room_key",content:{algorithm:c.MEGOLM_ALGORITHM,room_id:e,sender_key:t,sender_claimed_ed25519_key:i.sender_claimed_ed25519_key,session_id:n,session_key:i.key,chain_index:i.chain_index,forwarding_curve25519_key_chain:i.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":i.shared_history||!1}}}))}importRoomKey(e,t={}){const n={};return(t.untrusted||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"!==t.source&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch((e=>{a.logger.log("Failed to back up megolm session",e)})),this.retryDecryption(e.sender_key,e.session_id)}))}retryDecryption(e,t){var n;return s(this,void 0,void 0,(function*(){const i=this.pendingEvents[e];if(!i)return!0;const r=i.get(t);return!r||(a.logger.debug("Retrying decryption on events",[...r]),yield Promise.all([...r].map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto,{isRetry:!0})}catch(e){}}))))),!(null===(n=this.pendingEvents[e])||void 0===n?void 0:n.has(t)))}))}retryDecryptionFromSender(e){return s(this,void 0,void 0,(function*(){const t=this.pendingEvents[e];return!t||(delete this.pendingEvents[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[e])}))}sendSharedHistoryInboundSessions(e){return s(this,void 0,void 0,(function*(){yield c.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,e),a.logger.log("sendSharedHistoryInboundSessions to users",Object.keys(e));const t=yield this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);a.logger.log("shared-history sessions",t);for(const[n,i]of t){const t=yield this.buildKeyForwardingMessage(this.roomId,n,i),r=[],o={};for(const[n,i]of Object.entries(e)){o[n]={};for(const e of i){const i={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};o[n][e.deviceId]=i,r.push(c.encryptMessageForDevice(i.ciphertext,this.userId,void 0,this.olmDevice,n,e,t))}}yield Promise.all(r);for(const e of Object.keys(o)){for(const t of Object.keys(o[e]))0===Object.keys(o[e][t].ciphertext).length&&(a.logger.log("No ciphertext for device "+e+":"+t+": pruning"),delete o[e][t]);0===Object.keys(o[e]).length&&(a.logger.log("Pruned all devices for user "+e),delete o[e])}if(0===Object.keys(o).length)return void a.logger.log("No users left to send to: aborting");yield this.baseApis.sendToDevice("m.room.encrypted",o)}}))}}const f={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};(0,l.registerAlgorithm)(c.MEGOLM_ALGORITHM,g,p)},{"../../logger":126,"../OlmDevice":90,"../olmlib":105,"./base":95}],98:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0});const a=e("../../logger"),c=o(e("../olmlib")),l=e("../deviceinfo"),d=e("./base"),u=l.DeviceInfo.DeviceVerification;class h extends d.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,n){return s(this,void 0,void 0,(function*(){const i=(yield e.getEncryptionTargetMembers()).map((function(e){return e.userId}));yield this.ensureSession(i);const r={room_id:e.roomId,type:t,content:n},o={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},s=[];for(let e=0;e<i.length;++e){const t=i[e],n=this.crypto.getStoredDevicesForUser(t);for(let e=0;e<n.length;++e){const i=n[e];i.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(i.verified!=u.BLOCKED&&s.push(c.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,t,i,r)))}}return Promise.all(s).then((()=>o))}))}}class g extends d.DecryptionAlgorithm{decryptEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getWireContent(),n=t.sender_key,i=t.ciphertext;if(!i)throw new d.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in i))throw new d.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const r=i[this.olmDevice.deviceCurve25519Key];let o;try{o=yield this.decryptMessage(n,r)}catch(e){throw new d.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:n,err:e})}const s=JSON.parse(o);if(s.recipient!=this.userId)throw new d.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+s.recipient);if(s.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new d.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:s.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});if(s.sender!=e.getSender())throw new d.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+s.sender,{reported_sender:e.getSender()});if(s.room_id!==e.getRoomId())throw new d.DecryptionError("OLM_BAD_ROOM","Message intended for room "+s.room_id,{reported_room:e.getRoomId()});return{clearEvent:s,senderCurve25519Key:n,claimedEd25519Key:(s.keys||{}).ed25519||null}}))}decryptMessage(e,t){if(0!==t.type)return this.reallyDecryptMessage(e,t);{const n=this.olmDevice.olmPrekeyPromise.then((()=>this.reallyDecryptMessage(e,t)));return this.olmDevice.olmPrekeyPromise=n.catch((()=>{})),n}}reallyDecryptMessage(e,t){return s(this,void 0,void 0,(function*(){const n=yield this.olmDevice.getSessionIdsForDevice(e),i={};for(let r=0;r<n.length;r++){const o=n[r];try{const n=yield this.olmDevice.decryptMessage(e,o,t.type,t.body);return a.logger.log("Decrypted Olm message from "+e+" with session "+o),n}catch(n){if(yield this.olmDevice.matchesSession(e,o,t.type,t.body))throw new Error("Error decrypting prekey message with existing session id "+o+": "+n.message);i[o]=n.message}}if(0!==t.type){if(0===n.length)throw new Error("No existing sessions");throw new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(i))}let r;try{r=yield this.olmDevice.createInboundSession(e,t.type,t.body)}catch(e){throw i["(new)"]=e.message,new Error("Error decrypting prekey message: "+JSON.stringify(i))}return a.logger.log("created new inbound Olm session ID "+r.session_id+" with "+e),r.payload}))}}(0,d.registerAlgorithm)(c.OLM_ALGORITHM,h,g)},{"../../logger":126,"../deviceinfo":102,"../olmlib":105,"./base":95}],99:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.CrossSigningKey=void 0,function(e){e.Master="master",e.SelfSigning="self_signing",e.UserSigning="user_signing"}(n.CrossSigningKey||(n.CrossSigningKey={}))},{}],100:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.DefaultAlgorithm=n.algorithmsByName=n.Aes256=n.Curve25519=n.BackupManager=void 0;const r=e("../client"),o=e("../logger"),s=e("./olmlib"),a=e("./key_passphrase"),c=e("../utils"),l=e("./store/indexeddb-crypto-store"),d=e("./recoverykey"),u=e("./aes"),h=e("../NamespacedValue"),g=e("./index");class p{constructor(e,t){this.baseApis=e,this.getKey=t,this.checkedForBackup=!1,this.sendingBackups=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){const t=n.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 i=n.algorithmsByName[e.algorithm];if(!i)throw new Error("Unknown backup algorithm");return i.init(e.auth_data,t)}enableKeyBackup(e){return i(this,void 0,void 0,(function*(){this.backupInfo=e,this.algorithm&&this.algorithm.free(),this.algorithm=yield p.makeAlgorithm(e,this.getKey),this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!0),this.scheduleKeyBackupSend()}))}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?Boolean(this.algorithm):null}prepareKeyBackupVersion(e,t){return i(this,void 0,void 0,(function*(){const i=t?n.algorithmsByName[t]:n.DefaultAlgorithm;if(!i)throw new Error("Unknown backup algorithm");const[r,o]=yield i.prepare(e),s=(0,d.encodeRecoveryKey)(r);return{algorithm:i.algorithmName,auth_data:o,recovery_key:s,privateKey:r}}))}createKeyBackupVersion(e){return i(this,void 0,void 0,(function*(){this.algorithm=yield p.makeAlgorithm(e,this.getKey)}))}checkAndStart(){return i(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 e;try{e=yield this.baseApis.getKeyBackupVersion()}catch(e){return o.logger.log("Error checking for active key backup",e),404===e.httpStatus&&(this.checkedForBackup=!0),null}this.checkedForBackup=!0;const t=yield this.isKeyBackupTrusted(e);return t.usable&&!this.backupInfo?(o.logger.log("Found usable key backup v"+e.version+": enabling key backups"),yield this.enableKeyBackup(e)):!t.usable&&this.backupInfo?(o.logger.log("No usable key backup: disabling key backup"),this.disableKeyBackup()):t.usable||this.backupInfo?t.usable&&this.backupInfo&&(e.version!==this.backupInfo.version?(o.logger.log("On backup version "+this.backupInfo.version+" but found version "+e.version+": switching."),this.disableKeyBackup(),yield this.enableKeyBackup(e),yield this.scheduleAllGroupSessionsForBackup()):o.logger.log("Backup version "+e.version+" still current")):o.logger.log("No usable key backup: not enabling key backup"),{backupInfo:e,trustInfo:t}}))}checkKeyBackup(){return i(this,void 0,void 0,(function*(){return this.checkedForBackup=!1,this.checkAndStart()}))}isKeyBackupTrusted(e){return i(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 n=yield this.baseApis.crypto.getSessionBackupPrivateKey();if(n){let r;try{r=yield p.makeAlgorithm(e,(()=>i(this,void 0,void 0,(function*(){return n})))),(yield r.keyMatches(n))&&(o.logger.info("Backup is trusted locally"),t.trusted_locally=!0)}catch(e){}finally{r&&r.free()}}const r=e.auth_data.signatures[this.baseApis.getUserId()]||{};for(const n of Object.keys(r)){const i=n.split(":");if("ed25519"!==i[0]){o.logger.log("Ignoring unknown signature type: "+i[0]);continue}const r={deviceId:i[1]},a=this.baseApis.crypto.crossSigningInfo.getId();if(a===r.deviceId){r.crossSigningId=!0;try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,this.baseApis.getUserId(),r.deviceId,a),r.valid=!0}catch(e){o.logger.warn("Bad signature from cross signing key "+a,e),r.valid=!1}t.sigs.push(r);continue}const c=this.baseApis.crypto.deviceList.getStoredDevice(this.baseApis.getUserId(),r.deviceId);if(c){r.device=c,r.deviceTrust=this.baseApis.checkDeviceTrust(this.baseApis.getUserId(),r.deviceId);try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,this.baseApis.getUserId(),c.deviceId,c.getFingerprint()),r.valid=!0}catch(t){o.logger.info("Bad signature from key ID "+n+" userID "+this.baseApis.getUserId()+" device ID "+c.deviceId+" fingerprint: "+c.getFingerprint(),e.auth_data,t),r.valid=!1}}else r.valid=null,o.logger.info("Ignoring signature from unknown key "+n);t.sigs.push(r)}return t.usable=t.sigs.some((e=>e.valid&&(e.device&&e.deviceTrust.isVerified()||e.crossSigningId))),t.usable=t.usable||t.trusted_locally,t}))}scheduleKeyBackupSend(e=1e4){return i(this,void 0,void 0,(function*(){if(!this.sendingBackups){this.sendingBackups=!0;try{const t=Math.random()*e;yield(0,c.sleep)(t);let n=0;for(;;){if(!this.algorithm)return;try{if(0===(yield this.backupPendingKeys(200)))return;n=0}catch(e){if(n++,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(g.CryptoEvent.KeyBackupFailed,e.data.errcode),e}n&&(yield(0,c.sleep)(1e3*Math.pow(2,Math.min(n-1,4))))}}finally{this.sendingBackups=!1}}}))}backupPendingKeys(e){return i(this,void 0,void 0,(function*(){const t=yield this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!t.length)return 0;let n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,n);const i={};for(const e of t){const t=e.sessionData.room_id;void 0===i[t]&&(i[t]={sessions:{}});const n=this.baseApis.crypto.olmDevice.exportInboundGroupSession(e.senderKey,e.sessionId,e.sessionData);n.algorithm=s.MEGOLM_ALGORITHM;const r=(n.forwarding_curve25519_key_chain||[]).length,o=this.baseApis.crypto.deviceList.getUserByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey),a=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey),c=this.baseApis.crypto.checkDeviceInfoTrust(o,a).isVerified();i[t].sessions[e.sessionId]={first_message_index:n.first_known_index,forwarded_count:r,is_verified:c,session_data:yield this.algorithm.encryptSession(n)}}return yield this.baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:i}),yield this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(t),n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,n),t.length}))}backupGroupSession(e,t){return i(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),this.backupInfo&&this.scheduleKeyBackupSend()}))}scheduleAllGroupSessionsForBackup(){return i(this,void 0,void 0,(function*(){yield this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)}))}flagAllGroupSessionsForBackup(){return i(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.doTxn("readwrite",[l.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,l.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(g.CryptoEvent.KeyBackupSessionsRemaining,e),e}))}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}n.BackupManager=p;class f{constructor(e,t,n){this.authData=e,this.publicKey=t,this.getKey=n}static init(e,n){return i(this,void 0,void 0,(function*(){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");const i=new t.Olm.PkEncryption;return i.set_recipient_key(e.public_key),new f(e,i,n)}))}static prepare(e){return i(this,void 0,void 0,(function*(){const n=new t.Olm.PkDecryption;try{const i={};if(e)if(e instanceof Uint8Array)i.public_key=n.init_with_private_key(e);else{const t=yield(0,a.keyFromPassphrase)(e);i.private_key_salt=t.salt,i.private_key_iterations=t.iterations,i.public_key=n.init_with_private_key(t.key)}else i.public_key=n.generate_key();return(new t.Olm.PkEncryption).set_recipient_key(i.public_key),[n.get_private_key(),i]}finally{n.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 i(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 i(this,void 0,void 0,(function*(){const n=yield this.getKey(),i=new t.Olm.PkDecryption;try{if(i.init_with_private_key(n)!==this.authData.public_key)throw{errcode:r.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY};const t=[];for(const[n,r]of Object.entries(e))try{const e=JSON.parse(i.decrypt(r.session_data.ephemeral,r.session_data.mac,r.session_data.ciphertext));e.session_id=n,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,r)}return t}finally{i.free()}}))}keyMatches(e){return i(this,void 0,void 0,(function*(){const n=new t.Olm.PkDecryption;let i;try{i=n.init_with_private_key(e)}finally{n.free()}return i===this.authData.public_key}))}free(){this.publicKey.free()}}n.Curve25519=f,f.algorithmName="m.megolm_backup.v1.curve25519-aes-sha2";const v=new h.UnstableValue(null,"org.matrix.msc3270.v1.aes-hmac-sha2");class y{constructor(e,t){this.authData=e,this.key=t}static init(e,t){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("auth_data missing");const n=yield t();if(e.mac){const{mac:t}=yield(0,u.calculateKeyCheck)(n,e.iv);if(e.mac.replace(/=+$/g,"")!==t.replace(/=+/g,""))throw new Error("Key does not match")}return new y(e,n)}))}static prepare(e){return i(this,void 0,void 0,(function*(){let t;const n={};if(e)if(e instanceof Uint8Array)t=new Uint8Array(e);else{const i=yield(0,a.keyFromPassphrase)(e);n.private_key_salt=i.salt,n.private_key_iterations=i.iterations,t=i.key}else t=function(e){const t=(0,c.getCrypto)();if(t)return t.randomBytes(e);if(null===window||void 0===window?void 0:window.crypto){const t=new Uint8Array(e);return window.crypto.getRandomValues(t),t}throw new Error("No usable crypto implementation")}(32);const{iv:i,mac:r}=yield(0,u.calculateKeyCheck)(t);return n.iv=i,n.mac=r,[t,n]}))}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 i(this,void 0,void 0,(function*(){const t=[];for(const[n,i]of Object.entries(e))try{const e=JSON.parse(yield(0,u.decryptAES)(i.session_data,this.key,n));e.session_id=n,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,i)}return t}))}keyMatches(e){return i(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)}}n.Aes256=y,y.algorithmName=v.name,n.algorithmsByName={[f.algorithmName]:f,[y.algorithmName]:y},n.DefaultAlgorithm=f}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../NamespacedValue":80,"../client":84,"../logger":126,"../utils":159,"./aes":94,"./index":103,"./key_passphrase":104,"./olmlib":105,"./recoverykey":106,"./store/indexeddb-crypto-store":108}],101:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.DehydrationManager=n.DEHYDRATION_ALGORITHM=void 0;const s=o(e("another-json")),a=e("./olmlib"),c=e("../crypto/store/indexeddb-crypto-store"),l=e("./aes"),d=e("../logger"),u=e("../http-api");n.DEHYDRATION_ALGORITHM="org.matrix.msc2697.v1.olm.libolm_pickle";const h=6048e5;n.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,d=i.from(this.crypto.olmDevice.pickleKey),u=yield(0,l.decryptAES)(r,d,n.DEHYDRATION_ALGORITHM);this.key=(0,a.decodeBase64)(u),this.keyInfo=o,this.deviceDisplayName=s;const g=Date.now(),p=Math.max(1,c+h-g);this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),p)}}))),"dehydration")}))}setKeyAndQueueDehydration(e,t={},n){return r(this,void 0,void 0,(function*(){(yield this.setKey(e,t,n))||this.dehydrateDevice()}))}setKey(e,n={},i){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=n,this.deviceDisplayName=i),r}))}dehydrateDevice(){return r(this,void 0,void 0,(function*(){if(this.inProgress)d.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=i.from(this.crypto.olmDevice.pickleKey),r=yield(0,l.encryptAES)((0,a.encodeBase64)(this.key),e,n.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()})})),d.logger.log("Attempting to dehydrate device"),d.logger.log("Creating account");const o=new t.Olm.Account;o.create();const g=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 f=JSON.parse(o.one_time_keys()),v=JSON.parse(o.fallback_key());o.mark_keys_as_published();const y=o.pickle(new Uint8Array(this.key)),m={algorithm:n.DEHYDRATION_ALGORITHM,account:y};this.keyInfo.passphrase&&(m.passphrase=this.keyInfo.passphrase),d.logger.log("Uploading account to server");const E=(yield this.crypto.baseApis.http.authedRequest(void 0,u.Method.Put,"/dehydrated_device",void 0,{device_data:m,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;d.logger.log("Preparing device keys",E);const S={algorithms:this.crypto.supportedAlgorithms,device_id:E,user_id:this.crypto.userId,keys:{[`ed25519:${E}`]:g.ed25519,[`curve25519:${E}`]:g.curve25519}},b=o.sign(s.default.stringify(S));S.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:b}},this.crypto.crossSigningInfo.getId("self_signing")&&(yield this.crypto.crossSigningInfo.signObject(S,"self_signing")),d.logger.log("Preparing one-time keys");const _={};for(const[e,t]of Object.entries(f.curve25519)){const n={key:t},i=o.sign(s.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:i}},_[`signed_curve25519:${e}`]=n}d.logger.log("Preparing fallback keys");const T={};for(const[e,t]of Object.entries(v.curve25519)){const n={key:t,fallback:!0},i=o.sign(s.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:i}},T[`signed_curve25519:${e}`]=n}return d.logger.log("Uploading keys to server"),yield this.crypto.baseApis.http.authedRequest(void 0,u.Method.Post,"/keys/upload/"+encodeURI(E),void 0,{device_keys:S,one_time_keys:_,"org.matrix.msc2732.fallback_keys":T}),d.logger.log("Done dehydrating"),this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),h),E}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":108,"../http-api":123,"../logger":126,"./aes":94,"./olmlib":105,"another-json":14,buffer:20}],102:[function(e,t,n){"use strict";var i;Object.defineProperty(n,"__esModule",{value:!0}),n.DeviceInfo=void 0,function(e){e[e.Blocked=-1]="Blocked",e[e.Unverified=0]="Unverified",e[e.Verified=1]="Verified"}(i||(i={}));class r{constructor(e){this.deviceId=e,this.keys={},this.verified=i.Unverified,this.known=!1,this.unsigned={},this.signatures={}}static fromStorage(e,t){const n=new r(t);for(const t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}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==i.Blocked}isVerified(){return this.verified==i.Verified}isUnverified(){return this.verified==i.Unverified}isKnown(){return!0===this.known}}n.DeviceInfo=r,r.DeviceVerification={VERIFIED:i.Verified,UNVERIFIED:i.Unverified,BLOCKED:i.Blocked}},{}],103:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t},a=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.IncomingRoomKeyRequest=n.fixBackupKey=n.Crypto=n.CryptoEvent=n.isCryptoAvailable=n.verificationMethods=void 0;const l=c(e("another-json")),d=e("../ReEmitter"),u=e("../logger"),h=e("./OlmDevice"),g=s(e("./olmlib")),p=e("./DeviceList"),f=e("./deviceinfo"),v=s(e("./algorithms")),y=e("./CrossSigning"),m=e("./EncryptionSetup"),E=e("./SecretStorage"),S=e("./OutgoingRoomKeyRequestManager"),b=e("./store/indexeddb-crypto-store"),_=e("./verification/QRCode"),T=e("./verification/SAS"),w=e("./key_passphrase"),I=e("./recoverykey"),R=e("./verification/request/VerificationRequest"),k=e("./verification/request/InRoomChannel"),O=e("./verification/request/ToDeviceChannel"),C=e("./verification/IllegalMethod"),P=e("../errors"),M=e("./aes"),D=e("./dehydration"),A=e("./backup"),x=e("../models/room"),U=e("../models/room-member"),N=e("../models/event"),L=e("../client"),B=e("../models/typed-event-emitter"),K=f.DeviceInfo.DeviceVerification,j={[_.ReciprocateQRCode.NAME]:_.ReciprocateQRCode,[T.SAS.NAME]:T.SAS,[_.SHOW_QR_CODE_METHOD]:C.IllegalMethod,[_.SCAN_QR_CODE_METHOD]:C.IllegalMethod};n.verificationMethods={RECIPROCATE_QR_CODE:_.ReciprocateQRCode.NAME,SAS:T.SAS.NAME},n.isCryptoAvailable=function(){return Boolean(t.Olm)};var F;!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"}(F=n.CryptoEvent||(n.CryptoEvent={}));class q extends B.TypedEventEmitter{constructor(e,t,n,i,r,o,s,c){if(super(),this.baseApis=e,this.sessionStore=t,this.userId=n,this.deviceId=i,this.clientStore=r,this.cryptoStore=o,this.roomList=s,this.trustCrossSignedDevices=!0,this.lastOneTimeKeyCheck=null,this.oneTimeKeyCheckInProgress=!1,this.roomEncryptors={},this.roomDecryptors={},this.deviceKeys={},this.globalBlacklistUnverifiedDevices=!1,this.globalErrorOnUnknownDevices=!0,this.receivedRoomKeyRequests=[],this.receivedRoomKeyRequestCancellations=[],this.processingRoomKeyRequests=!1,this.lazyLoadMembers=!1,this.roomDeviceTrackingState={},this.lastNewSessionForced={},this.sendKeyRequestsImmediately=!1,this.onDeviceListUserCrossSigningUpdated=e=>a(this,void 0,void 0,(function*(){if(e===this.userId){const t=this.deviceList.getStoredCrossSigningForUser(e),n=t?t.getId():null,i=this.crossSigningInfo.getId(),r=i!==n;i&&n&&!r?yield this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit(F.KeysChanged,{}),this.emit(F.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(F.UserTrustStatusChanged,e,this.checkUserTrust(e))}})),this.onMembership=(e,t,n)=>{try{this.onRoomMembership(e,t,n)}catch(e){u.logger.error("Error handling membership change:",e)}},this.onToDeviceEvent=e=>{try{u.logger.log(`received to_device ${e.getType()} from: ${e.getSender()} id: ${e.getId()}`),"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()||"org.matrix.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){u.logger.error("Error handling toDeviceEvent:",e)}},this.onTimelineEvent=(e,t,n,i,{liveEvent:r=!0}={})=>{if(!k.InRoomChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.inRoomVerificationRequests,(e=>{const t=new k.InRoomChannel(this.baseApis,e.getRoomId());return new R.VerificationRequest(t,this.verificationMethods,this.baseApis)}),r)},this.reEmitter=new d.TypedReEmitter(this),c){this.verificationMethods=new Map;for(const e of c)"string"==typeof e?j[e]&&this.verificationMethods.set(e,j[e]):e.NAME?this.verificationMethods.set(e.NAME,e):u.logger.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=new Map(Object.entries(j));this.backupManager=new A.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=V(t);if(e){const[t]=yield this.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",e,[t])}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 h.OlmDevice(o),this.deviceList=new p.DeviceList(e,o,this.olmDevice),this.deviceList.on(F.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[F.DevicesUpdated,F.WillUpdateDevices]),this.supportedAlgorithms=Object.keys(v.DECRYPTION_CLASSES),this.outgoingRoomKeyRequestManager=new S.OutgoingRoomKeyRequestManager(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new O.ToDeviceRequests,this.inRoomVerificationRequests=new k.InRoomRequests;const l=this.baseApis.cryptoCallbacks||{},f=(0,y.createCryptoStoreCacheCallbacks)(o,this.olmDevice);this.crossSigningInfo=new y.CrossSigningInfo(n,l,f),this.secretStorage=new E.SecretStorage(e,l,e),this.dehydrationManager=new D.DehydrationManager(this),!l.getCrossSigningKey&&l.getSecretStorageKey&&(l.getCrossSigningKey=e=>a(this,void 0,void 0,(function*(){return y.CrossSigningInfo.getFromSecretStorage(e,this.secretStorage)})))}static getOlmVersion(){return h.OlmDevice.getOlmVersion()}init({exportedOlmDevice:e,pickleKey:n}={}){return a(this,void 0,void 0,(function*(){u.logger.log("Crypto: initialising Olm..."),yield t.Olm.init(),u.logger.log(e?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield this.olmDevice.init({fromExportedDevice:e,pickleKey:n}),u.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,u.logger.log("Crypto: fetching own devices...");let i=this.deviceList.getRawStoredDevicesForUser(this.userId);if(i||(i={}),!i[this.deviceId]){u.logger.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:K.VERIFIED,known:!0};i[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,i),this.deviceList.saveIfDirty()}yield this.cryptoStore.doTxn("readonly",[b.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(u.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),u.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 n of Object.keys(t)){const t=this.checkDeviceTrust(e,n);if(!t.isLocallyVerified()&&t.isCrossSigningVerified()){const t=this.deviceList.getStoredDevice(e,n);this.emit(F.DeviceVerificationChanged,e,n,t)}}}}createRecoveryKeyFromPassphrase(e){return a(this,void 0,void 0,(function*(){const n=new t.Olm.PkDecryption;try{const t={};if(e){const i=yield(0,w.keyFromPassphrase)(e);t.passphrase={algorithm:"m.pbkdf2",iterations:i.iterations,salt:i.salt},t.pubkey=n.init_with_private_key(i.key)}else t.pubkey=n.generate_key();const i=n.get_private_key();return{keyInfo:t,encodedPrivateKey:(0,I.encodeRecoveryKey)(i),privateKey:i}}finally{n&&n.free()}}))}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),n=!this.backupManager.getKeyBackupEnabled()||(yield this.baseApis.isKeyBackupKeyStored());return!!(e&&t&&n)}))}bootstrapCrossSigning({authUploadDeviceSigningKeys:e,setupNewCrossSigning:t}={}){return a(this,void 0,void 0,(function*(){u.logger.log("Bootstrapping cross-signing");const n=this.baseApis.cryptoCallbacks,i=new m.EncryptionSetupBuilder(this.baseApis.store.accountData,n),r=new y.CrossSigningInfo(this.userId,i.crossSigningCallbacks,i.crossSigningCallbacks),o=()=>a(this,void 0,void 0,(function*(){r.resetKeys(),yield this.signObject(r.keys.master),i.addCrossSigningKeys(e,r.keys);const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=yield r.signDevice(this.userId,t);i.addKeySignature(this.userId,this.deviceId,n),this.backupManager.backupInfo&&(yield r.signObject(this.backupManager.backupInfo.auth_data,"master"),i.addSessionBackup(this.backupManager.backupInfo))})),s=this.crossSigningInfo.getId(),c=yield this.crossSigningInfo.isStoredInKeyCache(),l=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),d=c||l;u.logger.log({setupNewCrossSigning:t,publicKeysOnDevice:s,privateKeysInCache:c,privateKeysInStorage:l,privateKeysExistSomewhere:d}),!d||t?(u.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield o()):s&&c?u.logger.log("Cross-signing public keys trusted and private keys found locally"):l&&(u.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 h=i.crossSigningCallbacks.privateKeys;if(h.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new E.SecretStorage(i.accountDataClientAdapter,i.ssssCryptoCallbacks);(yield e.hasKey())&&(u.logger.log("Storing new cross-signing private keys in secret storage"),yield y.CrossSigningInfo.storeInSecretStorage(h,e))}const g=i.buildOperation();yield g.apply(this),yield i.persist(this),u.logger.log("Cross-signing ready")}))}bootstrapSecretStorage({createSecretStorageKey:e=(()=>a(this,void 0,void 0,(function*(){return{}}))),keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:i,getKeyBackupPassphrase:r}={}){return a(this,void 0,void 0,(function*(){u.logger.log("Bootstrapping Secure Secret Storage");const o=this.baseApis.cryptoCallbacks,s=new m.EncryptionSetupBuilder(this.baseApis.store.accountData,o),c=new E.SecretStorage(s.accountDataClientAdapter,s.ssssCryptoCallbacks);let l=null;const d=(e,t)=>a(this,void 0,void 0,(function*(){t&&(e.key=t);const{keyId:n,keyInfo:i}=yield c.addKey(E.SECRET_STORAGE_ALGORITHM_V1_AES,e);return t&&s.ssssCryptoCallbacks.addPrivateKey(n,i,t),yield c.setDefaultKeyId(n),n})),h=(e,t)=>a(this,void 0,void 0,(function*(){if(!t.mac){const n=yield this.baseApis.cryptoCallbacks.getSecretStorageKey({keys:{[e]:t}},"");if(n){const i=n[1];s.ssssCryptoCallbacks.addPrivateKey(e,t,i);const{iv:r,mac:o}=yield(0,M.calculateKeyCheck)(i);t.iv=r,t.mac=o,yield s.setAccountData(`m.secret_storage.key.${e}`,t)}}})),p=e=>a(this,void 0,void 0,(function*(){if(this.crossSigningInfo.getId()&&(yield this.crossSigningInfo.isStoredInKeyCache("master")))try{u.logger.log("Adding cross-signing signature to key backup"),yield this.crossSigningInfo.signObject(e,"master")}catch(e){u.logger.error("Signing key backup with cross-signing keys failed",e)}else u.logger.warn("Cross-signing keys not available, skipping signature on key backup")})),f=yield this.getSecretStorageKey(),[v,S]=f||[null,null],b=!i&&S&&S.algorithm===E.SECRET_STORAGE_ALGORITHM_V1_AES;if(u.logger.log({keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:i,storageExists:b,oldKeyInfo:S}),b||t)if(!b&&t){u.logger.log("Secret storage does not exist, using key backup key");const e=(yield this.getSessionBackupPrivateKey())||(yield r()),n={};t.auth_data.private_key_salt&&t.auth_data.private_key_iterations&&(n.passphrase={algorithm:"m.pbkdf2",iterations:t.auth_data.private_key_iterations,salt:t.auth_data.private_key_salt,bits:256}),l=yield d(n,e),yield c.store("m.megolm_backup.v1",g.encodeBase64(e),[l]),yield p(t.auth_data),s.addSessionBackup(t)}else u.logger.log("Secret storage exists"),S&&S.algorithm===E.SECRET_STORAGE_ALGORITHM_V1_AES&&(yield h(v,S));else{u.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:t={},privateKey:n}=yield e();l=yield d(t,n)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield this.isCrossSigningReady())&&(l||!(yield this.crossSigningInfo.isStoredInSecretStorage(c)))){u.logger.log("Copying cross-signing private keys from cache to secret storage");const e=yield this.crossSigningInfo.getCrossSigningKeysFromCache();yield y.CrossSigningInfo.storeInSecretStorage(e,c)}if(n&&!t){u.logger.log("Creating new message key backup version");const e=yield this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=(0,I.decodeRecoveryKey)(e.recovery_key);yield c.store("m.megolm_backup.v1",g.encodeBase64(t));const n={algorithm:e.algorithm,auth_data:e.auth_data};yield p(n.auth_data),yield this.signObject(n.auth_data),s.addSessionBackup(n)}const _=yield c.get("m.megolm_backup.v1");if(_){u.logger.info("Got session backup key from secret storage: caching");const e=V(_);e&&(yield c.store("m.megolm_backup.v1",e,[l||v]));const t=new Uint8Array(g.decodeBase64(e||_));s.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=(yield this.getSessionBackupPrivateKey())||(yield r());if(!e)return void u.logger.error("Key backup is enabled but couldn't get key backup key!");u.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 T=s.buildOperation();yield T.apply(this),yield s.persist(this),u.logger.log("Secure Secret Storage ready")}))}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}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,n){let i=null;try{i=new t.Olm.PkDecryption;return i.init_with_private_key(e)===n}finally{i&&i.free()}}getSessionBackupPrivateKey(){return a(this,void 0,void 0,(function*(){let e=yield new Promise((e=>{this.cryptoStore.doTxn("readonly",[b.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(g.decodeBase64(V(e)||e)),yield this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=i.from(this.olmDevice.pickleKey),n=yield(0,M.decryptAES)(e,t,"m.megolm_backup.v1");e=g.decodeBase64(n)}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=i.from(this.olmDevice.pickleKey),n=yield(0,M.encryptAES)(g.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[b.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeSecretStorePrivateKey(e,"m.megolm_backup.v1",n)}))}))}checkCrossSigningPrivateKey(e,n){let i=null;try{i=new t.Olm.PkSigning;return i.init_with_seed(e)===n}finally{i&&i.free()}}afterCrossSigningLocalKeyChange(){return a(this,void 0,void 0,(function*(){u.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);u.logger.info(`Starting background key sig upload for ${this.deviceId}`);const n=({shouldEmit:e=!1})=>this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:t}}).then((t=>{const{failures:i}=t||{};if(Object.keys(i||[]).length>0)throw e&&this.baseApis.emit(F.KeySignatureUploadFailure,i,"afterCrossSigningLocalKeyChange",n),new P.KeySignatureUploadError("Key upload failed",{failures:i});u.logger.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{u.logger.error(`Error during background key sig upload for ${this.deviceId}`,e)}));n({shouldEmit:!0});const i=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(i){u.logger.info("Starting device verification upgrade");const e={};for(const[t,n]of Object.entries(this.deviceList.crossSigningInfo)){const i=yield this.checkForDeviceVerificationUpgrade(t,y.CrossSigningInfo.fromStorage(n,t));i&&(e[t]=i)}if(Object.keys(e).length>0){u.logger.info(`Found ${Object.keys(e).length} verif users to upgrade`);try{const t=yield i({users:e});if(t)for(const n of t)n in e&&(yield this.baseApis.setDeviceVerified(n,e[n].crossSigningInfo.getId()))}catch(e){u.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}u.logger.info("Finished device verification upgrade")}u.logger.info("Finished cross-signing key change post-processing")}))}checkForDeviceVerificationUpgrade(e,t){return a(this,void 0,void 0,(function*(){const n=this.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!n.isVerified()){const n=this.deviceList.getRawStoredDevicesForUser(e),i=yield this.checkForValidDeviceSignature(e,t.keys.master,n);if(i.length)return{devices:i.map((e=>f.DeviceInfo.fromStorage(n[e],e))),crossSigningInfo:t}}}))}checkForValidDeviceSignature(e,t,n){return a(this,void 0,void 0,(function*(){const i=[];if(n&&t.signatures&&t.signatures[e])for(const r of Object.keys(t.signatures[e])){const[,o]=r.split(":",2);if(o in n&&n[o].verified===K.VERIFIED)try{yield g.verifySignature(this.olmDevice,t,e,o,n[o].keys[r]),i.push(o)}catch(e){}}return i}))}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 y.UserTrustLevel(!1,!1,!1)}checkDeviceTrust(e,t){const n=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,n)}checkDeviceInfoTrust(e,t){const n=!(!t||!t.isVerified()),i=this.deviceList.getStoredCrossSigningForUser(e);if(t&&i){const r=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(i,t,n,r)}return new y.DeviceTrustLevel(!1,!1,n,!1)}checkIfOwnDeviceCrossSigned(e){const t=this.deviceList.getStoredDevice(this.userId,e),n=this.deviceList.getStoredCrossSigningForUser(this.userId);return n.checkDeviceTrust(n,t,!1,!0).isCrossSigningVerified()}checkOwnCrossSigningTrust({allowPrivateKeyRequests:e=!1}={}){return a(this,void 0,void 0,(function*(){const t=this.userId;yield this.downloadKeys([this.userId]);const n=yield this.crossSigningInfo.getCrossSigningKeysFromCache(),i=this.deviceList.getStoredCrossSigningForUser(t);if(!i)return void u.logger.error("Got cross-signing update event for user "+t+" but no new cross-signing information found!");const r=i.getId(),o=this.crossSigningInfo.getId()!==r,s=i.getId()&&!n.has("master");if(o&&u.logger.info("Got new master public key",r),e&&(o||s)){u.logger.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("master",r))[1],u.logger.info("Got cross-signing master private key")}finally{e&&e.free()}}const a=this.crossSigningInfo.getId("self_signing"),c=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(i.keys);const l=a!==i.getId("self_signing"),d=c!==i.getId("user_signing"),h=i.getId("self_signing")&&!n.has("self_signing"),g=i.getId("user_signing")&&!n.has("user_signing"),p={};if(l&&u.logger.info("Got new self-signing key",i.getId("self_signing")),e&&(l||h)){u.logger.info("Attempting to retrieve cross-signing self-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("self_signing",i.getId("self_signing")))[1],u.logger.info("Got cross-signing self-signing private key")}finally{e&&e.free()}const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=yield this.crossSigningInfo.signDevice(this.userId,t);p[this.deviceId]=n}if(d&&u.logger.info("Got new user-signing key",i.getId("user_signing")),e&&(d||g)){u.logger.info("Attempting to retrieve cross-signing user-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("user_signing",i.getId("user_signing")))[1],u.logger.info("Got cross-signing user-signing private key")}finally{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 f=Object.keys(p);if(f.length){const e=({shouldEmit:t=!1})=>(u.logger.info(`Starting background key sig upload for ${f}`),this.baseApis.uploadKeySignatures({[this.userId]:p}).then((n=>{const{failures:i}=n||{};if(u.logger.info(`Finished background key sig upload for ${f}`),Object.keys(i||[]).length>0)throw t&&this.baseApis.emit(F.KeySignatureUploadFailure,i,"checkOwnCrossSigningTrust",e),new P.KeySignatureUploadError("Key upload failed",{failures:i})})).catch((e=>{u.logger.error(`Error during background key sig upload for ${f}`,e)})));e({shouldEmit:!0})}this.emit(F.UserTrustStatusChanged,t,this.checkUserTrust(t)),o&&(this.emit(F.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",[b.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(u.logger.info(`Starting device verification upgrade for ${e}`),this.crossSigningInfo.keys.user_signing){const n=this.deviceList.getStoredCrossSigningForUser(e);if(n){const i=yield this.checkForDeviceVerificationUpgrade(e,n);if(i){(yield t({users:{[e]:i}})).includes(e)&&(yield this.baseApis.setDeviceVerified(e,n.getId()))}}}u.logger.info(`Finished device verification upgrade for ${e}`)}}))}setTrustedBackupPubKey(e){return a(this,void 0,void 0,(function*(){this.sessionStore.setLocalTrustedBackupPubKey(e),yield this.backupManager.checkKeyBackup()}))}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(U.RoomMemberEvent.Membership,this.onMembership),e.on(L.ClientEvent.ToDeviceEvent,this.onToDeviceEvent),e.on(x.RoomEvent.Timeline,this.onTimelineEvent),e.on(N.MatrixEventEvent.Decrypted,this.onTimelineEvent)}start(){this.outgoingRoomKeyRequestManager.start()}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}setGlobalErrorOnUnknownDevices(e){this.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){return this.globalErrorOnUnknownDevices}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(),n=Math.floor(t/2),i=e=>a(this,void 0,void 0,(function*(){for(;n>e||this.getNeedsNewFallback();){if(n>e){u.logger.info("generating oneTimeKeys");const t=Math.min(n-e,5);yield this.olmDevice.generateOneTimeKeys(t)}if(this.getNeedsNewFallback()){const e=yield this.olmDevice.getFallbackKey();e.curve25519&&0!=Object.keys(e.curve25519).length||(u.logger.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),yield this.olmDevice.generateFallbackKey())}u.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=>i(e))).catch((e=>{u.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 n=yield this.olmDevice.getFallbackKey();for(const[i,r]of Object.entries(n.curve25519)){const n={key:r,fallback:!0};t["signed_curve25519:"+i]=n,e.push(this.signObject(n))}this.setNeedsNewFallback(!1)}const n=yield this.olmDevice.getOneTimeKeys(),i={};for(const t in n.curve25519)if(n.curve25519.hasOwnProperty(t)){const r={key:n.curve25519[t]};i["signed_curve25519:"+t]=r,e.push(this.signObject(r))}yield Promise.all(e);const r={one_time_keys:i};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,n,i,r){return a(this,void 0,void 0,(function*(){void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null);const o=this.deviceList.getStoredCrossSigningForUser(e);if(o&&o.getId()===t){if(null!==i||null!==r)throw new Error("Cannot set blocked or known for a cross-signing key");if(!n)throw new Error("Cannot set a cross-signing key as unverified");if(this.crossSigningInfo.getId()||e!==this.crossSigningInfo.userId||(this.storeTrustedSelfKeys(o.keys),this.emit(F.UserTrustStatusChanged,this.userId,this.checkUserTrust(e))),e!==this.userId){u.logger.info("Master key "+o.getId()+" for "+e+" marked verified. Signing...");const n=yield this.crossSigningInfo.signUser(o);if(n){const i=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){u.logger.info("Uploading signature for "+e+"...");const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(F.KeySignatureUploadFailure,s,"setDeviceVerification",i),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield i({shouldEmit:!0})}return n}return o}const s=this.deviceList.getRawStoredDevicesForUser(e);if(!s||!s[t])throw new Error("Unknown device "+e+":"+t);const c=s[t];let l=c.verified;n?l=K.VERIFIED:null!==n&&l==K.VERIFIED&&(l=K.UNVERIFIED),i?l=K.BLOCKED:null!==i&&l==K.BLOCKED&&(l=K.UNVERIFIED);let d=c.known;if(null!==r&&(d=r),c.verified===l&&c.known===d||(c.verified=l,c.known=d,this.deviceList.storeDevicesForUser(e,s),this.deviceList.saveIfDirty()),n&&e===this.userId){let n;u.logger.info("Own device "+t+" marked verified: signing");if(this.checkDeviceTrust(e,t).isCrossSigningVerified()?u.logger.log(`Own device ${t} already cross-signing verified`):n=yield this.crossSigningInfo.signDevice(e,f.DeviceInfo.fromStorage(c,t)),n){const i=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){u.logger.info("Uploading signature for "+t);const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(F.KeySignatureUploadFailure,s,"setDeviceVerification",i),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield i({shouldEmit:!0})}}const h=f.DeviceInfo.fromStorage(c,t);return this.emit(F.DeviceVerificationChanged,e,t,h),h}))}findVerificationRequestDMInProgress(e){return this.inRoomVerificationRequests.findRequestInProgress(e)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){const n=this.inRoomVerificationRequests.findRequestInProgress(t);if(n)return Promise.resolve(n);const i=new k.InRoomChannel(this.baseApis,t,e);return this.requestVerificationWithChannel(e,i,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));const n=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(n)return Promise.resolve(n);const i=new O.ToDeviceChannel(this.baseApis,e,t,O.ToDeviceChannel.makeTransactionId());return this.requestVerificationWithChannel(e,i,this.toDeviceVerificationRequests)}requestVerificationWithChannel(e,t,n){return a(this,void 0,void 0,(function*(){let e=new R.VerificationRequest(t,this.verificationMethods,this.baseApis);t.transactionId&&n.setRequestByChannel(t,e),yield e.sendRequest();const i=n.getRequestByChannel(t);return i?e=i:(u.logger.log(`Crypto: adding new request to requestsByTxnId with id ${t.transactionId} ${t.roomId}`),n.setRequestByChannel(t,e)),e}))}beginKeyVerification(e,t,n,i=null){let r;if(i){if(r=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,i),!r)throw new Error(`No request found for user ${t} with transactionId ${i}`)}else{i=O.ToDeviceChannel.makeTransactionId();const e=new O.ToDeviceChannel(this.baseApis,t,[n],i,n);r=new R.VerificationRequest(e,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,i,r)}return r.beginKeyVerification(e,{userId:t,deviceId:n})}legacyDeviceVerification(e,t,n){return a(this,void 0,void 0,(function*(){const i=O.ToDeviceChannel.makeTransactionId(),r=new O.ToDeviceChannel(this.baseApis,e,[t],i,t),o=new R.VerificationRequest(r,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,i,o);const s=o.beginKeyVerification(n,{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)||[],n={};for(let e=0;e<t.length;++e){const i=t[e],r=i.getIdentityKey(),o=yield this.olmDevice.getSessionInfoForDevice(r);n[i.deviceId]={deviceIdKey:r,sessions:o}}return n}))}getEventSenderDeviceInfo(e){const t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n)return null;if(e.getForwardingCurve25519KeyChain().length>0)return null;if(e.isKeySourceUntrusted())return null;const i=this.deviceList.getDeviceByIdentityKey(n,t);if(null===i)return null;const r=e.getClaimedEd25519Key();return r?r!==i.getFingerprint()?(u.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+" but sender device has key "+i.getFingerprint()),null):i:(u.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){const t={};if(t.senderKey=e.getSenderKey(),t.algorithm=e.getWireContent().algorithm,!t.senderKey||!t.algorithm)return t.encrypted=!1,t;t.encrypted=!0;e.getForwardingCurve25519KeyChain().length>0||e.isKeySourceUntrusted()?t.authenticated=!1:t.authenticated=!0,t.sender=this.deviceList.getDeviceByIdentityKey(t.algorithm,t.senderKey);const n=e.getClaimedEd25519Key();return n||(u.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),t.mismatchedSender=!0),t.sender&&n!==t.sender.getFingerprint()&&(u.logger.warn("Event "+e.getId()+" claims ed25519 key "+n+"but sender device has key "+t.sender.getFingerprint()),t.mismatchedSender=!0),t}forceDiscardSession(e){const t=this.roomEncryptors[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");t.forceDiscardSession()}setRoomEncryption(e,t,n){return a(this,void 0,void 0,(function*(){if(!t.algorithm)return void u.logger.log("Ignoring setRoomEncryption with no algorithm");const i=this.roomList.getRoomEncryption(e);if(i&&JSON.stringify(i)!=JSON.stringify(t))return void u.logger.error("Ignoring m.room.encryption event which requests a change of config in "+e);if(this.roomEncryptors[e])return;let r=null;i||(r=this.roomList.setRoomEncryption(e,t));const o=v.ENCRYPTION_CLASSES[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:e,config:t});this.roomEncryptors[e]=s,r&&(yield r),this.lazyLoadMembers?u.logger.log("Enabling encryption in "+e):(u.logger.log("Enabling encryption in "+e+"; starting to track device lists for all users therein"),yield this.trackRoomDevices(e),n||this.deviceList.refreshOutdatedDeviceLists())}))}trackRoomDevices(e){const t=()=>a(this,void 0,void 0,(function*(){if(!this.roomEncryptors[e])return;const t=this.clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);u.logger.log(`Starting to track devices for room ${e} ...`);(yield t.getEncryptionTargetMembers()).forEach((e=>{this.deviceList.startTrackingDeviceList(e.userId)}))}));let n=this.roomDeviceTrackingState[e];return n||(n=t(),this.roomDeviceTrackingState[e]=n.catch((t=>{throw this.roomDeviceTrackingState[e]=null,t}))),n}ensureOlmSessionsForUsers(e,t){const n={};for(let t=0;t<e.length;++t){const i=e[t];n[i]=[];const r=this.getStoredDevicesForUser(i)||[];for(let e=0;e<r.length;++e){const t=r[e];t.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(t.verified!=K.BLOCKED&&n[i].push(t))}}return g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,n,t)}exportRoomKeys(){return a(this,void 0,void 0,(function*(){const e=[];return yield this.cryptoStore.doTxn("readonly",[b.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],(t=>{this.cryptoStore.getAllEndToEndInboundGroupSessions(t,(t=>{if(null===t)return;const n=this.olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId,t.sessionData);delete n.first_known_index,n.algorithm=g.MEGOLM_ALGORITHM,e.push(n)}))})),e}))}importRoomKeys(e,t={}){let n=0,i=0;const r=e.length;function o(){t.progressCallback({stage:"load_keys",successes:n,failures:i,total:r})}return Promise.all(e.map((e=>{if(!e.room_id||!e.algorithm)return u.logger.warn("ignoring room key entry with missing fields",e),i++,t.progressCallback&&o(),null;return this.getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e,t).finally((()=>{n++,t.progressCallback&&o()}))}))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){const t=this.roomEncryptors[e.roomId];t&&t.prepareToEncrypt(e)}encryptEvent(e,t){return a(this,void 0,void 0,(function*(){if(!t)throw new Error("Cannot send encrypted messages in unknown rooms");const n=e.getRoomId(),i=this.roomEncryptors[n];if(!i)throw new Error("Room was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");this.roomDeviceTrackingState[n]||this.trackRoomDevices(n),yield this.roomDeviceTrackingState[n];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 i.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(e.getUnsigned().redacted_because),n=yield this.decryptEvent(t);return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:n.clearEvent}}}}{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,n=!1){return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,n).then((()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()})).catch((e=>{u.logger.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{u.logger.warn("Error clearing pending room key requests",e)}))}cancelAndResendAllOutgoingKeyRequests(){return a(this,void 0,void 0,(function*(){yield this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}))}onCryptoEvent(e){return a(this,void 0,void 0,(function*(){const t=e.getRoomId(),n=e.getContent();try{yield this.setRoomEncryption(t,n,!0)}catch(e){u.logger.error("Error configuring encryption in room "+t+":",e)}}))}onSyncWillProcess(e){return a(this,void 0,void 0,(function*(){e.oldSyncToken||(u.logger.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}))}onSyncCompleted(e){return a(this,void 0,void 0,(function*(){this.deviceList.setSyncToken(e.nextSyncToken),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(e.changed&&Array.isArray(e.changed)&&e.changed.forEach((e=>{this.deviceList.invalidateUserDeviceList(e)})),e.left&&Array.isArray(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 n=yield t.getEncryptionTargetMembers();for(const t of n)e.push(t.userId)}return e}))}getTrackedE2eRooms(){return this.clientStore.getRooms().filter((e=>{if(!this.roomEncryptors[e.roomId])return!1;if(!this.roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t}))}onRoomKeyEvent(e){const t=e.getContent();if(!t.room_id||!t.algorithm)return void u.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 u.logger.error("key withheld event is missing fields");u.logger.info(`Got room key withheld event from ${e.getSender()} (${t.sender_key}) for ${t.algorithm}/${t.room_id}/${t.session_id} with reason ${t.code} (${t.reason})`);const n=this.getRoomDecryptor(t.room_id,t.algorithm);if(n.onRoomKeyWithheldEvent&&n.onRoomKeyWithheldEvent(e),!t.room_id){const e=this.getRoomDecryptors(t.algorithm);for(const n of e)n.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(),n=t&&t.from_device;if(!n)return;const i=e.getSender(),r=new O.ToDeviceChannel(this.baseApis,i,[n]);return new R.VerificationRequest(r,this.verificationMethods,this.baseApis)}))}handleVerificationEvent(e,t,n,i=!0){return a(this,void 0,void 0,(function*(){if(e.isSending()&&e.status!=N.EventStatus.SENT){let t,n;try{yield new Promise(((i,r)=>{t=i,n=()=>{e.status==N.EventStatus.CANCELLED&&r(new Error("Event status set to CANCELLED."))},e.once(N.MatrixEventEvent.LocalEventIdReplaced,t),e.on(N.MatrixEventEvent.Status,n)}))}catch(e){return void u.logger.error("error while waiting for the verification event to be sent: "+e.message)}finally{e.removeListener(N.MatrixEventEvent.LocalEventIdReplaced,t),e.removeListener(N.MatrixEventEvent.Status,n)}}let r=t.getRequest(e),o=!1;if(!r){if(r=n(e),!r)return void u.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,i)}catch(e){u.logger.error("error while handling verification event: "+e.message)}o&&!r.initiatedByMe&&!r.invalid&&!r.observeOnly&&this.baseApis.emit(F.VerificationRequest,r)}))}onToDeviceBadEncrypted(e){return a(this,void 0,void 0,(function*(){const t=e.getWireContent(),n=e.getSender(),i=t.algorithm,r=t.sender_key,o=()=>{const e=this.getRoomDecryptors(g.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(r)};if(void 0===n||void 0===r||void 0===r)return;this.lastNewSessionForced[n]=this.lastNewSessionForced[n]||{};const s=this.lastNewSessionForced[n][r]||0;if(s+36e5>Date.now())return u.logger.debug("New session already forced with device "+n+":"+r+" at "+s+": not forcing another"),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),void o();let a=this.deviceList.getDeviceByIdentityKey(i,r);if(!a&&(yield this.downloadKeys([n],!1),a=this.deviceList.getDeviceByIdentityKey(i,r),!a))return u.logger.info("Couldn't find device for identity key "+r+": not re-establishing session"),yield this.olmDevice.recordSessionProblem(r,"wedged",!1),void o();const c={};c[n]=[a],yield g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,c,!0),this.lastNewSessionForced[n][r]=Date.now();const l={algorithm:g.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};yield g.encryptMessageForDevice(l.ciphertext,this.userId,this.deviceId,this.olmDevice,n,a,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),o(),yield this.baseApis.sendToDevice("m.room.encrypted",{[n]:{[a.deviceId]:l}});const d=yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,a.deviceId);for(const e of d)this.requestRoomKey(e.requestBody,e.recipients,!0)}))}onRoomMembership(e,t,n){const i=t.roomId,r=this.roomEncryptors[i];r&&(this.roomDeviceTrackingState[i]&&("join"==t.membership?(u.logger.log("Join event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&this.clientStore.getRoom(i).shouldEncryptForInvitedMembers()&&(u.logger.log("Invite event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId))),r.onRoomMembership(e,t,n))}onRoomKeyRequestEvent(e){const t=e.getContent();if("request"===t.action){const t=new $(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new G(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){u.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,n=e.deviceId,i=e.requestBody,r=i.room_id,o=i.algorithm;if(u.logger.log(`m.room_key_request from ${t}:${n} for ${r} / ${i.session_id} (id ${e.requestId})`),t!==this.userId){if(!this.roomEncryptors[r])return void u.logger.debug(`room key request for unencrypted room ${r}`);const e=this.roomEncryptors[r],o=this.deviceList.getStoredDevice(t,n);if(!o)return void u.logger.debug(`Ignoring keyshare for unknown device ${t}:${n}`);try{yield e.reshareKeyWithDevice(i.sender_key,i.session_id,t,o)}catch(e){u.logger.warn("Failed to re-share keys for session "+i.session_id+" with device "+t+":"+o.deviceId,e)}return}if(n===this.deviceId)return void u.logger.log("Ignoring room key request from ourselves");if(!this.roomDecryptors[r])return void u.logger.log(`room key request for unencrypted room ${r}`);const s=this.roomDecryptors[r][o];if(s)if(yield s.hasKeysForKeyRequest(e)){if(e.share=()=>{s.shareKeysWithDevice(e)},this.checkDeviceTrust(t,n).isVerified())return u.logger.log("device is already verified: sharing keys"),void e.share();this.emit(F.RoomKeyRequest,e)}else u.logger.log(`room key request for unknown session ${r} / `+i.session_id);else u.logger.log(`room key request for unknown alg ${o} in room ${r}`)}))}processReceivedRoomKeyRequestCancellation(e){return a(this,void 0,void 0,(function*(){u.logger.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit(F.RoomKeyRequestCancellation,e)}))}getRoomDecryptor(e,t){let n,i;if((e=e||null)&&(n=this.roomDecryptors[e],n||(this.roomDecryptors[e]=n={}),i=n[t],i))return i;const r=v.DECRYPTION_CLASSES[t];if(!r)throw new v.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return i=new r({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:e}),n&&(n[t]=i),i}getRoomDecryptors(e){const t=[];for(const n of Object.values(this.roomDecryptors))e in n&&t.push(n[e]);return t}signObject(e){return a(this,void 0,void 0,(function*(){const t=e.signatures||{},n=e.unsigned;delete e.signatures,delete e.unsigned,t[this.userId]=t[this.userId]||{},t[this.userId]["ed25519:"+this.deviceId]=yield this.olmDevice.sign(l.default.stringify(e)),e.signatures=t,void 0!==n&&(e.unsigned=n)}))}}function V(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return g.encodeBase64(t)}n.Crypto=q,n.fixBackupKey=V;class ${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")}}}n.IncomingRoomKeyRequest=$;class G{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)},{"../ReEmitter":81,"../client":84,"../errors":119,"../logger":126,"../models/event":135,"../models/room":140,"../models/room-member":137,"../models/typed-event-emitter":143,"./CrossSigning":87,"./DeviceList":88,"./EncryptionSetup":89,"./OlmDevice":90,"./OutgoingRoomKeyRequestManager":91,"./SecretStorage":93,"./aes":94,"./algorithms":96,"./backup":100,"./dehydration":101,"./deviceinfo":102,"./key_passphrase":104,"./olmlib":105,"./recoverykey":106,"./store/indexeddb-crypto-store":108,"./verification/IllegalMethod":113,"./verification/QRCode":114,"./verification/SAS":115,"./verification/request/InRoomChannel":116,"./verification/request/ToDeviceChannel":117,"./verification/request/VerificationRequest":118,"another-json":14,buffer:20}],104:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.deriveKey=n.keyFromPassphrase=n.keyFromAuthData=void 0;const o=e("../randomstring"),s=e("../utils"),a="undefined"!=typeof window&&window.crypto?window.crypto.subtle||window.crypto.webkitSubtle:null,c=5e5;function l(e,n,o,c=256){return r(this,void 0,void 0,(function*(){return a?function(e,n,i,o){return r(this,void 0,void 0,(function*(){const r=t.crypto.subtle,s=t.TextEncoder;if(!r||!s)throw new Error("Password-based backup is not avaiable on this platform");const a=yield r.importKey("raw",(new s).encode(e),{name:"PBKDF2"},!1,["deriveBits"]),c=yield r.deriveBits({name:"PBKDF2",salt:(new s).encode(n),iterations:i,hash:"SHA-512"},a,o);return new Uint8Array(c)}))}(e,n,o,c):function(e,t,n,o){return r(this,void 0,void 0,(function*(){const r=(0,s.getCrypto)();if(!r)throw new Error("No usable crypto implementation");return r.pbkdf2Sync(e,i.from(t,"binary"),n,o,"sha512")}))}(e,n,o,c)}))}n.keyFromAuthData=function(e,n){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 l(n,e.private_key_salt,e.private_key_iterations,e.private_key_bits||256)},n.keyFromPassphrase=function(e){return r(this,void 0,void 0,(function*(){if(!t.Olm)throw new Error("Olm is not available");const n=(0,o.randomString)(32);return{key:yield l(e,n,c,256),salt:n,iterations:c}}))},n.deriveKey=l}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../randomstring":146,"../utils":159,buffer:20}],105:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.decodeBase64=n.encodeUnpaddedBase64=n.encodeBase64=n.pkVerify=n.pkSign=n.verifySignature=n.ensureOlmSessionsForDevices=n.getExistingOlmSessions=n.encryptMessageForDevice=n.MEGOLM_BACKUP_ALGORITHM=n.MEGOLM_ALGORITHM=n.OLM_ALGORITHM=void 0;const s=o(e("another-json")),a=e("../logger");var c;function l(e,t,n,i){return r(this,void 0,void 0,(function*(){const r=i.deviceId;try{yield d(e,t,n,r,i.getFingerprint())}catch(e){return a.logger.error("Unable to verify signature on one-time key for device "+n+":"+r+":",e),null}let o;try{o=yield e.createOutboundSession(i.getIdentityKey(),t.key)}catch(e){return a.logger.error("Error starting olm session with device "+n+":"+r+": "+e),null}return a.logger.log("Started new olm sessionid "+o+" for device "+n+":"+r),o}))}function d(e,t,n,i,o){return r(this,void 0,void 0,(function*(){const r="ed25519:"+i,a=((t.signatures||{})[n]||{})[r];if(!a)throw Error("No signature");const c=Object.assign({},t);"unsigned"in c&&delete c.unsigned,delete c.signatures;const l=s.default.stringify(c);e.verifySignature(o,l,a)}))}function u(e){return i.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"}(c||(c={})),n.OLM_ALGORITHM=c.Olm,n.MEGOLM_ALGORITHM=c.Megolm,n.MEGOLM_BACKUP_ALGORITHM=c.MegolmBackup,n.encryptMessageForDevice=function(e,t,n,i,o,s,c){return r(this,void 0,void 0,(function*(){const r=s.getIdentityKey(),l=yield i.getSessionIdForDevice(r);if(null===l)return;a.logger.log("Using sessionid "+l+" for device "+o+":"+s.deviceId);const d={sender:t,sender_device:n,keys:{ed25519:i.deviceEd25519Key},recipient:o,recipient_keys:{ed25519:s.getFingerprint()}};Object.assign(d,c),e[r]=yield i.encryptMessage(r,l,JSON.stringify(d))}))},n.getExistingOlmSessions=function(e,t,n){return r(this,void 0,void 0,(function*(){const t={},i={},o=[];for(const[s,a]of Object.entries(n))for(const n of a){const a=n.deviceId,c=n.getIdentityKey();o.push((()=>r(this,void 0,void 0,(function*(){const r=yield e.getSessionIdForDevice(c,!0);null===r?(t[s]=t[s]||[],t[s].push(n)):(i[s]=i[s]||{},i[s][a]={device:n,sessionId:r})})))())}return yield Promise.all(o),[t,i]}))},n.ensureOlmSessionsForDevices=function(e,t,n,i=!1,o,s,c=a.logger){return r(this,void 0,void 0,(function*(){"number"==typeof i&&(c=s,s=o,o=i,i=!1);const r=[],a={},d={};for(const[,t]of Object.entries(n))for(const n of t){const t=n.getIdentityKey();t!==e.deviceCurve25519Key&&(e.sessionsInProgress[t]||(e.sessionsInProgress[t]=new Promise((n=>{d[t]=i=>{delete e.sessionsInProgress[t],n(i)}}))))}for(const[t,o]of Object.entries(n)){a[t]={};for(const n of o){const o=n.deviceId,s=n.getIdentityKey();if(s===e.deviceCurve25519Key){c.info("Attempted to start session with ourself! Ignoring"),a[t][o]={device:n,sessionId:null};continue}const l=`for ${s} (${t}:${o})`,u=yield e.getSessionIdForDevice(s,!!d[s],c);null!==u&&d[s]&&d[s](),(null===u||i)&&(i?c.info(`Forcing new Olm session ${l}`):c.info(`Making new Olm session ${l}`),r.push([t,o])),a[t][o]={device:n,sessionId:u}}}if(0===r.length)return a;const u="signed_curve25519";let h,g=`one-time keys for ${r.length} devices`;try{c.debug(`Claiming ${g}`),h=yield t.claimOneTimeKeys(r,u,o),c.debug(`Claimed ${g}`)}catch(e){for(const e of Object.values(d))e();throw c.log(`Failed to claim ${g}`,e,r),e}s&&"failures"in h&&s.push(...Object.keys(h.failures));const p=h.one_time_keys||{},f=[];for(const[t,r]of Object.entries(n)){const n=p[t]||{};for(let o=0;o<r.length;o++){const s=r[o],u=s.deviceId,h=s.getIdentityKey();if(h===e.deviceCurve25519Key)continue;if(a[t][u].sessionId&&!i)continue;const g=n[u]||{};let p=null;for(const e in g)0===e.indexOf("signed_curve25519:")&&(p=g[e]);p?f.push(l(e,p,t,s).then((e=>{d[h]&&d[h](e),a[t][u].sessionId=e}),(e=>{throw d[h]&&d[h](),e}))):(c.warn(`No one-time keys (alg=signed_curve25519) for device ${t}:${u}`),d[h]&&d[h]())}}return g=`Olm sessions for ${f.length} devices`,c.debug(`Starting ${g}`),yield Promise.all(f),c.debug(`Started ${g}`),a}))},n.verifySignature=d,n.pkSign=function(e,n,i,r){let o=!1;if(n instanceof Uint8Array){const e=new t.Olm.PkSigning;r=e.init_with_seed(n),n=e,o=!0}const a=e.signatures||{};delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{const t=a[i]||{};return a[i]=t,t["ed25519:"+r]=n.sign(s.default.stringify(e))}finally{e.signatures=a,c&&(e.unsigned=c),o&&n.free()}},n.pkVerify=function(e,n,i){const r="ed25519:"+n;if(!(e.signatures&&e.signatures[i]&&e.signatures[i][r]))throw new Error("No signature");const o=e.signatures[i][r],a=new t.Olm.Utility,c=e.signatures;delete e.signatures;const l=e.unsigned;e.unsigned&&delete e.unsigned;try{a.ed25519_verify(n,s.default.stringify(e),o)}finally{e.signatures=c,l&&(e.unsigned=l),a.free()}},n.encodeBase64=u,n.encodeUnpaddedBase64=function(e){return u(e).replace(/=+$/g,"")},n.decodeBase64=function(e){return i.from(e,"base64")}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../logger":126,"another-json":14,buffer:20}],106:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.decodeRecoveryKey=n.encodeRecoveryKey=void 0;const a=s(e("bs58")),c=[139,1];n.encodeRecoveryKey=function(e){const t=i.alloc(c.length+e.length+1);t.set(c,0),t.set(e,c.length);let n=0;for(let e=0;e<t.length-1;++e)n^=t[e];return t[t.length-1]=n,a.encode(t).match(/.{1,4}/g).join(" ")},n.decodeRecoveryKey=function(e){const n=a.decode(e.replace(/ /g,""));let i=0;for(const e of n)i^=e;if(0!==i)throw new Error("Incorrect parity");for(let e=0;e<c.length;++e)if(n[e]!==c[e])throw new Error("Incorrect prefix");if(n.length!==c.length+t.Olm.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");return Uint8Array.from(n.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:19,buffer:20}],107:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.upgradeDatabase=n.Backend=n.VERSION=void 0;const a=e("../../logger"),c=o(e("../../utils"));n.VERSION=10;function l(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function d(e){return new Promise(((t,n)=>{e.oncomplete=()=>{void 0!==e._mx_abortexception&&n(e._mx_abortexception),t(null)},e.onerror=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),n(e.error))},e.onabort=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),n(e.error))}}))}n.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(((n,i)=>{const r=this.db.transaction("outgoingRoomKeyRequests","readwrite");r.onerror=i,this._getOutgoingRoomKeyRequest(r,t,(i=>{if(i)return a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),void n(i);a.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),r.oncomplete=()=>{n(e)};r.objectStore("outgoingRoomKeyRequests").add(e)}))}))}getOutgoingRoomKeyRequest(e){return new Promise(((t,n)=>{const i=this.db.transaction("outgoingRoomKeyRequests","readonly");i.onerror=n,this._getOutgoingRoomKeyRequest(i,e,(e=>{t(e)}))}))}_getOutgoingRoomKeyRequest(e,t,n){const i=e.objectStore("outgoingRoomKeyRequests").index("session").openCursor([t.room_id,t.session_id]);i.onsuccess=()=>{const e=i.result;if(!e)return void n(null);const r=e.value;c.deepCompare(r.requestBody,t)?n(r):e.continue()}}getOutgoingRoomKeyRequestByState(e){if(0===e.length)return Promise.resolve(null);let t,n=0;const i=this.db.transaction("outgoingRoomKeyRequests","readonly"),r=i.objectStore("outgoingRoomKeyRequests"),o=e[n];return r.index("state").openCursor(o).onsuccess=function i(){const r=this.result;if(r)return void(t=r.value);if(n++,n>=e.length)return;const o=e[n];this.source.openCursor(o).onsuccess=i},d(i).then((()=>t))}getAllOutgoingRoomKeyRequestsByState(e){return new Promise(((t,n)=>{const i=this.db.transaction("outgoingRoomKeyRequests","readonly").objectStore("outgoingRoomKeyRequests").index("state").getAll(e);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)}))}getOutgoingRoomKeyRequestsByTarget(e,t,n){let i=0;const r=[];const o=this.db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),a=n[i];return s.index("state").openCursor(a).onsuccess=function o(){const s=this.result;if(s){const n=s.value;n.recipients.includes({userId:e,deviceId:t})&&r.push(n),s.continue()}else{if(i++,i>=n.length)return;const e=n[i];this.source.openCursor(e).onsuccess=o}},d(o).then((()=>r))}updateOutgoingRoomKeyRequest(e,t,n){let i=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,n),e.update(r),i=r):a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${r.state}`)},d(r).then((()=>i))}deleteOutgoingRoomKeyRequest(e,t){const n=this.db.transaction("outgoingRoomKeyRequests","readwrite"),i=n.objectStore("outgoingRoomKeyRequests").openCursor(e);return i.onsuccess=()=>{const e=i.result;if(!e)return;const n=e.value;n.state==t?e.delete():a.logger.warn(`Cannot delete room key request in state ${n.state} (expected ${t})`)},d(n)}getAccount(e,t){const n=e.objectStore("account").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const n=e.objectStore("account").get("crossSigningKeys");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}getSecretStorePrivateKey(e,t,n){const i=e.objectStore("account").get(`ssss_cache:${n}`);i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}storeCrossSigningKeys(e,t){e.objectStore("account").put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,n){e.objectStore("account").put(n,`ssss_cache:${t}`)}countEndToEndSessions(e,t){const n=e.objectStore("sessions").count();n.onsuccess=function(){try{t(n.result)}catch(t){l(e,t)}}}getEndToEndSessions(e,t,n){const i=t.objectStore("sessions").index("deviceKey").openCursor(e),r={};i.onsuccess=function(){const e=i.result;if(e)r[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{n(r)}catch(e){l(t,e)}}}getEndToEndSession(e,t,n,i){const r=n.objectStore("sessions").get([e,t]);r.onsuccess=function(){try{r.result?i({session:r.result.session,lastReceivedMessageTs:r.result.lastReceivedMessageTs}):i(null)}catch(e){l(n,e)}}}getAllEndToEndSessions(e,t){const n=e.objectStore("sessions").openCursor();n.onsuccess=function(){try{const e=n.result;e?(t(e.value),e.continue()):t(null)}catch(t){l(e,t)}}}storeEndToEndSession(e,t,n,i){i.objectStore("sessions").put({deviceKey:e,sessionId:t,session:n.session,lastReceivedMessageTs:n.lastReceivedMessageTs})}storeEndToEndSessionProblem(e,t,n){return s(this,void 0,void 0,(function*(){const i=this.db.transaction("session_problems","readwrite");return i.objectStore("session_problems").put({deviceKey:e,type:t,fixed:n,time:Date.now()}),d(i)}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){let n;const i=this.db.transaction("session_problems","readwrite"),r=i.objectStore("session_problems").index("deviceKey").getAll(e);return r.onsuccess=()=>{const e=r.result;if(!e.length)return void(n=null);e.sort(((e,t)=>e.time-t.time));const i=e[e.length-1];for(const r of e)if(r.time>t)return void(n=Object.assign({},r,{fixed:i.fixed}));n=i.fixed?null:i},yield d(i),n}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),n=[];return yield Promise.all(e.map((e=>new Promise((i=>{const{userId:r,deviceInfo:o}=e,s=t.get([r,o.deviceId]);s.onsuccess=function(){s.result||(t.put({userId:r,deviceId:o.deviceId}),n.push(e)),i()}}))))),n}))}getEndToEndInboundGroupSession(e,t,n,i){let r=!1,o=!1;const s=n.objectStore("inbound_group_sessions").get([e,t]);s.onsuccess=function(){try{r=s.result?s.result.session:null,!1!==o&&i(r,o)}catch(e){l(n,e)}};const a=n.objectStore("inbound_group_sessions_withheld").get([e,t]);a.onsuccess=function(){try{o=a.result?a.result.session:null,!1!==r&&i(r,o)}catch(e){l(n,e)}}}getAllEndToEndInboundGroupSessions(e,t){const n=e.objectStore("inbound_group_sessions").openCursor();n.onsuccess=function(){const i=n.result;if(i){try{t({senderKey:i.value.senderCurve25519Key,sessionId:i.value.sessionId,sessionData:i.value.session})}catch(t){l(e,t)}i.continue()}else try{t(null)}catch(t){l(e,t)}}}addEndToEndInboundGroupSession(e,t,n,i){const r=i.objectStore("inbound_group_sessions").add({senderCurve25519Key:e,sessionId:t,session:n});r.onerror=n=>{"ConstraintError"===r.error.name?(n.stopPropagation(),n.preventDefault(),a.logger.log("Ignoring duplicate inbound group session: "+e+" / "+t)):l(i,new Error("Failed to add inbound group session: "+r.error))}}storeEndToEndInboundGroupSession(e,t,n,i){i.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:n})}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){i.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:e,sessionId:t,session:n})}getEndToEndDeviceData(e,t){const n=e.objectStore("device_data").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeEndToEndDeviceData(e,t){t.objectStore("device_data").put(e,"-")}storeEndToEndRoom(e,t,n){n.objectStore("rooms").put(t,e)}getEndToEndRooms(e,t){const n={},i=e.objectStore("rooms").openCursor();i.onsuccess=function(){const r=i.result;if(r)n[r.key]=r.value,r.continue();else try{t(n)}catch(t){l(e,t)}}}getSessionsNeedingBackup(e){return new Promise(((t,n)=>{const i=[],r=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");r.onerror=n,r.oncomplete=function(){t(i)};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 n=s.get(t.key);n.onsuccess=function(){i.push({senderKey:n.result.senderCurve25519Key,sessionId:n.result.sessionId,sessionData:n.result.session})},(!e||i.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,n)=>{const i=t.count();i.onerror=n,i.onsuccess=()=>e(i.result)}))}unmarkSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,i)=>{const r=n.delete([e.senderKey,e.sessionId]);r.onsuccess=t,r.onerror=i})))))}))}markSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,i)=>{const r=n.put({senderCurve25519Key:e.senderKey,sessionId:e.sessionId});r.onsuccess=t,r.onerror=i})))))}))}addSharedHistoryInboundGroupSession(e,t,n,i){i||(i=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));const r=i.objectStore("shared_history_inbound_group_sessions"),o=r.get([e]);o.onsuccess=()=>{const{sessions:i}=o.result||{sessions:[]};i.push([t,n]),r.put({roomId:e,sessions:i})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));const n=t.objectStore("shared_history_inbound_group_sessions").get([e]);return new Promise(((e,t)=>{n.onsuccess=()=>{const{sessions:t}=n.result||{sessions:[]};e(t)},n.onerror=t}))}doTxn(e,t,n,i=a.logger){const r=this.db.transaction(t,e),o=d(r),s=n(r);return o.then((()=>s))}},n.upgradeDatabase=function(e,t){if(a.logger.log(`Upgrading IndexedDBCryptoStore from version ${t} to ${n.VERSION}`),t<1&&function(e){const t=e.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});t.createIndex("session",["requestBody.room_id","requestBody.session_id"]),t.createIndex("state","state")}(e),t<2&&e.createObjectStore("account"),t<3){e.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")}if(t<4&&e.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]}),t<5&&e.createObjectStore("device_data"),t<6&&e.createObjectStore("rooms"),t<7&&e.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]}),t<8&&e.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]}),t<9){e.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),e.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})}t<10&&e.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})}},{"../../logger":126,"../../utils":159}],108:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.IndexedDBCryptoStore=void 0;const s=e("../../logger"),a=e("./localStorage-crypto-store"),c=e("./memory-crypto-store"),l=o(e("./indexeddb-crypto-store-backend")),d=e("../../errors"),u=o(e("../../indexeddb-helpers"));class h{constructor(e,t){this.indexedDB=e,this.dbName=t,this.backendPromise=null,this.backend=null}static exists(e,t){return u.exists(e,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 n=this.indexedDB.open(this.dbName,l.VERSION);n.onupgradeneeded=e=>{const t=n.result,i=e.oldVersion;l.upgradeDatabase(t,i)},n.onblocked=()=>{s.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{s.logger.log("Error connecting to indexeddb",e),t(n.error)},n.onsuccess=()=>{const t=n.result;s.logger.log(`connected to indexeddb ${this.dbName}`),e(new l.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 d.InvalidCryptoStoreError(d.InvalidCryptoStoreError.TOO_NEW);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 n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{s.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{s.logger.log("Error deleting data from indexeddb",e),t(n.error)},n.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,n){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,n)}updateOutgoingRoomKeyRequest(e,t,n){return this.backend.updateOutgoingRoomKeyRequest(e,t,n)}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,n){this.backend.getSecretStorePrivateKey(e,t,n)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,n){this.backend.storeSecretStorePrivateKey(e,t,n)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,n,i){this.backend.getEndToEndSession(e,t,n,i)}getEndToEndSessions(e,t,n){this.backend.getEndToEndSessions(e,t,n)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,n,i){this.backend.storeEndToEndSession(e,t,n,i)}storeEndToEndSessionProblem(e,t,n){return this.backend.storeEndToEndSessionProblem(e,t,n)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}getEndToEndInboundGroupSession(e,t,n,i){this.backend.getEndToEndInboundGroupSession(e,t,n,i)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,n,i){this.backend.addEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){this.backend.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,n,i)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,n){this.backend.storeEndToEndRoom(e,t,n)}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,n,i){this.backend.addSharedHistoryInboundGroupSession(e,t,n,i)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}doTxn(e,t,n,i){return this.backend.doTxn(e,t,n,i)}}n.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_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":119,"../../indexeddb-helpers":124,"../../logger":126,"./indexeddb-crypto-store-backend":107,"./localStorage-crypto-store":109,"./memory-crypto-store":110}],109:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.LocalStorageCryptoStore=void 0;const r=e("../../logger"),o=e("./memory-crypto-store"),s="crypto.",a="crypto.account",c="crypto.cross_signing_keys",l="crypto.notified_error_devices",d="crypto.device_data",u="crypto.inboundgroupsessions/",h="crypto.sessionsneedingbackup";function g(e){return"crypto.sessions/"+e}function p(e){return"crypto.session.problems/"+e}function f(e,t){return u+e+"/"+t}function v(e,t){return"crypto.inboundgroupsessions.withheld/"+e+"/"+t}function y(e){return"crypto.rooms/"+e}class m extends o.MemoryCryptoStore{constructor(e){super(),this.store=e}static exists(e){const t=e.length;for(let n=0;n<t;n++)if(e.key(n).startsWith(s))return!0;return!1}countEndToEndSessions(e,t){let n=0;for(let e=0;e<this.store.length;++e)this.store.key(e).startsWith(g(""))&&++n;t(n)}_getEndToEndSessions(e){const t=E(this.store,g(e)),n={};for(const[e,i]of Object.entries(t||{}))n[e]="string"==typeof i?{session:i}:i;return n}getEndToEndSession(e,t,n,i){i(this._getEndToEndSessions(e)[t]||{})}getEndToEndSessions(e,t,n){n(this._getEndToEndSessions(e)||{})}getAllEndToEndSessions(e,t){for(let e=0;e<this.store.length;++e)if(this.store.key(e).startsWith(g(""))){const n=this.store.key(e).split("/")[1];for(const e of Object.values(this._getEndToEndSessions(n)))t(e)}}storeEndToEndSession(e,t,n,i){const r=this._getEndToEndSessions(e)||{};r[t]=n,S(this.store,g(e),r)}storeEndToEndSessionProblem(e,t,n){return i(this,void 0,void 0,(function*(){const i=p(e),r=E(this.store,i)||[];r.push({type:t,fixed:n,time:Date.now()}),r.sort(((e,t)=>e.time-t.time)),S(this.store,i,r)}))}getEndToEndSessionProblem(e,t){return i(this,void 0,void 0,(function*(){const n=p(e),i=E(this.store,n)||[];if(!i.length)return null;const r=i[i.length-1];for(const e of i)if(e.time>t)return Object.assign({},e,{fixed:r.fixed});return r.fixed?null:r}))}filterOutNotifiedErrorDevices(e){return i(this,void 0,void 0,(function*(){const t=E(this.store,l)||{},n=[];for(const i of e){const{userId:e,deviceInfo:r}=i;e in t?r.deviceId in t[e]||(n.push(i),t[e][r.deviceId]=!0):(n.push(i),t[e]={[r.deviceId]:!0})}return S(this.store,l,t),n}))}getEndToEndInboundGroupSession(e,t,n,i){i(E(this.store,f(e,t)),E(this.store,v(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(let e=0;e<this.store.length;++e){const n=this.store.key(e);n.startsWith(u)&&t({senderKey:n.slice(u.length,u.length+43),sessionId:n.slice(u.length+44),sessionData:E(this.store,n)})}t(null)}addEndToEndInboundGroupSession(e,t,n,i){E(this.store,f(e,t))||this.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){S(this.store,f(e,t),n)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){S(this.store,v(e,t),n)}getEndToEndDeviceData(e,t){t(E(this.store,d))}storeEndToEndDeviceData(e,t){S(this.store,d,e)}storeEndToEndRoom(e,t,n){S(this.store,y(e),t)}getEndToEndRooms(e,t){const n={},i=y("");for(let e=0;e<this.store.length;++e){const t=this.store.key(e);if(t.startsWith(i)){n[t.slice(i.length)]=E(this.store,t)}}t(n)}getSessionsNeedingBackup(e){const t=E(this.store,h)||{},n=[];for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const t=i.slice(0,43),r=i.slice(44);if(this.getEndToEndInboundGroupSession(t,r,null,(e=>{n.push({senderKey:t,sessionId:r,sessionData:e})})),e&&n.length>=e)break}return Promise.resolve(n)}countSessionsNeedingBackup(){const e=E(this.store,h)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=E(this.store,h)||{};for(const n of e)delete t[n.senderKey+"/"+n.sessionId];return S(this.store,h,t),Promise.resolve()}markSessionsNeedingBackup(e){const t=E(this.store,h)||{};for(const n of e)t[n.senderKey+"/"+n.sessionId]=!0;return S(this.store,h,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(a),Promise.resolve()}getAccount(e,t){t(E(this.store,a))}storeAccount(e,t){S(this.store,a,t)}getCrossSigningKeys(e,t){t(E(this.store,c))}getSecretStorePrivateKey(e,t,n){t(E(this.store,`crypto.ssss_cache.${n}`))}storeCrossSigningKeys(e,t){S(this.store,c,t)}storeSecretStorePrivateKey(e,t,n){S(this.store,`crypto.ssss_cache.${t}`,n)}doTxn(e,t,n){return Promise.resolve(n(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.stack||e),r.logger.log(e.stack)}return null}function S(e,t,n){e.setItem(t,JSON.stringify(n))}n.LocalStorageCryptoStore=m},{"../../logger":126,"./memory-crypto-store":110}],110:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.MemoryCryptoStore=void 0;const a=e("../../logger"),c=o(e("../../utils"));n.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={}}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 n=this._getOutgoingRoomKeyRequest(t);return n?(a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),n):(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 n of e)if(t.state===n)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter((t=>t.state==e)))}getOutgoingRoomKeyRequestsByTarget(e,t,n){const i=[];for(const r of this.outgoingRoomKeyRequests)for(const o of n)r.state===o&&r.recipients.includes({userId:e,deviceId:t})&&i.push(r);return Promise.resolve(i)}updateOutgoingRoomKeyRequest(e,t,n){for(const i of this.outgoingRoomKeyRequests)if(i.requestId===e)return i.state!==t?(a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${i.state}`),Promise.resolve(null)):(Object.assign(i,n),Promise.resolve(i));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(let n=0;n<this.outgoingRoomKeyRequests.length;n++){const i=this.outgoingRoomKeyRequests[n];if(i.requestId===e)return i.state!=t?(a.logger.warn(`Cannot delete room key request in state ${i.state} (expected ${t})`),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(n,1),Promise.resolve(i))}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,n){t(this.privateKeys[n]||null)}storeCrossSigningKeys(e,t){this.crossSigningKeys=t}storeSecretStorePrivateKey(e,t,n){this.privateKeys[t]=n}countEndToEndSessions(e,t){t(Object.keys(this.sessions).length)}getEndToEndSession(e,t,n,i){i((this.sessions[e]||{})[t]||null)}getEndToEndSessions(e,t,n){n(this.sessions[e]||{})}getAllEndToEndSessions(e,t){Object.entries(this.sessions).forEach((([e,n])=>{Object.entries(n).forEach((([n,i])=>{t(Object.assign(Object.assign({},i),{deviceKey:e,sessionId:n}))}))}))}storeEndToEndSession(e,t,n,i){let r=this.sessions[e];void 0===r&&(r={},this.sessions[e]=r),r[t]=n}storeEndToEndSessionProblem(e,t,n){return s(this,void 0,void 0,(function*(){const i=this.sessionProblems[e]=this.sessionProblems[e]||[];i.push({type:t,fixed:n,time:Date.now()}),i.sort(((e,t)=>e.time-t.time))}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){const n=this.sessionProblems[e]||[];if(!n.length)return null;const i=n[n.length-1];for(const e of n)if(e.time>t)return Object.assign({},e,{fixed:i.fixed});return i.fixed?null:i}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.notifiedErrorDevices,n=[];for(const i of e){const{userId:e,deviceInfo:r}=i;e in t?r.deviceId in t[e]||(n.push(i),t[e][r.deviceId]=!0):(n.push(i),t[e]={[r.deviceId]:!0})}return n}))}getEndToEndInboundGroupSession(e,t,n,i){const r=e+"/"+t;i(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,n,i){const r=e+"/"+t;void 0===this.inboundGroupSessions[r]&&(this.inboundGroupSessions[r]=n)}storeEndToEndInboundGroupSession(e,t,n,i){this.inboundGroupSessions[e+"/"+t]=n}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){const r=e+"/"+t;this.inboundGroupSessionsWithheld[r]=n}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,n){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){const t=[];for(const n in this.sessionsNeedingBackup)if(this.inboundGroupSessions[n]&&(t.push({senderKey:n.slice(0,43),sessionId:n.slice(44),sessionData:this.inboundGroupSessions[n]}),e&&n.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,n){const i=this.sharedHistoryInboundGroupSessions[e]||[];i.push([t,n]),this.sharedHistoryInboundGroupSessions[e]=i}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}doTxn(e,t,n){return Promise.resolve(n(null))}}},{"../../logger":126,"../../utils":159}],111:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.VerificationBase=n.VerificationEvent=n.SwitchStartEventError=void 0;const r=e("../../models/event"),o=e("../../logger"),s=e("../deviceinfo"),a=e("./Error"),c=e("../CrossSigning"),l=e("../../models/typed-event-emitter"),d=new Error("Verification timed out");class u extends Error{constructor(e){super(),this.startEvent=e}}var h;n.SwitchStartEventError=u,function(e){e.Cancel="cancel"}(h=n.VerificationEvent||(n.VerificationEvent={}));class g extends l.TypedEventEmitter{constructor(e,t,n,i,r,o){super(),this.channel=e,this.baseApis=t,this.userId=n,this.deviceId=i,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(){o.logger.info("Refreshing/starting the verification transaction timeout timer"),null!==this.transactionTimeoutTimer&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout((()=>{this._done||this.cancelled||(o.logger.info("Triggering verification timeout"),this.cancel(d))}),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(o.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const t=this.rejectEvent;this.rejectEvent=void 0,t(new u(e))}else this.startEvent=e}handleEvent(e){if(!this._done)if(e.getType()===this.expectedEvent)"m.key.verification.done"!==this.expectedEvent&&(this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),this.resolveEvent(e));else if("m.key.verification.cancel"===e.getType()){const t=this.reject;if(this.reject=void 0,t){const n=e.getContent(),{reason:i,code:r}=n;t(new Error(`Other side cancelled verification because ${i} (${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(){if(this.endTimer(),!this._done)return this.request.onVerifierFinished(),this.resolve(),(0,c.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===d){const e=(0,a.newTimeoutError)();this.send(e.getType(),e.getContent())}else if(e instanceof r.MatrixEvent){if(e.getSender()!==this.userId){const t=e.getContent();"m.key.verification.cancel"===e.getType()?(t.code=t.code||"m.unknown",t.reason=t.reason||t.body||"Unknown reason",this.send("m.key.verification.cancel",t)):this.send("m.key.verification.cancel",{code:"m.unknown",reason:t.body||"Unknown reason"})}}else this.send("m.key.verification.cancel",{code:"m.unknown",reason:e.toString()});null!==this.promise?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(h.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(),Promise.resolve(this.doVerification()).then(this.done.bind(this),this.cancel.bind(this)))),this.promise}verifyKeys(e,t,n){return i(this,void 0,void 0,(function*(){const i=[];for(const[r,a]of Object.entries(t)){const t=r.split(":",2)[1],c=this.baseApis.getStoredDevice(e,t);if(c)n(r,c,a),i.push(t);else{const c=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);c&&c.getId()===t?(n(r,s.DeviceInfo.fromStorage({keys:{[r]:t}},t),a),i.push(t)):o.logger.warn(`verification: Could not find device ${t} to verify`)}}if(!i.length)throw new Error("No devices could be verified");o.logger.info("Verification completed! Marking devices verified: ",i);for(const t of i)yield this.baseApis.setDeviceVerified(e,t)}))}get events(){}}n.VerificationBase=g},{"../../logger":126,"../../models/event":135,"../../models/typed-event-emitter":143,"../CrossSigning":87,"../deviceinfo":102,"./Error":112}],112:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.errorFromEvent=n.newInvalidMessageError=n.newUserMismatchError=n.newKeyMismatchError=n.newUnexpectedMessageError=n.newUnknownMethodError=n.newUnknownTransactionError=n.newTimeoutError=n.newUserCancelledError=n.errorFactory=n.newVerificationError=void 0;const i=e("../../models/event");function r(e,t,n){const r=Object.assign({},{code:e,reason:t},n);return new i.MatrixEvent({type:"m.key.verification.cancel",content:r})}function o(e,t){return function(n){return r(e,t,n)}}n.newVerificationError=r,n.errorFactory=o,n.newUserCancelledError=o("m.user","Cancelled by user"),n.newTimeoutError=o("m.timeout","Timed out"),n.newUnknownTransactionError=o("m.unknown_transaction","Unknown transaction"),n.newUnknownMethodError=o("m.unknown_method","Unknown method"),n.newUnexpectedMessageError=o("m.unexpected_message","Unexpected message"),n.newKeyMismatchError=o("m.key_mismatch","Key mismatch"),n.newUserMismatchError=o("m.user_error","User mismatch"),n.newInvalidMessageError=o("m.invalid_message","Invalid message"),n.errorFromEvent=function(e){const t=e.getContent();if(t){const{code:e,reason:n}=t;return{code:e,reason:n}}return{code:"Unknown error",reason:"m.unknown"}}},{"../../models/event":135}],113:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.IllegalMethod=void 0;const r=e("./Base");class o extends r.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>i(this,void 0,void 0,(function*(){throw new Error("Verification is not possible with this method")}))}static factory(e,t,n,i,r,s){return new o(e,t,n,i,r,s)}static get NAME(){return"org.matrix.illegal_method"}}n.IllegalMethod=o},{"./Base":111}],114:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.QRCodeData=n.ReciprocateQRCode=n.QrCodeEvent=n.SCAN_QR_CODE_METHOD=n.SHOW_QR_CODE_METHOD=void 0;const o=e("./Base"),s=e("./Error"),a=e("../olmlib"),c=e("../../logger");var l;n.SHOW_QR_CODE_METHOD="m.qr_code.show.v1",n.SCAN_QR_CODE_METHOD="m.qr_code.scan.v1",function(e){e.ShowReciprocateQr="show_reciprocate_qr"}(l=n.QrCodeEvent||(n.QrCodeEvent={}));class d 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!==e.encodedSharedSecret)throw(0,s.newKeyMismatchError)();yield new Promise(((e,t)=>{this.reciprocateQREvent={confirm:e,cancel:()=>t((0,s.newUserCancelledError)())},this.emit(l.ShowReciprocateQr,this.reciprocateQREvent)}));const t={};switch(e.mode){case u.VerifyOtherUser:{const n=e.otherUserMasterKey;t[`ed25519:${n}`]=n;break}case u.VerifySelfTrusted:{const n=this.request.targetDevice.deviceId;t[`ed25519:${n}`]=e.otherDeviceKey;break}case u.VerifySelfUntrusted:{const n=e.myMasterKey;t[`ed25519:${n}`]=n;break}}yield this.verifyKeys(this.userId,t,((e,n,i)=>{const r=t[e];if(!r)throw(0,s.newKeyMismatchError)();if(i!==r)throw c.logger.error("key ID from key info does not match"),(0,s.newKeyMismatchError)();for(const e in n.keys){if(!e.startsWith("ed25519"))continue;const i=t[e];if(!i)throw(0,s.newKeyMismatchError)();if(n.keys[e]!==i)throw c.logger.error("master key does not match"),(0,s.newKeyMismatchError)()}}))}))}static factory(e,t,n,i,r,o){return new d(e,t,n,i,r,o)}static get NAME(){return"m.reciprocate.v1"}}n.ReciprocateQRCode=d;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,n,i,r,o){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=n,this.otherDeviceKey=i,this.myMasterKey=r,this.buffer=o}static create(e,t){return r(this,void 0,void 0,(function*(){const n=h.generateSharedSecret(),i=h.determineMode(e,t);let r=null,o=null,s=null;if(i===u.VerifyOtherUser){r=t.getStoredCrossSigningForUser(e.otherUserId).getId("master")}else if(i===u.VerifySelfTrusted)o=yield h.getOtherDeviceKey(e,t);else if(i===u.VerifySelfUntrusted){const e=t.getUserId();s=t.getStoredCrossSigningForUser(e).getId("master")}const a=h.generateQrData(e,t,i,n,r,o,s),c=h.generateBuffer(a);return new h(i,n,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 n=t.getUserId(),i=e.targetDevice,r=i?i.deviceId:null,o=t.getStoredDevice(n,r);if(!o)throw new Error("could not find device "+r);return o.getFingerprint()}))}static determineMode(e,t){const n=t.getUserId(),i=e.otherUserId;let r=u.VerifyOtherUser;if(n===i){r=t.checkUserTrust(n).isCrossSigningVerified()?u.VerifySelfTrusted:u.VerifySelfUntrusted}return r}static generateQrData(e,t,n,i,r,o,s){const a=t.getUserId(),c={prefix:"MATRIX",version:2,mode:n,transactionId:e.channel.transactionId,firstKeyB64:"",secondKeyB64:"",secretB64:i},l=t.getStoredCrossSigningForUser(a);return n===u.VerifyOtherUser?(c.firstKeyB64=l.getId("master"),c.secondKeyB64=r):n===u.VerifySelfTrusted?(c.firstKeyB64=l.getId("master"),c.secondKeyB64=o):n===u.VerifySelfUntrusted&&(c.firstKeyB64=t.getDeviceEd25519Key(),c.secondKeyB64=s),c}static generateBuffer(e){let t=i.alloc(0);const n=e=>{const n=i.from([e]);t=i.concat([t,n])},r=(e,n,r=!0)=>{const o=i.from(e,n);r&&(e=>{const n=i.alloc(2);n.writeInt16BE(e,0),t=i.concat([t,n])})(o.byteLength),t=i.concat([t,o])},o=e=>{const n=(0,a.decodeBase64)(e),r=i.from(n);t=i.concat([t,r])};return r(e.prefix,"ascii",!1),n(e.version),n(e.mode),r(e.transactionId,"utf-8"),o(e.firstKeyB64),o(e.secondKeyB64),o(e.secretB64),t}}n.QRCodeData=h}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../../logger":126,"../olmlib":105,"./Base":111,"./Error":112,buffer:20}],115:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.SAS=n.SasEvent=void 0;const o=r(e("another-json")),s=e("./Base"),a=e("./Error"),c=e("../../logger"),l="m.key.verification.start",d=["m.key.verification.accept","m.key.verification.key","m.key.verification.mac"];let u;const h=(0,a.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),g=(0,a.errorFactory)("m.mismatched_commitment","Mismatched commitment");const p=[["🐶","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 f={decimal: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)]},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=>p[e]))}};function v(e,t){const n={};for(const i of t)i in f&&(n[i]=f[i](e));return n}const y={"hkdf-hmac-sha256":"calculate_mac","hmac-sha256":"calculate_mac_long_kdf"};function m(e,t){return function(...n){const i=e[y[t]].apply(e,n);return c.logger.log("SAS calculateMAC:",t,n,i),i}}const E={"curve25519-hkdf-sha256":function(e,t,n){const i=`${e.baseApis.getUserId()}|${e.baseApis.deviceId}|${e.ourSASPubKey}|`,r=`${e.userId}|${e.deviceId}|${e.theirSASPubKey}|`,o="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?i+r:r+i)+e.channel.transactionId;return t.generate_bytes(o,n)},curve25519:function(e,t,n){const i=`${e.baseApis.getUserId()}${e.baseApis.deviceId}`,r=`${e.userId}${e.deviceId}`,o="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?i+r:r+i)+e.channel.transactionId;return t.generate_bytes(o,n)}},S=["curve25519-hkdf-sha256","curve25519"],b=["sha256"],_=["hkdf-hmac-sha256","hmac-sha256"],T=Object.keys(f),w=new Set(S),I=new Set(b),R=new Set(_),k=new Set(T);function O(e,t){return e instanceof Array?e.filter((e=>t.has(e))):[]}var C;!function(e){e.ShowSas="show_sas"}(C=n.SasEvent||(n.SasEvent={}));class P extends s.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>i(this,void 0,void 0,(function*(){yield t.Olm.init(),u=u||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 d}canSwitchStartEvent(e){if(e.getType()!==l)return!1;const t=e.getContent();return t&&t.method===P.NAME&&this.waitingForAccept}sendStart(){return i(this,void 0,void 0,(function*(){const e=this.channel.completeContent(l,{method:P.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:S,hashes:b,message_authentication_codes:_,short_authentication_string:T});return yield this.channel.sendCompleted(l,e),e}))}doSendVerification(){return i(this,void 0,void 0,(function*(){let e,n;if(this.waitingForAccept=!0,e=this.startEvent?this.channel.completedContentFromEvent(this.startEvent):yield this.sendStart(),!this.initiatedByMe)throw new s.SwitchStartEventError(this.startEvent);try{n=yield this.waitForEvent("m.key.verification.accept")}finally{this.waitingForAccept=!1}let r=n.getContent();const c=O(r.short_authentication_string,k);if(!(w.has(r.key_agreement_protocol)&&I.has(r.hash)&&R.has(r.message_authentication_code)&&c.length))throw(0,a.newUnknownMethodError)();if("string"!=typeof r.commitment)throw(0,a.newInvalidMessageError)();const l=r.key_agreement_protocol,d=r.message_authentication_code,p=r.commitment,f=new t.Olm.SAS;try{this.ourSASPubKey=f.get_pubkey(),yield this.send("m.key.verification.key",{key:this.ourSASPubKey}),n=yield this.waitForEvent("m.key.verification.key"),r=n.getContent();const t=r.key+o.default.stringify(e);if(u.sha256(t)!==p)throw g();this.theirSASPubKey=r.key,f.set_their_key(r.key);const s=E[l](this,f,6),y=new Promise(((e,t)=>{this.sasEvent={sas:v(s,c),confirm:()=>i(this,void 0,void 0,(function*(){try{yield this.sendMAC(f,d),e()}catch(e){t(e)}})),cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit(C.ShowSas,this.sasEvent)}));[n]=yield Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),y]),r=n.getContent(),yield this.checkMAC(f,r,d)}finally{f.free()}}))}doRespondVerification(){return i(this,void 0,void 0,(function*(){let e=this.channel.completedContentFromEvent(this.startEvent);const n=O(S,new Set(e.key_agreement_protocols))[0],r=O(b,new Set(e.hashes))[0],s=O(_,new Set(e.message_authentication_codes))[0],c=O(e.short_authentication_string,k);if(void 0===n||void 0===r||void 0===s||!c.length)throw(0,a.newUnknownMethodError)();const l=new t.Olm.SAS;try{const t=l.get_pubkey()+o.default.stringify(e);yield this.send("m.key.verification.accept",{key_agreement_protocol:n,hash:r,message_authentication_code:s,short_authentication_string:c,commitment:u.sha256(t)});let d=yield this.waitForEvent("m.key.verification.key");e=d.getContent(),this.theirSASPubKey=e.key,l.set_their_key(e.key),this.ourSASPubKey=l.get_pubkey(),yield this.send("m.key.verification.key",{key:this.ourSASPubKey});const g=E[n](this,l,6),p=new Promise(((e,t)=>{this.sasEvent={sas:v(g,c),confirm:()=>i(this,void 0,void 0,(function*(){try{yield this.sendMAC(l,s),e()}catch(e){t(e)}})),cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit(C.ShowSas,this.sasEvent)}));[d]=yield Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),p]),e=d.getContent(),yield this.checkMAC(l,e,s)}finally{l.free()}}))}sendMAC(e,t){const n={},i=[],r="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,o=`ed25519:${this.baseApis.deviceId}`;n[o]=m(e,t)(this.baseApis.getDeviceEd25519Key(),r+o),i.push(o);const s=this.baseApis.getCrossSigningId();if(s){const o=`ed25519:${s}`;n[o]=m(e,t)(s,r+o),i.push(o)}const a=m(e,t)(i.sort().join(","),r+"KEY_IDS");return this.send("m.key.verification.mac",{mac:n,keys:a})}checkMAC(e,t,n){return i(this,void 0,void 0,(function*(){const i="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this.baseApis.getUserId()+this.baseApis.deviceId+this.channel.transactionId;if(t.keys!==m(e,n)(Object.keys(t.mac).sort().join(","),i+"KEY_IDS"))throw(0,a.newKeyMismatchError)();yield this.verifyKeys(this.userId,t.mac,((t,r,o)=>{if(o!==m(e,n)(r.keys[t],i+t))throw(0,a.newKeyMismatchError)()}))}))}}n.SAS=P}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../logger":126,"./Base":111,"./Error":112,"another-json":14}],116:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.InRoomRequests=n.InRoomChannel=void 0;const r=e("./VerificationRequest"),o=e("../../../logger"),s=e("../../../@types/event").EventType.RoomMessage,a="m.reference",c="m.relates_to";class l{constructor(e,t,n=null){this.client=e,this.roomId=t,this.userId=n,this.requestEventId=null}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){if(l.getEventType(e)!==r.REQUEST_TYPE)return;const n=t.getUserId(),i=e.getSender(),o=e.getContent().to;return i===n?o:o===n?i:void 0}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===r.REQUEST_TYPE}canCreateRequest(e){return l.canCreateRequest(e)}static getTransactionId(e){if(l.getEventType(e)===r.REQUEST_TYPE)return e.getId();{const t=e.getRelation();if(t&&t.rel_type===a)return t.event_id}}static validateEvent(e,t){const n=l.getTransactionId(e);if("string"!=typeof n||0===n.length)return!1;const i=l.getEventType(e),s=e.getContent();if(i===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(!l.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(i,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,n=!1){if(t.hasEventId(e.getId()))return;const i=l.getEventType(e);if(e.getRoomId()!==this.roomId)return;if(null===this.userId){const t=l.getOtherPartyUserId(e,this.client);t&&(this.userId=t)}const r=this.client.getUserId(),s=e.getSender();if(null!==this.userId&&s!==r&&s!==this.userId)return void o.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${s}`);null===this.requestEventId&&(this.requestEventId=l.getTransactionId(e));const a=!!e.getUnsigned().transaction_id,c=e.getSender()===this.client.getUserId();return t.handleEvent(i,e,n,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 n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){return i(this,void 0,void 0,(function*(){let n=e;e===r.REQUEST_TYPE&&(n=s);const i=yield this.client.sendEvent(this.roomId,n,t);e===r.REQUEST_TYPE&&(this.requestEventId=i.event_id)}))}}n.InRoomChannel=l;n.InRoomRequests=class{constructor(){this.requestsByRoomId=new Map}getRequest(e){const t=e.getRoomId(),n=l.getTransactionId(e);return this.getRequestByTxnId(t,n)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){const n=this.requestsByRoomId.get(e);if(n)return n.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),l.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,n){let i=this.requestsByRoomId.get(e);i||(i=new Map,this.requestsByRoomId.set(e,i)),i.set(t,n)}removeRequest(e){const t=e.getRoomId(),n=this.requestsByRoomId.get(t);n&&(n.delete(l.getTransactionId(e)),0===n.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":72,"../../../logger":126,"./VerificationRequest":118}],117:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.ToDeviceRequests=n.ToDeviceChannel=void 0;const r=e("../../../randomstring"),o=e("../../../logger"),s=e("./VerificationRequest"),a=e("../Error"),c=e("../../../models/event");class l{constructor(e,t,n,i=null,r=null){this.client=e,this.userId=t,this.devices=n,this.transactionId=i,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 l.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return o.logger.warn("Ignoring flagged verification request from "+e.getSender()),!1;const n=e.getContent();if(!n)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!n.transaction_id)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;const i=e.getType();if(i===s.REQUEST_TYPE){if(!Number.isFinite(n.timestamp))return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&n.from_device==t.getDeviceId())return o.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return s.VerificationRequest.validateEvent(i,e,t)}getTimestamp(e){const t=e.getContent();return t&&t.timestamp}handleEvent(e,t,n=!1){return i(this,void 0,void 0,(function*(){const i=e.getType(),r=e.getContent();if(i===s.REQUEST_TYPE||i===s.READY_TYPE||i===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,n,!1,!1);const c=t.phase===s.PHASE_STARTED||t.phase===s.PHASE_READY;if((i===s.START_TYPE||i===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=l.makeTransactionId());const n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){return i(this,void 0,void 0,(function*(){let n;n=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 i=new c.MatrixEvent({sender:this.client.getUserId(),content:t,type:e});return yield this.request.handleEvent(e,i,!0,!0,!0),n}))}sendToDevices(e,t,n){return i(this,void 0,void 0,(function*(){if(n.length){const i={};for(const e of n)i[e]=t;yield this.client.sendToDevice(e,{[this.userId]:i})}}))}static makeTransactionId(){return(0,r.randomString)(32)}}n.ToDeviceChannel=l;n.ToDeviceRequests=class{constructor(){this.requestsByUserId=new Map}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),l.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){const n=this.requestsByUserId.get(e);if(n)return n.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),l.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,n){let i=this.requestsByUserId.get(e);i||(i=new Map,this.requestsByUserId.set(e,i)),i.set(t,n)}removeRequest(e){const t=e.getSender(),n=this.requestsByUserId.get(t);n&&(n.delete(l.getTransactionId(e)),0===n.size&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){const n=this.requestsByUserId.get(e);if(n)for(const e of n.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":126,"../../../models/event":135,"../../../randomstring":146,"../Error":112,"./VerificationRequest":118}],118:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.VerificationRequest=n.VerificationRequestEvent=n.PHASE_DONE=n.PHASE_CANCELLED=n.PHASE_STARTED=n.PHASE_READY=n.PHASE_REQUESTED=n.PHASE_UNSENT=n.Phase=n.READY_TYPE=n.DONE_TYPE=n.CANCEL_TYPE=n.START_TYPE=n.REQUEST_TYPE=n.EVENT_PREFIX=void 0;const r=e("../../../logger"),o=e("../Error"),s=e("../QRCode"),a=e("../../../models/typed-event-emitter");var c,l;n.EVENT_PREFIX="m.key.verification.",n.REQUEST_TYPE=n.EVENT_PREFIX+"request",n.START_TYPE=n.EVENT_PREFIX+"start",n.CANCEL_TYPE=n.EVENT_PREFIX+"cancel",n.DONE_TYPE=n.EVENT_PREFIX+"done",n.READY_TYPE=n.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"}(c=n.Phase||(n.Phase={})),n.PHASE_UNSENT=c.Unsent,n.PHASE_REQUESTED=c.Requested,n.PHASE_READY=c.Ready,n.PHASE_STARTED=c.Started,n.PHASE_CANCELLED=c.Cancelled,n.PHASE_DONE=c.Done,function(e){e.Change="change"}(l=n.VerificationRequestEvent||(n.VerificationRequestEvent={}));class d extends a.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=()=>i(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(n.PHASE_UNSENT,!1)}static validateEvent(e,t,i){const o=t.getContent();return!(!e||!e.startsWith(n.EVENT_PREFIX))&&(o?e!==n.REQUEST_TYPE&&e!==n.READY_TYPE||Array.isArray(o.methods)?e!==n.REQUEST_TYPE&&e!==n.READY_TYPE&&e!==n.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===n.PHASE_UNSENT}get requested(){return this.phase===n.PHASE_REQUESTED}get cancelled(){return this.phase===n.PHASE_CANCELLED}get ready(){return this.phase===n.PHASE_READY}get started(){return this.phase===n.PHASE_STARTED}get done(){return this.phase===n.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<=n.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(n.REQUEST_TYPE);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(n.REQUEST_TYPE)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return this.phase<n.PHASE_READY&&!this._accepting&&!this._declining}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==n.PHASE_DONE&&this._phase!==n.PHASE_CANCELLED}get qrCodeData(){return this._qrCodeData}otherPartySupportsMethod(e,t=!1){if(!t&&!this.ready&&!this.started)return!1;const i=this.eventsByThem.get(n.REQUEST_TYPE)||this.eventsByThem.get(n.READY_TYPE);if(!i){if(this.started&&this.initiatedByMe){const t=this.eventsByUs.get(n.START_TYPE),i=t&&t.getContent();return e==(i&&i.method)}return!1}const r=i.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===n.PHASE_UNSENT&&e)return!0;const t=this.eventsByUs.has(n.REQUEST_TYPE),i=this.eventsByThem.has(n.REQUEST_TYPE);if(t&&!i)return!0;if(!t&&i)return!1;const r=this.eventsByUs.has(n.START_TYPE),o=this.eventsByThem.has(n.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(n.CANCEL_TYPE),t=this.eventsByThem.get(n.CANCEL_TYPE);return e&&(!t||e.getId()<t.getId())?e.getSender():t?t.getSender():void 0}get cancellationCode(){const e=this.getEventByEither(n.CANCEL_TYPE);return e?e.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){const e=(this.eventsByThem.get(n.REQUEST_TYPE)||this.eventsByThem.get(n.READY_TYPE)||this.eventsByThem.get(n.START_TYPE)).getContent().from_device;return{userId:this.otherUserId,deviceId:e}}beginKeyVerification(e,t=null){if(!this.observeOnly&&!this._verifier){if(this.phase===n.PHASE_REQUESTED||this.phase===n.PHASE_READY||this.phase===n.PHASE_UNSENT&&this.channel.canCreateRequest(n.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 i(this,void 0,void 0,(function*(){if(!this.observeOnly&&this._phase===n.PHASE_UNSENT){const e=[...this.verificationMethods.keys()];yield this.channel.send(n.REQUEST_TYPE,{methods:e})}}))}cancel({reason:e="User declined",code:t="m.user"}={}){return i(this,void 0,void 0,(function*(){if(!this.observeOnly&&this._phase!==n.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(n.CANCEL_TYPE,{code:t,reason:e})}}))}accept(){return i(this,void 0,void 0,(function*(){if(!this.observeOnly&&this.phase===n.PHASE_REQUESTED&&!this.initiatedByMe){const e=[...this.verificationMethods.keys()];this._accepting=!0,this.emit(l.Change),yield this.channel.send(n.READY_TYPE,{methods:e})}}))}waitFor(e){return new Promise(((t,n)=>{const i=()=>{let r=!1;return e(this)?(t(this),r=!0):this.cancelled&&(n(new Error("cancelled")),r=!0),r&&this.off(l.Change,i),r};i()||this.on(l.Change,i)}))}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:n.PHASE_UNSENT}],t=()=>e[e.length-1].phase,i=this.eventsByThem.has(n.REQUEST_TYPE),r=this.getEventBy(n.REQUEST_TYPE,i);r&&e.push({phase:n.PHASE_REQUESTED,event:r});const o=r&&this.getEventBy(n.READY_TYPE,!i);let s;if(o&&t()===n.PHASE_REQUESTED&&e.push({phase:n.PHASE_READY,event:o}),o||!r){const e=this.eventsByThem.get(n.START_TYPE),t=this.eventsByUs.get(n.START_TYPE);s=e&&t?e.getSender()<t.getSender()?e:t:e||t}else s=this.getEventBy(n.START_TYPE,!i);if(s){const i=t()===n.PHASE_REQUESTED&&r.getSender()!==s.getSender(),o=t()===n.PHASE_UNSENT&&this.channel.canCreateRequest(n.START_TYPE);(i||t()===n.PHASE_READY||o)&&e.push({phase:n.PHASE_STARTED,event:s})}const a=this.eventsByUs.get(n.DONE_TYPE);(this.verifierHasFinished||a&&t()===n.PHASE_STARTED)&&e.push({phase:n.PHASE_DONE});const c=this.getEventByEither(n.CANCEL_TYPE);return(this._cancelled||c)&&t()!==n.PHASE_DONE?(e.push({phase:n.PHASE_CANCELLED,event:c}),e):e}transitionToPhase(e){const{phase:t,event:i}=e;if((t===n.PHASE_REQUESTED||t===n.PHASE_READY)&&!this.wasSentByOwnDevice(i)){const e=i.getContent();this.commonMethods=e.methods.filter((e=>this.verificationMethods.has(e)))}if(this.observeOnly||t!==n.PHASE_REQUESTED&&t!==n.PHASE_STARTED&&t!==n.PHASE_READY||this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(i)&&!this.wasSentByOwnDevice(i)&&(this._observeOnly=!0),t===n.PHASE_STARTED){const{method:e}=i.getContent();this._verifier||this.observeOnly||(this._verifier=this.createVerifier(e,i),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)),n=e.slice(t+1);for(const e of n)this.transitionToPhase(e);return n}isWinningStartRace(e){if(e.getType()!==n.START_TYPE)return!1;const t=this._verifier.startEvent;let i,r;if(this.isSelfVerification)if(t){const e=t.getContent();i=e&&e.from_device}else i=this.client.getDeviceId();else i=t?t.getSender():this.client.getUserId();if(this.isSelfVerification){const t=e.getContent();r=t&&t.from_device}else r=e.getSender();return r<i}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 i(this,void 0,void 0,(function*(){if(this.done||this.cancelled)return;const i=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 i=this.isWinningStartRace(t);this._verifier.canSwitchStartEvent(t)&&i?this._verifier.switchStartEvent(t):a||(e===n.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===n.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!==i&&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:${i}=>${this._observeOnly}`)}}))}setupTimeout(e){if(!this.timeoutTimer&&!this.observeOnly&&e===n.PHASE_REQUESTED&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer){(e===n.PHASE_STARTED||e===n.PHASE_READY||e===n.PHASE_DONE||e===n.PHASE_CANCELLED)&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}}cancelOnError(e,t){return i(this,void 0,void 0,(function*(){if(e===n.START_TYPE){const e=t.getContent().method;if(!this.verificationMethods.has(e))return yield this.cancel((0,o.errorFromEvent)((0,o.newUnknownMethodError)())),!0}const i=e===n.REQUEST_TYPE&&this.phase!==n.PHASE_UNSENT,s=e===n.READY_TYPE&&this.phase!==n.PHASE_REQUESTED&&this.phase!==n.PHASE_STARTED;if(this.phase!==n.PHASE_UNSENT&&(i||s)){r.logger.warn(`Cancelling, unexpected ${e} verification event from ${t.getSender()}`);const n=`Unexpected ${e} event in phase ${this.phase}`;return yield this.cancel((0,o.errorFromEvent)((0,o.newUnexpectedMessageError)({reason:n}))),!0}return!1}))}adjustObserveOnly(e,t=!1){t||(this._observeOnly=!0),this.calculateEventTimeout(e)<3e3&&(this._observeOnly=!0)}addEvent(e,t,i=!1){if(i?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===n.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,n=null){n||(n=this.targetDevice);const{userId:i,deviceId:o}=n,s=this.verificationMethods.get(e);if(s)return new s(this.channel,this.client,i,o,t,this);r.logger.warn("could not find verifier constructor for method",e)}wasSentByOwnUser(e){return 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("m.key.verification.done",{}),this.verifierHasFinished=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}n.VerificationRequest=d},{"../../../logger":126,"../../../models/typed-event-emitter":143,"../Error":112,"../QRCode":114}],119:[function(e,t,n){"use strict";var i=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.InvalidCryptoStoreError=h,n.InvalidStoreError=u,n.KeySignatureUploadError=void 0;var r=i(e("@babel/runtime/helpers/createClass")),o=i(e("@babel/runtime/helpers/classCallCheck")),s=i(e("@babel/runtime/helpers/inherits")),a=i(e("@babel/runtime/helpers/possibleConstructorReturn")),c=i(e("@babel/runtime/helpers/getPrototypeOf")),l=i(e("@babel/runtime/helpers/wrapNativeSuper"));function d(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 n,i=(0,c.default)(e);if(t){var r=(0,c.default)(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return(0,a.default)(this,n)}}function u(e,t){var n="Store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again",i=Reflect.construct(Error,[n]);return Reflect.setPrototypeOf(i,Reflect.getPrototypeOf(this)),i.reason=e,i.value=t,i}function h(e){var t="Crypto store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again",n=Reflect.construct(Error,[t]);return Reflect.setPrototypeOf(n,Reflect.getPrototypeOf(this)),n.reason=e,n.name="InvalidCryptoStoreError",n}u.TOGGLED_LAZY_LOADING="TOGGLED_LAZY_LOADING",u.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(u,Error),h.TOO_NEW="TOO_NEW",h.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(h,Error);var g=function(e){(0,s.default)(n,e);var t=d(n);function n(e,i){var r;return(0,o.default)(this,n),(r=t.call(this,e)).value=i,r}return(0,r.default)(n)}((0,l.default)(Error));n.KeySignatureUploadError=g},{"@babel/runtime/helpers/classCallCheck":2,"@babel/runtime/helpers/createClass":4,"@babel/runtime/helpers/getPrototypeOf":5,"@babel/runtime/helpers/inherits":6,"@babel/runtime/helpers/interopRequireDefault":7,"@babel/runtime/helpers/possibleConstructorReturn":10,"@babel/runtime/helpers/wrapNativeSuper":13}],120:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.eventMapperFor=void 0;const i=e("./models/event");n.eventMapperFor=function(e,t){let n=Boolean(t.preventReEmit);const r=!1!==t.decrypt;return function(t){const o=e.getRoom(t.room_id);let s;o&&void 0===t.state_key&&(s=o.findEventById(t.event_id)),!s||s.status?s=new i.MatrixEvent(t):(s.setUnsigned(Object.assign(Object.assign({},s.getUnsigned()),t.unsigned)),n=!0);const a=null==o?void 0:o.findThreadForEvent(s);return a&&s.setThread(a),s.isEncrypted()&&(n||e.reEmitter.reEmit(s,[i.MatrixEventEvent.Decrypted]),r&&e.decryptEventIfNeeded(s)),n||(e.reEmitter.reEmit(s,[i.MatrixEventEvent.Replaced,i.MatrixEventEvent.VisibilityChange]),null==o||o.reEmitter.reEmit(s,[i.MatrixEventEvent.BeforeRedaction])),s}}},{"./models/event":135}],121:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FilterComponent=void 0;const i=e("./models/thread");n.FilterComponent=class{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,n;const r=(null===(t=e.getUnsigned())||void 0===t?void 0:t["m.relations"])||{},o=Object.keys(r),s=[];return this.userId&&(null===(n=null==r?void 0:r[i.THREAD_RELATION_TYPE.name])||void 0===n?void 0:n.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,[i.FILTER_RELATED_BY_SENDERS.name]:this.filterJson[i.FILTER_RELATED_BY_SENDERS.name]||[],[i.FILTER_RELATED_BY_REL_TYPES.name]:this.filterJson[i.FILTER_RELATED_BY_REL_TYPES.name]||[]}}checkFields(e,t,n,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 n=t.slice(0,-1);return e.slice(0,n.length)===n}return e===t}(n,e)}};for(let e=0;e<Object.keys(a).length;e++){const t=Object.keys(a)[e],n=a[t],i="not_"+t,r=this.filterJson[i];if(null==r?void 0:r.some(n))return!1;const o=this.filterJson[t];if(o&&!o.some(n))return!1}const c=this.filterJson.contains_url;if(void 0!==c&&c!==r)return!1;const l=this.filterJson[i.FILTER_RELATED_BY_REL_TYPES.name];if(void 0!==l&&!this.arrayMatchesFilter(l,o))return!1;const d=this.filterJson[i.FILTER_RELATED_BY_SENDERS.name];return!(void 0!==d&&!this.arrayMatchesFilter(d,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":142}],122:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.Filter=void 0;const i=e("./filter-component");function r(e,t,n){const i=t.split(".");let r=e;for(let e=0;e<i.length-1;e++)r[i[e]]||(r[i[e]]={}),r=r[i[e]];r[i[i.length-1]]=n}class o{constructor(e,t){this.userId=e,this.filterId=t,this.definition={}}static fromJson(e,t,n){const i=new o(e,t);return i.setDefinition(n),i}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;const t=e.room,n={};t&&(t.rooms&&(n.rooms=t.rooms),t.rooms&&(n.not_rooms=t.not_rooms)),this.roomFilter=new i.FilterComponent(n,this.userId),this.roomTimelineFilter=new i.FilterComponent((null==t?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomTimelineFilter.filter(this.roomFilter.filter(e))}setTimelineLimit(e){r(this.definition,"room.timeline.limit",e)}setLazyLoadMembers(e){r(this.definition,"room.state.lazy_load_members",!!e)}setIncludeLeaveRooms(e){r(this.definition,"room.include_leave",e)}}n.Filter=o,o.LAZY_LOADING_MESSAGES_FILTER={lazy_load_members:!0}},{"./filter-component":121}],123:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.retryNetworkOperation=n.AbortError=n.ConnectionError=n.MatrixError=n.MatrixHttpApi=n.HttpApiEvent=n.Method=n.PREFIX_MEDIA_R0=n.PREFIX_IDENTITY_V2=n.PREFIX_IDENTITY_V1=n.PREFIX_UNSTABLE=n.PREFIX_V3=n.PREFIX_V1=n.PREFIX_R0=void 0;const a=e("content-type"),c=o(e("./realtime-callbacks")),l=e("./utils"),d=o(e("./utils")),u=e("./logger");var h,g;n.PREFIX_R0="/_matrix/client/r0",n.PREFIX_V1="/_matrix/client/v1",n.PREFIX_V3="/_matrix/client/v3",n.PREFIX_UNSTABLE="/_matrix/client/unstable",n.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1",n.PREFIX_IDENTITY_V2="/_matrix/identity/v2",n.PREFIX_MEDIA_R0="/_matrix/media/r0",function(e){e.Get="GET",e.Put="PUT",e.Post="POST",e.Delete="DELETE"}(h=n.Method||(n.Method={})),function(e){e.SessionLoggedOut="Session.logged_out",e.NoConsent="no_consent"}(g=n.HttpApiEvent||(n.HttpApiEvent={}));function p(e){return e.status||e.statusCode}function f(e,t,n=!1,i){return function(r,o,s){if(r){"AbortError"===r.name||"aborted"===r||r instanceof v||(r=new y("request failed",r))}let c=s;if(!r)try{p(o)>=400?r=function(e,t){const n=p(e),i=function(e){let t;e.getResponseHeader?t=e.getResponseHeader("Content-Type"):e.headers&&(t=e.headers["content-type"]||null);if(!t)return null;try{return(0,a.parse)(t)}catch(e){throw new Error(`Error parsing Content-Type '${t}': ${e}`)}}(e);let r;if(i)if("application/json"===i.type){const e="object"==typeof t?t:JSON.parse(t);r=new v(e)}else"text/plain"===i.type&&(r=new Error(`Server returned ${n} error: ${t}`));r||(r=new Error(`Server returned ${n} error`));return r.httpStatus=n,r}(o,s):i&&(c=i(s))}catch(e){r=new Error(`Error parsing server response: ${e}`)}if(r)e.reject(r),null==t||t(r);else if(n)e.resolve(c),null==t||t(null,c);else{const n={code:p(o),headers:o.headers,data:c};e.resolve(n),null==t||t(null,n)}}}n.MatrixHttpApi=class{constructor(e,t){this.eventEmitter=e,this.opts=t,this.uploads=[],d.checkObjectHasKeys(t,["baseUrl","request","prefix"]),t.onlyData=!!t.onlyData,t.useAuthorizationHeader=!!t.useAuthorizationHeader}setIdBaseUrl(e){this.opts.idBaseUrl=e}getContentUri(){return{base:this.opts.baseUrl,path:"/_matrix/media/r0/upload",params:{access_token:this.opts.accessToken}}}uploadContent(e,n){d.isFunction(n)?n={callback:n}:n||(n={});const i=!1!==n.includeFilename,r=n.type||e.type||"application/octet-stream",o=n.name||e.name;let s=e;const a=s.stream;a&&"function"!=typeof a&&(u.logger.warn("Using `file.stream` as the content to upload. Future versions of the js-sdk will change this to expect `file` to be the content directly."),s=a);let l=n.rawResponse;void 0===l&&(t.XMLHttpRequest?l=!1:(u.logger.warn("Returning the raw JSON from uploadContent(). Future versions of the js-sdk will change this default, to return the parsed object. Set opts.rawResponse=false to change this behaviour now."),l=!0));let g=n.onlyContentUri;l||void 0!==g||(t.XMLHttpRequest?(u.logger.warn("Returning only the content-uri from uploadContent(). Future versions of the js-sdk will change this default, to return the whole response object. Set opts.onlyContentUri=false to change this behaviour now."),g=!0):g=!1);const p={loaded:0,total:0};let v,y=null;if(l||(y=function(e){let t=JSON.parse(e);if(g&&(t=t.content_uri,void 0===t))throw Error("Bad response");return t}),t.XMLHttpRequest){const e=d.defer(),a=new t.XMLHttpRequest,l=f(e,n.callback,this.opts.onlyData),u=function(){a.abort(),l(new Error("Timeout"))};let h=c.setTimeout(u,3e4);a.onreadystatechange=function(){let e;if(a.readyState===t.XMLHttpRequest.DONE){c.clearTimeout(h);try{if(0===a.status)throw new m;if(!a.responseText)throw new Error("No response body.");e=a.responseText,y&&(e=y(e))}catch(e){return e.httpStatus=a.status,void l(e)}l(void 0,a,e)}},a.upload.addEventListener("progress",(function(e){c.clearTimeout(h),p.loaded=e.loaded,p.total=e.total,h=c.setTimeout(u,3e4),n.progressHandler&&n.progressHandler({loaded:e.loaded,total:e.total})}));let g=this.opts.baseUrl+"/_matrix/media/r0/upload";const E=[];i&&o&&E.push("filename="+encodeURIComponent(o)),this.opts.useAuthorizationHeader||E.push("access_token="+encodeURIComponent(this.opts.accessToken)),E.length>0&&(g+="?"+E.join("&")),a.open("POST",g),this.opts.useAuthorizationHeader&&a.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),a.setRequestHeader("Content-Type",r),a.send(s),v=e.promise,v.abort=a.abort.bind(a)}else{const e={};i&&o&&(e.filename=o);const t={"Content-Type":r};0===s.length&&(t["Content-Length"]="0"),v=this.authedRequest(n.callback,h.Post,"/upload",e,s,{prefix:"/_matrix/media/r0",headers:t,json:!1,bodyParser:y})}return p.promise=v.finally((()=>{for(let e=0;e<this.uploads.length;++e)if(this.uploads[e]===p)return void this.uploads.splice(e,1)})),p.promise.abort=v.abort,this.uploads.push(p),p.promise}cancelUpload(e){return!!e.abort&&(e.abort(),!0)}getCurrentUploads(){return this.uploads}idServerRequest(e,t,n,i,r,o){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");const s=this.opts.idBaseUrl+r+n;if(void 0!==e&&!d.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);const a={uri:s,method:t,withCredentials:!1,json:!0,_matrix_opts:this.opts,headers:{}};t===h.Get?a.qs=i:"object"==typeof i&&(a.json=i),o&&(a.headers.Authorization=`Bearer ${o}`);const c=d.defer();return this.opts.request(a,f(c,e,this.opts.onlyData)),c.promise}authedRequest(e,t,n,i,r,o){i||(i={});let s=o||{};this.opts.useAuthorizationHeader?(isFinite(o)&&(s={localTimeoutMs:o}),s.headers||(s.headers={}),s.headers.Authorization||(s.headers.Authorization="Bearer "+this.opts.accessToken),i.access_token&&delete i.access_token):i.access_token||(i.access_token=this.opts.accessToken);const a=this.request(e,t,n,i,r,s);return a.catch((e=>{"M_UNKNOWN_TOKEN"!=e.errcode||(null==s?void 0:s.inhibitLogoutEmit)?"M_CONSENT_NOT_GIVEN"==e.errcode&&this.eventEmitter.emit(g.NoConsent,e.message,e.data.consent_uri):this.eventEmitter.emit(g.SessionLoggedOut,e)})),a}request(e,t,n,i,r,o){var s;const a=null!==(s=null==o?void 0:o.prefix)&&void 0!==s?s:this.opts.prefix,c=this.opts.baseUrl+a+n;return this.requestOtherUrl(e,t,c,i,r,o)}requestOtherUrl(e,t,n,i,r,o){let s=o||{};return isFinite(o)&&(s={localTimeoutMs:o}),this.doRequest(e,t,n,i,r,s)}getUrl(e,t,n){let i="";return t&&(i="?"+d.encodeParams(t)),this.opts.baseUrl+n+e+i}doRequest(e,t,n,i,r,o){var s;if(void 0!==e&&!d.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);this.opts.extraParams&&(i=Object.assign(Object.assign({},i||{}),this.opts.extraParams));const a=Object.assign({},o.headers||{});o||(o={});const l=null===(s=o.json)||void 0===s||s;let u=o.bodyParser;l&&(r&&(r=JSON.stringify(r),a["content-type"]="application/json"),a.accept||(a.accept="application/json"),void 0===u&&(u=function(e){return JSON.parse(e)}));const h=d.defer();let g,p,y=!1;const m=o.localTimeoutMs||this.opts.localTimeoutMs,E=()=>{m&&(g&&c.clearTimeout(g),g=c.setTimeout((function(){var e;y=!0,null===(e=null==p?void 0:p.abort)||void 0===e||e.call(p),h.reject(new v({error:"Locally timed out waiting for a response",errcode:"ORG.MATRIX.JSSDK_TIMEOUT",timeout:m}))}),m))};E();const S=h.promise;try{p=this.opts.request({uri:n,method:t,withCredentials:!1,qs:i,qsStringifyOptions:o.qsStringifyOptions,useQuerystring:!0,body:r,json:!1,timeout:m,headers:a||{},_matrix_opts:this.opts},((t,n,i)=>{if(m&&(c.clearTimeout(g),y))return;f(h,e,this.opts.onlyData,u)(t,n,i)})),p&&("onprogress"in p&&(p.onprogress=e=>{E()}),p.abort&&(S.abort=p.abort.bind(p)))}catch(t){h.reject(t),e&&e(t)}return S}};class v extends Error{constructor(e={}){super(`MatrixError: ${e.errcode}`),this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.message=e.error||"Unknown message",this.data=e}}n.MatrixError=v;class y extends Error{constructor(e,t){super(e+(t?`: ${t.message}`:""))}get name(){return"ConnectionError"}}n.ConnectionError=y;class m extends Error{constructor(){super("Operation aborted")}get name(){return"AbortError"}}n.AbortError=m,n.retryNetworkOperation=function(e,t){return s(this,void 0,void 0,(function*(){let n=0,i=null;for(;n<e;)try{if(n>0){const e=1e3*Math.pow(2,n);u.logger.log(`network operation failed ${n} times, retrying in ${e}ms...`),yield(0,l.sleep)(e)}return t()}catch(e){if(!(e instanceof y))throw e;n+=1,i=e}throw i}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./logger":126,"./realtime-callbacks":147,"./utils":159,"content-type":23}],124:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.exists=void 0,n.exists=function(e,t){return new Promise(((n,i)=>{let r=!0;const o=e.open(t);o.onupgradeneeded=()=>{r=!1},o.onblocked=()=>i(o.error),o.onsuccess=()=>{o.result.close(),r||e.deleteDatabase(t),n(r)},o.onerror=e=>i(o.error)}))}},{}],125:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.InteractiveAuth=n.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=n.AuthType||(n.AuthType={}));class l extends Error{constructor(e,t,n){super(e),this.required_stages=t,this.flows=n,this.name="NoAuthFlowFoundError"}}n.InteractiveAuth=class{constructor(e){var t;this.requestingEmailToken=!1,this.attemptAuthDeferred=null,this.chosenFlow=null,this.currentStage=null,this.emailAttempt=1,this.submitPromise=null,this.requestEmailToken=()=>i(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=null!==(t=e.emailSid)&&void 0!==t?t:null}attemptAuth(){var e,t;this.attemptAuthDeferred=(0,o.defer)();const n=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);let e=null;this.data.session&&(e={session:this.data.session}),this.doRequest(e).finally((()=>{var e;null===(e=this.busyChangedCallback)||void 0===e||e.call(this,!1)}))}return n}poll(){return i(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(){return this.data?this.data.session:void 0}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 n,r;return i(this,void 0,void 0,(function*(){if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");for(t||null===(n=this.busyChangedCallback)||void 0===n||n.call(this,!0);this.submitPromise;)try{yield this.submitPromise}catch(e){}let i;this.data.session?(i={session:this.data.session},Object.assign(i,e)):i=e;try{this.submitPromise=this.doRequest(i,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 n,o,s;return i(this,void 0,void 0,(function*(){try{const n=yield this.requestCallback(e,t);this.attemptAuthDeferred.resolve(n),this.attemptAuthDeferred=null}catch(e){const i=null!==(o=null===(n=e.data)||void 0===n?void 0:n.flows)&&void 0!==o?o:null,a=this.data.flows||Boolean(i);401===e.httpStatus&&e.data&&a||(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.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&&this.chosenFlow.stages.includes(c.Email))try{yield this.requestEmailToken()}catch(e){this.attemptAuthDeferred.reject(e),this.attemptAuthDeferred=null}}}))}startNextAuthStage(){const e=this.chooseStage();if(!e)throw new Error("No incomplete flows from the server");if(this.currentStage=e,e===c.Dummy)return void this.submitAuthDict({type:"m.login.dummy"});if(this.data&&this.data.errcode||this.data.error)return void this.stateUpdatedCallback(e,{errcode:this.data.errcode||"",error:this.data.error||""});const t={};e==s&&(t.emailSid=this.emailSid),this.stateUpdatedCallback(e,t)}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),n=Boolean(this.inputs.phoneCountry)&&Boolean(this.inputs.phoneNumber);for(const i of e){let e=!1,r=!1;for(const t of i.stages)t===s?e=!0:t==a&&(r=!0);if(e==t&&r==n)return i}const i=[];throw t&&i.push(s),n&&i.push(a),new l("No appropriate authentication flow found",i,e)}firstUncompletedStage(e){const t=this.data.completed||[];for(let n=0;n<e.stages.length;++n){const i=e.stages[n];if(-1===t.indexOf(i))return i}}}},{"./logger":126,"./utils":159}],126:[function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.logger=void 0;const r=i(e("loglevel")),o="matrix";function s(e){e.withPrefix=function(e){return function(e){const t=r.default.getLogger(`matrix-${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,n){return function(...t){this.prefix&&t.unshift(this.prefix);return"error"===e||"warn"===e||"trace"===e||"info"===e?console[e](...t):console.log(...t)}},n.logger=r.default.getLogger(o),n.logger.setLevel(r.default.levels.DEBUG,!1),s(n.logger)},{loglevel:32}],127:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)},s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.createClient=n.setCryptoStoreFactory=n.wrapRequest=n.getRequest=n.request=n.createNewMatrixCall=n.ContentHelpers=void 0;const a=e("./crypto/store/memory-crypto-store"),c=e("./store/memory"),l=e("./scheduler"),d=e("./client");o(e("./client"),n),o(e("./http-api"),n),o(e("./autodiscovery"),n),o(e("./sync-accumulator"),n),o(e("./errors"),n),o(e("./models/beacon"),n),o(e("./models/event"),n),o(e("./models/room"),n),o(e("./models/event-timeline"),n),o(e("./models/event-timeline-set"),n),o(e("./models/room-member"),n),o(e("./models/room-state"),n),o(e("./models/user"),n),o(e("./scheduler"),n),o(e("./filter"),n),o(e("./timeline-window"),n),o(e("./interactive-auth"),n),o(e("./service-types"),n),o(e("./store/memory"),n),o(e("./store/indexeddb"),n),o(e("./store/session/webstorage"),n),o(e("./crypto/store/memory-crypto-store"),n),o(e("./crypto/store/indexeddb-crypto-store"),n),o(e("./content-repo"),n),o(e("./@types/event"),n),o(e("./@types/PushRules"),n),o(e("./@types/partials"),n),o(e("./@types/requests"),n),o(e("./@types/search"),n),o(e("./models/room-summary"),n),n.ContentHelpers=s(e("./content-helpers"));var u=e("./webrtc/call");let h;Object.defineProperty(n,"createNewMatrixCall",{enumerable:!0,get:function(){return u.createNewMatrixCall}}),n.request=function(e){h=e},n.getRequest=function(){return h},n.wrapRequest=function(e){const t=h;h=function(n,i){return e(t,n,i)}};let g=()=>new a.MemoryCryptoStore;n.setCryptoStoreFactory=function(e){g=e},n.createClient=function(e){return"string"==typeof e&&(e={baseUrl:e}),e.request=e.request||h,e.store=e.store||new c.MemoryStore({localStorage:t.localStorage}),e.scheduler=e.scheduler||new l.MatrixScheduler,e.cryptoStore=e.cryptoStore||g(),new d.MatrixClient(e)}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":70,"./@types/event":72,"./@types/partials":75,"./@types/requests":77,"./@types/search":78,"./autodiscovery":82,"./client":84,"./content-helpers":85,"./content-repo":86,"./crypto/store/indexeddb-crypto-store":108,"./crypto/store/memory-crypto-store":110,"./errors":119,"./filter":122,"./http-api":123,"./interactive-auth":125,"./models/beacon":130,"./models/event":135,"./models/event-timeline":134,"./models/event-timeline-set":133,"./models/room":140,"./models/room-member":137,"./models/room-state":138,"./models/room-summary":139,"./models/user":144,"./scheduler":148,"./service-types":149,"./store/indexeddb":152,"./store/memory":153,"./store/session/webstorage":154,"./sync-accumulator":156,"./timeline-window":158,"./webrtc/call":160}],128:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.MSC3089Branch=void 0;const r=e("../@types/event"),o=e("./event-timeline");n.MSC3089Branch=class{constructor(e,t,n){this.client=e,this.indexEvent=t,this.directory=n}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 i(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 i(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 i(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 i(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 i(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,n,o){return i(this,void 0,void 0,(function*(){const i=yield this.directory.createFile(e,t,n,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},i.event_id),yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{active:!1}),this.id),i}))}getVersionHistory(){return i(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 n=[...t.getLiveTimeline().getEvents()].reverse();let i,r=yield this.getFileEvent();do{if(i=n.find((e=>e.replacingEventId()===r.getId())),i){const t=this.directory.getFile(i.getId());if(!t)break;e.push(t),r=i}}while(i);return e}))}}},{"../@types/event":72,"./event-timeline":134}],129:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.MSC3089TreeSpace=n.TreePermissions=n.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=void 0;const o=r(e("p-retry")),s=e("../@types/event"),a=e("../logger"),c=e("../utils"),l=e("./MSC3089Branch"),d=e("../crypto/algorithms/megolm");var u;n.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=n.TreePermissions||(n.TreePermissions={}));n.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 i(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,s.EventType.RoomName,{name:e},"")}))}invite(e,t=!0,n=!0){return i(this,void 0,void 0,(function*(){const i=[this.retryInvite(e)];return t&&i.push(...this.getDirectories().map((i=>i.invite(e,t,n)))),Promise.all(i).then((()=>{n&&(0,d.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[e])}))}))}retryInvite(e){return(0,c.simpleRetryOperation)((()=>i(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 n;return i(this,void 0,void 0,(function*(){const i=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");const r=i.getContent()||{},o=r.users_default||0,a=r.events_default||50,c=(null===(n=r.events)||void 0===n?void 0:n[s.EventType.RoomPowerLevels])||100,l=r.users||{};switch(t){case u.Viewer:l[e]=o;break;case u.Editor:l[e]=a;break;case u.Owner:l[e]=c;break;default:throw new Error("Invalid role: "+t)}r.users=l,yield this.client.sendStateEvent(this.roomId,s.EventType.RoomPowerLevels,r,"")}))}getPermissions(e){var t,n;const i=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");const r=i.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,l=(null===(n=r.users)||void 0===n?void 0:n[e])||o;return l>=c?u.Owner:l>=a?u.Editor:u.Viewer}createDirectory(e){return i(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 n of t)try{const t=n.getStateKey();if(t){const n=this.client.unstableGetFileTreeSpace(t);n&&e.push(n)}}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 i(this,void 0,void 0,(function*(){const e=this.getDirectories();for(const t of e)yield t.delete();const t=["invite","knock","join"],n=this.room.currentState.getStateEvents(s.EventType.RoomMember);for(const e of n){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 n,i,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),l=this.client.getRoom(t.roomId);if(!a||!l)return(0,c.lexicographicCompare)(e.roomId,t.roomId);const d=null!==(i=null===(n=a.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===n?void 0:n.getTs())&&void 0!==i?i:0,u=null!==(o=null===(r=l.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===r?void 0:r.getTs())&&void 0!==o?o:0;return d===u?(0,c.lexicographicCompare)(e.roomId,t.roomId):d-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 n=this.client.getRoom(t);if(!n)throw new Error("Unable to locate room for parent");return n}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,n;return i(this,void 0,void 0,(function*(){if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const i=this.getParentRoom(),r=i.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 l=o[a?e:e-1],d=o[a?e+1:e];let u=c.DEFAULT_ALPHABET[0],h=!1;if(l)if(e===o.length-1)(null==d?void 0:d.order)&&(u=(0,c.nextString)(d.order));else{const e=null==l?void 0:l.order,t=null==d?void 0:d.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==d?void 0:d.order)&&(u=(0,c.prevString)(d.order));if(h){let n;for(let r=0;r<=e;r++){const e=o[r];if(0===r&&(n=e.order),e.order)n=e.order;else{n=n?(0,c.nextString)(n):c.DEFAULT_ALPHABET[0];const r=i.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(i.roomId,s.EventType.SpaceChild,Object.assign(Object.assign({},o),{order:n}),e.roomId)}}n&&(u=(0,c.nextString)(n))}const g=i.currentState.getStateEvents(s.EventType.SpaceChild,this.roomId),p=null!==(n=null==g?void 0:g.getContent())&&void 0!==n?n:{via:[this.client.getDomain()]};yield this.client.sendStateEvent(i.roomId,s.EventType.SpaceChild,Object.assign(Object.assign({},p),{order:u}),this.roomId)}))}createFile(e,t,n,r){return i(this,void 0,void 0,(function*(){const i=yield this.client.uploadContent(t,{includeFilename:!1,onlyContentUri:!0,rawResponse:!1});n.url=i;const o={msgtype:s.MsgType.File,body:e,url:i,file:n};(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 l.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 l.MSC3089Branch(this.client,e,this)))}}},{"../@types/event":72,"../crypto/algorithms/megolm":97,"../logger":126,"../utils":159,"./MSC3089Branch":128,"p-retry":56}],130:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.Beacon=n.getBeaconInfoIdentifier=n.isTimestampInDuration=n.BeaconEvent=void 0;const i=e("../@types/location"),r=e("../content-helpers"),o=e("../utils"),s=e("./typed-event-emitter");var a;!function(e){e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate"}(a=n.BeaconEvent||(n.BeaconEvent={}));n.isTimestampInDuration=(e,t,n)=>n>=e&&e+t>=n;n.getBeaconInfoIdentifier=e=>`${e.getRoomId()}_${e.getStateKey()}`;class c extends s.TypedEventEmitter{constructor(e){super(),this.rootEvent=e,this.clearLatestLocation=()=>{this._latestLocationState=void 0,this.emit(a.LocationUpdate,this.latestLocationState)},this.setBeaconInfo(this.rootEvent),this.roomId=this.rootEvent.getRoomId()}get isLive(){return this._isLive}get identifier(){return(0,n.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._latestLocationState}update(e){if((0,n.getBeaconInfoIdentifier)(e)!==this.identifier)throw new Error("Invalid updating event");e.event.origin_server_ts<this.rootEvent.event.origin_server_ts||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(a.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchInterval&&clearInterval(this.livenessWatchInterval),this._isLive=!1,this.emit(a.Destroy,this.identifier)}monitorLiveness(){var e,t;if(this.livenessWatchInterval&&clearInterval(this.livenessWatchInterval),this.checkLiveness(),this.isLive){const n=(null===(e=this._beaconInfo)||void 0===e?void 0:e.timestamp)+(null===(t=this._beaconInfo)||void 0===t?void 0:t.timeout)-Date.now();n>1&&(this.livenessWatchInterval=setInterval((()=>{this.monitorLiveness()}),n))}}addLocations(e){var t;if(!this.isLive)return;const s=null===(t=e.filter((e=>{const t=e.getContent(),r=i.M_TIMESTAMP.findIn(t);return(0,n.isTimestampInDuration)(this._beaconInfo.timestamp,this._beaconInfo.timeout,r)&&(!this.latestLocationState||r>this.latestLocationState.timestamp)})).sort(o.sortEventsByLatestContentTimestamp))||void 0===t?void 0:t[0];s&&(this._latestLocationState=(0,r.parseBeaconContent)(s.getContent()),this.emit(a.LocationUpdate,this.latestLocationState))}setBeaconInfo(e){this._beaconInfo=(0,r.parseBeaconInfoContent)(e.getContent()),this.checkLiveness()}checkLiveness(){var e,t,i;const r=this.isLive;this._isLive=(null===(e=this._beaconInfo)||void 0===e?void 0:e.live)&&(0,n.isTimestampInDuration)(null===(t=this._beaconInfo)||void 0===t?void 0:t.timestamp,null===(i=this._beaconInfo)||void 0===i?void 0:i.timeout,Date.now()),r!==this.isLive&&this.emit(a.LivenessChange,this.isLive,this)}}n.Beacon=c},{"../@types/location":74,"../content-helpers":85,"../utils":159,"./typed-event-emitter":143}],131:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.EventContext=void 0;const i=e("./event-timeline");n.EventContext=class{constructor(e){this.ourEvent=e,this.ourEventIndex=0,this.paginateTokens={[i.Direction.Backward]:null,[i.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?i.Direction.Backward:i.Direction.Forward]}setPaginateToken(e,t=!1){this.paginateTokens[t?i.Direction.Backward:i.Direction.Forward]=e}addEvents(e,t=!1){t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}},{"./event-timeline":134}],132:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.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"}(n.EventStatus||(n.EventStatus={}))},{}],133:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.EventTimelineSet=n.DuplicateStrategy=void 0;const i=e("./event-timeline"),r=e("./event"),o=e("../logger"),s=e("./relations"),a=e("./room"),c=e("./typed-event-emitter");let l;var d;l=o.logger.log.bind(o.logger),function(e){e.Ignore="ignore",e.Replace="replace"}(d=n.DuplicateStrategy||(n.DuplicateStrategy={}));class u extends c.TypedEventEmitter{constructor(e,t){super(),this.room=e,this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new i.EventTimeline(this),this.unstableClientRelationAggregation=!!t.unstableClientRelationAggregation,this.displayPendingEvents=!1!==t.pendingEvents,this.timelines=[this.liveTimeline],this._eventIdToTimeline={},this.filter=t.filter,this.unstableClientRelationAggregation&&(this.relations={})}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}eventIdToTimeline(e){return this._eventIdToTimeline[e]}replaceEventId(e,t){const n=this._eventIdToTimeline[e];n&&(delete this._eventIdToTimeline[e],this._eventIdToTimeline[t]=n)}resetLiveTimeline(e,t){const n=!this.timelineSupport||!t,r=this.liveTimeline,o=n?r.forkLive(i.EventTimeline.FORWARDS):r.fork(i.EventTimeline.FORWARDS);n?(this.timelines=[o],this._eventIdToTimeline={}):this.timelines.push(o),t&&r.setPaginationToken(t,i.EventTimeline.FORWARDS),o.setPaginationToken(e,i.EventTimeline.BACKWARDS),this.liveTimeline=o,this.emit(a.RoomEvent.TimelineReset,this.room,this,n)}getTimelineForEvent(e){const t=this._eventIdToTimeline[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 i.EventTimeline(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,n,r){if(!n)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&n==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?i.EventTimeline.BACKWARDS:i.EventTimeline.FORWARDS,a=t?i.EventTimeline.FORWARDS:i.EventTimeline.BACKWARDS;let c=!1,d=!1;for(let r=0;r<e.length;r++){const u=e[r],h=u.getId(),g=this._eventIdToTimeline[h];if(!g){this.addEventToTimeline(u,n,t),d=!0,c=!0;continue}if(d=!1,g==n){l("Event "+h+" already in timeline "+n);continue}const p=n.getNeighbouringTimeline(s);if(p){l(g==p?"Event "+h+" in neighbouring timeline - switching to "+g:"Event "+h+" already in a different timeline "+g),n=g;continue}o.logger.info("Already have timeline for "+h+" - joining timeline "+n+" to "+g);const f=g===this.liveTimeline,v=n===this.liveTimeline,y=s===i.EventTimeline.BACKWARDS&&f,m=s===i.EventTimeline.FORWARDS&&v;y||m?(y&&o.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+g+")"),m&&o.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+n+")")):(n.setNeighbouringTimeline(g,s),g.setNeighbouringTimeline(n,a),n=g,c=!0)}if(d||!c){if(s===i.EventTimeline.FORWARDS&&n===this.liveTimeline)return o.logger.warn({lastEventWasNew:d,didUpdate:c}),void o.logger.warn(`Refusing to set forwards pagination token of live timeline ${n} to ${r}`);n.setPaginationToken(r,s)}}addLiveEvent(e,t=d.Ignore,n=!1,r){if(this.filter){if(!this.filter.filterRoomTimeline([e]).length)return}const o=this._eventIdToTimeline[e.getId()];if(o)if(t===d.Replace){l("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());const t=o.getEvents();for(let n=0;n<t.length;n++)if(t[n].getId()===e.getId()){r||(r=o.getState(i.EventTimeline.FORWARDS)),i.EventTimeline.setEventMetadata(e,r,!1),t[n]=e;break}}else l("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this.liveTimeline,!1,n,r)}addEventToTimeline(e,t,n,i=!1,r){const o=e.getId();t.addEvent(e,n,r),this._eventIdToTimeline[o]=t,this.setRelationsTarget(e),this.aggregateRelations(e);const s={timeline:t,liveEvent:!n&&t==this.liveTimeline&&!i};this.emit(a.RoomEvent.Timeline,e,this.room,Boolean(n),!1,s)}handleRemoteEcho(e,t,n){const i=this._eventIdToTimeline[t];i?(delete this._eventIdToTimeline[t],this._eventIdToTimeline[n]=i):this.filter?this.filter.filterRoomTimeline([e]).length&&this.addEventToTimeline(e,this.liveTimeline,!1):this.addEventToTimeline(e,this.liveTimeline,!1)}removeEvent(e){const t=this._eventIdToTimeline[e];if(!t)return null;const n=t.removeEvent(e);if(n){delete this._eventIdToTimeline[e];const i={timeline:t};this.emit(a.RoomEvent.Timeline,n,this.room,void 0,!0,i)}return n}compareEventOrdering(e,t){if(e==t)return 0;const n=this._eventIdToTimeline[e],r=this._eventIdToTimeline[t];if(void 0===n)return null;if(void 0===r)return null;if(n===r){let i,r;const o=n.getEvents();for(let n=0;n<o.length&&(void 0===i||void 0===r);n++){const s=o[n].getId();s==e&&(i=n),s==t&&(r=n)}return i-r}let o=n;for(;o;){if(o===r)return-1;o=o.getNeighbouringTimeline(i.EventTimeline.FORWARDS)}for(o=n;o;){if(o===r)return 1;o=o.getNeighbouringTimeline(i.EventTimeline.BACKWARDS)}return null}getRelationsForEvent(e,t,n){if(!this.unstableClientRelationAggregation)throw new Error("Client-side relation aggregation is disabled");if(!e||!t||!n)throw new Error("Invalid arguments for `getRelationsForEvent`");return((this.relations[e]||{})[t]||{})[n]}getAllRelationsEventForEvent(e){var t;const n=(null===(t=this.relations)||void 0===t?void 0:t[e])||{},i=[];for(const e of Object.values(n))for(const t of Object.values(e))i.push(...t.getRelations());return i}setRelationsTarget(e){if(!this.unstableClientRelationAggregation)return;const t=this.relations[e.getId()];if(t)for(const n of Object.values(t))for(const t of Object.values(n))t.setTargetEvent(e)}aggregateRelations(e){if(!this.unstableClientRelationAggregation)return;if(e.isRedacted()||e.status===r.EventStatus.CANCELLED)return;const t=e=>{e.isDecryptionFailure()?e.once(r.MatrixEventEvent.Decrypted,t):this.aggregateRelations(e)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption())return void e.once(r.MatrixEventEvent.Decrypted,t);const n=e.getRelation();if(!n)return;const i=n.event_id,o=n.rel_type,a=e.getType();let c=this.relations[i];c||(c=this.relations[i]={});let l=c[o];l||(l=c[o]={});let d=l[a];if(!d){d=l[a]=new s.Relations(o,a,this.room);const e=this.findEventById(i)||this.room.getPendingEvent(i);e&&d.setTargetEvent(e)}d.addEvent(e)}}n.EventTimelineSet=u},{"../logger":126,"./event":135,"./event-timeline":134,"./relations":136,"./room":140,"./typed-event-emitter":143}],134:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.EventTimeline=n.Direction=void 0;const i=e("./room-state"),r=e("../@types/event");var o;!function(e){e.Backward="b",e.Forward="f"}(o=n.Direction||(n.Direction={}));class s{constructor(e){var t,n;this.eventTimelineSet=e,this.events=[],this.baseIndex=0,this.paginationRequests={[o.Backward]:null,[o.Forward]:null},this.roomId=null!==(n=null===(t=e.room)||void 0===t?void 0:t.roomId)&&void 0!==n?n:null,this.startState=new i.RoomState(this.roomId),this.startState.paginationToken=null,this.endState=new i.RoomState(this.roomId),this.endState.paginationToken=null,this.prevTimeline=null,this.nextTimeline=null,this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}static setEventMetadata(e,t,n){var i,o,s,a;(null===(o=null===(i=e.sender)||void 0===i?void 0:i.events)||void 0===o?void 0:o.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()!==r.EventType.RoomMember||(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}initialiseState(e){if(this.events.length>0)throw new Error("Cannot initialise state after events are added");for(const t of e)Object.freeze(t);this.startState.setStateEvents(e),this.endState.setStateEvents(e)}forkLive(e){const t=this.getState(e),n=new s(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t,this.endState=t.clone(),n}fork(e){const t=this.getState(e),n=new s(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t.clone(),n}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==s.BACKWARDS)return this.startState;if(e==s.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.getState(e).paginationToken}setPaginationToken(e,t){this.getState(t).paginationToken=e}getNeighbouringTimeline(e){if(e==s.BACKWARDS)return this.prevTimeline;if(e==s.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==s.BACKWARDS)this.prevTimeline=e;else{if(t!=s.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t,n){n||(n=t?this.startState:this.endState);const i=this.getTimelineSet();let r;i.room&&(s.setEventMetadata(e,n,t),e.isState()&&i.room.getUnfilteredTimelineSet()===i&&(n.setStateEvents([e]),e.sender&&("m.room.member"!==e.getType()||t)||s.setEventMetadata(e,n,t))),r=t?0:this.events.length,this.events.splice(r,0,e),t&&this.baseIndex++}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const n=this.events[t];if(n.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,n}return null}toString(){return this.name}}n.EventTimeline=s,s.BACKWARDS=o.Backward,s.FORWARDS=o.Forward},{"../@types/event":72,"./room-state":138}],135:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.MatrixEvent=n.MatrixEventEvent=n.EventStatus=void 0;const r=e("matrix-events-sdk"),o=e("../logger"),s=e("../@types/event"),a=e("../utils"),c=e("./thread"),l=e("../ReEmitter"),d=e("./typed-event-emitter");var u=e("./event-status");Object.defineProperty(n,"EventStatus",{enumerable:!0,get:function(){return u.EventStatus}});const h={};function g(e){return h[e]||(h[e]=e),h[e]}const p=Object.freeze({visible:!0});var f;!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"}(f=n.MatrixEventEvent||(n.MatrixEventEvent={}));class v extends d.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.txnId=null,this.thread=null,this.sender=null,this.target=null,this.status=null,this.error=null,this.forwardLooking=!0,this.verificationRequest=null,["state_key","type","sender","room_id","membership"].forEach((t=>{"string"==typeof e[t]&&(e[t]=g(e[t]))})),["membership","avatar_url","displayname"].forEach((t=>{var n;"string"==typeof(null===(n=e.content)||void 0===n?void 0:n[t])&&(e.content[t]=g(e.content[t]))})),["rel_type"].forEach((t=>{var n,i;"string"==typeof(null===(i=null===(n=e.content)||void 0===n?void 0:n["m.relates_to"])||void 0===i?void 0:i[t])&&(e.content["m.relates_to"][t]=g(e.content["m.relates_to"][t]))})),this.txnId=e.txn_id||null,this.localTimestamp=Date.now()-(null!==(t=this.getAge())&&void 0!==t?t:0),this.reEmitter=new l.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,n]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||void 0===e[t]&&(e[t]=n);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}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 n=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];return(null==n?void 0:n.rel_type)===c.THREAD_RELATION_TYPE.name?n.event_id:(null===(t=this.getThread())||void 0===t?void 0:t.id)||this.threadId}get isThreadRelation(){return!!this.threadRootId&&this.threadId!==this.getId()}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;const t=this.getContent()["m.relates_to"]||this.getWireContent()["m.relates_to"];return null===(e=null==t?void 0:t["m.in_reply_to"])||void 0===e?void 0:e.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,n,i){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=i}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)}shouldAttemptDecryption(){return!this.isRedacted()&&(!this.isBeingDecrypted()&&(!this.clearEvent&&!!this.isEncrypted()))}attemptDecryption(e,t={}){return i(this,void 0,void 0,(function*(){if("boolean"==typeof t&&(t={isRetry:t}),!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");if(this.clearEvent&&!this.isDecryptionFailure())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 n=this.getWireContent();return e.requestRoomKey({algorithm:n.algorithm,room_id:this.getRoomId(),session_id:n.session_id,sender_key:n.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){const t=this.getWireContent(),n=[{userId:e,deviceId:"*"}],i=this.getSender();return i!==e&&n.push({userId:i,deviceId:t.device_id}),n}decryptionLoop(e,t={}){return i(this,void 0,void 0,(function*(){for(yield Promise.resolve();;){let n,i;this.retryDecryption=!1;try{e?(n=yield e.decryptEvent(this),!0===t.isRetry&&o.logger.info(`Decrypted event on retry (id=${this.getId()})`)):n=this.badEncryptedMessage("Encryption not enabled")}catch(e){if("DecryptionError"!==e.name){const n=t.isRetry?"re":"";return o.logger.error(`Error ${n}decrypting event (id=${this.getId()}): ${e.stack||e}`),this._decryptionPromise=null,void(this.retryDecryption=!1)}if(i=e,this.retryDecryption){o.logger.log(`Got error decrypting event (id=${this.getId()}: ${e}), but retrying`);continue}o.logger.warn(`Error decrypting event (id=${this.getId()}): ${e.detailedString}`),n=this.badEncryptedMessage(e.message)}return this._decryptionPromise=null,this.retryDecryption=!1,this.setClearData(n),this.setPushActions(null),void(!1!==t.emit&&this.emit(f.Decrypted,this,i))}}))}badEncryptedMessage(e){return{clearEvent:{type:s.EventType.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}}}}setClearData(e){this.clearEvent=e.clearEvent,this.senderCurve25519Key=e.senderCurve25519Key||null,this.claimedEd25519Key=e.claimedEd25519Key||null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!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{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=null),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(f.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){const t=!e||e.visible,n=e?e.reason:null;let i=!1;this.visibility.visible!==e.visible?i=!0:this.visibility.visible||this.visibility.reason===n||(i=!0),i&&(this.visibility=t?p:Object.freeze({visible:!1,reason:n}),this.emit(f.VisibilityChange,this,t))}messageVisibility(){return this.visibility}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(f.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)&&!y.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=null);const t=m[this.getType()]||{},n=this.getContent();for(const e in n)n.hasOwnProperty(e)&&!t[e]&&delete n[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 n=this.getWireContent(),i=!!n.visible,r=n.reason;return r&&"string"!=typeof r?null:{visible:i,reason:r,eventId:t}}isVisibilityEvent(){return s.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())}getRedactionEvent(){var e,t;return this.isRedacted()?(null===(e=this.clearEvent)||void 0===e?void 0:e.unsigned)?null===(t=this.clearEvent)||void 0===t?void 0:t.unsigned.redacted_because:this.event.unsigned.redacted_because?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),n=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()!==n&&this.emit(f.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(f.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(f.LocalEventIdReplaced,this)}isRelation(e){var t;const n=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return(!this.isState()||(null==n?void 0:n.rel_type)!==s.RelationType.Replace)&&((null==n?void 0:n.rel_type)&&n.event_id&&(!e||n.rel_type===e))}getRelation(){return this.isRelation()?this.getWireContent()["m.relates_to"]:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=e,this.emit(f.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(){const e=this.getServerAggregatedRelation(s.RelationType.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent)return this._replacingEvent.getDate()}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()}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,n]of Object.entries(this))"event"!==t&&(e[t]=n);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=(0,a.deepSortedObjectEntries)(this.event),n=(0,a.deepSortedObjectEntries)(e.event);return JSON.stringify(t)===JSON.stringify(n)}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=e,this.setThreadId(e.id),this.reEmitter.reEmit(e,[c.ThreadEvent.Update])}getThread(){return this.thread}setThreadId(e){this.threadId=e}}n.MatrixEvent=v;const y=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),m={[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},[s.EventType.RoomAliases]:{aliases:1}}},{"../@types/event":72,"../ReEmitter":81,"../logger":126,"../utils":159,"./event-status":132,"./thread":142,"./typed-event-emitter":143,"matrix-events-sdk":48}],136:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.Relations=n.RelationsEvent=void 0;const r=e("./event"),o=e("../logger"),s=e("../@types/event"),a=e("./typed-event-emitter");var c;!function(e){e.Add="Relations.add",e.Remove="Relations.remove",e.Redaction="Relations.redaction"}(c=n.RelationsEvent||(n.RelationsEvent={}));class l extends a.TypedEventEmitter{constructor(e,t,n){super(),this.relationType=e,this.eventType=t,this.room=n,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=>i(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(c.Redaction,e)}}))}addEvent(e){return i(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 n=t.rel_type,i=e.getType();if(this.relationType===n&&this.eventType===i){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(c.Add,e),this.maybeEmitCreated()}else o.logger.error("Event relation info doesn't match this container")}))}removeEvent(e){return i(this,void 0,void 0,(function*(){if(!this.relations.has(e))return;const t=e.getRelation();if(!t)return void o.logger.error("Event must have relation info");const n=t.rel_type,i=e.getType();if(this.relationType===n&&this.eventType===i){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(c.Remove,e)}else o.logger.error("Event relation info doesn't match this container")}))}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){const{key:t}=e.getRelation();if(!t)return;let n=this.annotationsByKey[t];n||(n=this.annotationsByKey[t]=new Set,this.sortedAnnotationsByKey.push([t,n])),n.add(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const n=e[1];return t[1].size-n.size}));const i=e.getSender();let r=this.annotationsBySender[i];r||(r=this.annotationsBySender[i]=new Set),r.add(e)}removeAnnotationFromAggregation(e){const{key:t}=e.getRelation();if(!t)return;const n=this.annotationsByKey[t];n&&(n.delete(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const n=e[1];return t[1].size-n.size})));const i=e.getSender(),r=this.annotationsBySender[i];r&&r.delete(e)}getSortedAnnotationsByKey(){return this.relationType!==s.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==s.RelationType.Annotation?null:this.annotationsBySender}getLastReplacement(){return i(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,n=this.getRelations().reduce(((e,n)=>n.getSender()!==this.targetEvent.getSender()||t&&t>n.getTs()||e&&e.getTs()>n.getTs()?e:n),null);return(null==n?void 0:n.shouldAttemptDecryption())?yield n.attemptDecryption(this.room.client.crypto):(null==n?void 0:n.isBeingDecrypted())&&(yield n.getDecryptionPromise()),n}))}setTargetEvent(e){return i(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))}}n.Relations=l},{"../@types/event":72,"../logger":126,"./event":135,"./typed-event-emitter":143}],137:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.RoomMember=n.RoomMemberEvent=void 0;const s=e("../content-repo"),a=o(e("../utils")),c=e("../logger"),l=e("./typed-event-emitter"),d=e("../@types/event");var u;!function(e){e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing"}(u=n.RoomMemberEvent||(n.RoomMemberEvent={}));class h extends l.TypedEventEmitter{constructor(e,t){super(),this.roomId=e,this.userId=t,this._isOutOfBand=!1,this.typing=!1,this.powerLevel=0,this.powerLevelNorm=0,this.user=null,this.membership=null,this.disambiguate=!1,this.events={member:null},this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){const n=e.getDirectionalContent().displayname;if(e.getType()!==d.EventType.RoomMember)return;this._isOutOfBand=!1,this.events.member=e;const i=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,n){if(!t||t===e)return!1;if(!a.removeHiddenChars(t))return!1;if(!n)return!1;if(g.test(t))return!0;if(p.test(t))return!0;return!!n.getUserIdsWithDisplayName(t).some((t=>t!==e))}(this.userId,n,t);const r=this.name;this.name=function(e,t,n,i){return i?a.removeDirectionOverrideChars(t)+" ("+e+")":t&&t!==e&&a.removeHiddenChars(t)?a.removeDirectionOverrideChars(t):e}(this.userId,n,0,this.disambiguate),this.rawDisplayName=a.removeDirectionOverrideChars(e.getDirectionalContent().displayname),this.rawDisplayName&&a.removeHiddenChars(this.rawDisplayName)||(this.rawDisplayName=this.userId),i!==this.membership&&(this.updateModifiedTime(),this.emit(u.Membership,e,this,i)),r!==this.name&&(this.updateModifiedTime(),this.emit(u.Name,e,this,r))}setPowerLevelEvent(e){if("m.room.power_levels"!==e.getType())return;const t=e.getDirectionalContent();let n=t.users_default||0;const i=t.users||{};Object.values(i).forEach((function(e){n=Math.max(n,e)}));const r=this.powerLevel,o=this.powerLevelNorm;void 0!==i[this.userId]&&Number.isInteger(i[this.userId])?this.powerLevel=i[this.userId]:void 0!==t.users_default?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,n>0&&(this.powerLevelNorm=100*this.powerLevel/n),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 n=e.getContent().user_ids;Array.isArray(n)&&(-1!==n.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&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),n=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),n=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return n}}getAvatarUrl(e,t,n,i,r=!0,o){const a=this.getMxcAvatarUrl();if(!a&&!r)return null;const c=(0,s.getHttpUriForMxc)(e,a,t,n,i,o);return c||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:null}}n.RoomMember=h;const g=/@.+:.+/,p=/[\u200E\u200F\u202A-\u202F]/},{"../@types/event":72,"../content-repo":86,"../logger":126,"../utils":159,"./typed-event-emitter":143}],138:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.RoomState=n.RoomStateEvent=void 0;const a=e("./room-member"),c=e("../logger"),l=o(e("../utils")),d=e("../@types/event"),u=e("./event"),h=e("../@types/partials"),g=e("./typed-event-emitter"),p=e("./beacon"),f=e("../ReEmitter"),v=e("../@types/beacon");var y,m;!function(e){e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished"}(y||(y={})),function(e){e.Events="RoomState.events",e.Members="RoomState.members",e.NewMember="RoomState.newMember",e.Update="RoomState.update",e.BeaconLiveness="RoomState.BeaconLiveness"}(m=n.RoomStateEvent||(n.RoomStateEvent={}));class E extends g.TypedEventEmitter{constructor(e,t={status:y.NotStarted}){super(),this.roomId=e,this.oobMemberFlags=t,this.reEmitter=new f.TypedReEmitter(this),this.sentinels={},this.displayNameToUserIds={},this.userIdsToDisplayNames={},this.tokenToInvite={},this.joinedMemberCount=null,this.summaryJoinedMemberCount=null,this.invitedMemberCount=null,this.summaryInvitedMemberCount=null,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 n=this.members[e];n&&t.setMembershipEvent(n.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 n=this.events.get(e).get(t);return n||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 E(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=y.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==y.Finished&&this.getMembers().forEach((t=>{if(t.isOutOfBand()){e.getMember(t.userId).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){this.updateModifiedTime(),e.forEach((e=>{if(e.getRoomId()!==this.roomId)return;if(!e.isState())return;v.M_BEACON_INFO.matches(e.getType())&&this.setBeacon(e);const t=this.getStateEventMatching(e);this.setStateEvent(e),e.getType()===d.EventType.RoomMember&&(this.updateDisplayNameCache(e.getStateKey(),e.getContent().displayname),this.updateThirdPartyTokenCache(e)),this.emit(m.Events,e,this,t)})),this.onBeaconLivenessChange(),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===d.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 n=this.getOrCreateMember(t,e);n.setMembershipEvent(e,this),this.updateMember(n),this.emit(m.Members,e,this,n)}else if(e.getType()===d.EventType.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const n=t.getLastModifiedTime();t.setPowerLevelEvent(e),n!==t.getLastModifiedTime()&&this.emit(m.Members,e,this,t)})),this.sentinels={}}})),this.emit(m.Update,this)}processBeaconEvents(e,t){if(!e.length||!this.beacons.size)return;const n=[...this.beacons.values()].reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.beaconInfoId]:t})),{}),i=(e,t)=>{if(!v.M_BEACON.matches(t.getType()))return;const i=n[e];i&&i.addLocations([t])};e.forEach((e=>{var r;const o=null===(r=e.getRelation())||void 0===r?void 0:r.event_id;n[o]&&(t.decryptEventIfNeeded(e),e.isBeingDecrypted()||e.isDecryptionFailure()?e.once(u.MatrixEventEvent.Decrypted,(()=>s(this,void 0,void 0,(function*(){i(o,e)})))):i(o,e))}))}getOrCreateMember(e,t){let n=this.members[e];return n||(n=new a.RoomMember(this.roomId,e),this.members[e]=n,this.emit(m.NewMember,t,this,n)),n}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 n=(0,p.getBeaconInfoIdentifier)(e);if(this.beacons.has(n)){const i=this.beacons.get(n);return e.isRedacted()?void(i.beaconInfoId===(null===(t=e.getRedactionEvent())||void 0===t?void 0:t.redacts)&&(i.destroy(),this.beacons.delete(n))):i.update(e)}if(e.isRedacted())return;const i=new p.Beacon(e);this.reEmitter.reEmit(i,[p.BeaconEvent.New,p.BeaconEvent.Update,p.BeaconEvent.Destroy,p.BeaconEvent.LivenessChange]),this.emit(p.BeaconEvent.New,e,i),i.on(p.BeaconEvent.LivenessChange,this.onBeaconLivenessChange.bind(this)),i.on(p.BeaconEvent.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(i.identifier,i)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter((e=>e.isLive)).map((e=>e.identifier)),this.emit(m.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,n;return null!==(n=null===(t=this.events.get(e.getType()))||void 0===t?void 0:t.get(e.getStateKey()))&&void 0!==n?n:null}updateMember(e){const t=this.getStateEvents(d.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===y.NotStarted}markOutOfBandMembersStarted(){this.oobMemberFlags.status===y.NotStarted&&(this.oobMemberFlags.status=y.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===y.InProgress&&(this.oobMemberFlags.status=y.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=y.NotStarted}setOutOfBandMembers(e){c.logger.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===y.InProgress&&(c.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=y.Finished,e.forEach((e=>this.setOutOfBandMember(e))),this.emit(m.Update,this))}setOutOfBandMember(e){if(e.getType()!==d.EventType.RoomMember)return;const t=e.getStateKey(),n=this.getMember(t);if(n&&!n.isOutOfBand())return;const i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),i.markOutOfBand(),this.updateDisplayNameCache(i.userId,i.name),this.setStateEvent(e),this.updateMember(i),this.emit(m.Members,e,this,i)}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){return this.displayNameToUserIds[l.removeHiddenChars(e)]||[]}maySendRedactionForEvent(e,t){const n=this.getMember(t);if(!n||"leave"===n.membership)return!1;if(e.status||e.isRedacted())return!1;const i=this.maySendEvent(d.EventType.RoomRedaction,t);return e.getSender()===t?i:this.hasSufficientPowerLevelFor("redact",n.powerLevel)}hasSufficientPowerLevelFor(e,t){const n=this.getStateEvents(d.EventType.RoomPowerLevels,"");let i={};n&&(i=n.getContent());let r=50;return l.isNumber(i[e])&&(r=i[e]),t>=r}maySendMessage(e){return this.maySendEventOfType(d.EventType.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!t.isGuest()&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){const i=this.getStateEvents(d.EventType.RoomPowerLevels,"");let r,o={},s=0,a=0,c=0;if(i){r=i.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 l=n?s:a;return Number.isSafeInteger(o[e])&&(l=o[e]),c>=l}mayTriggerNotifOfType(e,t){const n=this.getMember(t);if(!n)return!1;const i=this.getStateEvents(d.EventType.RoomPowerLevels,"");let r=50;return i&&i.getContent()&&i.getContent().notifications&&l.isNumber(i.getContent().notifications[e])&&(r=i.getContent().notifications[e]),n.powerLevel>=r}getJoinRule(){var e;const t=this.getStateEvents(d.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(d.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(d.EventType.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||h.GuestAccess.Forbidden}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;if(!t)return;this.getStateEvents(d.EventType.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=l.removeHiddenChars(n),i=this.displayNameToUserIds[t];if(i){const n=i.filter((t=>t!==e));this.displayNameToUserIds[t]=n}}this.userIdsToDisplayNames[e]=t;const i=t&&l.removeHiddenChars(t);i&&(this.displayNameToUserIds[i]||(this.displayNameToUserIds[i]=[]),this.displayNameToUserIds[i].push(e))}}n.RoomState=E},{"../@types/beacon":71,"../@types/event":72,"../@types/partials":75,"../ReEmitter":81,"../logger":126,"../utils":159,"./beacon":130,"./event":135,"./room-member":137,"./typed-event-emitter":143}],139:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.RoomSummary=void 0;n.RoomSummary=class{constructor(e,t){this.roomId=e}}},{}],140:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.Room=n.RoomEvent=n.NotificationCountType=void 0;const a=e("./event-timeline-set"),c=e("./event-timeline"),l=e("../content-repo"),d=o(e("../utils")),u=e("../utils"),h=e("./event"),g=e("./event-status"),p=e("./room-member"),f=e("./room-summary"),v=e("../logger"),y=e("../ReEmitter"),m=e("../@types/event"),E=e("../client"),S=e("../filter"),b=e("./thread"),_=e("./typed-event-emitter"),T=e("../@types/read_receipts"),w=["1","2","3","4","5","6","7","8","9"];function I(e,t,n){return new h.MatrixEvent({content:{[t.getId()]:{[n]:{[e]:{ts:t.getTs()}}}},type:"m.receipt",room_id:t.getRoomId()})}var R,k;!function(e){e.Highlight="highlight",e.Total="total"}(R=n.NotificationCountType||(n.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"}(k=n.RoomEvent||(n.RoomEvent={}));class O extends _.TypedEventEmitter{constructor(e,t,n,i={}){if(super(),this.roomId=e,this.client=t,this.myUserId=n,this.opts=i,this.txnToEvent={},this.receipts={},this.receiptCacheByEventId={},this.notificationCounts={},this.threadsTimelineSets=[],this.filteredTimelineSets={},this.blacklistUnverifiedDevices=null,this.selfMembership=null,this.summaryHeroes=null,this.getTypeWarning=!1,this.getVersionWarning=!1,this.tags={},this.accountData={},this.summary=null,this.threads=new Map,this.visibilityEvents=new Map,this.threadTimelineSetsPromise=null,this.threadsReady=!1,this.applyRedaction=e=>{if(e.isRedaction()){const t=e.event.redacts,n=this.findEventById(t);if(n){if(n.makeRedacted(e),n.isState()){this.currentState.getStateEvents(n.getType(),n.getStateKey()).getId()===n.getId()&&this.currentState.setStateEvents([n])}this.emit(k.Redaction,e,this),this.visibilityEvents.delete(t),n.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e)}}},this.setMaxListeners(100),this.reEmitter=new y.TypedReEmitter(this),i.pendingEventOrdering=i.pendingEventOrdering||E.PendingEventOrdering.Chronological,this.name=e,this.timelineSets=[new a.EventTimelineSet(this,i)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[k.Timeline,k.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===E.PendingEventOrdering.Detached){this.pendingEventList=[];const e=t.sessionStore.store.getItem(C(this.roomId));e&&JSON.parse(e).forEach((e=>s(this,void 0,void 0,(function*(){const t=new h.MatrixEvent(e);t.getType()===m.EventType.RoomMessageEncrypted&&(yield t.attemptDecryption(this.client.crypto)),t.setStatus(g.EventStatus.NOT_SENT),this.addPendingEvent(t,t.getTxnId())}))))}this.opts.lazyLoadMembers?this.membersPromise=null: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.supportsExperimentalThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(b.ThreadFilterType.My)]);const e=yield this.threadTimelineSetsPromise;this.threadsTimelineSets.push(...e)}catch(e){this.threadTimelineSetsPromise=null}}))}decryptCriticalEvents(){const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),n=t.findIndex((t=>t.event.event_id===e)),i=t.slice(n).filter((e=>e.shouldAttemptDecryption())).reverse().map((e=>e.attemptDecryption(this.client.crypto,{isRetry:!0})));return Promise.allSettled(i)}decryptAllEvents(){const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter((e=>e.shouldAttemptDecryption())).reverse().map((e=>e.attemptDecryption(this.client.crypto,{isRetry:!0})));return Promise.allSettled(e)}getVersion(){const e=this.currentState.getStateEvents(m.EventType.RoomCreate,"");if(!e)return this.getVersionWarning||(v.logger.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1";const t=e.getContent().room_version;return void 0===t?"1":t}shouldUpgradeToVersion(){return w.includes(this.getVersion())?null:"9"}getRecommendedVersion(){return s(this,void 0,void 0,(function*(){let e=(yield this.client.getCapabilities())["m.room_versions"];if(!e){e={default:"9",available:{}};for(const t of w)e.available[t]=E.RoomVersionStability.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){v.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 v.logger.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}))}checkVersionAgainstCapability(e){const t=this.getVersion();v.logger.log(`[${this.roomId}] Current version: ${t}`),v.logger.log(`[${this.roomId}] Version capability: `,e);const n={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return n;return Object.keys(e.available).filter((t=>"stable"===e.available[t])).includes(t)||(n.version=e.default,n.needsUpgrade=!0,n.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),n.urgent?v.logger.warn(`URGENT upgrade required on ${this.roomId}`):v.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(m.EventType.RoomTombstone,e)}getPendingEvents(){if(this.opts.pendingEventOrdering!==E.PendingEventOrdering.Detached)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(this.opts.pendingEventOrdering!==E.PendingEventOrdering.Detached)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=d.removeElement(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){return this.opts.pendingEventOrdering===E.PendingEventOrdering.Detached&&this.pendingEventList.some((t=>t.getId()===e))}getPendingEvent(e){return this.opts.pendingEventOrdering!==E.PendingEventOrdering.Detached?null:this.pendingEventList.find((t=>t.getId()===e))}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(){return this.selfMembership}getDMInviter(){if(this.myUserId){const e=this.getMember(this.myUserId);if(e)return e.getDMInviter()}if("invite"===this.selfMembership){if(2==this.getInvitedAndJoinedMemberCount()&&this.summaryHeroes.length)return this.summaryHeroes[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 p.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(k.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",e)).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(),v.logger.log(`LL: got ${t.length} members from server for room ${this.roomId}`));return{memberEvents:t.map(this.client.getEventMapper()),fromServer:e}}))}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then((e=>(this.currentState.setOutOfBandMembers(e.memberEvents),this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId)&&this.client.crypto.trackRoomDevices(this.roomId),e.fromServer))).catch((e=>{throw this.membersPromise=null,this.currentState.markOutOfBandMembersFailed(),e}));return e.then((e=>{if(e){const e=this.currentState.getMembers().filter((e=>e.isOutOfBand())).map((e=>e.events.member.event));v.logger.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{v.logger.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{v.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=null)}))}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch((e=>{v.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),v.logger.log(e)}))}resetLiveTimeline(e,t){for(let n=0;n<this.timelineSets.length;n++)this.timelineSets[n].resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(c.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(c.EventTimeline.FORWARDS)}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),n=this.findThreadForEvent(t);return n?n.timelineSet.getLiveTimeline():this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const n=this.getThreads();for(let i=0;i<n.length;i++){if(t=n[i].findEventById(e),t)return t}}return t}getUnreadNotificationCount(e=R.Total){return this.notificationCounts[e]}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t}setSummary(e){const t=e["m.heroes"],n=e["m.joined_member_count"],i=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(i)&&this.currentState.setInvitedMemberCount(i),Array.isArray(t)&&(this.summaryHeroes=t.filter((e=>e!==this.myUserId)))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,i,r=!0){const o=this.currentState.getStateEvents(m.EventType.RoomAvatar,"");if(!o&&!r)return null;const s=o?o.getContent().url:null;return s?(0,l.getHttpUriForMxc)(e,s,t,n,i):null}getMxcAvatarUrl(){var e,t;return(null===(t=null===(e=this.currentState.getStateEvents(m.EventType.RoomAvatar,""))||void 0===e?void 0:e.getContent())||void 0===t?void 0:t.url)||null}getAliases(){const e=[],t=this.currentState.getStateEvents(m.EventType.RoomAliases);if(t)for(const n of t)if(Array.isArray(n.getContent().aliases)){const t=n.getContent().aliases.filter((e=>"string"==typeof e&&("#"===e[0]&&!!e.endsWith(`:${n.getStateKey()}`))));e.push(...t)}return e}getCanonicalAlias(){const e=this.currentState.getStateEvents(m.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(m.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,n,i){n.getTimelineSet().addEventsToTimeline(e,t,n,i)}getThread(e){return this.threads.get(e)}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(m.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 n=this.getMember(e);return!!n&&n.membership===t}getOrCreateFilteredTimelineSet(e,{prepopulateTimeline:t=!0,useSyncEvents:n=!0,pendingEvents:i=!0}={}){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const r=Object.assign({filter:e,pendingEvents:i},this.opts),o=new a.EventTimelineSet(this,r);this.reEmitter.reEmit(o,[k.Timeline,k.TimelineReset]),n&&(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(c.EventTimeline.BACKWARDS);)e=e.getNeighbouringTimeline(c.EventTimeline.BACKWARDS);o.getLiveTimeline().setPaginationToken(e.getPaginationToken(c.EventTimeline.BACKWARDS),c.EventTimeline.BACKWARDS)}else if(n){const e=s.getPaginationToken(c.Direction.Forward);o.getLiveTimeline().setPaginationToken(e,c.Direction.Backward)}return o}getThreadListFilter(e=b.ThreadFilterType.All){return s(this,void 0,void 0,(function*(){const t=this.client.getUserId(),n=new S.Filter(t),i={room:{timeline:{[b.FILTER_RELATED_BY_REL_TYPES.name]:[b.THREAD_RELATION_TYPE.name]}}};e===b.ThreadFilterType.My&&(i.room.timeline[b.FILTER_RELATED_BY_SENDERS.name]=[t]),n.setDefinition(i);const r=yield this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,n);return n.filterId=r,n}))}createThreadTimelineSet(e){return s(this,void 0,void 0,(function*(){let t;if(b.Thread.hasServerSideSupport){const n=yield this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(n,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new a.EventTimelineSet(this,{pendingEvents:!1}),Array.from(this.threads).forEach((([,n])=>{if(0===n.length)return;const i=n.events.some((e=>e.getSender()===this.client.getUserId()));(e!==b.ThreadFilterType.My||i)&&t.getLiveTimeline().addEvent(n.rootEvent,!1)}));return t}))}fetchRoomThreads(){return s(this,void 0,void 0,(function*(){if(this.threadsReady||!this.client.supportsExperimentalThreads())return;const e=yield this.getThreadListFilter(),{chunk:t}=yield this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,c.Direction.Backward,e);if(!t.length)return;const n=t.map(this.client.getEventMapper()).sort(((e,t)=>{const n=e.getServerAggregatedRelation(m.RelationType.Thread),i=t.getServerAggregatedRelation(m.RelationType.Thread);return n.latest_event.origin_server_ts-i.latest_event.origin_server_ts}));let i;const r=this.getLiveTimeline().getState(c.EventTimeline.FORWARDS);for(const e of n){this.threadsTimelineSets[0].addLiveEvent(e,a.DuplicateStrategy.Ignore,!1,r);e.getServerAggregatedRelation(m.RelationType.Thread).current_user_participated&&(this.threadsTimelineSets[1].addLiveEvent(e,a.DuplicateStrategy.Ignore,!1,r),i=e),this.getThread(e.getId())||this.createThread(e.getId(),e,[],!0)}this.client.decryptEventIfNeeded(n[n.length-1]),i&&this.client.decryptEventIfNeeded(i),this.threadsReady=!0,this.on(b.ThreadEvent.NewReply,this.onThreadNewReply)}))}onThreadNewReply(e){for(const t of this.threadsTimelineSets)t.removeEvent(e.id),t.addLiveEvent(e.rootEvent)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}eventShouldLiveIn(e,t,n){var i;if(!this.client.supportsExperimentalThreads())return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||(null==n?void 0:n.has(e.getId())))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};if(e.isThreadRelation)return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:e.threadRootId};const r=e.getAssociatedId(),o=null!==(i=this.findEventById(r))&&void 0!==i?i:null==t?void 0:t.find((e=>e.getId()===r));return o&&(e.isRelation()||e.isRedaction())?this.eventShouldLiveIn(o,t,n):(null==n?void 0:n.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,n=!1){var i;let r=this.getThread(e);if(r)r.addEvents(t,n);else{const o=null!==(i=this.findEventById(e))&&void 0!==i?i:t.find((t=>t.getId()===e));r=this.createThread(e,o,t,n),this.emit(b.ThreadEvent.Update,r)}}processThreadedEvents(e,t){var n;e.forEach(this.applyRedaction);const i={};for(const t of e){const{threadId:e,shouldLiveInThread:r}=this.eventShouldLiveIn(t);r&&!i[e]&&(i[e]=[]),null===(n=i[e])||void 0===n||n.push(t)}Object.entries(i).map((([e,n])=>this.addThreadedEvents(e,n,t)))}createThread(e,t,n=[],i){var r;if(t){const e=this.getTimelineForEvent(t.getId()),i=null==e?void 0:e.getTimelineSet().getAllRelationsEventForEvent(t.getId());(null==i?void 0:i.length)&&(n=n.concat(i.filter((e=>!e.isRelation(m.RelationType.Replace)))))}const o=new b.Thread(e,t,{initialEvents:n,room:this,client:this.client});return this.threads.set(o.id,o),this.reEmitter.reEmit(o,[b.ThreadEvent.Update,b.ThreadEvent.NewReply,k.Timeline,k.TimelineReset]),(!this.lastThread||(null===(r=this.lastThread.rootEvent)||void 0===r?void 0:r.localTimestamp)<(null==t?void 0:t.localTimestamp))&&(this.lastThread=o),this.emit(b.ThreadEvent.New,o,i),this.threadsReady&&this.threadsTimelineSets.forEach((e=>{o.rootEvent&&(b.Thread.hasServerSideSupport?e.addLiveEvent(o.rootEvent):e.addEventToTimeline(o.rootEvent,e.getLiveTimeline(),i))})),o}processLiveEvent(e){if(this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e),e.getUnsigned().transaction_id){const t=this.txnToEvent[e.getUnsigned().transaction_id];t&&this.handleRemoteEcho(e,t)}}addLiveEvent(e,t,n=!1){for(let i=0;i<this.timelineSets.length;i++)this.timelineSets[i].addLiveEvent(e,t,n);e.sender&&e.getType()!==m.EventType.RoomRedaction&&this.addReceipt(I(e.sender.userId,e,T.ReceiptType.Read),!0)}addPendingEvent(e,t){var n;if(e.status!==g.EventStatus.SENDING&&e.status!==g.EventStatus.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent[t])throw new Error("addPendingEvent called on an event with known txnId "+t);if(c.EventTimeline.setEventMetadata(e,this.getLiveTimeline().getState(c.EventTimeline.FORWARDS),!1),this.txnToEvent[t]=e,this.opts.pendingEventOrdering===E.PendingEventOrdering.Detached){if(this.pendingEventList.some((e=>e.status===g.EventStatus.NOT_SENT))&&(v.logger.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(g.EventStatus.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let i=null===(n=this.pendingEventList)||void 0===n?void 0:n.find((e=>e.getId()===t));i||(i=this.findEventById(t)),i&&(i.markLocallyRedacted(e),this.emit(k.Redaction,e,this))}}else for(let t=0;t<this.timelineSets.length;t++){const n=this.timelineSets[t];n.getFilter()?n.getFilter().filterRoomTimeline([e]).length&&n.addEventToTimeline(e,n.getLiveTimeline(),!1):n.addEventToTimeline(e,n.getLiveTimeline(),!1)}this.emit(k.LocalEchoUpdated,e,this,null,null)}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===m.EventType.RoomMessageEncrypted,n=this.client.isRoomEncrypted(this.roomId);return t||!n})),{store:t}=this.client.sessionStore;this.pendingEventList.length>0?t.setItem(C(this.roomId),JSON.stringify(e)):t.removeItem(C(this.roomId))}}aggregateNonLiveRelation(e){const{shouldLiveInRoom:t,threadId:n}=this.eventShouldLiveIn(e),i=this.getThread(n);if(null==i||i.timelineSet.aggregateRelations(e),t)for(let t=0;t<this.timelineSets.length;t++){const n=this.timelineSets[t];n.getFilter()?n.getFilter().filterRoomTimeline([e]).length&&n.aggregateRelations(e):n.aggregateRelations(e)}}getEventForTxnId(e){return this.txnToEvent[e]}handleRemoteEcho(e,t){const n=t.getId(),i=e.getId(),r=t.status;v.logger.debug(`Got remote echo for event ${n} -> ${i} old status ${r}`),delete this.txnToEvent[e.getUnsigned().transaction_id],this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:o,threadId:s}=this.eventShouldLiveIn(e),a=this.getThread(s);if(null==a||a.timelineSet.handleRemoteEcho(t,n,i),o)for(let e=0;e<this.timelineSets.length;e++){this.timelineSets[e].handleRemoteEcho(t,n,i)}this.emit(k.LocalEchoUpdated,t,this,n,r)}updatePendingEvent(e,t,n){if(v.logger.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${n}`),t==g.EventStatus.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==g.EventStatus.SENT){if(this.getTimelineForEvent(n))return}const i=e.status,r=e.getId();if(!i)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const o=P[i];if(!o||o.indexOf(t)<0)throw new Error("Invalid EventStatus transition "+i+"->"+t);if(e.setStatus(t),t==g.EventStatus.SENT){e.replaceLocalEventId(n);const{shouldLiveInRoom:t,threadId:i}=this.eventShouldLiveIn(e),o=this.getThread(i);if(null==o||o.timelineSet.replaceEventId(r,n),t)for(let e=0;e<this.timelineSets.length;e++)this.timelineSets[e].replaceEventId(r,n)}else if(t==g.EventStatus.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(r);this.removePendingEvent(r),e.isRedaction()&&this.revertRedactionLocalEcho(e)}this.removeEvent(r)}this.savePendingEvents(),this.emit(k.LocalEchoUpdated,e,this,r,i)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit(k.RedactionCancelled,e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}addLiveEvents(e,t,n=!1){var i;if(t&&-1===["replace","ignore"].indexOf(t))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(c.EventTimeline.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(c.EventTimeline.FORWARDS)+")");if(t.getNeighbouringTimeline(c.EventTimeline.FORWARDS))throw new Error(`live timeline ${e} is no longer live - it has a neighbouring timeline`)}const r=this.findThreadRoots(e),o={};for(const s of e){this.processLiveEvent(s);const{shouldLiveInRoom:a,shouldLiveInThread:c,threadId:l}=this.eventShouldLiveIn(s,e,r);c&&!o[l]&&(o[l]=[]),null===(i=o[l])||void 0===i||i.push(s),a&&this.addLiveEvent(s,t,n)}Object.entries(o).forEach((([e,t])=>{this.addThreadedEvents(e,t,!1)}))}partitionThreadedEvents(e){if(this.client.supportsExperimentalThreads()){const t=this.findThreadRoots(e);return e.reduce(((n,i)=>{const{shouldLiveInRoom:r,shouldLiveInThread:o,threadId:s}=this.eventShouldLiveIn(i,e,t);return r&&n[0].push(i),o&&(i.setThreadId(s),n[1].push(i)),n}),[[],[]])}return[e,[]]}findThreadRoots(e){const t=new Set;for(const n of e)n.isThreadRelation&&t.add(n.relationEventId);return t}addEphemeralEvents(e){for(const t of e)"m.typing"===t.getType()?this.currentState.setTypingEvent(t):"m.receipt"===t.getType()&&this.addReceipt(t)}removeEvents(e){for(let t=0;t<e.length;++t)this.removeEvent(e[t])}removeEvent(e){let t=!1;for(let n=0;n<this.timelineSets.length;n++){const i=this.timelineSets[n].removeEvent(e);i&&(i.isRedaction()&&this.revertRedactionLocalEcho(i),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(m.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 h.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,u.normalize)(this.name),this.summary=new f.RoomSummary(this.roomId,{title:this.name}),t!==this.name&&this.emit(k.Name,this)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return[T.ReceiptType.Read,T.ReceiptType.ReadPrivate].includes(e.type)})).map((function(e){return e.userId}))}getReadReceiptForUserId(e,t=!1,n=T.ReceiptType.Read){var i,r;const[o,s]=null!==(r=null===(i=this.receipts[n])||void 0===i?void 0:i[e])&&void 0!==r?r:[];return t?o:null!=s?s:o}getEventReadUpTo(e,t=!1){var n,i,r,o;const s=this.getUnfilteredTimelineSet(),a=this.getReadReceiptForUserId(e,t,T.ReceiptType.Read),c=this.getReadReceiptForUserId(e,t,T.ReceiptType.ReadPrivate);let l;return(null==a?void 0:a.eventId)&&(null==c?void 0:c.eventId)&&(l=s.compareEventOrdering(null==a?void 0:a.eventId,null==c?void 0:c.eventId)),l||(l=(null===(n=null==a?void 0:a.data)||void 0===n?void 0:n.ts)-(null===(i=null==c?void 0:c.data)||void 0===i?void 0:i.ts)),l?l<0?null==c?void 0:c.eventId:null==a?void 0:a.eventId:null!==(o=null!==(r=null==c?void 0:c.eventId)&&void 0!==r?r:null==a?void 0:a.eventId)&&void 0!==o?o:null}hasUserReadEvent(e,t){const n=this.getEventReadUpTo(e,!1);if(n===t)return!0;if(this.timeline.length&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===e)return!0;for(let e=this.timeline.length-1;e>=0;--e){const i=this.timeline[e];if(i.getId()===t)return!1;if(i.getId()===n)return!0}return!1}getReceiptsForEvent(e){return this.receiptCacheByEventId[e.getId()]||[]}addReceipt(e,t=!1){this.addReceiptsToStructure(e,t),this.emit(k.Receipt,e,this)}addReceiptsToStructure(e,t){const n=e.getContent();Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((i=>{Object.keys(n[e][i]).forEach((r=>{var o,s,a;const c=n[e][i][r];this.receipts[i]||(this.receipts[i]={}),this.receipts[i][r]||(this.receipts[i][r]=[null,null]);const l=this.receipts[i][r];let d=l[0];if(t&&(d=null!==(o=l[1])&&void 0!==o?o:l[0]),d){const t=this.getUnfilteredTimelineSet().compareEventOrdering(d.eventId,e);if(null!==t&&t>=0)return}const u={eventId:e,data:c},h=t?l[0]:u,g=t?u:l[1];let p=null;h&&g&&(p=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,g.eventId));const f=null===p||p<0,v=null!==(s=l[1])&&void 0!==s?s:l[0];t&&f?l[1]=u:t||(l[0]=u,f||(l[1]=null));if(v!==(null!==(a=l[1])&&void 0!==a?a:l[0])){if(v&&this.receiptCacheByEventId[v.eventId]){const e=v.eventId;this.receiptCacheByEventId[e]=this.receiptCacheByEventId[e].filter((e=>e.type!==i||e.userId!==r)),this.receiptCacheByEventId[e].length<1&&delete this.receiptCacheByEventId[e]}this.receiptCacheByEventId[e]||(this.receiptCacheByEventId[e]=[]),this.receiptCacheByEventId[e].push({userId:r,type:i,data:c})}}))}))}))}addLocalEchoReceipt(e,t,n){this.addReceipt(I(e,t,n),!0)}addTags(e){this.tags=e.getContent().tags||{},this.emit(k.Tags,e,this)}addAccountData(e){for(let t=0;t<e.length;t++){const n=e[t];"m.tag"===n.getType()&&this.addTags(n);const i=this.accountData[n.getType()];this.accountData[n.getType()]=n,this.emit(k.AccountData,n,this,i)}}getAccountData(e){return this.accountData[e]}maySendMessage(){return"join"===this.getMyMembership()&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(m.EventType.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(m.EventType.RoomMessage,this.myUserId))}canInvite(e){let t="join"===this.getMyMembership();const n=this.currentState.getStateEvents(m.EventType.RoomPowerLevels,""),i=n&&n.getContent(),r=this.getMember(e);return i&&r&&i.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(m.EventType.RoomCreate,"");if(e)return e.getContent()[m.RoomCreateTypeField];this.getTypeWarning||(v.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===m.RoomType.Space}isCallRoom(){return this.getType()===m.RoomType.UnstableCall}isElementVideoRoom(){return this.getType()===m.RoomType.ElementVideo}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(m.EventType.RoomName,"");if(e&&e.getContent()&&e.getContent().name)return e.getContent().name}const n=this.getCanonicalAlias();if(n)return n;let i=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,r=[];const o=this.currentState.getStateEvents(m.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,"");Array.isArray(null==o?void 0:o.getContent().service_members)&&(r=o.getContent().service_members);let s=null;if(this.summaryHeroes)s=[],this.summaryHeroes.forEach((e=>{if(r.includes(e))return void i--;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)||(i--,!1))),t.sort(((e,t)=>d.compare(e.userId,t.userId))),t=t.slice(0,5),s=t.map((e=>e.name))}if(i)return M(s,i);if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(m.EventType.RoomThirdPartyInvite);if(e&&e.length){return`Inviting ${M(e.map((e=>e.getContent().display_name)))}`}}let a=s;return a.length||(a=this.currentState.getMembers().filter((t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership)).map((e=>e.name))),a.length?`Empty room (was ${M(a)})`:"Empty room"}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const n=e.getSender();if(!n)return;if(!(m.EVENT_VISIBILITY_CHANGE_TYPE.name&&this.currentState.maySendStateEvent(m.EVENT_VISIBILITY_CHANGE_TYPE.name,n)||m.EVENT_VISIBILITY_CHANGE_TYPE.altName&&this.currentState.maySendStateEvent(m.EVENT_VISIBILITY_CHANGE_TYPE.altName,n)))return;const i=this.visibilityEvents.get(t.eventId);if(i){let t=i.length-1;const n=Math.max(0,i.length-30);for(;t>=n;--t){if(i[t].getTs()<e.getTs())break}-1===t?i.unshift(e):i.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().event_id,n=this.visibilityEvents.get(t);if(!n)return;const i=n.findIndex((t=>t.getId()===e.getId()));if(-1!==i&&(n.splice(i,1),i===n.length)){const e=this.findEventById(t);if(!e)return;if(0===i)this.visibilityEvents.delete(t),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 n=t[t.length-1],i=n.asVisibilityChange();i&&(i.visible,n.getTs()<e.getTs()||e.applyVisibilityEvent(i))}}function C(e){return`mx_pending_events_${e}`}n.Room=O;const P={[g.EventStatus.ENCRYPTING]:[g.EventStatus.SENDING,g.EventStatus.NOT_SENT,g.EventStatus.CANCELLED],[g.EventStatus.SENDING]:[g.EventStatus.ENCRYPTING,g.EventStatus.QUEUED,g.EventStatus.NOT_SENT,g.EventStatus.SENT],[g.EventStatus.QUEUED]:[g.EventStatus.SENDING,g.EventStatus.CANCELLED],[g.EventStatus.SENT]:[],[g.EventStatus.NOT_SENT]:[g.EventStatus.SENDING,g.EventStatus.QUEUED,g.EventStatus.CANCELLED],[g.EventStatus.CANCELLED]:[]};function M(e,t=e.length+1){const n=t-1;if(e.length){if(1===e.length&&n<=1)return e[0];if(2===e.length&&n<=2)return`${e[0]} and ${e[1]}`;return n>1?`${e[0]} and ${n} others`:`${e[0]} and 1 other`}return"Empty room"}},{"../@types/event":72,"../@types/read_receipts":76,"../ReEmitter":81,"../client":84,"../content-repo":86,"../filter":122,"../logger":126,"../utils":159,"./event":135,"./event-status":132,"./event-timeline":134,"./event-timeline-set":133,"./room-member":137,"./room-summary":139,"./thread":142,"./typed-event-emitter":143}],141:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.SearchResult=void 0;const i=e("./event-context");class r{constructor(e,t){this.rank=e,this.context=t}static fromJson(e,t){const n=e.context||{};let o=(n.events_before||[]).map(t),s=(n.events_after||[]).map(t);const a=new i.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(n.start,!0),a.addEvents(o,!0),a.addEvents(s,!1),a.setPaginateToken(n.end,!1),new r(e.rank,a)}}n.SearchResult=r},{"./event-context":131}],142:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.ThreadFilterType=n.THREAD_RELATION_TYPE=n.FILTER_RELATED_BY_REL_TYPES=n.FILTER_RELATED_BY_SENDERS=n.Thread=n.ThreadEvent=void 0;const r=e("../matrix"),o=e("../ReEmitter"),s=e("./event"),a=e("./event-timeline"),c=e("./event-timeline-set"),l=e("./typed-event-emitter"),d=e("../NamespacedValue"),u=e("../logger");var h;!function(e){e.New="Thread.new",e.Update="Thread.update",e.NewReply="Thread.newReply",e.ViewThread="Thread.viewThread"}(h=n.ThreadEvent||(n.ThreadEvent={}));class g extends l.TypedEventEmitter{constructor(e,t,i){var s;if(super(),this.id=e,this.rootEvent=t,this._currentUserParticipated=!1,this.replyCount=0,this.initialEventsFetched=!g.hasServerSideSupport,this.onBeforeRedaction=(e,t)=>{(null==e?void 0:e.isRelation(n.THREAD_RELATION_TYPE.name))&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.emit(h.Update,this))},this.onRedaction=e=>{var t;if(e.threadRootId!==this.id)return;const i=[...this.timelineSet.getLiveTimeline().getEvents()].reverse();this.lastEvent=null!==(t=i.find((e=>!e.isRedacted()&&e.isRelation(n.THREAD_RELATION_TYPE.name))))&&void 0!==t?t:this.rootEvent,this.emit(h.Update,this)},this.onEcho=e=>{if(e.threadRootId!==this.id)return;if(this.lastEvent===e)return;const t=e.isRelation(n.THREAD_RELATION_TYPE.name);(!this.lastEvent||this.lastEvent.isRedacted()||t&&e.getId()!==this.lastEvent.getId()&&e.localTimestamp>this.lastEvent.localTimestamp)&&(this.lastEvent=e,this.lastEvent.getId()!==this.id&&(g.hasServerSideSupport&&this.replyCount++,this.emit(h.NewReply,this,e))),this.emit(h.Update,this)},!(null==i?void 0:i.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=i.room,this.client=i.client,this.timelineSet=new c.EventTimelineSet(this.room,{unstableClientRelationAggregation:!0,timelineSupport:!0,pendingEvents:!0}),this.reEmitter=new o.TypedReEmitter(this),this.reEmitter.reEmit(this.timelineSet,[r.RoomEvent.Timeline,r.RoomEvent.TimelineReset]),this.room.on(r.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.room.on(r.RoomEvent.Redaction,this.onRedaction),this.room.on(r.RoomEvent.LocalEchoUpdated,this.onEcho),this.timelineSet.on(r.RoomEvent.Timeline,this.onEcho),i.initialEvents&&this.addEvents(i.initialEvents,!1),this.initialiseThread(),null===(s=this.rootEvent)||void 0===s||s.setThread(this)}fetchRootEvent(){var e;return i(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){u.logger.error("Failed to fetch thread root to construct thread with",e)}null===(e=this.rootEvent)||void 0===e||e.setThread(this),this.emit(h.Update,this)}))}static setServerSideSupport(e,t){g.hasServerSideSupport=e,t||(n.FILTER_RELATED_BY_SENDERS.setPreferUnstable(!0),n.FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(!0),n.THREAD_RELATION_TYPE.setPreferUnstable(!0))}get roomState(){return this.room.getLiveTimeline().getState(a.EventTimeline.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,t,!1,this.roomState)}addEvents(e,t){e.forEach((e=>this.addEvent(e,t,!1))),this.emit(h.Update,this)}addEvent(e,t,i=!0){var o,s;if(e.setThread(this),this._currentUserParticipated||e.getSender()!==this.client.getUserId()||(this._currentUserParticipated=!0),[r.RelationType.Annotation,r.RelationType.Replace].includes(null===(o=e.getRelation())||void 0===o?void 0:o.rel_type))return this.timelineSet.setRelationsTarget(e),void this.timelineSet.aggregateRelations(e);g.hasServerSideSupport?!t&&this.initialEventsFetched&&e.localTimestamp>(null===(s=this.lastReply())||void 0===s?void 0:s.localTimestamp)&&(this.fetchEditsWhereNeeded(e),this.addEventToTimeline(e,!1)):(this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e,{})),g.hasServerSideSupport&&this.rootEvent||!e.isRelation(n.THREAD_RELATION_TYPE.name)||this.replyCount++,i&&this.emit(h.Update,this)}getRootEventBundledRelationship(e=this.rootEvent){return null==e?void 0:e.getServerAggregatedRelation(n.THREAD_RELATION_TYPE.name)}initialiseThread(){return i(this,void 0,void 0,(function*(){let e=this.getRootEventBundledRelationship();if(g.hasServerSideSupport&&!e&&(yield this.fetchRootEvent(),e=this.getRootEventBundledRelationship()),g.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=e.current_user_participated;const t=new s.MatrixEvent(e.latest_event);this.setEventMetadata(t),t.setThread(this),this.lastEvent=t,this.fetchEditsWhereNeeded(t)}this.emit(h.Update,this)}))}fetchEditsWhereNeeded(...e){return i(this,void 0,void 0,(function*(){return Promise.all(e.filter((e=>e.isEncrypted())).map((e=>this.client.relations(this.roomId,e.getId(),r.RelationType.Replace,e.getType(),{limit:1}).then((t=>{t.events.length&&e.makeReplaced(t.events[0])})).catch((e=>{u.logger.error("Failed to load edits for encrypted thread event",e)})))))}))}fetchInitialEvents(){return i(this,void 0,void 0,(function*(){this.initialEventsFetched||(yield this.fetchEvents(),this.initialEventsFetched=!0)}))}setEventMetadata(e){a.EventTimeline.setEventMetadata(e,this.roomState,!1),e.setThread(this)}findEventById(e){var t;return(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())===e?this.lastEvent:this.timelineSet.findEventById(e)}lastReply(e=(()=>!0)){for(let t=this.events.length-1;t>=0;t--){const n=this.events[t];if(e(n))return n}}get roomId(){return this.room.roomId}get length(){return this.replyCount}get replyToEvent(){var e;return null!==(e=this.lastEvent)&&void 0!==e?e:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof s.MatrixEvent}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}fetchEvents(e={limit:20,direction:a.Direction.Backward}){var t;return i(this,void 0,void 0,(function*(){let{originalEvent:i,events:r,prevBatch:o,nextBatch:s}=yield this.client.relations(this.room.roomId,this.id,n.THREAD_RELATION_TYPE.name,null,e);e.to||s||(r=[...r,i]),yield this.fetchEditsWhereNeeded(...r),yield Promise.all(r.map((e=>(this.setEventMetadata(e),this.client.decryptEventIfNeeded(e)))));const c=(null!==(t=e.direction)&&void 0!==t?t:a.Direction.Backward)===a.Direction.Backward;return this.timelineSet.addEventsToTimeline(r,c,this.liveTimeline,c?s:o),{originalEvent:i,events:r,prevBatch:o,nextBatch:s}}))}}n.Thread=g,n.FILTER_RELATED_BY_SENDERS=new d.ServerControlledNamespacedValue("related_by_senders","io.element.relation_senders"),n.FILTER_RELATED_BY_REL_TYPES=new d.ServerControlledNamespacedValue("related_by_rel_types","io.element.relation_types"),n.THREAD_RELATION_TYPE=new d.ServerControlledNamespacedValue("m.thread","io.element.thread"),function(e){e[e.My=0]="My",e[e.All=1]="All"}(n.ThreadFilterType||(n.ThreadFilterType={}))},{"../NamespacedValue":80,"../ReEmitter":81,"../logger":126,"../matrix":127,"./event":135,"./event-timeline":134,"./event-timeline-set":133,"./typed-event-emitter":143}],143:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TypedEventEmitter=n.EventEmitterEvents=void 0;const i=e("events");!function(e){e.NewListener="newListener",e.RemoveListener="removeListener",e.Error="error"}(n.EventEmitterEvents||(n.EventEmitterEvents={}));class r extends i.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)}}n.TypedEventEmitter=r},{events:24}],144:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.User=n.UserEvent=void 0;const i=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=n.UserEvent||(n.UserEvent={}));class o extends i.TypedEventEmitter{constructor(e){super(),this.userId=e,this.presenceStatusMsg=null,this.presence="offline",this.lastActiveAgo=0,this.lastPresenceTs=0,this.currentlyActive=!1,this.events={presence:null,profile:null},this.displayName=e,this.rawDisplayName=e,this.avatarUrl=null,this.updateModifiedTime()}setPresenceEvent(e){if("m.presence"!==e.getType())return;const t=null===this.events.presence;this.events.presence=e;const n=[];(e.getContent().presence!==this.presence||t)&&n.push(r.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push(r.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push(r.DisplayName),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&n.push(r.CurrentlyActive),this.presence=e.getContent().presence,n.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(let t=0;t<n.length;t++)this.emit(n[t],e,this)}setDisplayName(e){const t=this.displayName;this.displayName="string"==typeof e?e:void 0,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName="string"==typeof e?e:void 0}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}}n.User=o},{"./typed-event-emitter":143}],145:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.PushProcessor=void 0;const i=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:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:s.EventType.RoomServerAcl}],actions:[]}];class l{constructor(e){this.client=e}static actionListToActionsObject(e){const t={notify:!1,tweaks:{}};for(let n=0;n<e.length;++n){const i=e[n];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){let t=JSON.parse(JSON.stringify(e));t||(t={}),t.global||(t.global={}),t.global.override||(t.global.override=[]);const n=t.global.override;for(const e of c){const t=n.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 override for ${t}`),n.push(e)}}return t}matchingRuleFromKindSet(e,t){for(let n=0;n<a.length;++n){const i=a[n],r=t[i];if(r)for(let t=0;t<r.length;++t){const n=r[t];if(!n.enabled)continue;const o=this.templateRuleToRaw(i,n);if(o&&this.ruleMatchesEvent(o,e))return Object.assign(Object.assign({},n),{kind:i})}}return null}templateRuleToRaw(e,t){const n={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case o.PushRuleKind.Underride:case o.PushRuleKind.Override:n.conditions=t.conditions;break;case o.PushRuleKind.RoomSpecific:if(!t.rule_id)return null;n.conditions.push({kind:o.ConditionKind.EventMatch,key:"room_id",value:t.rule_id});break;case o.PushRuleKind.SenderSpecific:if(!t.rule_id)return null;n.conditions.push({kind:o.ConditionKind.EventMatch,key:"user_id",value:t.rule_id});break;case o.PushRuleKind.ContentSpecific:if(!t.pattern)return null;n.conditions.push({kind:o.ConditionKind.EventMatch,key:"content.body",pattern:t.pattern})}return n}eventFulfillsCondition(e,t){switch(e.kind){case o.ConditionKind.EventMatch:return this.eventFulfillsEventMatchCondition(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)}return!1}eventFulfillsSenderNotifPermCondition(e,t){const n=e.key;if(!n)return!1;const i=this.client.getRoom(t.getRoomId());return!!(null==i?void 0:i.currentState)&&i.currentState.mayTriggerNotifOfType(n,t.getSender())}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;const n=this.client.getRoom(t.getRoomId());if(!n||!n.currentState||!n.currentState.members)return!1;const i=n.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 i==s;case"<":return i<s;case">":return i>s;case"<=":return i<=s;case">=":return i>=s;default:return!1}}eventFulfillsDisplayNameCondition(e,t){let n=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(n=t.getClearContent()),!n||!n.body||"string"!=typeof n.body)return!1;const r=this.client.getRoom(t.getRoomId());if(!(r&&r.currentState&&r.currentState.members&&r.currentState.getMember(this.client.credentials.userId)))return!1;const o=r.currentState.getMember(this.client.credentials.userId).name,s=new RegExp("(^|\\W)"+(0,i.escapeRegExp)(o)+"(\\W|$)","i");return n.body.search(s)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;const n=this.valueForDottedKey(e.key,t);if("string"!=typeof n)return!1;if(e.value)return e.value===n;if("string"!=typeof e.pattern)return!1;let i;return i="content.body"==e.key?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$"),!!n.match(i)}createCachedRegex(e,t,n){return l.cachedGlobToRegex[t]||(l.cachedGlobToRegex[t]=new RegExp(e+(0,i.globToRegexp)(t)+n,"i")),l.cachedGlobToRegex[t]}valueForDottedKey(e,t){const n=e.split(".");let r;const o=n[0];for("content"===o?(r=t.getContent(),n.shift()):"type"===o?(r=t.getType(),n.shift()):r=t.event;n.length>0;){const e=n.shift();if((0,i.isNullOrUndefined)(r[e]))return null;r=r[e]}return r}matchingRuleForEventWithRulesets(e,t){return t?e.getSender()===this.client.credentials.userId?null:this.matchingRuleFromKindSet(e,t.global):null}pushActionsForEventAndRulesets(e,t){const n=this.matchingRuleForEventWithRulesets(e,t);if(!n)return{};const i=l.actionListToActionsObject(n.actions);return void 0===i.tweaks.highlight&&(i.tweaks.highlight=n.kind==o.PushRuleKind.ContentSpecific),i}ruleMatchesEvent(e,t){var n;if(!(null===(n=e.conditions)||void 0===n?void 0:n.length))return!0;let i=!0;for(let n=0;n<e.conditions.length;++n){const r=e.conditions[n];i&=this.eventFulfillsCondition(r,t)}return i}actionsForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){for(const t of["global"])if(void 0!==this.client.pushRules[t])for(const n of a)if(void 0!==this.client.pushRules[t][n])for(const i of this.client.pushRules[t][n])if(i.rule_id===e)return i;return null}}n.PushProcessor=l,l.cachedGlobToRegex={}},{"./@types/PushRules":70,"./@types/event":72,"./logger":126,"./utils":159}],146:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.randomUppercaseString=n.randomLowercaseString=n.randomString=void 0;const i="abcdefghijklmnopqrstuvwxyz",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ";function o(e,t){let n="";for(let i=0;i<e;++i)n+=t.charAt(Math.floor(Math.random()*t.length));return n}n.randomString=function(e){return o(e,r+i+"0123456789")},n.randomLowercaseString=function(e){return o(e,i)},n.randomUppercaseString=function(e){return o(e,r)}},{}],147:[function(e,t,n){(function(t){(function(){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.clearTimeout=n.setTimeout=n.setNow=void 0;const i=e("./logger");let r,o=0;const s=[];n.setNow=function(e){a=e||Date.now};let a=Date.now;function c(){r&&t.clearTimeout(r);const e=s[0];if(!e)return;const n=a(),i=Math.min(e.runAt-n,1e3);r=t.setTimeout(l,i)}function l(){let e;const n=a(),r=[];for(;;){const t=s[0];if(!t||t.runAt>n)break;e=s.shift(),e.key,r.push(e)}c();for(let n=0;n<r.length;n++){e=r[n];try{e.func.apply(t,e.params)}catch(e){i.logger.error("Uncaught exception in callback function",e.stack||e)}}}n.setTimeout=function(e,t,...n){(t=t||0)<0&&(t=0);const i=a()+t,r=o++,l={runAt:i,func:e,params:n,key:r},d=function(e,t){let n=0,i=e.length;for(;n<i;){const r=n+i>>1;t(e[r])>0?i=r:n=r+1}return n}(s,(function(e){return e.runAt-i}));return s.splice(d,0,l),c(),r},n.clearTimeout=function(e){if(0===s.length)return;let t;for(t=0;t<s.length;t++){if(s[t].key==e){s.splice(t,1);break}}0===t&&c()}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./logger":126}],148:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(n,"__esModule",{value:!0}),n.MatrixScheduler=void 0;const s=o(e("./utils")),a=(e("./logger"),e("./@types/event"));class c{constructor(e=c.RETRY_BACKOFF_RATELIMIT,t=c.QUEUE_MESSAGES){this.retryAlgorithm=e,this.queueAlgorithm=t,this.queues={},this.activeQueues=[],this.procFn=null,this.processQueue=e=>{const t=this.peekNextEvent(e);if(!t){const t=this.activeQueues.indexOf(e);return t>=0&&this.activeQueues.splice(t,1),void l("Stopping queue '%s' as it is now empty",e)}l("Queue '%s' has %s pending events",e,this.queues[e].length),Promise.resolve().then((()=>this.procFn(t.event))).then((n=>{this.removeNextEvent(e),l("Queue '%s' sent event %s",e,t.event.getId()),t.defer.resolve(n),this.processQueue(e)}),(n=>{t.attempts+=1;const i=this.retryAlgorithm(t.event,t.attempts,n);l("retry(%s) err=%s event_id=%s waitTime=%s",t.attempts,n,t.event.getId(),i),-1===i?(l("Queue '%s' giving up on event %s",e,t.event.getId()),this.removeNextEvent(e),t.defer.reject(n),this.processQueue(e)):setTimeout(this.processQueue,i,e)}))}}static RETRY_BACKOFF_RATELIMIT(e,t,n){if(400===n.httpStatus||403===n.httpStatus||401===n.httpStatus)return-1;if("rejected"===n.cors)return-1;if("M_TOO_LARGE"===n.name)return-1;if("M_LIMIT_EXCEEDED"===n.name){const e=n.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()===a.EventType.RoomMessage||e.hasAssocation()?"message":null}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 n=!1;return s.removeElement(this.queues[t],(t=>{if(t.event.getId()===e.getId())return n=!0,!0})),n}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 n=s.defer();return this.queues[t].push({event:e,defer:n,attempts:0}),l("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),this.startProcessingQueues(),n.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),l("Spinning up queue: '%s'",e),this.processQueue(e)}))}peekNextEvent(e){const t=this.queues[e];return Array.isArray(t)?t[0]:null}removeNextEvent(e){const t=this.queues[e];return Array.isArray(t)?t.shift():null}}function l(...e){false}n.MatrixScheduler=c},{"./@types/event":72,"./logger":126,"./utils":159}],149:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.SERVICE_TYPES=void 0,function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"}(n.SERVICE_TYPES||(n.SERVICE_TYPES={}))},{}],150:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.LocalIndexedDBStoreBackend=void 0;const a=e("../sync-accumulator"),c=o(e("../utils")),l=o(e("../indexeddb-helpers")),d=e("../logger");function u(e,t,n){const i=e.openCursor(t);return new Promise(((e,t)=>{const r=[];i.onerror=()=>{t(new Error("Query failed: "+i.error))},i.onsuccess=()=>{const t=i.result;t?(r.push(n(t)),t.continue()):e(r)}}))}function h(e){return new Promise(((t,n)=>{e.oncomplete=function(e){t(e)},e.onerror=function(){n(e.error)}}))}function g(e){return new Promise(((t,n)=>{e.onsuccess=function(e){t(e)},e.onerror=function(){n(e.error)}}))}function p(e){return g(e).then((t=>e.result))}n.LocalIndexedDBStoreBackend=class{constructor(e,t){this.indexedDB=e,this.db=null,this.disconnected=!0,this._isNewlyCreated=!1,this.isPersisting=!1,this.pendingUserPresenceData=[],this.dbName="matrix-js-sdk:"+(t||"default"),this.syncAccumulator=new a.SyncAccumulator}static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),l.exists(e,t)}connect(){if(!this.disconnected)return d.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,d.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const e=this.indexedDB.open(this.dbName,3);return e.onupgradeneeded=t=>{const n=e.result,i=t.oldVersion;d.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${i}`),i<1&&(this._isNewlyCreated=!0,function(e){e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})}(n)),i<2&&function(e){e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")}(n),i<3&&function(e){e.createObjectStore("client_options",{keyPath:["clobber"]})}(n)},e.onblocked=()=>{d.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},d.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),g(e).then((()=>(d.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=e.result,this.db.onversionchange=()=>{this.db.close()},this.init())))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then((([e,t])=>{d.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,n)=>{const i=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),r=IDBKeyRange.only(e),o=i.openCursor(r),s=[];let a=!1;o.onsuccess=()=>{const e=o.result;if(!e)return s.length||a?t(s):t(null);const n=e.value;n.oob_written?a=!0:s.push(n),e.continue()},o.onerror=e=>{n(e)}})).then((t=>(d.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*(){d.logger.log(`LL: backend about to store ${t.length} members for ${e}`);const n=this.db.transaction(["oob_membership_events"],"readwrite"),i=n.objectStore("oob_membership_events");t.forEach((e=>{i.put(e)}));const r={room_id:e,oob_written:!0,state_key:0};i.put(r),yield h(n),d.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"),n=IDBKeyRange.only(e),i=p(t.openKeyCursor(n,"next")).then((e=>e&&e.primaryKey[1])),r=p(t.openKeyCursor(n,"prev")).then((e=>e&&e.primaryKey[1])),[o,s]=yield Promise.all([i,r]),a=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),c=IDBKeyRange.bound([e,o],[e,s]);var l;d.logger.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,o],[e,s]),yield(l=a.delete(c),new Promise(((e,t)=>{l.onsuccess=()=>e(l),l.onerror=e=>t(e)})))}))}clearDatabase(){return new Promise((e=>{d.logger.log(`Removing indexeddb instance: ${this.dbName}`);const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{d.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{d.logger.warn(`unable to delete js-sdk store indexeddb: ${t.error}`),e()},t.onsuccess=()=>{d.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*(){const t=this.syncAccumulator.getJSON(!0);if(this.isPersisting)return d.logger.warn("Skipping syncToDatabase() as persist already in flight"),void this.pendingUserPresenceData.push(...e);e.unshift(...this.pendingUserPresenceData),this.isPersisting=!0;try{yield Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData)])}finally{this.isPersisting=!1}}))}persistSyncData(e,t){return d.logger.log("Persisting sync data up to",e),c.promiseTry((()=>{const n=this.db.transaction(["sync"],"readwrite");return n.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t}),h(n).then((()=>{d.logger.log("Persisted sync data up to",e)}))}))}persistAccountData(e){return c.promiseTry((()=>{const t=this.db.transaction(["accountData"],"readwrite"),n=t.objectStore("accountData");for(let t=0;t<e.length;t++)n.put(e[t]);return h(t).then()}))}persistUserPresenceEvents(e){return c.promiseTry((()=>{const t=this.db.transaction(["users"],"readwrite"),n=t.objectStore("users");for(const t of e)n.put({userId:t[0],event:t[1]});return h(t).then()}))}getUserPresenceEvents(){return c.promiseTry((()=>u(this.db.transaction(["users"],"readonly").objectStore("users"),void 0,(e=>[e.value.userId,e.value.event]))))}loadAccountData(){return d.logger.log("LocalIndexedDBStoreBackend: loading account data..."),c.promiseTry((()=>u(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,(e=>e.value)).then((e=>(d.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))))}loadSyncData(){return d.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),c.promiseTry((()=>u(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,(e=>e.value)).then((e=>(d.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&d.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))))}getClientOptions(){return Promise.resolve().then((()=>u(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 h(t)}))}}},{"../indexeddb-helpers":124,"../logger":126,"../sync-accumulator":156,"../utils":159}],151:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.RemoteIndexedDBStoreBackend=void 0;const i=e("../logger"),r=e("../utils");n.RemoteIndexedDBStoreBackend=class{constructor(e,t){this.workerFactory=e,this.dbName=t,this.nextSeq=0,this.inFlight={},this.startPromise=null,this.onWorkerMessage=e=>{const t=e.data;if("cmd_success"==t.command||"cmd_fail"==t.command){if(void 0===t.seq)return void i.logger.error("Got reply from worker with no seq");const e=this.inFlight[t.seq];if(void 0===e)return void i.logger.error("Got reply for unknown seq "+t.seq);if(delete this.inFlight[t.seq],"cmd_success"==t.command)e.resolve(t.result);else{const n=new Error(t.error.message);n.name=t.error.name,e.reject(n)}}else i.logger.warn("Unrecognised message from worker: ",t)}}connect(){return 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")}ensureStarted(){return null===this.startPromise&&(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("_setupWorker",[this.dbName]).then((()=>{i.logger.log("IndexedDB worker is ready")}))),this.startPromise}doCmd(e,t){return Promise.resolve().then((()=>{const n=this.nextSeq++,i=(0,r.defer)();return this.inFlight[n]=i,this.worker.postMessage({command:e,seq:n,args:t}),i.promise}))}}},{"../logger":126,"../utils":159}],152:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.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"),l=e("../logger"),d=e("../models/typed-event-emitter");class u extends r.MemoryStore{constructor(e){if(super(e),this.startedUp=!1,this.syncTs=0,this.userModifiedMap={},this.emitter=new d.TypedEventEmitter,this.on=this.emitter.on.bind(this.emitter),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((()=>{l.logger.log("Deleted indexeddb data.")}),(e=>{throw l.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)}static exists(e,t){return o.LocalIndexedDBStoreBackend.exists(e,t)}startup(){return this.startedUp?(l.logger.log("IndexedDBStore.startup: already started"),Promise.resolve()):(l.logger.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect().then((()=>(l.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents()))).then((e=>{l.logger.log("IndexedDBStore.startup: processing presence events"),e.forEach((([e,t])=>{const n=new a.User(e);t&&n.setPresenceEvent(new c.MatrixEvent(t)),this.userModifiedMap[n.userId]=n.getLastModifiedTime(),this.storeUser(n)}))})))}wantsSave(){return Date.now()-this.syncTs>3e5}save(e=!1){return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){const n=super[t];return(...t)=>i(this,void 0,void 0,(function*(){try{return yield e.call(this,...t)}catch(e){l.logger.error("IndexedDBStore failure, degrading to MemoryStore",e),this.emitter.emit("degraded",e);try{l.logger.log("IndexedDBStore trying to delete degraded data"),yield this.backend.clearDatabase(),l.logger.log("IndexedDBStore delete after degrading succeeded")}catch(e){l.logger.warn("IndexedDBStore delete after degrading failed",e)}if(n)return n.call(this,...t)}}))}}n.IndexedDBStore=u},{"../logger":126,"../models/event":135,"../models/typed-event-emitter":143,"../models/user":144,"./indexeddb-local-backend":150,"./indexeddb-remote-backend":151,"./memory":153}],153:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.MemoryStore=void 0;const i=e("../models/user"),r=e("../models/room-state");function o(e){return"string"==typeof e&&!!e&&"undefined"!==e&&"null"!==e||"number"==typeof e}n.MemoryStore=class{constructor(e={}){this.rooms={},this.users={},this.syncToken=null,this.filters={},this.accountData={},this.oobMembers={},this.clientOptions={},this.onRoomMember=(e,t,n)=>{if("invite"===n.membership)return;const r=this.users[n.userId]||new i.User(n.userId);n.name&&(r.setDisplayName(n.name),n.events.member&&r.setRawDisplayName(n.events.member.getDirectionalContent().displayname)),n.events.member&&n.events.member.getContent().avatar_url&&r.setAvatarUrl(n.events.member.getContent().avatar_url),this.users[r.userId]=r},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(r.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(r.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,n,i){}storeFilter(e){e&&(this.filters[e.userId]||(this.filters[e.userId]={}),this.filters[e.userId][e.filterId]=e)}getFilter(e,t){return this.filters[e]&&this.filters[e][t]?this.filters[e][t]:null}getFilterIdByName(e){if(!this.localStorage)return null;const t="mxjssdk_memory_filter_"+e;try{const e=this.localStorage.getItem(t);if(o(e))return e}catch(e){}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const n="mxjssdk_memory_filter_"+e;try{o(t)?this.localStorage.setItem(n,t):this.localStorage.removeItem(n)}catch(e){}}storeAccountDataEvents(e){e.forEach((e=>{this.accountData[e.getType()]=e}))}getAccountData(e){return this.accountData[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={},this.accountData={},Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers[e]||null)}setOutOfBandMembers(e,t){return this.oobMembers[e]=t,Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers={},Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}}},{"../models/room-state":138,"../models/user":144}],154:[function(e,t,n){"use strict";var i=e("@babel/runtime/helpers/typeof");Object.defineProperty(n,"__esModule",{value:!0}),n.WebStorageSessionStore=l;var r=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var n=o(t);if(n&&n.has(e))return n.get(e);var r={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var c=s?Object.getOwnPropertyDescriptor(e,a):null;c&&(c.get||c.set)?Object.defineProperty(r,a,c):r[a]=e[a]}r.default=e,n&&n.set(e,r);return r}(e("../../utils"));e("../../logger");function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(o=function(e){return e?n:t})(e)}function s(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return a(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,r=function(){};return{s:r,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},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,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(c)throw o}}}}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}var c="session.e2e.";function l(e){if(this.store=e,!(r.isFunction(e.getItem)&&r.isFunction(e.setItem)&&r.isFunction(e.removeItem)&&r.isFunction(e.key)&&"number"==typeof e.length))throw new Error("Supplied webStore does not meet the WebStorage API interface")}l.prototype={removeEndToEndAccount:function(){this.store.removeItem(d)},getEndToEndAccount:function(){return this.store.getItem(d)},getAllEndToEndDevices:function(){for(var e=p(""),t={},n=0;n<this.store.length;++n){var i=this.store.key(n),r=i.slice(e.length);i.startsWith(e)&&(t[r]=y(this.store,i))}return t},getEndToEndDeviceTrackingStatus:function(){return y(this.store,h)},getEndToEndDeviceSyncToken:function(){return y(this.store,u)},removeEndToEndDeviceData:function(){E(this.store,p("")),E(this.store,h),E(this.store,u)},getEndToEndSessions:function(e){return y(this.store,f(e))},getAllEndToEndSessions:function(){var e,t={},n=s(m(this.store,f("")));try{for(n.s();!(e=n.n()).done;){var i=e.value;t[i.slice(f("").length)]=y(this.store,i)}}catch(e){n.e(e)}finally{n.f()}return t},removeAllEndToEndSessions:function(){E(this.store,f(""))},getAllEndToEndInboundGroupSessionKeys:function(){for(var e=c+"inboundgroupsessions/",t=[],n=0;n<this.store.length;n++){var i=this.store.key(n);i.startsWith(e)&&t.push({senderKey:i.slice(e.length,e.length+43),sessionId:i.slice(e.length+44)})}return t},getEndToEndInboundGroupSession:function(e,t){var n=function(e,t){return c+"inboundgroupsessions/"+e+"/"+t}(e,t);return this.store.getItem(n)},removeAllEndToEndInboundGroupSessions:function(){E(this.store,c+"inboundgroupsessions/")},getAllEndToEndRooms:function(){var e,t={},n=s(m(this.store,v("")));try{for(n.s();!(e=n.n()).done;){var i=e.value;t[i.slice(v("").length)]=y(this.store,i)}}catch(e){n.e(e)}finally{n.f()}return t},removeAllEndToEndRooms:function(){E(this.store,v(""))},setLocalTrustedBackupPubKey:function(e){this.store.setItem(g,e)},getLocalTrustedBackupPubKey:function(){return this.store.getItem(g)}};var d=c+"account",u=c+"device_sync_token",h=c+"device_tracking",g=c+"trusted_backup_pubkey";function p(e){return c+"devices/"+e}function f(e){return c+"sessions/"+e}function v(e){return c+"rooms/"+e}function y(e,t){try{return JSON.parse(e.getItem(t))}catch(e){S("Failed to get key %s: %s",t,e),S(e.stack)}return null}function m(e,t){for(var n=[],i=0;i<e.length;++i){var r=e.key(i);r.startsWith(t)&&n.push(r)}return n}function E(e,t){for(var n=[],i=0;i<e.length;++i){var r=e.key(i);r.startsWith(t)&&n.push(r)}for(var o=0,s=n;o<s.length;o++){var a=s[o];e.removeItem(a)}}function S(){false}},{"../../logger":126,"../../utils":159,"@babel/runtime/helpers/typeof":12}],155:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.StubStore=void 0;n.StubStore=class{constructor(){this.accountData={},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,n,i){}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({})}storeClientOptions(e){return Promise.resolve()}}},{}],156:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.SyncAccumulator=n.Category=void 0;const i=e("./logger"),r=e("./utils"),o=e("./@types/read_receipts");var s;!function(e){e.Invite="invite",e.Leave="leave",e.Join="join"}(s=n.Category||(n.Category={}));function a(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)}n.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((n=>{this.accumulateRoom(n,s.Invite,e.rooms.invite[n],t)})),e.rooms.join&&Object.keys(e.rooms.join).forEach((n=>{this.accumulateRoom(n,s.Join,e.rooms.join[n],t)})),e.rooms.leave&&Object.keys(e.rooms.leave).forEach((n=>{this.accumulateRoom(n,s.Leave,e.rooms.leave[n],t)})))}accumulateRoom(e,t,n,r=!1){switch(t){case s.Invite:this.accumulateInviteState(e,n);break;case s.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,n,r);break;case s.Leave:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:i.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 n=this.inviteRooms[e];t.invite_state.events.forEach((e=>{let t=!1;for(let i=0;i<n.invite_state.events.length;i++){const r=n.invite_state.events[i];r.type===e.type&&r.state_key==e.state_key&&(n.invite_state.events[i]=e,t=!0)}t||n.invite_state.events.push(e)}))}accumulateJoinState(e,t,n=!1){this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_summary:{},_readReceipts:{}});const i=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach((e=>{i._accountData[e.type]=e})),t.unread_notifications&&(i._unreadNotifications=t.unread_notifications),t.summary){const e="m.heroes",n="m.invited_member_count",r="m.joined_member_count",o=i._summary,s=t.summary;o[e]=s[e]||o[e],o[r]=s[r]||o[r],o[n]=s[n]||o[n]}if(t.ephemeral&&t.ephemeral.events&&t.ephemeral.events.forEach((e=>{"m.receipt"===e.type&&e.content&&Object.keys(e.content).forEach((t=>{if(!e.content[t][o.ReceiptType.Read]&&!e.content[t][o.ReceiptType.ReadPrivate])return;const n=e.content[t][o.ReceiptType.Read];n&&Object.keys(n).forEach((n=>{i._readReceipts[n]={data:e.content[t][o.ReceiptType.Read][n],type:o.ReceiptType.Read,eventId:t}}));const r=e.content[t][o.ReceiptType.ReadPrivate];r&&Object.keys(r).forEach((n=>{i._readReceipts[n]={data:e.content[t][o.ReceiptType.ReadPrivate][n],type:o.ReceiptType.ReadPrivate,eventId:t}}))}))})),t.timeline&&t.timeline.limited&&(i._timeline=[]),t.state&&t.state.events&&t.state.events.forEach((e=>{a(i._currentState,e)})),t.timeline&&t.timeline.events&&t.timeline.events.forEach(((e,r)=>{let o;if(a(i._currentState,e),n)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)}i._timeline.push({event:o,token:0===r?t.timeline.prev_batch:null})})),i._timeline.length>this.opts.maxTimelineEntries){for(let e=i._timeline.length-this.opts.maxTimelineEntries;e<i._timeline.length;e++)if(i._timeline[e].token){i._timeline=i._timeline.slice(e,i._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((n=>{const i=this.joinRooms[n],o={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:i._unreadNotifications,summary:i._summary};Object.keys(i._accountData).forEach((e=>{o.account_data.events.push(i._accountData[e])}));const s={type:"m.receipt",room_id:n,content:{}};Object.keys(i._readReceipts).forEach((e=>{const t=i._readReceipts[e];s.content[t.eventId]||(s.content[t.eventId]={}),s.content[t.eventId][t.type]||(s.content[t.eventId][t.type]={}),s.content[t.eventId][t.type][e]=t.data})),Object.keys(s.content).length>0&&o.ephemeral.events.push(s),i._timeline.forEach((t=>{if(!o.timeline.prev_batch){if(!t.token)return;o.timeline.prev_batch=t.token}let n;!e&&t.event._localTs?(n=Object.assign({},t.event),void 0!==n.unsigned&&(n.unsigned=Object.assign({},n.unsigned)),delete n._localTs,n.unsigned=n.unsigned||{},n.unsigned.age=Date.now()-t.event._localTs):n=t.event,o.timeline.events.push(n)}));const c=Object.create(null);for(let e=o.timeline.events.length-1;e>=0;e--){const t=o.timeline.events[e];if(null===t.state_key||void 0===t.state_key)continue;const n=(0,r.deepCopy)(t);n.unsigned&&(n.unsigned.prev_content&&(n.content=n.unsigned.prev_content),n.unsigned.prev_sender&&(n.sender=n.unsigned.prev_sender)),a(c,n)}Object.keys(i._currentState).forEach((e=>{Object.keys(i._currentState[e]).forEach((t=>{let n=i._currentState[e][t];c[e]&&c[e][t]&&(n=c[e][t]),o.state.events.push(n)}))})),t.join[n]=o}));const n=[];return Object.keys(this.accountData).forEach((e=>{n.push(this.accountData[e])})),{nextBatch:this.nextBatch,roomsData:t,accountData:n}}getNextBatchToken(){return this.nextBatch}}},{"./@types/read_receipts":76,"./logger":126,"./utils":159}],157:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.SyncApi=n.SyncState=void 0;const a=e("./models/user"),c=e("./models/room"),l=o(e("./utils")),d=e("./filter"),u=e("./models/event-timeline"),h=e("./pushprocessor"),g=e("./logger"),p=e("./errors"),f=e("./client"),v=e("./http-api"),y=e("./@types/event"),m=e("./models/room-state"),E=e("./models/room-member"),S=e("./models/beacon");var b,_;function T(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function w(...e){g.logger.log(...e)}!function(e){e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING"}(b=n.SyncState||(n.SyncState={})),function(e){e.Offline="offline",e.Online="online",e.Unavailable="unavailable"}(_||(_={}));function I(e,t){const n=new a.User(t);return e.reEmitter.reEmit(n,[a.UserEvent.AvatarUrl,a.UserEvent.DisplayName,a.UserEvent.Presence,a.UserEvent.CurrentlyActive,a.UserEvent.LastPresenceTs]),n}n.SyncApi=class{constructor(e,t={}){var n;this.client=e,this.opts=t,this._peekRoom=null,this.currentSyncRequest=null,this.syncState=null,this.syncStateData=null,this.catchingUp=!1,this.running=!1,this.keepAliveTimer=null,this.connectionReturnedDefer=null,this.notifEvents=[],this.failedSyncCount=0,this.storeIsInvalid=!1,this.onOnline=()=>{w("Browser thinks we are back online"),this.startKeepAlives(0)},this.opts.initialSyncLimit=null!==(n=this.opts.initialSyncLimit)&&void 0!==n?n:8,this.opts.resolveInvitesToProfiles=this.opts.resolveInvitesToProfiles||!1,this.opts.pollTimeout=this.opts.pollTimeout||3e4,this.opts.pendingEventOrdering=this.opts.pendingEventOrdering||f.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=!0===this.opts.experimentalThreadSupport,t.canResetEntireTimeline||(t.canResetEntireTimeline=e=>!1),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[c.RoomEvent.Timeline,c.RoomEvent.TimelineReset])}createRoom(e){const t=this.client,{timelineSupport:n,unstableClientRelationAggregation:i}=t,r=new c.Room(e,t,t.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:n,unstableClientRelationAggregation:i});return t.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]),this.registerStateListeners(r),r}registerStateListeners(e){const t=this.client;t.reEmitter.reEmit(e.currentState,[m.RoomStateEvent.Events,m.RoomStateEvent.Members,m.RoomStateEvent.NewMember,m.RoomStateEvent.Update,S.BeaconEvent.New,S.BeaconEvent.Update,S.BeaconEvent.Destroy,S.BeaconEvent.LivenessChange]),e.currentState.on(m.RoomStateEvent.NewMember,(function(e,n,i){i.user=t.getUser(i.userId),t.reEmitter.reEmit(i,[E.RoomMemberEvent.Name,E.RoomMemberEvent.Typing,E.RoomMemberEvent.PowerLevel,E.RoomMemberEvent.Membership])}))}deregisterStateListeners(e){e.currentState.removeAllListeners(m.RoomStateEvent.Events),e.currentState.removeAllListeners(m.RoomStateEvent.Members),e.currentState.removeAllListeners(m.RoomStateEvent.NewMember)}syncLeftRooms(){const e=this.client,t=new d.Filter(this.client.credentials.userId);t.setTimelineLimit(1),t.setIncludeLeaveRooms(!0);const n=this.opts.pollTimeout+8e4,i={timeout:0};return e.getOrCreateFilter(T(e.credentials.userId,"LEFT_ROOMS"),t).then((function(t){return i.filter=t,e.http.authedRequest(void 0,v.Method.Get,"/sync",i,void 0,n)})).then((t=>s(this,void 0,void 0,(function*(){var n;let i=[];return(null===(n=t.rooms)||void 0===n?void 0:n.leave)&&(i=this.mapSyncResponseToRoomArray(t.rooms.leave)),Promise.all(i.map((t=>s(this,void 0,void 0,(function*(){const n=t.room;if(!t.isBrandNewRoom)return;t.timeline=t.timeline||{};const i=this.mapSyncEventsFormat(t.timeline,n),r=this.mapSyncEventsFormat(t.state,n);return n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,u.EventTimeline.BACKWARDS),yield this.processRoomEvents(n,r,i),n.recalculate(),e.store.storeRoom(n),e.emit(f.ClientEvent.Room,n),this.processEventsForNotifs(n,i),n})))))}))))}peek(e){if(this._peekRoom&&this._peekRoom.roomId===e)return Promise.resolve(this._peekRoom);const t=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 n=l.deepCopy(e.state).map(t.getEventMapper()),i=e.state.map(t.getEventMapper()),r=e.messages.chunk.map(t.getEventMapper());return e.presence&&Array.isArray(e.presence)&&e.presence.map(t.getEventMapper()).forEach((function(e){let n=t.store.getUser(e.getContent().user_id);n?n.setPresenceEvent(e):(n=I(t,e.getContent().user_id),n.setPresenceEvent(e),t.store.storeUser(n)),t.emit(f.ClientEvent.Event,e)})),e.messages.start&&(this._peekRoom.oldState.paginationToken=e.messages.start),this._peekRoom.oldState.setStateEvents(n),this._peekRoom.currentState.setStateEvents(i),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(r.reverse(),!0,this._peekRoom.getLiveTimeline(),e.messages.start),t.store.storeRoom(this._peekRoom),t.emit(f.ClientEvent.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom}))}stopPeeking(){this._peekRoom=null}peekPoll(e,t){this._peekRoom===e?this.client.http.authedRequest(void 0,v.Method.Get,"/events",{room_id:e.roomId,timeout:String(3e4),from:t},void 0,5e4).then((t=>{if(this._peekRoom!==e)return void w("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=I(this.client,e.getContent().user_id),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit(f.ClientEvent.Event,e)}));const n=t.chunk.filter((function(t){return t.room_id===e.roomId&&t.event_id})).map(this.client.getEventMapper());e.addLiveEvents(n),this.peekPoll(e,t.end)}),(n=>{g.logger.error("[%s] Peek poll failed: %s",e.roomId,n),setTimeout((()=>{this.peekPoll(e,t)}),3e4)})):w("Stopped peeking in room %s",e.roomId)}getSyncState(){return this.syncState}getSyncStateData(){return this.syncStateData}recoverFromSyncStartupError(e,t){return s(this,void 0,void 0,(function*(){yield e;const n=this.startKeepAlives();this.updateSyncState(b.Error,{error:t}),yield n}))}wasLazyLoadingToggled(e=!1){return s(this,void 0,void 0,(function*(){let t=!1;if(!(yield this.client.store.isNewlyCreated())){const n=yield this.client.store.getClientOptions();return n&&(t=!!n.lazyLoadMembers),t!==e}return!1}))}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(g.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(b.Error,{error:e}),!0)}sync(){const e=this.client;this.running=!0,t.window&&t.window.addEventListener&&t.window.addEventListener("online",this.onOnline,!1);let n=Promise.resolve(),i=null;const r=()=>s(this,void 0,void 0,(function*(){try{w("Getting push rules...");const t=yield e.getPushRules();w("Got push rules"),e.pushRules=t}catch(e){if(g.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return w("Waiting for saved sync before retrying push rules..."),yield this.recoverFromSyncStartupError(n,e),void r()}a()})),o=()=>{const t=new d.Filter(e.credentials.userId);return t.setTimelineLimit(this.opts.initialSyncLimit),t},a=()=>s(this,void 0,void 0,(function*(){if(w("Checking lazy load status..."),this.opts.lazyLoadMembers&&e.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers){w("Checking server lazy load support...");(yield e.doesServerSupportLazyLoading())?(w("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=o()),this.opts.filter.setLazyLoadMembers(!0)):(w("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)}w("Checking whether lazy loading has changed in store...");if(yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const e=p.InvalidStoreError.TOGGLED_LAZY_LOADING,t=new p.InvalidStoreError(e,!!this.opts.lazyLoadMembers);return this.updateSyncState(b.Error,{error:t}),void g.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&this.opts.crypto&&this.opts.crypto.enableLazyLoading();try{w("Storing client options..."),yield this.client.storeClientOptions(),w("Stored client options")}catch(e){throw g.logger.error("Storing client options failed",e),e}c()})),c=()=>s(this,void 0,void 0,(function*(){let t,r;w("Getting filter..."),t=this.opts.filter?this.opts.filter:o();try{r=yield e.getOrCreateFilter(T(e.credentials.userId),t)}catch(e){if(g.logger.error("Getting filter failed",e),this.shouldAbortSync(e))return;return w("Waiting for saved sync before retrying filter..."),yield this.recoverFromSyncStartupError(n,e),void c()}e.resetNotifTimelineSet(),null===this.currentSyncRequest&&(w("Sending first sync request..."),this.currentSyncRequest=this.doSyncRequest({filterId:r},i)),w("Waiting for saved sync before starting sync processing..."),yield n,this.doSync({filterId:r})}));e.isGuest()?this.doSync({}):(w("Getting saved sync token..."),n=e.store.getSavedSyncToken().then((t=>(w("Got saved sync token"),i=t,w("Getting saved sync..."),e.store.getSavedSync()))).then((e=>{if(w(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)})).catch((e=>{g.logger.error("Getting saved sync failed",e)})),r())}stop(){var e;w("SyncApi.stop"),t.window&&t.window.removeEventListener&&t.window.removeEventListener("online",this.onOnline,!1),this.running=!1,null===(e=this.currentSyncRequest)||void 0===e||e.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=null)}retryImmediately(){return!!this.connectionReturnedDefer&&(this.startKeepAlives(0),!0)}syncFromCache(e){return s(this,void 0,void 0,(function*(){w("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const n={oldSyncToken:null,nextSyncToken:t,catchingUp:!1,fromCache:!0},i={next_batch:t,rooms:e.roomsData,account_data:{events:e.accountData}};try{yield this.processSyncResponse(n,i)}catch(e){g.logger.error("Error processing cached sync",e)}this.storeIsInvalid||this.updateSyncState(b.Prepared,n)}))}doSync(e){return s(this,void 0,void 0,(function*(){const t=this.client;if(!this.running)return w("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(b.Stopped);const n=t.store.getSyncToken();let i;try{null===this.currentSyncRequest&&(this.currentSyncRequest=this.doSyncRequest(e,n)),i=yield this.currentSyncRequest}catch(t){return void this.onSyncError(t,e)}finally{this.currentSyncRequest=null}t.store.setSyncToken(i.next_batch),this.failedSyncCount=0,yield t.store.setSyncData(i);const r={oldSyncToken:n,nextSyncToken:i.next_batch,catchingUp:this.catchingUp};this.opts.crypto&&(yield this.opts.crypto.onSyncWillProcess(r));try{yield this.processSyncResponse(r,i)}catch(e){g.logger.error("Caught /sync error",e),this.client.emit(f.ClientEvent.SyncUnexpectedError,e)}r.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(b.Prepared,r),e.hasSyncedBefore=!0),this.opts.crypto&&(yield this.opts.crypto.onSyncCompleted(r)),this.updateSyncState(b.Syncing,r),t.store.wantsSave()&&(this.opts.crypto&&(yield this.opts.crypto.saveDeviceList(0)),t.store.save()),this.doSync(e)}))}doSyncRequest(e,t){const n=this.getSyncParams(e,t);return this.client.http.authedRequest(void 0,v.Method.Get,"/sync",n,void 0,n.timeout+8e4)}getSyncParams(e,t){let n=this.opts.pollTimeout;("SYNCING"!==this.getSyncState()||this.catchingUp)&&(this.catchingUp=!0,n=0);let i=e.filterId;this.client.isGuest()&&!i&&(i=this.getGuestFilter());const r={filter:i,timeout:n};return this.opts.disablePresence&&(r.set_presence=_.Offline),t?r.since=t:r._cacheBuster=Date.now(),"ERROR"!=this.getSyncState()&&"RECONNECTING"!=this.getSyncState()||(r.timeout=0),r}onSyncError(e,t){if(!this.running)return w("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(b.Stopped);g.logger.error("/sync error %s",e),g.logger.error(e),this.shouldAbortSync(e)||(this.failedSyncCount++,g.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),w("Starting keep-alive"),this.startKeepAlives().then((e=>{e&&this.getSyncState()===b.Error&&this.updateSyncState(b.Catchup,{oldSyncToken:null,nextSyncToken:null,catchingUp:!0}),this.doSync(t)})),this.currentSyncRequest=null,this.updateSyncState(this.failedSyncCount>=3?b.Error:b.Reconnecting,{error:e}))}processSyncResponse(e,t){var n;return s(this,void 0,void 0,(function*(){const i=this.client;if(t.presence&&Array.isArray(t.presence.events)&&t.presence.events.map(i.getEventMapper()).forEach((function(e){let t=i.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=I(i,e.getSender()),t.setPresenceEvent(e),i.store.storeUser(t)),i.emit(f.ClientEvent.Event,e)})),t.account_data&&Array.isArray(t.account_data.events)){const e=t.account_data.events.map(i.getEventMapper()),n=e.reduce(((e,t)=>(e[t.getId()]=i.store.getAccountData(t.getType()),e)),{});i.store.storeAccountDataEvents(e),e.forEach((function(e){if(e.getType()===y.EventType.PushRules){const t=e.getContent();i.pushRules=h.PushProcessor.rewriteDefaultRules(t)}const t=n[e.getId()];return i.emit(f.ClientEvent.AccountData,e,t),e}))}if(Array.isArray(null===(n=t.to_device)||void 0===n?void 0:n.events)&&t.to_device.events.length>0){const e=[];t.to_device.events.map(i.getEventMapper()).map((t=>{if("m.key.verification.cancel"===t.getType()){const n=t.getContent().transaction_id;n&&e.push(n)}return t})).forEach((function(t){const n=t.getContent();if("m.room.message"!=t.getType()||"m.bad.encrypted"!=n.msgtype){if("m.key.verification.start"===t.getType()||"m.key.verification.request"===t.getType()){const i=n.transaction_id;e.includes(i)&&t.flagCancelled()}i.emit(f.ClientEvent.ToDeviceEvent,t)}else g.logger.log("Ignoring undecryptable to-device event from "+t.getSender())}))}else this.catchingUp=!1;let r=[],o=[],a=[];if(t.rooms&&(t.rooms.invite&&(r=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(o=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(a=this.mapSyncResponseToRoomArray(t.rooms.leave))),this.notifEvents=[],yield l.promiseMapSeries(r,(e=>s(this,void 0,void 0,(function*(){const t=e.room,n=this.mapSyncEventsFormat(e.invite_state,t);yield this.processRoomEvents(t,n),e.isBrandNewRoom?(t.recalculate(),i.store.storeRoom(t),i.emit(f.ClientEvent.Room,t)):t.recalculate(),n.forEach((function(e){i.emit(f.ClientEvent.Event,e)}))})))),yield l.promiseMapSeries(o,(t=>s(this,void 0,void 0,(function*(){const n=t.room,r=this.mapSyncEventsFormat(t.state,n),o=this.mapSyncEventsFormat(t.timeline,n,!1),a=this.mapSyncEventsFormat(t.ephemeral),d=this.mapSyncEventsFormat(t.account_data),h=i.isRoomEncrypted(n.roomId);if(t.unread_notifications&&(n.setUnreadNotificationCount(c.NotificationCountType.Total,t.unread_notifications.notification_count),(!h||h&&n.getUnreadNotificationCount(c.NotificationCountType.Highlight)<=0)&&n.setUnreadNotificationCount(c.NotificationCountType.Highlight,t.unread_notifications.highlight_count)),t.timeline=t.timeline||{},t.isBrandNewRoom)n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,u.EventTimeline.BACKWARDS);else if(t.timeline.limited){let r=!0;for(let e=o.length-1;e>=0;e--){const t=o[e].getId();if(n.getTimelineForEvent(t)){w("Already have event "+t+" in limited sync - not resetting"),r=!1,o.splice(0,e);break}}r&&(this.deregisterStateListeners(n),n.resetLiveTimeline(t.timeline.prev_batch,this.opts.canResetEntireTimeline(n.roomId)?null:e.oldSyncToken),i.resetNotifTimelineSet(),this.registerStateListeners(n))}yield this.processRoomEvents(n,r,o,e.fromCache),t.summary&&n.setSummary(t.summary),n.addEphemeralEvents(a),n.addAccountData(d),n.recalculate(),t.isBrandNewRoom&&(i.store.storeRoom(n),i.emit(f.ClientEvent.Room,n)),this.processEventsForNotifs(n,o);const g=e=>s(this,void 0,void 0,(function*(){i.emit(f.ClientEvent.Event,e),e.isState()&&"m.room.encryption"==e.getType()&&this.opts.crypto&&(yield this.opts.crypto.onCryptoEvent(e))}));yield l.promiseMapSeries(r,g),yield l.promiseMapSeries(o,g),a.forEach((function(e){i.emit(f.ClientEvent.Event,e)})),d.forEach((function(e){i.emit(f.ClientEvent.Event,e)})),n.decryptCriticalEvents()})))),yield l.promiseMapSeries(a,(e=>s(this,void 0,void 0,(function*(){const t=e.room,n=this.mapSyncEventsFormat(e.state,t),r=this.mapSyncEventsFormat(e.timeline,t),o=this.mapSyncEventsFormat(e.account_data);yield this.processRoomEvents(t,n,r),t.addAccountData(o),t.recalculate(),e.isBrandNewRoom&&(i.store.storeRoom(t),i.emit(f.ClientEvent.Room,t)),this.processEventsForNotifs(t,r),n.forEach((function(e){i.emit(f.ClientEvent.Event,e)})),r.forEach((function(e){i.emit(f.ClientEvent.Event,e)})),o.forEach((function(e){i.emit(f.ClientEvent.Event,e)}))})))),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((function(e){i.getNotifTimelineSet().addLiveEvent(e)}))),t.device_lists&&this.opts.crypto&&(yield this.opts.crypto.handleDeviceListChanges(e,t.device_lists)),this.opts.crypto&&t.device_one_time_keys_count){const e=t.device_one_time_keys_count.signed_curve25519||0;this.opts.crypto.updateOneTimeKeyCount(e)}if(this.opts.crypto&&(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"];this.opts.crypto.setNeedsNewFallback(e instanceof Array&&!e.includes("signed_curve25519"))}}))}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=l.defer()),this.connectionReturnedDefer.promise}pokeKeepAlive(e=!1){const t=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(e),this.connectionReturnedDefer=null)};this.client.http.request(void 0,v.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3}).then((()=>{t()}),(n=>{400==n.httpStatus||404==n.httpStatus?this.keepAliveTimer=setTimeout(t,2e3):(e=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,e),5e3+Math.floor(5e3*Math.random())),this.updateSyncState(b.Error,{error:n}))}))}mapSyncResponseToRoomArray(e){const t=this.client;return Object.keys(e).map((n=>{const i=e[n];let r=t.store.getRoom(n),o=!1;return r||(r=this.createRoom(n),o=!0),i.room=r,i.isBrandNewRoom=o,i}))}mapSyncEventsFormat(e,t,n=!0){if(!e||!Array.isArray(e.events))return[];const i=this.client.getEventMapper({decrypt:n});return e.events.map((function(e){return t&&(e.room_id=t.roomId),i(e)}))}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(n){if(n._requestedProfileInfo)return;n._requestedProfileInfo=!0;const i=t.getUser(n.userId);let r;r=i?Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):t.getProfileInfo(n.userId),r.then((function(t){const i=n.events.member;"invite"===i.getContent().membership&&(i.getContent().avatar_url=t.avatar_url,i.getContent().displayname=t.displayname,n.setMembershipEvent(i,e.currentState))}),(function(e){}))}))}processRoomEvents(e,t,n,i=!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)}this.resolveInvites(e),e.recalculate(),o||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(n||[],null,i),this.client.processBeaconEvents(e,n)}))}processEventsForNotifs(e,t){if(this.client.getNotifTimelineSet())for(let e=0;e<t.length;e++){const n=this.client.getPushActionsForEvent(t[e]);n&&n.notify&&n.tweaks&&n.tweaks.highlight&&this.notifEvents.push(t[e])}}getGuestFilter(){return"{}"}updateSyncState(e,t){const n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(f.ClientEvent.Sync,this.syncState,n,t)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/event":72,"./client":84,"./errors":119,"./filter":122,"./http-api":123,"./logger":126,"./models/beacon":130,"./models/event-timeline":134,"./models/room":140,"./models/room-member":137,"./models/room-state":138,"./models/user":144,"./pushprocessor":145,"./utils":159}],158:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TimelineIndex=n.TimelineWindow=void 0;const i=e("./models/event-timeline"),r=(e("./logger"),function(){});n.TimelineWindow=class{constructor(e,t,n={}){this.client=e,this.timelineSet=t,this.start=null,this.end=null,this.eventCount=0,this.windowLimit=n.windowLimit||1e3}load(e,t=20){const n=n=>{let i;const r=n.getEvents();if(e){if(i=r.findIndex((t=>t.getId()===e)),i<0)throw new Error("getEventTimeline result didn't include requested event")}else i=r.length;const s=Math.min(r.length,i+Math.ceil(t/2)),a=Math.max(0,s-t);this.start=new o(n,a-n.getBaseIndex()),this.end=new o(n,s-n.getBaseIndex()),this.eventCount=s-a};if(e){const t=this.timelineSet.getTimelineForEvent(e);return t?(n(t),Promise.resolve()):this.client.getEventTimeline(this.timelineSet,e).then(n)}return n(this.timelineSet.getLiveTimeline()),Promise.resolve()}getTimelineIndex(e){if(e==i.EventTimeline.BACKWARDS)return this.start;if(e==i.EventTimeline.FORWARDS)return this.end;throw new Error("Invalid direction '"+e+"'")}extend(e,t){const n=this.getTimelineIndex(e);if(!n)return r("TimelineWindow: no timeline yet"),!1;const o=e==i.EventTimeline.BACKWARDS?n.retreat(t):n.advance(t);if(o){this.eventCount+=o,r("TimelineWindow: increased cap by "+o+" (now "+this.eventCount+")");const t=this.eventCount-this.windowLimit;return t>0&&this.unpaginate(t,e!=i.EventTimeline.BACKWARDS),!0}return!1}canPaginate(e){const t=this.getTimelineIndex(e);if(!t)return r("TimelineWindow: no timeline yet"),!1;if(e==i.EventTimeline.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;return Boolean(t.timeline.getNeighbouringTimeline(e)||null!==t.timeline.getPaginationToken(e))}paginate(e,t,n=!0,o=5){const s=this.getTimelineIndex(e);if(!s)return r("TimelineWindow: no timeline yet"),Promise.resolve(!1);if(s.pendingPaginate)return s.pendingPaginate;if(this.extend(e,t))return Promise.resolve(!0);if(!n||0===o)return Promise.resolve(!1);if(null===s.timeline.getPaginationToken(e))return r("TimelineWindow: no token"),Promise.resolve(!1);r("TimelineWindow: starting request");const a=this.client.paginateEventTimeline(s.timeline,{backwards:e==i.EventTimeline.BACKWARDS,limit:t}).finally((function(){s.pendingPaginate=null})).then((n=>(r("TimelineWindow: request completed with result "+n),!!n&&this.paginate(e,t,!0,o-1))));return s.pendingPaginate=a,a}unpaginate(e,t){const n=t?this.start:this.end;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 i=t?n.advance(e):n.retreat(e);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=i,this.eventCount-=i,r("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];const e=[];let t=this.start.timeline;for(;;){const n=t.getEvents();let r=0,o=n.length;t===this.start.timeline&&(r=this.start.index+t.getBaseIndex()),t===this.end.timeline&&(o=this.end.index+t.getBaseIndex());for(let t=r;t<o;t++)e.push(n[t]);if(t===this.end.timeline)break;t=t.getNeighbouringTimeline(i.EventTimeline.FORWARDS)}return e}};class o{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 n=this.timeline.getNeighbouringTimeline(e<0?i.EventTimeline.BACKWARDS:i.EventTimeline.FORWARDS);return n?(this.timeline=n,this.index=e<0?this.maxIndex():this.minIndex(),r("paginate: switched to new neighbour"),this.advance(e)):0}retreat(e){return-1*this.advance(-1*e)}}n.TimelineIndex=o},{"./logger":126,"./models/event-timeline":134}],159:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.sortEventsByLatestContentTimestamp=n.recursivelyAssign=n.compare=n.lexicographicCompare=n.prevString=n.nextString=n.averageBetweenStrings=n.stringToBase=n.baseToString=n.alphabetPad=n.DEFAULT_ALPHABET=n.getCrypto=n.setCrypto=n.simpleRetryOperation=n.chunkPromises=n.promiseTry=n.promiseMapSeries=n.defer=n.isNullOrUndefined=n.sleep=n.ensureNoTrailingSlash=n.globToRegexp=n.escapeRegExp=n.normalize=n.removeDirectionOverrideChars=n.removeHiddenChars=n.isNumber=n.polyfillSuper=n.inherits=n.deepSortedObjectEntries=n.deepCompare=n.deepCopy=n.checkObjectHasNoAdditionalKeys=n.checkObjectHasKeys=n.isFunction=n.removeElement=n.encodeUri=n.decodeParams=n.encodeParams=void 0;const o=r(e("unhomoglyph")),s=r(e("p-retry")),a=e("./@types/location");function c(e){return"string"==typeof e?(0,o.default)(e.normalize("NFD").replace(l,"")):""}n.encodeParams=function(e){const t=new URLSearchParams;for(const[n,i]of Object.entries(e))null!=i&&t.set(n,String(i));return t.toString()},n.decodeParams=function(e){const t={},n=new URLSearchParams(e);for(const e of n.keys()){const i=n.getAll(e);t[e]=1===i.length?i[0]:i}return t},n.encodeUri=function(e,t){for(const n in t)t.hasOwnProperty(n)&&(e=e.replace(n,encodeURIComponent(t[n])));return e},n.removeElement=function(e,t,n){let i;if(n){for(i=e.length-1;i>=0;i--)if(t(e[i],i,e))return e.splice(i,1),!0}else for(i=0;i<e.length;i++)if(t(e[i],i,e))return e.splice(i,1),!0;return!1},n.isFunction=function(e){return"[object Function]"===Object.prototype.toString.call(e)},n.checkObjectHasKeys=function(e,t){for(let n=0;n<t.length;n++)if(!e.hasOwnProperty(t[n]))throw new Error("Missing required key: "+t[n])},n.checkObjectHasNoAdditionalKeys=function(e,t){for(const n in e)if(e.hasOwnProperty(n)&&-1===t.indexOf(n))throw new Error("Unknown key: "+n)},n.deepCopy=function(e){return JSON.parse(JSON.stringify(e))},n.deepCompare=function e(t,n){if(t===n)return!0;if(typeof t!=typeof n)return!1;if("number"==typeof t&&isNaN(t)&&isNaN(n))return!0;if(null===t||null===n)return t===n;if(!(t instanceof Object))return!1;if(t.constructor!==n.constructor||t.prototype!==n.prototype)return!1;if(t instanceof RegExp||t instanceof Date)return t.toString()===n.toString();if(t instanceof Array){if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(!e(t[i],n[i]))return!1}else{let i;for(i in n)if(n.hasOwnProperty(i)!==t.hasOwnProperty(i))return!1;for(i in n){if(n.hasOwnProperty(i)!==t.hasOwnProperty(i))return!1;if(!e(t[i],n[i]))return!1}}return!0},n.deepSortedObjectEntries=function e(t){if("object"!=typeof t)return t;if(null==t||Array.isArray(t))return t;const n=[];for(const[i,r]of Object.entries(t))n.push([i,e(r)]);return n.sort(((e,t)=>f(e[0],t[0]))),n},n.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},n.polyfillSuper=function(e,t,...n){try{t.call(e,...n)}catch(i){const r=new t(...n);Object.assign(e,r)}},n.isNumber=function(e){return"number"==typeof e&&isFinite(e)},n.removeHiddenChars=c,n.removeDirectionOverrideChars=function(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""},n.normalize=function(e){return c(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()};const l=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\s]/g;function d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let u;function h(e,t,i=n.DEFAULT_ALPHABET){return e.padEnd(t,i[0])}function g(e,t=n.DEFAULT_ALPHABET){var i;const r=BigInt(t.length);if(e<=r)return null!==(i=t[Number(e)-1])&&void 0!==i?i:"";let o=e/r,s=Number(e%r)-1;return s<0&&(o-=BigInt(Math.abs(s)),s=Number(r)-1),g(o,t)+t[s]}function p(e,t=n.DEFAULT_ALPHABET){const i=BigInt(t.length);let r=BigInt(0);for(let n=e.length-1,o=BigInt(0);n>=0;n--,o++){const s=e.charCodeAt(n)-t.charCodeAt(0);r+=BigInt(1+s)*i**o}return r}function f(e,t){return e<t?-1:e>t?1:0}n.escapeRegExp=d,n.globToRegexp=function(e,t){t="boolean"!=typeof t||t;let n=d(e);return n=n.replace(/\\\*/g,".*"),n=n.replace(/\?/g,"."),t&&(n=n.replace(/\\\[(!|)(.*)\\]/g,(function(e,t,n,i,r){return"["+(t?"^":"")+n.replace(/\\-/,"-")+"]"}))),n},n.ensureNoTrailingSlash=function(e){return e&&e.endsWith("/")?e.slice(0,-1):e},n.sleep=function(e,t){return new Promise((n=>{setTimeout(n,e,t)}))},n.isNullOrUndefined=function(e){return null==e},n.defer=function(){let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));return{resolve:e,reject:t,promise:n}},n.promiseMapSeries=function(e,t){return i(this,void 0,void 0,(function*(){for(const n of e)yield t(yield n)}))},n.promiseTry=function(e){return Promise.resolve(e())},n.chunkPromises=function(e,t){return i(this,void 0,void 0,(function*(){const n=[];for(let i=0;i<e.length;i+=t)n.push(...yield Promise.all(e.slice(i,i+t).map((e=>e()))));return n}))},n.simpleRetryOperation=function(e){return(0,s.default)((t=>e(t)),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})},n.setCrypto=function(e){u=e},n.getCrypto=function(){return u},n.DEFAULT_ALPHABET=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})(),n.alphabetPad=h,n.baseToString=g,n.stringToBase=p,n.averageBetweenStrings=function(e,t,i=n.DEFAULT_ALPHABET){const r=Math.max(e.length,t.length),o=p(h(e,r,i),i),s=p(h(t,r,i),i),a=(o+s)/BigInt(2);return a===o||a==s?g(a,i)+i[0]:g(a,i)},n.nextString=function(e,t=n.DEFAULT_ALPHABET){return g(p(e,t)+BigInt(1),t)},n.prevString=function(e,t=n.DEFAULT_ALPHABET){return g(p(e,t)-BigInt(1),t)},n.lexicographicCompare=f;const v=new Intl.Collator;function y(e){var t;return null!==(t=a.M_TIMESTAMP.findIn(e.getContent()))&&void 0!==t?t:-1}n.compare=function(e,t){return v.compare(e,t)},n.recursivelyAssign=function e(t,n,i=!1){for(const[r,o]of Object.entries(n))t[r]instanceof Object&&o?e(t[r],o):null==o&&i||(t[r]=o);return t},n.sortEventsByLatestContentTimestamp=function(e,t){return y(t)-y(e)}},{"./@types/location":74,"p-retry":56,unhomoglyph:69}],160:[function(e,t,n){(function(t){(function(){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),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 n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.createNewMatrixCall=n.supportsMatrixCall=n.MatrixCall=n.CallError=n.CallErrorCode=n.CallEvent=n.CallParty=n.CallDirection=n.CallType=n.CallState=void 0;const a=e("../logger"),c=o(e("../utils")),l=e("../@types/event"),d=e("../randomstring"),u=e("./callEventTypes"),h=e("./callFeed"),g=e("../models/typed-event-emitter");var p,f,v,y,m,E;!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"}(p=n.CallState||(n.CallState={})),function(e){e.Voice="voice",e.Video="video"}(f=n.CallType||(n.CallType={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(v=n.CallDirection||(n.CallDirection={})),function(e){e.Local="local",e.Remote="remote"}(y=n.CallParty||(n.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"}(m=n.CallEvent||(n.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.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.Transfered="transferred"}(E=n.CallErrorCode||(n.CallErrorCode={}));class S extends Error{constructor(e,t,n){super(t+": "+n),this.code=e}}function b(){return Date.now().toString()+(0,d.randomString)(16)}n.CallError=S;class _ extends g.TypedEventEmitter{constructor(e){super(),this.state=p.Fledgling,this.candidateSendQueue=[],this.candidateSendTries=0,this.sentEndOfCandidates=!1,this.feeds=[],this.usermediaSenders=[],this.screensharingSenders=[],this.inviteOrAnswerSent=!1,this.remoteOnHold=!1,this.makingOffer=!1,this.remoteCandidateBuffer=new Map,this.callLength=0,this.gotLocalIceCandidate=e=>{if(e.candidate){if(a.logger.debug("Call "+this.callId+" got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate),this.callHasEnded())return;""===e.candidate.candidate&&this.sentEndOfCandidates||(this.queueCandidate(e.candidate),""===e.candidate.candidate&&(this.sentEndOfCandidates=!0))}},this.onIceGatheringStateChange=e=>{if(a.logger.debug("ice gathering state changed to "+this.peerConn.iceGatheringState),"complete"===this.peerConn.iceGatheringState&&!this.sentEndOfCandidates){const e={candidate:""};this.queueCandidate(e),this.sentEndOfCandidates=!0}},this.gotLocalOffer=e=>s(this,void 0,void 0,(function*(){if(a.logger.debug("Created offer: ",e),this.callHasEnded())return void a.logger.debug("Ignoring newly created offer on call ID "+this.callId+" because the call has ended");try{yield this.peerConn.setLocalDescription(e)}catch(e){return a.logger.debug("Error setting local description!",e),void this.terminate(y.Local,E.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&(yield new Promise((e=>{setTimeout(e,200)}))),this.callHasEnded())return;const t=this.state===p.CreateOffer?l.EventType.CallInvite:l.EventType.CallNegotiate,n={lifetime:6e4};this.state===p.CreateOffer?n.offer=this.peerConn.localDescription:n.description=this.peerConn.localDescription,n.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},n[u.SDPStreamMetadataKey]=this.getLocalSDPStreamMetadata(),a.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`),this.candidateSendQueue=[];try{yield this.sendVoipEvent(t,n)}catch(e){a.logger.error("Failed to send invite",e),e.event&&this.client.cancelPendingEvent(e.event);let t=E.SignallingFailed,n="Signalling failed";return this.state===p.CreateOffer&&(t=E.SendInvite,n="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=E.UnknownDevices,n="Unknown devices present in the room"),this.emit(m.Error,new S(t,n,e)),void this.terminate(y.Local,t,!1)}this.sendCandidateQueue(),this.state===p.CreateOffer&&(this.inviteOrAnswerSent=!0,this.setState(p.InviteSent),this.inviteTimeout=setTimeout((()=>{this.inviteTimeout=null,this.state===p.InviteSent&&this.hangup(E.InviteTimeout,!1)}),6e4))})),this.getLocalOfferFailed=e=>{a.logger.error("Failed to get local offer",e),this.emit(m.Error,new S(E.LocalOfferFailed,"Failed to get local offer!",e)),this.terminate(y.Local,E.LocalOfferFailed,!1)},this.getUserMediaFailed=e=>{this.successor?this.successor.getUserMediaFailed(e):(a.logger.warn("Failed to get user media - ending call",e),this.emit(m.Error,new S(E.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e)),this.terminate(y.Local,E.NoUserMedia,!1))},this.onIceConnectionStateChanged=()=>{this.callHasEnded()||(a.logger.debug("Call ID "+this.callId+": ICE connection state changed to: "+this.peerConn.iceConnectionState),"connected"==this.peerConn.iceConnectionState?(this.setState(p.Connected),this.callLengthInterval||(this.callLengthInterval=setInterval((()=>{this.callLength++,this.emit(m.LengthChanged,this.callLength)}),1e3))):"failed"==this.peerConn.iceConnectionState&&this.hangup(E.IceFailed,!1))},this.onSignallingStateChanged=()=>{a.logger.debug("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},this.onTrack=e=>{if(0===e.streams.length)return void a.logger.warn(`Streamless ${e.track.kind} found: ignoring.`);const t=e.streams[0];this.pushRemoteFeed(t),t.addEventListener("removetrack",(()=>{0===t.getTracks().length&&(a.logger.info(`Stream ID ${t.id} has no tracks remaining - removing`),this.deleteFeedByStream(t))}))},this.onDataChannel=e=>{this.emit(m.DataChannel,e.channel)},this.onNegotiationNeeded=()=>s(this,void 0,void 0,(function*(){if(a.logger.info("Negotiation is needed!"),this.state===p.CreateOffer||0!==this.opponentVersion){this.makingOffer=!0;try{this.getRidOfRTXCodecs();const e=yield this.peerConn.createOffer();yield this.gotLocalOffer(e)}catch(e){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}else a.logger.info("Opponent does not support renegotiation: ignoring negotiationneeded event")})),this.onHangupReceived=e=>{a.logger.debug("Hangup received for call ID "+this.callId),this.partyIdMatches(e)||this.state===p.Ringing?this.terminate(y.Remote,e.reason||E.UserHangup,!0):a.logger.info(`Ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)},this.onRejectReceived=e=>{a.logger.debug("Reject received for call ID "+this.callId);[p.InviteSent,p.Ringing].includes(this.state)||this.state===p.Fledgling&&this.direction===v.Inbound?this.terminate(y.Remote,e.reason||E.UserHangup,!0):a.logger.debug(`Call is in state: ${this.state}: ignoring reject`)},this.onAnsweredElsewhere=e=>{a.logger.debug("Call ID "+this.callId+" answered elsewhere"),this.terminate(y.Remote,E.AnsweredElsewhere,!0)},this.roomId=e.roomId,this.client=e.client,this.forceTURN=e.forceTURN,this.ourPartyId=this.client.deviceId,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)c.checkObjectHasKeys(e,["urls"]);this.callId=b()}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 n=this.peerConn.createDataChannel(e,t);return this.emit(m.DataChannel,n),a.logger.debug("created data channel"),n}getOpponentMember(){return this.opponentMember}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 type(){return this.hasLocalUserMediaVideoTrack||this.hasRemoteUserMediaVideoTrack?f.Video:f.Voice}get hasLocalUserMediaVideoTrack(){var e;return(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getVideoTracks().length)>0}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some((e=>e.purpose===u.SDPStreamMetadataPurpose.Usermedia&&e.stream.getVideoTracks().length>0))}get hasLocalUserMediaAudioTrack(){var e;return(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getAudioTracks().length)>0}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some((e=>e.purpose===u.SDPStreamMetadataPurpose.Usermedia&&e.stream.getAudioTracks().length>0))}get localUsermediaFeed(){return this.getLocalFeeds().find((e=>e.purpose===u.SDPStreamMetadataPurpose.Usermedia))}get localScreensharingFeed(){return this.getLocalFeeds().find((e=>e.purpose===u.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===u.SDPStreamMetadataPurpose.Usermedia))}get remoteScreensharingFeed(){return this.getRemoteFeeds().find((e=>e.purpose===u.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()))}getLocalSDPStreamMetadata(){const e={};for(const t of this.getLocalFeeds())e[t.stream.id]={purpose:t.purpose,audio_muted:t.isAudioMuted(),video_muted:t.isVideoMuted()};return a.logger.debug("Got local SDPStreamMetadata",e),e}noIncomingFeeds(){return!this.feeds.some((e=>!e.isLocal()))}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,n=this.remoteSDPStreamMetadata[e.id].purpose,i=this.remoteSDPStreamMetadata[e.id].audio_muted,r=this.remoteSDPStreamMetadata[e.id].video_muted;if(!n)return void a.logger.warn(`Ignoring stream with id ${e.id} because we didn't get any metadata about it`);const o=this.getRemoteFeeds().find((e=>e.purpose===n));o?o.setNewStream(e):(this.feeds.push(new h.CallFeed({client:this.client,roomId:this.roomId,userId:t,stream:e,purpose:n,audioMuted:i,videoMuted:r})),this.emit(m.FeedsChanged,this.feeds)),a.logger.info(`Pushed remote stream (id="${e.id}", active="${e.active}", purpose=${n})`)}pushRemoteFeedWithoutMetadata(e){var t;const n=this.getOpponentMember().userId,i=u.SDPStreamMetadataPurpose.Usermedia,r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;if(r&&e.id!==r.id)return void a.logger.warn(`Ignoring new stream ID ${e.id}: we already have stream ID ${r.id}`);const o=this.getFeedByStreamId(e.id);o?o.setNewStream(e):(this.feeds.push(new h.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,stream:e,purpose:i})),this.emit(m.FeedsChanged,this.feeds)),a.logger.info(`Pushed remote stream (id="${e.id}", active="${e.active}")`)}pushNewLocalFeed(e,t,n=!0){const i=this.client.getUserId();T(e.getAudioTracks(),!0),T(e.getVideoTracks(),!0);const r=this.getLocalFeeds().find((e=>e.purpose===t));r?r.setNewStream(e):(this.pushLocalFeed(new h.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,stream:e,purpose:t}),n),this.emit(m.FeedsChanged,this.feeds))}pushLocalFeed(e,t=!0){if(this.feeds.push(e),t){const t=e.purpose===u.SDPStreamMetadataPurpose.Usermedia?this.usermediaSenders:this.screensharingSenders;t.splice(0,t.length);for(const n of e.stream.getTracks())a.logger.info(`Adding track (id="${n.id}", kind="${n.kind}", streamId="${e.stream.id}", streamPurpose="${e.purpose}", enabled=${n.enabled}) to peer connection`),t.push(this.peerConn.addTrack(n,e.stream))}a.logger.info(`Pushed local stream (id="${e.stream.id}", active="${e.stream.active}", purpose="${e.purpose}")`),this.emit(m.FeedsChanged,this.feeds)}removeLocalFeed(e){const t=e.purpose===u.SDPStreamMetadataPurpose.Usermedia?this.usermediaSenders:this.screensharingSenders;for(const e of t)this.peerConn.removeTrack(e);t.splice(0,t.length),this.deleteFeedByStream(e.stream)}deleteAllFeeds(){for(const e of this.feeds)e.dispose();this.feeds=[],this.emit(m.FeedsChanged,this.feeds)}deleteFeedByStream(e){a.logger.debug(`Removing feed with stream id ${e.id}`);const t=this.getFeedByStreamId(e.id);t?(t.dispose(),this.feeds.splice(this.feeds.indexOf(t),1),this.emit(m.FeedsChanged,this.feeds)):a.logger.warn(`Didn't find the feed with stream id ${e.id} to delete`)}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[1])})),t}))}initWithInvite(e){var t;return s(this,void 0,void 0,(function*(){const n=e.getContent();this.direction=v.Inbound;(yield this.client.checkTurnServers())||a.logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");const i=n[u.SDPStreamMetadataKey];i?this.updateRemoteSDPStreamMetadata(i):a.logger.debug("Did not get any SDPStreamMetadata! Can not send/receive multiple streams"),this.peerConn=this.createPeerConnection(),this.chooseOpponent(e);try{yield this.peerConn.setRemoteDescription(n.offer),yield this.addBufferedIceCandidates()}catch(e){return a.logger.debug("Failed to set remote description",e),void this.terminate(y.Local,E.SetRemoteDescription,!1)}const r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;if(!r||0===r.getTracks().length)return a.logger.error("No remote stream or no tracks after setting remote description!"),void this.terminate(y.Local,E.SetRemoteDescription,!1);this.setState(p.Ringing),e.getLocalAge()&&setTimeout((()=>{this.state==p.Ringing&&(a.logger.debug("Call invite has expired. Hanging up."),this.hangupParty=y.Remote,this.setState(p.Ended),this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit(m.Hangup))}),n.lifetime-e.getLocalAge())}))}initWithHangup(e){this.setState(p.Ended)}shouldAnswerWithMediaType(e,t,n){return e&&!t?(a.logger.warn(`Unable to answer with ${n} because the other side isn't sending it either.`),!1):c.isNullOrUndefined(e)||e===t||this.opponentSupportsSDPStreamMetadata()?null!=e?e:t:(a.logger.warn(`Unable to answer with ${n}=${e} because the other side doesn't support it. Answering with ${n}=${t}.`),t)}answer(e,t){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(a.logger.debug(`Answering call ${this.callId}`),this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&this.setState(p.WaitLocalMedia);else{const n=this.state,i=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),r=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.setState(p.WaitLocalMedia),this.waitForLocalAVStream=!0;try{const e=yield this.client.getMediaHandler().getUserMediaStream(i,r);this.waitForLocalAVStream=!1;const t=[new h.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:e,purpose:u.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&t.push(this.localScreensharingFeed),this.answerWithCallFeeds(t)}catch(e){if(!r)return void this.getUserMediaFailed(e);a.logger.warn("Failed to getUserMedia(), trying to getUserMedia() without video"),this.setState(n),this.waitForLocalAVStream=!1,yield this.answer(i,!1)}}}}))}answerWithCallFeeds(e){this.inviteOrAnswerSent||(a.logger.debug(`Answering call ${this.callId}`),this.gotCallFeedsForAnswer(e))}replacedBy(e){this.state===p.WaitLocalMedia?(a.logger.debug("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):[p.CreateOffer,p.InviteSent].includes(this.state)&&(a.logger.debug("Handing local stream to new call"),e.gotCallFeedsForAnswer(this.getLocalFeeds())),this.successor=e,this.emit(m.Replaced,e),this.hangup(E.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(a.logger.debug("Ending call "+this.callId),this.terminate(y.Local,e,!t),this.state===p.WaitLocalMedia)return;const n={};(this.opponentVersion&&this.opponentVersion>=1||e!==E.UserHangup)&&(n.reason=e),this.sendVoipEvent(l.EventType.CallHangup,n)}reject(){if(this.state!==p.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion<1)return a.logger.info(`Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`),void this.hangup(E.UserHangup,!0);a.logger.debug("Rejecting call: "+this.callId),this.terminate(y.Local,E.UserHangup,!0),this.sendVoipEvent(l.EventType.CallReject,{})}upgradeCall(e,t){return s(this,void 0,void 0,(function*(){if((e||t)&&this.opponentSupportsSDPStreamMetadata())try{const n=e||this.hasLocalUserMediaAudioTrack,i=t||this.hasLocalUserMediaVideoTrack,r=yield this.client.getMediaHandler().getUserMediaStream(n,i,!1);yield this.updateLocalUsermediaStream(r,e,t)}catch(e){a.logger.error("Failed to upgrade the call",e),this.emit(m.Error,new S(E.NoUserMedia,"Failed to get camera access: ",e))}}))}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 a.logger.warn("There is already a screensharing stream - there is nothing to do!"),!0;if(!e&&!this.isScreensharing())return a.logger.warn("There already isn't a screensharing stream - there is nothing to do!"),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(a.logger.debug(`Set screensharing enabled? ${e}`),!e){for(const e of this.screensharingSenders)this.peerConn.removeTrack(e);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,u.SDPStreamMetadataPurpose.Screenshare),!0)}catch(e){return a.logger.error("Failed to get screen-sharing stream:",e),!1}}))}setScreensharingEnabledWithoutMetadataSupport(e,t){return s(this,void 0,void 0,(function*(){if(a.logger.debug(`Set screensharing enabled? ${e} using replaceTrack()`),!e){const e=this.localUsermediaStream.getTracks().find((e=>"video"===e.kind));return this.usermediaSenders.find((e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)})).replaceTrack(e),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));return this.usermediaSenders.find((e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)})).replaceTrack(n),this.pushNewLocalFeed(e,u.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(e){return a.logger.error("Failed to get screen-sharing stream:",e),!1}}))}updateLocalUsermediaStream(e,t=!1,n=!1){return s(this,void 0,void 0,(function*(){const i=this.localUsermediaFeed,r=t||!i.isAudioMuted()&&!this.remoteOnHold,o=n||!i.isVideoMuted()&&!this.remoteOnHold;T(e.getAudioTracks(),r),T(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);const s=[];for(const t of e.getTracks()){const n=this.usermediaSenders.find((e=>{var n;return(null===(n=e.track)||void 0===n?void 0:n.kind)===t.kind}));let r;n?(a.logger.info(`Replacing track (id="${t.id}", kind="${t.kind}", streamId="${e.id}", streamPurpose="${i.purpose}") to peer connection`),yield n.replaceTrack(t),r=n):(a.logger.info(`Adding track (id="${t.id}", kind="${t.kind}", streamId="${e.id}", streamPurpose="${i.purpose}") to peer connection`),r=this.peerConn.addTrack(t,this.localUsermediaStream)),s.push(r)}this.usermediaSenders=s}))}setLocalVideoMuted(e){var t;return s(this,void 0,void 0,(function*(){return(yield this.client.getMediaHandler().hasVideoDevice())?this.hasLocalUserMediaVideoTrack||e?(null===(t=this.localUsermediaFeed)||void 0===t||t.setVideoMuted(e),this.updateMuteStatus(),this.isLocalVideoMuted()):(yield this.upgradeCall(!1,!0),this.isLocalVideoMuted()):this.isLocalVideoMuted()}))}isLocalVideoMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isVideoMuted()}setMicrophoneMuted(e){var t;return s(this,void 0,void 0,(function*(){return(yield this.client.getMediaHandler().hasAudioDevice())?this.hasLocalUserMediaAudioTrack||e?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioMuted(e),this.updateMuteStatus(),this.isMicrophoneMuted()):(yield this.upgradeCall(!0,!1),this.isMicrophoneMuted()):this.isMicrophoneMuted()}))}isMicrophoneMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted()}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.emit(m.RemoteHoldUnhold,this.remoteOnHold)}}isLocalOnHold(){if(this.state!==p.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers()){["inactive","recvonly"].includes(t.currentDirection)||(e=!1)}return e}sendDtmfDigit(e){for(const t of this.peerConn.getSenders())if("audio"===t.track.kind&&t.dtmf)return void t.dtmf.insertDTMF(e);throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){this.sendVoipEvent(l.EventType.CallSDPStreamMetadataChangedPrefix,{[u.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()});const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;T(this.localUsermediaStream.getAudioTracks(),!e),T(this.localUsermediaStream.getVideoTracks(),!t)}gotCallFeedsForInvite(e){if(this.successor)this.successor.gotCallFeedsForAnswer(e);else if(this.callHasEnded())this.stopAllMedia();else{for(const t of e)this.pushLocalFeed(t);this.setState(p.CreateOffer),a.logger.debug("gotUserMediaForInvite")}}sendAnswer(){return s(this,void 0,void 0,(function*(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[u.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},a.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`),this.candidateSendQueue=[];try{yield this.sendVoipEvent(l.EventType.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.setState(p.Ringing),this.client.cancelPendingEvent(e.event);let t=E.SendAnswer,n="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=E.UnknownDevices,n="Unknown devices present in the room"),this.emit(m.Error,new S(t,n,e)),e}this.sendCandidateQueue()}))}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.setState(p.CreateAnswer);try{this.getRidOfRTXCodecs(),t=yield this.peerConn.createAnswer()}catch(e){return a.logger.debug("Failed to create answer: ",e),void this.terminate(y.Local,E.CreateAnswer,!0)}try{yield this.peerConn.setLocalDescription(t),this.setState(p.Connecting),yield new Promise((e=>{setTimeout(e,200)})),this.sendAnswer()}catch(e){return a.logger.debug("Error setting local description!",e),void this.terminate(y.Local,E.SetLocalDescription,!0)}}))}onRemoteIceCandidatesReceived(e){return s(this,void 0,void 0,(function*(){if(this.callHasEnded())return;const t=e.getContent(),n=t.candidates;if(!n)return void a.logger.info("Ignoring candidates event with no candidates!");const i=0===t.version?null:t.party_id||null;if(void 0===this.opponentPartyId){a.logger.info(`Buffering ${n.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(i)||[];return e.push(...n),void this.remoteCandidateBuffer.set(i,e)}this.partyIdMatches(t)?yield this.addIceCandidates(n):a.logger.info(`Ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`)}))}onAnswerReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent();if(a.logger.debug(`Got answer for call ID ${this.callId} from party ID ${t.party_id}`),this.callHasEnded())return void a.logger.debug(`Ignoring answer because call ID ${this.callId} has ended`);if(void 0!==this.opponentPartyId)return void a.logger.info(`Ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);this.chooseOpponent(e),yield this.addBufferedIceCandidates(),this.setState(p.Connecting);const n=t[u.SDPStreamMetadataKey];n?this.updateRemoteSDPStreamMetadata(n):a.logger.warn("Did not get any SDPStreamMetadata! Can not send/receive multiple streams");try{yield this.peerConn.setRemoteDescription(t.answer)}catch(e){return a.logger.debug("Failed to set remote description",e),void this.terminate(y.Local,E.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{yield this.sendVoipEvent(l.EventType.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){a.logger.warn("Failed to send select_answer event",e)}}))}onSelectAnswerReceived(e){return s(this,void 0,void 0,(function*(){if(this.direction!==v.Inbound)return void a.logger.warn("Got select_answer for an outbound call: ignoring");const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(a.logger.info(`Got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),this.terminate(y.Remote,E.AnsweredElsewhere,!0)):a.logger.warn("Got nonsensical select_answer with null/undefined selected_party_id: ignoring")}))}onNegotiateReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),n=t.description;if(!n||!n.sdp||!n.type)return void a.logger.info("Ignoring invalid m.call.negotiate event");const i=this.direction===v.Inbound,r="offer"===n.type&&(this.makingOffer||"stable"!==this.peerConn.signalingState);if(this.ignoreOffer=!i&&r,this.ignoreOffer)return void a.logger.info("Ignoring colliding negotiate event because we're impolite");const o=this.isLocalOnHold(),s=t[u.SDPStreamMetadataKey];s?this.updateRemoteSDPStreamMetadata(s):a.logger.warn("Received negotiation event without SDPStreamMetadata!");try{if(yield this.peerConn.setRemoteDescription(n),"offer"===n.type){this.getRidOfRTXCodecs();const e=yield this.peerConn.createAnswer();yield this.peerConn.setLocalDescription(e),this.sendVoipEvent(l.EventType.CallNegotiate,{description:this.peerConn.localDescription,[u.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}}catch(e){a.logger.warn("Failed to complete negotiation",e)}const c=this.isLocalOnHold();o!==c&&(this.emit(m.LocalHoldUnhold,c),this.emit(m.HoldUnhold,c))}))}updateRemoteSDPStreamMetadata(e){var t,n,i;this.remoteSDPStreamMetadata=c.recursivelyAssign(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){const r=e.stream.id;e.setAudioMuted(null===(t=this.remoteSDPStreamMetadata[r])||void 0===t?void 0:t.audio_muted),e.setVideoMuted(null===(n=this.remoteSDPStreamMetadata[r])||void 0===n?void 0:n.video_muted),e.purpose=null===(i=this.remoteSDPStreamMetadata[r])||void 0===i?void 0:i.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[u.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(m.AssertedIdentityChanged))}))}callHasEnded(){return this.state===p.Ended}getRidOfRTXCodecs(){var e,t;if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const n=RTCRtpReceiver.getCapabilities("video").codecs,i=[...RTCRtpSender.getCapabilities("video").codecs,...n];for(const e of i)if("video/rtx"===e.mimeType){const t=i.indexOf(e);i.splice(t,1)}for(const n of this.peerConn.getTransceivers())!this.screensharingSenders.includes(n.sender)||"video"!==(null===(e=n.sender.track)||void 0===e?void 0:e.kind)&&"video"!==(null===(t=n.receiver.track)||void 0===t?void 0:t.kind)||n.setCodecPreferences(i)}setState(e){const t=this.state;this.state=e,this.emit(m.State,e,t)}sendVoipEvent(e,t){return this.client.sendEvent(this.roomId,e,Object.assign({},t,{version:1,call_id:this.callId,party_id:this.ourPartyId}))}queueCandidate(e){if(this.candidateSendQueue.push(e),this.state===p.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===v.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout((()=>{this.sendCandidateQueue()}),t)}transfer(e){return s(this,void 0,void 0,(function*(){const t=yield this.client.getProfileInfo(e),n=b(),i={replacement_id:b(),target_user:{id:e,display_name:t.displayname,avatar_url:t.avatar_url},create_call:n};yield this.sendVoipEvent(l.EventType.CallReplaces,i),yield this.terminate(y.Local,E.Transfered,!0)}))}transferToCall(e){return s(this,void 0,void 0,(function*(){const t=yield this.client.getProfileInfo(e.getOpponentMember().userId),n=yield this.client.getProfileInfo(this.getOpponentMember().userId),i=b(),r={replacement_id:b(),target_user:{id:this.getOpponentMember().userId,display_name:n.displayname,avatar_url:n.avatar_url},await_call:i};yield e.sendVoipEvent(l.EventType.CallReplaces,r);const o={replacement_id:b(),target_user:{id:e.getOpponentMember().userId,display_name:t.displayname,avatar_url:t.avatar_url},create_call:i};yield this.sendVoipEvent(l.EventType.CallReplaces,o),yield this.terminate(y.Local,E.Transfered,!0),yield e.terminate(y.Local,E.Transfered,!0)}))}terminate(e,t,n){return s(this,void 0,void 0,(function*(){this.callHasEnded()||(this.callStatsAtEnd=yield this.collectCallStats(),this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=null),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=null),t!==E.Replaced&&this.stopAllMedia(),this.deleteAllFeeds(),this.hangupParty=e,this.hangupReason=t,this.setState(p.Ended),this.peerConn&&"closed"!==this.peerConn.signalingState&&this.peerConn.close(),n&&this.emit(m.Hangup))}))}stopAllMedia(){a.logger.debug("Stopping all media for call",this.callId);for(const e of this.feeds)if(e.isLocal()&&e.purpose===u.SDPStreamMetadataPurpose.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===u.SDPStreamMetadataPurpose.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else{a.logger.debug("Stopping remote stream",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)return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e};a.logger.debug("Attempting to send "+e.length+" candidates");try{yield this.sendVoipEvent(l.EventType.CallCandidates,t),this.candidateSendTries=0}catch(t){if(t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){a.logger.debug("Failed to send candidates on attempt "+this.candidateSendTries+". Giving up on this call.",t);const e=E.SignallingFailed,n="Signalling failed";return this.emit(m.Error,new S(e,n,t)),void this.hangup(e,!1)}const n=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,a.logger.debug("Failed to send candidates. Retrying in "+n+"ms",t),setTimeout((()=>{this.sendCandidateQueue()}),n)}}))}placeCall(e,t){return s(this,void 0,void 0,(function*(){if(!e)throw new Error("You CANNOT start a call without audio");this.setState(p.WaitLocalMedia);try{const n=yield this.client.getMediaHandler().getUserMediaStream(e,t);T(n.getAudioTracks(),!0),T(n.getVideoTracks(),!0);const i=new h.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:n,purpose:u.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1});yield this.placeCallWithCallFeeds([i])}catch(e){return void this.getUserMediaFailed(e)}}))}placeCallWithCallFeeds(e){return s(this,void 0,void 0,(function*(){this.checkForErrorListener(),this.direction=v.Outbound,this.client.callEventHandler.calls.set(this.callId,this);(yield this.client.checkTurnServers())||a.logger.warn("Failed to get TURN credentials! Proceeding with call anyway..."),this.peerConn=this.createPeerConnection(),this.gotCallFeedsForInvite(e)}))}createPeerConnection(){const e=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize});return e.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),e.addEventListener("signalingstatechange",this.onSignallingStateChanged),e.addEventListener("icecandidate",this.gotLocalIceCandidate),e.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),e.addEventListener("track",this.onTrack),e.addEventListener("negotiationneeded",this.onNegotiationNeeded),e.addEventListener("datachannel",this.onDataChannel),e}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){const t=e.getContent();a.logger.debug(`Choosing party ID ${t.party_id} for call ID ${this.callId}`),this.opponentVersion=t.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=t.party_id||null,this.opponentCaps=t.capabilities||{},this.opponentMember=e.sender}addBufferedIceCandidates(){return s(this,void 0,void 0,(function*(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(a.logger.info(`Adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),yield this.addIceCandidates(e)),this.remoteCandidateBuffer=null}))}addIceCandidates(e){return s(this,void 0,void 0,(function*(){for(const t of e)if(null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex){a.logger.debug("Call "+this.callId+" got remote ICE "+t.sdpMid+" candidate: "+t.candidate);try{yield this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer||a.logger.info("Failed to add remote ICE candidate",e)}}else a.logger.debug("Ignoring remote ICE candidate with no sdpMid or sdpMLineIndex")}))}get hasPeerConnection(){return Boolean(this.peerConn)}}function T(e,t){for(let n=0;n<e.length;n++)e[n].enabled=t}function w(){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&&a.logger.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return a.logger.error("Exception thrown when trying to access WebRTC",e),!1}return!0}n.MatrixCall=_,n.supportsMatrixCall=w,n.createNewMatrixCall=function(e,t,n){if(!w())return null;const i=!!n&&n.forceTURN,r={client:e,roomId:t,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||i},o=new _(r);return e.reEmitter.reEmit(o,Object.values(m)),o}}).call(this)}).call(this,e("_process"))},{"../@types/event":72,"../logger":126,"../models/typed-event-emitter":143,"../randomstring":146,"../utils":159,"./callEventTypes":162,"./callFeed":163,_process:57}],161:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.CallEventHandler=n.CallEventHandlerEvent=void 0;const r=e("../models/event"),o=e("../logger"),s=e("./call"),a=e("../@types/event"),c=e("../client"),l=e("../sync"),d=e("../models/room");var u;!function(e){e.Incoming="Call.incoming"}(u=n.CallEventHandlerEvent||(n.CallEventHandlerEvent={}));n.CallEventHandler=class{constructor(e){this.evaluateEventBuffer=()=>i(this,void 0,void 0,(function*(){if(this.client.getSyncState()===l.SyncState.Syncing){yield Promise.all(this.callEventBuffer.map((e=>{this.client.decryptEventIfNeeded(e)})));const e=new Set;for(const t of this.callEventBuffer)t.getType()!==a.EventType.CallAnswer&&t.getType()!==a.EventType.CallHangup||e.add(t.getContent().call_id);for(const t of this.callEventBuffer)if(t.getType()!==a.EventType.CallInvite||!e.has(t.getContent().call_id))try{yield this.handleCallEvent(t)}catch(e){o.logger.error("Caught exception handling call event",e)}this.callEventBuffer=[]}})),this.onRoomTimeline=e=>{this.client.decryptEventIfNeeded(e),(this.eventIsACall(e)||e.isBeingDecrypted())&&this.callEventBuffer.push(e),(e.isBeingDecrypted()||e.isDecryptionFailure())&&e.once(r.MatrixEventEvent.Decrypted,(()=>i(this,void 0,void 0,(function*(){if(this.eventIsACall(e))if(this.callEventBuffer.includes(e))this.evaluateEventBuffer();else try{yield this.handleCallEvent(e)}catch(e){o.logger.error("Caught exception handling call event",e)}}))))},this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(c.ClientEvent.Sync,this.evaluateEventBuffer),this.client.on(d.RoomEvent.Timeline,this.onRoomTimeline)}stop(){this.client.removeListener(c.ClientEvent.Sync,this.evaluateEventBuffer),this.client.removeListener(d.RoomEvent.Timeline,this.onRoomTimeline)}eventIsACall(e){const t=e.getType();return t.startsWith("m.call.")||t.startsWith("org.matrix.call.")}handleCallEvent(e){return i(this,void 0,void 0,(function*(){const t=e.getContent(),n=e.getType(),i=e.getSender()===this.client.credentials.userId;let r=t.call_id?this.calls.get(t.call_id):void 0;if(n!==a.EventType.CallInvite)if(n!==a.EventType.CallCandidates)if([a.EventType.CallHangup,a.EventType.CallReject].includes(n))r?r.state!==s.CallState.Ended&&(n===a.EventType.CallHangup?r.onHangupReceived(t):r.onRejectReceived(t),r.state===s.CallState.Ended&&this.calls.delete(t.call_id)):(r=(0,s.createNewMatrixCall)(this.client,e.getRoomId()),r&&(r.callId=t.call_id,r.initWithHangup(e),this.calls.set(t.call_id,r)));else if(r&&r.hasPeerConnection){if(e.getContent().party_id!==r.ourPartyId)switch(n){case a.EventType.CallAnswer:i?r.state===s.CallState.Ringing&&r.onAnsweredElsewhere(t):r.onAnswerReceived(e);break;case a.EventType.CallSelectAnswer:r.onSelectAnswerReceived(e);break;case a.EventType.CallNegotiate:r.onNegotiateReceived(e);break;case a.EventType.CallAssertedIdentity:case a.EventType.CallAssertedIdentityPrefix:r.onAssertedIdentityReceived(e);break;case a.EventType.CallSDPStreamMetadataChanged:case a.EventType.CallSDPStreamMetadataChangedPrefix:r.onSDPStreamMetadataChangedReceived(e)}}else o.logger.info(`Discarding possible call event ${e.getId()} as we don't have a call/peerConn`,n);else{if(i)return;r?r.onRemoteIceCandidatesReceived(e):(this.candidateEventsByCall.has(t.call_id)||this.candidateEventsByCall.set(t.call_id,[]),this.candidateEventsByCall.get(t.call_id).push(e))}else{if(i)return;if(e.getLocalAge()>t.lifetime-3e3)return;if(r&&r.state===s.CallState.Ended)return;r&&o.logger.log(`WARN: Already have a MatrixCall with id ${t.call_id} but got an invite. Clobbering.`);const n=this.client.getTurnServersExpiry()-Date.now();if(o.logger.info("Current turn creds expire in "+n+" ms"),r=(0,s.createNewMatrixCall)(this.client,e.getRoomId(),{forceTURN:this.client.forceTURN}),!r)return void o.logger.log("Incoming call ID "+t.call_id+" but this client doesn't support WebRTC");if(r.callId=t.call_id,yield r.initWithInvite(e),this.calls.set(r.callId,r),this.candidateEventsByCall.get(r.callId))for(const e of this.candidateEventsByCall.get(r.callId))r.onRemoteIceCandidatesReceived(e);let a;for(const e of this.calls.values()){const t=[s.CallState.WaitLocalMedia,s.CallState.CreateOffer,s.CallState.InviteSent].includes(e.state);if(r.roomId===e.roomId&&e.direction===s.CallDirection.Outbound&&t){a=e;break}}a?a.state===s.CallState.WaitLocalMedia||a.state===s.CallState.CreateOffer||a.callId>r.callId?(o.logger.log("Glare detected: answering incoming call "+r.callId+" and canceling outgoing call "+a.callId),a.replacedBy(r),r.answer()):(o.logger.log("Glare detected: rejecting incoming call "+r.callId+" and keeping outgoing call "+a.callId),r.hangup(s.CallErrorCode.Replaced,!0)):this.client.emit(u.Incoming,r)}}))}}},{"../@types/event":72,"../client":84,"../logger":126,"../models/event":135,"../models/room":140,"../sync":157,"./call":160}],162:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.SDPStreamMetadataPurpose=n.SDPStreamMetadataKey=void 0,n.SDPStreamMetadataKey="org.matrix.msc3077.sdp_stream_metadata",function(e){e.Usermedia="m.usermedia",e.Screenshare="m.screenshare"}(n.SDPStreamMetadataPurpose||(n.SDPStreamMetadataPurpose={}))},{}],163:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.CallFeed=n.CallFeedEvent=n.SPEAKING_THRESHOLD=void 0;const i=e("../models/typed-event-emitter");n.SPEAKING_THRESHOLD=-60;var r;!function(e){e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.VolumeChanged="volume_changed",e.Speaking="speaking"}(r=n.CallFeedEvent||(n.CallFeedEvent={}));class o extends i.TypedEventEmitter{constructor(e){super(),this.measuringVolumeActivity=!1,this.speakingThreshold=n.SPEAKING_THRESHOLD,this.speaking=!1,this.onAddTrack=()=>{this.emit(r.NewStream,this.stream)},this.volumeLooper=()=>{if(!this.analyser)return;if(!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let e=-1/0;for(let t=0;t<this.frequencyBinCount.length;t++)this.frequencyBinCount[t]>e&&(e=this.frequencyBinCount[t]);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(e),this.emit(r.VolumeChanged,e);let t=!1;for(let e=0;e<this.speakingVolumeSamples.length;e++){if(this.speakingVolumeSamples[e]>this.speakingThreshold){t=!0;break}}this.speaking!==t&&(this.speaking=t,this.emit(r.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,200)},this.client=e.client,this.roomId=e.roomId,this.userId=e.userId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(8).fill(-1/0),this.updateStream(null,e.stream),this.hasAudioTrack&&this.initVolumeMeasuring()}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){t!==e&&(e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),t&&(this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?this.initVolumeMeasuring():this.measureVolumeActivity(!1)),this.emit(r.NewStream,this.stream))}initVolumeMeasuring(){const e=window.AudioContext||window.webkitAudioContext;if(!this.hasAudioTrack||!e)return;this.audioContext=new e,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(){return this.client.getRoom(this.roomId).getMember(this.userId)}isLocal(){return this.userId===this.client.getUserId()}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)}setAudioMuted(e){this.audioMuted=e,this.speakingVolumeSamples.fill(-1/0),this.emit(r.MuteStateChanged,this.audioMuted,this.videoMuted)}setVideoMuted(e){this.videoMuted=e,this.emit(r.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!(this.audioContext&&this.analyser&&this.frequencyBinCount&&this.hasAudioTrack))return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(r.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}dispose(){clearTimeout(this.volumeLooperTimeout)}}n.CallFeed=o},{"../models/typed-event-emitter":143}],164:[function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(n,"__esModule",{value:!0}),n.MediaHandler=void 0;const r=e("../logger"),o=e("./call");n.MediaHandler=class{constructor(e){this.client=e,this.userMediaStreams=[],this.screensharingStreams=[]}setAudioInput(e){return i(this,void 0,void 0,(function*(){r.logger.info("LOG setting audio input to",e),this.audioInput!==e&&(this.audioInput=e,yield this.updateLocalUsermediaStreams())}))}setVideoInput(e){return i(this,void 0,void 0,(function*(){r.logger.info("LOG setting video input to",e),this.videoInput!==e&&(this.videoInput=e,yield this.updateLocalUsermediaStreams())}))}updateLocalUsermediaStreams(){return i(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 t of this.client.callEventHandler.calls.values()){if(t.state===o.CallState.Ended||!e.has(t.callId))continue;const{audio:n,video:i}=e.get(t.callId),r=yield this.getUserMediaStream(n,i,!1);yield t.updateLocalUsermediaStream(r)}}))}hasAudioDevice(){return i(this,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind)).length>0}))}hasVideoDevice(){return i(this,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).length>0}))}getUserMediaStream(e,t,n=!0){var o,s,a,c;return i(this,void 0,void 0,(function*(){const i=e&&(yield this.hasAudioDevice()),l=t&&(yield this.hasVideoDevice());let d;if(!this.localUserMediaStream||0===this.localUserMediaStream.getAudioTracks().length&&i||0===this.localUserMediaStream.getVideoTracks().length&&l||(null===(s=null===(o=this.localUserMediaStream.getAudioTracks()[0])||void 0===o?void 0:o.getSettings())||void 0===s?void 0:s.deviceId)!==this.audioInput||(null===(c=null===(a=this.localUserMediaStream.getVideoTracks()[0])||void 0===a?void 0:a.getSettings())||void 0===c?void 0:c.deviceId)!==this.videoInput){const e=this.getUserMediaContraints(i,l);r.logger.log("Getting user media with constraints",e),d=yield navigator.mediaDevices.getUserMedia(e);for(const e of d.getTracks()){const t=e.getSettings();"audio"===e.kind?this.audioInput=t.deviceId:"video"===e.kind&&(this.videoInput=t.deviceId)}n&&(this.localUserMediaStream=d)}else{if(d=this.localUserMediaStream.clone(),!i)for(const e of d.getAudioTracks())d.removeTrack(e);if(!l)for(const e of d.getVideoTracks())d.removeTrack(e)}return n&&this.userMediaStreams.push(d),d}))}stopUserMediaStream(e){r.logger.debug("Stopping usermedia stream",e.id);for(const t of e.getTracks())t.stop();const t=this.userMediaStreams.indexOf(e);-1!==t&&(r.logger.debug("Splicing usermedia stream out stream array",e.id),this.userMediaStreams.splice(t,1)),this.localUserMediaStream===e&&(this.localUserMediaStream=void 0)}getScreensharingStream(e,t=!0){return i(this,void 0,void 0,(function*(){let n;if(0===this.screensharingStreams.length){const t=this.getScreenshareContraints(e);if(!t)return null;e?(r.logger.debug("Getting screensharing stream using getUserMedia()",e),n=yield navigator.mediaDevices.getUserMedia(t)):(r.logger.debug("Getting screensharing stream using getDisplayMedia()"),n=yield navigator.mediaDevices.getDisplayMedia(t))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];r.logger.log("Cloning screensharing stream",e.id),n=e.clone()}return t&&this.screensharingStreams.push(n),n}))}stopScreensharingStream(e){r.logger.debug("Stopping screensharing stream",e.id);for(const t of e.getTracks())t.stop();const t=this.screensharingStreams.indexOf(e);-1!==t&&(r.logger.debug("Splicing screensharing stream out stream array",e.id),this.screensharingStreams.splice(t,1))}stopAllStreams(){for(const e of this.userMediaStreams)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}getUserMediaContraints(e,t){const n=!!navigator.webkitGetUserMedia;return{audio:!!e&&{deviceId:this.audioInput?{ideal:this.audioInput}:void 0},video:!!t&&{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:n?{exact:640}:{ideal:640},height:n?{exact:360}:{ideal:360}}}}getScreenshareContraints(e){return e?(r.logger.debug("Using desktop capturer source",e),{audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e}}}):(r.logger.debug("Not using desktop capturer source"),{audio:!1,video:!0})}}},{"../logger":126,"./call":160}]},{},[83]);
|