@liascript/exporter 2.2.0--0.10.0 → 2.2.0--0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/assets/indexeddb/icon.05160f63.woff +0 -0
  2. package/dist/assets/indexeddb/icon.263395d9.woff2 +0 -0
  3. package/dist/assets/{scorm1.2/icon.1a0c9db0.eot → indexeddb/icon.444ba4a7.eot} +0 -0
  4. package/dist/assets/{scorm2004/icon.95d89539.svg → indexeddb/icon.60022774.svg} +1 -1
  5. package/dist/assets/indexeddb/{icon.1a0c9db0.eot → icon.c688815e.ttf} +0 -0
  6. package/dist/assets/indexeddb/index.15b24674.js +1 -0
  7. package/dist/assets/indexeddb/index.34c432d7.js +1 -0
  8. package/dist/assets/indexeddb/{index.20e4bb88.js → index.57ee398c.js} +1 -1
  9. package/dist/assets/indexeddb/index.da081100.css +2 -0
  10. package/dist/assets/indexeddb/index.html +1 -1
  11. package/dist/assets/pdf/icon.05160f63.woff +0 -0
  12. package/dist/assets/pdf/icon.263395d9.woff2 +0 -0
  13. package/dist/assets/{scorm2004/icon.1a0c9db0.eot → pdf/icon.444ba4a7.eot} +0 -0
  14. package/dist/assets/pdf/{icon.95d89539.svg → icon.60022774.svg} +1 -1
  15. package/dist/assets/{indexeddb/icon.f3d23f63.ttf → pdf/icon.c688815e.ttf} +0 -0
  16. package/dist/assets/pdf/index.34918aba.js +1 -0
  17. package/dist/assets/pdf/index.4eb67871.js +1 -0
  18. package/dist/assets/pdf/index.6a227a4e.js +1 -0
  19. package/dist/assets/pdf/index.8cfb3ae9.css +2 -0
  20. package/dist/assets/pdf/index.html +1 -1
  21. package/dist/assets/scorm1.2/icon.05160f63.woff +0 -0
  22. package/dist/assets/scorm1.2/icon.263395d9.woff2 +0 -0
  23. package/dist/assets/scorm1.2/icon.444ba4a7.eot +0 -0
  24. package/dist/assets/scorm1.2/{icon.95d89539.svg → icon.60022774.svg} +1 -1
  25. package/dist/assets/{pdf/icon.74e441c4.ttf → scorm1.2/icon.c688815e.ttf} +0 -0
  26. package/dist/assets/scorm1.2/index.15b24674.js +1 -0
  27. package/dist/assets/{web/index.20e4bb88.js → scorm1.2/index.57ee398c.js} +1 -1
  28. package/dist/assets/scorm1.2/index.da081100.css +2 -0
  29. package/dist/assets/scorm1.2/index.dd21a342.js +1 -0
  30. package/dist/assets/scorm1.2/index.html +1 -1
  31. package/dist/assets/scorm2004/icon.05160f63.woff +0 -0
  32. package/dist/assets/scorm2004/icon.263395d9.woff2 +0 -0
  33. package/dist/assets/scorm2004/icon.444ba4a7.eot +0 -0
  34. package/dist/assets/{indexeddb/icon.95d89539.svg → scorm2004/icon.60022774.svg} +1 -1
  35. package/dist/assets/{pdf/icon.f3eefe1e.eot → scorm2004/icon.c688815e.ttf} +0 -0
  36. package/dist/assets/scorm2004/index.15b24674.js +1 -0
  37. package/dist/assets/scorm2004/index.501ad7a7.js +1 -0
  38. package/dist/assets/{scorm1.2/index.20e4bb88.js → scorm2004/index.57ee398c.js} +1 -1
  39. package/dist/assets/scorm2004/index.da081100.css +2 -0
  40. package/dist/assets/scorm2004/index.html +1 -1
  41. package/dist/assets/web/icon.05160f63.woff +0 -0
  42. package/dist/assets/web/icon.263395d9.woff2 +0 -0
  43. package/dist/assets/web/icon.444ba4a7.eot +0 -0
  44. package/dist/assets/web/icon.60022774.svg +1 -0
  45. package/dist/assets/web/icon.c688815e.ttf +0 -0
  46. package/dist/assets/web/index.15b24674.js +1 -0
  47. package/dist/assets/{scorm2004/index.20e4bb88.js → web/index.57ee398c.js} +1 -1
  48. package/dist/assets/web/index.9cbf3c78.js +1 -0
  49. package/dist/assets/web/index.da081100.css +2 -0
  50. package/dist/assets/web/index.html +1 -1
  51. package/dist/index.js +2 -4
  52. package/output.pdf +0 -0
  53. package/package.json +1 -1
  54. package/src/index.ts +1 -1
  55. package/dist/assets/indexeddb/icon.589b6ad7.woff +0 -0
  56. package/dist/assets/indexeddb/icon.85f94224.woff2 +0 -0
  57. package/dist/assets/indexeddb/index.53bf5066.js +0 -1
  58. package/dist/assets/indexeddb/index.db57a2e0.css +0 -2
  59. package/dist/assets/indexeddb/index.e77f639b.js +0 -1
  60. package/dist/assets/indexeddb/vendor/browser-matrix.min.js +0 -18
  61. package/dist/assets/indexeddb/vendor/browser-matrix.min.js.map +0 -1
  62. package/dist/assets/pdf/icon.0052da31.woff2 +0 -0
  63. package/dist/assets/pdf/icon.618c9e50.woff +0 -0
  64. package/dist/assets/pdf/index.1301ab01.css +0 -2
  65. package/dist/assets/pdf/index.78c516ac.js +0 -1
  66. package/dist/assets/pdf/index.980e3eb5.js +0 -1
  67. package/dist/assets/pdf/index.a08c2596.js +0 -1
  68. package/dist/assets/pdf/vendor/browser-matrix.min.js +0 -18
  69. package/dist/assets/pdf/vendor/browser-matrix.min.js.map +0 -1
  70. package/dist/assets/scorm1.2/icon.589b6ad7.woff +0 -0
  71. package/dist/assets/scorm1.2/icon.85f94224.woff2 +0 -0
  72. package/dist/assets/scorm1.2/icon.f3d23f63.ttf +0 -0
  73. package/dist/assets/scorm1.2/index.13cf7c84.js +0 -1
  74. package/dist/assets/scorm1.2/index.db57a2e0.css +0 -2
  75. package/dist/assets/scorm1.2/index.e77f639b.js +0 -1
  76. package/dist/assets/scorm1.2/vendor/browser-matrix.min.js +0 -18
  77. package/dist/assets/scorm1.2/vendor/browser-matrix.min.js.map +0 -1
  78. package/dist/assets/scorm2004/icon.589b6ad7.woff +0 -0
  79. package/dist/assets/scorm2004/icon.85f94224.woff2 +0 -0
  80. package/dist/assets/scorm2004/icon.f3d23f63.ttf +0 -0
  81. package/dist/assets/scorm2004/index.24949300.js +0 -1
  82. package/dist/assets/scorm2004/index.db57a2e0.css +0 -2
  83. package/dist/assets/scorm2004/index.e77f639b.js +0 -1
  84. package/dist/assets/scorm2004/vendor/browser-matrix.min.js +0 -18
  85. package/dist/assets/scorm2004/vendor/browser-matrix.min.js.map +0 -1
  86. package/dist/assets/web/icon.1a0c9db0.eot +0 -0
  87. package/dist/assets/web/icon.589b6ad7.woff +0 -0
  88. package/dist/assets/web/icon.85f94224.woff2 +0 -0
  89. package/dist/assets/web/icon.95d89539.svg +0 -1
  90. package/dist/assets/web/icon.f3d23f63.ttf +0 -0
  91. package/dist/assets/web/index.762e3251.js +0 -1
  92. package/dist/assets/web/index.db57a2e0.css +0 -2
  93. package/dist/assets/web/index.e77f639b.js +0 -1
  94. package/dist/assets/web/vendor/browser-matrix.min.js +0 -18
  95. package/dist/assets/web/vendor/browser-matrix.min.js.map +0 -1
@@ -1,18 +0,0 @@
1
- !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 d=new Error("Cannot find module '"+s+"'");throw d.code="MODULE_NOT_FOUND",d}var l=n[s]={exports:{}};t[s][0].call(l.exports,(function(e){return r(t[s][1][e]||e)}),l,l.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.default=t.exports,t.exports.__esModule=!0},{}],2:[function(e,t,n){function i(e,t,n,i,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(i,r)}t.exports=function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var s=e.apply(t,n);function a(e){i(s,r,o,a,c,"next",e)}function c(e){i(s,r,o,a,c,"throw",e)}a(void 0)}))}},t.exports.default=t.exports,t.exports.__esModule=!0},{}],3:[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.default=t.exports,t.exports.__esModule=!0},{}],4:[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,t.exports.default=t.exports,t.exports.__esModule=!0):(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.default=t.exports,t.exports.__esModule=!0),o.apply(null,arguments)}t.exports=o,t.exports.default=t.exports,t.exports.__esModule=!0},{"./isNativeReflectConstruct.js":11,"./setPrototypeOf.js":13}],5:[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),e},t.exports.default=t.exports,t.exports.__esModule=!0},{}],6:[function(e,t,n){t.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},t.exports.default=t.exports,t.exports.__esModule=!0},{}],7:[function(e,t,n){function i(e){return t.exports=i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},t.exports.default=t.exports,t.exports.__esModule=!0,i(e)}t.exports=i,t.exports.default=t.exports,t.exports.__esModule=!0},{}],8:[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}}),t&&i(e,t)},t.exports.default=t.exports,t.exports.__esModule=!0},{"./setPrototypeOf.js":13}],9:[function(e,t,n){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.default=t.exports,t.exports.__esModule=!0},{}],10:[function(e,t,n){t.exports=function(e){return-1!==Function.toString.call(e).indexOf("[native code]")},t.exports.default=t.exports,t.exports.__esModule=!0},{}],11:[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.default=t.exports,t.exports.__esModule=!0},{}],12:[function(e,t,n){var i=e("@babel/runtime/helpers/typeof").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.default=t.exports,t.exports.__esModule=!0},{"./assertThisInitialized.js":1,"@babel/runtime/helpers/typeof":14}],13:[function(e,t,n){function i(e,n){return t.exports=i=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},t.exports.default=t.exports,t.exports.__esModule=!0,i(e,n)}t.exports=i,t.exports.default=t.exports,t.exports.__esModule=!0},{}],14:[function(e,t,n){function i(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?(t.exports=i=function(e){return typeof e},t.exports.default=t.exports,t.exports.__esModule=!0):(t.exports=i=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.default=t.exports,t.exports.__esModule=!0),i(e)}t.exports=i,t.exports.default=t.exports,t.exports.__esModule=!0},{}],15:[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.default=t.exports,t.exports.__esModule=!0,a(e)}t.exports=a,t.exports.default=t.exports,t.exports.__esModule=!0},{"./construct.js":4,"./getPrototypeOf.js":7,"./isNativeFunction.js":10,"./setPrototypeOf.js":13}],16:[function(e,t,n){t.exports=e("regenerator-runtime")},{"regenerator-runtime":48}],17:[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}},{}],18:[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),d=Math.log(a)/Math.log(256),l=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);var n=0;if(" "!==e[n]){for(var r=0,o=0;e[n]===c;)r++,n++;for(var s=(e.length-n)*d+1>>>0,l=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*l[g]>>>0,l[g]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");o=h,n++}if(" "!==e[n]){for(var p=s-o;p!==s&&0===l[p];)p++;var f=i.allocUnsafe(r+(s-p));f.fill(0,0,r);for(var y=r;p!==s;)f[y++]=l[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 d=(s-o)*l+1>>>0,u=new Uint8Array(d);o!==s;){for(var h=t[o],g=0,p=d-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=d-r;f!==d&&0===u[f];)f++;for(var y=c.repeat(n);f<d;++f)y+=e.charAt(u[f]);return y},decodeUnsafe:u,decode:function(e){var t=u(e);if(t)return t;throw new Error("Non-base"+a+" character")}}}},{"safe-buffer":52}],19:[function(e,t,n){"use strict";n.byteLength=function(e){var t=d(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=d(e),s=i[0],a=i[1],c=new o(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),l=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[l++]=t>>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===a&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,c[l++]=255&t);1===a&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=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(l(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 d(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 l(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},{}],20:[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"],d=0;d<c.length;d++)if(o[c[d]])throw new Error("options."+c[d]+" 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 l=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:l(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=l(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,d="",l=[];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,l[c++]=s.charAt(t)+s.charAt(n)+s.charAt(i)+s.charAt(r)}while(a<e.length);switch(d=l.join(""),e.length%3){case 1:d=d.slice(0,-2)+"==";break;case 2:d=d.slice(0,-1)+"="}return d}(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 d(){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(d,i.timeout);var l={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(!l.response){if(l.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",l.loading=!0,l.end=!0,i.callback(e,r)}i.onResponse(null,r)}}function g(){l.loading||(l.loading=!0,t.log.debug("Response body loading",{id:r.id}))}function p(){if(!l.end){if(l.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()},{}],21:[function(e,t,n){},{}],22:[function(e,t,n){(function(e){(function(){!function(i){var r="object"==typeof n&&n&&!n.nodeType&&n,o="object"==typeof t&&t&&!t.nodeType&&t,s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self!==s||(i=s);var a,c,d=2147483647,l=36,u=/^xn--/,h=/[^\x20-\x7E]/,g=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,y=String.fromCharCode;function m(e){throw new RangeError(p[e])}function v(e,t){for(var n=e.length,i=[];n--;)i[n]=t(e[n]);return i}function S(e,t){var n=e.split("@"),i="";return n.length>1&&(i=n[0]+"@",e=n[1]),i+v((e=e.replace(g,".")).split("."),t).join(".")}function E(e){for(var t,n,i=[],r=0,o=e.length;r<o;)(t=e.charCodeAt(r++))>=55296&&t<=56319&&r<o?56320==(64512&(n=e.charCodeAt(r++)))?i.push(((1023&t)<<10)+(1023&n)+65536):(i.push(t),r--):i.push(t);return i}function b(e){return v(e,(function(e){var t="";return e>65535&&(t+=y((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=y(e)})).join("")}function _(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,n){var i=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;i+=l)e=f(e/35);return f(i+36*e/(e+38))}function T(e){var t,n,i,r,o,s,a,c,u,h,g,p=[],y=e.length,v=0,S=128,E=72;for((n=e.lastIndexOf("-"))<0&&(n=0),i=0;i<n;++i)e.charCodeAt(i)>=128&&m("not-basic"),p.push(e.charCodeAt(i));for(r=n>0?n+1:0;r<y;){for(o=v,s=1,a=l;r>=y&&m("invalid-input"),((c=(g=e.charCodeAt(r++))-48<10?g-22:g-65<26?g-65:g-97<26?g-97:l)>=l||c>f((d-v)/s))&&m("overflow"),v+=c*s,!(c<(u=a<=E?1:a>=E+26?26:a-E));a+=l)s>f(d/(h=l-u))&&m("overflow"),s*=h;E=w(v-o,t=p.length+1,0==o),f(v/t)>d-S&&m("overflow"),S+=f(v/t),v%=t,p.splice(v++,0,S)}return b(p)}function I(e){var t,n,i,r,o,s,a,c,u,h,g,p,v,S,b,T=[];for(p=(e=E(e)).length,t=128,n=0,o=72,s=0;s<p;++s)(g=e[s])<128&&T.push(y(g));for(i=r=T.length,r&&T.push("-");i<p;){for(a=d,s=0;s<p;++s)(g=e[s])>=t&&g<a&&(a=g);for(a-t>f((d-n)/(v=i+1))&&m("overflow"),n+=(a-t)*v,t=a,s=0;s<p;++s)if((g=e[s])<t&&++n>d&&m("overflow"),g==t){for(c=n,u=l;!(c<(h=u<=o?1:u>=o+26?26:u-o));u+=l)b=c-h,S=l-h,T.push(y(_(h+b%S,0))),c=f(b/S);T.push(y(_(c,0))),o=w(n,v,i==r),n=0,++i}++n,++t}return T.join("")}if(a={version:"1.4.1",ucs2:{decode:E,encode:b},decode:T,encode:I,toASCII:function(e){return S(e,(function(e){return h.test(e)?"xn--"+I(e):e}))},toUnicode:function(e){return S(e,(function(e){return u.test(e)?T(e.slice(4).toLowerCase()):e}))}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",(function(){return a}));else if(r&&o)if(t.exports==r)o.exports=a;else for(c in a)a.hasOwnProperty(c)&&(r[c]=a[c]);else i.punycode=a}(this)}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],23:[function(e,t,n){var i=e("base-x");t.exports=i("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},{"base-x":18}],24:[function(e,t,n){(function(t){(function(){
2
- /*!
3
- * The buffer module from node.js, for the browser.
4
- *
5
- * @author Feross Aboukhadijeh <https://feross.org>
6
- * @license MIT
7
- */
8
- "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 d(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 l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(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):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,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 d(e){return c(e),o(e<0?0:0|u(e))}function l(e){for(var t=e.length<0?0:0|u(e.length),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 B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(r)return i?-1:B(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 C(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return w(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(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:y(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):y(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function y(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 d(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(o=n;o<a;o++)if(d(e,o)===d(t,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===c)return l*s}else-1!==l&&(o-=o-l),l=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){for(var u=!0,h=0;h<c;h++)if(d(e,o+h)!==d(t,h)){u=!1;break}if(u)return o}return-1}function m(e,t,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 v(e,t,n,i){return L(B(t,e.length-n),e,n,i)}function S(e,t,n,i){return L(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function E(e,t,n,i){return S(e,t,n,i)}function b(e,t,n,i){return L(K(t),e,n,i)}function _(e,t,n,i){return L(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 w(e,n,i){return 0===n&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,i))}function T(e,t,n){n=Math.min(e.length,n);for(var i=[],r=t;r<n;){var o,s,a,c,d=e[r],l=null,u=d>239?4:d>223?3:d>191?2:1;if(r+u<=n)switch(u){case 1:d<128&&(l=d);break;case 2:128==(192&(o=e[r+1]))&&(c=(31&d)<<6|63&o)>127&&(l=c);break;case 3:o=e[r+1],s=e[r+2],128==(192&o)&&128==(192&s)&&(c=(15&d)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[r+1],s=e[r+2],a=e[r+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&d)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,u=1):l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|1023&l),i.push(l),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 d(e)},s.allocUnsafeSlow=function(e){return d(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(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?T(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),d=this.slice(i,r),l=e.slice(t,n),u=0;u<c;++u)if(d[u]!==l[u]){o=d[u],a=l[u];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,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 m(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return E(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 C(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 O(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 D(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 A(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 P(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 M(e,t,n,r,o){return t=+t,n>>>=0,o||P(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||P(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||D(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||D(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||D(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(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||D(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||D(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||D(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||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||D(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||D(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||D(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||D(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||D(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(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)||A(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)||A(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||A(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||A(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||A(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||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var r=Math.pow(2,8*n-1);A(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);A(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||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||A(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||A(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||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return M(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 B(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 K(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 L(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":19,buffer:24,ieee754:35}],25:[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}},{"./":26,"get-intrinsic":31}],26:[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),d=r("%Object.defineProperty%",!0),l=r("%Math.max%");if(d)try{d({},"a",{value:1})}catch(e){d=null}t.exports=function(e){var t=a(i,s,arguments);if(c&&d){var n=c(t,"length");n.configurable&&d(t,"length",{value:1+l(0,e.length-(arguments.length-1))})}return t};var u=function(){return a(i,o,arguments)};d?d(t.exports,"apply",{value:u}):t.exports.apply=u},{"function-bind":30,"get-intrinsic":31}],27:[function(e,t,n){
9
- /*!
10
- * content-type
11
- * Copyright(c) 2015 Douglas Christopher Wilson
12
- * MIT Licensed
13
- */
14
- "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 d(e){var t=String(e);if(o.test(t))return t;if(t.length>0&&!r.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(a,"\\$1")+'"'}function l(e){this.parameters=Object.create(null),this.type=e}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+"="+d(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 l(r.toLowerCase());if(-1!==n){var a,d,u;for(i.lastIndex=n;d=i.exec(t);){if(d.index!==n)throw new TypeError("invalid parameter format");n+=d[0].length,a=d[1].toLowerCase(),'"'===(u=d[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}},{}],28:[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))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(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 d(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,n,i){var r,o,s,a;if(d(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=l(e))>0&&s.length>r&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function 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):y(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 y(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function m(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 l(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 d=c.length,l=y(c,d);for(n=0;n<d;++n)o(l[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 d(t),this.on(e,g(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return d(t),this.prependListener(e,g(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,i,r,o,s;if(d(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):[]}},{}],29:[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)))},d=Math.max(0,t.length-a.length),l=[],u=0;u<d;u++)l.push("$"+u);if(n=Function("binder","return function ("+l.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}},{}],30:[function(e,t,n){"use strict";var i=e("./implementation");t.exports=Function.prototype.bind||i},{"./implementation":29}],31:[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 d=function(){throw new s},l=c?function(){try{return d}catch(e){try{return c(arguments,"callee").get}catch(e){return d}}}():d,u=e("has-symbols")(),h=Object.getPrototypeOf||function(e){return e.__proto__},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%":l,"%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},y=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},m={"%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"]},v=e("function-bind"),S=e("has"),E=v.call(Function.call,Array.prototype.concat),b=v.call(Function.apply,Array.prototype.splice),_=v.call(Function.call,String.prototype.replace),w=v.call(Function.call,String.prototype.slice),T=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,R=function(e){var t=w(e,0,1),n=w(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,T,(function(e,t,n,r){i[i.length]=n?_(r,I,"$1"):t||e})),i},k=function(e,t){var n,i=e;if(S(m,i)&&(i="%"+(n=m[i])[0]+"%"),S(f,i)){var o=f[i];if(o===g&&(o=y(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,d=o.value,l=!1,u=o.alias;u&&(i=u[0],b(n,E([0,1],u)));for(var h=1,g=!0;h<n.length;h+=1){var p=n[h],y=w(p,0,1),m=w(p,-1);if(('"'===y||"'"===y||"`"===y||'"'===m||"'"===m||"`"===m)&&y!==m)throw new r("property names with quotes must have matching quotes");if("constructor"!==p&&g||(l=!0),S(f,a="%"+(i+="."+p)+"%"))d=f[a];else if(null!=d){if(!(p in d)){if(!t)throw new s("base intrinsic for "+e+" exists, but the property is not available.");return}if(c&&h+1>=n.length){var v=c(d,p);d=(g=!!v)&&"get"in v&&!("originalValue"in v.get)?v.get:d[p]}else g=S(d,p),d=d[p];g&&!l&&(f[a]=d)}}return d}},{"function-bind":30,has:34,"has-symbols":32}],32:[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":33}],33:[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}},{}],34:[function(e,t,n){"use strict";var i=e("function-bind");t.exports=i.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":30}],35:[function(e,t,n){
15
- /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
16
- n.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,c=(1<<a)-1,d=c>>1,l=-7,u=n?r-1:0,h=n?-1:1,g=e[t+u];for(u+=h,o=g&(1<<-l)-1,g>>=-l,l+=a;l>0;o=256*o+e[t+u],u+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=i;l>0;s=256*s+e[t+u],u+=h,l-=8);if(0===o)o=1-d;else{if(o===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,i),o-=d}return(g?-1:1)*s*Math.pow(2,o-i)},n.write=function(e,t,n,i,r,o){var s,a,c,d=8*o-r-1,l=(1<<d)-1,u=l>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,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=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=l?(a=0,s=l):s+u>=1?(a=(t*c-1)*Math.pow(2,r),s+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),s=0));r>=8;e[n+g]=255&a,g+=p,a/=256,r-=8);for(s=s<<r|a,d+=r;d>0;e[n+g]=255&s,g+=p,s/=256,d-=8);e[n+g-p]|=128*f}},{}],36:[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 d(e,t,n){return s(e)||c.apply(this,arguments)}function l(e,n,r){var o,s=this,c="loglevel";function l(){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||d,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){l()||s.setLevel(e,!1)},s.enableAll=function(e){s.setLevel(s.levels.TRACE,e)},s.disableAll=function(e){s.setLevel(s.levels.SILENT,e)};var u=l();null==u&&(u=null==n?"WARN":n),s.setLevel(u,!1)}var u=new l,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 l(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}))},{}],37:[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,d=a&&c&&"function"==typeof c.get?c.get:null,l=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,y=Function.prototype.toString,m=String.prototype.match,v="function"==typeof BigInt?BigInt.prototype.valueOf:null,S=Object.getOwnPropertySymbols,E="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,b="function"==typeof Symbol&&"object"==typeof Symbol.iterator,_=Object.prototype.propertyIsEnumerable,w=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),T=e("./util.inspect").custom,I=T&&D(T)?T:null,R="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function k(e,t,n){var i="double"===(n.quoteStyle||t)?'"':"'";return i+e+i}function C(e){return String(e).replace(/"/g,"&quot;")}function O(e){return!("[object Array]"!==M(e)||R&&"object"==typeof e&&R in e)}function D(e){if(b)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!E)return!1;try{return E.call(e),!0}catch(e){}return!1}t.exports=function e(t,n,i,r){var a=n||{};if(P(a,"quoteStyle")&&"single"!==a.quoteStyle&&"double"!==a.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(P(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=!P(a,"customInspect")||a.customInspect;if("boolean"!=typeof c&&"symbol"!==c)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(P(a,"indent")&&null!==a.indent&&"\t"!==a.indent&&!(parseInt(a.indent,10)===a.indent&&a.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return U(t,a);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var f=void 0===a.depth?5:a.depth;if(void 0===i&&(i=0),i>=f&&f>0&&"object"==typeof t)return O(t)?"[Array]":"[Object]";var S=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=Array(e.indent+1).join(" ")}return{base:n,prev:Array(t+1).join(n)}}(a,i);if(void 0===r)r=[];else if(x(r,t)>=0)return"[Circular]";function _(t,n,o){if(n&&(r=r.slice()).push(n),o){var s={depth:a.depth};return P(a,"quoteStyle")&&(s.quoteStyle=a.quoteStyle),e(t,s,i+1,r)}return e(t,a,i+1,r)}if("function"==typeof t){var T=function(e){if(e.name)return e.name;var t=m.call(y.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),A=F(t,_);return"[Function"+(T?": "+T:" (anonymous)")+"]"+(A.length>0?" { "+A.join(", ")+" }":"")}if(D(t)){var N=b?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):E.call(t);return"object"!=typeof t||b?N:B(N)}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 q="<"+String(t.nodeName).toLowerCase(),$=t.attributes||[],G=0;G<$.length;G++)q+=" "+$[G].name+"="+k(C($[G].value),"double",a);return q+=">",t.childNodes&&t.childNodes.length&&(q+="..."),q+="</"+String(t.nodeName).toLowerCase()+">"}if(O(t)){if(0===t.length)return"[]";var V=F(t,_);return S&&!function(e){for(var t=0;t<e.length;t++)if(x(e[t],"\n")>=0)return!1;return!0}(V)?"["+j(V,S)+"]":"[ "+V.join(", ")+" ]"}if(function(e){return!("[object Error]"!==M(e)||R&&"object"==typeof e&&R in e)}(t)){var H=F(t,_);return 0===H.length?"["+String(t)+"]":"{ ["+String(t)+"] "+H.join(", ")+" }"}if("object"==typeof t&&c){if(I&&"function"==typeof t[I])return t[I]();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{d.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var W=[];return s.call(t,(function(e,n){W.push(_(n,t,!0)+" => "+_(e,t))})),L("Map",o.call(t),W,S)}if(function(e){if(!d||!e||"object"!=typeof e)return!1;try{d.call(e);try{o.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var Y=[];return l.call(t,(function(e){Y.push(_(e,t))})),L("Set",d.call(t),Y,S)}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 K("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 K("WeakSet");if(function(e){if(!g||!e||"object"!=typeof e)return!1;try{return g.call(e),!0}catch(e){}return!1}(t))return K("WeakRef");if(function(e){return!("[object Number]"!==M(e)||R&&"object"==typeof e&&R in e)}(t))return B(_(Number(t)));if(function(e){if(!e||"object"!=typeof e||!v)return!1;try{return v.call(e),!0}catch(e){}return!1}(t))return B(_(v.call(t)));if(function(e){return!("[object Boolean]"!==M(e)||R&&"object"==typeof e&&R in e)}(t))return B(p.call(t));if(function(e){return!("[object String]"!==M(e)||R&&"object"==typeof e&&R in e)}(t))return B(_(String(t)));if(!function(e){return!("[object Date]"!==M(e)||R&&"object"==typeof e&&R in e)}(t)&&!function(e){return!("[object RegExp]"!==M(e)||R&&"object"==typeof e&&R in e)}(t)){var Q=F(t,_),J=w?w(t)===Object.prototype:t instanceof Object||t.constructor===Object,z=t instanceof Object?"":"null prototype",X=!J&&R&&Object(t)===t&&R in t?M(t).slice(8,-1):z?"Object":"",Z=(J||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(X||z?"["+[].concat(X||[],z||[]).join(": ")+"] ":"");return 0===Q.length?Z+"{}":S?Z+"{"+j(Q,S)+"}":Z+"{ "+Q.join(", ")+" }"}return String(t)};var A=Object.prototype.hasOwnProperty||function(e){return e in this};function P(e,t){return A.call(e,t)}function M(e){return f.call(e)}function x(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 U(e,t){if(e.length>t.maxStringLength){var n=e.length-t.maxStringLength,i="... "+n+" more character"+(n>1?"s":"");return U(e.slice(0,t.maxStringLength),t)+i}return k(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,N),"single",t)}function N(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":"")+t.toString(16).toUpperCase()}function B(e){return"Object("+e+")"}function K(e){return e+" { ? }"}function L(e,t,n,i){return e+" ("+t+") {"+(i?j(n,i):n.join(", "))+"}"}function j(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+e.join(","+n)+"\n"+t.prev}function F(e,t){var n=O(e),i=[];if(n){i.length=e.length;for(var r=0;r<e.length;r++)i[r]=P(e,r)?t(e[r],e):""}var o,s="function"==typeof S?S(e):[];if(b){o={};for(var a=0;a<s.length;a++)o["$"+s[a]]=s[a]}for(var c in e)P(e,c)&&(n&&String(Number(c))===c&&c<e.length||b&&o["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof S)for(var d=0;d<s.length;d++)_.call(e,s[d])&&i.push("["+t(s[d])+"]: "+t(e[s[d]],e));return i}},{"./util.inspect":21}],38:[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:49}],39:[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 d,l=[],u=!1,h=-1;function g(){u&&d&&(u=!1,d.length?l=d.concat(l):h=-1,l.length&&p())}function p(){if(!u){var e=c(g);u=!0;for(var t=l.length;t;){for(d=l,l=[];++h<t;)d&&d[h].run();h=-1,t=l.length}d=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{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 y(){}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];l.push(new f(e,t)),1!==l.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=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,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}},{}],40:[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}},{}],41:[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":40,"./parse":42,"./stringify":43}],42:[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},d=function(e,t,n,i){if(e){var o=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,s=/(\[[^[\]]*])/g,a=n.depth>0&&/(\[[^[\]]*])/.exec(o),d=a?o.slice(0,a.index):o,l=[];if(d){if(!n.plainObjects&&r.call(Object.prototype,d)&&!n.allowPrototypes)return;l.push(d)}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;l.push(a[1])}return a&&l.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 d="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,l=parseInt(d,10);n.parseArrays||""!==d?!isNaN(l)&&a!==d&&String(l)===d&&l>=0&&n.parseArrays&&l<=n.arrayLimit?(s=[])[l]=r:s[d]=r:s={0:r}}r=s}return r}(l,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 l="string"==typeof e?function(e,t){var n,d={},l=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,u=t.parameterLimit===1/0?void 0:t.parameterLimit,h=l.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,y,m=h[n],v=m.indexOf("]="),S=-1===v?m.indexOf("="):v+1;-1===S?(f=t.decoder(m,s.decoder,p,"key"),y=t.strictNullHandling?null:""):(f=t.decoder(m.slice(0,S),s.decoder,p,"key"),y=i.maybeMap(c(m.slice(S+1),t),(function(e){return t.decoder(e,s.decoder,p,"value")}))),y&&t.interpretNumericEntities&&"iso-8859-1"===p&&(y=a(y)),m.indexOf("[]=")>-1&&(y=o(y)?[y]:y),r.call(d,f)?d[f]=i.combine(d[f],y):d[f]=y}return d}(e,n):e,u=n.plainObjects?Object.create(null):{},h=Object.keys(l),g=0;g<h.length;++g){var p=h[g],f=d(p,l[p],n,"string"==typeof e);u=i.merge(u,f,n)}return!0===n.allowSparse?u:i.compact(u)}},{"./utils":44}],43:[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,d=Array.prototype.push,l=function(e,t){d.apply(e,c(t)?t:[t])},u=Date.prototype.toISOString,h=o.default,g={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:r.encode,encodeValuesOnly:!1,format:h,formatter:o.formatters[h],indices:!1,serializeDate:function(e){return u.call(e)},skipNulls:!1,strictNullHandling:!1},p=function e(t,n,o,s,a,d,u,h,p,f,y,m,v,S,E){var b,_=t;if(E.has(t))throw new RangeError("Cyclic object value");if("function"==typeof u?_=u(n,_):_ instanceof Date?_=f(_):"comma"===o&&c(_)&&(_=r.maybeMap(_,(function(e){return e instanceof Date?f(e):e}))),null===_){if(s)return d&&!v?d(n,g.encoder,S,"key",y):n;_=""}if("string"==typeof(b=_)||"number"==typeof b||"boolean"==typeof b||"symbol"==typeof b||"bigint"==typeof b||r.isBuffer(_))return d?[m(v?n:d(n,g.encoder,S,"key",y))+"="+m(d(_,g.encoder,S,"value",y))]:[m(n)+"="+m(String(_))];var w,T=[];if(void 0===_)return T;if("comma"===o&&c(_))w=[{value:_.length>0?_.join(",")||null:void 0}];else if(c(u))w=u;else{var I=Object.keys(_);w=h?I.sort(h):I}for(var R=0;R<w.length;++R){var k=w[R],C="object"==typeof k&&void 0!==k.value?k.value:_[k];if(!a||null!==C){var O=c(_)?"function"==typeof o?o(n,k):n:n+(p?"."+k:"["+k+"]");E.set(t,!0);var D=i();l(T,e(C,O,o,s,a,d,u,h,p,f,y,m,v,S,D))}}return T};t.exports=function(e,t){var n,r=e,d=function(e){if(!e)return g;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||g.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=g.filter;return("function"==typeof e.filter||c(e.filter))&&(r=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:g.addQueryPrefix,allowDots:void 0===e.allowDots?g.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:g.charsetSentinel,delimiter:void 0===e.delimiter?g.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:g.encode,encoder:"function"==typeof e.encoder?e.encoder:g.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:g.encodeValuesOnly,filter:r,format:n,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:g.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:g.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:g.strictNullHandling}}(t);"function"==typeof d.filter?r=(0,d.filter)("",r):c(d.filter)&&(n=d.filter);var u,h=[];if("object"!=typeof r||null===r)return"";u=t&&t.arrayFormat in a?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var f=a[u];n||(n=Object.keys(r)),d.sort&&n.sort(d.sort);for(var y=i(),m=0;m<n.length;++m){var v=n[m];d.skipNulls&&null===r[v]||l(h,p(r[v],v,f,d.strictNullHandling,d.skipNulls,d.encode?d.encoder:null,d.filter,d.sort,d.allowDots,d.serializeDate,d.format,d.formatter,d.encodeValuesOnly,d.charset,y))}var S=h.join(d.delimiter),E=!0===d.addQueryPrefix?"?":"";return d.charsetSentinel&&("iso-8859-1"===d.charset?E+="utf8=%26%2310003%3B&":E+="utf8=%E2%9C%93&"),S.length>0?E+S:""}},{"./formats":40,"./utils":44,"side-channel":53}],44:[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 d=a[c],l=s[d];"object"==typeof l&&null!==l&&-1===n.indexOf(l)&&(t.push({obj:s,prop:d}),n.push(l))}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="",d=0;d<a.length;++d){var l=a.charCodeAt(d);45===l||46===l||95===l||126===l||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===i.RFC1738&&(40===l||41===l)?c+=a.charAt(d):l<128?c+=s[l]:l<2048?c+=s[192|l>>6]+s[128|63&l]:l<55296||l>=57344?c+=s[224|l>>12]+s[128|l>>6&63]+s[128|63&l]:(d+=1,l=65536+((1023&l)<<10|1023&a.charCodeAt(d)),c+=s[240|l>>18]+s[128|l>>12&63]+s[128|l>>6&63]+s[128|63&l])}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":40}],45:[function(e,t,n){"use strict";function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,o){t=t||"&",n=n||"=";var s={};if("string"!=typeof e||0===e.length)return s;var a=/\+/g;e=e.split(t);var c=1e3;o&&"number"==typeof o.maxKeys&&(c=o.maxKeys);var d=e.length;c>0&&d>c&&(d=c);for(var l=0;l<d;++l){var u,h,g,p,f=e[l].replace(a,"%20"),y=f.indexOf(n);y>=0?(u=f.substr(0,y),h=f.substr(y+1)):(u=f,h=""),g=decodeURIComponent(u),p=decodeURIComponent(h),i(s,g)?r(s[g])?s[g].push(p):s[g]=[s[g],p]:s[g]=p}return s};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],46:[function(e,t,n){"use strict";var i=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?o(s(e),(function(s){var a=encodeURIComponent(i(s))+n;return r(e[s])?o(e[s],(function(e){return a+encodeURIComponent(i(e))})).join(t):a+encodeURIComponent(i(e[s]))})).join(t):a?encodeURIComponent(i(a))+n+encodeURIComponent(i(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var n=[],i=0;i<e.length;i++)n.push(t(e[i],i));return n}var s=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],47:[function(e,t,n){"use strict";n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":45,"./encode":46}],48:[function(e,t,n){var i=function(e){"use strict";var t,n=Object.prototype,i=n.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},o=r.iterator||"@@iterator",s=r.asyncIterator||"@@asyncIterator",a=r.toStringTag||"@@toStringTag";function c(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,n){return e[t]=n}}function d(e,t,n,i){var r=t&&t.prototype instanceof y?t:y,o=Object.create(r.prototype),s=new C(i||[]);return o._invoke=function(e,t,n){var i=u;return function(r,o){if(i===g)throw new Error("Generator is already running");if(i===p){if("throw"===r)throw o;return D()}for(n.method=r,n.arg=o;;){var s=n.delegate;if(s){var a=I(s,n);if(a){if(a===f)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===u)throw i=p,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=g;var c=l(e,t,n);if("normal"===c.type){if(i=n.done?p:h,c.arg===f)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(i=p,n.method="throw",n.arg=c.arg)}}}(e,n,s),o}function l(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=d;var u="suspendedStart",h="suspendedYield",g="executing",p="completed",f={};function y(){}function m(){}function v(){}var S={};c(S,o,(function(){return this}));var E=Object.getPrototypeOf,b=E&&E(E(O([])));b&&b!==n&&i.call(b,o)&&(S=b);var _=v.prototype=y.prototype=Object.create(S);function w(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function n(r,o,s,a){var c=l(e[r],e,o);if("throw"!==c.type){var d=c.arg,u=d.value;return u&&"object"==typeof u&&i.call(u,"__await")?t.resolve(u.__await).then((function(e){n("next",e,s,a)}),(function(e){n("throw",e,s,a)})):t.resolve(u).then((function(e){d.value=e,s(d)}),(function(e){return n("throw",e,s,a)}))}a(c.arg)}var r;this._invoke=function(e,i){function o(){return new t((function(t,r){n(e,i,t,r)}))}return r=r?r.then(o,o):o()}}function I(e,n){var i=e.iterator[n.method];if(i===t){if(n.delegate=null,"throw"===n.method){if(e.iterator.return&&(n.method="return",n.arg=t,I(e,n),"throw"===n.method))return f;n.method="throw",n.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var r=l(i,e.iterator,n.arg);if("throw"===r.type)return n.method="throw",n.arg=r.arg,n.delegate=null,f;var o=r.arg;return o?o.done?(n[e.resultName]=o.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,f):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,f)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function O(e){if(e){var n=e[o];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,s=function n(){for(;++r<e.length;)if(i.call(e,r))return n.value=e[r],n.done=!1,n;return n.value=t,n.done=!0,n};return s.next=s}}return{next:D}}function D(){return{value:t,done:!0}}return m.prototype=v,c(_,"constructor",v),c(v,"constructor",m),m.displayName=c(v,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,c(e,a,"GeneratorFunction")),e.prototype=Object.create(_),e},e.awrap=function(e){return{__await:e}},w(T.prototype),c(T.prototype,s,(function(){return this})),e.AsyncIterator=T,e.async=function(t,n,i,r,o){void 0===o&&(o=Promise);var s=new T(d(t,n,i,r),o);return e.isGeneratorFunction(n)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},w(_),c(_,a,"Generator"),c(_,o,(function(){return this})),c(_,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var i=t.pop();if(i in e)return n.value=i,n.done=!1,n}return n.done=!0,n}},e.values=O,C.prototype={constructor:C,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(k),!e)for(var n in this)"t"===n.charAt(0)&&i.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(i,r){return a.type="throw",a.arg=e,n.next=i,r&&(n.method="next",n.arg=t),!!r}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return r("end");if(s.tryLoc<=this.prev){var c=i.call(s,"catchLoc"),d=i.call(s,"finallyLoc");if(c&&d){if(this.prev<s.catchLoc)return r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(c){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!d)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,f):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),k(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var i=n.completion;if("throw"===i.type){var r=i.arg;k(n)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,i){return this.delegate={iterator:O(e),resultName:n,nextLoc:i},"next"===this.method&&(this.arg=t),f}},e}("object"==typeof t?t.exports:{});try{regeneratorRuntime=i}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=i:Function("r","regeneratorRuntime = r")(i)}},{}],49:[function(e,t,n){t.exports=e("./lib/retry")},{"./lib/retry":50}],50:[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":51}],51:[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}},{}],52:[function(e,t,n){
17
- /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
18
- 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:24}],53:[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),d=r("WeakMap.prototype.get",!0),l=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 d(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),l(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":25,"get-intrinsic":31,"object-inspect":37}],54:[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","ᙱ":"ᖖᒋ","ᙲ":"ᖖᒌ","ᙴ":"ᖖᒎ","ᙵ":"ᖖᒐ","ᙶ":"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ","ˡ":"ᣳ","ʳ":"ᣴ","ˢ":"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ","ᛡ":"ᚼ","⍿":"ᚽ","ᛂ":"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥","ㄱ":"ᄀ","ᆨ":"ᄀ","ᄁ":"ᄀᄀ","ㄲ":"ᄀᄀ","ᆩ":"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ","ᇃ":"ᄀᄅ","ᇻ":"ᄀᄇ","ᆪ":"ᄀᄉ","ㄳ":"ᄀᄉ","ᇄ":"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ","ㄴ":"ᄂ","ᆫ":"ᄂ","ᄓ":"ᄂᄀ","ᇅ":"ᄂᄀ","ᄔ":"ᄂᄂ","ㅥ":"ᄂᄂ","ᇿ":"ᄂᄂ","ᄕ":"ᄂᄃ","ㅦ":"ᄂᄃ","ᇆ":"ᄂᄃ","ퟋ":"ᄂᄅ","ᄖ":"ᄂᄇ","ᅛ":"ᄂᄉ","ᇇ":"ᄂᄉ","ㅧ":"ᄂᄉ","ᅜ":"ᄂᄌ","ᆬ":"ᄂᄌ","ㄵ":"ᄂᄌ","ퟌ":"ᄂᄎ","ᇉ":"ᄂᄐ","ᅝ":"ᄂᄒ","ᆭ":"ᄂᄒ","ㄶ":"ᄂᄒ","ᇈ":"ᄂᅀ","ㅨ":"ᄂᅀ","ㄷ":"ᄃ","ᆮ":"ᄃ","ᄗ":"ᄃᄀ","ᇊ":"ᄃᄀ","ᄄ":"ᄃᄃ","ㄸ":"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ","ᇋ":"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ","ㄹ":"ᄅ","ᆯ":"ᄅ","ꥤ":"ᄅᄀ","ᆰ":"ᄅᄀ","ㄺ":"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ","ᇌ":"ᄅᄀᄉ","ㅩ":"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ","ᄘ":"ᄅᄂ","ᇍ":"ᄅᄂ","ꥦ":"ᄅᄃ","ᇎ":"ᄅᄃ","ㅪ":"ᄅᄃ","ꥧ":"ᄅᄃᄃ","ᇏ":"ᄅᄃᄒ","ᄙ":"ᄅᄅ","ᇐ":"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ","ᆱ":"ᄅᄆ","ㄻ":"ᄅᄆ","ᇑ":"ᄅᄆᄀ","ᇒ":"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ","ᆲ":"ᄅᄇ","ㄼ":"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ","ᇓ":"ᄅᄇᄉ","ㅫ":"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ","ᇕ":"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ","ᇔ":"ᄅᄇᄒ","ꥬ":"ᄅᄉ","ᆳ":"ᄅᄉ","ㄽ":"ᄅᄉ","ᇖ":"ᄅᄉᄉ","ᄛ":"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ","ᇘ":"ᄅᄏ","ᆴ":"ᄅᄐ","ㄾ":"ᄅᄐ","ᆵ":"ᄅᄑ","ㄿ":"ᄅᄑ","ᄚ":"ᄅᄒ","ㅀ":"ᄅᄒ","ᄻ":"ᄅᄒ","ᆶ":"ᄅᄒ","ퟲ":"ᄅᄒ","ᇗ":"ᄅᅀ","ㅬ":"ᄅᅀ","ퟛ":"ᄅᅌ","ᇙ":"ᄅᅙ","ㅭ":"ᄅᅙ","ퟜ":"ᄅᅙᄒ","ㅁ":"ᄆ","ᆷ":"ᄆ","ꥯ":"ᄆᄀ","ᇚ":"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ","ᇛ":"ᄆᄅ","ퟠ":"ᄆᄆ","ᄜ":"ᄆᄇ","ㅮ":"ᄆᄇ","ᇜ":"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ","ᇝ":"ᄆᄉ","ㅯ":"ᄆᄉ","ᇞ":"ᄆᄉᄉ","ᄝ":"ᄆᄋ","ㅱ":"ᄆᄋ","ᇢ":"ᄆᄋ","ퟢ":"ᄆᄌ","ᇠ":"ᄆᄎ","ᇡ":"ᄆᄒ","ᇟ":"ᄆᅀ","ㅰ":"ᄆᅀ","ㅂ":"ᄇ","ᆸ":"ᄇ","ᄞ":"ᄇᄀ","ㅲ":"ᄇᄀ","ᄟ":"ᄇᄂ","ᄠ":"ᄇᄃ","ㅳ":"ᄇᄃ","ퟣ":"ᄇᄃ","ᇣ":"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ","ᄈ":"ᄇᄇ","ㅃ":"ᄇᄇ","ퟦ":"ᄇᄇ","ᄬ":"ᄇᄇᄋ","ㅹ":"ᄇᄇᄋ","ᄡ":"ᄇᄉ","ㅄ":"ᄇᄉ","ᆹ":"ᄇᄉ","ᄢ":"ᄇᄉᄀ","ㅴ":"ᄇᄉᄀ","ᄣ":"ᄇᄉᄃ","ㅵ":"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ","ᄤ":"ᄇᄉᄇ","ᄥ":"ᄇᄉᄉ","ᄦ":"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ","ᄫ":"ᄇᄋ","ㅸ":"ᄇᄋ","ᇦ":"ᄇᄋ","ᄧ":"ᄇᄌ","ㅶ":"ᄇᄌ","ퟨ":"ᄇᄌ","ᄨ":"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ","ᄩ":"ᄇᄐ","ㅷ":"ᄇᄐ","ᄪ":"ᄇᄑ","ᇤ":"ᄇᄑ","ꥴ":"ᄇᄒ","ᇥ":"ᄇᄒ","ㅅ":"ᄉ","ᆺ":"ᄉ","ᄭ":"ᄉᄀ","ㅺ":"ᄉᄀ","ᇧ":"ᄉᄀ","ᄮ":"ᄉᄂ","ㅻ":"ᄉᄂ","ᄯ":"ᄉᄃ","ㅼ":"ᄉᄃ","ᇨ":"ᄉᄃ","ᄰ":"ᄉᄅ","ᇩ":"ᄉᄅ","ᄱ":"ᄉᄆ","ퟪ":"ᄉᄆ","ᄲ":"ᄉᄇ","ㅽ":"ᄉᄇ","ᇪ":"ᄉᄇ","ᄳ":"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ","ᄊ":"ᄉᄉ","ㅆ":"ᄉᄉ","ᆻ":"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ","ᄴ":"ᄉᄉᄉ","ᄵ":"ᄉᄋ","ᄶ":"ᄉᄌ","ㅾ":"ᄉᄌ","ퟯ":"ᄉᄌ","ᄷ":"ᄉᄎ","ퟰ":"ᄉᄎ","ᄸ":"ᄉᄏ","ᄹ":"ᄉᄐ","ퟱ":"ᄉᄐ","ᄺ":"ᄉᄑ","ퟮ":"ᄉᅀ","ㅇ":"ᄋ","ᆼ":"ᄋ","ᅁ":"ᄋᄀ","ᇬ":"ᄋᄀ","ᇭ":"ᄋᄀᄀ","ᅂ":"ᄋᄃ","ꥶ":"ᄋᄅ","ᅃ":"ᄋᄆ","ᅄ":"ᄋᄇ","ᅅ":"ᄋᄉ","ᇱ":"ᄋᄉ","ㆂ":"ᄋᄉ","ᅇ":"ᄋᄋ","ㆀ":"ᄋᄋ","ᇮ":"ᄋᄋ","ᅈ":"ᄋᄌ","ᅉ":"ᄋᄎ","ᇯ":"ᄋᄏ","ᅊ":"ᄋᄐ","ᅋ":"ᄋᄑ","ꥷ":"ᄋᄒ","ᅆ":"ᄋᅀ","ᇲ":"ᄋᅀ","ㆃ":"ᄋᅀ","ㅈ":"ᄌ","ᆽ":"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ","ᅍ":"ᄌᄋ","ᄍ":"ᄌᄌ","ㅉ":"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ","ㅊ":"ᄎ","ᆾ":"ᄎ","ᅒ":"ᄎᄏ","ᅓ":"ᄎᄒ","ㅋ":"ᄏ","ᆿ":"ᄏ","ㅌ":"ᄐ","ᇀ":"ᄐ","ꥹ":"ᄐᄐ","ㅍ":"ᄑ","ᇁ":"ᄑ","ᅖ":"ᄑᄇ","ᇳ":"ᄑᄇ","ퟺ":"ᄑᄉ","ᅗ":"ᄑᄋ","ㆄ":"ᄑᄋ","ᇴ":"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ","ㅎ":"ᄒ","ᇂ":"ᄒ","ᇵ":"ᄒᄂ","ᇶ":"ᄒᄅ","ᇷ":"ᄒᄆ","ᇸ":"ᄒᄇ","ꥻ":"ᄒᄉ","ᅘ":"ᄒᄒ","ㆅ":"ᄒᄒ","ᄽ":"ᄼᄼ","ᄿ":"ᄾᄾ","ㅿ":"ᅀ","ᇫ":"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ","ㆁ":"ᅌ","ᇰ":"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ","ᅏ":"ᅎᅎ","ᅑ":"ᅐᅐ","ㆆ":"ᅙ","ᇹ":"ᅙ","ꥼ":"ᅙᅙ","ㅤ":"ᅠ","ㅏ":"ᅡ","ᆣ":"ᅡー","ᅶ":"ᅡᅩ","ᅷ":"ᅡᅮ","ᅢ":"ᅡ丨","ㅐ":"ᅡ丨","ㅑ":"ᅣ","ᅸ":"ᅣᅩ","ᅹ":"ᅣᅭ","ᆤ":"ᅣᅮ","ᅤ":"ᅣ丨","ㅒ":"ᅣ丨","ㅓ":"ᅥ","ᅼ":"ᅥー","ᅺ":"ᅥᅩ","ᅻ":"ᅥᅮ","ᅦ":"ᅥ丨","ㅔ":"ᅥ丨","ㅕ":"ᅧ","ᆥ":"ᅧᅣ","ᅽ":"ᅧᅩ","ᅾ":"ᅧᅮ","ᅨ":"ᅧ丨","ㅖ":"ᅧ丨","ㅗ":"ᅩ","ᅪ":"ᅩᅡ","ㅘ":"ᅩᅡ","ᅫ":"ᅩᅡ丨","ㅙ":"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨","ᅿ":"ᅩᅥ","ᆀ":"ᅩᅥ丨","ힰ":"ᅩᅧ","ᆁ":"ᅩᅧ丨","ᆂ":"ᅩᅩ","ힱ":"ᅩᅩ丨","ᆃ":"ᅩᅮ","ᅬ":"ᅩ丨","ㅚ":"ᅩ丨","ㅛ":"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨","ᆄ":"ᅭᅣ","ㆇ":"ᅭᅣ","ᆆ":"ᅭᅣ","ᆅ":"ᅭᅣ丨","ㆈ":"ᅭᅣ丨","ힴ":"ᅭᅥ","ᆇ":"ᅭᅩ","ᆈ":"ᅭ丨","ㆉ":"ᅭ丨","ㅜ":"ᅮ","ᆉ":"ᅮᅡ","ᆊ":"ᅮᅡ丨","ᅯ":"ᅮᅥ","ㅝ":"ᅮᅥ","ᆋ":"ᅮᅥー","ᅰ":"ᅮᅥ丨","ㅞ":"ᅮᅥ丨","ힵ":"ᅮᅧ","ᆌ":"ᅮᅧ丨","ᆍ":"ᅮᅮ","ᅱ":"ᅮ丨","ㅟ":"ᅮ丨","ힶ":"ᅮ丨丨","ㅠ":"ᅲ","ᆎ":"ᅲᅡ","ힷ":"ᅲᅡ丨","ᆏ":"ᅲᅥ","ᆐ":"ᅲᅥ丨","ᆑ":"ᅲᅧ","ㆊ":"ᅲᅧ","ᆒ":"ᅲᅧ丨","ㆋ":"ᅲᅧ丨","ힸ":"ᅲᅩ","ᆓ":"ᅲᅮ","ᆔ":"ᅲ丨","ㆌ":"ᅲ丨","ㆍ":"ᆞ","ퟅ":"ᆞᅡ","ᆟ":"ᆞᅥ","ퟆ":"ᆞᅥ丨","ᆠ":"ᆞᅮ","ᆢ":"ᆞᆞ","ᆡ":"ᆞ丨","ㆎ":"ᆞ丨","ヘ":"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄","不":"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨","ᅵ":"丨","ㅣ":"丨","⼁":"丨","ᆜ":"丨ー","ᆘ":"丨ᅡ","ᆙ":"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨","ᆚ":"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ","ᆛ":"丨ᅮ","ퟃ":"丨ᅲ","ᆝ":"丨ᆞ","ퟄ":"丨丨","串":"串","丸":"丸","丹":"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀","亂":"亂","㇚":"亅","⼅":"亅","了":"了","ニ":"二","⼆":"二","𠄢":"𠄢","⼇":"亠","亮":"亮","⼈":"人","イ":"亻","⺅":"亻","什":"什","仌":"仌","令":"令","你":"你","倂":"併","倂":"併","侀":"侀","來":"來","例":"例","侮":"侮","侮":"侮","侻":"侻","便":"便","值":"値","倫":"倫","偺":"偺","備":"備","像":"像","僚":"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿","兀":"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全","兩":"兩","ハ":"八","⼋":"八","六":"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况","冷":"冷","凉":"凉","凌":"凌","凜":"凜","凞":"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃","切":"切","切":"切","列":"列","利":"利","㓟":"㓟","刺":"刺","刻":"刻","剆":"剆","割":"割","剷":"剷","劉":"劉","𠠄":"𠠄","カ":"力","力":"力","⼒":"力","劣":"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉","勒":"勒","勞":"勞","勤":"勤","勤":"勤","勵":"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕","北":"北","北":"北","⼕":"匚","⼖":"匸","匿":"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博","ト":"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即","卵":"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶","參":"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣","ロ":"口","⼝":"口","囗":"口","⼞":"口","句":"句","叫":"叫","叱":"叱","吆":"吆","吏":"吏","吝":"吝","吸":"吸","呂":"呂","呈":"呈","周":"周","咞":"咞","咢":"咢","咽":"咽","䎛":"㖈","哶":"哶","唐":"唐","啓":"啓","啟":"啓","啕":"啕","啣":"啣","善":"善","善":"善","喇":"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳","嗀":"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器","囹":"囹","圖":"圖","圗":"圗","⼟":"土","士":"土","⼠":"土","型":"型","城":"城","㦳":"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀","塚":"塚","塚":"塚","塞":"塞","填":"塡","壿":"墫","墬":"墬","墳":"墳","壘":"壘","壟":"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊","タ":"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄","奈":"奈","契":"契","奔":"奔","奢":"奢","女":"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦","嬀":"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀","宅":"宅","𡧈":"𡧈","寃":"寃","寘":"寘","寧":"寧","寧":"寧","寧":"寧","寮":"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸","尿":"尿","屠":"屠","屢":"屢","層":"層","履":"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦","崙":"崙","嵃":"嵃","嵐":"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲","嶺":"嶺","⼮":"巛","巢":"巢","エ":"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾","帲":"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干","年":"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广","度":"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶","廊":"廊","廊":"廊","廉":"廉","廒":"廒","廓":"廓","廙":"廙","廬":"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱","弄":"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳","律":"律","㣣":"㣣","徚":"徚","復":"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志","念":"念","忹":"忹","怒":"怒","怜":"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘","惡":"惡","𢛔":"𢛔","愈":"愈","慨":"慨","慄":"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎","憐":"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲","懶":"懶","懶":"懶","戀":"戀","⼽":"戈","成":"成","戛":"戛","戮":"戮","戴":"戴","⼾":"戶","戸":"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱","拉":"拉","拏":"拏","拓":"拓","拔":"拔","拼":"拼","拾":"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨","捻":"捻","掃":"掃","掠":"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮","搉":"㩁","撚":"撚","撝":"撝","擄":"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬","數":"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗","料":"料","⽄":"斤","⽅":"方","旅":"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日","易":"易","曶":"㫚","㫤":"㫤","晉":"晉","晩":"晚","晴":"晴","晴":"晴","暑":"暑","暑":"暑","暈":"暈","㬈":"㬈","暜":"暜","暴":"暴","曆":"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰","更":"更","書":"書","⽉":"月","𣍟":"𣍟","肦":"朌","胐":"朏","胊":"朐","脁":"朓","胶":"㬵","朗":"朗","朗":"朗","朗":"朗","脧":"朘","望":"望","望":"望","幐":"㬺","䐠":"㬻","𣎓":"𣎓","膧":"朣","𣎜":"𣎜","⽊":"木","李":"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃","柿":"杮","杻":"杻","枅":"枅","林":"林","㭉":"㭉","𣏕":"𣏕","柳":"柳","柺":"柺","栗":"栗","栟":"栟","桒":"桒","𣑭":"𣑭","梁":"梁","梅":"梅","梅":"梅","梎":"梎","梨":"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝","槩":"㮣","樧":"榝","榣":"榣","槪":"槪","樂":"樂","樂":"樂","樂":"樂","樓":"樓","𣚣":"𣚣","檨":"檨","櫓":"櫓","櫛":"櫛","欄":"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲","歷":"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟","殮":"殮","⽎":"殳","殺":"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧","沈":"沈","沿":"沿","泌":"泌","泍":"泍","泥":"泥","𣲼":"𣲼","洛":"洛","洞":"洞","洴":"洴","派":"派","流":"流","流":"流","流":"流","洖":"洖","浩":"浩","浪":"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞","淋":"淋","淚":"淚","淪":"淪","淹":"淹","渚":"渚","港":"港","湮":"湮","潙":"溈","滋":"滋","滋":"滋","溜":"溜","溺":"溺","滇":"滇","滑":"滑","滛":"滛","㴳":"㴳","漏":"漏","漢":"漢","漢":"漢","漣":"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆","濫":"濫","濾":"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災","炙":"炙","炭":"炭","烈":"烈","烙":"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅","煉":"煉","𤋮":"𤋮","熜":"熜","燎":"燎","燐":"燐","𤎫":"𤎫","爐":"爐","爛":"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛","牢":"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯","狀":"狀","𤜵":"𤜵","狼":"狼","猪":"猪","猪":"猪","𤠔":"𤠔","獵":"獵","獺":"獺","⽞":"玄","率":"率","率":"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥","玲":"玲","㺸":"㺸","㺸":"㺸","珞":"珞","琉":"琉","理":"理","琢":"琢","瑇":"瑇","瑜":"瑜","瑩":"瑩","瑱":"瑱","瑱":"瑱","璅":"璅","璉":"璉","璘":"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶","留":"留","略":"略","異":"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒","痢":"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝","療":"療","癩":"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼","益":"益","益":"益","盛":"盛","盧":"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳","省":"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹","晣":"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝","硏":"研","硎":"硎","硫":"硫","碌":"碌","碌":"碌","碑":"碑","磊":"磊","磌":"磌","磌":"磌","磻":"磻","䃣":"䃣","礪":"礪","⽰":"示","⺭":"礻","礼":"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝","神":"神","祥":"祥","視":"視","視":"視","祿":"祿","𥚚":"𥚚","禍":"禍","禎":"禎","福":"福","福":"福","𥛅":"𥛅","禮":"禮","⽱":"禸","⽲":"禾","秊":"秊","䄯":"䄯","秫":"秫","稜":"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱","立":"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹","笠":"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐","簾":"簾","籠":"籠","⽶":"米","类":"类","粒":"粒","精":"精","糒":"糒","糖":"糖","糨":"糨","䊠":"䊠","糣":"糣","糧":"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀","紐":"紐","索":"索","累":"累","絶":"絕","絣":"絣","絛":"絛","綠":"綠","綾":"綾","緇":"緇","練":"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉","縷":"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙","罹":"罹","罺":"罺","羅":"羅","𦌾":"𦌾","⽺":"羊","羕":"羕","羚":"羚","羽":"羽","⽻":"羽","翺":"翺","老":"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳","聆":"聆","聠":"聠","𦖨":"𦖨","聯":"聯","聰":"聰","聾":"聾","⾀":"聿","⺺":"肀","⾁":"肉","肋":"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙","腁":"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵","朦":"䑃","臘":"臘","⾂":"臣","臨":"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮","良":"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽","若":"若","若":"若","苦":"苦","𦬼":"𦬼","茶":"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓","菉":"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華","菱":"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭","落":"落","葉":"葉","蔿":"蒍","𦳕":"𦳕","𦵫":"𦵫","蓮":"蓮","蓱":"蓱","蓳":"蓳","蓼":"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬","藍":"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡","藺":"藺","蘆":"蘆","䕫":"䕫","蘒":"蘒","蘭":"蘭","𧃒":"𧃒","虁":"蘷","蘿":"蘿","⾌":"虍","⻁":"虎","虐":"虐","虜":"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊","螺":"螺","蠁":"蠁","䗹":"䗹","蠟":"蠟","⾎":"血","行":"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤","裂":"裂","𧙧":"𧙧","裏":"裏","裗":"裗","裞":"裞","裡":"裡","裸":"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁","襤":"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆","見":"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦","詽":"訮","訞":"䚶","䚾":"䚾","䛇":"䛇","誠":"誠","說":"說","說":"說","調":"調","請":"請","諒":"諒","論":"論","諭":"諭","諭":"諭","諸":"諸","諸":"諸","諾":"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹","識":"識","讀":"讀","讏":"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆","豈":"豈","豕":"豕","⾗":"豕","豣":"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁","賂":"賂","賈":"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起","趆":"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼","跺":"跥","路":"路","跰":"跰","躛":"躗","⾝":"身","車":"車","⾞":"車","軔":"軔","輧":"軿","輦":"輦","輪":"輪","輸":"輸","輸":"輸","輻":"輻","轢":"轢","⻋":"车","⾟":"辛","辞":"辞","辰":"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡","連":"連","逸":"逸","逸":"逸","遲":"遲","遼":"遼","𨗒":"𨗒","𨗭":"𨗭","邏":"邏","⾢":"邑","邔":"邔","郎":"郎","郞":"郎","郞":"郎","郱":"郱","都":"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉","酪":"酪","醙":"醙","醴":"醴","⾤":"釆","里":"里","⾥":"里","量":"量","金":"金","⾦":"金","鈴":"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼","錄":"錄","鍊":"鍊","鎮":"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕","閭":"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝","阮":"阮","陋":"陋","降":"降","陵":"陵","陸":"陸","陼":"陼","隆":"隆","隣":"隣","䧦":"䧦","⾪":"隶","隷":"隷","隸":"隷","隸":"隷","⾫":"隹","雃":"雃","離":"離","難":"難","難":"難","⾬":"雨","零":"零","雷":"雷","霣":"霣","𩅅":"𩅅","露":"露","靈":"靈","⾭":"靑","⻘":"青","靖":"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋","領":"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻","類":"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢","飯":"飯","飼":"飼","䬳":"䬳","館":"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂","駱":"駱","駾":"駾","驪":"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚","魯":"魯","鱀":"鱀","鱗":"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎","鶴":"鶴","𪄅":"𪄅","䳸":"䳸","鷺":"鷺","𪈎":"𪈎","鸞":"鸞","鹃":"鹂","⿄":"鹵","鹿":"鹿","⿅":"鹿","𪊑":"𪊑","麗":"麗","麟":"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍","黎":"黎","䵖":"䵖","⿊":"黑","黒":"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿","龍":"龍","⿓":"龍","龎":"龎","⻰":"龙","龜":"龜","龜":"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"}},{}],55:[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":54}],56:[function(e,t,n){"use strict";var i=e("punycode"),r=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=S,n.resolve=function(e,t){return S(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?S(e,!1,!0).resolveObject(t):t},n.format=function(e){r.isString(e)&&(e=S(e));return e instanceof o?e.format():o.prototype.format.call(e)},n.Url=o;var s=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,d=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),l=["'"].concat(d),u=["%","/","?",";","#"].concat(l),h=["/","?","#"],g=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,f={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function S(e,t,n){if(e&&r.isObject(e)&&e instanceof o)return e;var i=new o;return i.parse(e,t,n),i}o.prototype.parse=function(e,t,n){if(!r.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),a=-1!==o&&o<e.indexOf("#")?"?":"#",d=e.split(a);d[0]=d[0].replace(/\\/g,"/");var S=e=d.join(a);if(S=S.trim(),!n&&1===e.split("#").length){var E=c.exec(S);if(E)return this.path=S,this.href=S,this.pathname=E[1],E[2]?(this.search=E[2],this.query=t?v.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var b=s.exec(S);if(b){var _=(b=b[0]).toLowerCase();this.protocol=_,S=S.substr(b.length)}if(n||b||S.match(/^\/\/[^@\/]+@[^@\/]+/)){var w="//"===S.substr(0,2);!w||b&&y[b]||(S=S.substr(2),this.slashes=!0)}if(!y[b]&&(w||b&&!m[b])){for(var T,I,R=-1,k=0;k<h.length;k++){-1!==(C=S.indexOf(h[k]))&&(-1===R||C<R)&&(R=C)}-1!==(I=-1===R?S.lastIndexOf("@"):S.lastIndexOf("@",R))&&(T=S.slice(0,I),S=S.slice(I+1),this.auth=decodeURIComponent(T)),R=-1;for(k=0;k<u.length;k++){var C;-1!==(C=S.indexOf(u[k]))&&(-1===R||C<R)&&(R=C)}-1===R&&(R=S.length),this.host=S.slice(0,R),S=S.slice(R),this.parseHost(),this.hostname=this.hostname||"";var O="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!O)for(var D=this.hostname.split(/\./),A=(k=0,D.length);k<A;k++){var P=D[k];if(P&&!P.match(g)){for(var M="",x=0,U=P.length;x<U;x++)P.charCodeAt(x)>127?M+="x":M+=P[x];if(!M.match(g)){var N=D.slice(0,k),B=D.slice(k+1),K=P.match(p);K&&(N.push(K[1]),B.unshift(K[2])),B.length&&(S="/"+B.join(".")+S),this.hostname=N.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=i.toASCII(this.hostname));var L=this.port?":"+this.port:"",j=this.hostname||"";this.host=j+L,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==S[0]&&(S="/"+S))}if(!f[_])for(k=0,A=l.length;k<A;k++){var F=l[k];if(-1!==S.indexOf(F)){var q=encodeURIComponent(F);q===F&&(q=escape(F)),S=S.split(F).join(q)}}var $=S.indexOf("#");-1!==$&&(this.hash=S.substr($),S=S.slice(0,$));var G=S.indexOf("?");if(-1!==G?(this.search=S.substr(G),this.query=S.substr(G+1),t&&(this.query=v.parse(this.query)),S=S.slice(0,G)):t&&(this.search="",this.query={}),S&&(this.pathname=S),m[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){L=this.pathname||"";var V=this.search||"";this.path=L+V}return this.href=this.format(),this},o.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",i=this.hash||"",o=!1,s="";this.host?o=e+this.host:this.hostname&&(o=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(o+=":"+this.port)),this.query&&r.isObject(this.query)&&Object.keys(this.query).length&&(s=v.stringify(this.query));var a=this.search||s&&"?"+s||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||m[t])&&!1!==o?(o="//"+(o||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):o||(o=""),i&&"#"!==i.charAt(0)&&(i="#"+i),a&&"?"!==a.charAt(0)&&(a="?"+a),t+o+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.replace("#","%23"))+i},o.prototype.resolve=function(e){return this.resolveObject(S(e,!1,!0)).format()},o.prototype.resolveObject=function(e){if(r.isString(e)){var t=new o;t.parse(e,!1,!0),e=t}for(var n=new o,i=Object.keys(this),s=0;s<i.length;s++){var a=i[s];n[a]=this[a]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),d=0;d<c.length;d++){var l=c[d];"protocol"!==l&&(n[l]=e[l])}return m[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!m[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var g=u[h];n[g]=e[g]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),n.pathname=p.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var f=n.pathname||"",v=n.search||"";n.path=f+v}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var S=n.pathname&&"/"===n.pathname.charAt(0),E=e.host||e.pathname&&"/"===e.pathname.charAt(0),b=E||S||n.host&&e.pathname,_=b,w=n.pathname&&n.pathname.split("/")||[],T=(p=e.pathname&&e.pathname.split("/")||[],n.protocol&&!m[n.protocol]);if(T&&(n.hostname="",n.port=null,n.host&&(""===w[0]?w[0]=n.host:w.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),b=b&&(""===p[0]||""===w[0])),E)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,w=p;else if(p.length)w||(w=[]),w.pop(),w=w.concat(p),n.search=e.search,n.query=e.query;else if(!r.isNullOrUndefined(e.search)){if(T)n.hostname=n.host=w.shift(),(O=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=O.shift(),n.host=n.hostname=O.shift());return n.search=e.search,n.query=e.query,r.isNull(n.pathname)&&r.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!w.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var I=w.slice(-1)[0],R=(n.host||e.host||w.length>1)&&("."===I||".."===I)||""===I,k=0,C=w.length;C>=0;C--)"."===(I=w[C])?w.splice(C,1):".."===I?(w.splice(C,1),k++):k&&(w.splice(C,1),k--);if(!b&&!_)for(;k--;k)w.unshift("..");!b||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),R&&"/"!==w.join("/").substr(-1)&&w.push("");var O,D=""===w[0]||w[0]&&"/"===w[0].charAt(0);T&&(n.hostname=n.host=D?"":w.length?w.shift():"",(O=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=O.shift(),n.host=n.hostname=O.shift()));return(b=b||n.host&&w.length)&&!D&&w.unshift(""),w.length?n.pathname=w.join("/"):(n.pathname=null,n.path=null),r.isNull(n.pathname)&&r.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":57,punycode:22,querystring:47}],57:[function(e,t,n){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],58:[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={}))},{}],59:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),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.Thread="io.element.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"}(n.MsgType||(n.MsgType={})),n.RoomCreateTypeField="type",function(e){e.Space="m.space"}(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")},{"../NamespacedValue":62}],60:[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={}))},{}],61:[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={}))},{}],62:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.UnstableValue=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.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}}},{}],63:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.ReEmitter=void 0;n.ReEmitter=class{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)}}}},{}],64:[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"),o=e("url");var s;!function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"}(s=n.AutoDiscoveryAction||(n.AutoDiscoveryAction={}));class a{static fromDiscoveryConfig(e){return i(this,void 0,void 0,(function*(){const t={"m.homeserver":{state:a.FAIL_ERROR,error:a.ERROR_INVALID,base_url:null},"m.identity_server":{state:a.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=a.FAIL_PROMPT,t["m.homeserver"].error=a.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=a.FAIL_PROMPT,t["m.homeserver"].error=a.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=a.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=a.ERROR_INVALID_HOMESERVER,t["m.homeserver"].base_url=n,Promise.resolve(t);t["m.homeserver"]={state:a.SUCCESS,error:null,base_url:n};let o="";if(e["m.identity_server"]){const n={"m.homeserver":t["m.homeserver"],"m.identity_server":{state:a.FAIL_PROMPT,error:a.ERROR_INVALID_IS,base_url:null}};if(o=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!o)return r.logger.error("Invalid base_url for m.identity_server"),n["m.identity_server"].error=a.ERROR_INVALID_IS_BASE_URL,Promise.resolve(n);const i=yield this.fetchWellKnownObject(`${o}/_matrix/identity/api/v1`);if(!i||!i.raw||i.action!==s.SUCCESS)return r.logger.error("Invalid /api/v1 response"),n["m.identity_server"].error=a.ERROR_INVALID_IDENTITY_SERVER,n["m.identity_server"].base_url=o,Promise.resolve(n)}return o&&o.toString().length>0&&(t["m.identity_server"]={state:a.SUCCESS,error:null,base_url:o}),Object.keys(e).map((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:a.FAIL_ERROR,error:a.ERROR_INVALID,base_url:null},"m.identity_server":{state:a.PROMPT,error:null,base_url:null}},n=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return n&&n.action===s.SUCCESS?a.fromDiscoveryConfig(n.raw):(r.logger.error("No response or error when parsing .well-known"),n.reason&&r.logger.error(n.reason),n.action===s.IGNORE?t["m.homeserver"]={state:a.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=a.FAIL_PROMPT,t["m.homeserver"].error=a.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=o.URL?new o.URL(e):new URL(e)}catch(n){t=new 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 r=`${t.protocol}//${t.hostname}${n}${i}`;return r.endsWith("/")&&(r=r.substring(0,r.length-1)),r}catch(e){return r.logger.error(e),!1}}static fetchWellKnownObject(t){return i(this,void 0,void 0,(function*(){return new Promise((function(n,i){const r=e("./matrix").getRequest();if(!r)throw new Error("No request library available");r({method:"GET",uri:t,timeout:5e3},((e,t,i)=>{if(e||t&&(t.statusCode<200||t.statusCode>=300)){let i=s.FAIL_PROMPT,r=(e?e.message:null)||"General failure";return t&&404===t.statusCode&&(i=s.IGNORE,r=a.ERROR_MISSING_WELLKNOWN),void n({raw:{},action:i,reason:r,error:e})}try{n({raw:JSON.parse(i),action:s.SUCCESS})}catch(e){let t=a.ERROR_INVALID;"SyntaxError"===e.name&&(t=a.ERROR_INVALID_JSON),n({raw:{},action:s.FAIL_PROMPT,reason:t,error:e})}}))}))}))}}n.AutoDiscovery=a,a.ERROR_INVALID="Invalid homeserver discovery response",a.ERROR_GENERIC_FAILURE="Failed to get autodiscovery configuration from server",a.ERROR_INVALID_HS_BASE_URL="Invalid base_url for m.homeserver",a.ERROR_INVALID_HOMESERVER="Homeserver URL does not appear to be a valid Matrix homeserver",a.ERROR_INVALID_IS_BASE_URL="Invalid base_url for m.identity_server",a.ERROR_INVALID_IDENTITY_SERVER="Identity server URL does not appear to be a valid identity server",a.ERROR_INVALID_IS="Invalid identity server discovery response",a.ERROR_MISSING_WELLKNOWN="No .well-known JSON file found",a.ERROR_INVALID_JSON="Invalid JSON",a.ALL_ERRORS=[a.ERROR_INVALID,a.ERROR_GENERIC_FAILURE,a.ERROR_INVALID_HS_BASE_URL,a.ERROR_INVALID_HOMESERVER,a.ERROR_INVALID_IS_BASE_URL,a.ERROR_INVALID_IDENTITY_SERVER,a.ERROR_INVALID_IS,a.ERROR_MISSING_WELLKNOWN,a.ERROR_INVALID_JSON],a.FAIL_ERROR=s.FAIL_ERROR,a.FAIL_PROMPT=s.FAIL_PROMPT,a.PROMPT=s.PROMPT,a.SUCCESS=s.SUCCESS},{"./logger":108,"./matrix":109,url:56}],65:[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=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!==r(e)&&"function"!=typeof e)return{default:e};var n=l(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"));Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(o,e)||e in n&&n[e]===s[e]||Object.defineProperty(n,e,{enumerable:!0,get:function(){return s[e]}}))}));var a,c=i(e("browser-request")),d=i(e("qs"));function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(l=function(e){return e?n:t})(e)}s.request((function(e,t){return e.qs=d.default.stringify(e.qs||{},e.qsStringifyOptions),(0,c.default)(e,t)}));try{a=t.indexedDB}catch(e){}a&&s.setCryptoStoreFactory((function(){return new s.IndexedDBCryptoStore(a,"matrix-js-sdk:crypto")}));var u=s;n.default=u,t.matrixcs=s}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./matrix":109,"@babel/runtime/helpers/interopRequireDefault":9,"@babel/runtime/helpers/typeof":14,"browser-request":20,qs:41}],66:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.RoomVersionStability=n.PendingEventOrdering=n.CRYPTO_ENABLED=void 0;const a=e("events"),c=e("./sync"),d=e("./models/event"),l=e("./store/stub"),u=e("./webrtc/call"),h=e("./filter"),g=e("./webrtc/callEventHandler"),p=o(e("./utils")),f=e("./utils"),y=e("./models/event-timeline"),m=e("./pushprocessor"),v=e("./autodiscovery"),S=o(e("./crypto/olmlib")),E=e("./crypto/olmlib"),b=e("./ReEmitter"),_=e("./crypto/RoomList"),w=e("./logger"),T=e("./service-types"),I=e("./http-api"),R=e("./crypto"),k=e("./crypto/recoverykey"),C=e("./crypto/key_passphrase"),O=e("./models/user"),D=e("./content-repo"),A=e("./models/search-result"),P=e("./crypto/dehydration"),M=e("./matrix"),x=e("./crypto/api"),U=e("./sync.api"),N=o(e("./content-helpers")),B=e("./@types/event"),K=e("./@types/partials"),L=e("./event-mapper"),j=e("./randomstring"),F=e("./crypto/backup"),q=e("./models/MSC3089TreeSpace"),$=e("./@types/search"),G=e("./@types/PushRules"),V=e("./webrtc/mediaHandler");n.CRYPTO_ENABLED=(0,R.isCryptoAvailable)();const H=6e5;var W;!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"}(W||(W={}));class Y extends a.EventEmitter{constructor(e){super(),this.reEmitter=new b.ReEmitter(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 m.PushProcessor(this),this.turnServers=[],this.turnServersExpiry=0,this.txnCtr=0,this.mediaHandler=new V.MediaHandler,this.startCallEventHandler=()=>{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.off("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 l.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?w.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?w.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):w.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction((e=>s(this,void 0,void 0,(function*(){const t=this.getRoom(e.getRoomId());e.status!==d.EventStatus.SENDING&&this.updatePendingEventStatus(t,e,d.EventStatus.SENDING);const n=yield this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,d.EventStatus.SENT,n.event_id),n}))));(0,u.createNewMatrixCall)(this,void 0,void 0)&&(this.callEventHandler=new g.CallEventHandler(this),this.canSupportVoip=!0,this.on("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("Event.decrypted",(e=>{const t=e.getPushActions(),n=this.pushProcessor.actionsForEvent(e);e.setPushActions(n);const i=this.getRoom(e.getRoomId());if(!i)return;const r=i.getUnreadNotificationCount(M.NotificationCountType.Highlight),o=!(!t||!t.tweaks)&&!!t.tweaks.highlight,s=!(!n||!n.tweaks)&&!!n.tweaks.highlight;if((o!==s||r>0)&&!i.hasUserReadEvent(this.getUserId(),e.getId())){let e=r;s&&!o&&e++,!s&&o&&e--,i.setUnreadNotificationCount(M.NotificationCountType.Highlight,e);i.getUnreadNotificationCount(M.NotificationCountType.Total)<e&&i.setUnreadNotificationCount(M.NotificationCountType.Total,e)}})),this.on("Room.receipt",((e,t)=>{if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter((e=>Object.keys(n[e]["m.read"]).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("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 O.User(t)),this.crypto&&(this.crypto.uploadDeviceKeys(),this.crypto.start()),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),H),this.checkTurnServers()),this.syncApi&&(w.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop()),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;w.logger.log("stopping MatrixClient"),this.clientRunning=!1,null===(e=this.syncApi)||void 0===e||e.stop(),this.syncApi=null,null===(n=this.crypto)||void 0===n||n.stop(),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 w.logger.info("no dehydrated device found");const n=new t.Olm.Account;try{const t=e.device_data;if(t.algorithm!==P.DEHYDRATION_ALGORITHM)return void w.logger.warn("Wrong algorithm for dehydrated device");w.logger.log("unpickling dehydrated device");const i=yield this.cryptoCallbacks.getDehydrationKey(t,(e=>{n.unpickle(new Uint8Array(e),t.account)}));n.unpickle(i,t.account),w.logger.log("unpickled device");if(!0===(yield this.http.authedRequest(void 0,"POST","/dehydrated_device/claim",void 0,{device_id:e.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=e.device_id,w.logger.info("using dehydrated device");const t=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:n.pickle(t),sessions:[],pickleKey:t},n.free(),this.deviceId}return n.free(),void w.logger.info("not using dehydrated device")}catch(e){n.free(),w.logger.warn("could not unpickle",e)}}))}getDehydratedDevice(){return s(this,void 0,void 0,(function*(){try{return yield this.http.authedRequest(void 0,"GET","/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void w.logger.info("could not get dehydrated device",e.toString())}}))}setDehydrationKey(e,t,n){return s(this,void 0,void 0,(function*(){if(this.crypto)return yield this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n);w.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),yield this.crypto.dehydrationManager.dehydrateDevice();w.logger.warn("not dehydrating device if crypto is not enabled")}))}exportDevice(){return s(this,void 0,void 0,(function*(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:yield this.crypto.olmDevice.export()};w.logger.warn("not exporting device if crypto is not enabled")}))}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];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===U.SyncState.Prepared||e===U.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?(w.logger.log("Returning cached capabilities"),Promise.resolve(this.cachedCapabilities.capabilities)):this.http.authedRequest(void 0,"GET","/capabilities").catch((e=>(w.logger.error(e),null))).then((e=>{e||(e={});const n=e.capabilities||{},i=Object.keys(n).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:n,expiration:t+i},w.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 w.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");w.logger.log("Crypto: Starting up crypto store..."),yield this.cryptoStore.startup(),w.logger.log("Crypto: initialising roomlist..."),yield this.roomList.init();const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(null===this.deviceId)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const t=new R.Crypto(this,this.sessionStore,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,["crypto.keyBackupFailed","crypto.keyBackupSessionsRemaining","crypto.roomKeyRequest","crypto.roomKeyRequestCancellation","crypto.warning","crypto.devicesUpdated","crypto.willUpdateDevices","deviceVerificationChanged","userTrustStatusChanged","crossSigning.keysChanged"]),w.logger.log("Crypto: initialising crypto object..."),yield t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=R.Crypto.getOlmVersion(),t.registerEventHandlers(this),this.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)}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,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e,t)}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(B.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,"GET","/room_keys/version",void 0,void 0,{prefix:I.PREFIX_UNSTABLE})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}try{F.BackupManager.checkBackupVersion(e)}catch(e){throw e}return 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,E.encodeBase64)(o)),w.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",!1))}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,"POST","/room_keys/version",void 0,t,{prefix:I.PREFIX_UNSTABLE});return yield this.checkKeyBackup(),this.getKeyBackupEnabled()||w.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,"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,"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,C.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,C.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,E.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,d=[];const l=this.makeKeyBackupPath(t,n,i.version),u=yield F.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:Y.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{w.logger.warn("Error caching session backup key:",e)})).then(o),a&&a({stage:"fetch"});const i=yield this.http.authedRequest(void 0,"GET",l.path,l.queryData,void 0,{prefix:I.PREFIX_UNSTABLE});if(i.rooms)for(const[e,t]of Object.entries(i.rooms)){if(!t.sessions)continue;c+=Object.keys(t.sessions).length;const n=yield u.decryptSessions(t.sessions);for(const t of n)t.room_id=e,d.push(t)}else if(i.sessions){c=Object.keys(i.sessions).length,d=yield u.decryptSessions(i.sessions);for(const e of d)e.room_id=t}else{c=1;try{const[e]=yield u.decryptSessions({[n]:i});e.room_id=t,e.session_id=n,d.push(e)}catch(e){w.logger.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return yield this.importRoomKeys(d,{progressCallback:a,untrusted:h,source:"backup"}),yield this.checkKeyBackup(),{total:c,imported:d.length}}))}deleteKeysFromBackup(e,t,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,"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 w.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):w.logger.warn("Algorithm does not support sharing previous keys",n.algorithm)}))}getGroup(e){return this.store.getGroup(e)}getGroups(){return this.store.getGroups()}getMediaConfig(e){return this.http.authedRequest(e,"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(B.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(B.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,"PUT",i,void 0,t)));return n&&r.then((e=>n(null,e)),n),r}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){return s(this,void 0,void 0,(function*(){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const t=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return yield this.http.authedRequest(void 0,"GET",t,void 0)}catch(e){if(e.data&&"M_NOT_FOUND"===e.data.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.map((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,"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 d=p.encodeUri("/join/$roomid",{$roomid:e}),l=(yield this.http.authedRequest(void 0,"POST",d,o,i,s)).room_id,u=new c.SyncApi(this,this.clientOpts).createRoom(l);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,d.EventStatus.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if([d.EventStatus.QUEUED,d.EventStatus.NOT_SENT].indexOf(e.status)<0)throw new Error("cannot cancel an event with status "+e.status);this.scheduler&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,d.EventStatus.CANCELLED)}setRoomName(e,t,n){return this.sendStateEvent(e,B.EventType.RoomName,{name:t},void 0,n)}setRoomTopic(e,t,n){return this.sendStateEvent(e,B.EventType.RoomTopic,{topic:t},void 0,n)}getRoomTags(e,t){const n=p.encodeUri("/user/$userId/rooms/$roomId/tags/",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(t,"GET",n,void 0)}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,"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,"DELETE",i,void 0,void 0)}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,"PUT",r,void 0,n)}setPowerLevel(e,t,n,i,r){let o={users:{}};(null==i?void 0:i.getType())===B.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,"PUT",s,void 0,o)}sendEvent(e,t,n,i,r){return this.sendCompleteEvent(e,{type:t,content:n},i,r)}sendCompleteEvent(e,t,n,i){p.isFunction(n)&&(i=n,n=void 0),n||(n=this.makeTxnId());const r=new d.MatrixEvent(Object.assign(t,{event_id:"~"+e+":"+n,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),o=this.getRoom(e),s=r.getAssociatedId();if(s&&s.startsWith("~")){const e=o.getPendingEvents().find((e=>e.getId()===s));e.once("Event.localEventIdReplaced",(()=>{r.updateAssociatedId(e.getId())}))}const a=r.getType();return w.logger.log(`sendEvent of type ${a} in ${e} with txnId ${n}`),r.setTxnId(n),r.setStatus(d.EventStatus.SENDING),o&&o.addPendingEvent(r,n),r.status===d.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(o,r,i)}encryptAndSendEvent(e,t,n){return Promise.resolve().then((()=>{const n=this.encryptEventIfNeeded(t,e);return n?(this.updatePendingEventStatus(e,t,d.EventStatus.ENCRYPTING),n.then((()=>this.updatePendingEventStatus(e,t,d.EventStatus.SENDING)))):null})).then((()=>{let n;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,d.EventStatus.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then((n=>(e.updatePendingEvent(t,d.EventStatus.SENT,n.event_id),n))))),n})).then((e=>(null==n||n(null,e),e))).catch((i=>{w.logger.error("Error sending event",i.stack||i);try{t.error=i,this.updatePendingEventStatus(e,t,d.EventStatus.NOT_SENT),i.event=t,null==n||n(i)}catch(e){w.logger.error("Exception in error handler!",e.stack||i)}throw i}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.crypto&&this.usingExternalCrypto)return null;if(e.getType()===B.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===B.EventType.Reaction?t:this.isRoomEncrypted(e)?B.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,"PUT",i,void 0,e.getWireContent()).then((t=>(w.logger.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,n,i){const r=("object"==typeof i?i:{}).reason,o="function"==typeof i?i:void 0;return this.sendCompleteEvent(e,{type:B.EventType.RoomRedaction,content:{reason:r},redacts:t},n,o)}sendMessage(e,t,n,i){return p.isFunction(n)&&(i=n,n=void 0),this.sendEvent(e,B.EventType.RoomMessage,t,n,i)}sendTextMessage(e,t,n,i){const r=N.makeTextMessage(t);return this.sendMessage(e,r,n,i)}sendNotice(e,t,n,i){const r=N.makeNotice(t);return this.sendMessage(e,r,n,i)}sendEmoteMessage(e,t,n,i){const r=N.makeEmoteMessage(t);return this.sendMessage(e,r,n,i)}sendImageMessage(e,t,n,i="Image",r){p.isFunction(i)&&(r=i,i=void 0);const o={msgtype:B.MsgType.Image,url:t,info:n,body:i};return this.sendMessage(e,o,void 0,r)}sendStickerMessage(e,t,n,i="Sticker",r){p.isFunction(i)&&(r=i,i=void 0);const o={url:t,info:n,body:i};return this.sendEvent(e,B.EventType.Sticker,o,void 0,r)}sendHtmlMessage(e,t,n,i){const r=N.makeHtmlMessage(t,n);return this.sendMessage(e,r,void 0,i)}sendHtmlNotice(e,t,n,i){const r=N.makeHtmlNotice(t,n);return this.sendMessage(e,r,void 0,i)}sendHtmlEmote(e,t,n,i){const r=N.makeHtmlEmote(t,n);return this.sendMessage(e,r,void 0,i)}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,"POST",r,void 0,n||{}),s=this.getRoom(e.getRoomId());return s&&s.addLocalEchoReceipt(this.credentials.userId,e,t),o}sendReadReceipt(e,t,n){return s(this,void 0,void 0,(function*(){"function"==typeof t&&(n=t,t={}),t||(t={});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})`);const o={"org.matrix.msc2285.hidden":Boolean(t.hidden)};return this.sendReceipt(e,"m.read",o,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;if(n){if(o=n.getId(),r&&r.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);r&&r.addLocalEchoReceipt(this.credentials.userId,n,"m.read")}return this.setRoomReadMarkersHttpRequest(e,t,o,i)}))}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,"GET","/preview_url",{url:e,ts:t},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,"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(B.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(B.EventType.RoomTombstone,"");if(!e||e.getContent().replacement_room!==n.roomId)break}i.splice(0,0,n),r=n.currentState.getStateEvents(B.EventType.RoomCreate,"")}}let o=n.currentState.getStateEvents(B.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(B.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(B.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,"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("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,"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,"POST",r,void 0,o)}setMembershipState(e,t,n,i,r){p.isFunction(i)&&(r=i,i=void 0);const o=p.encodeUri("/rooms/$roomId/state/m.room.member/$userId",{$roomId:e,$userId:t});return this.http.authedRequest(r,"PUT",o,void 0,{membership:n,reason:i})}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,"POST",o,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e){return e.getPushActions()||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,"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("User.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("User.avatarUrl",i.events.presence,i)),n}))}mxcUrlToHttp(e,t,n,i,r){return(0,D.getHttpUriForMxc)(this.baseUrl,e,t,n,i,r)}_unstable_setStatusMessage(e){const t="im.vector.user_status";return Promise.all(this.getRooms().map((n=>s(this,void 0,void 0,(function*(){const i="join"===n.getMyMembership(),r=2===n.getInvitedAndJoinedMemberCount();if(!i||!r)return;n.currentState.mayClientSendStateEvent(t,this)&&(yield this.sendStateEvent(n.roomId,t,{status:e},this.getUserId()))}))))).then()}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,"PUT",n,void 0,e)}getPresence(e,t){const n=p.encodeUri("/presence/$userId/status",{$userId:e});return this.http.authedRequest(t,"GET",n,void 0,void 0)}scrollback(e,t,n){p.isFunction(t)&&(n=t,t=void 0),t=t||30;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,y.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]=this.partitionThreadedEvents(i);e.addEventsToTimeline(o,!0,e.getLiveTimeline()),this.processThreadEvents(e,s),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,L.eventMapperFor)(this,e||{})}getEventTimeline(e,t){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 Promise.resolve(e.getTimelineForEvent(t));const n=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let i;this.clientOpts.lazyLoadMembers&&(i={filter:JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER)});return this.http.authedRequest(void 0,"GET",n,i).then((n=>{if(!n.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);n.events_after.reverse();const i=n.events_after.concat([n.event]).concat(n.events_before).map(this.getEventMapper());let r=e.getTimelineForEvent(i[0].getId());if(r){const e=n.state.map(this.getEventMapper());r.getState(y.EventTimeline.BACKWARDS).setUnknownStateEvents(e)}else r=e.addTimeline(),r.initialiseState(n.state.map(this.getEventMapper())),r.getState(y.EventTimeline.FORWARDS).paginationToken=n.end;const[o,s]=this.partitionThreadedEvents(i);return e.addEventsToTimeline(o,!0,r,n.start),this.processThreadEvents(e.room,s),e.getTimelineForEvent(t)||r}))}createMessagesRequest(e,t,n,i,r){var o;const s=p.encodeUri("/rooms/$roomId/messages",{$roomId:e});void 0===n&&(n=30);const a={from:t,limit:n,dir:i};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,"GET",s,a)}paginateEventTimeline(e,t){const n=e.getTimelineSet()===this.notifTimelineSet,i=(t=t||{}).backwards||!1;if(n&&!i)throw new Error("paginateNotifTimeline can only paginate backwards");const r=i?y.EventTimeline.BACKWARDS:y.EventTimeline.FORWARDS,o=e.getPaginationToken(r);if(!o)return Promise.resolve(!1);const s=e.paginationRequests[r];if(s)return s;let a,c,d;if(n)a="/notifications",c={limit:"limit"in t?t.limit:30,only:"highlight"},o&&"end"!==o&&(c.from=o),d=this.http.authedRequest(void 0,"GET","/notifications",c,void 0).then((t=>{const n=t.next_token,o=[];for(let e=0;e<t.notifications.length;e++){const n=t.notifications[e],i=this.getEventMapper()(n.event);i.setPushActions(m.PushProcessor.actionListToActionsObject(n.actions)),i.event.room_id=n.room_id,o[e]=i}const[s,a]=this.partitionThreadedEvents(o),c=e.getTimelineSet();return c.addEventsToTimeline(s,i,e,n),this.processThreadEvents(c.room,a),i&&!t.next_token&&e.setPaginationToken(null,r),!!t.next_token})).finally((()=>{e.paginationRequests[r]=null})),e.paginationRequests[r]=d;else{const n=this.getRoom(e.getRoomId());if(!n)throw new Error("Unknown room "+e.getRoomId());d=this.createMessagesRequest(e.getRoomId(),o,t.limit,r,e.getFilter()),d.then((t=>{if(t.state){const n=e.getState(r),i=t.state.map(this.getEventMapper());n.setUnknownStateEvents(i)}const o=t.end,s=t.chunk.map(this.getEventMapper()),[a,c]=this.partitionThreadedEvents(s);return e.getTimelineSet().addEventsToTimeline(a,i,e,o),this.processThreadEvents(n,c),i&&t.end==t.start&&e.setPaginationToken(null,r),t.end!=t.start})).finally((()=>{e.paginationRequests[r]=null})),e.paginationRequests[r]=d}return d}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,B.EventType.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let i=Promise.resolve(void 0);return t.allowRead&&(i=this.sendStateEvent(e,B.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){return s(this,void 0,void 0,(function*(){const n=Object.assign({},t);if(!(yield this.doesServerSupportSeparateAddAndBind())&&this.idBaseUrl){const e=new URL(this.idBaseUrl);if(n.id_server=e.host,this.identityServer&&this.identityServer.getAccessToken&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(void 0,"POST",e,void 0,n)}))}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;const o=this.getRoomPushRule(e,t);if(o&&0<=o.actions.indexOf("dont_notify")&&(r=!0),n?o?r||(i=p.defer(),this.deletePushRule(e,G.PushRuleKind.RoomSpecific,o.rule_id).then((()=>{this.addPushRule(e,G.PushRuleKind.RoomSpecific,t,{actions:["dont_notify"]}).then((()=>{i.resolve()})).catch((e=>{i.reject(e)}))})).catch((e=>{i.reject(e)})),i=i.promise):i=this.addPushRule(e,G.PushRuleKind.RoomSpecific,t,{actions:["dont_notify"]}):r&&(i=this.deletePushRule(e,G.PushRuleKind.RoomSpecific,o.rule_id)),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:$.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){const n=t.search_categories.room_events;e.count=n.count,e.next_batch=n.next_batch;const i={};n.highlights.forEach((e=>{i[e]=1})),e.highlights.forEach((e=>{i[e]=1})),e.highlights=Object.keys(i);const r=n.results?n.results.length:0;for(let t=0;t<r;t++){const i=A.SearchResult.fromJson(n.results[t],this.getEventMapper()),r=this.getRoom(i.context.getEvent().getRoomId());if(r)for(const e of i.context.getTimeline()){const t=r.getMember(e.getSender());!e.sender&&t&&(e.sender=t)}e.results.push(i)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new c.SyncApi(this,this.clientOpts);return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then((e=>{w.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,"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,"GET",i,void 0,void 0).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,"POST",e,void 0,{})}turnServer(e){return this.http.authedRequest(e,"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>H)w.logger.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),e=!0;else{w.logger.debug("Fetching new TURN credentials");try{const t=yield this.turnServer();if(t.uris){w.logger.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const n={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[n],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0}}catch(e){w.logger.error("Failed to get TURN URIs",e),403===e.httpStatus&&(w.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=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,"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,"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,"POST",t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){return s(this,void 0,void 0,(function*(){this.clientWellKnownPromise=v.AutoDiscovery.getRawClientConfig(this.getDomain()),this.clientWellKnown=yield this.clientWellKnownPromise,this.emit("WellKnown.client",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*(){if(!(yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666")))throw Error("Server does not support shared_rooms API");const t=p.encodeUri("/uk.half-shot.msc2666/user/shared_rooms/$userId",{$userId:e});return(yield this.http.authedRequest(void 0,"GET",t,void 0,void 0,{prefix:I.PREFIX_UNSTABLE})).joined}))}getVersions(){return this.serverVersionsPromise||(this.serverVersionsPromise=this.http.request(void 0,"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 t&&t.includes("r0.6.0")||n&&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}`]}))}hasLazyLoadMembersEnabled(){return!!this.clientOpts.lazyLoadMembers}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,n,i,r){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();let c;s.original_event&&(c=a(s.original_event));let d=s.chunk.map(a);if(o===B.EventType.RoomMessageEncrypted){const e=c?d.concat(c):d;yield Promise.all(e.map((e=>{if(e.isEncrypted())return new Promise((t=>e.once("Event.decrypted",t)))}))),d=d.filter((e=>e.getType()===i))}return c&&n===B.RelationType.Replace&&(d=d.filter((e=>e.getSender()===c.getSender()))),{originalEvent:c,events:d,nextBatch:s.next_batch}}))}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,j.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 T.SERVICE_TYPES.IS:return t+I.PREFIX_IDENTITY_V2+"/terms";case T.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}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(void 0,"GET","/register/available",{username:e}).then((e=>e.available))}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};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,"POST","/register",i,e)}loginFlows(e){return this.http.request(e,"GET","/login")}login(e,t,n){const i={type:e};return p.extend(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)}),"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){return this.http.authedRequest(e,"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,"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,"POST","/createRoom",void 0,e)}))}fetchRelations(e,t,n,i,r){return s(this,void 0,void 0,(function*(){const o={};r.from&&(o.from=r.from);const s=p.encodeParams(o),a=p.encodeUri("/rooms/$roomId/relations/$eventId/$relationType/$eventType?"+s,{$roomId:e,$eventId:t,$relationType:n,$eventType:i});return yield this.http.authedRequest(void 0,"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,"GET",n)}fetchRoomEvent(e,t,n){const i=p.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(n,"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,"GET",a)}upgradeRoom(e,t){const n=p.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(void 0,"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,"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,"PUT",s,void 0,n)}roomInitialSync(e,t,n){p.isFunction(t)&&(n=t,t=void 0);const i=p.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this.http.authedRequest(n,"GET",i,{limit:t})}setRoomReadMarkersHttpRequest(e,t,n,i){const r=p.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),o={"m.fully_read":t,"m.read":n,"org.matrix.msc2285.hidden":Boolean(!!i&&i.hidden)};return this.http.authedRequest(void 0,"POST",r,void 0,o)}getJoinedRooms(){const e=p.encodeUri("/joined_rooms",{});return this.http.authedRequest(void 0,"GET",e)}getJoinedRoomMembers(e){const t=p.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(void 0,"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,"GET","/publicRooms"):this.http.authedRequest(t,"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,"PUT",i,void 0,r)}deleteAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,"DELETE",n,void 0,void 0)}unstableGetLocalAliases(e,t){const n=p.encodeUri("/rooms/$roomId/aliases",{$roomId:e}),i=I.PREFIX_UNSTABLE+"/org.matrix.msc2432";return this.http.authedRequest(t,"GET",n,null,null,{prefix:i})}getRoomIdForAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,"GET",n)}resolveRoomAlias(e,t){const n=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.request(t,"GET",n)}getRoomDirectoryVisibility(e,t){const n=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(t,"GET",n)}setRoomDirectoryVisibility(e,t,n){const i=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(n,"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,"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,"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,"GET",i)}getThreePids(e){return this.http.authedRequest(e,"GET","/account/3pid",void 0,void 0)}addThreePid(e,t,n){const i={threePidCreds:e,bind:t};return this.http.authedRequest(n,"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,"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,"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,"POST","/account/3pid/unbind",null,n,{prefix:i})}))}deleteThreePid(e,t){return this.http.authedRequest(void 0,"POST","/account/3pid/delete",null,{medium:e,address:t})}setPassword(e,t,n){const i={auth:e,new_password:t};return this.http.authedRequest(n,"POST","/account/password",null,i)}getDevices(){return this.http.authedRequest(void 0,"GET","/devices",void 0,void 0)}getDevice(e){const t=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,"GET",t,void 0,void 0)}setDeviceDetails(e,t){const n=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,"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,"DELETE",n,void 0,i)}deleteMultipleDevices(e,t){const n={devices:e};t&&(n.auth=t);return this.http.authedRequest(void 0,"POST","/delete_devices",void 0,n)}getPushers(e){return this.http.authedRequest(e,"GET","/pushers",void 0,void 0)}setPusher(e,t){return this.http.authedRequest(t,"POST","/pushers/set",null,e)}getPushRules(e){return this.http.authedRequest(e,"GET","/pushrules/").then((e=>m.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,"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,"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,"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,"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,"POST","/search",n,e.body)}uploadKeysRequest(e,t,n){return this.http.authedRequest(n,"POST","/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(void 0,"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,"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,"POST","/keys/claim",void 0,r)}getKeyChanges(e,t){const n={from:e,to:t};return this.http.authedRequest(void 0,"GET","/keys/changes",n,void 0)}uploadDeviceSigningKeys(e,t){const n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(void 0,"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,"POST",t,null,e)}requestEmailToken(e,t,n,i,r,o){return s(this,void 0,void 0,(function*(){const s={client_secret:t,email:e,send_attempt:n,next_link:i};return yield this.http.idServerRequest(r,"POST","/validate/email/requestToken",s,I.PREFIX_IDENTITY_V2,o)}))}requestMsisdnToken(e,t,n,i,r,o,a){return s(this,void 0,void 0,(function*(){const s={client_secret:n,country:e,phone_number:t,send_attempt:i,next_link:r};return yield this.http.idServerRequest(o,"POST","/validate/msisdn/requestToken",s,I.PREFIX_IDENTITY_V2,a)}))}submitMsisdnToken(e,t,n,i){return s(this,void 0,void 0,(function*(){const r={sid:e,client_secret:t,token:n};return yield this.http.idServerRequest(void 0,"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,"POST",e,void 0,r)}getIdentityHashDetails(e){return this.http.idServerRequest(void 0,"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,"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,"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 w.logger.log(`PUT ${i}`,o),this.http.authedRequest(void 0,"PUT",i,void 0,r)}getThirdpartyProtocols(){return this.http.authedRequest(void 0,"GET","/thirdparty/protocols",void 0,void 0).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,"GET",n,t,void 0)}getThirdpartyUser(e,t){const n=p.encodeUri("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(void 0,"GET",n,t,void 0)}getTerms(e,t){const n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(void 0,"GET",n)}agreeToTerms(e,t,n,i){const r=this.termsUrlForService(e,t),o={Authorization:"Bearer "+n};return this.http.requestOtherUrl(void 0,"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,"POST",r,null,{score:n,reason:i})}getSpaceSummary(e,t,n,i,r,o){const s=p.encodeUri("/rooms/$roomId/spaces",{$roomId:e});return this.http.authedRequest(void 0,"POST",s,null,{max_rooms_per_space:t,suggested_only:n,auto_join_only:i,limit:r,batch:o},{prefix:"/_matrix/client/unstable/org.matrix.msc2946"})}getRoomHierarchy(e,t,n,i=!1,r){const o=p.encodeUri("/rooms/$roomId/hierarchy",{$roomId:e});return this.http.authedRequest(void 0,"GET",o,{suggested_only:i,max_depth:n,from:r,limit:t},void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"}).catch((n=>{if("M_UNRECOGNIZED"===n.errcode)return this.getSpaceSummary(e,void 0,i,void 0,t).then((({rooms:e,events:t})=>{const n=new Map(e.map((e=>[e.room_id,Object.assign(Object.assign({},e),{children_state:[]})])));return t.forEach((e=>{var t;null===(t=n.get(e.room_id))||void 0===t||t.children_state.push(e)})),{rooms:Array.from(n.values())}}));throw n}))}unstableCreateFileTree(e){return s(this,void 0,void 0,(function*(){const{room_id:t}=yield this.createRoom({name:e,preset:K.Preset.PrivateChat,power_level_content_override:Object.assign(Object.assign({},q.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{users:{[this.getUserId()]:100}}),creation_content:{[B.RoomCreateTypeField]:B.RoomType.Space},initial_state:[{type:B.UNSTABLE_MSC3088_PURPOSE.name,state_key:B.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[B.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:B.EventType.RoomEncryption,state_key:"",content:{algorithm:S.MEGOLM_ALGORITHM}}]});return new q.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(B.EventType.RoomCreate,""),o=i.currentState.getStateEvents(B.UNSTABLE_MSC3088_PURPOSE.name,B.UNSTABLE_MSC3089_TREE_SUBTYPE.name);if(!r)throw new Error("Expected single room create event");return(null===(t=null==o?void 0:o.getContent())||void 0===t?void 0:t[B.UNSTABLE_MSC3088_ENABLED.name])?(null===(n=r.getContent())||void 0===n?void 0:n[B.RoomCreateTypeField])!==B.RoomType.Space?null:new q.MSC3089TreeSpace(this,e):null}getGroupSummary(e){const t=p.encodeUri("/groups/$groupId/summary",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupProfile(e){const t=p.encodeUri("/groups/$groupId/profile",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}setGroupProfile(e,t){const n=p.encodeUri("/groups/$groupId/profile",{$groupId:e});return this.http.authedRequest(void 0,"POST",n,void 0,t)}setGroupJoinPolicy(e,t){const n=p.encodeUri("/groups/$groupId/settings/m.join_policy",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,{"m.join_policy":t})}getGroupUsers(e){const t=p.encodeUri("/groups/$groupId/users",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupInvitedUsers(e){const t=p.encodeUri("/groups/$groupId/invited_users",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupRooms(e){const t=p.encodeUri("/groups/$groupId/rooms",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}inviteUserToGroup(e,t){const n=p.encodeUri("/groups/$groupId/admin/users/invite/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"PUT",n,void 0,{})}removeUserFromGroup(e,t){const n=p.encodeUri("/groups/$groupId/admin/users/remove/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"PUT",n,void 0,{})}addUserToGroupSummary(e,t,n){const i=p.encodeUri(n?"/groups/$groupId/summary/$roleId/users/$userId":"/groups/$groupId/summary/users/$userId",{$groupId:e,$roleId:n,$userId:t});return this.http.authedRequest(void 0,"PUT",i,void 0,{})}removeUserFromGroupSummary(e,t){const n=p.encodeUri("/groups/$groupId/summary/users/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}addRoomToGroupSummary(e,t,n){const i=p.encodeUri(n?"/groups/$groupId/summary/$categoryId/rooms/$roomId":"/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$categoryId:n,$roomId:t});return this.http.authedRequest(void 0,"PUT",i,void 0,{})}removeRoomFromGroupSummary(e,t){const n=p.encodeUri("/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}addRoomToGroup(e,t,n){void 0===n&&(n=!0);const i=p.encodeUri("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"PUT",i,void 0,{"m.visibility":{type:n?"public":"private"}})}updateGroupRoomVisibility(e,t,n){const i=p.encodeUri("/groups/$groupId/admin/rooms/$roomId/config/m.visibility",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"PUT",i,void 0,{type:n?"public":"private"})}removeRoomFromGroup(e,t){const n=p.encodeUri("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}acceptGroupInvite(e,t=null){const n=p.encodeUri("/groups/$groupId/self/accept_invite",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,t||{})}joinGroup(e){const t=p.encodeUri("/groups/$groupId/self/join",{$groupId:e});return this.http.authedRequest(void 0,"PUT",t,void 0,{})}leaveGroup(e){const t=p.encodeUri("/groups/$groupId/self/leave",{$groupId:e});return this.http.authedRequest(void 0,"PUT",t,void 0,{})}getJoinedGroups(){const e=p.encodeUri("/joined_groups",{});return this.http.authedRequest(void 0,"GET",e)}createGroup(e){const t=p.encodeUri("/create_group",{});return this.http.authedRequest(void 0,"POST",t,void 0,e)}getPublicisedGroups(e){const t=p.encodeUri("/publicised_groups",{});return this.http.authedRequest(void 0,"POST",t,void 0,{user_ids:e})}setGroupPublicity(e,t){const n=p.encodeUri("/groups/$groupId/self/update_publicity",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,{publicise:t})}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,"GET",n,{via:t},null,{qsStringifyOptions:{arrayFormat:"repeat"},prefix:"/_matrix/client/unstable/im.nheko.summary"})}))}partitionThreadedEvents(e){const t=new Set;return this.supportsExperimentalThreads()?e.reduce(((n,i)=>{const r=this.getRoom(i.getRoomId());let o=i.isThreadRelation;if(o)t.add(i.relationEventId);else{const s=i.parentEventId,a=(null==r?void 0:r.findEventById(s))||e.find((e=>e.getId()===s));o=null==a?void 0:a.isThreadRelation;((null==a?void 0:a.isThreadRoot)||t.has(i.relationEventId))&&!i.isThreadRelation&&i.relationEventId&&n[1].push(i)}return n[o?1:0].push(i),n}),[[],[]]):[e,[]]}processThreadEvents(e,t){t.sort(((e,t)=>e.getTs()-t.getTs())).forEach((t=>{e.addThreadedEvent(t)}))}}n.MatrixClient=Y,Y.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":58,"./@types/event":59,"./@types/partials":60,"./@types/search":61,"./ReEmitter":63,"./autodiscovery":64,"./content-helpers":67,"./content-repo":68,"./crypto":85,"./crypto/RoomList":74,"./crypto/api":81,"./crypto/backup":82,"./crypto/dehydration":83,"./crypto/key_passphrase":86,"./crypto/olmlib":87,"./crypto/recoverykey":88,"./event-mapper":102,"./filter":104,"./http-api":105,"./logger":108,"./matrix":109,"./models/MSC3089TreeSpace":111,"./models/event":116,"./models/event-timeline":115,"./models/search-result":123,"./models/user":125,"./pushprocessor":126,"./randomstring":127,"./service-types":130,"./store/stub":136,"./sync":139,"./sync.api":138,"./utils":141,"./webrtc/call":142,"./webrtc/callEventHandler":143,"./webrtc/mediaHandler":146,events:28}],67:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.makeEmoteMessage=n.makeNotice=n.makeTextMessage=n.makeHtmlEmote=n.makeHtmlNotice=n.makeHtmlMessage=void 0;const i=e("./@types/event");n.makeHtmlMessage=function(e,t){return{msgtype:i.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeHtmlNotice=function(e,t){return{msgtype:i.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeHtmlEmote=function(e,t){return{msgtype:i.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}},n.makeTextMessage=function(e){return{msgtype:i.MsgType.Text,body:e}},n.makeNotice=function(e){return{msgtype:i.MsgType.Notice,body:e}},n.makeEmoteMessage=function(e){return{msgtype:i.MsgType.Emote,body:e}}},{"./@types/event":59}],68:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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 d={};n&&(d.width=Math.round(n)),i&&(d.height=Math.round(i)),r&&(d.method=r),Object.keys(d).length>0&&(c="/_matrix/media/r0/thumbnail/");const l=a.indexOf("#");let u="";return l>=0&&(u=a.substr(l),a=a.substr(0,l)),e+c+a+(0===Object.keys(d).length?"":"?"+s.encodeParams(d))+u}},{"./utils":141}],69:[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("events"),s=e("./olmlib"),a=e("../logger"),c=e("../crypto/store/indexeddb-crypto-store"),d=e("./aes");function l(e){return Object.values(e.keys)[0]}class u extends o.EventEmitter{constructor(e,t={},n={}){super(),this.userId=e,this.callbacks=t,this.cacheCallbacks=n,this.keys={},this.firstUse=!0,this.crossSigningVerifiedBefore=!1}static fromStorage(e,t){const n=new u(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",!1))||{};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}`,!1))||{});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,s.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,s.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&h.MASTER||!this.keys.master)e=h.MASTER|h.USER_SIGNING|h.SELF_SIGNING;else if(0===e)return;const n={},i={};let r,o;try{if(e&h.MASTER?(r=new t.Olm.PkSigning,n.master=r.generate_seed(),o=r.init_with_seed(n.master),i.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+o]:o}}):[o,r]=yield this.getCrossSigningKey("master"),e&h.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,s.pkSign)(i.self_signing,r,this.userId,o)}finally{e.free()}}if(e&h.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,s.pkSign)(i.user_signing,r,this.userId,o)}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 a.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 a.logger.error(t),new Error(t)}try{(0,s.pkVerify)(e.user_signing,n,this.userId)}catch(e){throw a.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 a.logger.error(t),new Error(t)}try{(0,s.pkVerify)(e.self_signing,n,this.userId)}catch(e){throw a.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,s.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");a.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");a.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 g(!0,!0,this.firstUse);if(!this.keys.user_signing)return new g(!1,!1,e.firstUse);let t;const n=e.keys.master,i=this.getId("user_signing");try{(0,s.pkVerify)(n,i,this.userId),t=!0}catch(e){t=!1}return new g(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,n,i){const r=this.checkUserTrust(e),o=e.keys.self_signing;if(!o)return new p(!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,s.pkVerify)(o,e.getId(),e.userId),(0,s.pkVerify)(a,l(o),e.userId),p.fromUserTrustLevel(r,n,i)}catch(e){return new p(!1,!1,n,i)}}getCacheCallbacks(){return this.cacheCallbacks}}var h;n.CrossSigningInfo=u,function(e){e[e.MASTER=4]="MASTER",e[e.USER_SIGNING=2]="USER_SIGNING",e[e.SELF_SIGNING=1]="SELF_SIGNING"}(h=n.CrossSigningLevel||(n.CrossSigningLevel={}));class g{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=g;class p{constructor(e,t,n,i){this.crossSigningVerified=e,this.tofu=t,this.localVerified=n,this.trustCrossSignedDevices=i}static fromUserTrustLevel(e,t,n){return new p(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=p,n.createCryptoStoreCacheCallbacks=function(e,t){return{getCrossSigningKeyCache:function(n,o){return r(this,void 0,void 0,(function*(){const r=yield new Promise((t=>e.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(i=>{e.getSecretStorePrivateKey(i,t,n)}))));if(r&&r.ciphertext){const e=i.from(t.pickleKey),o=yield(0,d.decryptAES)(r,e,n);return(0,s.decodeBase64)(o)}return r}))},storeCrossSigningKeyCache:function(n,o){return r(this,void 0,void 0,(function*(){if(!(o instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${o}`);const r=i.from(t.pickleKey),a=yield(0,d.encryptAES)((0,s.encodeBase64)(o),r,n);return e.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.storeSecretStorePrivateKey(t,n,a)}))}))}}},n.requestKeysDuringVerification=function(e,t,n){if(e.getUserId()===t)return a.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise(((t,i)=>{const o=e,c=o.crypto.crossSigningInfo,d=new u(c.userId,{getCrossSigningKey:e=>r(this,void 0,void 0,(function*(){a.logger.debug("Cross-signing: requesting secret",e,n);const{promise:t}=o.requestSecret(`m.cross_signing.${e}`,[n]),i=yield t,r=(0,s.decodeBase64)(i);return Uint8Array.from(r)}))},c.getCacheCallbacks());d.keys=c.keys;const l=new Promise((e=>{setTimeout(e,6e4,new Error("Timeout"))})),h=(()=>r(this,void 0,void 0,(function*(){if(!(yield o.crypto.getSessionBackupPrivateKey())){a.logger.info("No cached backup key found. Requesting...");const e=o.requestSecret("m.megolm_backup.v1",[n]),t=yield e.promise;a.logger.info("Got key backup key, decoding...");const i=(0,s.decodeBase64)(t);a.logger.info("Decoded backup key, storing..."),yield o.crypto.storeSessionBackupPrivateKey(Uint8Array.from(i)),a.logger.info("Backup key stored. Starting backup restore...");const r=yield o.getKeyBackupVersion();o.restoreKeyBackupWithCache(void 0,void 0,r).then((()=>{a.logger.info("Backup restored.")}))}})))();return Promise.race([Promise.all([d.getCrossSigningKey("master"),d.getCrossSigningKey("self_signing"),d.getCrossSigningKey("user_signing"),h]),l]).then(t,i)})).catch((e=>{a.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":90,"../logger":108,"./aes":76,"./olmlib":87,buffer:24,events:28}],70:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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("events"),c=e("../logger"),d=e("./deviceinfo"),l=e("./CrossSigning"),u=o(e("./olmlib")),h=e("./store/indexeddb-crypto-store"),g=e("../utils");var p;!function(e){e[e.NotTracked=0]="NotTracked",e[e.PendingDownload=1]="PendingDownload",e[e.DownloadInProgress=2]="DownloadInProgress",e[e.UpToDate=3]="UpToDate"}(p=n.TrackingStatus||(n.TrackingStatus={}));class f extends a.EventEmitter{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",[h.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]==p.DownloadInProgress&&(this.deviceTrackingStatus[e]=p.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,t)=>{this.resolveSavePromise=e})),this.savePromise=n),null===this.saveTimer){const n=this.resolveSavePromise;this.savePromiseTime=t,this.saveTimer=setTimeout((()=>{c.logger.log("Saving device tracking data",this.syncToken),this.savePromiseTime=null,this.saveTimer=null,this.savePromise=null,this.resolveSavePromise=null,this.cryptoStore.doTxn("readwrite",[h.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=>{c.logger.error("Failed to save device tracking data",this.syncToken),c.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]?(c.logger.log(`downloadKeys: already have a download in progress for ${e}: awaiting its result`),i.push(this.keyDownloadsInProgressByUser[e])):(t||r!=p.UpToDate)&&n.push(e)})),0!=n.length){c.logger.log("downloadKeys: downloading for",n);const e=this.doKeyDownload(n);i.push(e)}return 0===i.length&&c.logger.log("downloadKeys: already have all necessary keys"),Promise.all(i).then((()=>this.getDevicesFromStore(e)))}getDevicesFromStore(e){const t={};return e.map((e=>{t[e]={};(this.getStoredDevicesForUser(e)||[]).map((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(d.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 d.DeviceInfo.fromStorage(n[t],t)}getUserByIdentityKey(e,t){return e!==u.OLM_ALGORITHM&&e!==u.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 d.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]||(c.logger.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=p.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(c.logger.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=p.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=p.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(c.logger.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=p.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this.deviceTrackingStatus)){this.deviceTrackingStatus[t]==p.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 c.logger.error("Error downloading keys for "+e+":",t),n(!1),t}));e.forEach((e=>{this.keyDownloadsInProgressByUser[e]=t;this.deviceTrackingStatus[e]==p.PendingDownload&&(this.deviceTrackingStatus[e]=p.DownloadInProgress)}));const n=n=>{this.emit("crypto.willUpdateDevices",e,!this.hasFetched),e.forEach((e=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser[e]!==t)return void c.logger.log("Another update in the queue for",e,"- not marking up-to-date");delete this.keyDownloadsInProgressByUser[e];this.deviceTrackingStatus[e]==p.DownloadInProgress&&(n?(this.deviceTrackingStatus[e]=p.UpToDate,c.logger.log("Device list for",e,"now up to date")):this.deviceTrackingStatus[e]=p.PendingDownload)})),this.saveIfDirty(),this.emit("crypto.devicesUpdated",e,!this.hasFetched),this.hasFetched=!0};return t}}n.DeviceList=f;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,g.defer)()),this.syncToken=t,this.downloadInProgress?(c.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,c.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,g.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,g.sleep)(5);try{yield this.processQueryResponseForUser(t,n[t],{master:i[t],self_signing:r[t],user_signing:o[t]})}catch(e){c.logger.error(`Error processing keys for ${t}:`,e)}}})))).then((()=>{c.logger.log("Completed key download for "+e),this.downloadInProgress=!1,t.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()}),(n=>{c.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*(){c.logger.log("got device keys for "+e+":",t),c.logger.log("got cross-signing keys for "+e+":",n);{const n={},i=this.deviceList.getRawStoredDevicesForUser(e);i&&Object.keys(i).forEach((e=>{const t=d.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){c.logger.warn(`Local device ${e} missing from sync, skipping removal`);continue}c.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):c.logger.warn("Mismatched device_id "+o.device_id+" in keys from "+t+":"+r):c.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("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 c.logger.warn("Device "+r+":"+i+" has no ed25519 key"),!1;const a=n.unsigned||{},l=n.signatures||{};try{yield u.verifySignature(e,n,r,i,s)}catch(e){return c.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 c.logger.warn("Ed25519 key for device "+r+":"+i+" has changed"),!1}else t[i]=h=new d.DeviceInfo(i);return h.keys=n.keys||{},h.algorithms=n.algorithms||[],h.unsigned=a,h.signatures=l,!0}))}},{"../logger":108,"../utils":141,"./CrossSigning":69,"./deviceinfo":84,"./olmlib":87,"./store/indexeddb-crypto-store":90,events:28}],71:[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("events"),a=e("./CrossSigning"),c=e("./store/indexeddb-crypto-store"),d=e("../http-api");n.EncryptionSetupBuilder=class{constructor(e,t){this.crossSigningKeys=null,this.keySignatures=null,this.keyBackupInfo=null,this.accountDataClientAdapter=new u(e),this.crossSigningCallbacks=new h,this.ssssCryptoCallbacks=new g(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 l(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}persist(e){return i(this,void 0,void 0,(function*(){if(this.crossSigningKeys){const t=(0,a.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",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.cryptoStore.storeCrossSigningKeys(t,this.crossSigningKeys.keys)}))}this.sessionBackupPrivateKey&&(yield e.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey))}))}};class l{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,"PUT","/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:d.PREFIX_UNSTABLE}):yield t.http.authedRequest(void 0,"POST","/room_keys/version",void 0,this.keyBackupInfo,{prefix:d.PREFIX_UNSTABLE}))}))}}n.EncryptionSetupOperation=l;class u extends s.EventEmitter{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("accountData",i,n),{}}))}}class h{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 g{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":105,"../logger":108,"../models/event":116,"./CrossSigning":69,"./store/indexeddb-crypto-store":90,events:28}],72:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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"),d=o(e("./algorithms"));function l(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.fallback_key())}))})),e}))}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 l(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 s(this,void 0,void 0,(function*(){return yield this.cryptoStore.getEndToEndSessionProblem(e,t)}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){return yield 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}`),l(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,d,l,u={}){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,c.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(s=>{this.getInboundGroupSession(e,n,r,s,((c,h)=>{const g=new t.Olm.InboundGroupSession;try{if(l?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:d,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,l;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&&(l=new d.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(l=e&&"OLM.UNKNOWN_MESSAGE_INDEX"===e.message&&h?new d.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(l=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]")),l)throw l;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":108,"./algorithms":78,"./store/indexeddb-crypto-store":90}],73:[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 yield 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":59,"../logger":108}],74:[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":90}],75:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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")),d=e("../randomstring"),l=e("./aes"),u=e("./olmlib");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("accountData",i),t())};this.accountDataAdapter.on("accountData",i),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch((e=>{this.accountDataAdapter.removeListener("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,l.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,l.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,u.encodeBase64)(o.get_private_key()):yield o.decrypt(n)}finally{o&&o.free&&o.free()}}))}isStored(e,t){return s(this,void 0,void 0,(function*(){const i=yield this.accountDataAdapter.getAccountDataFromServer(e);if(!i)return null;if(!i.encrypted)return null;void 0===t&&(t=!0);const r={};for(const e of Object.keys(i.encrypted)){const t=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);if(!t)continue;const o=i.encrypted[e];t.algorithm===n.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(r[e]=t)}return Object.keys(r).length?r: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 s(this,void 0,void 0,(function*(){return yield(0,l.encryptAES)(e,o,t)}))},decrypt:function(e){return s(this,void 0,void 0,(function*(){return yield(0,l.decryptAES)(e,o,t)}))}}]}throw new Error("Unknown key type: "+e[r].algorithm)}))}}},{"../logger":108,"../randomstring":127,"./aes":76,"./olmlib":87}],76:[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 d(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"]),d=s.importKey("raw",o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return yield Promise.all([c,d])}))}function l(e,n,a,l){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 d(t,n),l=(new TextEncoder).encode(e),u=yield s.encrypt({name:"AES-CTR",counter:i,length:64},a,l),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,l):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 d;a?d=(0,o.decodeBase64)(a):(d=i.randomBytes(16),d[8]&=127);const[l,u]=c(n,s),h=i.createCipheriv("aes-256-ctr",l,d),g=t.concat([h.update(e,"utf8"),h.final()]),p=i.createHmac("sha256",u).update(g).digest("base64");return{iv:(0,o.encodeBase64)(d),ciphertext:g.toString("base64"),mac:p}}))}(e,n,a,l)}n.encryptAES=l,n.decryptAES=function(e,n,a){return s?function(e,t,n){return i(this,void 0,void 0,(function*(){const[i,r]=yield d(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,d]=c(n,s);if(i.createHmac("sha256",d).update(t.from(e.ciphertext,"base64")).digest("base64").replace(/=+$/g,"")!==e.mac.replace(/=+$/g,""))throw new Error(`Error decrypting secret ${s}: bad MAC`);const l=i.createDecipheriv("aes-256-ctr",a,(0,o.decodeBase64)(e.iv));return l.update(e.ciphertext,"base64","utf8")+l.final("utf8")}))}(e,n,a)};n.calculateKeyCheck=function(e,t){return l("\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":141,"./olmlib":87,buffer:24}],77:[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}},{}],78:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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":77,"./megolm":79,"./olm":80}],79:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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")),d=e("./base"),l=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 d.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 d=this.setupPromise.then((o=>s(this,void 0,void 0,(function*(){r=o;const d=u(e);r&&d!==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(d),a.logger.log(`Started new megolm session ${r.sessionId} for room ${this.roomId}`),this.outboundSessions[r.sessionId]=r);const l={};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]||(l[e]=l[e]||[],l[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":d}},[p,f]=yield c.getExistingOlmSessions(this.olmDevice,this.baseApis,l);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 d.catch((e=>{a.logger.error(`Failed to ensure outbound session in ${this.roomId}`,e)})),this.setupPromise=d.then(o,o),d.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],d=a.userId,l=a.deviceInfo,u=l.deviceId;o.set(u,l),r[d]||(r[d]={}),r[d][u]=t,s.push(c.encryptMessageForDevice(t.ciphertext,this.userId,this.deviceId,this.olmDevice,d,l,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);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 d={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}},l={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};yield c.encryptMessageForDevice(l.ciphertext,this.userId,this.deviceId,this.olmDevice,n,i,d),yield this.baseApis.sendToDevice("m.room.encrypted",{[n]:{[i.deviceId]:l}}),a.logger.debug(`Re-shared key for megolm session ${t} with ${n}:${i.deviceId}`)}))}shareKeyWithDevices(e,t,n,i,r,o,d){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,d,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:l.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},d=this.olmDevice.encryptGroupMessage(o.sessionId,JSON.stringify(s)),l={algorithm:c.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:d,session_id:o.sessionId,device_id:this.deviceId};return o.useCount++,l}))}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 d.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:l.WITHHELD_MESSAGES[n?"m.blacklisted":"m.unverified"],deviceInfo:t[i]},delete t[i]}}}return[i,r]}))}}class p extends d.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 d.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 d.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 d.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",e,{session:t.sender_key+"|"+t.session_id})}throw new d.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 d.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=r&&r.get(i);o&&(o.delete(e),0===o.size&&r.delete(n),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){return s(this,void 0,void 0,(function*(){const n=this.pendingEvents[e];if(!n)return!0;const i=n.get(t);return!i||(a.logger.debug("Retrying decryption on events",[...i]),yield Promise.all([...i].map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto,{isRetry:!0})}catch(e){}}))))),!(this.pendingEvents[e]||{})[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,d.registerAlgorithm)(c.MEGOLM_ALGORITHM,g,p)},{"../../logger":108,"../OlmDevice":72,"../olmlib":87,"./base":77}],80:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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")),d=e("../deviceinfo"),l=e("./base"),u=d.DeviceInfo.DeviceVerification;class h extends l.EncryptionAlgorithm{constructor(){super(...arguments),this.sessionPrepared=!1,this.prepPromise=null}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then((t=>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 yield Promise.all(s).then((()=>o))}))}}class g extends l.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 l.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in i))throw new l.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 l.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:n,err:e})}const s=JSON.parse(o);if(s.recipient!=this.userId)throw new l.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+s.recipient);if(s.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new l.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:s.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});if(s.sender!=e.getSender())throw new l.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+s.sender,{reported_sender:e.getSender()});if(s.room_id!==e.getRoomId())throw new l.DecryptionError("OLM_BAD_ROOM","Message intended for room "+s.room_id,{reported_room:e.getRoomId()});return{clearEvent:s,senderCurve25519Key:n,claimedEd25519Key:(s.keys||{}).ed25519||null}}))}decryptMessage(e,t){return s(this,void 0,void 0,(function*(){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((()=>{})),yield 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,l.registerAlgorithm)(c.OLM_ALGORITHM,h,g)},{"../../logger":108,"../deviceinfo":84,"../olmlib":87,"./base":77}],81:[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={}))},{}],82:[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"),d=e("./store/indexeddb-crypto-store"),l=e("./recoverykey"),u=e("./aes"),h=e("../utils"),g=e("../NamespacedValue");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){return i(this,void 0,void 0,(function*(){const i=n.algorithmsByName[e.algorithm];if(!i)throw new Error("Unknown backup algorithm");return yield 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("crypto.keyBackupStatus",!0),this.scheduleKeyBackupSend()}))}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit("crypto.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,l.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=this.baseApis.crypto.sessionStore.getLocalTrustedBackupPubKey();"public_key"in e.auth_data&&e.auth_data.public_key===n&&(o.logger.info("Backup public key "+n+" is trusted locally"),t.trusted_locally=!0);const i=e.auth_data.signatures[this.baseApis.getUserId()]||[];for(const n of Object.keys(i)){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=yield 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,void 0);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("crypto.keyBackupFailed",e.data.errcode),e}n&&(yield(0,c.sleep)(1e3*Math.pow(2,Math.min(n-1,4)),void 0))}}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("crypto.keyBackupSessionsRemaining",n);const i={};for(const e of t){const t=e.sessionData.room_id;void 0===i[t]&&(i[t]={sessions:{}});const n=yield 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("crypto.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",[d.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,d.IndexedDBCryptoStore.STORE_BACKUP],(e=>{this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(e,(t=>{null!==t&&this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([t],e)}))}));const e=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return this.baseApis.emit("crypto.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 y=new g.UnstableValue(null,"org.matrix.msc3270.v1.aes-hmac-sha2");class m{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 m(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,h.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){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,yield(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=m,m.algorithmName=y.name,n.algorithmsByName={[f.algorithmName]:f,[m.algorithmName]:m},n.DefaultAlgorithm=f}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../NamespacedValue":62,"../client":66,"../logger":108,"../utils":141,"./aes":76,"./key_passphrase":86,"./olmlib":87,"./recoverykey":88,"./store/indexeddb-crypto-store":90}],83:[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=e("./olmlib"),a=e("../crypto/store/indexeddb-crypto-store"),c=e("./aes"),d=o(e("another-json")),l=e("../logger");n.DEHYDRATION_ALGORITHM="org.matrix.msc2697.v1.olm.libolm_pickle";const u=6048e5;n.DehydrationManager=class{constructor(e){this.crypto=e,this.inProgress=!1,this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){return r(this,void 0,void 0,(function*(){return yield this.crypto.cryptoStore.doTxn("readonly",[a.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:a,time:d}=e,l=i.from(this.crypto.olmDevice.pickleKey),h=yield(0,c.decryptAES)(r,l,n.DEHYDRATION_ALGORITHM);this.key=(0,s.decodeBase64)(h),this.keyInfo=o,this.deviceDisplayName=a;const g=Date.now(),p=Math.max(1,d+u-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",[a.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)l.logger.log("Dehydration already in progress -- not starting new dehydration");else{this.inProgress=!0,this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0);try{const e=i.from(this.crypto.olmDevice.pickleKey),r=yield(0,c.encryptAES)((0,s.encodeBase64)(this.key),e,n.DEHYDRATION_ALGORITHM);yield this.crypto.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",{keyInfo:this.keyInfo,key:r,deviceDisplayName:this.deviceDisplayName,time:Date.now()})})),l.logger.log("Attempting to dehydrate device"),l.logger.log("Creating account");const o=new t.Olm.Account;o.create();const h=JSON.parse(o.identity_keys()),g=o.max_number_of_one_time_keys();o.generate_one_time_keys(g/2),o.generate_fallback_key();const p=JSON.parse(o.one_time_keys()),f=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),l.logger.log("Uploading account to server");const v=(yield this.crypto.baseApis.http.authedRequest(void 0,"PUT","/dehydrated_device",void 0,{device_data:m,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;l.logger.log("Preparing device keys",v);const S={algorithms:this.crypto.supportedAlgorithms,device_id:v,user_id:this.crypto.userId,keys:{[`ed25519:${v}`]:h.ed25519,[`curve25519:${v}`]:h.curve25519}},E=o.sign(d.default.stringify(S));S.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:E}},this.crypto.crossSigningInfo.getId("self_signing")&&(yield this.crypto.crossSigningInfo.signObject(S,"self_signing")),l.logger.log("Preparing one-time keys");const b={};for(const[e,t]of Object.entries(p.curve25519)){const n={key:t},i=o.sign(d.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:i}},b[`signed_curve25519:${e}`]=n}l.logger.log("Preparing fallback keys");const _={};for(const[e,t]of Object.entries(f.curve25519)){const n={key:t,fallback:!0},i=o.sign(d.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:i}},_[`signed_curve25519:${e}`]=n}return l.logger.log("Uploading keys to server"),yield this.crypto.baseApis.http.authedRequest(void 0,"POST","/keys/upload/"+encodeURI(v),void 0,{device_keys:S,one_time_keys:b,"org.matrix.msc2732.fallback_keys":_}),l.logger.log("Done dehydrating"),this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),u),v}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":90,"../logger":108,"./aes":76,"./olmlib":87,"another-json":17,buffer:24}],84:[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}},{}],85:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.isCryptoAvailable=n.verificationMethods=void 0;const d=c(e("another-json")),l=e("events"),u=e("../ReEmitter"),h=e("../logger"),g=e("./OlmDevice"),p=s(e("./olmlib")),f=e("./DeviceList"),y=e("./deviceinfo"),m=s(e("./algorithms")),v=e("./CrossSigning"),S=e("./EncryptionSetup"),E=e("./SecretStorage"),b=e("./OutgoingRoomKeyRequestManager"),_=e("./store/indexeddb-crypto-store"),w=e("./verification/QRCode"),T=e("./verification/SAS"),I=e("./key_passphrase"),R=e("./recoverykey"),k=e("./verification/request/VerificationRequest"),C=e("./verification/request/InRoomChannel"),O=e("./verification/request/ToDeviceChannel"),D=e("./verification/IllegalMethod"),A=e("../errors"),P=e("./aes"),M=e("./dehydration"),x=e("./backup"),U=e("../models/event"),N=y.DeviceInfo.DeviceVerification,B={[w.ReciprocateQRCode.NAME]:w.ReciprocateQRCode,[T.SAS.NAME]:T.SAS,[w.SHOW_QR_CODE_METHOD]:D.IllegalMethod,[w.SCAN_QR_CODE_METHOD]:D.IllegalMethod};n.verificationMethods={RECIPROCATE_QR_CODE:w.ReciprocateQRCode.NAME,SAS:T.SAS.NAME},n.isCryptoAvailable=function(){return Boolean(t.Olm)};class K extends l.EventEmitter{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("crossSigning.keysChanged",{}),this.emit("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("userTrustStatusChanged",e,this.checkUserTrust(e))}})),this.onToDeviceEvent=e=>{try{h.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):"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("Event.decrypted",(e=>{this.onToDeviceEvent(e)})))}catch(e){h.logger.error("Error handling toDeviceEvent:",e)}},this.onTimelineEvent=(e,t,n,i,{liveEvent:r=!0}={})=>{if(!C.InRoomChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.inRoomVerificationRequests,(e=>{const t=new C.InRoomChannel(this.baseApis,e.getRoomId());return new k.VerificationRequest(t,this.verificationMethods,this.baseApis)}),r)},this.reEmitter=new u.ReEmitter(this),c){this.verificationMethods=new Map;for(const e of c)"string"==typeof e?B[e]&&this.verificationMethods.set(e,B[e]):e.NAME?this.verificationMethods.set(e.NAME,e):h.logger.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=B;this.backupManager=new x.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=L(t);if(e){const[t]=yield this.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",e,[t])}return p.decodeBase64(e||t)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return yield this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})))),this.olmDevice=new g.OlmDevice(o),this.deviceList=new f.DeviceList(e,o,this.olmDevice),this.deviceList.on("userCrossSigningUpdated",this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,["crypto.devicesUpdated","crypto.willUpdateDevices"]),this.supportedAlgorithms=Object.keys(m.DECRYPTION_CLASSES),this.outgoingRoomKeyRequestManager=new b.OutgoingRoomKeyRequestManager(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new O.ToDeviceRequests,this.inRoomVerificationRequests=new C.InRoomRequests;const d=this.baseApis.cryptoCallbacks||{},l=(0,v.createCryptoStoreCacheCallbacks)(o,this.olmDevice);this.crossSigningInfo=new v.CrossSigningInfo(n,d,l),this.secretStorage=new E.SecretStorage(e,d,e),this.dehydrationManager=new M.DehydrationManager(this),!d.getCrossSigningKey&&d.getSecretStorageKey&&(d.getCrossSigningKey=e=>a(this,void 0,void 0,(function*(){return v.CrossSigningInfo.getFromSecretStorage(e,this.secretStorage)})))}static getOlmVersion(){return g.OlmDevice.getOlmVersion()}init({exportedOlmDevice:e,pickleKey:n}={}){return a(this,void 0,void 0,(function*(){h.logger.log("Crypto: initialising Olm..."),yield t.Olm.init(),h.logger.log(e?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield this.olmDevice.init({fromExportedDevice:e,pickleKey:n}),h.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,h.logger.log("Crypto: fetching own devices...");let i=this.deviceList.getRawStoredDevicesForUser(this.userId);if(i||(i={}),!i[this.deviceId]){h.logger.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:N.VERIFIED,known:!0};i[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,i),this.deviceList.saveIfDirty()}yield this.cryptoStore.doTxn("readonly",[_.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(h.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),h.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("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,I.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,R.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*(){h.logger.log("Bootstrapping cross-signing");const n=this.baseApis.cryptoCallbacks,i=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,n),r=new v.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(),d=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),l=c||d;h.logger.log({setupNewCrossSigning:t,publicKeysOnDevice:s,privateKeysInCache:c,privateKeysInStorage:d,privateKeysExistSomewhere:l}),!l||t?(h.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield o()):s&&c?h.logger.log("Cross-signing public keys trusted and private keys found locally"):d&&(h.logger.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),yield this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const u=i.crossSigningCallbacks.privateKeys;if(u.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new E.SecretStorage(i.accountDataClientAdapter,i.ssssCryptoCallbacks);(yield e.hasKey())&&(h.logger.log("Storing new cross-signing private keys in secret storage"),yield v.CrossSigningInfo.storeInSecretStorage(u,e))}const g=i.buildOperation();yield g.apply(this),yield i.persist(this),h.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*(){h.logger.log("Bootstrapping Secure Secret Storage");const o=this.baseApis.cryptoCallbacks,s=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,o),c=new E.SecretStorage(s.accountDataClientAdapter,s.ssssCryptoCallbacks);let d=null;const l=(e,t)=>a(this,void 0,void 0,(function*(){e=e||{},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})),u=(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,P.calculateKeyCheck)(i);t.iv=r,t.mac=o,yield s.setAccountData(`m.secret_storage.key.${e}`,t)}}})),g=e=>a(this,void 0,void 0,(function*(){if(this.crossSigningInfo.getId()&&(yield this.crossSigningInfo.isStoredInKeyCache("master")))try{h.logger.log("Adding cross-signing signature to key backup"),yield this.crossSigningInfo.signObject(e,"master")}catch(e){h.logger.error("Signing key backup with cross-signing keys failed",e)}else h.logger.warn("Cross-signing keys not available, skipping signature on key backup")})),f=yield this.getSecretStorageKey(),[y,m]=f||[null,null],b=!i&&m&&m.algorithm===E.SECRET_STORAGE_ALGORITHM_V1_AES;if(h.logger.log({keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:i,storageExists:b,oldKeyInfo:m}),b||t)if(!b&&t){h.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}),d=yield l(n,e),yield c.store("m.megolm_backup.v1",p.encodeBase64(e),[d]),yield g(t.auth_data),s.addSessionBackup(t)}else h.logger.log("Secret storage exists"),m&&m.algorithm===E.SECRET_STORAGE_ALGORITHM_V1_AES&&(yield u(y,m));else{h.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:t,privateKey:n}=yield e();d=yield l(t,n)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield this.isCrossSigningReady())&&(d||!(yield this.crossSigningInfo.isStoredInSecretStorage(c)))){h.logger.log("Copying cross-signing private keys from cache to secret storage");const e=yield this.crossSigningInfo.getCrossSigningKeysFromCache();yield v.CrossSigningInfo.storeInSecretStorage(e,c)}if(n&&!t){h.logger.log("Creating new message key backup version");const e=yield this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=(0,R.decodeRecoveryKey)(e.recovery_key);yield c.store("m.megolm_backup.v1",p.encodeBase64(t));const n={algorithm:e.algorithm,auth_data:e.auth_data};yield g(n.auth_data),yield this.signObject(n.auth_data),s.addSessionBackup(n)}const _=yield c.get("m.megolm_backup.v1");if(_){h.logger.info("Got session backup key from secret storage: caching");const e=L(_);e&&(yield c.store("m.megolm_backup.v1",e,[d||y]));const t=new Uint8Array(p.decodeBase64(e||_));yield s.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=(yield this.getSessionBackupPrivateKey())||(yield r());if(!e)return void h.logger.error("Key backup is enabled but couldn't get key backup key!");h.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),yield c.store("m.megolm_backup.v1",p.encodeBase64(e))}const w=s.buildOperation();yield w.apply(this),yield s.persist(this),h.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,t){return this.secretStorage.isStored(e,t)}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",[_.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(p.decodeBase64(L(e)||e)),yield this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=i.from(this.olmDevice.pickleKey),n=yield(0,P.decryptAES)(e,t,"m.megolm_backup.v1");e=p.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,P.encryptAES)(p.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[_.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*(){h.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);h.logger.info(`Starting background key sig upload for ${this.deviceId}`);const n=({shouldEmit:e})=>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("crypto.keySignatureUploadFailure",i,"afterCrossSigningLocalKeyChange",n),new A.KeySignatureUploadError("Key upload failed",{failures:i});h.logger.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{h.logger.error(`Error during background key sig upload for ${this.deviceId}`,e)}));n({shouldEmit:!0});const i=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(i){h.logger.info("Starting device verification upgrade");const e={};for(const[t,n]of Object.entries(this.deviceList.crossSigningInfo)){const i=yield this.checkForDeviceVerificationUpgrade(t,v.CrossSigningInfo.fromStorage(n,t));i&&(e[t]=i)}if(Object.keys(e).length>0){h.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){h.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}h.logger.info("Finished device verification upgrade")}h.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=>y.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===N.VERIFIED)try{yield p.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 v.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 v.DeviceTrustLevel(!1,!1,n,!1)}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 h.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&&h.logger.info("Got new master public key",r),e&&(o||s)){h.logger.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("master",r))[1],h.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 d=a!==i.getId("self_signing"),l=c!==i.getId("user_signing"),u=i.getId("self_signing")&&!n.has("self_signing"),g=i.getId("user_signing")&&!n.has("user_signing"),p={};if(d&&h.logger.info("Got new self-signing key",i.getId("self_signing")),e&&(d||u)){h.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],h.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(l&&h.logger.info("Got new user-signing key",i.getId("user_signing")),e&&(l||g)){h.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],h.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})=>(h.logger.info(`Starting background key sig upload for ${f}`),this.baseApis.uploadKeySignatures({[this.userId]:p}).then((n=>{const{failures:i}=n||{};if(h.logger.info(`Finished background key sig upload for ${f}`),Object.keys(i||[]).length>0)throw t&&this.baseApis.emit("crypto.keySignatureUploadFailure",i,"checkOwnCrossSigningTrust",e),new A.KeySignatureUploadError("Key upload failed",{failures:i})})).catch((e=>{h.logger.error(`Error during background key sig upload for ${f}`,e)})));e({shouldEmit:!0})}this.emit("userTrustStatusChanged",t,this.checkUserTrust(t)),o&&(this.baseApis.emit("crossSigning.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",[_.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(h.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()))}}}h.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("RoomMember.membership",((e,t,n)=>{try{this.onRoomMembership(e,t,n)}catch(e){h.logger.error("Error handling membership change:",e)}})),e.on("toDeviceEvent",this.onToDeviceEvent),e.on("Room.timeline",this.onTimelineEvent),e.on("Event.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){h.logger.info("generating oneTimeKeys");const t=Math.min(n-e,5);yield this.olmDevice.generateOneTimeKeys(t)}this.getNeedsNewFallback()&&(h.logger.info("generating fallback key"),yield this.olmDevice.generateFallbackKey()),h.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=>{h.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=[],t={};if(this.getNeedsNewFallback()){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=yield this.baseApis.uploadKeysRequest({one_time_keys:i,"org.matrix.msc2732.fallback_keys":t});return yield this.olmDevice.markKeysAsPublished(),r}))}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("userTrustStatusChanged",this.userId,this.checkUserTrust(e))),e!==this.userId){h.logger.info("Master key "+o.getId()+" for "+e+" marked verified. Signing...");const n=yield this.crossSigningInfo.signUser(o);if(n){const i=({shouldEmit:r})=>a(this,void 0,void 0,(function*(){h.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("crypto.keySignatureUploadFailure",s,"setDeviceVerification",i),new A.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 d=c.verified;n?d=N.VERIFIED:null!==n&&d==N.VERIFIED&&(d=N.UNVERIFIED),i?d=N.BLOCKED:null!==i&&d==N.BLOCKED&&(d=N.UNVERIFIED);let l=c.known;if(null!==r&&(l=r),c.verified===d&&c.known===l||(c.verified=d,c.known=l,this.deviceList.storeDevicesForUser(e,s),this.deviceList.saveIfDirty()),n&&e===this.userId){let n;h.logger.info("Own device "+t+" marked verified: signing");if(this.checkDeviceTrust(e,t).isCrossSigningVerified()?h.logger.log(`Own device ${t} already cross-signing verified`):n=yield this.crossSigningInfo.signDevice(e,y.DeviceInfo.fromStorage(c,t)),n){const i=({shouldEmit:r})=>a(this,void 0,void 0,(function*(){h.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("crypto.keySignatureUploadFailure",s,"setDeviceVerification",i),new A.KeySignatureUploadError("Key upload failed",{failures:s})}));yield i({shouldEmit:!0})}}const u=y.DeviceInfo.fromStorage(c,t);return this.emit("deviceVerificationChanged",e,t,u),u}))}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 C.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 k.VerificationRequest(t,this.verificationMethods,this.baseApis);t.transactionId&&n.setRequestByChannel(t,e),yield e.sendRequest();const i=n.getRequestByChannel(t);return i?e=i:(h.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 k.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 k.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()?(h.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+" but sender device has key "+i.getFingerprint()),null):i:(h.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||(h.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),t.mismatchedSender=!0),t.sender&&n!==t.sender.getFingerprint()&&(h.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 h.logger.log("Ignoring setRoomEncryption with no algorithm");const i=this.roomList.getRoomEncryption(e);if(i&&JSON.stringify(i)!=JSON.stringify(t))return void h.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=m.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?h.logger.log("Enabling encryption in "+e):(h.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}`);h.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){const t={};for(let n=0;n<e.length;++n){const i=e[n];t[i]=[];const r=this.getStoredDevicesForUser(i)||[];for(let e=0;e<r.length;++e){const n=r[e];n.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(n.verified!=N.BLOCKED&&t[i].push(n))}}return p.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,t)}exportRoomKeys(){return a(this,void 0,void 0,(function*(){const e=[];return yield this.cryptoStore.doTxn("readonly",[_.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=p.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 h.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()}))})))}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 U.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(),n=this.getRoomDecryptor(e.getRoomId(),t.algorithm);return yield n.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=>{h.logger.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{h.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){h.logger.error("Error configuring encryption in room "+t+":",e)}}))}onSyncWillProcess(e){return a(this,void 0,void 0,(function*(){e.oldSyncToken||(h.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 h.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 h.logger.error("key withheld event is missing fields");h.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 k.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!=U.EventStatus.SENT){let t,n;try{yield new Promise(((i,r)=>{t=i,n=()=>{e.status==U.EventStatus.CANCELLED&&r(new Error("Event status set to CANCELLED."))},e.once("Event.localEventIdReplaced",t),e.on("Event.status",n)}))}catch(e){return void h.logger.error("error while waiting for the verification event to be sent: "+e.message)}finally{e.removeListener("Event.localEventIdReplaced",t),e.removeListener("Event.status",n)}}let r=t.getRequest(e),o=!1;if(!r){if(r=n(e),!r)return void h.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){h.logger.error("error while handling verification event: "+e.message)}o&&!r.initiatedByMe&&!r.invalid&&!r.observeOnly&&this.baseApis.emit("crypto.verification.request",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(p.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 h.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 h.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 p.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,c,!0),this.lastNewSessionForced[n][r]=Date.now();const d={algorithm:p.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};yield p.encryptMessageForDevice(d.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]:d}});const l=yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,a.deviceId);for(const e of l)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?(h.logger.log("Join event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&this.clientStore.getRoom(i).shouldEncryptForInvitedMembers()&&(h.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 j(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new F(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){h.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(h.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 h.logger.debug(`room key request for unencrypted room ${r}`);const e=this.roomEncryptors[r],o=this.deviceList.getStoredDevice(t,n);if(!o)return void h.logger.debug(`Ignoring keyshare for unknown device ${t}:${n}`);try{yield e.reshareKeyWithDevice(i.sender_key,i.session_id,t,o)}catch(e){h.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 h.logger.log("Ignoring room key request from ourselves");if(!this.roomDecryptors[r])return void h.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 h.logger.log("device is already verified: sharing keys"),void e.share();this.emit("crypto.roomKeyRequest",e)}else h.logger.log(`room key request for unknown session ${r} / `+i.session_id);else h.logger.log(`room key request for unknown alg ${o} in room ${r}`)}))}processReceivedRoomKeyRequestCancellation(e){return a(this,void 0,void 0,(function*(){h.logger.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit("crypto.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=m.DECRYPTION_CLASSES[t];if(!r)throw new m.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(d.default.stringify(e)),e.signatures=t,void 0!==n&&(e.unsigned=n)}))}}function L(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return p.encodeBase64(t)}n.Crypto=K,n.fixBackupKey=L;class j{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=j;class F{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":63,"../errors":101,"../logger":108,"../models/event":116,"./CrossSigning":69,"./DeviceList":70,"./EncryptionSetup":71,"./OlmDevice":72,"./OutgoingRoomKeyRequestManager":73,"./SecretStorage":75,"./aes":76,"./algorithms":78,"./backup":82,"./dehydration":83,"./deviceinfo":84,"./key_passphrase":86,"./olmlib":87,"./recoverykey":88,"./store/indexeddb-crypto-store":90,"./verification/IllegalMethod":95,"./verification/QRCode":96,"./verification/SAS":97,"./verification/request/InRoomChannel":98,"./verification/request/ToDeviceChannel":99,"./verification/request/VerificationRequest":100,"another-json":17,buffer:24,events:28}],86:[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.deriveKey=n.keyFromPassphrase=n.keyFromAuthData=void 0;const r=e("../randomstring"),o=5e5;function s(e,n,r,o=256){return i(this,void 0,void 0,(function*(){const i=t.crypto.subtle,s=t.TextEncoder;if(!i||!s)throw new Error("Password-based backup is not avaiable on this platform");const a=yield i.importKey("raw",(new s).encode(e),{name:"PBKDF2"},!1,["deriveBits"]),c=yield i.deriveBits({name:"PBKDF2",salt:(new s).encode(n),iterations:r,hash:"SHA-512"},a,o);return new Uint8Array(c)}))}n.keyFromAuthData=function(e,n){return i(this,void 0,void 0,(function*(){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 yield s(n,e.private_key_salt,e.private_key_iterations,e.private_key_bits||256)}))},n.keyFromPassphrase=function(e){return i(this,void 0,void 0,(function*(){if(!t.Olm)throw new Error("Olm is not available");const n=(0,r.randomString)(32);return{key:yield s(e,n,o,256),salt:n,iterations:o}}))},n.deriveKey=s}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../randomstring":127}],87:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.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 d=c(e("another-json")),l=e("../logger"),u=s(e("../utils"));var h;function g(e,t,n,i){return a(this,void 0,void 0,(function*(){const r=i.deviceId;try{yield p(e,t,n,r,i.getFingerprint())}catch(e){return l.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 l.logger.error("Error starting olm session with device "+n+":"+r+": "+e),null}return l.logger.log("Started new olm sessionid "+o+" for device "+n+":"+r),o}))}function p(e,t,n,i,r){return a(this,void 0,void 0,(function*(){const o="ed25519:"+i,s=((t.signatures||{})[n]||{})[o];if(!s)throw Error("No signature");const a=Object.assign({},t);"unsigned"in a&&delete a.unsigned,delete a.signatures;const c=d.default.stringify(a);e.verifySignature(r,c,s)}))}function f(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"}(h||(h={})),n.OLM_ALGORITHM=h.Olm,n.MEGOLM_ALGORITHM=h.Megolm,n.MEGOLM_BACKUP_ALGORITHM=h.MegolmBackup,n.encryptMessageForDevice=function(e,t,n,i,r,o,s){return a(this,void 0,void 0,(function*(){const a=o.getIdentityKey(),c=yield i.getSessionIdForDevice(a);if(null===c)return;l.logger.log("Using sessionid "+c+" for device "+r+":"+o.deviceId);const d={sender:t,sender_device:n,keys:{ed25519:i.deviceEd25519Key},recipient:r,recipient_keys:{ed25519:o.getFingerprint()}};u.extend(d,s),e[a]=yield i.encryptMessage(a,c,JSON.stringify(d))}))},n.getExistingOlmSessions=function(e,t,n){return a(this,void 0,void 0,(function*(){const t={},i={},r=[];for(const[o,s]of Object.entries(n))for(const n of s){const s=n.deviceId,c=n.getIdentityKey();r.push((()=>a(this,void 0,void 0,(function*(){const r=yield e.getSessionIdForDevice(c,!0);null===r?(t[o]=t[o]||[],t[o].push(n)):(i[o]=i[o]||{},i[o][s]={device:n,sessionId:r})})))())}return yield Promise.all(r),[t,i]}))},n.ensureOlmSessionsForDevices=function(e,t,n,i=!1,r,o,s=l.logger){return a(this,void 0,void 0,(function*(){"number"==typeof i&&(s=o,o=r,r=i,i=!1);const a=[],c={},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,r]of Object.entries(n)){c[t]={};for(const n of r){const r=n.deviceId,o=n.getIdentityKey();if(o===e.deviceCurve25519Key){s.info("Attempted to start session with ourself! Ignoring"),c[t][r]={device:n,sessionId:null};continue}const l=`for ${o} (${t}:${r})`,u=yield e.getSessionIdForDevice(o,!!d[o],s);null!==u&&d[o]&&d[o](),(null===u||i)&&(i?s.info(`Forcing new Olm session ${l}`):s.info(`Making new Olm session ${l}`),a.push([t,r])),c[t][r]={device:n,sessionId:u}}}if(0===a.length)return c;const l="signed_curve25519";let u,h=`one-time keys for ${a.length} devices`;try{s.debug(`Claiming ${h}`),u=yield t.claimOneTimeKeys(a,l,r),s.debug(`Claimed ${h}`)}catch(e){for(const e of Object.values(d))e();throw s.log(`Failed to claim ${h}`,e,a),e}o&&"failures"in u&&o.push(...Object.keys(u.failures));const p=u.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 a=r[o],l=a.deviceId,u=a.getIdentityKey();if(u===e.deviceCurve25519Key)continue;if(c[t][l].sessionId&&!i)continue;const h=n[l]||{};let p=null;for(const e in h)0===e.indexOf("signed_curve25519:")&&(p=h[e]);p?f.push(g(e,p,t,a).then((e=>{d[u]&&d[u](e),c[t][l].sessionId=e}),(e=>{throw d[u]&&d[u](),e}))):(s.warn(`No one-time keys (alg=signed_curve25519) for device ${t}:${l}`),d[u]&&d[u]())}}return h=`Olm sessions for ${f.length} devices`,s.debug(`Starting ${h}`),yield Promise.all(f),s.debug(`Started ${h}`),c}))},n.verifySignature=p,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 s=e.signatures||{};delete e.signatures;const a=e.unsigned;e.unsigned&&delete e.unsigned;try{const t=s[i]||{};return s[i]=t,t["ed25519:"+r]=n.sign(d.default.stringify(e))}finally{e.signatures=s,a&&(e.unsigned=a),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],s=new t.Olm.Utility,a=e.signatures;delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{s.ed25519_verify(n,d.default.stringify(e),o)}finally{e.signatures=a,c&&(e.unsigned=c),s.free()}},n.encodeBase64=f,n.encodeUnpaddedBase64=function(e){return f(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":108,"../utils":141,"another-json":17,buffer:24}],88:[function(e,t,n){(function(t,i){(function(){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.decodeRecoveryKey=n.encodeRecoveryKey=void 0;const o=r(e("bs58")),s=[139,1];n.encodeRecoveryKey=function(e){const t=new i(s.length+e.length+1);t.set(s,0),t.set(e,s.length);let n=0;for(let e=0;e<t.length-1;++e)n^=t[e];return t[t.length-1]=n,o.default.encode(t).match(/.{1,4}/g).join(" ")},n.decodeRecoveryKey=function(e){const n=o.default.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<s.length;++e)if(n[e]!==s[e])throw new Error("Incorrect prefix");if(n.length!==s.length+t.Olm.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");return Uint8Array.from(n.slice(s.length,s.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:23,buffer:24}],89:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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 d(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function l(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(r){const o=r.target.result;if(o)return void(t=o.value);if(n++,n>=e.length)return;const s=e[n];r.target.source.openCursor(s).onsuccess=i},l(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(s){const a=s.target.result;if(a){const n=a.value;n.recipients.includes({userId:e,deviceId:t})&&r.push(n),a.continue()}else{if(i++,i>=n.length)return;const e=n[i];s.target.source.openCursor(e).onsuccess=o}},l(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(e){const r=e.target.result;if(!r)return;const o=r.value;o.state==t?(Object.assign(o,n),r.update(o),i=o):a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${o.state}`)},l(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})`)},l(n)}getAccount(e,t){const n=e.objectStore("account").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){d(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){d(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){d(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){d(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){d(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){d(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){d(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()}),l(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 l(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){d(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){d(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){d(e,t)}i.continue()}else try{t(null)}catch(t){d(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)):d(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){d(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){d(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=l(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":108,"../../utils":141}],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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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"),d=o(e("./indexeddb-crypto-store-backend")),l=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,d.VERSION);n.onupgradeneeded=e=>{const t=n.result,i=e.oldVersion;d.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 d.Backend(t))}})).then((e=>e.doTxn("readonly",[h.STORE_INBOUND_GROUP_SESSIONS,h.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(t=>{e.getEndToEndInboundGroupSession("","",t,(()=>{}))})).then((()=>e)))).catch((e=>{if("VersionError"===e.name)throw s.logger.warn("Crypto DB is too new for us to use!",e),new l.InvalidCryptoStoreError(l.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":101,"../../indexeddb-helpers":106,"../../logger":108,"./indexeddb-crypto-store-backend":89,"./localStorage-crypto-store":91,"./memory-crypto-store":92}],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.LocalStorageCryptoStore=void 0;const r=e("../../logger"),o=e("./memory-crypto-store"),s="crypto.",a="crypto.account",c="crypto.cross_signing_keys",d="crypto.notified_error_devices",l="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 y(e,t){return"crypto.inboundgroupsessions.withheld/"+e+"/"+t}function m(e){return"crypto.rooms/"+e}class v 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=S(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,E(this.store,g(e),r)}storeEndToEndSessionProblem(e,t,n){return i(this,void 0,void 0,(function*(){const i=p(e),r=S(this.store,i)||[];r.push({type:t,fixed:n,time:Date.now()}),r.sort(((e,t)=>e.time-t.time)),E(this.store,i,r)}))}getEndToEndSessionProblem(e,t){return i(this,void 0,void 0,(function*(){const n=p(e),i=S(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=S(this.store,d)||{},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 E(this.store,d,t),n}))}getEndToEndInboundGroupSession(e,t,n,i){i(S(this.store,f(e,t)),S(this.store,y(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.substr(u.length,43),sessionId:n.substr(u.length+44),sessionData:S(this.store,n)})}t(null)}addEndToEndInboundGroupSession(e,t,n,i){S(this.store,f(e,t))||this.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){E(this.store,f(e,t),n)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){E(this.store,y(e,t),n)}getEndToEndDeviceData(e,t){t(S(this.store,l))}storeEndToEndDeviceData(e,t){E(this.store,l,e)}storeEndToEndRoom(e,t,n){E(this.store,m(e),t)}getEndToEndRooms(e,t){const n={},i=m("");for(let e=0;e<this.store.length;++e){const t=this.store.key(e);if(t.startsWith(i)){n[t.substr(i.length)]=S(this.store,t)}}t(n)}getSessionsNeedingBackup(e){const t=S(this.store,h)||{},n=[];for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const t=i.substr(0,43),r=i.substr(44);if(this.getEndToEndInboundGroupSession(t,r,null,(e=>{n.push({senderKey:t,sessionId:r,sessionData:e})})),e&&i.length>=e)break}return Promise.resolve(n)}countSessionsNeedingBackup(){const e=S(this.store,h)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=S(this.store,h)||{};for(const n of e)delete t[n.senderKey+"/"+n.sessionId];return E(this.store,h,t),Promise.resolve()}markSessionsNeedingBackup(e){const t=S(this.store,h)||{};for(const n of e)t[n.senderKey+"/"+n.sessionId]=!0;return E(this.store,h,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(a),Promise.resolve()}getAccount(e,t){t(S(this.store,a))}storeAccount(e,t){E(this.store,a,t)}getCrossSigningKeys(e,t){t(S(this.store,c))}getSecretStorePrivateKey(e,t,n){t(S(this.store,`crypto.ssss_cache.${n}`))}storeCrossSigningKeys(e,t){E(this.store,c,t)}storeSecretStorePrivateKey(e,t,n){E(this.store,`crypto.ssss_cache.${t}`,n)}doTxn(e,t,n){return Promise.resolve(n(null))}}function S(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 E(e,t,n){e.setItem(t,JSON.stringify(n))}n.LocalStorageCryptoStore=v},{"../../logger":108,"./memory-crypto-store":92}],92:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.substr(0,43),sessionId:e.substr(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.substr(0,43),sessionId:n.substr(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":108,"../../utils":141}],93:[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.SwitchStartEventError=void 0;const r=e("../../models/event"),o=e("events"),s=e("../../logger"),a=e("../deviceinfo"),c=e("./Error"),d=e("../CrossSigning"),l=new Error("Verification timed out");class u extends Error{constructor(e){super(),this.startEvent=e}}n.SwitchStartEventError=u;class h extends o.EventEmitter{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(){s.logger.info("Refreshing/starting the verification transaction timeout timer"),null!==this.transactionTimeoutTimer&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout((()=>{this._done||this.cancelled||(s.logger.info("Triggering verification timeout"),this.cancel(l))}),6e5)}endTimer(){null!==this.transactionTimeoutTimer&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));const t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise(((e,t)=>{this.resolveEvent=e,this.rejectEvent=t})))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(s.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const t=this.rejectEvent;this.rejectEvent=void 0,t(new 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,d.requestKeysDuringVerification)(this.baseApis,this.userId,this.deviceId)}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===l){const e=(0,c.newTimeoutError)();this.send(e.getType(),e.getContent())}else if(e instanceof r.MatrixEvent){if(e.getSender()!==this.userId){const t=e.getContent();"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("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,o]of Object.entries(t)){const t=r.split(":",2)[1],c=this.baseApis.getStoredDevice(e,t);if(c)n(r,c,o),i.push(t);else{const c=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);c&&c.getId()===t?(n(r,a.DeviceInfo.fromStorage({keys:{[r]:t}},t),o),i.push(t)):s.logger.warn(`verification: Could not find device ${t} to verify`)}}if(!i.length)throw new Error("No devices could be verified");s.logger.info("Verification completed! Marking devices verified: ",i);for(const t of i)yield this.baseApis.setDeviceVerified(e,t)}))}get events(){}}n.VerificationBase=h},{"../../logger":108,"../../models/event":116,"../CrossSigning":69,"../deviceinfo":84,"./Error":94,events:28}],94:[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":116}],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.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":93}],96:[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.SCAN_QR_CODE_METHOD=n.SHOW_QR_CODE_METHOD=void 0;const o=e("./Base"),s=e("./Error"),a=e("../olmlib"),c=e("../../logger");n.SHOW_QR_CODE_METHOD="m.qr_code.show.v1",n.SCAN_QR_CODE_METHOD="m.qr_code.scan.v1";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("show_reciprocate_qr",this.reciprocateQREvent)}));const t={};switch(e.mode){case l.VerifyOtherUser:{const n=e.otherUserMasterKey;t[`ed25519:${n}`]=n;break}case l.VerifySelfTrusted:{const n=this.request.targetDevice.deviceId;t[`ed25519:${n}`]=e.otherDeviceKey;break}case l.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 l;!function(e){e[e.VerifyOtherUser=0]="VerifyOtherUser",e[e.VerifySelfTrusted=1]="VerifySelfTrusted",e[e.VerifySelfUntrusted=2]="VerifySelfUntrusted"}(l||(l={}));class u{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=u.generateSharedSecret(),i=u.determineMode(e,t);let r=null,o=null,s=null;if(i===l.VerifyOtherUser){r=t.getStoredCrossSigningForUser(e.otherUserId).getId("master")}else if(i===l.VerifySelfTrusted)o=yield u.getOtherDeviceKey(e,t);else if(i===l.VerifySelfUntrusted){const e=t.getUserId();s=t.getStoredCrossSigningForUser(e).getId("master")}const a=u.generateQrData(e,t,i,n,r,o,s),c=u.generateBuffer(a);return new u(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=l.VerifyOtherUser;if(n===i){r=t.checkUserTrust(n).isCrossSigningVerified()?l.VerifySelfTrusted:l.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},d=t.getStoredCrossSigningForUser(a);return n===l.VerifyOtherUser?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=r):n===l.VerifySelfTrusted?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=o):n===l.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=u}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../../logger":108,"../olmlib":87,"./Base":93,"./Error":94,buffer:24}],97:[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=void 0;const o=e("./Base"),s=r(e("another-json")),a=e("./Error"),c=e("../../logger"),d="m.key.verification.start",l=["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 y(e,t){const n={};for(const i of t)i in f&&(n[i]=f[i](e));return n}const m={"hkdf-hmac-sha256":"calculate_mac","hmac-sha256":"calculate_mac_long_kdf"};function v(e,t){return function(...n){const i=e[m[t]].apply(e,n);return c.logger.log("SAS calculateMAC:",t,n,i),i}}const S={"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)}},E=["curve25519-hkdf-sha256","curve25519"],b=["sha256"],_=["hkdf-hmac-sha256","hmac-sha256"],w=Object.keys(f),T=new Set(E),I=new Set(b),R=new Set(_),k=new Set(w);function C(e,t){return e instanceof Array?e.filter((e=>t.has(e))):[]}class O extends o.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 o.SwitchStartEventError))throw t;this.startEvent=t.startEvent,e=!0}}while(e)}))}static get NAME(){return"m.sas.v1"}get events(){return l}canSwitchStartEvent(e){if(e.getType()!==d)return!1;const t=e.getContent();return t&&t.method===O.NAME&&this.waitingForAccept}sendStart(){return i(this,void 0,void 0,(function*(){const e=this.channel.completeContent(d,{method:O.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:E,hashes:b,message_authentication_codes:_,short_authentication_string:w});return yield this.channel.sendCompleted(d,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 o.SwitchStartEventError(this.startEvent);try{n=yield this.waitForEvent("m.key.verification.accept")}finally{this.waitingForAccept=!1}let r=n.getContent();const c=C(r.short_authentication_string,k);if(!(T.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 d=r.key_agreement_protocol,l=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+s.default.stringify(e);if(u.sha256(t)!==p)throw g();this.theirSASPubKey=r.key,f.set_their_key(r.key);const o=S[d](this,f,6),m=new Promise(((e,t)=>{this.sasEvent={sas:y(o,c),confirm:()=>i(this,void 0,void 0,(function*(){try{yield this.sendMAC(f,l),e()}catch(e){t(e)}})),cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit("show_sas",this.sasEvent)}));[n]=yield Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),m]),r=n.getContent(),yield this.checkMAC(f,r,l)}finally{f.free()}}))}doRespondVerification(){return i(this,void 0,void 0,(function*(){let e=this.channel.completedContentFromEvent(this.startEvent);const n=C(E,new Set(e.key_agreement_protocols))[0],r=C(b,new Set(e.hashes))[0],o=C(_,new Set(e.message_authentication_codes))[0],c=C(e.short_authentication_string,k);if(void 0===n||void 0===r||void 0===o||!c.length)throw(0,a.newUnknownMethodError)();const d=new t.Olm.SAS;try{const t=d.get_pubkey()+s.default.stringify(e);yield this.send("m.key.verification.accept",{key_agreement_protocol:n,hash:r,message_authentication_code:o,short_authentication_string:c,commitment:u.sha256(t)});let l=yield this.waitForEvent("m.key.verification.key");e=l.getContent(),this.theirSASPubKey=e.key,d.set_their_key(e.key),this.ourSASPubKey=d.get_pubkey(),yield this.send("m.key.verification.key",{key:this.ourSASPubKey});const g=S[n](this,d,6),p=new Promise(((e,t)=>{this.sasEvent={sas:y(g,c),confirm:()=>i(this,void 0,void 0,(function*(){try{yield this.sendMAC(d,o),e()}catch(e){t(e)}})),cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit("show_sas",this.sasEvent)}));[l]=yield Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),p]),e=l.getContent(),yield this.checkMAC(d,e,o)}finally{d.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]=v(e,t)(this.baseApis.getDeviceEd25519Key(),r+o),i.push(o);const s=this.baseApis.getCrossSigningId();if(s){const o=`ed25519:${s}`;n[o]=v(e,t)(s,r+o),i.push(o)}const a=v(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!==v(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!==v(e,n)(r.keys[t],i+t))throw(0,a.newKeyMismatchError)()}))}))}}n.SAS=O}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../logger":108,"./Base":93,"./Error":94,"another-json":17}],98:[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 d{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(d.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 d.canCreateRequest(e)}static getTransactionId(e){if(d.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=d.getTransactionId(e);if("string"!=typeof n||0===n.length)return!1;const i=d.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(!d.getOtherPartyUserId(e,t))return o.logger.log(`InRoomChannel: validateEvent: not directed to or sent by me: ${e.getSender()}, ${s&&s.to}`),!1}return r.VerificationRequest.validateEvent(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){return i(this,void 0,void 0,(function*(){if(t.hasEventId(e.getId()))return;const i=d.getEventType(e);if(e.getRoomId()!==this.roomId)return;if(null===this.userId){const t=d.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=d.getTransactionId(e));const a=!!e.getUnsigned().transaction_id,c=e.getSender()===this.client.getUserId();return yield 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=d;n.InRoomRequests=class{constructor(){this.requestsByRoomId=new Map}getRequest(e){const t=e.getRoomId(),n=d.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(),d.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(d.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":59,"../../../logger":108,"./VerificationRequest":100}],99:[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 d{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 d.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=d.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=d;n.ToDeviceRequests=class{constructor(){this.requestsByUserId=new Map}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){const n=this.requestsByUserId.get(e);if(n)return n.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,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(d.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":108,"../../../models/event":116,"../../../randomstring":127,"../Error":94,"./VerificationRequest":100}],100:[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.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("events"),s=e("../Error"),a=e("../QRCode");var c;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;class d extends o.EventEmitter{constructor(e,t,i){super(),this.channel=e,this.verificationMethods=t,this.client=i,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=()=>{try{this.initiatedByMe?this.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):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,s.newUnknownMethodError)();if(this._verifier=this.createVerifier(e,null,t),!this._verifier)throw(0,s.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("change"),this._verifier)return this._verifier.cancel((0,s.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("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("change",i),r};i()||this.on("change",i)}))}setPhase(e,t=!0){this._phase=e,t&&this.emit("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,s,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&&!s&&(yield this.cancelOnError(e,t)))return;if(c?this.eventsByUs.has(e):this.eventsByThem.has(e))return;const l=this.phase;this.addEvent(e,t,c);const u=this.applyPhaseTransitions();try{if(this._verifier&&!this.observeOnly){const i=this.isWinningStartRace(t);this._verifier.canSwitchStartEvent(t)&&i?this._verifier.switchStartEvent(t):s||(e===n.CANCEL_TYPE||(null===(d=this._verifier.events)||void 0===d?void 0:d.includes(e)))&&this._verifier.handleEvent(t)}if(u.length){if(o&&u.some((e=>e.phase===n.PHASE_READY))){this.otherPartySupportsMethod(a.SCAN_QR_CODE_METHOD,!0)&&(this._qrCodeData=yield a.QRCodeData.create(this,this.client))}const e=u[u.length-1],{phase:t}=e;this.setupTimeout(t),this.setPhase(t)}else this._observeOnly!==i&&this.emit("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:${s}, phase:${l}=>${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,s.errorFromEvent)((0,s.newUnknownMethodError)())),!0}const i=e===n.REQUEST_TYPE&&this.phase!==n.PHASE_UNSENT,o=e===n.READY_TYPE&&this.phase!==n.PHASE_REQUESTED;if(this.phase!==n.PHASE_UNSENT&&(i||o)){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,s.errorFromEvent)((0,s.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":108,"../Error":94,"../QRCode":96,events:28}],101:[function(e,t,n){"use strict";var i=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.InvalidCryptoStoreError=u,n.InvalidStoreError=l,n.KeySignatureUploadError=void 0;var r=i(e("@babel/runtime/helpers/classCallCheck")),o=i(e("@babel/runtime/helpers/inherits")),s=i(e("@babel/runtime/helpers/possibleConstructorReturn")),a=i(e("@babel/runtime/helpers/getPrototypeOf")),c=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,a.default)(e);if(t){var r=(0,a.default)(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return(0,s.default)(this,n)}}function l(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 u(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}l.TOGGLED_LAZY_LOADING="TOGGLED_LAZY_LOADING",l.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(l,Error),u.TOO_NEW="TOO_NEW",u.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(u,Error);var h=function(e){(0,o.default)(n,e);var t=d(n);function n(e,i){var o;return(0,r.default)(this,n),(o=t.call(this,e)).value=i,o}return n}((0,c.default)(Error));n.KeySignatureUploadError=h},{"@babel/runtime/helpers/classCallCheck":3,"@babel/runtime/helpers/getPrototypeOf":7,"@babel/runtime/helpers/inherits":8,"@babel/runtime/helpers/interopRequireDefault":9,"@babel/runtime/helpers/possibleConstructorReturn":12,"@babel/runtime/helpers/wrapNativeSuper":15}],102:[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){const n=Boolean(t.preventReEmit),r=!1!==t.decrypt;return function(t){const o=new i.MatrixEvent(t);return o.isEncrypted()&&(n||e.reEmitter.reEmit(o,["Event.decrypted"]),r&&e.decryptEventIfNeeded(o)),n||e.reEmitter.reEmit(o,["Event.replaced"]),o}}},{"./models/event":116}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FilterComponent=void 0;n.FilterComponent=class{constructor(e){this.filterJson=e}check(e){return this.checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url)}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}}checkFields(e,t,n,i){const r={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.substr(0,n.length)===n}return e===t}(n,e)}};for(let e=0;e<Object.keys(r).length;e++){const t=Object.keys(r)[e],n=r[t],i="not_"+t,o=this.filterJson[i];if(null==o?void 0:o.some(n))return!1;const s=this.filterJson[t];if(s&&!s.some(n))return!1}const o=this.filterJson.contains_url;return void 0===o||o===i}filter(e){return e.filter(this.check,this)}limit(){return void 0!==this.filterJson.limit?this.filterJson.limit:10}}},{}],104:[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.roomTimelineFilter=new i.FilterComponent((null==t?void 0:t.timeline)||{})}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":103}],105:[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}),n.MatrixError=n.ConnectionError=n.AbortError=void 0,n.MatrixHttpApi=T,n.PREFIX_UNSTABLE=n.PREFIX_R0=n.PREFIX_MEDIA_R0=n.PREFIX_IDENTITY_V2=n.PREFIX_IDENTITY_V1=void 0,n.retryNetworkOperation=function(e,t){return O.apply(this,arguments)};var o=i(e("@babel/runtime/regenerator")),s=i(e("@babel/runtime/helpers/asyncToGenerator")),a=i(e("@babel/runtime/helpers/createClass")),c=i(e("@babel/runtime/helpers/classCallCheck")),d=i(e("@babel/runtime/helpers/inherits")),l=i(e("@babel/runtime/helpers/possibleConstructorReturn")),u=i(e("@babel/runtime/helpers/getPrototypeOf")),h=i(e("@babel/runtime/helpers/wrapNativeSuper")),g=i(e("@babel/runtime/helpers/defineProperty")),p=i(e("@babel/runtime/helpers/typeof")),f=e("content-type"),y=E(e("./utils")),m=e("./logger"),v=E(e("./realtime-callbacks"));function S(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(S=function(e){return e?n:t})(e)}function E(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!==r(e)&&"function"!=typeof e)return{default:e};var n=S(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]}return i.default=e,n&&n.set(e,i),i}function b(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=(0,u.default)(e);if(t){var r=(0,u.default)(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return(0,l.default)(this,n)}}function _(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 w(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_(Object(n),!0).forEach((function(t){(0,g.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}n.PREFIX_R0="/_matrix/client/r0";n.PREFIX_UNSTABLE="/_matrix/client/unstable";n.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1";n.PREFIX_IDENTITY_V2="/_matrix/identity/v2";function T(e,t){y.checkObjectHasKeys(t,["baseUrl","request","prefix"]),t.onlyData=t.onlyData||!1,this.event_emitter=e,this.opts=t,this.useAuthorizationHeader=Boolean(t.useAuthorizationHeader),this.uploads=[]}n.PREFIX_MEDIA_R0="/_matrix/media/r0",T.prototype={setIdBaseUrl:function(e){this.opts.idBaseUrl=e},getContentUri:function(){var e={access_token:this.opts.accessToken};return{base:this.opts.baseUrl,path:"/_matrix/media/r0/upload",params:e}},uploadContent:function(e,n){y.isFunction(n)?n={callback:n}:void 0===n&&(n={});var i=!1!==n.includeFilename,r=n.type||e.type||"application/octet-stream",o=n.name||e.name,s=e;s.stream&&"function"!=typeof s.stream&&(m.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=s.stream);var a=n.rawResponse;void 0===a&&(t.XMLHttpRequest?a=!1:(m.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."),a=!0));var c=n.onlyContentUri;a||void 0!==c||(t.XMLHttpRequest?(m.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."),c=!0):c=!1);var d,l={loaded:0,total:0},u=null;if(a||(u=function(e){var t=JSON.parse(e);if(c&&void 0===(t=t.content_uri))throw Error("Bad response");return t}),t.XMLHttpRequest){var h=y.defer(),g=new t.XMLHttpRequest;l.xhr=g;var p=I(h,n.callback,this.opts.onlyData),f=function(){g.abort(),p(new Error("Timeout"))};g.timeout_timer=v.setTimeout(f,3e4),g.onreadystatechange=function(){var e;if(g.readyState===t.XMLHttpRequest.DONE){v.clearTimeout(g.timeout_timer);try{if(0===g.status)throw new C;if(!g.responseText)throw new Error("No response body.");e=g.responseText,u&&(e=u(e))}catch(e){return e.http_status=g.status,void p(e)}p(void 0,g,e)}},g.upload.addEventListener("progress",(function(e){v.clearTimeout(g.timeout_timer),l.loaded=e.loaded,l.total=e.total,g.timeout_timer=v.setTimeout(f,3e4),n.progressHandler&&n.progressHandler({loaded:e.loaded,total:e.total})}));var S=this.opts.baseUrl+"/_matrix/media/r0/upload",E=[];i&&o&&E.push("filename="+encodeURIComponent(o)),this.useAuthorizationHeader||E.push("access_token="+encodeURIComponent(this.opts.accessToken)),E.length>0&&(S+="?"+E.join("&")),g.open("POST",S),this.useAuthorizationHeader&&g.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),g.setRequestHeader("Content-Type",r),g.send(s),(d=h.promise).abort=g.abort.bind(g)}else{var b={};i&&o&&(b.filename=o),d=this.authedRequest(n.callback,"POST","/upload",b,s,{prefix:"/_matrix/media/r0",headers:{"Content-Type":r},json:!1,bodyParser:u})}var _=this,w=d.finally((function(){for(var e=0;e<_.uploads.length;++e)if(_.uploads[e]===l)return void _.uploads.splice(e,1)}));return w.abort=d.abort,l.promise=w,this.uploads.push(l),w},cancelUpload:function(e){return!!e.abort&&(e.abort(),!0)},getCurrentUploads:function(){return this.uploads},idServerRequest:function(e,t,n,i,r,o){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");var s=this.opts.idBaseUrl+r+n;if(void 0!==e&&!y.isFunction(e))throw Error("Expected callback to be a function but got "+(0,p.default)(e));var a={uri:s,method:t,withCredentials:!1,json:!0,_matrix_opts:this.opts,headers:{}};"GET"===t?a.qs=i:"object"===(0,p.default)(i)&&(a.json=i),o&&(a.headers.Authorization="Bearer ".concat(o));var c=y.defer();return this.opts.request(a,I(c,e,this.opts.onlyData)),c.promise},authedRequest:function(e,t,n,i,r,o){i||(i={}),this.useAuthorizationHeader?(isFinite(o)&&(o={localTimeoutMs:o}),o||(o={}),o.headers||(o.headers={}),o.headers.Authorization||(o.headers.Authorization="Bearer "+this.opts.accessToken),i.access_token&&delete i.access_token):i.access_token||(i.access_token=this.opts.accessToken);var s=this.request(e,t,n,i,r,o),a=this;return s.catch((function(e){"M_UNKNOWN_TOKEN"==e.errcode?a.event_emitter.emit("Session.logged_out",e):"M_CONSENT_NOT_GIVEN"==e.errcode&&a.event_emitter.emit("no_consent",e.message,e.data.consent_uri)})),s},request:function(e,t,n,i,r,o){var s=void 0!==(o=o||{}).prefix?o.prefix:this.opts.prefix,a=this.opts.baseUrl+s+n;return this.requestOtherUrl(e,t,a,i,r,o)},requestOtherUrl:function(e,t,n,i,r,o){return null==o?o={}:isFinite(o)&&(o={localTimeoutMs:o}),this._request(e,t,n,i,r,o)},getUrl:function(e,t,n){var i="";return t&&(i="?"+y.encodeParams(t)),this.opts.baseUrl+n+e+i},_request:function(e,t,n,i,r,o){if(void 0!==e&&!y.isFunction(e))throw Error("Expected callback to be a function but got "+(0,p.default)(e));o=o||{};var s=this;this.opts.extraParams&&(i=w(w({},i),this.opts.extraParams));var a=y.extend({},o.headers||{}),c=void 0===o.json||o.json,d=o.bodyParser;c&&(r&&(r=JSON.stringify(r),a["content-type"]="application/json"),a.accept||(a.accept="application/json"),void 0===d&&(d=function(e){return JSON.parse(e)}));var l,u,h=y.defer(),g=!1,f=o.localTimeoutMs||this.opts.localTimeoutMs,m=function(){f&&(l&&v.clearTimeout(l),l=v.setTimeout((function(){g=!0,u&&u.abort&&u.abort(),h.reject(new R({error:"Locally timed out waiting for a response",errcode:"ORG.MATRIX.JSSDK_TIMEOUT",timeout:f}))}),f))};m();var S=h.promise;try{(u=this.opts.request({uri:n,method:t,withCredentials:!1,qs:i,qsStringifyOptions:o.qsStringifyOptions,useQuerystring:!0,body:r,json:!1,timeout:f,headers:a||{},_matrix_opts:this.opts},(function(t,n,i){f&&(v.clearTimeout(l),g)||I(h,e,s.opts.onlyData,d)(t,n,i)})))&&("onprogress"in u&&(u.onprogress=function(e){m()}),u.abort&&(S.abort=u.abort.bind(u)))}catch(t){h.reject(t),e&&e(t)}return S}};var I=function(e,t,n,i){return t=t||function(){},function(r,o,s){r&&("AbortError"===r.name||"aborted"===r||r instanceof R||(r=new k("request failed",r)));if(!r)try{(o.status||o.statusCode)>=400?r=function(e,t){var n,i=e.status||e.statusCode,r=function(e){var t;e.getResponseHeader?t=e.getResponseHeader("Content-Type"):e.headers&&(t=e.headers["content-type"]||null);if(!t)return null;try{return(0,f.parse)(t)}catch(e){throw new Error("Error parsing Content-Type '".concat(t,"': ").concat(e))}}(e);if(r)if("application/json"===r.type){var o="object"===(0,p.default)(t)?t:JSON.parse(t);n=new R(o)}else"text/plain"===r.type&&(n=new Error("Server returned ".concat(i," error: ").concat(t)));n||(n=new Error("Server returned ".concat(i," error")));return n.httpStatus=i,n}(o,s):i&&(s=i(s))}catch(e){r=new Error("Error parsing server response: ".concat(e))}if(r)e.reject(r),t(r);else{var a={code:o.status||o.statusCode,headers:o.headers,data:s};e.resolve(n?s:a),t(null,n?s:a)}}};var R=function(e){(0,d.default)(n,e);var t=b(n);function n(e){var i;return(0,c.default)(this,n),e=e||{},(i=t.call(this,"MatrixError: ".concat(e.errcode))).errcode=e.errcode,i.name=e.errcode||"Unknown error code",i.message=e.error||"Unknown message",i.data=e,i}return n}((0,h.default)(Error));n.MatrixError=R;var k=function(e){(0,d.default)(n,e);var t=b(n);function n(e){var i,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;return(0,c.default)(this,n),(i=t.call(this,e+(r?": ".concat(r.message):"")))._cause=r,i}return(0,a.default)(n,[{key:"name",get:function(){return"ConnectionError"}},{key:"cause",get:function(){return this._cause}}]),n}((0,h.default)(Error));n.ConnectionError=k;var C=function(e){(0,d.default)(n,e);var t=b(n);function n(){return(0,c.default)(this,n),t.call(this,"Operation aborted")}return(0,a.default)(n,[{key:"name",get:function(){return"AbortError"}}]),n}((0,h.default)(Error));function O(){return(O=(0,s.default)(o.default.mark((function e(t,n){var i,r;return o.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=0,r=null;case 2:if(!(i<t)){e.next=21;break}if(e.prev=3,!(i>0)){e.next=6;break}return e.delegateYield(o.default.mark((function e(){var t;return o.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=1e3*Math.pow(2,i),m.logger.log("network operation failed ".concat(i," times,")+" retrying in ".concat(t,"ms...")),e.next=4,new Promise((function(e){return setTimeout(e,t)}));case 4:case"end":return e.stop()}}),e)}))(),"t0",6);case 6:return e.next=8,n();case 8:return e.abrupt("return",e.sent);case 11:if(e.prev=11,e.t1=e.catch(3),!(e.t1 instanceof k)){e.next=18;break}i+=1,r=e.t1,e.next=19;break;case 18:throw e.t1;case 19:e.next=2;break;case 21:throw r;case 22:case"end":return e.stop()}}),e,null,[[3,11]])})))).apply(this,arguments)}n.AbortError=C}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./logger":108,"./realtime-callbacks":128,"./utils":141,"@babel/runtime/helpers/asyncToGenerator":2,"@babel/runtime/helpers/classCallCheck":3,"@babel/runtime/helpers/createClass":5,"@babel/runtime/helpers/defineProperty":6,"@babel/runtime/helpers/getPrototypeOf":7,"@babel/runtime/helpers/inherits":8,"@babel/runtime/helpers/interopRequireDefault":9,"@babel/runtime/helpers/possibleConstructorReturn":12,"@babel/runtime/helpers/typeof":14,"@babel/runtime/helpers/wrapNativeSuper":15,"@babel/runtime/regenerator":16,"content-type":27}],106:[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)}))}},{}],107:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.InteractiveAuth=n.AuthType=void 0;const a=o(e("./utils")),c=e("./logger"),d=e("./utils"),l="m.login.email.identity",u="m.login.msisdn";var h;!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="org.matrix.msc3231.login.registration_token"}(h=n.AuthType||(n.AuthType={}));class g 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.submitPromise=null,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,d.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 s(this,void 0,void 0,(function*(){if(!this.data.session)return;if(!this.attemptAuthDeferred)return;if(this.submitPromise)return;let e={};if(this.currentStage==l&&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:l,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,i;return s(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 r;this.data.session?(r={session:this.data.session},a.extend(r,e)):r=e;try{this.submitPromise=this.doRequest(r,t),yield this.submitPromise}finally{this.submitPromise=null,t||null===(i=this.busyChangedCallback)||void 0===i||i.call(this,!1)}}))}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e,t=!1){var n,i,r;return s(this,void 0,void 0,(function*(){try{const n=yield this.requestCallback(e,t);this.attemptAuthDeferred.resolve(n),this.attemptAuthDeferred=null}catch(e){const o=null!==(i=null===(n=e.data)||void 0===n?void 0:n.flows)&&void 0!==i?i:null,s=this.data.flows||Boolean(o);401===e.httpStatus&&e.data&&s||(t?c.logger.log("Background poll request failed doing UI auth: ignoring",e):null===(r=this.attemptAuthDeferred)||void 0===r||r.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.requestingEmailToken&&this.chosenFlow.stages.includes(h.Email)){this.requestingEmailToken=!0;try{const e=yield this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,1,this.data.session);this.emailSid=e.sid}catch(e){this.attemptAuthDeferred.reject(e),this.attemptAuthDeferred=null}finally{this.requestingEmailToken=!1}}}}))}startNextAuthStage(){const e=this.chooseStage();if(!e)throw new Error("No incomplete flows from the server");if(this.currentStage=e,e===h.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==l&&(t.emailSid=this.emailSid),this.stateUpdatedCallback(e,t)}chooseStage(){null===this.chosenFlow&&(this.chosenFlow=this.chooseFlow()),c.logger.log("Active flow => %s",JSON.stringify(this.chosenFlow));const e=this.firstUncompletedStage(this.chosenFlow);return c.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===l?e=!0:t==u&&(r=!0);if(e==t&&r==n)return i}const i=[];throw t&&i.push(l),n&&i.push(u),new g("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":108,"./utils":141}],108:[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:36}],109:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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"),d=e("./scheduler"),l=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/event"),n),o(e("./models/room"),n),o(e("./models/group"),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),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 d.MatrixScheduler,e.cryptoStore=e.cryptoStore||g(),new l.MatrixClient(e)}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./autodiscovery":64,"./client":66,"./content-helpers":67,"./content-repo":68,"./crypto/store/indexeddb-crypto-store":90,"./crypto/store/memory-crypto-store":92,"./errors":101,"./filter":104,"./http-api":105,"./interactive-auth":107,"./models/event":116,"./models/event-timeline":115,"./models/event-timeline-set":114,"./models/group":117,"./models/room":122,"./models/room-member":119,"./models/room-state":120,"./models/user":125,"./scheduler":129,"./service-types":130,"./store/indexeddb":133,"./store/memory":134,"./store/session/webstorage":135,"./sync-accumulator":137,"./timeline-window":140,"./webrtc/call":142}],110:[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");n.MSC3089Branch=class{constructor(e,t,n){this.client=e,this.indexEvent=t,this.directory=n}get id(){return this.indexEvent.getStateKey()}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;return{info:e,httpUrl:this.client.mxcUrlToHttp(e.url)}}))}getFileEvent(){return i(this,void 0,void 0,(function*(){const e=this.client.getRoom(this.roomId);if(!e)throw new Error("Unknown room");const 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}}));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)}))}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":59}],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())}))},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=e("../@types/event"),s=e("../logger"),a=e("../utils"),c=e("./MSC3089Branch"),d=r(e("p-retry")),l=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:{[o.EventType.RoomPowerLevels]:100,[o.EventType.RoomHistoryVisibility]:100,[o.EventType.RoomTombstone]:100,[o.EventType.RoomEncryption]:100,[o.EventType.RoomName]:50,[o.EventType.RoomMessage]:50,[o.EventType.RoomMessageEncrypted]:50,[o.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(o.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,o.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,l.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[e])}))}))}retryInvite(e){return(0,a.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 d.default.AbortError(e);throw e}))}))))}setPermissions(e,t){var n;return i(this,void 0,void 0,(function*(){const i=this.room.currentState.getStateEvents(o.EventType.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");const r=i.getContent()||{},s=r.users_default||0,a=r.events_default||50,c=(null===(n=r.events)||void 0===n?void 0:n[o.EventType.RoomPowerLevels])||100,d=r.users||{};switch(t){case u.Viewer:d[e]=s;break;case u.Editor:d[e]=a;break;case u.Owner:d[e]=c;break;default:throw new Error("Invalid role: "+t)}r.users=d,yield this.client.sendStateEvent(this.roomId,o.EventType.RoomPowerLevels,r,"")}))}getPermissions(e){var t,n;const i=this.room.currentState.getStateEvents(o.EventType.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");const r=i.getContent()||{},s=r.users_default||0,a=r.events_default||50,c=(null===(t=r.events)||void 0===t?void 0:t[o.EventType.RoomPowerLevels])||100,d=(null===(n=r.users)||void 0===n?void 0:n[e])||s;return d>=c?u.Owner:d>=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,o.EventType.SpaceChild,{via:[this.client.getDomain()]},t.roomId),yield this.client.sendStateEvent(t.roomId,o.EventType.SpaceParent,{via:[this.client.getDomain()]},this.roomId),t}))}getDirectories(){const e=[],t=this.room.currentState.getStateEvents(o.EventType.SpaceChild);for(const n of t)try{const t=this.client.unstableGetFileTreeSpace(n.getStateKey());t&&e.push(t)}catch(e){s.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(o.EventType.RoomMember);for(const e of n){e.getStateKey()!==this.client.getUserId()&&t.includes(e.getContent().membership)&&(yield this.client.kick(this.roomId,e.getStateKey(),"Room deleted"))}yield this.client.leave(this.roomId)}))}getOrderedChildren(e){const t=e.map((e=>({roomId:e.getStateKey(),order:e.getContent().order})));return t.sort(((e,t)=>{var n,i,r,s;if(e.order&&!t.order)return-1;if(!e.order&&t.order)return 1;if(e.order||t.order)return(0,a.lexicographicCompare)(e.order,t.order);{const c=this.client.getRoom(e.roomId),d=this.client.getRoom(t.roomId);if(!c||!d)return(0,a.lexicographicCompare)(e.roomId,t.roomId);const l=null!==(i=null===(n=c.currentState.getStateEvents(o.EventType.RoomCreate,""))||void 0===n?void 0:n.getTs())&&void 0!==i?i:0,u=null!==(s=null===(r=d.currentState.getStateEvents(o.EventType.RoomCreate,""))||void 0===r?void 0:r.getTs())&&void 0!==s?s:0;return l===u?(0,a.lexicographicCompare)(e.roomId,t.roomId):l-u}})),t}getParentRoom(){const e=this.room.currentState.getStateEvents(o.EventType.SpaceParent)[0];if(!e)throw new Error("Expected to have a parent in a non-top level space");const t=this.client.getRoom(e.getStateKey());if(!t)throw new Error("Unable to locate room for parent");return t}getOrder(){if(this.isTopLevel)return-1;const e=this.getParentRoom().currentState.getStateEvents(o.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(o.EventType.SpaceChild),s=this.getOrderedChildren(r);e=Math.max(Math.min(e,s.length-1),0);const c=this.getOrder()<e;c&&e===s.length-1?e--:c||0!==e||e++;const d=s[c?e:e-1],l=s[c?e+1:e];let u=a.DEFAULT_ALPHABET[0],h=!1;if(d)if(e===s.length-1)(null==l?void 0:l.order)&&(u=(0,a.nextString)(l.order));else{const e=null==d?void 0:d.order,t=null==l?void 0:l.order;e&&t?u=e===t?(0,a.nextString)(e):(0,a.averageBetweenStrings)(e,t):e?u=(0,a.nextString)(e):t?u=(0,a.prevString)(t):h=!0}else(null==l?void 0:l.order)&&(u=(0,a.prevString)(l.order));if(h){let n;for(let r=0;r<=e;r++){const e=s[r];if(0===r&&(n=e.order),e.order)n=e.order;else{n=n?(0,a.nextString)(n):a.DEFAULT_ALPHABET[0];const r=i.currentState.getStateEvents(o.EventType.SpaceChild,e.roomId),s=null!==(t=null==r?void 0:r.getContent())&&void 0!==t?t:{via:[this.client.getDomain()]};yield this.client.sendStateEvent(i.roomId,o.EventType.SpaceChild,Object.assign(Object.assign({},s),{order:n}),e.roomId)}}u=(0,a.nextString)(n)}const g=i.currentState.getStateEvents(o.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,o.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(new Blob([t]),{includeFilename:!1,onlyContentUri:!0});n.url=i;const s={msgtype:o.MsgType.File,body:e,url:i,file:n};(r=null!=r?r:{})["m.new_content"]&&(r["m.new_content"]=s);const a=yield this.client.sendMessage(this.roomId,Object.assign(Object.assign(Object.assign({},r),s),{[o.UNSTABLE_MSC3089_LEAF.name]:{}}));return yield this.client.sendStateEvent(this.roomId,o.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e},a.event_id),a}))}getFile(e){const t=this.room.currentState.getStateEvents(o.UNSTABLE_MSC3089_BRANCH.name,e);return t?new c.MSC3089Branch(this.client,t,this):null}listFiles(){return this.listAllFiles().filter((e=>e.isActive))}listAllFiles(){var e;return(null!==(e=this.room.currentState.getStateEvents(o.UNSTABLE_MSC3089_BRANCH.name))&&void 0!==e?e:[]).map((e=>new c.MSC3089Branch(this.client,e,this)))}}},{"../@types/event":59,"../crypto/algorithms/megolm":79,"../logger":108,"../utils":141,"./MSC3089Branch":110,"p-retry":38}],112:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BaseModel=void 0;const i=e("events");class r extends i.EventEmitter{on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.addListener(e,t),this}removeListener(e,t){return super.removeListener(e,t),this}}n.BaseModel=r},{events:28}],113:[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.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":115}],114:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.EventTimelineSet=n.DuplicateStrategy=void 0;const i=e("events"),r=e("./event-timeline"),o=e("./event"),s=e("../logger"),a=e("./relations");let c;var d;c=s.logger.log.bind(s.logger),function(e){e.Ignore="ignore",e.Replace="replace"}(d=n.DuplicateStrategy||(n.DuplicateStrategy={}));class l extends i.EventEmitter{constructor(e,t){super(),this.room=e,this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new r.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.filter?this.filter.filterRoomTimeline(this.room.getPendingEvents()):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,i=this.liveTimeline,o=n?i.forkLive(r.EventTimeline.FORWARDS):i.fork(r.EventTimeline.FORWARDS);n?(this.timelines=[o],this._eventIdToTimeline={}):this.timelines.push(o),t&&i.setPaginationToken(t,r.EventTimeline.FORWARDS),o.setPaginationToken(e,r.EventTimeline.BACKWARDS),this.liveTimeline=o,this.emit("Room.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 r.EventTimeline(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,n,i){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 o=t?r.EventTimeline.BACKWARDS:r.EventTimeline.FORWARDS,a=t?r.EventTimeline.FORWARDS:r.EventTimeline.BACKWARDS;let d=!1,l=!1;for(let i=0;i<e.length;i++){const u=e[i],h=u.getId(),g=this._eventIdToTimeline[h];if(!g){this.addEventToTimeline(u,n,t),l=!0,d=!0;continue}if(l=!1,g==n){c("Event "+h+" already in timeline "+n);continue}const p=n.getNeighbouringTimeline(o);if(p){c(g==p?"Event "+h+" in neighbouring timeline - switching to "+g:"Event "+h+" already in a different timeline "+g),n=g;continue}s.logger.info("Already have timeline for "+h+" - joining timeline "+n+" to "+g);const f=g===this.liveTimeline,y=n===this.liveTimeline,m=o===r.EventTimeline.BACKWARDS&&f,v=o===r.EventTimeline.FORWARDS&&y;m||v?(m&&s.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+g+")"),v&&s.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+n+")")):(n.setNeighbouringTimeline(g,o),g.setNeighbouringTimeline(n,a),n=g,d=!0)}if(l||!d){if(o===r.EventTimeline.FORWARDS&&n===this.liveTimeline)return s.logger.warn({lastEventWasNew:l,didUpdate:d}),void s.logger.warn(`Refusing to set forwards pagination token of live timeline ${n} to ${i}`);n.setPaginationToken(i,o)}}addLiveEvent(e,t=d.Ignore,n=!1,i){if(this.filter){if(!this.filter.filterRoomTimeline([e]).length)return}const o=this._eventIdToTimeline[e.getId()];if(o)if(t===d.Replace){c("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()){i||(i=o.getState(r.EventTimeline.FORWARDS)),r.EventTimeline.setEventMetadata(e,i,!1),t[n]=e;break}}else c("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this.liveTimeline,!1,n,i)}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("Room.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("Room.timeline",n,this.room,void 0,!0,i)}return n}compareEventOrdering(e,t){if(e==t)return 0;const n=this._eventIdToTimeline[e],i=this._eventIdToTimeline[t];if(void 0===n)return null;if(void 0===i)return null;if(n===i){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===i)return-1;o=o.getNeighbouringTimeline(r.EventTimeline.FORWARDS)}for(o=n;o;){if(o===i)return 1;o=o.getNeighbouringTimeline(r.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]}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===o.EventStatus.CANCELLED)return;if(e.isBeingDecrypted()||e.shouldAttemptDecryption())return void e.once("Event.decrypted",(()=>{this.aggregateRelations(e)}));const t=e.getRelation();if(!t)return;const n=t.event_id,i=t.rel_type,r=e.getType();let s=this.relations[n];s||(s=this.relations[n]={});let c=s[i];c||(c=s[i]={});let d,l=c[r];l||(l=c[r]=new a.Relations(i,r,this.room),d=this.findEventById(n)||this.room.getPendingEvent(n),d&&l.setTargetEvent(d)),l.addEvent(e)}}n.EventTimelineSet=l},{"../logger":108,"./event":116,"./event-timeline":115,"./relations":118,events:28}],115:[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":59,"./room-state":120}],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.MatrixEvent=n.EventStatus=void 0;const r=e("events"),o=e("../logger"),s=e("../@types/event"),a=e("../utils"),c=e("./thread"),d=e("../ReEmitter");!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={}));const l={};function u(e){return l[e]||(l[e]=e),l[e]}class h extends r.EventEmitter{constructor(e={}){super(),this.event=e,this.pushActions=null,this._replacingEvent=null,this._localRedactionEvent=null,this._isCancelled=!1,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]=u(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]=u(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]=u(e.content["m.relates_to"][t]))})),this.txnId=e.txn_id||null,this.localTimestamp=Date.now()-this.getAge(),this.reEmitter=new d.ReEmitter(this)}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;const t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];if((null==t?void 0:t.rel_type)===s.RelationType.Thread)return t.event_id}get isThreadRelation(){return!!this.threadRootId}get isThreadRoot(){const e=this.getThread();return(null==e?void 0:e.id)===this.getId()}get parentEventId(){return this.replyEventId||this.relationEventId}get replyEventId(){var e;const t=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.isEncrypted()&&!this.isBeingDecrypted()&&!this.clearEvent}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("Event.decrypted",this,i))}}))}badEncryptedMessage(e){return{clearEvent:{type:"m.room.message",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}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&"m.room.encrypted"===this.event.type}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||{}}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("Event.beforeRedaction",this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");let t;for(t in this._localRedactionEvent=null,this.emit("Event.beforeRedaction",this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event,this.event)this.event.hasOwnProperty(t)&&(g.has(t)||delete this.event[t]);const n=p[this.getType()]||{},i=this.getContent();for(t in i)i.hasOwnProperty(t)&&(n[t]||delete i[t])}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return"m.room.redaction"===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("Event.localEventIdReplaced",this)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit("Event.status",this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit("Event.localEventIdReplaced",this)}isRelation(e){const t=this.getWireContent(),n=t&&t["m.relates_to"];return n&&n.rel_type&&n.event_id&&(e&&n.rel_type===e||!e)}getRelation(){return this.isRelation()?this.getWireContent()["m.relates_to"]:null}makeReplaced(e){this.isRedacted()&&e||this._replacingEvent!==e&&(this._replacingEvent=e,this.emit("Event.replaced",this))}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){const t=this.getUnsigned()["m.relations"];if(t)return 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 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 h(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.reEmitter.reEmit(e,[c.ThreadEvent.Ready,c.ThreadEvent.Update])}getThread(){return this.thread}}n.MatrixEvent=h;const g=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),p={"m.room.member":{membership:1},"m.room.create":{creator:1},"m.room.join_rules":{join_rule:1},"m.room.power_levels":{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1},"m.room.aliases":{aliases:1}}},{"../@types/event":59,"../ReEmitter":63,"../logger":108,"../utils":141,"./thread":124,events:28}],117:[function(e,t,n){"use strict";var i=e("@babel/runtime/helpers/typeof");Object.defineProperty(n,"__esModule",{value:!0}),n.Group=a;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=s(t);if(n&&n.has(e))return n.get(e);var r={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var c=o?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")),o=e("events");function s(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(s=function(e){return e?n:t})(e)}function a(e){this.groupId=e,this.name=null,this.avatarUrl=null,this.myMembership=null,this.inviter=null}r.inherits(a,o.EventEmitter),a.prototype.setProfile=function(e,t){this.name===e&&this.avatarUrl===t||(this.name=e||this.groupId,this.avatarUrl=t,this.emit("Group.profile",this))},a.prototype.setMyMembership=function(e){this.myMembership!==e&&(this.myMembership=e,this.emit("Group.myMembership",this))},a.prototype.setInviter=function(e){this.inviter=e}},{"../utils":141,"@babel/runtime/helpers/typeof":14,events:28}],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.Relations=void 0;const r=e("events"),o=e("./event"),s=e("../logger"),a=e("../@types/event");class c extends r.EventEmitter{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===o.EventStatus.CANCELLED&&(e.removeListener("Event.status",this.onEventStatus),this.removeEvent(e)):e.removeListener("Event.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===a.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.removeListener("Event.beforeRedaction",this.onBeforeRedaction),this.emit("Relations.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 s.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("Event.status",this.onEventStatus),this.relations.add(e),this.relationEventIds.add(e.getId()),this.relationType===a.RelationType.Annotation)this.addAnnotationToAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.on("Event.beforeRedaction",this.onBeforeRedaction),this.emit("Relations.add",e),this.maybeEmitCreated()}else s.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 s.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===a.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}this.emit("Relations.remove",e)}else s.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!==a.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==a.RelationType.Annotation?null:this.annotationsBySender}getLastReplacement(){return i(this,void 0,void 0,(function*(){if(this.relationType!==a.RelationType.Replace)return null;if(!this.targetEvent)return null;const e=this.targetEvent.getServerAggregatedRelation(a.RelationType.Replace),t=e&&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===a.RelationType.Replace){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("Event.relationsCreated",this.relationType,this.eventType))}}n.Relations=c},{"../@types/event":59,"../logger":108,"./event":116,events:28}],119:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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=void 0;const s=e("events"),a=e("../content-repo"),c=o(e("../utils"));class d extends s.EventEmitter{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("m.room.member"!==e.getType())return;this._isOutOfBand=!1,this.events.member=e;const i=this.membership;this.membership=e.getDirectionalContent().membership,this.disambiguate=function(e,t,n){if(!t||t===e)return!1;if(!c.removeHiddenChars(t))return!1;if(!n)return!1;if(l.test(t))return!0;if(u.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?c.removeDirectionOverrideChars(t)+" ("+e+")":t&&t!==e&&c.removeHiddenChars(t)?c.removeDirectionOverrideChars(t):e}(this.userId,n,0,this.disambiguate),this.rawDisplayName=c.removeDirectionOverrideChars(e.getDirectionalContent().displayname),this.rawDisplayName&&c.removeHiddenChars(this.rawDisplayName)||(this.rawDisplayName=this.userId),i!==this.membership&&(this.updateModifiedTime(),this.emit("RoomMember.membership",e,this,i)),r!==this.name&&(this.updateModifiedTime(),this.emit("RoomMember.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("RoomMember.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("RoomMember.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 s=this.getMxcAvatarUrl();if(!s&&!r)return null;const c=(0,a.getHttpUriForMxc)(e,s,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=d;const l=/@.+:.+/,u=/[\u200E\u200F\u202A-\u202F]/},{"../content-repo":68,"../utils":141,events:28}],120:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.RoomState=void 0;const s=e("events"),a=e("./room-member"),c=e("../logger"),d=o(e("../utils")),l=e("../@types/event"),u=e("../@types/partials");var h;!function(e){e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished"}(h||(h={}));class g extends s.EventEmitter{constructor(e,t={status:h.NotStarted}){super(),this.roomId=e,this.oobMemberFlags=t,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.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}clone(){const e=new g(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=h.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==h.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;const t=this.getStateEventMatching(e);this.setStateEvent(e),e.getType()===l.EventType.RoomMember&&(this.updateDisplayNameCache(e.getStateKey(),e.getContent().displayname),this.updateThirdPartyTokenCache(e)),this.emit("RoomState.events",e,this,t)})),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===l.EventType.RoomMember){const t=e.getStateKey();"leave"!==e.getContent().membership&&"ban"!==e.getContent().membership||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);const n=this.getOrCreateMember(t,e);n.setMembershipEvent(e,this),this.updateMember(n),this.emit("RoomState.members",e,this,n)}else if(e.getType()===l.EventType.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const n=t.getLastModifiedTime();t.setPowerLevelEvent(e),n!==t.getLastModifiedTime()&&this.emit("RoomState.members",e,this,t)})),this.sentinels={}}}))}getOrCreateMember(e,t){let n=this.members[e];return n||(n=new a.RoomMember(this.roomId,e),this.members[e]=n,this.emit("RoomState.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)}getStateEventMatching(e){return this.events.has(e.getType())?this.events.get(e.getType()).get(e.getStateKey()):null}updateMember(e){const t=this.getStateEvents(l.EventType.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===h.NotStarted}markOutOfBandMembersStarted(){this.oobMemberFlags.status===h.NotStarted&&(this.oobMemberFlags.status=h.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===h.InProgress&&(this.oobMemberFlags.status=h.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=h.NotStarted}setOutOfBandMembers(e){c.logger.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===h.InProgress&&(c.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=h.Finished,e.forEach((e=>this.setOutOfBandMember(e))))}setOutOfBandMember(e){if(e.getType()!==l.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("RoomState.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[d.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(l.EventType.RoomRedaction,t);return e.getSender()===t?i:this.hasSufficientPowerLevelFor("redact",n.powerLevel)}hasSufficientPowerLevelFor(e,t){const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let i={};n&&(i=n.getContent());let r=50;return d.isNumber(i[e])&&(r=i[e]),t>=r}maySendMessage(e){return this.maySendEventOfType(l.EventType.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!t.isGuest()&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){const i=this.getStateEvents(l.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 d=n?s:a;return Number.isSafeInteger(o[e])&&(d=o[e]),c>=d}mayTriggerNotifOfType(e,t){const n=this.getMember(t);if(!n)return!1;const i=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r=50;return i&&i.getContent()&&i.getContent().notifications&&d.isNumber(i.getContent().notifications[e])&&(r=i.getContent().notifications[e]),n.powerLevel>=r}getJoinRule(){var e;const t=this.getStateEvents(l.EventType.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||u.JoinRule.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(l.EventType.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||u.HistoryVisibility.Shared}getGuestAccess(){var e;const t=this.getStateEvents(l.EventType.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||u.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(l.EventType.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=d.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&&d.removeHiddenChars(t);i&&(this.displayNameToUserIds[i]||(this.displayNameToUserIds[i]=[]),this.displayNameToUserIds[i].push(e))}}n.RoomState=g},{"../@types/event":59,"../@types/partials":60,"../logger":108,"../utils":141,"./room-member":119,events:28}],121:[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}}},{}],122:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.NotificationCountType=void 0;const a=e("events"),c=e("./event-timeline-set"),d=e("./event-timeline"),l=e("../content-repo"),u=o(e("../utils")),h=e("../utils"),g=e("./event"),p=e("./room-member"),f=e("./room-summary"),y=e("../logger"),m=e("../ReEmitter"),v=e("../@types/event"),S=e("../client"),E=e("./thread"),b=["1","2","3","4","5","6"];function _(e,t,n){const i={content:{},type:"m.receipt",room_id:t.getRoomId()};return i.content[t.getId()]={},i.content[t.getId()][n]={},i.content[t.getId()][n][e]={ts:t.getTs()},new g.MatrixEvent(i)}var w;!function(e){e.Highlight="highlight",e.Total="total"}(w=n.NotificationCountType||(n.NotificationCountType={}));class T extends a.EventEmitter{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.realReceipts={},this.notificationCounts={},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.setMaxListeners(100),this.reEmitter=new m.ReEmitter(this),i.pendingEventOrdering=i.pendingEventOrdering||S.PendingEventOrdering.Chronological,-1===["chronological","detached"].indexOf(i.pendingEventOrdering))throw new Error("opts.pendingEventOrdering MUST be either 'chronological' or 'detached'. Got: '"+i.pendingEventOrdering+"'");if(this.name=e,this.timelineSets=[new c.EventTimelineSet(this,i)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),["Room.timeline","Room.timelineReset"]),this.fixUpLegacyTimelineFields(),"detached"==this.opts.pendingEventOrdering){this.pendingEventList=[];const e=t.sessionStore.store.getItem(I(this.roomId));e&&JSON.parse(e).forEach((e=>s(this,void 0,void 0,(function*(){const t=new g.MatrixEvent(e);t.getType()===v.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)}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(v.EventType.RoomCreate,"");if(!e)return this.getVersionWarning||(y.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 b.includes(this.getVersion())?null:"6"}getRecommendedVersion(){return s(this,void 0,void 0,(function*(){let e=(yield this.client.getCapabilities())["m.room_versions"];if(!e){e={default:"6",available:{}};for(const t of b)e.available[t]=S.RoomVersionStability.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){y.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 y.logger.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}))}checkVersionAgainstCapability(e){const t=this.getVersion();y.logger.log(`[${this.roomId}] Current version: ${t}`),y.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?y.logger.warn(`URGENT upgrade required on ${this.roomId}`):y.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(v.EventType.RoomTombstone,e)}getPendingEvents(){if("detached"!==this.opts.pendingEventOrdering)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if("detached"!==this.opts.pendingEventOrdering)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=u.removeElement(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){return"detached"===this.opts.pendingEventOrdering&&this.pendingEventList.some((t=>t.getId()===e))}getPendingEvent(e){return"detached"!==this.opts.pendingEventOrdering?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("Room.myMembership",this,e,t))}loadMembersFromServer(){return s(this,void 0,void 0,(function*(){const e=this.client.store.getSyncToken(),t=u.encodeParams({not_membership:"leave",at:e}),n=u.encodeUri("/rooms/$roomId/members?"+t,{$roomId:this.roomId}),i=this.client.http;return(yield i.authedRequest(void 0,"GET",n)).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(),y.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));y.logger.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{y.logger.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{y.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=>{y.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),y.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(d.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(d.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){return this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(t)return t;{const n=this.getThreads();for(let i=0;i<n.length;i++){if(t=n[i].findEventById(e),t)return t}}}getUnreadNotificationCount(e=w.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(v.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(v.EventType.RoomAvatar,""))||void 0===e?void 0:e.getContent())||void 0===t?void 0:t.url)||null}getAliases(){const e=[],t=this.currentState.getStateEvents(v.EventType.RoomAliases);if(t)for(let n=0;n<t.length;++n){const i=t[n];if(Array.isArray(i.getContent().aliases)){const t=i.getContent().aliases.filter((e=>"string"==typeof e&&("#"===e[0]&&!!e.endsWith(`:${i.getStateKey()}`))));Array.prototype.push.apply(e,t)}}return e}getCanonicalAlias(){const e=this.currentState.getStateEvents(v.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(v.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,n,i){n.getTimelineSet().addEventsToTimeline(e,t,n,i)}getThread(e){return this.getThreads().find((t=>t.id===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(v.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){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const t=Object.assign({filter:e},this.opts),n=new c.EventTimelineSet(this,t);this.reEmitter.reEmit(n,["Room.timeline","Room.timelineReset"]),this.filteredTimelineSets[e.filterId]=n,this.timelineSets.push(n);const i=this.getLiveTimeline();i.getEvents().forEach((function(e){n.addLiveEvent(e)}));let r=i;for(;r.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);)r=r.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);return n.getLiveTimeline().setPaginationToken(r.getPaginationToken(d.EventTimeline.BACKWARDS),d.EventTimeline.BACKWARDS),n}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)}findThreadForEvent(e){if(!e)return null;if(e.isThreadRelation)return this.threads.get(e.threadRootId);if(e.isThreadRoot)return this.threads.get(e.getId());{const t=this.findEventById(e.parentEventId);return this.findThreadForEvent(t)}}addThreadedEvent(e){return s(this,void 0,void 0,(function*(){let t=this.findThreadForEvent(e);if(t)t.addEvent(e);else{const n=[e];let i=this.findEventById(e.threadRootId);if(!i){const t=yield this.client.fetchRoomEvent(this.roomId,e.threadRootId);i=new g.MatrixEvent(t)}n.unshift(i),t=new E.Thread(n,this,this.client),this.threads.set(t.id,t),this.reEmitter.reEmit(t,[E.ThreadEvent.Update,E.ThreadEvent.Ready]),this.emit(E.ThreadEvent.New,t)}this.emit(E.ThreadEvent.Update,t)}))}addLiveEvent(e,t,n=!1){if(e.isRedaction()){const t=e.event.redacts,n=this.findEventById(t);if(n){if(n.makeRedacted(e),n.getStateKey()){this.currentState.getStateEvents(n.getType(),n.getStateKey()).getId()===n.getId()&&this.currentState.setStateEvents([n])}this.emit("Room.redaction",e,this)}}if(e.getUnsigned().transaction_id){const t=this.txnToEvent[e.getUnsigned().transaction_id];if(t)return void this.handleRemoteEcho(e,t)}for(let i=0;i<this.timelineSets.length;i++)this.timelineSets[i].addLiveEvent(e,t,n);e.sender&&e.getType()!==v.EventType.RoomRedaction&&this.addReceipt(_(e.sender.userId,e,"m.read"),!0)}addPendingEvent(e,t){var n;if(!(null===(n=this.client)||void 0===n?void 0:n.supportsExperimentalThreads())||!e.threadRootId){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(d.EventTimeline.setEventMetadata(e,this.getLiveTimeline().getState(d.EventTimeline.FORWARDS),!1),this.txnToEvent[t]=e,"detached"==this.opts.pendingEventOrdering){if(this.pendingEventList.some((e=>e.status===g.EventStatus.NOT_SENT))&&(y.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 n=this.pendingEventList&&this.pendingEventList.find((e=>e.getId()===t));n||(n=this.getUnfilteredTimelineSet().findEventById(t)),n&&(n.markLocallyRedacted(e),this.emit("Room.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("Room.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===v.EventType.RoomMessageEncrypted,n=this.client.isRoomEncrypted(this.roomId);return t||!n})),{store:t}=this.client.sessionStore;this.pendingEventList.length>0?t.setItem(I(this.roomId),JSON.stringify(e)):t.removeItem(I(this.roomId))}}aggregateNonLiveRelation(e){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)}}handleRemoteEcho(e,t){const n=t.getId(),i=e.getId(),r=t.status;y.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);for(let e=0;e<this.timelineSets.length;e++){this.timelineSets[e].handleRemoteEcho(t,n,i)}this.emit("Room.localEchoUpdated",t,this,n,r)}updatePendingEvent(e,t,n){if(y.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.getUnfilteredTimelineSet().eventIdToTimeline(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=R[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);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.pendingEventList.findIndex((e=>e.getId()===r));if(-1!==e){const[t]=this.pendingEventList.splice(e,1);t.isRedaction()&&this.revertRedactionLocalEcho(t)}}this.removeEvent(r)}this.savePendingEvents(),this.emit("Room.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("Room.redactionCancelled",e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}addLiveEvents(e,t,n=!1){let i;if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(i=0;i<this.timelineSets.length;i++){const e=this.timelineSets[i].getLiveTimeline();if(e.getPaginationToken(d.EventTimeline.FORWARDS))throw new Error("live timeline "+i+" is no longer live - it has a pagination token ("+e.getPaginationToken(d.EventTimeline.FORWARDS)+")");if(e.getNeighbouringTimeline(d.EventTimeline.FORWARDS))throw new Error("live timeline "+i+" is no longer live - it has a neighbouring timeline")}for(i=0;i<e.length;i++){this.addLiveEvent(e[i],t,n);const r=this.threads.get(e[i].getId());r&&!r.ready&&r.addEvent(e[i],!0)}}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(v.EventType.RoomMember,this.myUserId);if(e&&"invite"===e.getContent().membership){(e.getUnsigned().invite_room_state||[]).forEach((e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new g.MatrixEvent({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])}))}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,h.normalize)(this.name),this.summary=new f.RoomSummary(this.roomId,{title:this.name}),t!==this.name&&this.emit("Room.name",this)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return"m.read"===e.type})).map((function(e){return e.userId}))}getEventReadUpTo(e,t=!1){let n=this.receipts;return t&&(n=this.realReceipts),void 0===n["m.read"]||void 0===n["m.read"][e]?null:n["m.read"][e].eventId}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){t||this.addReceiptsToStructure(e,this.realReceipts),this.addReceiptsToStructure(e,this.receipts),this.receiptCacheByEventId=this.buildReceiptCache(this.receipts),this.emit("Room.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=>{const o=n[e][i][r];t[i]||(t[i]={});const s=t[i][r];if(s){const t=this.getUnfilteredTimelineSet().compareEventOrdering(s.eventId,e);if(null!==t&&t>=0)return}else t[i][r]={};t[i][r]={eventId:e,data:o}}))}))}))}buildReceiptCache(e){const t={};return Object.keys(e).forEach((function(n){Object.keys(e[n]).forEach((function(i){const r=e[n][i];t[r.eventId]||(t[r.eventId]=[]),t[r.eventId].push({userId:i,type:n,data:r.data})}))})),t}addLocalEchoReceipt(e,t,n){this.addReceipt(_(e,t,n),!0)}addTags(e){this.tags=e.getContent().tags||{},this.emit("Room.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("Room.accountData",n,this,i)}}getAccountData(e){return this.accountData[e]}maySendMessage(){return"join"===this.getMyMembership()&&this.currentState.maySendEvent(v.EventType.RoomMessage,this.myUserId)}canInvite(e){let t="join"===this.getMyMembership();const n=this.currentState.getStateEvents(v.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(v.EventType.RoomCreate,"");if(e)return e.getContent()[v.RoomCreateTypeField];this.getTypeWarning||(y.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===v.RoomType.Space}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(v.EventType.RoomName,"");if(e&&e.getContent()&&e.getContent().name)return e.getContent().name}let n=this.getCanonicalAlias();if(!n){const e=this.getAltAliases();e.length&&(n=e[0])}if(n)return n;let i=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,r=[];const o=this.currentState.getStateEvents(v.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)=>u.compare(e.userId,t.userId))),t=t.slice(0,5),s=t.map((e=>e.name))}if(i)return k(s,i);if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(v.EventType.RoomThirdPartyInvite);if(e&&e.length){return`Inviting ${k(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 ${k(a)})`:"Empty room"}}function I(e){return`mx_pending_events_${e}`}n.Room=T;const R={};function k(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"}R[g.EventStatus.ENCRYPTING]=[g.EventStatus.SENDING,g.EventStatus.NOT_SENT],R[g.EventStatus.SENDING]=[g.EventStatus.ENCRYPTING,g.EventStatus.QUEUED,g.EventStatus.NOT_SENT,g.EventStatus.SENT],R[g.EventStatus.QUEUED]=[g.EventStatus.SENDING,g.EventStatus.CANCELLED],R[g.EventStatus.SENT]=[],R[g.EventStatus.NOT_SENT]=[g.EventStatus.SENDING,g.EventStatus.QUEUED,g.EventStatus.CANCELLED],R[g.EventStatus.CANCELLED]=[]},{"../@types/event":59,"../ReEmitter":63,"../client":66,"../content-repo":68,"../logger":108,"../utils":141,"./event":116,"./event-timeline":115,"./event-timeline-set":114,"./room-member":119,"./room-summary":121,"./thread":124,events:28}],123:[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||{},o=n.events_before||[],s=n.events_after||[],a=new i.EventContext(t(e.result));return a.setPaginateToken(n.start,!0),a.addEvents(o.map(t),!0),a.addEvents(s.map(t),!1),a.setPaginateToken(n.end,!1),new r(e.rank,a)}}n.SearchResult=r},{"./event-context":113}],124:[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.Thread=n.ThreadEvent=void 0;const r=e("./event"),o=e("./event-timeline"),s=e("./event-timeline-set"),a=e("./base-model");var c;!function(e){e.New="Thread.new",e.Ready="Thread.ready",e.Update="Thread.update"}(c=n.ThreadEvent||(n.ThreadEvent={}));class d extends a.BaseModel{constructor(e=[],t,n){if(super(),this.room=t,this.client=n,0===e.length)throw new Error("Can't create an empty thread");this.timelineSet=new s.EventTimelineSet(this.room,{unstableClientRelationAggregation:!0,timelineSupport:!0,pendingEvents:!1}),e.forEach((e=>this.addEvent(e)))}addEvent(e,t=!1){return i(this,void 0,void 0,(function*(){if(this.timelineSet.findEventById(e.getId())||null!==e.status)return;this.root||(e.isThreadRelation?this.root=e.threadRootId:this.root=e.getId());const n=this.room.getLiveTimeline().getState(o.EventTimeline.FORWARDS);e.setThread(this),this.timelineSet.addEventToTimeline(e,this.timelineSet.getLiveTimeline(),t,!1,n),this.ready&&this.client.decryptEventIfNeeded(e,{}),this.emit(c.Update,this)}))}findEventById(e){return this.timelineSet.findEventById(e)}get lastReply(){const e=this.events.filter((e=>e.isThreadRelation));return e[e.length-1]}get ready(){return void 0!==this.rootEvent}get id(){return this.root}get rootEvent(){return this.findEventById(this.root)}get roomId(){return this.rootEvent.getRoomId()}get length(){return this.events.filter((e=>e.isThreadRelation)).length}get participants(){const e=new Set;return this.events.forEach((t=>{e.add(t.getSender())})),e}get replyToEvent(){const e=this.events;return e[e.length-1]}get events(){return this.timelineSet.getLiveTimeline().getEvents()}merge(e){e.events.forEach((e=>{this.addEvent(e)})),this.events.forEach((e=>e.setThread(this)))}has(e){return this.timelineSet.findEventById(e)instanceof r.MatrixEvent}}n.Thread=d},{"./base-model":112,"./event":116,"./event-timeline":115,"./event-timeline-set":114}],125:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.User=void 0;const i=e("events");class r extends i.EventEmitter{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.unstable_statusMessage="",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("User.presence"),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push("User.avatarUrl"),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push("User.displayName"),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&n.push("User.currentlyActive"),this.presence=e.getContent().presence,n.push("User.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}unstable_updateStatusMessage(e){e.getContent()?this.unstable_statusMessage=e.getContent().status:this.unstable_statusMessage="",this.updateModifiedTime(),this.emit("User.unstable_statusMessage",this)}}n.User=r},{events:28}],126:[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=[o.PushRuleKind.Override,o.PushRuleKind.ContentSpecific,o.PushRuleKind.RoomSpecific,o.PushRuleKind.SenderSpecific,o.PushRuleKind.Underride],a=[{rule_id:".m.rule.tombstone",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:"m.room.tombstone"},{kind:o.ConditionKind.EventMatch,key:"state_key",pattern:""}],actions:[o.PushRuleActionName.Notify,{set_tweak:o.TweakName.Highlight,value:!0}]},{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:o.ConditionKind.EventMatch,key:"type",pattern:"m.reaction"}],actions:[o.PushRuleActionName.DontNotify]}];class c{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 a){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<s.length;++n){const i=s[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(/^([=<>]*)([0-9]*)$/);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 c.cachedGlobToRegex[t]||(c.cachedGlobToRegex[t]=new RegExp(e+(0,i.globToRegexp)(t)+n,"i")),c.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=c.actionListToActionsObject(n.actions);return void 0===i.tweaks.highlight&&(i.tweaks.highlight=n.kind==o.PushRuleKind.ContentSpecific),i}ruleMatchesEvent(e,t){let n=!0;for(let i=0;i<e.conditions.length;++i){const r=e.conditions[i];n&=this.eventFulfillsCondition(r,t)}return n}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 s)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=c,c.cachedGlobToRegex={}},{"./@types/PushRules":58,"./logger":108,"./utils":141}],127:[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)}},{}],128:[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(d,i)}function d(){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++,d={runAt:i,func:e,params:n,key:r},l=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(l,0,d),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":108}],129:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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 d("Stopping queue '%s' as it is now empty",e)}d("Queue '%s' has %s pending events",e,this.queues[e].length),Promise.resolve().then((()=>this.procFn(t.event))).then((n=>{this.removeNextEvent(e),d("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);d("retry(%s) err=%s event_id=%s waitTime=%s",t.attempts,n,t.event.getId(),i),-1===i?(d("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}),d("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),d("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 d(...e){false}n.MatrixScheduler=c},{"./@types/event":59,"./logger":108,"./utils":141}],130:[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={}))},{}],131:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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")),d=o(e("../indexeddb-helpers")),l=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.dbName="matrix-js-sdk:"+(t||"default"),this.syncAccumulator=new a.SyncAccumulator}static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),d.exists(e,t)}connect(){if(!this.disconnected)return l.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,l.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const e=this.indexedDB.open(this.dbName,3);return e.onupgradeneeded=t=>{const n=e.result,i=t.oldVersion;l.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=()=>{l.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},l.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),g(e).then((()=>(l.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])=>{l.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,groups:t.groupsData,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=>(l.logger.log(`LL: got ${t&&t.length} membershipEvents from storage for room ${e} ...`),t)))}setOutOfBandMembers(e,t){return s(this,void 0,void 0,(function*(){l.logger.log(`LL: backend about to store ${t.length} members for ${e}`);const 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),l.logger.log(`LL: backend done storing for ${e}!`)}))}clearOutOfBandMembers(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),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 d;l.logger.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,o],[e,s]),yield(d=a.delete(c),new Promise(((e,t)=>{d.onsuccess=()=>e(d),d.onerror=e=>t(e)})))}))}clearDatabase(){return new Promise((e=>{l.logger.log(`Removing indexeddb instance: ${this.dbName}`);const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{l.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{l.logger.warn(`unable to delete js-sdk store indexeddb: ${t.error}`),e()},t.onsuccess=()=>{l.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}}))}getSavedSync(e=!0){const t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(c.deepCopy(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then((()=>{this.syncAccumulator.accumulate(e)}))}syncToDatabase(e){return s(this,void 0,void 0,(function*(){const t=this.syncAccumulator.getJSON(!0);yield Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData,t.groupsData)])}))}persistSyncData(e,t,n){return l.logger.log("Persisting sync data up to",e),c.promiseTry((()=>{const i=this.db.transaction(["sync"],"readwrite");return i.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t,groupsData:n}),h(i).then()}))}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 l.logger.log("LocalIndexedDBStoreBackend: loading account data..."),c.promiseTry((()=>u(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))))}loadSyncData(){return l.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),c.promiseTry((()=>u(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&l.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))))}getClientOptions(){return Promise.resolve().then((()=>u(this.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,(e=>{if(e.value&&e.value&&e.value.options)return e.value.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":106,"../logger":108,"../sync-accumulator":137,"../utils":141}],132:[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":108,"../utils":141}],133:[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("events"),o=e("./memory"),s=e("./indexeddb-local-backend"),a=e("./indexeddb-remote-backend"),c=e("../models/user"),d=e("../models/event"),l=e("../logger");class u extends o.MemoryStore{constructor(e){if(super(e),this.startedUp=!1,this.syncTs=0,this.userModifiedMap={},this.emitter=new r.EventEmitter,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 a.RemoteIndexedDBStoreBackend(e.workerFactory,e.dbName):this.backend=new s.LocalIndexedDBStoreBackend(e.indexedDB,e.dbName)}static exists(e,t){return s.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 c.User(e);t&&n.setPresenceEvent(new d.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 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(...t)}}))}}n.IndexedDBStore=u},{"../logger":108,"../models/event":116,"../models/user":125,"./indexeddb-local-backend":131,"./indexeddb-remote-backend":132,"./memory":134,events:28}],134:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.MemoryStore=void 0;const i=e("../models/user");function r(e){return"string"==typeof e&&!!e&&"undefined"!==e&&"null"!==e||"number"==typeof e}n.MemoryStore=class{constructor(e={}){this.rooms={},this.groups={},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}storeGroup(e){this.groups[e.groupId]=e}getGroup(e){return this.groups[e]||null}getGroups(){return Object.values(this.groups)}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on("RoomState.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].removeListener("RoomState.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(r(e))return e}catch(e){}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const n="mxjssdk_memory_filter_"+e;try{r(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/user":125}],135:[function(e,t,n){"use strict";var i=e("@babel/runtime/helpers/typeof");Object.defineProperty(n,"__esModule",{value:!0}),n.WebStorageSessionStore=d;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 d(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")}d.prototype={removeEndToEndAccount:function(){this.store.removeItem(l)},getEndToEndAccount:function(){return this.store.getItem(l)},getAllEndToEndDevices:function(){for(var e=p(""),t={},n=0;n<this.store.length;++n){var i=this.store.key(n),r=i.substr(e.length);i.startsWith(e)&&(t[r]=m(this.store,i))}return t},getEndToEndDeviceTrackingStatus:function(){return m(this.store,h)},getEndToEndDeviceSyncToken:function(){return m(this.store,u)},removeEndToEndDeviceData:function(){S(this.store,p("")),S(this.store,h),S(this.store,u)},getEndToEndSessions:function(e){return m(this.store,f(e))},getAllEndToEndSessions:function(){var e,t={},n=s(v(this.store,f("")));try{for(n.s();!(e=n.n()).done;){var i=e.value;t[i.substr(f("").length)]=m(this.store,i)}}catch(e){n.e(e)}finally{n.f()}return t},removeAllEndToEndSessions:function(){S(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.substr(e.length,43),sessionId:i.substr(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(){S(this.store,c+"inboundgroupsessions/")},getAllEndToEndRooms:function(){var e,t={},n=s(v(this.store,y("")));try{for(n.s();!(e=n.n()).done;){var i=e.value;t[i.substr(y("").length)]=m(this.store,i)}}catch(e){n.e(e)}finally{n.f()}return t},removeAllEndToEndRooms:function(){S(this.store,y(""))},setLocalTrustedBackupPubKey:function(e){this.store.setItem(g,e)},getLocalTrustedBackupPubKey:function(){return this.store.getItem(g)}};var l=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 y(e){return c+"rooms/"+e}function m(e,t){try{return JSON.parse(e.getItem(t))}catch(e){E("Failed to get key %s: %s",t,e),E(e.stack)}return null}function v(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 S(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 E(){false}},{"../../logger":108,"../../utils":141,"@babel/runtime/helpers/typeof":14}],136:[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}storeGroup(e){}getGroup(e){return null}getGroups(){return[]}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()}}},{}],137:[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");var o;!function(e){e.Invite="invite",e.Leave="leave",e.Join="join"}(o=n.Category||(n.Category={}));function s(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.groups={invite:{},join:{},leave:{}},this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e,t=!1){this.accumulateRooms(e,t),this.accumulateGroups(e),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,o.Invite,e.rooms.invite[n],t)})),e.rooms.join&&Object.keys(e.rooms.join).forEach((n=>{this.accumulateRoom(n,o.Join,e.rooms.join[n],t)})),e.rooms.leave&&Object.keys(e.rooms.leave).forEach((n=>{this.accumulateRoom(n,o.Leave,e.rooms.leave[n],t)})))}accumulateRoom(e,t,n,r=!1){switch(t){case o.Invite:this.accumulateInviteState(e,n);break;case o.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,n,r);break;case o.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=>{e.content[t]["m.read"]&&Object.keys(e.content[t]["m.read"]).forEach((n=>{i._readReceipts[n]={data:e.content[t]["m.read"][n],eventId:t}}))}))})),t.timeline&&t.timeline.limited&&(i._timeline=[]),t.state&&t.state.events&&t.state.events.forEach((e=>{s(i._currentState,e)})),t.timeline&&t.timeline.events&&t.timeline.events.forEach(((e,r)=>{let o;if(s(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}}}accumulateGroups(e){e.groups&&(e.groups.invite&&Object.keys(e.groups.invite).forEach((t=>{this.accumulateGroup(t,o.Invite,e.groups.invite[t])})),e.groups.join&&Object.keys(e.groups.join).forEach((t=>{this.accumulateGroup(t,o.Join,e.groups.join[t])})),e.groups.leave&&Object.keys(e.groups.leave).forEach((t=>{this.accumulateGroup(t,o.Leave,e.groups.leave[t])})))}accumulateGroup(e,t,n){for(const t of[o.Invite,o.Leave,o.Join])delete this.groups[t][e];this.groups[t][e]=n}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 a={type:"m.receipt",room_id:n,content:{}};Object.keys(i._readReceipts).forEach((e=>{const t=i._readReceipts[e];a.content[t.eventId]||(a.content[t.eventId]={"m.read":{}}),a.content[t.eventId]["m.read"][e]=t.data})),Object.keys(a.content).length>0&&o.ephemeral.events.push(a),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)),s(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,groupsData:this.groups,accountData:n}}getNextBatchToken(){return this.nextBatch}}},{"./logger":108,"./utils":141}],138:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.SyncState=void 0,function(e){e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING"}(n.SyncState||(n.SyncState={}))},{}],139:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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=void 0;const a=e("./models/user"),c=e("./models/room"),d=e("./models/group"),l=o(e("./utils")),u=e("./filter"),h=e("./models/event-timeline"),g=e("./pushprocessor"),p=e("./logger"),f=e("./errors"),y=e("./client"),m=e("./sync.api"),v=e("./sync-accumulator"),S=e("./@types/event");function E(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function b(...e){p.logger.log(...e)}function _(e,t){const n=new a.User(t);return e.reEmitter.reEmit(n,["User.avatarUrl","User.displayName","User.presence","User.currentlyActive","User.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=()=>{b("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||y.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=!0===this.opts.experimentalThreadSupport,t.canResetEntireTimeline||(t.canResetEntireTimeline=e=>!1),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),["Room.timeline","Room.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,["Room.name","Room.timeline","Room.redaction","Room.redactionCancelled","Room.receipt","Room.tags","Room.timelineReset","Room.localEchoUpdated","Room.accountData","Room.myMembership","Room.replaceEvent"]),this.registerStateListeners(r),r}createGroup(e){const t=this.client,n=new d.Group(e);return t.reEmitter.reEmit(n,["Group.profile","Group.myMembership"]),t.store.storeGroup(n),n}registerStateListeners(e){const t=this.client;t.reEmitter.reEmit(e.currentState,["RoomState.events","RoomState.members","RoomState.newMember"]),e.currentState.on("RoomState.newMember",(function(e,n,i){i.user=t.getUser(i.userId),t.reEmitter.reEmit(i,["RoomMember.name","RoomMember.typing","RoomMember.powerLevel","RoomMember.membership"])}))}deregisterStateListeners(e){e.currentState.removeAllListeners("RoomState.events"),e.currentState.removeAllListeners("RoomState.members"),e.currentState.removeAllListeners("RoomState.newMember")}syncLeftRooms(){const e=this.client,t=new u.Filter(this.client.credentials.userId);t.setTimelineLimit(1),t.setIncludeLeaveRooms(!0);const n=this.opts.pollTimeout+8e4,i={timeout:0};return e.getOrCreateFilter(E(e.credentials.userId,"LEFT_ROOMS"),t).then((function(t){return i.filter=t,e.http.authedRequest(void 0,"GET","/sync",i,void 0,n)})).then((t=>{let n=[];t.rooms&&t.rooms.leave&&(n=this.mapSyncResponseToRoomArray(t.rooms.leave));const i=[];return n.forEach((t=>{const n=t.room;if(i.push(n),!t.isBrandNewRoom)return;t.timeline=t.timeline||{};const r=this.mapSyncEventsFormat(t.timeline,n),[o,s]=this.client.partitionThreadedEvents(r),a=this.mapSyncEventsFormat(t.state,n);n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,h.EventTimeline.BACKWARDS),this.processRoomEvents(n,a,o),this.processThreadEvents(n,s),n.recalculate(),e.store.storeRoom(n),e.emit("Room",n),this.processEventsForNotifs(n,r)})),i}))}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=_(t,e.getContent().user_id),n.setPresenceEvent(e),t.store.storeUser(n)),t.emit("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("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,"GET","/events",{room_id:e.roomId,timeout:3e4,from:t},void 0,5e4).then((t=>{if(this._peekRoom!==e)return void b("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=_(this.client,e.getContent().user_id),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit("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=>{p.logger.error("[%s] Peek poll failed: %s",e.roomId,n),setTimeout((()=>{this.peekPoll(e,t)}),3e4)})):b("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(m.SyncState.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&&(p.logger.warn("Token no longer valid - assuming logout"),this.stop(),!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{b("Getting push rules...");const t=yield e.getPushRules();b("Got push rules"),e.pushRules=t}catch(e){if(p.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return b("Waiting for saved sync before retrying push rules..."),yield this.recoverFromSyncStartupError(n,e),void r()}a()})),o=()=>{const t=new u.Filter(e.credentials.userId);return t.setTimelineLimit(this.opts.initialSyncLimit),t},a=()=>s(this,void 0,void 0,(function*(){if(b("Checking lazy load status..."),this.opts.lazyLoadMembers&&e.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers){b("Checking server lazy load support...");(yield e.doesServerSupportLazyLoading())?(b("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=o()),this.opts.filter.setLazyLoadMembers(!0)):(b("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)}b("Checking whether lazy loading has changed in store...");if(yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const e=f.InvalidStoreError.TOGGLED_LAZY_LOADING,t=new f.InvalidStoreError(e,!!this.opts.lazyLoadMembers);return this.updateSyncState(m.SyncState.Error,{error:t}),void p.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&this.opts.crypto&&this.opts.crypto.enableLazyLoading();try{b("Storing client options..."),yield this.client.storeClientOptions(),b("Stored client options")}catch(e){throw p.logger.error("Storing client options failed",e),e}c()})),c=()=>s(this,void 0,void 0,(function*(){let t,r;b("Getting filter..."),t=this.opts.filter?this.opts.filter:o();try{r=yield e.getOrCreateFilter(E(e.credentials.userId),t)}catch(e){if(p.logger.error("Getting filter failed",e),this.shouldAbortSync(e))return;return b("Waiting for saved sync before retrying filter..."),yield this.recoverFromSyncStartupError(n,e),void c()}e.resetNotifTimelineSet(),null===this.currentSyncRequest&&(b("Sending first sync request..."),this.currentSyncRequest=this.doSyncRequest({filterId:r},i)),b("Waiting for saved sync before starting sync processing..."),yield n,this.doSync({filterId:r})}));e.isGuest()?this.doSync({}):(b("Getting saved sync token..."),n=e.store.getSavedSyncToken().then((t=>(b("Got saved sync token"),i=t,b("Getting saved sync..."),e.store.getSavedSync()))).then((e=>{if(b(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)})).catch((e=>{p.logger.error("Getting saved sync failed",e)})),r())}stop(){b("SyncApi.stop"),t.window&&t.window.removeEventListener&&t.window.removeEventListener("online",this.onOnline,!1),this.running=!1,this.currentSyncRequest&&this.currentSyncRequest.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*(){b("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,groups:e.groupsData,account_data:{events:e.accountData}};try{yield this.processSyncResponse(n,i)}catch(e){p.logger.error("Error processing cached sync",e.stack||e)}this.storeIsInvalid||this.updateSyncState(m.SyncState.Prepared,n)}))}doSync(e){return s(this,void 0,void 0,(function*(){const t=this.client;if(!this.running)return b("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(m.SyncState.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){p.logger.error("Caught /sync error",e.stack||e),this.client.emit("sync.unexpectedError",e)}r.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(m.SyncState.Prepared,r),e.hasSyncedBefore=!0),this.opts.crypto&&(yield this.opts.crypto.onSyncCompleted(r)),this.updateSyncState(m.SyncState.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,"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 b("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(m.SyncState.Stopped);p.logger.error("/sync error %s",e),p.logger.error(e),this.shouldAbortSync(e)||(this.failedSyncCount++,p.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),b("Starting keep-alive"),this.startKeepAlives().then((e=>{e&&this.getSyncState()===m.SyncState.Error&&this.updateSyncState(m.SyncState.Catchup,{oldSyncToken:null,nextSyncToken:null,catchingUp:!0}),this.doSync(t)})),this.currentSyncRequest=null,this.updateSyncState(this.failedSyncCount>=3?m.SyncState.Error:m.SyncState.Reconnecting,{error:e}))}processSyncResponse(e,t){return s(this,void 0,void 0,(function*(){const n=this.client;if(t.presence&&Array.isArray(t.presence.events)&&t.presence.events.map(n.getEventMapper()).forEach((function(e){let t=n.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=_(n,e.getSender()),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)})),t.account_data&&Array.isArray(t.account_data.events)){const e=t.account_data.events.map(n.getEventMapper()),i=e.reduce(((e,t)=>(e[t.getId()]=n.store.getAccountData(t.getType()),e)),{});n.store.storeAccountDataEvents(e),e.forEach((function(e){if(e.getType()===S.EventType.PushRules){const t=e.getContent();n.pushRules=g.PushProcessor.rewriteDefaultRules(t)}const t=i[e.getId()];return n.emit("accountData",e,t),e}))}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){const e=[];t.to_device.events.map(n.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 i=t.getContent();if("m.room.message"!=t.getType()||"m.bad.encrypted"!=i.msgtype){if("m.key.verification.start"===t.getType()||"m.key.verification.request"===t.getType()){const n=i.transaction_id;e.includes(n)&&t.flagCancelled()}n.emit("toDeviceEvent",t)}else p.logger.log("Ignoring undecryptable to-device event from "+t.getSender())}))}else this.catchingUp=!1;t.groups&&(t.groups.invite&&this.processGroupSyncEntry(t.groups.invite,v.Category.Invite),t.groups.join&&this.processGroupSyncEntry(t.groups.join,v.Category.Join),t.groups.leave&&this.processGroupSyncEntry(t.groups.leave,v.Category.Leave));let i=[],r=[],o=[];if(t.rooms&&(t.rooms.invite&&(i=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(r=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(o=this.mapSyncResponseToRoomArray(t.rooms.leave))),this.notifEvents=[],i.forEach((e=>{const t=e.room,i=this.mapSyncEventsFormat(e.invite_state,t);this.processRoomEvents(t,i),e.isBrandNewRoom&&(t.recalculate(),n.store.storeRoom(t),n.emit("Room",t)),i.forEach((function(e){n.emit("event",e)})),t.updateMyMembership("invite")})),yield l.promiseMapSeries(r,(t=>s(this,void 0,void 0,(function*(){const i=t.room,r=this.mapSyncEventsFormat(t.state,i),o=this.mapSyncEventsFormat(t.timeline,i,!1),a=this.mapSyncEventsFormat(t.ephemeral),d=this.mapSyncEventsFormat(t.account_data),u=n.isRoomEncrypted(i.roomId);if(t.unread_notifications&&(i.setUnreadNotificationCount(c.NotificationCountType.Total,t.unread_notifications.notification_count),(!u||u&&i.getUnreadNotificationCount(c.NotificationCountType.Highlight)<=0)&&i.setUnreadNotificationCount(c.NotificationCountType.Highlight,t.unread_notifications.highlight_count)),t.timeline=t.timeline||{},t.isBrandNewRoom)i.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,h.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(i.getTimelineForEvent(t)){b("Already have event "+t+" in limited sync - not resetting"),r=!1,o.splice(0,e);break}}r&&(this.deregisterStateListeners(i),i.resetLiveTimeline(t.timeline.prev_batch,this.opts.canResetEntireTimeline(i.roomId)?null:e.oldSyncToken),n.resetNotifTimelineSet(),this.registerStateListeners(i))}const[g,p]=this.client.partitionThreadedEvents(o);this.processRoomEvents(i,r,g,e.fromCache),this.processThreadEvents(i,p),t.summary&&i.setSummary(t.summary),i.addEphemeralEvents(a),i.addAccountData(d),i.recalculate(),t.isBrandNewRoom&&(n.store.storeRoom(i),n.emit("Room",i)),this.processEventsForNotifs(i,o);const f=e=>s(this,void 0,void 0,(function*(){if(n.emit("event",e),e.isState()&&"m.room.encryption"==e.getType()&&this.opts.crypto&&(yield this.opts.crypto.onCryptoEvent(e)),e.isState()&&"im.vector.user_status"===e.getType()){let t=n.store.getUser(e.getStateKey());t?t.unstable_updateStatusMessage(e):(t=_(n,e.getStateKey()),t.unstable_updateStatusMessage(e),n.store.storeUser(t))}}));yield l.promiseMapSeries(r,f),yield l.promiseMapSeries(g,f),yield l.promiseMapSeries(p,f),a.forEach((function(e){n.emit("event",e)})),d.forEach((function(e){n.emit("event",e)})),i.updateMyMembership("join"),i.decryptCriticalEvents()})))),o.forEach((e=>{const t=e.room,i=this.mapSyncEventsFormat(e.state,t),r=this.mapSyncEventsFormat(e.timeline,t),o=this.mapSyncEventsFormat(e.account_data),[s,a]=this.client.partitionThreadedEvents(r);this.processRoomEvents(t,i,s),this.processThreadEvents(t,a),t.addAccountData(o),t.recalculate(),e.isBrandNewRoom&&(n.store.storeRoom(t),n.emit("Room",t)),this.processEventsForNotifs(t,r),i.forEach((function(e){n.emit("event",e)})),s.forEach((function(e){n.emit("event",e)})),a.forEach((function(e){n.emit("event",e)})),o.forEach((function(e){n.emit("event",e)})),t.updateMyMembership("leave")})),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((function(e){n.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["org.matrix.msc2732.device_unused_fallback_key_types"]){const e=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,"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(m.SyncState.Error,{error:n}))}))}processGroupSyncEntry(e,t){for(const n of Object.keys(e)){const i=e[n];let r=this.client.store.getGroup(n);const o=null===r;null===r&&(r=this.createGroup(n)),i.profile&&r.setProfile(i.profile.name,i.profile.avatar_url),i.inviter&&r.setInviter({userId:i.inviter}),r.setMyMembership(t),o&&this.client.emit("Group",r)}}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){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)}processThreadEvents(e,t){return this.client.processThreadEvents(e,t)}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("sync",this.syncState,n,t)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/event":59,"./client":66,"./errors":101,"./filter":104,"./logger":108,"./models/event-timeline":115,"./models/group":117,"./models/room":122,"./models/user":125,"./pushprocessor":126,"./sync-accumulator":137,"./sync.api":138,"./utils":141}],140:[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){for(let t=0;t<r.length;t++)if(r[t].getId()==e){i=t;break}if(void 0===i)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);if(t)return n(t),Promise.resolve(t);return 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)||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(!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":108,"./models/event-timeline":115}],141:[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.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.extend=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"));function a(e){return"string"==typeof e?(0,o.default)(e.normalize("NFD").replace(c,"")):""}n.encodeParams=function(e){return new URLSearchParams(e).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,r;if(n){for(i=e.length-1;i>=0;i--)if(t(e[i],i,e))return r=e[i],e.splice(i,1),r}else for(i=0;i<e.length;i++)if(t(e[i],i,e))return r=e[i],e.splice(i,1),r;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)=>p(e[0],t[0]))),n},n.extend=function(...e){const t=e[0]||{};for(let n=1;n<e.length;n++){const i=e[n];if(i)for(const e in i)t[e]=i[e]}return t},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=a,n.removeDirectionOverrideChars=function(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""},n.normalize=function(e){return a(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()};const c=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\s]/g;function d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let l;function u(e,t,i=n.DEFAULT_ALPHABET){return e.padEnd(t,i[0])}function h(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),h(o,t)+t[s]}function g(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 p(e,t){return e<t?-1:e===t?0:1}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.substr(0,e.length-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 new Promise((t=>t(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){l=e},n.getCrypto=function(){return l},n.DEFAULT_ALPHABET=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})(),n.alphabetPad=u,n.baseToString=h,n.stringToBase=g,n.averageBetweenStrings=function(e,t,i=n.DEFAULT_ALPHABET){const r=Math.max(e.length,t.length),o=g(u(e,r,i),i),s=g(u(t,r,i),i),a=(o+s)/BigInt(2);return a===o||a==s?h(a,i)+i[0]:h(a,i)},n.nextString=function(e,t=n.DEFAULT_ALPHABET){return h(g(e,t)+BigInt(1),t)},n.prevString=function(e,t=n.DEFAULT_ALPHABET){return h(g(e,t)-BigInt(1),t)},n.lexicographicCompare=p;const f=new Intl.Collator;n.compare=function(e,t){return f.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}},{"p-retry":38,unhomoglyph:55}],142:[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),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}: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.MatrixCall=n.CallError=n.CallErrorCode=n.CallEvent=n.CallParty=n.CallDirection=n.CallType=n.CallState=void 0;const a=e("../logger"),c=e("events"),d=o(e("../utils")),l=e("../@types/event"),u=e("../randomstring"),h=e("./callEventTypes"),g=e("./callFeed");var p,f,y,m,v,S;!function(e){e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended"}(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"}(y=n.CallDirection||(n.CallDirection={})),function(e){e.Local="local",e.Remote="remote"}(m=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"}(v=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"}(S=n.CallErrorCode||(n.CallErrorCode={}));class E extends Error{constructor(e,t,n){super(t+": "+n),this.code=e}}function b(){return Date.now().toString()+(0,u.randomString)(16)}n.CallError=E;class _ extends c.EventEmitter{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(m.Local,S.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[h.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=S.SignallingFailed,n="Signalling failed";return this.state===p.CreateOffer&&(t=S.SendInvite,n="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=S.UnknownDevices,n="Unknown devices present in the room"),this.emit(v.Error,new E(t,n,e)),void this.terminate(m.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(S.InviteTimeout,!1)}),6e4))})),this.getLocalOfferFailed=e=>{a.logger.error("Failed to get local offer",e),this.emit(v.Error,new E(S.LocalOfferFailed,"Failed to get local offer!",e)),this.terminate(m.Local,S.LocalOfferFailed,!1)},this.getUserMediaFailed=e=>{this.successor?this.successor.getUserMediaFailed(e):(a.logger.warn("Failed to get user media - ending call",e),this.emit(v.Error,new E(S.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e)),this.terminate(m.Local,S.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(v.LengthChanged,this.callLength)}),1e3))):"failed"==this.peerConn.iceConnectionState&&this.hangup(S.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",(()=>this.deleteFeedByStream(t)))},this.onDataChannel=e=>{this.emit(v.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(m.Remote,e.reason||S.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===y.Inbound?this.terminate(m.Remote,e.reason||S.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(m.Remote,S.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)d.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(v.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===h.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===h.SDPStreamMetadataPurpose.Usermedia&&e.stream.getAudioTracks().length>0))}get localUsermediaFeed(){return this.getLocalFeeds().find((e=>e.purpose===h.SDPStreamMetadataPurpose.Usermedia))}get localScreensharingFeed(){return this.getLocalFeeds().find((e=>e.purpose===h.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===h.SDPStreamMetadataPurpose.Usermedia))}get remoteScreensharingFeed(){return this.getRemoteFeeds().find((e=>e.purpose===h.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 g.CallFeed({client:this.client,roomId:this.roomId,userId:t,stream:e,purpose:n,audioMuted:i,videoMuted:r})),this.emit(v.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=h.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 g.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,stream:e,purpose:i})),this.emit(v.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();w(e.getAudioTracks(),!0);const r=this.getLocalFeeds().find((e=>e.purpose===t));r?r.setNewStream(e):(this.pushLocalFeed(new g.CallFeed({client:this.client,roomId:this.roomId,audioMuted:0===e.getAudioTracks().length,videoMuted:0===e.getVideoTracks().length,userId:i,stream:e,purpose:t}),n),this.emit(v.FeedsChanged,this.feeds))}pushLocalFeed(e,t=!0){if(this.feeds.push(e),t){const t=e.purpose===h.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}") 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(v.FeedsChanged,this.feeds)}removeLocalFeed(e){const t=e.purpose===h.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(v.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(v.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=[];for(const n of e)t.push(n[1]);return t}))}initWithInvite(e){var t;return s(this,void 0,void 0,(function*(){const n=e.getContent();this.direction=y.Inbound;(yield this.client.checkTurnServers())||a.logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");const i=n[h.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(m.Local,S.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(m.Local,S.SetRemoteDescription,!1);this.setState(p.Ringing),e.getLocalAge()&&setTimeout((()=>{this.state==p.Ringing&&(a.logger.debug("Call invite has expired. Hanging up."),this.hangupParty=m.Remote,this.setState(p.Ended),this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit(v.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):d.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 g.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:e,purpose:h.SDPStreamMetadataPurpose.Usermedia,audioMuted:0===e.getAudioTracks().length,videoMuted:0===e.getVideoTracks().length})];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(v.Replaced,e),this.hangup(S.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(a.logger.debug("Ending call "+this.callId),this.terminate(m.Local,e,!t),this.state===p.WaitLocalMedia)return;const n={};(this.opponentVersion&&this.opponentVersion>=1||e!==S.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(S.UserHangup,!0);a.logger.debug("Rejecting call: "+this.callId),this.terminate(m.Local,S.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;a.logger.debug(`Upgrading call: audio?=${n} video?=${i}`);const r=yield this.client.getMediaHandler().getUserMediaStream(n,i);if(n&&i){if(this.hasLocalUserMediaAudioTrack)return;if(this.hasLocalUserMediaVideoTrack)return;this.pushNewLocalFeed(r,h.SDPStreamMetadataPurpose.Usermedia)}else if(n){if(this.hasLocalUserMediaAudioTrack)return;const e=r.getAudioTracks()[0];this.localUsermediaStream.addTrack(e),this.peerConn.addTrack(e,this.localUsermediaStream)}else if(i){if(this.hasLocalUserMediaVideoTrack)return;const e=r.getVideoTracks()[0];this.localUsermediaStream.addTrack(e),this.peerConn.addTrack(e,this.localUsermediaStream)}}catch(e){a.logger.error("Failed to upgrade the call",e),this.emit(v.Error,new E(S.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 yield 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,h.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,h.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(e){return a.logger.error("Failed to get screen-sharing stream:",e),!1}}))}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(v.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(){var e,t;this.sendVoipEvent(l.EventType.CallSDPStreamMetadataChangedPrefix,{[h.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()});const n=(null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted())||this.remoteOnHold,i=(null===(t=this.localUsermediaFeed)||void 0===t?void 0:t.isVideoMuted())||this.remoteOnHold;w(this.localUsermediaStream.getAudioTracks(),!n),w(this.localUsermediaStream.getVideoTracks(),!i)}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},[h.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=S.SendAnswer,n="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=S.UnknownDevices,n="Unknown devices present in the room"),this.emit(v.Error,new E(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(m.Local,S.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(m.Local,S.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[h.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(m.Local,S.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!==y.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(m.Remote,S.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===y.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[h.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,[h.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}}catch(e){a.logger.warn("Failed to complete negotiation",e)}const c=this.isLocalOnHold();o!==c&&(this.emit(v.LocalHoldUnhold,c),this.emit(v.HoldUnhold,c))}))}updateRemoteSDPStreamMetadata(e){var t,n,i;this.remoteSDPStreamMetadata=d.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()[h.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(v.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(v.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===y.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(m.Local,S.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(m.Local,S.Replaced,!0),yield e.terminate(m.Local,S.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!==S.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(v.Hangup,this))}))}stopAllMedia(){a.logger.debug(`stopAllMedia (stream=${this.localUsermediaStream})`);for(const e of this.feeds)if(e.isLocal()&&e.purpose===h.SDPStreamMetadataPurpose.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===h.SDPStreamMetadataPurpose.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else for(const t of e.stream.getTracks())t.stop()}checkForErrorListener(){if(0===this.listeners("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=S.SignallingFailed,n="Signalling failed";return this.emit(v.Error,new E(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),i=new g.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:n,purpose:h.SDPStreamMetadataPurpose.Usermedia,audioMuted:0===n.getAudioTracks().length,videoMuted:0===n.getVideoTracks().length});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=y.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 w(e,t){for(let n=0;n<e.length;n++)e[n].enabled=t}n.MatrixCall=_,n.createNewMatrixCall=function(e,n,i){if("undefined"==typeof window||"undefined"==typeof document)return null;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"),null}catch(e){return a.logger.error("Exception thrown when trying to access WebRTC",e),null}const r=!!i&&i.forceTURN,o={client:e,roomId:n,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||r},s=new _(o);return e.reEmitter.reEmit(s,Object.values(v)),s}}).call(this)}).call(this,e("_process"))},{"../@types/event":59,"../logger":108,"../randomstring":127,"../utils":141,"./callEventTypes":144,"./callFeed":145,_process:39,events:28}],143:[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=void 0;const r=e("../logger"),o=e("./call"),s=e("../@types/event");n.CallEventHandler=class{constructor(e){this.evaluateEventBuffer=()=>i(this,void 0,void 0,(function*(){if("SYNCING"===this.client.getSyncState()){yield Promise.all(this.callEventBuffer.map((e=>{this.client.decryptEventIfNeeded(e)})));const e=new Set;for(const t of this.callEventBuffer)t.getType()!==s.EventType.CallAnswer&&t.getType()!==s.EventType.CallHangup||e.add(t.getContent().call_id);for(const t of this.callEventBuffer)if(t.getType()!==s.EventType.CallInvite||!e.has(t.getContent().call_id))try{yield this.handleCallEvent(t)}catch(e){r.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("Event.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){r.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("sync",this.evaluateEventBuffer),this.client.on("Room.timeline",this.onRoomTimeline)}stop(){this.client.removeListener("sync",this.evaluateEventBuffer),this.client.removeListener("Room.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 a=t.call_id?this.calls.get(t.call_id):void 0;if(n!==s.EventType.CallInvite)if(n!==s.EventType.CallCandidates)if([s.EventType.CallHangup,s.EventType.CallReject].includes(n))a?a.state!==o.CallState.Ended&&(n===s.EventType.CallHangup?a.onHangupReceived(t):a.onRejectReceived(t),this.calls.delete(t.call_id)):(a=(0,o.createNewMatrixCall)(this.client,e.getRoomId()),a&&(a.callId=t.call_id,a.initWithHangup(e),this.calls.set(t.call_id,a)));else if(a&&a.hasPeerConnection){if(e.getContent().party_id!==a.ourPartyId)switch(n){case s.EventType.CallAnswer:i?a.state===o.CallState.Ringing&&a.onAnsweredElsewhere(t):a.onAnswerReceived(e);break;case s.EventType.CallSelectAnswer:a.onSelectAnswerReceived(e);break;case s.EventType.CallNegotiate:a.onNegotiateReceived(e);break;case s.EventType.CallAssertedIdentity:case s.EventType.CallAssertedIdentityPrefix:a.onAssertedIdentityReceived(e);break;case s.EventType.CallSDPStreamMetadataChanged:case s.EventType.CallSDPStreamMetadataChangedPrefix:a.onSDPStreamMetadataChangedReceived(e)}}else r.logger.warn("Discarding an event, we don't have a call/peerConn",n);else{if(i)return;a?a.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(a&&a.state===o.CallState.Ended)return;a&&r.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(r.logger.info("Current turn creds expire in "+n+" ms"),a=(0,o.createNewMatrixCall)(this.client,e.getRoomId(),{forceTURN:this.client.forceTURN}),!a)return void r.logger.log("Incoming call ID "+t.call_id+" but this client doesn't support WebRTC");if(a.callId=t.call_id,yield a.initWithInvite(e),this.calls.set(a.callId,a),this.candidateEventsByCall.get(a.callId))for(const e of this.candidateEventsByCall.get(a.callId))a.onRemoteIceCandidatesReceived(e);let s;for(const e of this.calls.values()){const t=[o.CallState.WaitLocalMedia,o.CallState.CreateOffer,o.CallState.InviteSent].includes(e.state);if(a.roomId===e.roomId&&e.direction===o.CallDirection.Outbound&&t){s=e;break}}s?s.state===o.CallState.WaitLocalMedia||s.state===o.CallState.CreateOffer||s.callId>a.callId?(r.logger.log("Glare detected: answering incoming call "+a.callId+" and canceling outgoing call "+s.callId),s.replacedBy(a),a.answer()):(r.logger.log("Glare detected: rejecting incoming call "+a.callId+" and keeping outgoing call "+s.callId),a.hangup(o.CallErrorCode.Replaced,!0)):this.client.emit("Call.incoming",a)}}))}}},{"../@types/event":59,"../logger":108,"./call":142}],144:[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={}))},{}],145:[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.CallFeed=n.CallFeedEvent=n.SPEAKING_THRESHOLD=void 0;const r=i(e("events"));n.SPEAKING_THRESHOLD=-60;var o;!function(e){e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.VolumeChanged="volume_changed",e.Speaking="speaking"}(o=n.CallFeedEvent||(n.CallFeedEvent={}));class s extends r.default{constructor(e){super(),this.measuringVolumeActivity=!1,this.speakingThreshold=n.SPEAKING_THRESHOLD,this.speaking=!1,this.onAddTrack=()=>{this.emit(o.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(o.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(o.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(o.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(o.MuteStateChanged,this.audioMuted,this.videoMuted)}setVideoMuted(e){this.videoMuted=e,this.emit(o.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(o.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}dispose(){clearTimeout(this.volumeLooperTimeout)}}n.CallFeed=s},{events:28}],146:[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");n.MediaHandler=class{constructor(){this.userMediaStreams=[],this.screensharingStreams=[]}setAudioInput(e){this.audioInput=e}setVideoInput(e){this.videoInput=e}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){return i(this,void 0,void 0,(function*(){const n=e&&(yield this.hasAudioDevice()),i=t&&(yield this.hasVideoDevice());let o;const s=this.userMediaStreams.find((e=>n===e.getAudioTracks().length>0&&i===e.getVideoTracks().length>0));if(s)r.logger.log("Cloning user media stream",s.id),o=s.clone();else{const e=this.getUserMediaContraints(n,i);r.logger.log("Getting user media with constraints",e),o=yield navigator.mediaDevices.getUserMedia(e)}return this.userMediaStreams.push(o),o}))}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))}getScreensharingStream(e){return i(this,void 0,void 0,(function*(){let t;if(0===this.screensharingStreams.length){const n=this.getScreenshareContraints(e);if(!n)return null;e?(r.logger.debug("Getting screensharing stream using getUserMedia()",e),t=yield navigator.mediaDevices.getUserMedia(n)):(r.logger.debug("Getting screensharing stream using getDisplayMedia()"),t=yield navigator.mediaDevices.getDisplayMedia(n))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];r.logger.log("Cloning screensharing stream",e.id),t=e.clone()}return this.screensharingStreams.push(t),t}))}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=[]}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":108}]},{},[65]);