/*! For license information please see vendors~init.js.LICENSE.txt */ (window.webpackJsonp=window.webpackJsonp||[]).push([[30],[,,function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.JoinCall="io.element.join",e.HangupCall="im.vector.hangup",e.CallParticipants="io.element.participants",e.MuteAudio="io.element.mute_audio",e.UnmuteAudio="io.element.unmute_audio",e.MuteVideo="io.element.mute_video",e.UnmuteVideo="io.element.unmute_video",e.StartLiveStream="im.vector.start_live_stream",e.ScreenshareRequest="io.element.screenshare_request",e.ScreenshareStart="io.element.screenshare_start",e.ScreenshareStop="io.element.screenshare_stop",e.TileLayout="io.element.tile_layout",e.SpotlightLayout="io.element.spotlight_layout",e.OpenIntegrationManager="integration_manager_open",e.ViewRoom="io.element.view_room"}(r||(r={}))},,,,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(60);Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===r[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}}))}));var i=n(61);Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===i[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}}))}));var o=n(25);Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===o[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=n(62);Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===a[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}}))}));var s=n(21);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===s[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}}))}));var l=n(63);Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===l[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return l[e]}}))}));var c=n(64);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===c[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}}))}));var u=n(65);Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===u[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}}))}));var d=n(66);Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===d[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return d[e]}}))}));var h=n(33);Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===h[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return h[e]}}))}));var p=n(67);Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===p[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return p[e]}}))}));var m=n(68);Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===m[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return m[e]}}))}));var g=n(69);Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===g[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return g[e]}}))}));var f=n(22);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===f[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}}))}));var _=n(19);Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===_[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return _[e]}}))}));var b=n(20);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var v=n(35);Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===v[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return v[e]}}))}));var y=n(70);Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===y[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return y[e]}}))}));var E=n(71);Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===E[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return E[e]}}))}));var S=n(72);Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===S[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return S[e]}}))}));var w=n(73);Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===w[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return w[e]}}))}));var T=n(74);Object.keys(T).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===T[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return T[e]}}))}));var C=n(75);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var x=n(76);Object.keys(x).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===x[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return x[e]}}))}));var F=n(23);Object.keys(F).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===F[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return F[e]}}))}));var D=n(77);Object.keys(D).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===D[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return D[e]}}))}));var k=n(78);Object.keys(k).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===k[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return k[e]}}))}));var O=n(79);Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===O[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return O[e]}}))}));var I=n(34);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var A=n(80);Object.keys(A).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===A[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return A[e]}}))}));var R=n(81);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var N=n(82);Object.keys(N).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===N[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return N[e]}}))}));var M=n(83);Object.keys(M).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===M[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return M[e]}}))}));var P=n(84);Object.keys(P).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===P[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return P[e]}}))}));var L=n(85);Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===L[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}}))}));var B=n(86);Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===B[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}}))}));var U=n(87);Object.keys(U).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===U[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return U[e]}}))}));var j=n(88);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===j[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}}))}));var G=n(24);Object.keys(G).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===G[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return G[e]}}))}));var z=n(37);Object.keys(z).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===z[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return z[e]}}))}));var H=n(38);Object.keys(H).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===H[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return H[e]}}))}));var q=n(39);Object.keys(q).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===q[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return q[e]}}))}));var V=n(89);Object.keys(V).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===V[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return V[e]}}))}));var $=n(90);Object.keys($).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===$[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return $[e]}}))}));var K=n(36);Object.keys(K).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===K[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return K[e]}}))}));var W=n(91);Object.keys(W).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===W[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return W[e]}}))}))},,,,,,,,,,,function(e,t,n){"use strict";var r,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}_(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&_(e,"error",t,n)}(e,i,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var l=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,n,r){var i,o,a,s;if(c(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),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(i=u(e))>0&&a.length>i&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,s=l,console&&console.warn&&console.warn(s)}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 p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=h.bind(r);return i.listener=n,r.wrapFn=i,i}function m(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var l=i[e];if(void 0===l)return!1;if("function"==typeof l)o(l,this,t);else{var c=l.length,u=f(l,c);for(n=0;n=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},s.prototype.listenerCount=g,s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},,function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetApiDirection=void 0,t.invertedDirection=function(e){if(e===r.ToWidget)return r.FromWidget;if(e===r.FromWidget)return r.ToWidget;throw new Error("Invalid direction")},t.WidgetApiDirection=r,function(e){e.ToWidget="toWidget",e.FromWidget="fromWidget"}(r||(t.WidgetApiDirection=r={}))},function(e,t,n){"use strict";var r,i;Object.defineProperty(t,"__esModule",{value:!0}),t.UnstableApiVersion=t.MatrixApiVersion=t.CurrentApiVersions=void 0,t.MatrixApiVersion=r,function(e){e.Prerelease1="0.0.1",e.Prerelease2="0.0.2"}(r||(t.MatrixApiVersion=r={})),t.UnstableApiVersion=i,function(e){e.MSC2762="org.matrix.msc2762",e.MSC2871="org.matrix.msc2871",e.MSC2931="org.matrix.msc2931",e.MSC2974="org.matrix.msc2974",e.MSC2876="org.matrix.msc2876",e.MSC3819="org.matrix.msc3819",e.MSC3846="town.robin.msc3846",e.MSC3869="org.matrix.msc3869"}(i||(t.UnstableApiVersion=i={}));var o=[r.Prerelease1,r.Prerelease2,i.MSC2762,i.MSC2871,i.MSC2931,i.MSC2974,i.MSC2876,i.MSC3819,i.MSC3846,i.MSC3869];t.CurrentApiVersions=o},function(e,t,n){"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.PostmessageTransport=void 0;var i=n(17),o=n(6);function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n2&&void 0!==arguments[2]?arguments[2]:null;return this.kind===a.Event&&this.direction===e&&this.eventType===t&&("m.room.message"!==this.eventType||null===this.keyStr||this.keyStr===n)}}],i=[{key:"forStateEvent",value:function(t,n,r){n=n.replace(/#/g,"\\#"),r=null!=r?"#".concat(r):"";var i="org.matrix.msc2762.".concat(t,".state_event:").concat(n).concat(r);return e.findEventCapabilities([i])[0]}},{key:"forToDeviceEvent",value:function(t,n){var r="org.matrix.msc3819.".concat(t,".to_device:").concat(n);return e.findEventCapabilities([r])[0]}},{key:"forRoomEvent",value:function(t,n){var r="org.matrix.msc2762.".concat(t,".event:").concat(n);return e.findEventCapabilities([r])[0]}},{key:"forRoomMessageEvent",value:function(t,n){n=null==n?"":n;var r="org.matrix.msc2762.".concat(t,".event:m.room.message#").concat(n);return e.findEventCapabilities([r])[0]}},{key:"findEventCapabilities",value:function(t){var n,i=[],o=r(t);try{for(o.s();!(n=o.n()).done;){var l=n.value,c=null,u=void 0,d=null;if(l.startsWith("org.matrix.msc2762.send.event:")?(c=s.Send,d=a.Event,u=l.substring("org.matrix.msc2762.send.event:".length)):l.startsWith("org.matrix.msc2762.send.state_event:")?(c=s.Send,d=a.State,u=l.substring("org.matrix.msc2762.send.state_event:".length)):l.startsWith("org.matrix.msc3819.send.to_device:")?(c=s.Send,d=a.ToDevice,u=l.substring("org.matrix.msc3819.send.to_device:".length)):l.startsWith("org.matrix.msc2762.receive.event:")?(c=s.Receive,d=a.Event,u=l.substring("org.matrix.msc2762.receive.event:".length)):l.startsWith("org.matrix.msc2762.receive.state_event:")?(c=s.Receive,d=a.State,u=l.substring("org.matrix.msc2762.receive.state_event:".length)):l.startsWith("org.matrix.msc3819.receive.to_device:")&&(c=s.Receive,d=a.ToDevice,u=l.substring("org.matrix.msc3819.receive.to_device:".length)),null!==c&&null!==d){var h=u.startsWith("m.room.message#")||d===a.State,p=null;if(u.includes("#")&&h){var m=u.split("#"),g=m.findIndex((function(e){return!e.endsWith("\\")}));u=m.slice(0,g+1).map((function(e){return e.endsWith("\\")?e.substring(0,e.length-1):e})).join("#"),p=m.slice(g+1).join("#")}i.push(new e(c,u,d,p,l))}}}catch(e){o.e(e)}finally{o.f()}return i}}],n&&o(t.prototype,n),i&&o(t,i),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.WidgetEventCapability=l},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Symbols=void 0,t.Symbols=r,function(e){e.AnyRoom="*"}(r||(t.Symbols=r={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));class r{constructor(e){this.obj=e}get(e,t){const n=this.obj[e];return void 0!==n?n:this.obj[null!=t?t:(r=e,r.replace(/._./g,(e=>`${e[0]}${e[2].toUpperCase()}`)))];var r}toJSON(){return this.obj}}},,,,,,,function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.MatrixWidgetType=void 0,t.MatrixWidgetType=r,function(e){e.Custom="m.custom",e.JitsiMeet="m.jitsi",e.Stickerpicker="m.stickerpicker"}(r||(t.MatrixWidgetType=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.BuiltInModalButtonID=void 0,t.BuiltInModalButtonID=r,function(e){e.Close="m.close"}(r||(t.BuiltInModalButtonID=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.VideoConferenceCapabilities=t.StickerpickerCapabilities=t.MatrixCapabilities=void 0,t.getTimelineRoomIDFromCapability=function(e){return e.substring(e.indexOf(":")+1)},t.isTimelineCapability=function(e){return null==e?void 0:e.startsWith("org.matrix.msc2762.timeline:")},t.isTimelineCapabilityFor=function(e,t){return e==="org.matrix.msc2762.timeline:".concat(t)},t.MatrixCapabilities=r,function(e){e.Screenshots="m.capability.screenshot",e.StickerSending="m.sticker",e.AlwaysOnScreen="m.always_on_screen",e.RequiresClient="io.element.requires_client",e.MSC2931Navigate="org.matrix.msc2931.navigate",e.MSC3846TurnServers="town.robin.msc3846.turn_servers"}(r||(t.MatrixCapabilities=r={}));var i=[r.StickerSending];t.StickerpickerCapabilities=i;var o=[r.AlwaysOnScreen];t.VideoConferenceCapabilities=o},function(e,t,n){"use strict";function r(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 i(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 i(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function m(e,t){if(l.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return G(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return O(this,t,n);case"utf8":case"utf-8":return x(this,t,n);case"ascii":return D(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function f(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=l.from(t,r)),l.isBuffer(t))return 0===t.length?-1:b(e,t,n,r,i);if("number"==typeof t)return t&=255,l.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,i){var o,a=1,s=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,l/=2,n/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var u=-1;for(o=n;os&&(n=s-l),o=n;o>=0;o--){for(var d=!0,h=0;hi&&(r=i):r=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function C(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function x(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+d<=n)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(o=e[i+1]))&&(l=(31&c)<<6|63&o)>127&&(u=l);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(l=(15&c)<<12|(63&o)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(l=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=d}return function(e){var t=e.length;if(t<=F)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},l.prototype.compare=function(e,t,n,r,i){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),s=Math.min(o,a),c=this.slice(r,i),u=e.slice(t,n),d=0;di)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return y(this,e,t,n);case"ascii":return E(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return w(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var F=4096;function D(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;ir)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,r,i,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function M(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,r,o){return o||P(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,o){return o||P(e,0,n,8),i.write(e,t,n,r,52,8),n+8}l.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(i*=256);)r+=this[e+--t]*i;return r},l.prototype.readUInt8=function(e,t){return t||A(e,1,this.length),this[e]},l.prototype.readUInt16LE=function(e,t){return t||A(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUInt16BE=function(e,t){return t||A(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUInt32LE=function(e,t){return t||A(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUInt32BE=function(e,t){return t||A(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||A(e,t,this.length);for(var r=this[e],i=1,o=0;++o=(i*=128)&&(r-=Math.pow(2,8*t)),r},l.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||A(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return t||A(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){t||A(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){t||A(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return t||A(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return t||A(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readFloatLE=function(e,t){return t||A(e,4,this.length),i.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return t||A(e,4,this.length),i.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return t||A(e,8,this.length),i.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return t||A(e,8,this.length),i.read(this,e,!1,52,8)},l.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||R(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+n},l.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,255,0),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):M(this,e,t,!0),t+4},l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},l.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);R(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},l.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);R(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,127,-128),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):M(this,e,t,!0),t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},l.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!l.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=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 z(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(14))},,,,function(e,t,n){"use strict";t.byteLength=function(e){var t=c(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,r=c(e),a=r[0],s=r[1],l=new o(function(e,t,n){return 3*(t+n)/4-n}(0,a,s)),u=0,d=s>0?a-4:a;for(n=0;n>16&255,l[u++]=t>>8&255,l[u++]=255&t;2===s&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,l[u++]=255&t);1===s&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t);return l},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],a=16383,s=0,l=n-i;sl?l:s+a));1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};for(var r=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,l=a.length;s0)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 u(e,t,n){for(var i,o,a=[],s=t;s>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,l=(1<>1,u=-7,d=n?i-1:0,h=n?-1:1,p=e[t+d];for(d+=h,o=p&(1<<-u)-1,p>>=-u,u+=s;u>0;o=256*o+e[t+d],d+=h,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=r;u>0;a=256*a+e[t+d],d+=h,u-=8);if(0===o)o=1-c;else{if(o===l)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,r),o-=c}return(p?-1:1)*a*Math.pow(2,o-r)},t.write=function(e,t,n,r,i,o){var a,s,l,c=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:o-1,m=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),(t+=a+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(a++,l/=2),a+d>=u?(s=0,a=u):a+d>=1?(s=(t*l-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[n+p]=255&s,p+=m,s/=256,i-=8);for(a=a<0;e[n+p]=255&a,p+=m,a/=256,c-=8);e[n+p-m]|=128*g}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetApi=void 0;var i=n(17),o=n(19),a=n(20),s=n(21),l=n(22),c=n(23),u=n(33),d=n(34),h=n(24),p=n(25);function m(){m=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},"")}catch(e){l=function(e,t,n){return e[t]=n}}function c(e,t,n,r){var i=t&&t.prototype instanceof h?t:h,o=Object.create(i.prototype),a=new C(r||[]);return o._invoke=function(e,t,n){var r="suspendedStart";return function(i,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw o;return F()}for(n.method=i,n.arg=o;;){var a=n.delegate;if(a){var s=S(a,n);if(s){if(s===d)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,a),o}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var d={};function h(){}function p(){}function g(){}var f={};l(f,o,(function(){return this}));var _=Object.getPrototypeOf,b=_&&_(_(x([])));b&&b!==t&&n.call(b,o)&&(f=b);var v=g.prototype=h.prototype=Object.create(f);function y(e){["next","throw","return"].forEach((function(t){l(e,t,(function(e){return this._invoke(t,e)}))}))}function E(e,t){function i(o,a,s,l){var c=u(e[o],e,a);if("throw"!==c.type){var d=c.arg,h=d.value;return h&&"object"==r(h)&&n.call(h,"__await")?t.resolve(h.__await).then((function(e){i("next",e,s,l)}),(function(e){i("throw",e,s,l)})):t.resolve(h).then((function(e){d.value=e,s(d)}),(function(e){return i("throw",e,s,l)}))}l(c.arg)}var o;this._invoke=function(e,n){function r(){return new t((function(t,r){i(e,n,t,r)}))}return o=o?o.then(r,r):r()}}function S(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method))return d;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,d;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,d):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,d)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function x(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var s=n.call(o,"catchLoc"),l=n.call(o,"finallyLoc");if(s&&l){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),T(n),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;T(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:x(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),d}},e}function g(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function f(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var o=e.apply(t,n);function a(e){g(o,r,i,a,s,"next",e)}function s(e){g(o,r,i,a,s,"throw",e)}a(void 0)}))}}function _(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,E),(e=g.call(this)).clientOrigin=n,S(y(e),"transport",void 0),S(y(e),"capabilitiesFinished",!1),S(y(e),"supportsMSC2974Renegotiate",!1),S(y(e),"requestedCapabilities",[]),S(y(e),"approvedCapabilities",void 0),S(y(e),"cachedClientVersions",void 0),S(y(e),"turnServerWatchers",0),!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return e.transport=new s.PostmessageTransport(o.WidgetApiDirection.FromWidget,t,window.parent,window),e.transport.targetOrigin=n,e.transport.on("message",e.handleMessage.bind(y(e))),e}return t=E,n=[{key:"hasCapability",value:function(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}},{key:"requestCapability",value:function(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}},{key:"requestCapabilities",value:function(e){var t=this;e.forEach((function(e){return t.requestCapability(e)}))}},{key:"requestCapabilityForRoomTimeline",value:function(e){this.requestCapability("org.matrix.msc2762.timeline:".concat(e))}},{key:"requestCapabilityToSendState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Send,e,t).raw)}},{key:"requestCapabilityToReceiveState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Receive,e,t).raw)}},{key:"requestCapabilityToSendToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Receive,e).raw)}},{key:"requestOpenIDConnectToken",value:function(){var e=this;return new Promise((function(t,n){e.transport.sendComplete(l.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then((function(r){var i=r.response;i.state===c.OpenIDRequestState.Allowed?t(i):i.state===c.OpenIDRequestState.Blocked?n(new Error("User declined to verify their identity")):i.state===c.OpenIDRequestState.PendingUserConfirmation?e.on("action:".concat(l.WidgetApiToWidgetAction.OpenIDCredentials),(function o(a){a.preventDefault();var s=a.detail;s.data.original_request_id===r.requestId&&(s.data.state===c.OpenIDRequestState.Allowed?(t(s.data),e.transport.reply(s,{})):s.data.state===c.OpenIDRequestState.Blocked?(n(new Error("User declined to verify their identity")),e.transport.reply(s,{})):(n(new Error("Invalid state on reply: "+i.state)),e.transport.reply(s,{error:{message:"Invalid state"}})),e.off("action:".concat(l.WidgetApiToWidgetAction.OpenIDCredentials),o))})):n(new Error("Invalid state: "+i.state))})).catch(n)}))}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(l.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(l.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(e){return this.transport.send(l.WidgetApiFromWidgetAction.SendSticker,e).then()}},{key:"setAlwaysOnScreen",value:function(e){return this.transport.send(l.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:e}).then((function(e){return e.success}))}},{key:"openModalWidget",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:u.MatrixWidgetType.Custom;return this.transport.send(l.WidgetApiFromWidgetAction.OpenModalWidget,{type:i,url:e,name:t,buttons:n,data:r}).then()}},{key:"closeModalWidget",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.transport.send(l.WidgetApiFromWidgetAction.CloseModalWidget,e).then()}},{key:"sendRoomEvent",value:function(e,t,n){return this.transport.send(l.WidgetApiFromWidgetAction.SendEvent,{type:e,content:t,room_id:n})}},{key:"sendStateEvent",value:function(e,t,n,r){return this.transport.send(l.WidgetApiFromWidgetAction.SendEvent,{type:e,content:n,state_key:t,room_id:r})}},{key:"sendToDevice",value:function(e,t,n){return this.transport.send(l.WidgetApiFromWidgetAction.SendToDevice,{type:e,encrypted:t,messages:n})}},{key:"readRoomEvents",value:function(e,t,n,r){var i={type:e,msgtype:n};return void 0!==t&&(i.limit=t),r&&(r.includes(p.Symbols.AnyRoom)?i.room_ids=p.Symbols.AnyRoom:i.room_ids=r),this.transport.send(l.WidgetApiFromWidgetAction.MSC2876ReadEvents,i).then((function(e){return e.events}))}},{key:"readEventRelations",value:(i=f(m().mark((function e(t,n,r,i,o,s,c,u){var d;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(e.sent.includes(a.UnstableApiVersion.MSC3869)){e.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return d={event_id:t,rel_type:r,event_type:i,room_id:n,to:c,from:s,limit:o,direction:u},e.abrupt("return",this.transport.send(l.WidgetApiFromWidgetAction.MSC3869ReadRelations,d));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t,n,r,o,a,s,l){return i.apply(this,arguments)})},{key:"readStateEvents",value:function(e,t,n,r){var i={type:e,state_key:void 0===n||n};return void 0!==t&&(i.limit=t),r&&(r.includes(p.Symbols.AnyRoom)?i.room_ids=p.Symbols.AnyRoom:i.room_ids=r),this.transport.send(l.WidgetApiFromWidgetAction.MSC2876ReadEvents,i).then((function(e){return e.events}))}},{key:"setModalButtonEnabled",value:function(e,t){if(e===d.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(l.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:e,enabled:t}).then()}},{key:"navigateTo",value:function(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(l.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:e}).then()}},{key:"getTurnServers",value:function(){var e,t=this;return(e=m().mark((function e(){var n,r;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=function(){var e=f(m().mark((function e(r){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r.preventDefault(),n(r.detail.data),e.next=4,t.transport.reply(r.detail,{});case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.on("action:".concat(l.WidgetApiToWidgetAction.UpdateTurnServers),r),0!==t.turnServerWatchers){e.next=12;break}return e.prev=3,e.next=6,w(t.transport.send(l.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(3),t.off("action:".concat(l.WidgetApiToWidgetAction.UpdateTurnServers),r),e.t0;case 12:t.turnServerWatchers++,e.prev=13;case 14:return e.next=17,w(new Promise((function(e){return n=e})));case 17:return e.next=19,e.sent;case 19:e.next=14;break;case 21:if(e.prev=21,t.off("action:".concat(l.WidgetApiToWidgetAction.UpdateTurnServers),r),t.turnServerWatchers--,0!==t.turnServerWatchers){e.next=27;break}return e.next=27,w(t.transport.send(l.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return e.finish(21);case 28:case"end":return e.stop()}}),e,null,[[3,8],[13,,21,28]])})),function(){return new T(e.apply(this,arguments))})()}},{key:"start",value:function(){var e=this;this.transport.start(),this.getClientVersions().then((function(t){t.includes(a.UnstableApiVersion.MSC2974)&&(e.supportsMSC2974Renegotiate=!0)}))}},{key:"handleMessage",value:function(e){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case l.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case l.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(e.detail);case l.WidgetApiToWidgetAction.UpdateVisibility:case l.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:a.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var e=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(l.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then((function(t){return e.cachedClientVersions=t.supported_versions,t.supported_versions})).catch((function(e){return console.warn("non-fatal error getting supported client versions: ",e),[]}))}},{key:"handleCapabilities",value:function(e){var t=this;return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then((function(n){return n.includes(a.UnstableApiVersion.MSC2871)?t.once("action:".concat(l.WidgetApiToWidgetAction.NotifyCapabilities),(function(e){t.approvedCapabilities=e.detail.data.approved,t.emit("ready")})):t.emit("ready"),t.capabilitiesFinished=!0,t.transport.reply(e,{capabilities:t.requestedCapabilities})}))}}],n&&_(t.prototype,n),r&&_(t,r),Object.defineProperty(t,"prototype",{writable:!1}),E}(i.EventEmitter);t.WidgetApi=x},function(e,t,n){"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ClientWidgetApi=void 0;var i=n(17),o=n(21),a=n(19),s=n(22),l=n(35),c=n(20),u=n(24),d=n(23),h=n(36),p=n(25);function m(){m=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},"")}catch(e){l=function(e,t,n){return e[t]=n}}function c(e,t,n,r){var i=t&&t.prototype instanceof h?t:h,o=Object.create(i.prototype),a=new C(r||[]);return o._invoke=function(e,t,n){var r="suspendedStart";return function(i,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw o;return F()}for(n.method=i,n.arg=o;;){var a=n.delegate;if(a){var s=S(a,n);if(s){if(s===d)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,a),o}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var d={};function h(){}function p(){}function g(){}var f={};l(f,o,(function(){return this}));var _=Object.getPrototypeOf,b=_&&_(_(x([])));b&&b!==t&&n.call(b,o)&&(f=b);var v=g.prototype=h.prototype=Object.create(f);function y(e){["next","throw","return"].forEach((function(t){l(e,t,(function(e){return this._invoke(t,e)}))}))}function E(e,t){function i(o,a,s,l){var c=u(e[o],e,a);if("throw"!==c.type){var d=c.arg,h=d.value;return h&&"object"==r(h)&&n.call(h,"__await")?t.resolve(h.__await).then((function(e){i("next",e,s,l)}),(function(e){i("throw",e,s,l)})):t.resolve(h).then((function(e){d.value=e,s(d)}),(function(e){return i("throw",e,s,l)}))}l(c.arg)}var o;this._invoke=function(e,n){function r(){return new t((function(t,r){i(e,n,t,r)}))}return o=o?o.then(r,r):r()}}function S(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method))return d;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,d;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,d):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,d)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function x(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var s=n.call(o,"catchLoc"),l=n.call(o,"finallyLoc");if(s&&l){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),T(n),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;T(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:x(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),d}},e}function g(e,t,n,r,i,o,a){try{var s=e[o](a),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,i)}function f(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var o=e.apply(t,n);function a(e){g(o,r,i,a,s,"next",e)}function s(e){g(o,r,i,a,s,"throw",e)}a(void 0)}))}}function _(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 b(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 b(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw o}}}}function b(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(n){return n.matchesAsRoomEvent(u.EventDirection.Send,e,t)}))}},{key:"canSendStateEvent",value:function(e,t){return this.allowedEvents.some((function(n){return n.matchesAsStateEvent(u.EventDirection.Send,e,t)}))}},{key:"canSendToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(u.EventDirection.Send,e)}))}},{key:"canReceiveRoomEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(n){return n.matchesAsRoomEvent(u.EventDirection.Receive,e,t)}))}},{key:"canReceiveStateEvent",value:function(e,t){return this.allowedEvents.some((function(n){return n.matchesAsStateEvent(u.EventDirection.Receive,e,t)}))}},{key:"canReceiveToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(u.EventDirection.Receive,e)}))}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"beginCapabilities",value:function(){var e,t=this;this.emit("preparing"),this.transport.send(s.WidgetApiToWidgetAction.Capabilities,{}).then((function(n){return e=n.capabilities,t.driver.validateCapabilities(new Set(n.capabilities))})).then((function(n){console.log("Widget ".concat(t.widget.id," is allowed capabilities:"),Array.from(n)),t.allowedCapabilities=n,t.allowedEvents=u.WidgetEventCapability.findEventCapabilities(n),t.notifyCapabilities(e),t.emit("ready")}))}},{key:"notifyCapabilities",value:function(e){var t=this;this.transport.send(s.WidgetApiToWidgetAction.NotifyCapabilities,{requested:e,approved:Array.from(this.allowedCapabilities)}).catch((function(e){console.warn("non-fatal error notifying widget of approved capabilities:",e)})).then((function(){t.emit("capabilitiesNotified")}))}},{key:"onIframeLoad",value:function(e){this.widget.waitForIframeLoad?this.beginCapabilities():this.contentLoadedActionSent=!1}},{key:"handleContentLoadedAction",value:function(e){if(this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)");this.widget.waitForIframeLoad?this.transport.reply(e,{error:{message:"Improper sequence: not expecting ContentLoaded event if waitForIframLoad is true (default=true)"}}):(this.transport.reply(e,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:c.CurrentApiVersions})}},{key:"handleCapabilitiesRenegotiate",value:function(e){var t,n=this;this.transport.reply(e,{});var r=(null===(t=e.data)||void 0===t?void 0:t.capabilities)||[],i=new Set(r.filter((function(e){return!n.hasCapability(e)})));if(0===i.size)return this.notifyCapabilities([]);this.driver.validateCapabilities(i).then((function(e){return e.forEach((function(e){return n.allowedCapabilities.add(e)})),u.WidgetEventCapability.findEventCapabilities(e).forEach((function(e){return n.allowedEvents.push(e)})),n.notifyCapabilities(Array.from(i))}))}},{key:"handleNavigate",value:function(e){var t,n,r=this;if(!this.hasCapability(l.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(e,{error:{message:"Missing capability"}});if(null===(t=e.data)||void 0===t||!t.uri||null===(n=e.data)||void 0===n||!n.uri.toString().startsWith("https://matrix.to/#"))return this.transport.reply(e,{error:{message:"Invalid matrix.to URI"}});var i=function(t){return console.error("[ClientWidgetApi] Failed to handle navigation: ",t),r.transport.reply(e,{error:{message:"Error handling navigation"}})};try{this.driver.navigate(e.data.uri.toString()).catch((function(e){return i(e)})).then((function(){return r.transport.reply(e,{})}))}catch(e){return i(e)}}},{key:"handleOIDC",value:function(e){var t=this,n=1,r=function(r,i){return i=i||{},n>1?t.transport.send(s.WidgetApiToWidgetAction.OpenIDCredentials,y({state:r,original_request_id:e.requestId},i)):t.transport.reply(e,y({state:r},i))},i=function(i){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",i),n>1?r(d.OpenIDRequestState.Blocked):t.transport.reply(e,{error:{message:i}})},o=new h.SimpleObservable((function(e){return e.state===d.OpenIDRequestState.PendingUserConfirmation&&n>1?(o.close(),i("client provided out-of-phase response to OIDC flow")):e.state===d.OpenIDRequestState.PendingUserConfirmation?(r(e.state),void n++):e.state!==d.OpenIDRequestState.Allowed||e.token?(e.state===d.OpenIDRequestState.Blocked&&(e.token=null),o.close(),r(e.state,e.token)):i("client provided invalid OIDC token for an allowed request")}));this.driver.askOpenID(o)}},{key:"handleReadEvents",value:function(e){var t=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(void 0!==e.data.limit&&(!e.data.limit||e.data.limit<0))return this.transport.reply(e,{error:{message:"Invalid request - limit out of range"}});var n=null;if(e.data.room_ids){n=e.data.room_ids,Array.isArray(n)||(n=[n]);var r,i=_(n);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!this.canUseRoomTimeline(o))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(o)}})}}catch(e){i.e(e)}finally{i.f()}}var a=e.data.limit||0,s=Promise.resolve([]);if(void 0!==e.data.state_key){var l=!0===e.data.state_key?void 0:e.data.state_key.toString();if(!this.canReceiveStateEvent(e.data.type,l))return this.transport.reply(e,{error:{message:"Cannot read state events of this type"}});s=this.driver.readStateEvents(e.data.type,l,a,n)}else{if(!this.canReceiveRoomEvent(e.data.type,e.data.msgtype))return this.transport.reply(e,{error:{message:"Cannot read room events of this type"}});s=this.driver.readRoomEvents(e.data.type,e.data.msgtype,a,n)}return s.then((function(n){return t.transport.reply(e,{events:n})}))}},{key:"handleSendEvent",value:function(e){var t,n=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(e.data.room_id&&!this.canUseRoomTimeline(e.data.room_id))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(e.data.room_id)}});if(null!==e.data.state_key&&void 0!==e.data.state_key){if(!this.canSendStateEvent(e.data.type,e.data.state_key))return this.transport.reply(e,{error:{message:"Cannot send state events of this type"}});t=this.driver.sendEvent(e.data.type,e.data.content||{},e.data.state_key,e.data.room_id)}else{var r=e.data.content||{},i=r.msgtype;if(!this.canSendRoomEvent(e.data.type,i))return this.transport.reply(e,{error:{message:"Cannot send room events of this type"}});t=this.driver.sendEvent(e.data.type,r,null,e.data.room_id)}t.then((function(t){return n.transport.reply(e,{room_id:t.roomId,event_id:t.eventId})})).catch((function(t){return console.error("error sending event: ",t),n.transport.reply(e,{error:{message:"Error sending event"}})}))}},{key:"handleSendToDevice",value:(k=f(m().mark((function e(t){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.type){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Invalid request - missing event type"}});case 3:case 8:case 13:case 18:case 25:e.next=32;break;case 5:if(t.data.messages){e.next=10;break}return e.next=8,this.transport.reply(t,{error:{message:"Invalid request - missing event contents"}});case 10:if("boolean"==typeof t.data.encrypted){e.next=15;break}return e.next=13,this.transport.reply(t,{error:{message:"Invalid request - missing encryption flag"}});case 15:if(this.canSendToDeviceEvent(t.data.type)){e.next=20;break}return e.next=18,this.transport.reply(t,{error:{message:"Cannot send to-device events of this type"}});case 20:return e.prev=20,e.next=23,this.driver.sendToDevice(t.data.type,t.data.encrypted,t.data.messages);case 23:return e.next=25,this.transport.reply(t,{});case 27:return e.prev=27,e.t0=e.catch(20),console.error("error sending to-device event",e.t0),e.next=32,this.transport.reply(t,{error:{message:"Error sending event"}});case 32:case"end":return e.stop()}}),e,this,[[20,27]])}))),function(e){return k.apply(this,arguments)})},{key:"pollTurnServers",value:(D=f(m().mark((function e(t,n){var r,i,o,a,l,c;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.transport.send(s.WidgetApiToWidgetAction.UpdateTurnServers,n);case 3:r=!1,i=!1,e.prev=5,a=F(t);case 7:return e.next=9,a.next();case 9:if(!(r=!(l=e.sent).done)){e.next=16;break}return c=l.value,e.next=13,this.transport.send(s.WidgetApiToWidgetAction.UpdateTurnServers,c);case 13:r=!1,e.next=7;break;case 16:e.next=22;break;case 18:e.prev=18,e.t0=e.catch(5),i=!0,o=e.t0;case 22:if(e.prev=22,e.prev=23,!r||null==a.return){e.next=27;break}return e.next=27,a.return();case 27:if(e.prev=27,!i){e.next=30;break}throw o;case 30:return e.finish(27);case 31:return e.finish(22);case 32:e.next=37;break;case 34:e.prev=34,e.t1=e.catch(0),console.error("error polling for TURN servers",e.t1);case 37:case"end":return e.stop()}}),e,this,[[0,34],[5,18,22,32],[23,,27,31]])}))),function(e,t){return D.apply(this,arguments)})},{key:"handleWatchTurnServers",value:(C=f(m().mark((function e(t){var n,r,i,o;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(l.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=30;break;case 5:if(!this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.prev=10,n=this.driver.getTurnServers(),e.next=14,n.next();case 14:if(r=e.sent,i=r.done,o=r.value,!i){e.next=19;break}throw new Error("Client refuses to provide any TURN servers");case 19:return e.next=21,this.transport.reply(t,{});case 21:this.pollTurnServers(n,o),this.turnServers=n,e.next=30;break;case 25:return e.prev=25,e.t0=e.catch(10),console.error("error getting first TURN server results",e.t0),e.next=30,this.transport.reply(t,{error:{message:"TURN servers not available"}});case 30:case"end":return e.stop()}}),e,this,[[10,25]])}))),function(e){return C.apply(this,arguments)})},{key:"handleUnwatchTurnServers",value:(v=f(m().mark((function e(t){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(l.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=15;break;case 5:if(this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.next=12,this.turnServers.return(void 0);case 12:return this.turnServers=null,e.next=15,this.transport.reply(t,{});case 15:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"handleReadRelations",value:(b=f(m().mark((function e(t){var n,r,i=this;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.event_id){e.next=2;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(void 0!==t.data.limit&&t.data.limit<0)){e.next=4;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - limit out of range"}}));case 4:if(void 0===t.data.room_id||this.canUseRoomTimeline(t.data.room_id)){e.next=6;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Unable to access room timeline: ".concat(t.data.room_id)}}));case 6:return e.prev=6,e.next=9,this.driver.readEventRelations(t.data.event_id,t.data.room_id,t.data.rel_type,t.data.event_type,t.data.from,t.data.to,t.data.limit,t.data.direction);case 9:if(!(n=e.sent).originalEvent){e.next=18;break}if(void 0===n.originalEvent.state_key){e.next=16;break}if(this.canReceiveStateEvent(n.originalEvent.type,n.originalEvent.state_key)){e.next=14;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Cannot read state events of this type"}}));case 14:e.next=18;break;case 16:if(this.canReceiveRoomEvent(n.originalEvent.type,n.originalEvent.content.msgtype)){e.next=18;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Cannot read room events of this type"}}));case 18:return r=n.chunk.filter((function(e){return void 0!==e.state_key?i.canReceiveStateEvent(e.type,e.state_key):i.canReceiveRoomEvent(e.type,e.content.msgtype)})),e.abrupt("return",this.transport.reply(t,{original_event:n.originalEvent,chunk:r,prev_batch:n.prevBatch,next_batch:n.nextBatch}));case 22:return e.prev=22,e.t0=e.catch(6),console.error("error getting the relations",e.t0),e.next=27,this.transport.reply(t,{error:{message:"Unexpected error while reading relations"}});case 27:case"end":return e.stop()}}),e,this,[[6,22]])}))),function(e){return b.apply(this,arguments)})},{key:"handleMessage",value:function(e){if(!this.isStopped){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case s.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(e.detail);case s.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case s.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(e.detail);case s.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(e.detail);case s.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(e.detail);case s.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(e.detail);case s.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(e.detail);case s.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(e.detail);case s.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(e.detail);case s.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(e.detail);case s.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(e.detail);default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}}},{key:"takeScreenshot",value:function(){return this.transport.send(s.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(e){return this.transport.send(s.WidgetApiToWidgetAction.UpdateVisibility,{visible:e})}},{key:"sendWidgetConfig",value:function(e){return this.transport.send(s.WidgetApiToWidgetAction.WidgetConfig,e).then()}},{key:"notifyModalWidgetButtonClicked",value:function(e){return this.transport.send(s.WidgetApiToWidgetAction.ButtonClicked,{id:e}).then()}},{key:"notifyModalWidgetClose",value:function(e){return this.transport.send(s.WidgetApiToWidgetAction.CloseModalWidget,e).then()}},{key:"feedEvent",value:(g=f(m().mark((function e(t,n){var r;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.room_id===n||this.canUseRoomTimeline(t.room_id)){e.next=2;break}return e.abrupt("return");case 2:if(void 0===t.state_key||null===t.state_key){e.next=7;break}if(this.canReceiveStateEvent(t.type,t.state_key)){e.next=5;break}return e.abrupt("return");case 5:e.next=9;break;case 7:if(this.canReceiveRoomEvent(t.type,null===(r=t.content)||void 0===r?void 0:r.msgtype)){e.next=9;break}return e.abrupt("return");case 9:return e.next=11,this.transport.send(s.WidgetApiToWidgetAction.SendEvent,t);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t){return g.apply(this,arguments)})},{key:"feedToDevice",value:(i=f(m().mark((function e(t,n){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.canReceiveToDeviceEvent(t.type)){e.next=3;break}return e.next=3,this.transport.send(s.WidgetApiToWidgetAction.SendToDevice,y(y({},t),{},{encrypted:n}));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)})}],n&&E(t.prototype,n),r&&E(t,r),Object.defineProperty(t,"prototype",{writable:!1}),I}(i.EventEmitter);t.ClientWidgetApi=k},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isErrorResponse=function(e){if("error"in e){return!!e.error.message}return!1}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetKind=void 0,t.WidgetKind=r,function(e){e.Room="room",e.Account="account",e.Modal="modal"}(r||(t.WidgetKind=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.ModalButtonKind=void 0,t.ModalButtonKind=r,function(e){e.Primary="m.primary",e.Secondary="m.secondary",e.Warning="m.warning",e.Danger="m.danger",e.Link="m.link"}(r||(t.ModalButtonKind=r={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetParser=void 0;var r=n(39),i=n(37);function o(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 r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}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,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw o}}}}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{const n=a.a.translate(e,v(v({},t),{},{fallbackLocale:a.a.getLocale()}));if(!n||n.startsWith("missing translation:")){const n=a.a.translate(e,v(v({},t),{},{locale:"en"}));return!n||n.startsWith("missing translation:")?{translated:e,isFallback:!0}:{translated:n,isFallback:!0}}return{translated:n}};function C(e,t){const n=v(v({},t),{},{interpolate:!1});return n&&"object"==typeof n&&Object.keys(n).forEach((e=>{void 0===n[e]&&(c.a.warn("safeCounterpartTranslate called with undefined interpolation name: "+e),n[e]="undefined"),null===n[e]&&(c.a.warn("safeCounterpartTranslate called with null interpolation name: "+e),n[e]="null")})),T(e,n)}const x=(e,t)=>e;function F(e,t,n){const{translated:r}=C(e,t),i=O(r,t,n);return x(i,e)}function D(e,t,n){const{translated:r,isFallback:i}=C(e,t),o=O(r,t,n);return x(i?l.a.createElement("span",{lang:"en"},o):o,e)}function k(e){return e.replace(/%\(([^)]*)\)/g,"% ($1)")}function O(e,t,n){let r=e;if(void 0!==t){const e={};for(const n in t)e[`%\\(${n}\\)s`]=t[n];r=I(r,e)}if(void 0!==n){const e={};for(const t in n)e[`(<${t}>(.*?)<\\/${t}>|<${t}>|<${t}\\s*\\/>)`]=n[t];r=I(r,e)}return r}function I(e,t){const n=[e];let r=!1;for(const i in t){const o=new RegExp(i,"g");let a=!1;for(let e=0;e{r=t;for(let t=0;t{if(a.a.registerTranslations(n,e),await V(),a.a.setLocale(n),await d.b.setValue("language",null,p.a.DEVICE,n),c.a.log("set language to "+n),"en"!==n)return j(y+r.en.fileName)})).then((async e=>{e&&a.a.registerTranslations("en",e),await V()}))}function R(){return U().then((e=>{const t=[];for(const n in e)e.hasOwnProperty(n)&&t.push({value:n,label:e[n].label});return t}))}function N(){return navigator.languages&&navigator.languages.length?navigator.languages:navigator.language?[navigator.language]:[navigator.userLanguage||"en"]}function M(e){const t=[],n=P(e),r=n.split("-");return 2===r.length&&r[0]===r[1]?t.push(r[0]):(t.push(n),2===r.length&&t.push(r[0])),t}function P(e){return e.toLowerCase().replace("_","-")}function L(){return a.a.getLocale()}function B(e){const t=L(),n=e.map(P);{const r=n.indexOf(t);if(r>-1)return e[r]}{const r=n.findIndex((e=>e.slice(0,2)===t.slice(0,2)));if(r>-1)return e[r]}{const t=n.findIndex((e=>e.startsWith("en")));if(t>-1)return e[t]}return e[0]}async function U(){let e;e="string"==typeof _.a?_.a:y+"languages.json";const t=await fetch(e,{method:"GET"});if(!t.ok)throw new Error(`Failed to load ${e}, got ${t.status}`);return t.json()}async function j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;return Object(m.a)((()=>async function(e){const t=await fetch(e,{method:"GET"});if(!t.ok)throw new Error(`Failed to load ${e}, got ${t.status}`);return t.json()}(e)),t,(t=>(c.a.log("Failed to load i18n",e),c.a.error(t),!0)))}let G=null,z=0;class H{constructor(){}}function q(e){const t=new u.b((()=>({})));for(const[n,r]of Object.entries(e))for(const[e,i]of Object.entries(r))Object(u.L)(t.getOrCreate(e),n,i);for(const[e,n]of t)a.a.registerTranslations(e,n)}async function V(){q(f.a.instance.allTranslations);const e=g.b.get().custom_translations_url;if(e)try{let t;if(Date.now()>=z?(t=H.lookupFn?H.lookupFn(e):await(await fetch(e)).json(),G=t,z=Date.now()+3e5):t=G,!t)return;q(t)}catch(e){c.a.warn("Ignoring error while registering custom translations: ",e),z=Date.now()+3e5}}i()(H,"lookupFn",void 0)},function(e,t,n){"use strict";n.d(t,"a",(function(){return Z}));var r=n(13),i=n.n(r),o=n(136),a=n(351),s=n(16),l=n(179),c=n(353),u=n(174),d=n(419),h=n(1),p=n(928),m=n(125),g=n(147),f=n(143),_=n(140),b=n(151),v=n(124);function y(e,t,n){return{action:"MatrixActions.sync",state:t,prevState:n,matrixClient:e}}function E(e,t){return{action:"MatrixActions.accountData",event:t,event_type:t.getType(),event_content:t.getContent()}}function S(e,t,n){return{action:"MatrixActions.Room.accountData",event:t,event_type:t.getType(),event_content:t.getContent(),room:n}}function w(e,t){return{action:"MatrixActions.Room",room:t}}function T(e,t,n){return{action:"MatrixActions.Room.tags",room:n}}function C(e,t,n){return{action:"MatrixActions.Room.receipt",event:t,room:n,matrixClient:e}}function x(e,t,n,r,i,o){return{action:"MatrixActions.Room.timeline",event:t,isLiveEvent:o.liveEvent,isLiveUnfilteredRoomTimelineEvent:o.timeline.getTimelineSet()===(null==n?void 0:n.getUnfilteredTimelineSet()),room:n}}function F(e,t,n,r){return{action:"MatrixActions.RoomState.events",event:t,state:n,lastStateEvent:r}}function D(e,t,n,r){return{action:"MatrixActions.Room.myMembership",room:t,membership:n,oldMembership:r}}function k(e,t){return{action:"MatrixActions.Event.decrypted",event:t}}let O=[];function I(e,t,n){const r=function(){for(var t=arguments.length,r=new Array(t),i=0;i{e.removeListener(t,r)}))}var A={start(e){I(e,g.b.Sync,y),I(e,g.b.AccountData,E),I(e,_.d.AccountData,S),I(e,g.b.Room,w),I(e,_.d.Tags,T),I(e,_.d.Receipt,C),I(e,_.d.Timeline,x),I(e,_.d.MyMembership,D),I(e,f.c.Decrypted,k),I(e,b.b.Events,F)},stop(){O.forEach((e=>e())),O=[]}},R=n(127),N=n(431),M=n(432),P=n(289),L=n(250),B=n(292),U=n(523),j=n(120),G=n.n(j),z=n(121),H=n(131),q=n(135),V=n(145),$=n(155);var K=e=>{const t=H.b.get().brand,n=Object(z.a)("You've previously used a newer version of %(brand)s with this session. To use this version again with end to end encryption, you will need to sign out and back in again.",{brand:t});return G.a.createElement(q.a,{className:"mx_CryptoStoreTooNewDialog",contentId:"mx_Dialog_content",title:Object(z.a)("Incompatible Database"),hasCancel:!1,onFinished:e.onFinished},G.a.createElement("div",{className:"mx_Dialog_content",id:"mx_Dialog_content"},n),G.a.createElement(V.a,{primaryButton:Object(z.a)("Continue With Encryption Disabled"),hasCancel:!1,onPrimaryButtonClick:()=>e.onFinished(!1)},G.a.createElement("button",{onClick:()=>{R.b.createDialog($.a,{title:Object(z.a)("Sign out"),description:Object(z.a)("To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this",{brand:t}),button:Object(z.a)("Sign out"),focus:!1,onFinished:t=>{t&&(v.a.dispatch({action:"logout"}),e.onFinished(!0))}})}},Object(z.a)("Sign out"))))},W=n(137),Y=n(691);function Q(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function X(e){for(var t=1;t{switch(t.type){case o.RoomNameType.Generated:return"Inviting"===t.subtype?this.inviteeNamesToRoomName(t.names,t.count):this.memberNamesToRoomName(t.names,t.count);case o.RoomNameType.EmptyRoom:return t.oldName?Object(z.a)("Empty room (was %(oldName)s)",{oldName:t.oldName}):Object(z.a)("Empty room");default:return null}}};B.a.getDehydrationKey&&(t.cryptoCallbacks.getDehydrationKey=B.a.getDehydrationKey),this.matrixClient=Object(p.a)(t),this.matrixClient.setMaxListeners(500),this.matrixClient.setGuest(Boolean(e.guest));const n=new c.b(void 0,{timelineSupport:!0,pendingEvents:!1});n.getLiveTimeline().setPaginationToken("",l.b.BACKWARDS),this.matrixClient.setNotifTimelineSet(n)}};window.mxMatrixClientPeg||(window.mxMatrixClientPeg=Z)},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(132),i=n.n(r),o=n(120),a=n.n(o),s=n(126),l=n.n(s),c=n(152),u=n(142);const d=["element","onClick","children","kind","disabled","inputRef","className","onKeyDown","onKeyUp","triggerOnMouseDown"];function h(e){let{element:t,onClick:n,children:r,kind:o,disabled:s,inputRef:h,className:p,onKeyDown:m,onKeyUp:g,triggerOnMouseDown:f}=e;const _=i()(e,d);return s?(_["aria-disabled"]=!0,_.disabled=!0):(f?_.onMouseDown=null!=n?n:void 0:_.onClick=null!=n?n:void 0,_.onKeyDown=e=>{switch(Object(c.a)().getAccessibilityAction(e)){case u.h.Enter:return e.stopPropagation(),e.preventDefault(),null==n?void 0:n(e);case u.h.Space:e.stopPropagation(),e.preventDefault();break;default:null==m||m(e)}},_.onKeyUp=e=>{switch(Object(c.a)().getAccessibilityAction(e)){case u.h.Enter:e.stopPropagation(),e.preventDefault();break;case u.h.Space:return e.stopPropagation(),e.preventDefault(),null==n?void 0:n(e);default:null==g||g(e)}}),_.ref=h,_.className=l()("mx_AccessibleButton",p,{mx_AccessibleButton_hasKind:o,[`mx_AccessibleButton_kind_${o}`]:o,mx_AccessibleButton_disabled:s}),a.a.createElement(t,_,r)}h.defaultProps={element:"div",role:"button",tabIndex:0},h.displayName="AccessibleButton"},function(e,t,n){"use strict";n.d(t,"b",(function(){return a}));var r=n(992),i=n(676);class o extends r.Dispatcher{dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];e instanceof i.a?e.fn((e=>{this.dispatch(e,t)})):t?super.dispatch(e):window.setTimeout(super.dispatch.bind(this,e),0)}fire(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dispatch({action:e},t)}}const a=new o;window.mxDispatcher||(window.mxDispatcher=a),t.a=a},function(e,t,n){"use strict";n.d(t,"a",(function(){return $})),n.d(t,"b",(function(){return W}));var r=n(13),i=n.n(r),o=n(1),a=n(122),s=n(137),l=n(524);class c extends l.a{constructor(e,t){super(),this.featureNames=e,this.watchers=t}getValue(e,t){if(this.featureNames.includes(e))return this.readFeature(e);if("notificationsEnabled"===e)return this.getBoolean("notifications_enabled");if("notificationBodyEnabled"===e)return this.getBoolean("notifications_body_enabled");if("audioNotificationsEnabled"===e)return this.getBoolean("audio_notifications_enabled");return(this.getSettings()||{})[e]}setValue(e,t,n){if(this.featureNames.includes(e))return this.writeFeature(e,n),Promise.resolve();if("notificationsEnabled"===e)return this.setBoolean("notifications_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("notificationBodyEnabled"===e)return this.setBoolean("notifications_body_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("audioNotificationsEnabled"===e)return this.setBoolean("audio_notifications_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("layout"===e){const t=this.getSettings()||{};return delete t.useIRCLayout,t.layout=n,this.setObject("mx_local_settings",t),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve()}const r=this.getSettings()||{};return r[e]=n,this.setObject("mx_local_settings",r),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve()}canSetValue(e,t){return!0}watchSetting(e,t,n){this.watchers.watchSetting(e,t,n)}unwatchSetting(e){this.watchers.unwatchSetting(e)}getSettings(){return this.getObject("mx_local_settings")}readFeature(e){return(!a.a.get()||!a.a.get().isGuest())&&this.getBoolean("mx_labs_feature_"+e)}writeFeature(e,t){this.setBoolean("mx_labs_feature_"+e,t),this.watchers.notifyUpdate(e,null,s.a.DEVICE,t)}}var u=n(16);class d extends l.a{constructor(e){super(),this.watchers=e}getValue(e,t){if("blacklistUnverifiedDevices"===e){const e=this.read("mx_local_settings");if(null!=e&&e.blacklistUnverifiedDevicesPerRoom)return e.blacklistUnverifiedDevicesPerRoom[t]}const n=this.read(this.getKey(e,t));return n?n.value:null}setValue(e,t,n){if("blacklistUnverifiedDevices"===e){let r=this.read("mx_local_settings");return r||(r={}),r.blacklistUnverifiedDevicesPerRoom||(r.blacklistUnverifiedDevicesPerRoom={}),Object(u.L)(r.blacklistUnverifiedDevicesPerRoom,t,n),this.setObject("mx_local_settings",r),this.watchers.notifyUpdate(e,t,s.a.ROOM_DEVICE,n),Promise.resolve()}return null===n?this.removeItem(this.getKey(e,t)):this.setObject(this.getKey(e,t),{value:n}),this.watchers.notifyUpdate(e,t,s.a.ROOM_DEVICE,n),Promise.resolve()}canSetValue(e,t){return!0}read(e){return this.getObject(e)}getKey(e,t){return"mx_setting_"+e+"_"+t}}var h=n(324);class p extends h.a{constructor(e,t){super(),this.defaults=e,this.invertedDefaults=t}getValue(e,t){let n=this.defaults[e];return void 0===n&&(n=this.invertedDefaults[e]),n}async setValue(e,t,n){throw new Error("Cannot set values on the default level handler")}canSetValue(e,t){return!1}isSupported(){return!0}}var m=n(140),g=n(431),f=n(185);const _="im.vector.setting.allowed_widgets",b="im.vector.web.settings";class v extends g.a{constructor(e){super(),this.watchers=e,i()(this,"onAccountData",((e,t,n)=>{const r=t.roomId;if("org.matrix.room.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",r,s.a.ROOM_ACCOUNT,t)}else if(e.getType()===b){const t=n?n.getContent():{},i=Object(f.d)(t,e.getContent());for(const t of i){const n=e.getContent()[t];this.watchers.notifyUpdate(t,r,s.a.ROOM_ACCOUNT,n)}}else e.getType()===_&&this.watchers.notifyUpdate("allowedWidgets",r,s.a.ROOM_ACCOUNT,e.getContent())}))}initMatrixClient(e,t){e&&e.removeListener(m.d.AccountData,this.onAccountData),t.on(m.d.AccountData,this.onAccountData)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}if("allowedWidgets"===e)return this.getSettings(t,_);return(this.getSettings(t)||{})[e]}async setRoomAccountData(e,t,n,r){let i;null===n?i=r:(i=this.getSettings(e,t)||{},i[n]=r),await this.client.setRoomAccountData(e,t,i);const o=Object(u.m)(),a=(i,s)=>{s.roomId===e&&i.getType()===t&&(null!==n&&i.getContent()[n]!==r||(this.client.off(m.d.AccountData,a),o.resolve()))};this.client.on(m.d.AccountData,a),await o.promise}setValue(e,t,n){switch(e){case"urlPreviewsEnabled":return this.setRoomAccountData(t,"org.matrix.room.preview_urls","disable",!n);case"allowedWidgets":return this.setRoomAccountData(t,_,null,n);default:return this.setRoomAccountData(t,b,e,n)}}canSetValue(e,t){return!!this.client.getRoom(t)}isSupported(){return this.client&&!this.client.isGuest()}getSettings(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b;const r=null===(t=this.client.getRoom(e))||void 0===t?void 0:t.getAccountData(n);return r&&r.getContent()?Object(f.a)(r.getContent()):null}}var y=n(147);const E="im.vector.riot.breadcrumb_rooms",S="im.vector.setting.breadcrumbs",w=[E,S],T="io.element.recent_emoji",C="im.vector.setting.integration_provisioning",x="im.vector.analytics",F="im.vector.web.settings";class D extends g.a{constructor(e){super(),this.watchers=e,i()(this,"onAccountData",((e,t)=>{if("org.matrix.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",null,s.a.ACCOUNT,t)}else if(e.getType()===F||e.getType()===x){var n;const r=null!==(n=null==t?void 0:t.getContent())&&void 0!==n?n:{},i=Object(f.d)(r,e.getContent());for(const t of i){const n=e.getContent()[t];this.watchers.notifyUpdate(t,null,s.a.ACCOUNT,n)}}else if(w.includes(e.getType()))this.notifyBreadcrumbsUpdate(e);else if(e.getType()===C){const t=e.getContent().enabled;this.watchers.notifyUpdate("integrationProvisioning",null,s.a.ACCOUNT,t)}else if(e.getType()===T){const t=e.getContent().enabled;this.watchers.notifyUpdate("recent_emoji",null,s.a.ACCOUNT,t)}}))}get level(){return s.a.ACCOUNT}initMatrixClient(e,t){null==e||e.removeListener(y.b.AccountData,this.onAccountData),t.on(y.b.AccountData,this.onAccountData)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings("org.matrix.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}if("breadcrumb_rooms"===e){let e=this.getSettings(S);return e&&e.recent_rooms||(e=this.getSettings(E),e&&(e.recent_rooms=e.rooms)),e&&e.recent_rooms?e.recent_rooms:[]}if("recent_emoji"===e){const e=this.getSettings(T);return e?e.recent_emoji:null}if("integrationProvisioning"===e){const e=this.getSettings(C);return e?e.enabled:null}if("pseudonymousAnalyticsOptIn"===e){const t=this.getSettings(x)||{};return"boolean"!=typeof t[e]?null:t[e]}if("MessageComposerInput.insertTrailingColon"===e){const n=(this.getSettings()||{})[e];return null==n?(this.setValue(e,t,!0),!0):n}const n=this.getSettings()||{};let r=n[e];return null==r&&("hideAvatarChanges"!==e&&"hideDisplaynameChanges"!==e||(r=n.hideAvatarDisplaynameChanges)),r}async setAccountData(e,t,n,r){var i;let o=this.getSettings(e);!r||null!==(i=o)&&void 0!==i&&i[t]||(o=this.getSettings(r)),o||(o={}),o[t]=n;const a=Object(u.m)(),s=r=>{r.getType()===e&&r.getContent()[t]===n&&(this.client.off(y.b.AccountData,s),a.resolve())};this.client.on(y.b.AccountData,s),await this.client.setAccountData(e,o),await a.promise}setValue(e,t,n){switch(e){case"urlPreviewsEnabled":return this.setAccountData("org.matrix.preview_urls","disable",!n);case"breadcrumb_rooms":return this.setAccountData(S,"recent_rooms",n,E);case"recent_emoji":return this.setAccountData(T,"recent_emoji",n);case"integrationProvisioning":return this.setAccountData(C,"enabled",n);case"pseudonymousAnalyticsOptIn":return this.setAccountData(x,"pseudonymousAnalyticsOptIn",n);default:return this.setAccountData(F,e,n)}}canSetValue(e,t){return!0}isSupported(){return this.client&&!this.client.isGuest()}getSettings(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"im.vector.web.settings";if(!this.client)return null;const t=this.client.getAccountData(e);return t&&t.getContent()?Object(f.a)(t.getContent()):null}notifyBreadcrumbsUpdate(e){let t=[];if(e.getType()===E){const n=this.getSettings(S);t=n?n.recent_rooms:e.getContent().rooms}else{if(e.getType()!==S)return;t=e.getContent().recent_rooms}this.watchers.notifyUpdate("breadcrumb_rooms",null,s.a.ACCOUNT,t||[])}}var k=n(151);const O="im.vector.web.settings";class I extends g.a{constructor(e){super(),this.watchers=e,i()(this,"onEvent",((e,t,n)=>{const r=e.getRoomId(),i=this.client.getRoom(r);if(i&&(!i||t===i.currentState))if("org.matrix.room.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",r,s.a.ROOM,t)}else if(e.getType()===O){const t=n?n.getContent():{},i=Object(f.d)(t,e.getContent());for(const t of i)this.watchers.notifyUpdate(t,r,s.a.ROOM,e.getContent()[t])}}))}initMatrixClient(e,t){e&&e.removeListener(k.b.Events,this.onEvent),t.on(k.b.Events,this.onEvent)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}return(this.getSettings(t)||{})[e]}async sendStateEvent(e,t,n,r){const i=this.getSettings(e,t)||{};i[n]=r;const{event_id:o}=await this.client.sendStateEvent(e,t,i),a=Object(u.m)(),s=e=>{e.getId()===o&&(this.client.off(k.b.Events,s),a.resolve())};this.client.on(k.b.Events,s),await a.promise}setValue(e,t,n){return"urlPreviewsEnabled"===e?this.sendStateEvent(t,"org.matrix.room.preview_urls","disable",!n):this.sendStateEvent(t,O,e,n)}canSetValue(e,t){var n;const r=this.client.getRoom(t);let i=O;return"urlPreviewsEnabled"===e&&(i="org.matrix.room.preview_urls"),null!==(n=null==r?void 0:r.currentState.maySendStateEvent(i,this.client.getUserId()))&&void 0!==n&&n}isSupported(){return!!this.client}getSettings(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:O;const r=null===(t=this.client.getRoom(e))||void 0===t?void 0:t.currentState.getStateEvents(n,"");return null!=r&&r.getContent()?Object(f.a)(r.getContent()):null}}var A=n(131),R=n(26);class N extends h.a{constructor(e){super(),this.featureNames=e}getValue(e,t){const n=new R.a(A.b.get());if(this.featureNames.includes(e)){const t=(n.get("features")||{})[e];return Object(u.u)(t)?null:!0===t||!1===t?t:"enable"===t||"disable"!==t&&null}if("theme"===e)return n.get("default_theme");const r=n.get("setting_defaults");return!r||Object(u.u)(r[e])?null:r[e]}async setValue(e,t,n){throw new Error("Cannot change settings at the config level")}canSetValue(e,t){return!1}isSupported(){return!0}}var M=n(121),P=n(124),L=n(313);class B extends h.a{constructor(e,t){super(),this.handler=e,this.level=t,i()(this,"cache",{})}getValue(e,t){const n=null!=t?t:"UNDEFINED",r=this.cache[e];return null!=r&&r.hasOwnProperty(n)?r[n]:this.handler.getValue(e,t)}async setValue(e,t,n){var r;this.cache[e]||(this.cache[e]={});const i=this.cache[e],o=null!=t?t:"UNDEFINED";i[o]=n;const a=this.handler.getValue(e,t),s=this.handler.setValue(e,t,n);null===(r=this.handler.watchers)||void 0===r||r.notifyUpdate(e,t,this.level,n);try{await s}catch(n){var l;null===(l=this.handler.watchers)||void 0===l||l.notifyUpdate(e,t,this.level,a)}finally{i[o]===n&&delete i[o]}}canSetValue(e,t){return this.handler.canSetValue(e,t)}isSupported(){return this.handler.isSupported()}}var U=n(128),j=n(157);class G extends h.a{constructor(){super(),i()(this,"store",{}),i()(this,"onAction",(e=>{e.action===U.a.PlatformSet&&(this.store={},Object.entries(L.c).forEach((t=>{var n;let[r,i]=t;null!==(n=i.supportedLevels)&&void 0!==n&&n.includes(s.a.PLATFORM)&&e.platform.supportsSetting(r)&&e.platform.getSettingValue(r).then((e=>{this.store[r]=e}))})))})),P.a.register(this.onAction)}canSetValue(e,t){var n,r;return null!==(n=null===(r=j.a.get())||void 0===r?void 0:r.supportsSetting(e))&&void 0!==n&&n}getValue(e,t){return this.store[e]}async setValue(e,t,n){var r;this.store[e]=n,await(null===(r=j.a.get())||void 0===r?void 0:r.setSettingValue(e,n))}isSupported(){var e,t;return null!==(e=null===(t=j.a.get())||void 0===t?void 0:t.supportsSetting())&&void 0!==e&&e}}const z={},H={},q=[];for(const e in L.c){const t=L.c[e];z[e]=t.default,t.isFeature&&q.push(e),t.invertedSettingName&&(H[t.invertedSettingName]=!t.default)}const V={[s.a.DEVICE]:new c(q,L.d),[s.a.ROOM_DEVICE]:new d(L.d),[s.a.ROOM_ACCOUNT]:new B(new v(L.d),s.a.ROOM_ACCOUNT),[s.a.ACCOUNT]:new B(new D(L.d),s.a.ACCOUNT),[s.a.ROOM]:new B(new I(L.d),s.a.ROOM),[s.a.PLATFORM]:new B(new G,s.a.PLATFORM),[s.a.CONFIG]:new N(q),[s.a.DEFAULT]:new p(z,H)},$=[s.a.DEVICE,s.a.ROOM_DEVICE,s.a.ROOM_ACCOUNT,s.a.ACCOUNT,s.a.ROOM,s.a.CONFIG,s.a.DEFAULT];function K(e){return e.supportedLevelsAreOrdered||1===e.supportedLevels.length?[...e.supportedLevels]:$}class W{static getFeatureSettingNames(){return Object.keys(L.c).filter((e=>W.isFeature(e)))}static watchSetting(e,t,n){const r=L.c[e],i=e;if(!r)throw new Error(`${e} is not a setting`);r.invertedSettingName&&(e=r.invertedSettingName);const a=`${(new Date).getTime()}_${W.watcherCount++}_${e}_${t}`,s=(e,t,r)=>{var a;if(!W.doesSettingSupportLevel(i,t))return void o.a.warn(`Setting handler notified for an update of an invalid setting level: ${i}@${t} - this likely means a weird setting value made it into the level's storage. The notification will be ignored.`);const s=W.getValue(i),l=null!==(a=W.getValueAt(t,i))&&void 0!==a?a:r;n(i,e,t,l,s)};return W.watchers.set(a,s),L.d.watchSetting(e,t,s),a}static unwatchSetting(e){W.watchers.has(e)?(L.d.unwatchSetting(W.watchers.get(e)),W.watchers.delete(e)):o.a.warn(`Ending non-existent watcher ID ${e}`)}static monitorSetting(e,t){t=t||null,this.monitors.has(e)||this.monitors.set(e,new Map);const n=()=>{this.monitors.get(e).set(t,W.watchSetting(e,t,((e,t,n,r,i)=>{P.a.dispatch({action:U.a.SettingUpdated,settingName:e,roomId:t,level:n,newValueAtLevel:r,newValue:i})})))},r=Array.from(this.monitors.get(e).keys());r.find((e=>e===t||null===e))?null===t&&(r.forEach((t=>{W.unwatchSetting(this.monitors.get(e).get(t))})),this.monitors.get(e).clear(),n()):n()}static getDisplayName(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.a.DEFAULT;if(!L.c[e]||!L.c[e].displayName)return null;let n=L.c[e].displayName;return n instanceof Object&&(n=n[t]?n[t]:n.default),Object(M.a)(n)}static getDescription(e){var t;const n=null===(t=L.c[e])||void 0===t?void 0:t.description;return n?"string"!=typeof n?n():Object(M.a)(n):null}static isFeature(e){return!!L.c[e]&&!!L.c[e].isFeature}static shouldHaveWarning(e){var t;return!!L.c[e]&&(null!==(t=L.c[e].shouldWarn)&&void 0!==t&&t)}static getBetaInfo(e){var t;if(W.isFeature(e)&&!1!==W.getValueAt(s.a.CONFIG,e,null,!0,!0))return null===(t=L.c[e])||void 0===t?void 0:t.betaInfo}static getLabGroup(e){if(W.isFeature(e))return L.c[e].labsGroup}static isEnabled(e){var t,n;return!!L.c[e]&&(null===(t=!(null!==(n=L.c[e].controller)&&void 0!==n&&n.settingDisabled))||void 0===t||t)}static getValue(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!L.c[e])throw new Error("Setting '"+e+"' does not appear to be a setting.");const r=K(L.c[e]);return W.getValueAt(r[0],e,t,!1,n)}static getValueAt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const o=L.c[t];if(!o)throw new Error("Setting '"+t+"' does not appear to be a setting.");const a=K(o);a.includes(s.a.DEFAULT)||a.push(s.a.DEFAULT);const l=a.indexOf(e);if(-1===l)throw new Error(`Level "${e}" for setting "${t}" is not prioritized`);const c=W.getHandlers(t);if(o.invertedSettingName&&(t=o.invertedSettingName),r){const r=c[e];if(!r)return W.getFinalValue(o,e,n,null,null);const i=r.getValue(t,n);return W.getFinalValue(o,e,n,i,e)}for(let r=l;r{if("MatrixActions.sync"===t.action){P.a.unregister(e);if("boolean"!=typeof W.getValue("sendReadReceipts",null,!0)){const e=V[s.a.DEVICE].readFeature("feature_hidden_read_receipts");if("boolean"==typeof e){const t=!e;console.log(`Setting sendReadReceipts to ${t} because of previously-set labs flag`),W.setValue("sendReadReceipts",null,s.a.ACCOUNT,t)}}}}))}static debugSetting(e,t){o.a.log(`--- DEBUG ${e}`);const n=L.c[e];o.a.log(`--- definition: ${n?JSON.stringify(n):""}`),o.a.log(`--- default level order: ${JSON.stringify($)}`),o.a.log(`--- registered handlers: ${JSON.stringify(Object.keys(V))}`);const r=e=>{for(const n of Object.keys(V)){const r=V[n];try{const i=r.getValue(e,t);o.a.log(`--- ${n}@${t||""} = ${JSON.stringify(i)}`)}catch(e){o.a.log(`--- ${r.constructor.name}@${t||""} THREW ERROR: ${e.message}`),o.a.error(e)}if(t)try{const t=r.getValue(e,null);o.a.log(`--- ${n}@ = ${JSON.stringify(t)}`)}catch(e){o.a.log(`--- ${r.constructor.name}@ THREW ERROR: ${e.message}`),o.a.error(e)}}o.a.log("--- calculating as returned by SettingsStore"),o.a.log("--- these might not match if the setting uses a controller - be warned!");try{const n=W.getValue(e,t);o.a.log(`--- SettingsStore#generic@${t||""} = ${JSON.stringify(n)}`)}catch(e){o.a.log(`--- SettingsStore#generic@${t||""} THREW ERROR: ${e.message}`),o.a.error(e)}if(t)try{const t=W.getValue(e,null);o.a.log(`--- SettingsStore#generic@ = ${JSON.stringify(t)}`)}catch(e){o.a.log(`--- SettingsStore#generic@$ THREW ERROR: ${e.message}`),o.a.error(e)}for(const n of $){try{const r=W.getValueAt(n,e,t);o.a.log(`--- SettingsStore#${n}@${t||""} = ${JSON.stringify(r)}`)}catch(e){o.a.log(`--- SettingsStore#${n}@${t||""} THREW ERROR: ${e.message}`),o.a.error(e)}if(t)try{const t=W.getValueAt(n,e,null);o.a.log(`--- SettingsStore#${n}@ = ${JSON.stringify(t)}`)}catch(e){o.a.log(`--- SettingsStore#${n}@$ THREW ERROR: ${e.message}`),o.a.error(e)}}};r(e),n.invertedSettingName&&(o.a.log("--- TESTING INVERTED SETTING NAME"),o.a.log(`--- inverted: ${n.invertedSettingName}`),r(n.invertedSettingName)),o.a.log("--- END DEBUG")}static getHandler(e,t){const n=W.getHandlers(e);return n[t]?n[t]:null}static getHandlers(e){if(!L.c[e])return{};const t={};for(const n of L.c[e].supportedLevels){if(!V[n])throw new Error("Unexpected level "+n);W.isLevelSupported(n)&&(t[n]=V[n])}return t.default||(t.default=V.default),t}}i()(W,"watchers",new Map),i()(W,"monitors",new Map),i()(W,"watcherCount",1),window.mxSettingsStore=W},function(e,t,n){var r;!function(){"use strict";var n={}.hasOwnProperty;function i(){for(var e=[],t=0;t{const e=this.getCurrentModal();e&&(e.closeReason="backgroundClick",e.close(),e.closeReason=void 0)}))}static getOrCreateContainer(){let e=document.getElementById(_);return e||(e=document.createElement("div"),e.id=_,document.body.appendChild(e)),e}static getOrCreateStaticContainer(){let e=document.getElementById(b);return e||(e=document.createElement("div"),e.id=b,document.body.appendChild(e)),e}toggleCurrentDialogVisibility(){const e=this.getCurrentModal();e&&(e.hidden=!e.hidden)}hasDialogs(){return!!this.priorityModal||!!this.staticModal||this.modals.length>0}createDialog(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};return this.createDialogAsync(Promise.resolve(e),t,n,r,i,o)}appendDialog(e,t,n){return this.appendDialogAsync(Promise.resolve(e),t,n)}closeCurrentModal(e){const t=this.getCurrentModal();t&&(t.closeReason=e,t.close())}buildModal(e,t,n,r){const o={onFinished:null==t?void 0:t.onFinished,onBeforeClose:null==r?void 0:r.onBeforeClose,className:n,elem:null},[a,s]=this.getCloseFn(o,t),c=this.counter++;return o.elem=l.a.createElement(f.a,i()({key:c,prom:e},t,{onFinished:a})),o.close=a,{modal:o,closeDialog:a,onFinishedProm:s}}getCloseFn(e,t){var n=this;const r=Object(p.m)();return[async function(){if(e.beforeClosePromise)await e.beforeClosePromise;else if(e.onBeforeClose){e.beforeClosePromise=e.onBeforeClose(e.closeReason);const t=await e.beforeClosePromise;if(e.beforeClosePromise=void 0,!t)return}for(var i=arguments.length,o=new Array(i),a=0;a=0&&n.modals.splice(s,1),n.priorityModal===e&&(n.priorityModal=null,n.modals=[]),n.staticModal===e&&(n.staticModal=null,n.modals=[]),n.reRender()},r.promise]}createDialogAsync(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const a=this.getCurrentModal(),{modal:s,closeDialog:l,onFinishedProm:c}=this.buildModal(e,t,n,o);return r?this.priorityModal=s:i?this.staticModal=s:this.modals.unshift(s),this.reRender(),this.emitIfChanged(a),{close:l,finished:c}}appendDialogAsync(e,t,n){const r=this.getCurrentModal(),{modal:i,closeDialog:o,onFinishedProm:a}=this.buildModal(e,t,n,{});return this.modals.push(i),this.reRender(),this.emitIfChanged(r),{close:o,finished:a}}emitIfChanged(e){e!==this.getCurrentModal()&&this.emit(v.Opened)}getCurrentModal(){return this.priorityModal?this.priorityModal:this.modals[0]||this.staticModal}async reRender(){if(await Object(p.N)(0),0===this.modals.length&&!this.priorityModal&&!this.staticModal)return g.a.dispatch({action:"aria_unhide_main_app"}),u.a.unmountComponentAtNode(y.getOrCreateContainer()),void u.a.unmountComponentAtNode(y.getOrCreateStaticContainer());if(g.a.dispatch({action:"aria_hide_main_app"}),this.staticModal){const e=h()("mx_Dialog_wrapper mx_Dialog_staticWrapper",this.staticModal.className),t=l.a.createElement("div",{className:e},l.a.createElement("div",{className:"mx_Dialog"},this.staticModal.elem),l.a.createElement("div",{"data-testid":"dialog-background",className:"mx_Dialog_background mx_Dialog_staticBackground",onClick:this.onBackgroundClick}));u.a.render(t,y.getOrCreateStaticContainer())}else u.a.unmountComponentAtNode(y.getOrCreateStaticContainer());const t=this.getCurrentModal();if(t===this.staticModal||t.hidden)u.a.unmountComponentAtNode(y.getOrCreateContainer());else{const n=h()("mx_Dialog_wrapper",t.className,{mx_Dialog_wrapperWithStaticUnder:this.staticModal}),r=l.a.createElement("div",{className:n},l.a.createElement("div",{className:"mx_Dialog"},t.elem),l.a.createElement("div",{"data-testid":"dialog-background",className:"mx_Dialog_background",onClick:this.onBackgroundClick}));e((()=>u.a.render(r,y.getOrCreateContainer())))}}}window.singletonModalManager||(window.singletonModalManager=new y),t.b=window.singletonModalManager}).call(this,n(54).setImmediate)},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.ViewUser="view_user",e.ViewUserSettings="view_user_settings",e.ViewUserDeviceSettings="view_user_device_settings",e.ViewRoomDirectory="view_room_directory",e.ViewRoomError="view_room_error",e.ViewHomePage="view_home_page",e.RecheckTheme="recheck_theme",e.CheckUpdates="check_updates",e.FocusSendMessageComposer="focus_send_message_composer",e.ClearAndFocusSendMessageComposer="clear_focus_send_message_composer",e.FocusEditMessageComposer="focus_edit_message_composer",e.FocusAComposer="focus_a_composer",e.ToggleUserMenu="toggle_user_menu",e.ToggleSpacePanel="toggle_space_panel",e.UpdateFontSize="update_font_size",e.UpdateSystemFont="update_system_font",e.ViewRoom="view_room",e.ViewThread="view_thread",e.ViewRoomDelta="view_room_delta",e.OpenDialPad="open_dial_pad",e.DialNumber="dial_number",e.PstnSupportUpdated="pstn_support_updated",e.VirtualRoomSupportUpdated="virtual_room_support_updated",e.UploadStarted="upload_started",e.UploadProgress="upload_progress",e.UploadFinished="upload_finished",e.UploadFailed="upload_failed",e.UploadCanceled="upload_canceled",e.JoinRoom="join_room",e.JoinRoomReady="join_room_ready",e.JoinRoomError="join_room_error",e.BulkRedactStart="bulk_redact_start",e.BulkRedactEnd="bulk_redact_end",e.ComposerInsert="composer_insert",e.SwitchSpace="switch_space",e.UpdateSpaceHierarchy="update_space_hierarchy",e.SettingUpdated="setting_updated",e.EditEvent="edit_event",e.PseudonymousAnalyticsAccept="pseudonymous_analytics_accept",e.PseudonymousAnalyticsReject="pseudonymous_analytics_reject",e.ReportKeyBackupNotEnabled="report_key_backup_not_enabled",e.AfterLeaveRoom="after_leave_room",e.DoAfterSyncPrepared="do_after_sync_prepared",e.ViewStartChatOrReuse="view_start_chat_or_reuse",e.ActiveRoomChanged="active_room_changed",e.OpenForwardDialog="open_forward_dialog",e.OpenReportEventDialog="open_report_event_dialog",e.TriggerLogout="trigger_logout",e.OpenSpacePreferences="open_space_preferences",e.OpenSpaceSettings="open_space_settings",e.OpenInviteDialog="open_invite_dialog",e.OpenAddToExistingSpaceDialog="open_add_to_existing_space_dialog",e.DumpDebugLogs="dump_debug_logs",e.ShowRoomTopic="show_room_topic",e.OnLoggedOut="on_logged_out",e.OnLoggedIn="on_logged_in",e.OverwriteLogin="overwrite_login",e.PlatformSet="platform_set",e.ShowThread="show_thread"}(r||(r={}))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"h",(function(){return o})),n.d(t,"e",(function(){return a})),n.d(t,"i",(function(){return s})),n.d(t,"j",(function(){return l})),n.d(t,"k",(function(){return c})),n.d(t,"o",(function(){return u})),n.d(t,"n",(function(){return d})),n.d(t,"r",(function(){return h})),n.d(t,"q",(function(){return p})),n.d(t,"p",(function(){return m})),n.d(t,"m",(function(){return g})),n.d(t,"d",(function(){return f})),n.d(t,"l",(function(){return _})),n.d(t,"a",(function(){return b})),n.d(t,"g",(function(){return v})),n.d(t,"f",(function(){return y})),n.d(t,"c",(function(){return E}));var r=n(15);let i,o,a;!function(e){e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.RoomPredecessor="org.matrix.msc3946.room_predecessor",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.KeyVerificationKey="m.key.verification.key",e.KeyVerificationAccept="m.key.verification.accept",e.KeyVerificationReady="m.key.verification.ready",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.PollStart="org.matrix.msc3381.poll.start",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy",e.GroupCallPrefix="org.matrix.msc3401.call",e.GroupCallMemberPrefix="org.matrix.msc3401.call.member"}(i||(i={})),function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"}(o||(o={})),function(e){e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request"}(a||(a={}));const s="type";let l;!function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"}(l||(l={}));const c="org.matrix.msgid",u=new r.c("m.room.purpose","org.matrix.msc3088.purpose"),d=new r.c("m.enabled","org.matrix.msc3088.enabled"),h=new r.c("m.data_tree","org.matrix.msc3089.data_tree"),p=new r.c("m.leaf","org.matrix.msc3089.leaf"),m=new r.c("m.branch","org.matrix.msc3089.branch"),g=new r.c("m.room.marker","org.matrix.msc2716.marker"),f=new r.c("with_relations","org.matrix.msc3912.with_relations"),_=new r.c("io.element.functional_members","io.element.functional_members"),b=new r.c("m.visibility","org.matrix.msc3531.visibility"),v=new r.c("enabled","org.matrix.msc3881.enabled"),y=new r.c("device_id","org.matrix.msc3881.device_id"),E=new r.c("m.local_notification_settings","org.matrix.msc3890.local_notification_settings")},function(e,t){function n(){return e.exports=n=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){"use strict";n.d(t,"b",(function(){return l})),n.d(t,"c",(function(){return c}));var r=n(130),i=n.n(r),o=n(120),a=n.n(o);const s=Object(o.createContext)(void 0);function l(){return Object(o.useContext)(s)}s.displayName="MatrixClientContext",t.a=s;const c=e=>{const t=e;return Object(o.forwardRef)(((e,n)=>{const r=Object(o.useContext)(s);return a.a.createElement(t,i()({ref:n},e,{mxClient:r}))}))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(121);class l extends a.a.PureComponent{render(){const{w:e,h:t,message:n}=this.props;return a.a.createElement("div",{className:"mx_Spinner"},n&&a.a.createElement(a.a.Fragment,null,a.a.createElement("div",{className:"mx_Spinner_Msg"},n)," "),a.a.createElement("div",{className:"mx_Spinner_icon",style:{width:e,height:t},"aria-label":Object(s.a)("Loading…"),role:"progressbar","data-testid":"spinner"}))}}i()(l,"defaultProps",{w:32,h:32})},function(e,t,n){"use strict";n.d(t,"a",(function(){return v}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(427),l=n.n(s),c=n(126),u=n.n(c),d=n(123),h=n(122),p=n(121),m=n(133),g=n(175),f=n(159),_=n(152),b=n(142);class v extends a.a.Component{constructor(e){super(e),i()(this,"matrixClient",void 0),i()(this,"onKeyDown",(e=>{var t,n;null===(t=(n=this.props).onKeyDown)||void 0===t||t.call(n,e);switch(Object(_.a)().getAccessibilityAction(e)){case b.h.Escape:if(!this.props.hasCancel)break;e.stopPropagation(),e.preventDefault(),this.props.onFinished()}})),i()(this,"onCancelClick",(()=>{this.props.onFinished()})),this.matrixClient=h.a.get()}render(){let e,t;this.props.hasCancel&&(e=a.a.createElement(d.a,{onClick:this.onCancelClick,className:"mx_Dialog_cancelButton","aria-label":Object(p.a)("Close dialog")})),this.props.headerImage&&(t=a.a.createElement("img",{className:"mx_Dialog_titleImage",src:this.props.headerImage,alt:""}));const n={onKeyDown:this.onKeyDown,role:"dialog","aria-describedby":this.props.contentId};return this.props["aria-label"]?n["aria-label"]=this.props["aria-label"]:n["aria-labelledby"]="mx_BaseDialog_title",a.a.createElement(m.a.Provider,{value:this.matrixClient},a.a.createElement(f.a,{screenName:this.props.screenName}),a.a.createElement(l.a,{returnFocus:!0,lockProps:n,className:u()({[this.props.className]:!0,mx_Dialog_fixedWidth:this.props.fixedWidth})},this.props.top,a.a.createElement("div",{className:u()("mx_Dialog_header",{mx_Dialog_headerWithButton:!!this.props.headerButton,mx_Dialog_headerWithCancel:!!e})},a.a.createElement(g.a,{size:"h2",className:u()("mx_Dialog_title",this.props.titleClass),id:"mx_BaseDialog_title"},t,this.props.title),this.props.headerButton,e),this.props.children))}}i()(v,"defaultProps",{hasCancel:!0,fixedWidth:!0})},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"setCryptoStoreFactory",(function(){return L})),n.d(t,"createClient",(function(){return U})),n.d(t,"createRoomWidgetClient",(function(){return j}));var r=n(350),i=n(351),o=n(424),a=n(147),s=n(514);n.d(t,"CRYPTO_ENABLED",(function(){return a.a})),n.d(t,"UNSTABLE_MSC3852_LAST_SEEN_UA",(function(){return a.g})),n.d(t,"PendingEventOrdering",(function(){return a.e})),n.d(t,"RoomVersionStability",(function(){return a.f})),n.d(t,"M_AUTHENTICATION",(function(){return a.c})),n.d(t,"ClientEvent",(function(){return a.b})),n.d(t,"MatrixClient",(function(){return a.d})),n.d(t,"fixNotificationCountOnDecryption",(function(){return a.h})),n.d(t,"RoomWidgetClient",(function(){return s.a}));var l=n(193);n.d(t,"HttpApiEvent",(function(){return l.d})),n.d(t,"ClientPrefix",(function(){return l.a})),n.d(t,"IdentityPrefix",(function(){return l.e})),n.d(t,"MediaPrefix",(function(){return l.h})),n.d(t,"HTTPError",(function(){return l.c})),n.d(t,"MatrixError",(function(){return l.f})),n.d(t,"ConnectionError",(function(){return l.b})),n.d(t,"Method",(function(){return l.i})),n.d(t,"timeoutSignal",(function(){return l.m})),n.d(t,"anySignal",(function(){return l.j})),n.d(t,"parseErrorResponse",(function(){return l.k})),n.d(t,"retryNetworkOperation",(function(){return l.l})),n.d(t,"MatrixHttpApi",(function(){return l.g}));var c=n(321);n.d(t,"AutoDiscoveryAction",(function(){return c.b})),n.d(t,"AutoDiscovery",(function(){return c.a}));var u=n(515);n.d(t,"Category",(function(){return u.a})),n.d(t,"SyncAccumulator",(function(){return u.b}));var d=n(288);n.d(t,"InvalidStoreState",(function(){return d.d})),n.d(t,"InvalidStoreError",(function(){return d.c})),n.d(t,"InvalidCryptoStoreState",(function(){return d.b})),n.d(t,"InvalidCryptoStoreError",(function(){return d.a})),n.d(t,"KeySignatureUploadError",(function(){return d.e}));var h=n(355);n.d(t,"BeaconEvent",(function(){return h.b})),n.d(t,"isTimestampInDuration",(function(){return h.d})),n.d(t,"getBeaconInfoIdentifier",(function(){return h.c})),n.d(t,"Beacon",(function(){return h.a}));var p=n(143);n.d(t,"EventStatus",(function(){return p.a})),n.d(t,"MatrixEventEvent",(function(){return p.c})),n.d(t,"MatrixEvent",(function(){return p.b}));var m=n(140);n.d(t,"KNOWN_SAFE_ROOM_VERSION",(function(){return m.a})),n.d(t,"NotificationCountType",(function(){return m.b})),n.d(t,"RoomEvent",(function(){return m.d})),n.d(t,"Room",(function(){return m.c})),n.d(t,"RoomNameType",(function(){return m.e}));var g=n(179);n.d(t,"Direction",(function(){return g.a})),n.d(t,"EventTimeline",(function(){return g.b}));var f=n(353);n.d(t,"DuplicateStrategy",(function(){return f.a})),n.d(t,"EventTimelineSet",(function(){return f.b}));var _=n(410);n.d(t,"PollEvent",(function(){return _.b})),n.d(t,"Poll",(function(){return _.a}));var b=n(184);n.d(t,"RoomMemberEvent",(function(){return b.b})),n.d(t,"RoomMember",(function(){return b.a}));var v=n(151);n.d(t,"RoomStateEvent",(function(){return v.b})),n.d(t,"RoomState",(function(){return v.a}));var y=n(222);n.d(t,"UserEvent",(function(){return y.b})),n.d(t,"User",(function(){return y.a})),n.d(t,"MatrixScheduler",(function(){return o.a}));var E=n(315);n.d(t,"Filter",(function(){return E.a}));var S=n(516);n.d(t,"TimelineWindow",(function(){return S.b})),n.d(t,"TimelineIndex",(function(){return S.a}));var w=n(425);n.d(t,"AuthType",(function(){return w.a})),n.d(t,"InteractiveAuth",(function(){return w.b}));var T=n(271);n.d(t,"SERVICE_TYPES",(function(){return T.a})),n.d(t,"MemoryStore",(function(){return i.a}));var C=n(492);n.d(t,"IndexedDBStore",(function(){return C.a})),n.d(t,"MemoryCryptoStore",(function(){return r.a}));var x=n(225);n.d(t,"IndexedDBCryptoStore",(function(){return x.a}));var F=n(352);n.d(t,"getHttpUriForMxc",(function(){return F.a}));var D=n(129);n.d(t,"EventType",(function(){return D.b})),n.d(t,"RelationType",(function(){return D.h})),n.d(t,"MsgType",(function(){return D.e})),n.d(t,"RoomCreateTypeField",(function(){return D.i})),n.d(t,"RoomType",(function(){return D.j})),n.d(t,"ToDeviceMessageId",(function(){return D.k})),n.d(t,"UNSTABLE_MSC3088_PURPOSE",(function(){return D.o})),n.d(t,"UNSTABLE_MSC3088_ENABLED",(function(){return D.n})),n.d(t,"UNSTABLE_MSC3089_TREE_SUBTYPE",(function(){return D.r})),n.d(t,"UNSTABLE_MSC3089_LEAF",(function(){return D.q})),n.d(t,"UNSTABLE_MSC3089_BRANCH",(function(){return D.p})),n.d(t,"UNSTABLE_MSC2716_MARKER",(function(){return D.m})),n.d(t,"MSC3912_RELATION_BASED_REDACTIONS_PROP",(function(){return D.d})),n.d(t,"UNSTABLE_ELEMENT_FUNCTIONAL_USERS",(function(){return D.l})),n.d(t,"EVENT_VISIBILITY_CHANGE_TYPE",(function(){return D.a})),n.d(t,"PUSHER_ENABLED",(function(){return D.g})),n.d(t,"PUSHER_DEVICE_ID",(function(){return D.f})),n.d(t,"LOCAL_NOTIFICATION_SETTINGS_PREFIX",(function(){return D.c}));var k=n(231);n.d(t,"PushRuleActionName",(function(){return k.d})),n.d(t,"TweakName",(function(){return k.g})),n.d(t,"ConditionOperator",(function(){return k.b})),n.d(t,"DMMemberCountCondition",(function(){return k.c})),n.d(t,"isDmMemberCountCondition",(function(){return k.h})),n.d(t,"ConditionKind",(function(){return k.a})),n.d(t,"PushRuleKind",(function(){return k.e})),n.d(t,"RuleId",(function(){return k.f}));var O=n(160);n.d(t,"Visibility",(function(){return O.f})),n.d(t,"Preset",(function(){return O.d})),n.d(t,"JoinRule",(function(){return O.c})),n.d(t,"RestrictedAllowType",(function(){return O.e})),n.d(t,"GuestAccess",(function(){return O.a})),n.d(t,"HistoryVisibility",(function(){return O.b}));n(675);var I=n(423);n.d(t,"SearchOrderBy",(function(){return I.a}));var A=n(504);n.d(t,"RoomSummary",(function(){return A.a}));var R=n(269);n.d(t,"ContentHelpers",(function(){return R}));var N=n(188);n.d(t,"createNewMatrixCall",(function(){return N.h}));var M=n(224);n.d(t,"GroupCallEvent",(function(){return M.c})),n.d(t,"GroupCallIntent",(function(){return M.d})),n.d(t,"GroupCallState",(function(){return M.e})),n.d(t,"GroupCallType",(function(){return M.f}));let P=()=>new r.a;function L(e){P=e}function B(t){var n,r,a;return t.store=null!==(n=t.store)&&void 0!==n?n:new i.a({localStorage:e.localStorage}),t.scheduler=null!==(r=t.scheduler)&&void 0!==r?r:new o.a,t.cryptoStore=null!==(a=t.cryptoStore)&&void 0!==a?a:P(),t}function U(e){return new a.d(B(e))}function j(e,t,n,r){return new s.a(e,t,n,B(r))}}.call(this,n(14))},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.DEVICE="device",e.ROOM_DEVICE="room-device",e.ROOM_ACCOUNT="room-account",e.ACCOUNT="account",e.ROOM="room",e.PLATFORM="platform",e.CONFIG="config",e.DEFAULT="default"}(r||(r={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return s}));var r=n(120),i=n(194);let o;!function(e){e.Room="Room",e.Thread="Thread",e.ThreadsList="ThreadsList",e.File="File",e.Notification="Notification",e.Search="Search",e.Pinned="Pinned"}(o||(o={}));const a=Object(r.createContext)({roomLoading:!0,peekLoading:!1,shouldPeek:!0,membersLoaded:!1,numUnreadMessages:0,canPeek:!1,showApps:!1,isPeeking:!1,showRightPanel:!0,joining:!1,showTopUnreadMessagesBar:!1,statusBarVisible:!1,canReact:!1,canSelfRedact:!1,canSendMessages:!1,resizing:!1,layout:i.a.Group,lowBandwidth:!1,alwaysShowTimestamps:!1,showTwelveHourTimestamps:!1,readMarkerInViewThresholdMs:3e3,readMarkerOutOfViewThresholdMs:3e4,showHiddenEvents:!1,showReadReceipts:!0,showRedactions:!0,showJoinLeaves:!0,showAvatarChanges:!0,showDisplaynameChanges:!0,matrixClientIsReady:!1,showUrlPreview:!1,timelineRenderingType:o.Room,threadId:void 0,liveTimeline:void 0,narrow:!1,activeCall:null,msc3946ProcessDynamicPredecessor:!1});function s(){return Object(r.useContext)(a)}a.displayName="RoomContext",t.b=a},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(132),i=n.n(r),o=n(13),a=n.n(o),s=n(120),l=n.n(s),c=n(126),u=n.n(c),d=n(149),h=n(161);const p=["element","inputRef","prefixComponent","postfixComponent","className","onValidate","children","tooltipContent","forceValidity","tooltipClassName","list","validateOnBlur","validateOnChange","validateOnFocus","usePlaceholderAsHint","forceTooltipVisible"];function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function g(e){for(var t=1;t{this.validate({focused:!0})}),200)),a()(this,"onFocus",(e=>{var t,n;this.setState({focused:!0}),this.props.validateOnFocus&&this.validate({focused:!0}),null===(t=(n=this.props).onFocus)||void 0===t||t.call(n,e)})),a()(this,"onChange",(e=>{var t,n;this.props.validateOnChange&&this.validateOnChange(),null===(t=(n=this.props).onChange)||void 0===t||t.call(n,e)})),a()(this,"onBlur",(e=>{var t,n;this.setState({focused:!1}),this.props.validateOnBlur&&this.validate({focused:!1}),null===(t=(n=this.props).onBlur)||void 0===t||t.call(n,e)})),this.state={feedbackVisible:!1,focused:!1},this.id=this.props.id||`${f}_${_++}`}focus(){var e;null===(e=this.inputRef.current)||void 0===e||e.focus(),this.setState({focused:!0})}async validate(e){var t,n;let{focused:r,allowEmpty:i=!0}=e;if(!this.props.onValidate)return;const o=null!==(t=null===(n=this.inputRef.current)||void 0===n?void 0:n.value)&&void 0!==t?t:null,{valid:a,feedback:s}=await this.props.onValidate({value:o,focused:r,allowEmpty:i});return this.state.focused&&s?this.setState({valid:a,feedback:s,feedbackVisible:!0}):this.setState({valid:a,feedbackVisible:!1}),a}render(){var e;const t=this.props,{element:n,inputRef:r,prefixComponent:o,postfixComponent:a,className:s,onValidate:c,children:d,tooltipContent:m,forceValidity:f,tooltipClassName:_,list:b,validateOnBlur:v,validateOnChange:y,validateOnFocus:E,usePlaceholderAsHint:S,forceTooltipVisible:w}=t,T=i()(t,p);this.inputRef=r||l.a.createRef(),T.placeholder=null!==(e=T.placeholder)&&void 0!==e?e:T.label,T.id=this.id,T.onFocus=this.onFocus,T.onChange=this.onChange,T.onBlur=this.onBlur;const C=g(g({},T),{},{ref:this.inputRef,list:b}),x=l.a.createElement(this.props.element,C,d);let F,D;o&&(F=l.a.createElement("span",{className:"mx_Field_prefix"},o)),a&&(D=l.a.createElement("span",{className:"mx_Field_postfix"},a));const k=null!=f,O=u()("mx_Field",`mx_Field_${this.props.element}`,s,{mx_Field_labelAlwaysTopLeft:o||S,mx_Field_placeholderIsHint:S,mx_Field_valid:k?f:c&&!0===this.state.valid,mx_Field_invalid:k?!f:c&&!1===this.state.valid});let I;return(m||this.state.feedback)&&(I=l.a.createElement(h.b,{tooltipClassName:u()("mx_Field_tooltip","mx_Tooltip_noMargin",_),visible:this.state.focused&&w||this.state.feedbackVisible,label:m||this.state.feedback,alignment:h.b.Alignment.Right})),l.a.createElement("div",{className:O},F,x,l.a.createElement("label",{htmlFor:this.id},this.props.label),D,I)}}a()(b,"defaultProps",{element:"input",type:"text",validateOnFocus:!0,validateOnBlur:!0,validateOnChange:!0})},function(e,t,n){"use strict";n.d(t,"a",(function(){return D})),n.d(t,"b",(function(){return O})),n.d(t,"d",(function(){return I})),n.d(t,"c",(function(){return A})),n.d(t,"e",(function(){return N}));var r=n(13),i=n.n(r),o=n(10),a=n(353),s=n(179),l=n(352),c=n(16),u=n(143),d=n(409),h=n(184),p=n(504),m=n(1),g=n(287),f=n(129),_=n(147),b=n(315),v=n(151),y=n(355),E=n(170),S=n(18),w=n(661),T=n(662),C=n(410);function x(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function F(e){for(var t=1;t3&&void 0!==arguments[3]?arguments[3]:{};super(),this.roomId=e,this.client=t,this.myUserId=n,this.opts=r,i()(this,"reEmitter",void 0),i()(this,"txnToEvent",new Map),i()(this,"notificationCounts",{}),i()(this,"threadNotifications",new Map),i()(this,"cachedThreadReadReceipts",new Map),i()(this,"oldestThreadedReceiptTs",1/0),i()(this,"unthreadedReceipts",new Map),i()(this,"timelineSets",void 0),i()(this,"polls",new Map),i()(this,"threadsTimelineSets",[]),i()(this,"filteredTimelineSets",{}),i()(this,"timelineNeedsRefresh",!1),i()(this,"pendingEventList",void 0),i()(this,"blacklistUnverifiedDevices",void 0),i()(this,"selfMembership",void 0),i()(this,"summaryHeroes",null),i()(this,"getTypeWarning",!1),i()(this,"getVersionWarning",!1),i()(this,"membersPromise",void 0),i()(this,"name",void 0),i()(this,"normalizedName",void 0),i()(this,"tags",{}),i()(this,"accountData",new Map),i()(this,"summary",null),i()(this,"timeline",void 0),i()(this,"oldState",void 0),i()(this,"currentState",void 0),i()(this,"relations",new w.a(this.client,this)),i()(this,"threads",new Map),i()(this,"lastThread",void 0),i()(this,"visibilityEvents",new Map),i()(this,"threadTimelineSetsPromise",null),i()(this,"threadsReady",!1),i()(this,"updateThreadRootEvents",((e,t,n)=>{var r,i;e.length&&(this.updateThreadRootEvent(null===(r=this.threadsTimelineSets)||void 0===r?void 0:r[0],e,t,n),e.hasCurrentUserParticipated&&this.updateThreadRootEvent(null===(i=this.threadsTimelineSets)||void 0===i?void 0:i[1],e,t,n))})),i()(this,"updateThreadRootEvent",((e,t,n,r)=>{e&&t.rootEvent&&(r&&e.removeEvent(t.id),E.e.hasServerSideSupport?e.addLiveEvent(t.rootEvent,{duplicateStrategy:a.a.Replace,fromCache:!1,roomState:this.currentState}):e.addEventToTimeline(t.rootEvent,e.getLiveTimeline(),{toStartOfTimeline:n}))})),i()(this,"applyRedaction",(e=>{if(e.isRedaction()){const t=e.event.redacts,n=t?this.findEventById(t):void 0;if(n){if(n.makeRedacted(e),n.isState()){const e=this.currentState.getStateEvents(n.getType(),n.getStateKey());(null==e?void 0:e.getId())===n.getId()&&this.currentState.setStateEvents([n])}this.emit(I.Redaction,e,this),this.visibilityEvents.delete(t),n.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e)}}})),this.setMaxListeners(100),this.reEmitter=new g.b(this),r.pendingEventOrdering=r.pendingEventOrdering||_.e.Chronological,this.name=e,this.normalizedName=e,this.timelineSets=[new a.b(this,r)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[I.Timeline,I.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===_.e.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then((e=>{const n=this.client.getEventMapper({toDevice:!1,decrypt:!1});e.forEach((async e=>{const r=n(e);await t.decryptEventIfNeeded(r),r.setStatus(d.a.NOT_SENT),this.addPendingEvent(r,r.getTxnId())}))}))),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}async createThreadsTimelineSets(){var e;if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if(null!==(e=this.client)&&void 0!==e&&e.supportsThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(E.g.My)]);const e=await this.threadTimelineSetsPromise;return this.threadsTimelineSets.push(...e),e}catch(e){return this.threadTimelineSetsPromise=null,null}return null}async decryptCriticalEvents(){if(!this.client.isCryptoEnabled())return;const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),n=t.findIndex((t=>t.event.event_id===e)),r=t.slice(n).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));await Promise.allSettled(r)}async decryptAllEvents(){if(!this.client.isCryptoEnabled())return;const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));await Promise.allSettled(e)}getCreator(){var e;const t=this.currentState.getStateEvents(f.b.RoomCreate,"");return null!==(e=null==t?void 0:t.getContent().creator)&&void 0!==e?e:null}getVersion(){var e;const t=this.currentState.getStateEvents(f.b.RoomCreate,"");return t?null!==(e=t.getContent().room_version)&&void 0!==e?e:"1":(this.getVersionWarning||(m.a.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}shouldUpgradeToVersion(){return k.includes(this.getVersion())?null:D}async getRecommendedVersion(){let e=(await this.client.getCapabilities())["m.room_versions"];if(!e){e={default:D,available:{}};for(const t of k)e.available[t]=_.f.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){m.a.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");if(e=(await this.client.getCapabilities(!0))["m.room_versions"],!e)return m.a.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}checkVersionAgainstCapability(e){const t=this.getVersion();m.a.log(`[${this.roomId}] Current version: ${t}`),m.a.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?m.a.warn(`URGENT upgrade required on ${this.roomId}`):m.a.warn(`Non-urgent upgrade required on ${this.roomId}`)),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(f.b.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=c.I(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,n;return null!==(t=null===(n=this.pendingEventList)||void 0===n?void 0:n.some((t=>t.getId()===e)))&&void 0!==t&&t}getPendingEvent(e){var t,n;return null!==(t=null===(n=this.pendingEventList)||void 0===n?void 0:n.find((t=>t.getId()===e)))&&void 0!==t?t:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();if(e.length){return e[e.length-1].getTs()}return Number.MIN_SAFE_INTEGER}getMyMembership(){var e;return null!==(e=this.selfMembership)&&void 0!==e?e:"leave"}getDMInviter(){const e=this.getMember(this.myUserId);if(e)return e.getDMInviter();if("invite"===this.selfMembership){var t;if(2===this.getInvitedAndJoinedMemberCount())return null===(t=this.summaryHeroes)||void 0===t?void 0:t[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 h.a(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(I.MyMembership,this,e,t))}async loadMembersFromServer(){const e=this.client.store.getSyncToken();return(await this.client.members(this.roomId,void 0,"leave",null!=e?e:void 0)).chunk}async loadMembers(){let e=!1,t=await this.client.store.getOutOfBandMembers(this.roomId);(null===t||this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId))&&(e=!0,t=await this.loadMembersFromServer(),m.a.log(`LL: got ${t.length} members from server for room ${this.roomId}`));return{memberEvents:t.filter(c.A).map(this.client.getEventMapper()),fromServer:e}}membersLoaded(){return!this.opts.lazyLoadMembers||this.currentState.outOfBandMembersReady()}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then((e=>(this.currentState.setOutOfBandMembers(e.memberEvents),e.fromServer))).catch((e=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),e}));return e.then((e=>{if(e){const e=this.currentState.getMembers().filter((e=>e.isOutOfBand())).map((e=>{var t;return null===(t=e.events.member)||void 0===t?void 0:t.event}));m.a.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{m.a.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{m.a.error(e)})),this.membersPromise=e,this.membersPromise}async clearLoadedMembersIfNeeded(){this.opts.lazyLoadMembers&&this.membersPromise&&(await this.loadMembersIfNeeded(),await this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=void 0)}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch((e=>{m.a.error(`error after clearing loaded members from room ${this.roomId} after leaving`),m.a.log(e)}))}async refreshLiveTimeline(){const e=this.getLiveTimeline(),t=e.getPaginationToken(s.b.FORWARDS),n=e.getPaginationToken(s.b.BACKWARDS),r=e.getEvents(),i=r[r.length-1];m.a.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${i&&i.getId()} liveTimelineBefore=${e.toString()} forwardPaginationToken=${t} backwardPaginationToken=${n}`);const o=this.getUnfilteredTimelineSet();let a;i?(this.resetLiveTimeline(null,null),this.emit(I.TimelineRefresh,this,o),a=await this.client.getEventTimeline(o,i.getId())):a=await this.client.getLatestTimeline(o);const l=o.getLiveTimeline();!l||null===l.getPaginationToken(s.a.Forward)&&null===l.getPaginationToken(s.a.Backward)&&0===l.getEvents().length?(m.a.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),a.setPaginationToken(t,s.b.FORWARDS),o.setLiveTimeline(a),this.fixUpLegacyTimelineFields()):m.a.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.`),this.setTimelineNeedsRefresh(!1),this.emit(I.TimelineRefresh,this,o)}resetLiveTimeline(e,t){for(const n of this.timelineSets)n.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);for(const n of this.threads.values())n.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const e=this.oldState,t=this.currentState;this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(s.b.BACKWARDS),this.currentState=this.getLiveTimeline().getState(s.b.FORWARDS),e!==this.oldState&&this.emit(I.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(I.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[v.b.Events,v.b.Members,v.b.NewMember,v.b.Update,v.b.Marker,y.b.New,y.b.Update,y.b.Destroy,y.b.LivenessChange]),this.reEmitter.reEmit(this.currentState,[v.b.Events,v.b.Members,v.b.NewMember,v.b.Update,v.b.Marker,y.b.New,y.b.Update,y.b.Destroy,y.b.LivenessChange]))}async hasUnverifiedDevices(){if(!this.client.isRoomEncrypted(this.roomId))return!1;const e=await this.getEncryptionTargetMembers();for(const t of e){if(this.client.getStoredDevicesForUser(t.userId).some((e=>e.isUnverified())))return!0}return!1}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){const t=this.findEventById(e),n=this.findThreadForEvent(t);return n?n.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const n=this.getThreads();for(let r=0;r0&&void 0!==arguments[0]?arguments[0]:O.Total,t=this.getRoomUnreadNotificationCount(e);for(const r of this.threadNotifications.values()){var n;t+=null!==(n=r[e])&&void 0!==n?n:0}return t}getUnreadCountForEventContext(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:O.Total,n=arguments.length>1?arguments[1]:void 0;return null!==(e=!!n.threadRootId&&!n.isThreadRoot?this.getThreadUnreadNotificationCount(n.threadRootId,t):this.getRoomUnreadNotificationCount(t))&&void 0!==e?e:0}getRoomUnreadNotificationCount(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:O.Total;return null!==(e=this.notificationCounts[t])&&void 0!==e?e:0}getThreadUnreadNotificationCount(e){var t,n;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:O.Total;return null!==(t=null===(n=this.threadNotifications.get(e))||void 0===n?void 0:n[r])&&void 0!==t?t:0}hasThreadUnreadNotification(){for(const n of this.threadNotifications.values()){var e,t;if((null!==(e=n.highlight)&&void 0!==e?e:0)>0||(null!==(t=n.total)&&void 0!==t?t:0)>0)return!0}return!1}setThreadUnreadNotificationCount(e,t,n){var r,i;const o=F({highlight:null===(r=this.threadNotifications.get(e))||void 0===r?void 0:r.highlight,total:null===(i=this.threadNotifications.get(e))||void 0===i?void 0:i.total},{[t]:n});this.threadNotifications.set(e,o),this.emit(I.UnreadNotifications,o,e)}get threadsAggregateNotificationType(){let e=null;for(const r of this.threadNotifications.values()){var t,n;if((null!==(t=r.highlight)&&void 0!==t?t:0)>0)return O.Highlight;(null!==(n=r.total)&&void 0!==n?n:0)>0&&!e&&(e=O.Total)}return e}resetThreadUnreadNotificationCount(e){if(e)for(const[t]of this.threadNotifications)e.includes(t)||this.threadNotifications.delete(t);else this.threadNotifications.clear();this.emit(I.UnreadNotifications)}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(I.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){const t=e["m.heroes"],n=e["m.joined_member_count"],r=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(r)&&this.currentState.setInvitedMemberCount(r),Array.isArray(t)&&(this.summaryHeroes=t.filter((e=>e!==this.myUserId)))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return void 0===this.blacklistUnverifiedDevices?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,r){let i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];const o=this.currentState.getStateEvents(f.b.RoomAvatar,"");if(!o&&!i)return null;const a=o?o.getContent().url:null;return a?Object(l.a)(e,a,t,n,r):null}getMxcAvatarUrl(){var e,t;return(null===(e=this.currentState.getStateEvents(f.b.RoomAvatar,""))||void 0===e||null===(t=e.getContent())||void 0===t?void 0:t.url)||null}getCanonicalAlias(){const e=this.currentState.getStateEvents(f.b.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(f.b.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,n,r){n.getTimelineSet().addEventsToTimeline(e,t,n,r)}getThread(e){var t;return null!==(t=this.threads.get(e))&&void 0!==t?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter((function(t){return t.membership===e}))}async getEncryptionTargetMembers(){await 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(f.b.RoomHistoryVisibility,"");return"joined"!==(null==t||null===(e=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){let{prepopulateTimeline:t=!0,useSyncEvents:n=!0,pendingEvents:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const i=Object.assign({filter:e,pendingEvents:r},this.opts),o=new a.b(this,i);this.reEmitter.reEmit(o,[I.Timeline,I.TimelineReset]),n&&(this.filteredTimelineSets[e.filterId]=o,this.timelineSets.push(o));const l=this.getLiveTimeline();if(t){l.getEvents().forEach((function(e){o.addLiveEvent(e)}));let e=l;for(;e.getNeighbouringTimeline(s.b.BACKWARDS);)e=e.getNeighbouringTimeline(s.b.BACKWARDS);o.getLiveTimeline().setPaginationToken(e.getPaginationToken(s.b.BACKWARDS),s.b.BACKWARDS)}else if(n){const e=l.getPaginationToken(s.a.Forward);o.getLiveTimeline().setPaginationToken(e,s.a.Backward)}return o}async getThreadListFilter(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E.g.All;const t=this.client.getUserId(),n=new b.a(t),r={room:{timeline:{[E.a.name]:[E.d.name]}}};e===E.g.My&&(r.room.timeline[E.b.name]=[t]),n.setDefinition(r);const i=await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,n);return n.filterId=i,n}async createThreadTimelineSet(e){let t;if(E.e.hasServerSideListSupport)t=new a.b(this,F(F({},this.opts),{},{pendingEvents:!1}),void 0,void 0,null!=e?e:E.g.All),this.reEmitter.reEmit(t,[I.Timeline,I.TimelineReset]);else if(E.e.hasServerSideSupport){const n=await this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(n,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new a.b(this,{pendingEvents:!1}),Array.from(this.threads).forEach((n=>{let[,r]=n;if(0===r.length)return;const i=r.timeline.some((e=>e.getSender()===this.client.getUserId()));(e!==E.g.My||i)&&t.getLiveTimeline().addEvent(r.rootEvent,{toStartOfTimeline:!1})}));return t}processThreadRoots(e,t){for(const n of e)s.b.setEventMetadata(n,this.currentState,t),this.getThread(n.getId())||this.createThread(n.getId(),n,[],t)}async fetchRoomThreads(){if(!this.threadsReady&&this.client.supportsThreads()){if(E.e.hasServerSideListSupport)await Promise.all([this.fetchRoomThreadList(E.g.All),this.fetchRoomThreadList(E.g.My)]);else{const n=await this.getThreadListFilter(),{chunk:r}=await this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,s.a.Backward,n);if(!r.length)return;const i=r.map(this.client.getEventMapper()).sort(((e,t)=>{const n=e.getServerAggregatedRelation(E.d.name),r=t.getServerAggregatedRelation(E.d.name);return n.latest_event.origin_server_ts-r.latest_event.origin_server_ts}));let o;const l=this.getLiveTimeline().getState(s.b.FORWARDS);for(const n of i){var e;const r={duplicateStrategy:a.a.Ignore,fromCache:!1,roomState:l};null===(e=this.threadsTimelineSets[0])||void 0===e||e.addLiveEvent(n,r);const i=n.getServerAggregatedRelation(E.d.name);var t;if(null!=i&&i.current_user_participated)null===(t=this.threadsTimelineSets[1])||void 0===t||t.addLiveEvent(n,r),o=n}this.processThreadRoots(i,!0),this.client.decryptEventIfNeeded(i[i.length-1]),o&&this.client.decryptEventIfNeeded(o)}this.on(E.f.NewReply,this.onThreadNewReply),this.on(E.f.Delete,this.onThreadDelete),this.threadsReady=!0}}async processPollEvents(e){const t=e=>{if(o.M_POLL_START.matches(e.getType()))try{const t=new C.a(e,this.client,this);this.polls.set(e.getId(),t),this.emit(C.b.New,t)}catch{}},n=e=>{const t=e.relationEventId;if(t&&this.polls.has(t)){const n=this.polls.get(t);null==n||n.onNewRelation(e)}},r=e=>{t(e),n(e)};for(const t of e)try{await this.client.decryptEventIfNeeded(t),r(t)}catch{}}async fetchRoomThreadList(e){const t=e===E.g.My?this.threadsTimelineSets[1]:this.threadsTimelineSets[0],{chunk:n,end:r}=await this.client.createThreadListMessagesRequest(this.roomId,null,void 0,s.a.Backward,t.threadListType,t.getFilter());if(t.getLiveTimeline().setPaginationToken(null!=r?r:null,s.a.Backward),!n.length)return;const i=n.map(this.client.getEventMapper());this.processThreadRoots(i,!0);const o=this.getLiveTimeline().getState(s.b.FORWARDS);for(const e of i)t.addLiveEvent(e,{duplicateStrategy:a.a.Replace,fromCache:!1,roomState:o})}onThreadNewReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);const n=this.getTimelineForEvent(e.id),r=null==n||null===(t=n.getEvents())||void 0===t?void 0:t.find((t=>t.getId()===e.id));r?e.clearEventMetadata(r):m.a.debug("onThreadDelete: Could not find root event in room timeline");for(const t of this.threadsTimelineSets)t.removeEvent(e.id)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}eventShouldLiveIn(e,t,n){var r,i;if(null===(r=this.client)||void 0===r||!r.supportsThreads())return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||null!=n&&n.has(e.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};if(e.isRelation(E.d.name))return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:e.threadRootId};const o=e.getAssociatedId(),a=null!==(i=this.findEventById(o))&&void 0!==i?i:null==t?void 0:t.find((e=>e.getId()===o));return a&&(e.isRelation()||e.isRedaction())?this.eventShouldLiveIn(a,t,n):null!=n&&n.has(e.relationEventId)?{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.relationEventId}:{shouldLiveInRoom:!0,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;const{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this.getThread(e);if(!r){var i;const o=null!==(i=this.findEventById(e))&&void 0!==i?i:t.find((t=>t.getId()===e));r=this.createThread(e,o,t,n)}r.addEvents(t,n)}processThreadedEvents(e,t){e.forEach(this.applyRedaction);const n={};for(const t of e){var r;const{threadId:e,shouldLiveInThread:i}=this.eventShouldLiveIn(t);i&&!n[e]&&(n[e]=[]),null===(r=n[e])||void 0===r||r.push(t)}Object.entries(n).map((e=>{let[n,r]=e;return this.addThreadedEvents(n,r,t)}))}createThread(e,t){var n,r,i;let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],a=arguments.length>3?arguments[3]:void 0;if(this.threads.has(e))return this.threads.get(e);if(t){const e=this.relations.getAllChildEventsForEvent(t.getId());null!=e&&e.length&&(o=o.concat(e.filter((e=>!e.isRelation(f.h.Replace)))))}const s=new E.e(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:null!==(n=this.cachedThreadReadReceipts.get(e))&&void 0!==n?n:[]});this.cachedThreadReadReceipts.delete(e),this.threads.set(s.id,s),s.addEvents(o,!1),this.reEmitter.reEmit(s,[E.f.Delete,E.f.Update,E.f.NewReply,I.Timeline,I.TimelineReset]);const l=(null===(r=this.lastThread)||void 0===r?void 0:r.rootEvent)&&(null==t?void 0:t.localTimestamp)&&(null===(i=this.lastThread.rootEvent)||void 0===i?void 0:i.localTimestamp)<(null==t?void 0:t.localTimestamp);return this.lastThread&&!l||(this.lastThread=s),this.threadsReady&&this.updateThreadRootEvents(s,a,!1),this.emit(E.f.New,s,a),s}processLiveEvent(e){this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);if(!e.getUnsigned().transaction_id&&e.getSender()===this.myUserId)for(const[t,n]of this.txnToEvent)if(n.getId()===e.getId()){m.a.debug("processLiveEvent: found sent event without txn ID: ",t,e.getId());const n=e.getUnsigned();n.transaction_id=t,e.setUnsigned(n);break}}addLiveEvent(e,t){const{duplicateStrategy:n,timelineWasEmpty:r,fromCache:i}=t;for(const t of this.timelineSets)t.addLiveEvent(e,{duplicateStrategy:n,fromCache:i,timelineWasEmpty:r});e.sender&&e.getType()!==f.b.RoomRedaction&&this.addReceipt(Object(T.b)(e.sender.userId,e,S.b.Read),!0)}addPendingEvent(e,t){if(e.status!==d.a.SENDING&&e.status!==d.a.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(s.b.setEventMetadata(e,this.getLiveTimeline().getState(s.b.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some((e=>e.status===d.a.NOT_SENT))&&(m.a.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(d.a.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let n=this.pendingEventList.find((e=>e.getId()===t));!n&&t&&(n=this.findEventById(t)),n&&(n.markLocallyRedacted(e),this.emit(I.Redaction,e,this))}}else for(const t of this.timelineSets)t.getFilter()?t.getFilter().filterRoomTimeline([e]).length&&t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1}):t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(I.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){const e=this.pendingEventList.map((e=>F(F({},e.event),{},{txn_id:e.getTxnId()}))).filter((e=>{const t=e.type===f.b.RoomMessageEncrypted,n=this.client.isRoomEncrypted(this.roomId);return t||!n}));this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){const n=t.getId(),r=e.getId(),i=t.status;m.a.debug(`Got remote echo for event ${n} -> ${r} old status ${i}`),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:o,threadId:a}=this.eventShouldLiveIn(e),s=a?this.getThread(a):null;if(null==s||s.setEventMetadata(t),null==s||s.timelineSet.handleRemoteEcho(t,n,r),o)for(const e of this.timelineSets)e.handleRemoteEcho(t,n,r);this.emit(I.LocalEchoUpdated,t,this,n,i)}updatePendingEvent(e,t,n){if(m.a.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${n}`),t==d.a.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==d.a.SENT){if(this.getTimelineForEvent(n)){const t=this.findEventById(n);if(!(null==t?void 0:t.getUnsigned().transaction_id)&&t){const n=t.getUnsigned();n.transaction_id=e.getTxnId(),t.setUnsigned(n),this.removeEvent(t.getId()),this.handleRemoteEcho(t,e)}return}}const r=e.status,i=e.getId();if(!r)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const o=R[r];if(null==o||!o.includes(t))throw new Error(`Invalid EventStatus transition ${r}->${t}`);if(e.setStatus(t),t==d.a.SENT){e.replaceLocalEventId(n);const{shouldLiveInRoom:t,threadId:r}=this.eventShouldLiveIn(e),o=r?this.getThread(r):void 0;if(null==o||o.setEventMetadata(e),null==o||o.timelineSet.replaceEventId(i,n),t)for(const e of this.timelineSets)e.replaceEventId(i,n)}else if(t==d.a.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(i);this.removePendingEvent(i),null!=e&&e.isRedaction()&&this.revertRedactionLocalEcho(e)}this.removeEvent(i)}this.savePendingEvents(),this.emit(I.LocalEchoUpdated,e,this,i,r)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit(I.RedactionCancelled,e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}addLiveEvents(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t,i=!1;if("object"==typeof t?({duplicateStrategy:r,fromCache:n=!1,timelineWasEmpty:i}=t):void 0!==t&&m.a.warn("Overload deprecated: `Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"),r&&-1===["replace","ignore"].indexOf(r))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(let e=0;e{let[t,n]=e;this.addThreadedEvents(t,n,!1)}))}partitionThreadedEvents(e){if(this.client.supportsThreads()){const t=this.findThreadRoots(e);return e.reduce(((n,r)=>{const{shouldLiveInRoom:i,shouldLiveInThread:o,threadId:a}=this.eventShouldLiveIn(r,e,t);return i&&n[0].push(r),o&&(r.setThreadId(null!=a?a:""),n[1].push(r)),n}),[[],[]])}return[e,[]]}findThreadRoots(e){const t=new Set;for(const r of e){var n;if(r.isRelation(E.d.name))t.add(null!==(n=r.relationEventId)&&void 0!==n?n:"")}return t}addReceipt(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.getContent();Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((r=>{Object.keys(n[e][r]).forEach((i=>{var o,a,s;const l=n[e][r][i],c=!l.thread_id||l.thread_id===S.a,u=c?this:this.threads.get(null!==(o=l.thread_id)&&void 0!==o?o:"");var d;if(u){if(u.addReceiptToStructure(e,r,i,l,t),this.client.isInitialSyncComplete()&&i===this.client.getUserId()){const t=u.timeline[u.timeline.length-1];t&&e===t.getId()&&i===t.getSender()&&(u.setUnread(O.Total,0),u.setUnread(O.Highlight,0))}}else this.cachedThreadReadReceipts.set(l.thread_id,[...null!==(d=this.cachedThreadReadReceipts.get(l.thread_id))&&void 0!==d?d:[],{eventId:e,receiptType:r,userId:i,receipt:l,synthetic:t}]);i===this.client.getUserId()&&!c&&l.ts(null!==(a=null===(s=this.unthreadedReceipts.get(i))||void 0===s?void 0:s.ts)&&void 0!==a?a:0)&&this.unthreadedReceipts.set(i,l)}))}))})),this.emit(I.Receipt,e,this)}addEphemeralEvents(e){for(const t of e)t.getType()===f.b.Typing?this.currentState.setTypingEvent(t):t.getType()===f.b.Receipt&&this.addReceipt(t)}removeEvents(e){for(const t of e)this.removeEvent(t)}removeEvent(e){let t=!1;for(const n of this.timelineSets){const r=n.removeEvent(e);r&&(r.isRedaction()&&this.revertRedactionLocalEcho(r),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(f.b.RoomMember,this.myUserId);if(e){const t=e.getContent().membership;if(this.updateMyMembership(t),"invite"===t){(e.getUnsigned().invite_room_state||[]).forEach((e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new u.b({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=Object(c.B)(this.name),this.summary=new p.a(this.roomId,{title:this.name}),t!==this.name&&this.emit(I.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(I.Tags,e,this)}addAccountData(e){for(const t of e){"m.tag"===t.getType()&&this.addTags(t);const e=t.getType(),n=this.accountData.get(e);this.accountData.set(e,t),this.emit(I.AccountData,t,this,n)}}getAccountData(e){return this.accountData.get(e)}maySendMessage(){return"join"===this.getMyMembership()&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(f.b.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(f.b.RoomMessage,this.myUserId))}canInvite(e){let t="join"===this.getMyMembership();const n=this.currentState.getStateEvents(f.b.RoomPowerLevels,""),r=n&&n.getContent(),i=this.getMember(e);return r&&i&&r.invite>i.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(f.b.RoomCreate,"");if(e)return e.getContent()[f.i];this.getTypeWarning||(m.a.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===f.j.Space}isCallRoom(){return this.getType()===f.j.UnstableCall}isElementVideoRoom(){return this.getType()===f.j.ElementVideo}findPredecessor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const t=this.getLiveTimeline().getState(s.b.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){const t=this.client.roomNameGenerator(this.roomId,e);if(null!==t)return t}switch(e.type){case N.Actual:return e.name;case N.Generated:return"Inviting"===e.subtype?`Inviting ${M(e.names,e.count)}`:M(e.names,e.count);case N.EmptyRoom:return e.oldName?`Empty room (was ${e.oldName})`:"Empty room"}}calculateRoomName(e){if(!(arguments.length>1&&void 0!==arguments[1]&&arguments[1])){const e=this.currentState.getStateEvents(f.b.RoomName,"");if(null!=e&&e.getContent().name)return this.roomNameGenerator({type:N.Actual,name:e.getContent().name})}const t=this.getCanonicalAlias();if(t)return this.roomNameGenerator({type:N.Actual,name:t});let n=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,r=[];const i=this.currentState.getStateEvents(f.l.name,"");Array.isArray(null==i?void 0:i.getContent().service_members)&&(r=i.getContent().service_members);let o=[];if(this.summaryHeroes)this.summaryHeroes.forEach((e=>{if(r.includes(e))return void n--;const t=this.getMember(e);o.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((e=>{let{userId:t}=e;return!r.includes(t)||(n--,!1)})),t.sort(((e,t)=>c.h(e.userId,t.userId))),t=t.slice(0,5),o=t.map((e=>e.name))}if(n)return this.roomNameGenerator({type:N.Generated,names:o,count:n});if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(f.b.RoomThirdPartyInvite);if(null!=e&&e.length){const t=e.map((e=>e.getContent().display_name));return this.roomNameGenerator({type:N.Generated,subtype:"Inviting",names:t,count:t.length+1})}}let a,s=o;return s.length||(s=this.currentState.getMembers().filter((t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership)).map((e=>e.name))),s.length&&(a=this.roomNameGenerator({type:N.Generated,names:s,count:s.length+1})),this.roomNameGenerator({type:N.EmptyRoom,oldName:a})}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const n=e.getSender();if(!n)return;if(!(f.a.name&&this.currentState.maySendStateEvent(f.a.name,n)||f.a.altName&&this.currentState.maySendStateEvent(f.a.altName,n)))return;const r=this.visibilityEvents.get(t.eventId);if(r){let t=r.length-1;const n=Math.max(0,r.length-30);for(;t>=n;--t){if(r[t].getTs()t.getId()===e.getId()));if(-1!==i&&(r.splice(i,1),i===r.length)){const e=this.findEventById(n);if(!e)return;if(0===i)this.visibilityEvents.delete(n),e.applyVisibilityEvent();else{const t=r[r.length-1].asVisibilityChange();if(!t)throw new Error("at this stage, visibility changes should be well-formed");e.applyVisibilityEvent(t)}}}applyPendingVisibilityEvents(e){const t=this.visibilityEvents.get(e.getId());if(!t||0==t.length)return;const n=t[t.length-1],r=n.asVisibilityChange();r&&(r.visible,n.getTs()this.getThreadUnreadNotificationCount(e.id,O.Total)>0));for(const n of t)n.fixupNotifications(e)}}const R={[d.a.ENCRYPTING]:[d.a.SENDING,d.a.NOT_SENT,d.a.CANCELLED],[d.a.SENDING]:[d.a.ENCRYPTING,d.a.QUEUED,d.a.NOT_SENT,d.a.SENT],[d.a.QUEUED]:[d.a.SENDING,d.a.NOT_SENT,d.a.CANCELLED],[d.a.SENT]:[],[d.a.NOT_SENT]:[d.a.SENDING,d.a.QUEUED,d.a.CANCELLED],[d.a.CANCELLED]:[]};let N;function M(e,t){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"}!function(e){e[e.EmptyRoom=0]="EmptyRoom",e[e.Generated=1]="Generated",e[e.Actual=2]="Actual"}(N||(N={}))},function(e,t,n){"use strict";n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o})),n.d(t,"d",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(120);function i(e,t,n){o(e,t,n)}function o(e,t,n){const i=Object(r.useRef)(n);Object(r.useEffect)((()=>{i.current=n}),[n]),Object(r.useEffect)((()=>{if(!e)return;const n=function(){return i.current(...arguments)};return e.on(t,n),()=>{e.off(t,n)}}),[t,e])}function a(e,t,n){return s(e,t,n)}function s(e,t,n){const[i,a]=Object(r.useState)(n),s=Object(r.useCallback)((function(){a(n(...arguments))}),[n]);return Object(r.useEffect)(s,[e]),o(e,t,s),i}},function(e,t,n){"use strict";n.d(t,"h",(function(){return o})),n.d(t,"c",(function(){return a})),n.d(t,"e",(function(){return s})),n.d(t,"a",(function(){return l})),n.d(t,"g",(function(){return c})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"i",(function(){return h})),n.d(t,"f",(function(){return p}));var r=n(121),i=n(205);let o,a;!function(e){e.SendMessage="KeyBinding.sendMessageInComposer",e.SelectPrevSendHistory="KeyBinding.previousMessageInComposerHistory",e.SelectNextSendHistory="KeyBinding.nextMessageInComposerHistory",e.EditPrevMessage="KeyBinding.editPreviousMessage",e.EditNextMessage="KeyBinding.editNextMessage",e.CancelReplyOrEdit="KeyBinding.cancelReplyInComposer",e.ShowStickerPicker="KeyBinding.showStickerPicker",e.FormatBold="KeyBinding.toggleBoldInComposer",e.FormatItalics="KeyBinding.toggleItalicsInComposer",e.FormatLink="KeyBinding.FormatLink",e.FormatCode="KeyBinding.FormatCode",e.FormatQuote="KeyBinding.toggleQuoteInComposer",e.EditUndo="KeyBinding.editUndoInComposer",e.EditRedo="KeyBinding.editRedoInComposer",e.NewLine="KeyBinding.newLineInComposer",e.MoveCursorToStart="KeyBinding.jumpToStartInComposer",e.MoveCursorToEnd="KeyBinding.jumpToEndInComposer",e.CompleteAutocomplete="KeyBinding.completeAutocomplete",e.ForceCompleteAutocomplete="KeyBinding.forceCompleteAutocomplete",e.PrevSelectionInAutocomplete="KeyBinding.previousOptionInAutoComplete",e.NextSelectionInAutocomplete="KeyBinding.nextOptionInAutoComplete",e.CancelAutocomplete="KeyBinding.cancelAutoComplete",e.ClearRoomFilter="KeyBinding.clearRoomFilter",e.PrevRoom="KeyBinding.downerRoom",e.NextRoom="KeyBinding.upperRoom",e.SelectRoomInRoomList="KeyBinding.selectRoomInRoomList",e.CollapseRoomListSection="KeyBinding.collapseSectionInRoomList",e.ExpandRoomListSection="KeyBinding.expandSectionInRoomList",e.ScrollUp="KeyBinding.scrollUpInTimeline",e.ScrollDown="KeyBinding.scrollDownInTimeline",e.DismissReadMarker="KeyBinding.dismissReadMarkerAndJumpToBottom",e.JumpToOldestUnread="KeyBinding.jumpToOldestUnreadMessage",e.UploadFile="KeyBinding.uploadFileToRoom",e.SearchInRoom="KeyBinding.searchInRoom",e.JumpToFirstMessage="KeyBinding.jumpToFirstMessageInTimeline",e.JumpToLatestMessage="KeyBinding.jumpToLastMessageInTimeline",e.FilterRooms="KeyBinding.filterRooms",e.ToggleSpacePanel="KeyBinding.toggleSpacePanel",e.ToggleRoomSidePanel="KeyBinding.toggleRightPanel",e.ToggleUserMenu="KeyBinding.toggleTopLeftMenu",e.ShowKeyboardSettings="KeyBinding.showKeyBindingsSettings",e.GoToHome="KeyBinding.goToHomeView",e.SelectPrevRoom="KeyBinding.previousRoom",e.SelectNextRoom="KeyBinding.nextRoom",e.SelectPrevUnreadRoom="KeyBinding.previousUnreadRoom",e.SelectNextUnreadRoom="KeyBinding.nextUnreadRoom",e.SwitchToSpaceByNumber="KeyBinding.switchToSpaceByNumber",e.OpenUserSettings="KeyBinding.openUserSettings",e.PreviousVisitedRoomOrSpace="KeyBinding.PreviousVisitedRoomOrSpace",e.NextVisitedRoomOrSpace="KeyBinding.NextVisitedRoomOrSpace",e.ToggleMicInCall="KeyBinding.toggleMicInCall",e.ToggleWebcamInCall="KeyBinding.toggleWebcamInCall",e.Escape="KeyBinding.escape",e.Enter="KeyBinding.enter",e.Space="KeyBinding.space",e.Backspace="KeyBinding.backspace",e.Delete="KeyBinding.delete",e.Home="KeyBinding.home",e.End="KeyBinding.end",e.ArrowLeft="KeyBinding.arrowLeft",e.ArrowUp="KeyBinding.arrowUp",e.ArrowRight="KeyBinding.arrowRight",e.ArrowDown="KeyBinding.arrowDown",e.Tab="KeyBinding.tab",e.Comma="KeyBinding.comma",e.ToggleHiddenEventVisibility="KeyBinding.toggleHiddenEventVisibility"}(o||(o={})),function(e){e.NAVIGATION="Navigation",e.ACCESSIBILITY="Accessibility",e.CALLS="Calls",e.COMPOSER="Composer",e.ROOM_LIST="Room List",e.ROOM="Room",e.AUTOCOMPLETE="Autocomplete",e.LABS="Labs"}(a||(a={}));const s="digits",l={[i.b.PAGE_UP]:Object(r.c)("Page Up"),[i.b.PAGE_DOWN]:Object(r.c)("Page Down"),[i.b.ESCAPE]:Object(r.c)("Esc"),[i.b.ENTER]:Object(r.c)("Enter"),[i.b.SPACE]:Object(r.c)("Space"),[i.b.HOME]:Object(r.c)("Home"),[i.b.END]:Object(r.c)("End"),[i.b.ALT]:Object(r.c)("Alt"),[i.b.CONTROL]:Object(r.c)("Ctrl"),[i.b.SHIFT]:Object(r.c)("Shift"),[s]:Object(r.c)("[number]")},c={[i.b.ARROW_UP]:"↑",[i.b.ARROW_DOWN]:"↓",[i.b.ARROW_LEFT]:"←",[i.b.ARROW_RIGHT]:"→"};i.a&&(c[i.b.META]="⌘",c[i.b.ALT]="⌥");const u={[a.COMPOSER]:{categoryLabel:Object(r.c)("Composer"),settingNames:[o.SendMessage,o.NewLine,o.FormatBold,o.FormatItalics,o.FormatQuote,o.FormatLink,o.FormatCode,o.EditUndo,o.EditRedo,o.MoveCursorToStart,o.MoveCursorToEnd,o.CancelReplyOrEdit,o.EditNextMessage,o.EditPrevMessage,o.SelectNextSendHistory,o.SelectPrevSendHistory,o.ShowStickerPicker]},[a.CALLS]:{categoryLabel:Object(r.c)("Calls"),settingNames:[o.ToggleMicInCall,o.ToggleWebcamInCall]},[a.ROOM]:{categoryLabel:Object(r.c)("Room"),settingNames:[o.SearchInRoom,o.UploadFile,o.DismissReadMarker,o.JumpToOldestUnread,o.ScrollUp,o.ScrollDown,o.JumpToFirstMessage,o.JumpToLatestMessage]},[a.ROOM_LIST]:{categoryLabel:Object(r.c)("Room List"),settingNames:[o.SelectRoomInRoomList,o.ClearRoomFilter,o.CollapseRoomListSection,o.ExpandRoomListSection,o.NextRoom,o.PrevRoom]},[a.ACCESSIBILITY]:{categoryLabel:Object(r.c)("Accessibility"),settingNames:[o.Escape,o.Enter,o.Space,o.Backspace,o.Delete,o.Home,o.End,o.ArrowLeft,o.ArrowUp,o.ArrowRight,o.ArrowDown,o.Comma]},[a.NAVIGATION]:{categoryLabel:Object(r.c)("Navigation"),settingNames:[o.ToggleUserMenu,o.ToggleRoomSidePanel,o.ToggleSpacePanel,o.ShowKeyboardSettings,o.GoToHome,o.FilterRooms,o.SelectNextUnreadRoom,o.SelectPrevUnreadRoom,o.SelectNextRoom,o.SelectPrevRoom,o.OpenUserSettings,o.SwitchToSpaceByNumber,o.PreviousVisitedRoomOrSpace,o.NextVisitedRoomOrSpace]},[a.AUTOCOMPLETE]:{categoryLabel:Object(r.c)("Autocomplete"),settingNames:[o.CancelAutocomplete,o.NextSelectionInAutocomplete,o.PrevSelectionInAutocomplete,o.CompleteAutocomplete,o.ForceCompleteAutocomplete]},[a.LABS]:{categoryLabel:Object(r.c)("Labs"),settingNames:[o.ToggleHiddenEventVisibility]}},d=[o.OpenUserSettings,o.SwitchToSpaceByNumber,o.PreviousVisitedRoomOrSpace,o.NextVisitedRoomOrSpace],h=[o.OpenUserSettings],p={[o.FormatBold]:{default:{ctrlOrCmdKey:!0,key:i.b.B},displayName:Object(r.c)("Toggle Bold")},[o.FormatItalics]:{default:{ctrlOrCmdKey:!0,key:i.b.I},displayName:Object(r.c)("Toggle Italics")},[o.FormatQuote]:{default:{ctrlOrCmdKey:!0,shiftKey:!0,key:i.b.GREATER_THAN},displayName:Object(r.c)("Toggle Quote")},[o.FormatCode]:{default:{ctrlOrCmdKey:!0,key:i.b.E},displayName:Object(r.c)("Toggle Code Block")},[o.FormatLink]:{default:{ctrlOrCmdKey:!0,shiftKey:!0,key:i.b.L},displayName:Object(r.c)("Toggle Link")},[o.CancelReplyOrEdit]:{default:{key:i.b.ESCAPE},displayName:Object(r.c)("Cancel replying to a message")},[o.EditNextMessage]:{default:{key:i.b.ARROW_DOWN},displayName:Object(r.c)("Navigate to next message to edit")},[o.EditPrevMessage]:{default:{key:i.b.ARROW_UP},displayName:Object(r.c)("Navigate to previous message to edit")},[o.MoveCursorToStart]:{default:{ctrlOrCmdKey:!0,key:i.b.HOME},displayName:Object(r.c)("Jump to start of the composer")},[o.MoveCursorToEnd]:{default:{ctrlOrCmdKey:!0,key:i.b.END},displayName:Object(r.c)("Jump to end of the composer")},[o.SelectNextSendHistory]:{default:{altKey:!0,ctrlKey:!0,key:i.b.ARROW_DOWN},displayName:Object(r.c)("Navigate to next message in composer history")},[o.SelectPrevSendHistory]:{default:{altKey:!0,ctrlKey:!0,key:i.b.ARROW_UP},displayName:Object(r.c)("Navigate to previous message in composer history")},[o.ShowStickerPicker]:{default:{ctrlOrCmdKey:!0,key:i.b.SEMICOLON},displayName:Object(r.c)("Send a sticker")},[o.ToggleMicInCall]:{default:{ctrlOrCmdKey:!0,key:i.b.D},displayName:Object(r.c)("Toggle microphone mute")},[o.ToggleWebcamInCall]:{default:{ctrlOrCmdKey:!0,key:i.b.E},displayName:Object(r.c)("Toggle webcam on/off")},[o.DismissReadMarker]:{default:{key:i.b.ESCAPE},displayName:Object(r.c)("Dismiss read marker and jump to bottom")},[o.JumpToOldestUnread]:{default:{shiftKey:!0,key:i.b.PAGE_UP},displayName:Object(r.c)("Jump to oldest unread message")},[o.UploadFile]:{default:{ctrlOrCmdKey:!0,shiftKey:!0,key:i.b.U},displayName:Object(r.c)("Upload a file")},[o.ScrollUp]:{default:{key:i.b.PAGE_UP},displayName:Object(r.c)("Scroll up in the timeline")},[o.ScrollDown]:{default:{key:i.b.PAGE_DOWN},displayName:Object(r.c)("Scroll down in the timeline")},[o.FilterRooms]:{default:{ctrlOrCmdKey:!0,key:i.b.K},displayName:Object(r.c)("Jump to room search")},[o.SelectRoomInRoomList]:{default:{key:i.b.ENTER},displayName:Object(r.c)("Select room from the room list")},[o.CollapseRoomListSection]:{default:{key:i.b.ARROW_LEFT},displayName:Object(r.c)("Collapse room list section")},[o.ExpandRoomListSection]:{default:{key:i.b.ARROW_RIGHT},displayName:Object(r.c)("Expand room list section")},[o.NextRoom]:{default:{key:i.b.ARROW_DOWN},displayName:Object(r.c)("Navigate down in the room list")},[o.PrevRoom]:{default:{key:i.b.ARROW_UP},displayName:Object(r.c)("Navigate up in the room list")},[o.ToggleUserMenu]:{default:{ctrlOrCmdKey:!0,key:i.b.BACKTICK},displayName:Object(r.c)("Toggle the top left menu")},[o.ToggleRoomSidePanel]:{default:{ctrlOrCmdKey:!0,key:i.b.PERIOD},displayName:Object(r.c)("Toggle right panel")},[o.ShowKeyboardSettings]:{default:{ctrlOrCmdKey:!0,key:i.b.SLASH},displayName:Object(r.c)("Open this settings tab")},[o.GoToHome]:{default:{ctrlOrCmdKey:!0,altKey:!i.a,shiftKey:i.a,key:i.b.H},displayName:Object(r.c)("Go to Home View")},[o.SelectNextUnreadRoom]:{default:{shiftKey:!0,altKey:!0,key:i.b.ARROW_DOWN},displayName:Object(r.c)("Next unread room or DM")},[o.SelectPrevUnreadRoom]:{default:{shiftKey:!0,altKey:!0,key:i.b.ARROW_UP},displayName:Object(r.c)("Previous unread room or DM")},[o.SelectNextRoom]:{default:{altKey:!0,key:i.b.ARROW_DOWN},displayName:Object(r.c)("Next room or DM")},[o.SelectPrevRoom]:{default:{altKey:!0,key:i.b.ARROW_UP},displayName:Object(r.c)("Previous room or DM")},[o.CancelAutocomplete]:{default:{key:i.b.ESCAPE},displayName:Object(r.c)("Cancel autocomplete")},[o.NextSelectionInAutocomplete]:{default:{key:i.b.ARROW_DOWN},displayName:Object(r.c)("Next autocomplete suggestion")},[o.PrevSelectionInAutocomplete]:{default:{key:i.b.ARROW_UP},displayName:Object(r.c)("Previous autocomplete suggestion")},[o.ToggleSpacePanel]:{default:{ctrlOrCmdKey:!0,shiftKey:!0,key:i.b.D},displayName:Object(r.c)("Toggle space panel")},[o.ToggleHiddenEventVisibility]:{default:{ctrlOrCmdKey:!0,shiftKey:!0,key:i.b.H},displayName:Object(r.c)("Toggle hidden event visibility")},[o.JumpToFirstMessage]:{default:{key:i.b.HOME,ctrlKey:!0},displayName:Object(r.c)("Jump to first message")},[o.JumpToLatestMessage]:{default:{key:i.b.END,ctrlKey:!0},displayName:Object(r.c)("Jump to last message")},[o.EditUndo]:{default:{key:i.b.Z,ctrlOrCmdKey:!0},displayName:Object(r.c)("Undo edit")},[o.EditRedo]:{default:{key:i.a?i.b.Z:i.b.Y,ctrlOrCmdKey:!0,shiftKey:i.a},displayName:Object(r.c)("Redo edit")},[o.PreviousVisitedRoomOrSpace]:{default:{metaKey:i.a,altKey:!i.a,key:i.a?i.b.SQUARE_BRACKET_LEFT:i.b.ARROW_LEFT},displayName:Object(r.c)("Previous recently visited room or space")},[o.NextVisitedRoomOrSpace]:{default:{metaKey:i.a,altKey:!i.a,key:i.a?i.b.SQUARE_BRACKET_RIGHT:i.b.ARROW_RIGHT},displayName:Object(r.c)("Next recently visited room or space")},[o.SwitchToSpaceByNumber]:{default:{ctrlOrCmdKey:!0,key:s},displayName:Object(r.c)("Switch to space by number")},[o.OpenUserSettings]:{default:{metaKey:!0,key:i.b.COMMA},displayName:Object(r.c)("Open user settings")},[o.Escape]:{default:{key:i.b.ESCAPE},displayName:Object(r.c)("Close dialog or context menu")},[o.Enter]:{default:{key:i.b.ENTER},displayName:Object(r.c)("Activate selected button")},[o.Space]:{default:{key:i.b.SPACE}},[o.Backspace]:{default:{key:i.b.BACKSPACE}},[o.Delete]:{default:{key:i.b.DELETE}},[o.Home]:{default:{key:i.b.HOME}},[o.End]:{default:{key:i.b.END}},[o.ArrowLeft]:{default:{key:i.b.ARROW_LEFT}},[o.ArrowUp]:{default:{key:i.b.ARROW_UP}},[o.ArrowRight]:{default:{key:i.b.ARROW_RIGHT}},[o.ArrowDown]:{default:{key:i.b.ARROW_DOWN}},[o.Comma]:{default:{key:i.b.COMMA}}}},function(e,t,n){"use strict";n.d(t,"c",(function(){return f})),n.d(t,"b",(function(){return _}));var r=n(13),i=n.n(r),o=n(10),a=n(1),s=n(129),l=n(16),c=n(170),u=n(287),d=n(158),h=n(654),p=n(511),m=n(409);n.d(t,"a",(function(){return m.a}));const g=Object.freeze({visible:!0});let f;!function(e){e.Decrypted="Event.decrypted",e.BeforeRedaction="Event.beforeRedaction",e.VisibilityChange="Event.visibilityChange",e.LocalEventIdReplaced="Event.localEventIdReplaced",e.Status="Event.status",e.Replaced="Event.replaced",e.RelationsCreated="Event.relationsCreated"}(f||(f={}));class _ extends d.b{constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.event=t,i()(this,"pushActions",null),i()(this,"_replacingEvent",null),i()(this,"_localRedactionEvent",null),i()(this,"_isCancelled",!1),i()(this,"clearEvent",void 0),i()(this,"visibility",g),i()(this,"_hasCachedExtEv",!1),i()(this,"_cachedExtEv",void 0),i()(this,"senderCurve25519Key",null),i()(this,"claimedEd25519Key",null),i()(this,"forwardingCurve25519KeyChain",[]),i()(this,"untrusted",null),i()(this,"decryptionPromise",null),i()(this,"retryDecryption",!1),i()(this,"txnId",void 0),i()(this,"thread",void 0),i()(this,"threadId",void 0),i()(this,"encryptedDisabledForUnverifiedDevices",!1),i()(this,"localTimestamp",void 0),i()(this,"sender",null),i()(this,"target",null),i()(this,"status",null),i()(this,"error",null),i()(this,"forwardLooking",!0),i()(this,"verificationRequest",void 0),i()(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach((e=>{"string"==typeof t[e]&&(t[e]=Object(l.t)(t[e]))})),["membership","avatar_url","displayname"].forEach((e=>{var n;"string"==typeof(null===(n=t.content)||void 0===n?void 0:n[e])&&(t.content[e]=Object(l.t)(t.content[e]))})),["rel_type"].forEach((e=>{var n,r;"string"==typeof(null===(n=t.content)||void 0===n||null===(r=n["m.relates_to"])||void 0===r?void 0:r[e])&&(t.content["m.relates_to"][e]=Object(l.t)(t.content["m.relates_to"][e]))})),this.txnId=t.txn_id,this.localTimestamp=Date.now()-(null!==(e=this.getAge())&&void 0!==e?e:0),this.reEmitter=new u.b(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=o.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===s.b.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}getDetails(){let e=`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`;const t=this.getRoomId();t&&(e+=` room=${t}`);const n=this.getDate();return n&&(e+=` ts=${n.toISOString()}`),e}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e;const t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];return(null==t?void 0:t.rel_type)===c.d.name?t.event_id:(null===(n=this.getThread())||void 0===n?void 0:n.id)||this.threadId;var n}get isThreadRoot(){var e;return!!this.getServerAggregatedRelation(c.d.name)||(null===(e=this.getThread())||void 0===e?void 0:e.id)===this.getId()}get replyEventId(){var e,t;return null===(e=this.getWireContent()["m.relates_to"])||void 0===e||null===(t=e["m.in_reply_to"])||void 0===t?void 0:t.event_id}get relationEventId(){var e,t;return null===(e=this.getWireContent())||void 0===e||null===(t=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,r){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=r}isBeingDecrypted(){return null!=this.decryptionPromise}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){var e,t;return"m.bad.encrypted"===(null===(e=this.clearEvent)||void 0===e||null===(t=e.content)||void 0===t?void 0:t.msgtype)}get isEncryptedDisabledForUnverifiedDevices(){return this.isDecryptionFailure()&&this.encryptedDisabledForUnverifiedDevices}shouldAttemptDecryption(){return!this.isRedacted()&&(!this.isBeingDecrypted()&&(!this.clearEvent&&!!this.isEncrypted()))}async attemptDecryption(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");const n=this.clearEvent&&!this.isDecryptionFailure(),r=t.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(n&&!r)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(a.a.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){return[{userId:e,deviceId:"*"}]}async decryptionLoop(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(await Promise.resolve();;){let n,r;this.retryDecryption=!1;try{e?(n=await e.decryptEvent(this),!0===t.isRetry&&a.a.info(`Decrypted event on retry (${this.getDetails()})`)):n=this.badEncryptedMessage("Encryption not enabled")}catch(e){const t=e instanceof h.b?e.detailedString:String(e);if(r=e,this.retryDecryption){a.a.log(`Error decrypting event (${this.getDetails()}), but retrying: ${t}`);continue}a.a.warn(`Error decrypting event (${this.getDetails()}): ${t}`),n=this.badEncryptedMessage(String(e))}return this.decryptionPromise=null,this.retryDecryption=!1,this.setClearData(n),this.setPushActions(null),void(!1!==t.emit&&this.emit(f.Decrypted,this,r))}}badEncryptedMessage(e){return{clearEvent:{type:s.b.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}},encryptedDisabledForUnverifiedDevices:e===`DecryptionError: ${p.b["m.unverified"]}`}}setClearData(e){var t,n;this.clearEvent=e.clearEvent,this.senderCurve25519Key=null!==(t=e.senderCurve25519Key)&&void 0!==t?t:null,this.claimedEd25519Key=null!==(n=e.claimedEd25519Key)&&void 0!==n?n:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.encryptedDisabledForUnverifiedDevices=e.encryptedDisabledForUnverifiedDevices||!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===s.b.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return this.claimedEd25519Key?{ed25519:this.claimedEd25519Key}:{}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return!!this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(e){this.event.unsigned=e}unmarkLocallyRedacted(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(f.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,n;const r=null===(t=null==e?void 0:e.visible)||void 0===t||t,i=null!==(n=null==e?void 0:e.reason)&&void 0!==n?n:null;let o=!1;this.visibility.visible!==r?o=!0:this.visibility.visible||this.visibility.reason===i||(o=!0),o&&(this.visibility=r?g:Object.freeze({visible:!1,reason:i}),this.emit(f.VisibilityChange,this,r))}messageVisibility(){return this.visibility}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(f.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const e in this.event)this.event.hasOwnProperty(e)&&!b.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=void 0);const t=this.getType()in v?v[this.getType()]:{},n=this.getContent();for(const e in n)n.hasOwnProperty(e)&&!t[e]&&delete n[e];this.invalidateExtensibleEvent()}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===s.b.RoomRedaction}asVisibilityChange(){if(!s.a.matches(this.getType()))return null;const e=this.getRelation();if(!e||"m.reference"!=e.rel_type)return null;const t=e.event_id;if(!t)return null;const n=this.getWireContent(),r=!!n.visible,i=n.reason;return i&&"string"!=typeof i?null:{visible:r,reason:i,eventId:t}}isVisibilityEvent(){return s.a.matches(this.getType())}getRedactionEvent(){var e,t,n,r;return this.isRedacted()?null!==(e=this.clearEvent)&&void 0!==e&&e.unsigned?null!==(n=null===(r=this.clearEvent)||void 0===r?void 0:r.unsigned.redacted_because)&&void 0!==n?n:null:null!==(t=this.event.unsigned)&&void 0!==t&&t.redacted_because?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),n=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==n&&this.emit(f.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(f.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(f.LocalEventIdReplaced,this)}isRelation(e){var t;const n=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return(!this.isState()||(null==n?void 0:n.rel_type)!==s.h.Replace)&&!(null==n||!n.rel_type||!n.event_id||e&&n.rel_type!==e)}getRelation(){var e;return this.isRelation()&&null!==(e=this.getWireContent()["m.relates_to"])&&void 0!==e?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=null!=e?e:null,this.emit(f.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return null===(t=this.getUnsigned()["m.relations"])||void 0===t?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(s.h.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){const e=this.getServerAggregatedRelation(s.h.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent){var t;return null!==(t=this._replacingEvent.getDate())&&void 0!==t?t:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return this.replyEventId?this.replyEventId:e?e.event_id:this.isRedaction()?this.event.redacts:void 0}hasAssocation(){return!!this.getAssociatedId()}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new _(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=Object(l.l)(this.event),n=Object(l.l)(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&&this.reEmitter.stopReEmitting(this.thread,[c.f.Update]),this.thread=e,this.setThreadId(null==e?void 0:e.id),e&&this.reEmitter.reEmit(e,[c.f.Update])}getThread(){return this.thread}setThreadId(e){this.threadId=e}}const b=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),v={[s.b.RoomMember]:{membership:1},[s.b.RoomCreate]:{creator:1},[s.b.RoomJoinRules]:{join_rule:1},[s.b.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(121),l=n(135);class c extends a.a.Component{constructor(){super(...arguments),i()(this,"onClick",(()=>{this.props.onFinished(!0)}))}render(){return a.a.createElement(l.a,{className:"mx_ErrorDialog",onFinished:this.props.onFinished,title:this.props.title||Object(s.a)("Error"),headerImage:this.props.headerImage,contentId:"mx_Dialog_content"},a.a.createElement("div",{className:"mx_Dialog_content",id:"mx_Dialog_content"},this.props.description||Object(s.a)("An error has occurred.")),a.a.createElement("div",{className:"mx_Dialog_buttons"},a.a.createElement("button",{className:"mx_Dialog_primary",onClick:this.onClick,autoFocus:this.props.focus},this.props.button||Object(s.a)("OK"))))}}i()(c,"defaultProps",{focus:!0})},function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(121);class l extends a.a.Component{constructor(){super(...arguments),i()(this,"onCancelClick",(e=>{this.props.onCancel(e)}))}render(){let e,t="mx_Dialog_primary";this.props.primaryButtonClass&&(t+=" "+this.props.primaryButtonClass),(this.props.cancelButton||this.props.hasCancel)&&(e=a.a.createElement("button",{"data-testid":"dialog-cancel-button",type:"button",onClick:this.onCancelClick,className:this.props.cancelButtonClass,disabled:this.props.disabled},this.props.cancelButton||Object(s.a)("Cancel")));let n=null;return this.props.additive&&(n=a.a.createElement("div",{className:"mx_Dialog_buttons_additive"},this.props.additive)),a.a.createElement("div",{className:"mx_Dialog_buttons"},n,a.a.createElement("span",{className:"mx_Dialog_buttons_row"},e,this.props.children,a.a.createElement("button",{type:this.props.primaryIsSubmit?"submit":"button","data-testid":"dialog-primary-button",className:t,onClick:this.props.onPrimaryButtonClick,autoFocus:this.props.focus,disabled:this.props.disabled||this.props.primaryDisabled},this.props.primaryButton)))}}i()(l,"defaultProps",{hasCancel:!0,disabled:!1})},function(e,t,n){"use strict";n.d(t,"c",(function(){return i})),n.d(t,"i",(function(){return o})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"j",(function(){return l})),n.d(t,"b",(function(){return c})),n.d(t,"e",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return h})),n.d(t,"f",(function(){return p})),n.d(t,"k",(function(){return m})),n.d(t,"o",(function(){return g})),n.d(t,"m",(function(){return f})),n.d(t,"l",(function(){return _})),n.d(t,"n",(function(){return b}));var r=n(290);function i(e,t){if(e.length===t)return e;const n=[];if(e.length>t){const r=Math.round(e.length/t);for(let t=0;tt){for(;n.length>2*t||0===n.length;){n=[];for(let t=1;tObject(r.d)(Object(r.c)(e,i,o),t,n)))}function s(e,t){return new Array(t).fill(e)}function l(e,t,n){return e.length===t?e:e.length>t?e.slice(0,t):e.concat(n.slice(0,t-e.length))}function c(e){return e.slice(0,e.length)}function u(e,t){if(e.length===t.length){for(let n=0;n!e.includes(t)))||!!e.some((e=>!t.includes(e))))}function h(e,t){return{added:t.filter((t=>!e.includes(t))),removed:e.filter((e=>!t.includes(e)))}}function p(e,t){return e.filter((e=>t.includes(e)))}function m(){for(var e=arguments.length,t=new Array(e),n=0;n(t.forEach((t=>e.add(t))),e)),new Set))}function g(e,t,n){const r=Array.from(e),[i]=r.splice(t,1);return r.splice(n,0,i),r}const f=function(){for(var e=arguments.length,t=new Array(e),n=0;n{const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}),new Uint8Array(0))};async function _(e,t){for(const n of e)if(!await t(n))return!1;return!0}function b(e){return e.filter(Boolean)}},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return ie})),n.d(t,"g",(function(){return se})),n.d(t,"e",(function(){return le})),n.d(t,"f",(function(){return ce})),n.d(t,"c",(function(){return de})),n.d(t,"b",(function(){return pe})),n.d(t,"d",(function(){return ge})),n.d(t,"h",(function(){return fe}));var r=n(132),i=n.n(r),o=n(13),a=n.n(o),s=n(215),l=n(143),c=n(962),u=n(188),d=n(315),h=n(508),p=n(16),m=n(179),g=n(320),f=n(321),_=n(199),b=n(287),v=n(976),y=n(1),E=n(271),S=n(193),w=n(174),T=n(422),C=n(421),x=n(222),F=n(352),D=n(1561),k=n(671),O=n(987),I=n(269),A=n(140),R=n(184),N=n(129),M=n(160),P=n(988),L=n(223),B=n(672),U=n(1562),j=n(423),G=n(231),z=n(224),H=n(989),q=n(509),V=n(158),$=n(18),K=n(673),W=n(170),Y=n(204),Q=n(15),X=n(990),Z=n(991),J=n(413),ee=n(674);const te=["server","limit","since"];function ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function re(e){for(var t=1;t{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.groupCallEventHandler.start(),this.off(pe.Sync,this.startCallEventHandler))})),a()(this,"fixupRoomNotifications",(()=>{if(this.isInitialSyncComplete()){var e;const t=(null!==(e=this.getRooms())&&void 0!==e?e:[]).filter((e=>e.getUnreadNotificationCount(A.b.Total)>0));for(const e of t){const t=this.getSafeUserId();e.fixupNotifications(t)}this.off(pe.Sync,this.fixupRoomNotifications)}})),e.baseUrl=p.p(e.baseUrl),e.idBaseUrl=p.p(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=null!==(t=e.usingExternalCrypto)&&void 0!==t&&t,this.store=e.store||new c.a,this.deviceId=e.deviceId||null,this.sessionId=Object(L.b)(10);const n=e.userId||null;this.credentials={userId:n},this.http=new S.g(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,prefix:S.a.R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?y.a.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?y.a.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):y.a.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((async e=>{const t=this.getRoom(e.getRoomId());e.status!==l.a.SENDING&&this.updatePendingEventStatus(t,e,l.a.SENDING);const n=await this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,l.a.SENT,n.event_id),n})),Object(u.k)()&&(this.callEventHandler=new h.a(this),this.groupCallEventHandler=new q.a(this),this.canSupportVoip=!0,this.on(pe.Sync,this.startCallEventHandler)),this.on(pe.Sync,this.fixupRoomNotifications),this.timelineSupport=Boolean(e.timelineSupport),this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,void 0!==e.useE2eForGroupCall&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.roomList=new v.a(this.cryptoStore),this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new X.a(this),this.on(l.c.Decrypted,(e=>{fe(this,e)})),this.on(A.d.Receipt,((e,t)=>{if(t&&this.isRoomEncrypted(t.roomId)){const r=e.getContent();if(!(Object.keys(r).filter((e=>{for(const[t,n]of Object.entries(r[e]))if(p.w(t)&&n&&Object.keys(n).includes(this.getUserId()))return!0;return!1})).length>0))return;const i=20,o=t.getLiveTimeline().getEvents();let a=0;for(let e=o.length-1;e>=0;e--){var n;if(e===o.length-i)return;const r=o[e];if(t.hasUserReadEvent(this.getUserId(),r.getId()))break;const s=this.getPushActionsForEvent(r);a+=null!=s&&null!==(n=s.tweaks)&&void 0!==n&&n.highlight?1:0}t.setUnreadNotificationCount(A.b.Highlight,a)}})),this.ignoredInvites=new Z.a(this)}async startClient(e){var t;if(this.clientRunning)return;this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e});const n=this.getUserId();n&&this.store.storeUser(new x.a(n)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),ae),this.checkTurnServers()),this.syncApi&&(y.a.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{await this.getVersions();const{threads:e,list:t,fwdPagination:n}=await this.doesServerSupportThread();W.e.setServerSideSupport(e),W.e.setServerSideListSupport(t),W.e.setServerSideFwdPaginationSupport(n)}catch(e){y.a.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",e)}this.clientOpts=null!==(t=e)&&void 0!==t?t:{},this.clientOpts.slidingSync?this.syncApi=new K.a(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new s.a(this,this.clientOpts,this.buildSyncApiOptions()),this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&y.a.warn("`experimentalThreadSupport` has been deprecated, use `threadSupport` instead"),!this.clientOpts.hasOwnProperty("threadSupport")&&this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&(this.clientOpts.threadSupport=this.clientOpts.experimentalThreadSupport),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval((()=>{this.fetchClientWellKnown()}),1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start()}buildSyncApiOptions(){return{crypto:this.crypto,cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e)}}stopClient(){var t,n,r,i,o;null===(t=this.cryptoBackend)||void 0===t||t.stop(),this.clientRunning&&(y.a.log("stopping MatrixClient"),this.clientRunning=!1,null===(n=this.syncApi)||void 0===n||n.stop(),this.syncApi=void 0,null===(r=this.peekSync)||void 0===r||r.stopPeeking(),null===(i=this.callEventHandler)||void 0===i||i.stop(),null===(o=this.groupCallEventHandler)||void 0===o||o.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,e.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,void 0!==this.clientWellKnownIntervalID&&e.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop())}async rehydrateDevice(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const t=await this.getDehydratedDevice();if(!t)return;if(!t.device_data||!t.device_id)return void y.a.info("no dehydrated device found");const n=new e.Olm.Account;try{const e=t.device_data;if(e.algorithm!==k.a)return void y.a.warn("Wrong algorithm for dehydrated device");y.a.log("unpickling dehydrated device");const r=await this.cryptoCallbacks.getDehydrationKey(e,(t=>{n.unpickle(new Uint8Array(t),e.account)}));n.unpickle(r,e.account),y.a.log("unpickled device");if((await this.http.authedRequest(S.i.Post,"/dehydrated_device/claim",void 0,{device_id:t.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=t.device_id,y.a.info("using dehydrated device");const e=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:n.pickle(e),sessions:[],pickleKey:e},n.free(),this.deviceId}return n.free(),void y.a.info("not using dehydrated device")}catch(e){n.free(),y.a.warn("could not unpickle",e)}}async getDehydratedDevice(){try{return await this.http.authedRequest(S.i.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void y.a.info("could not get dehydrated device",e)}}async setDehydrationKey(e,t,n){if(this.crypto)return this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n);y.a.warn("not dehydrating device if crypto is not enabled")}async createDehydratedDevice(e,t,n){if(this.crypto)return await this.crypto.dehydrationManager.setKey(e,t,n),this.crypto.dehydrationManager.dehydrateDevice();y.a.warn("not dehydrating device if crypto is not enabled")}async exportDevice(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:await this.crypto.olmDevice.export()};y.a.warn("not exporting device if crypto is not enabled")}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const t=[];t.push(this.store.deleteAllData()),this.cryptoStore&&t.push(this.cryptoStore.deleteAllData());return t.push((async()=>{let t;try{t=e.indexedDB}catch(e){return}for(const e of[`${ee.a}::matrix-sdk-crypto`,`${ee.a}::matrix-sdk-crypto-meta`]){const n=new Promise(((n,r)=>{y.a.info(`Removing IndexedDB instance ${e}`);const i=t.deleteDatabase(e);i.onsuccess=t=>{y.a.info(`Removed IndexedDB instance ${e}`),n(0)},i.onerror=t=>{y.a.warn(`Failed to remove IndexedDB instance ${e}:`,t),n(0)},i.onblocked=t=>{y.a.info(`cannot yet remove IndexedDB instance ${e}`)}}));await n}})()),Promise.all(t).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return Object(u.h)(this,e)}async createGroupCall(e,t,n,r,i,o){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const a=this.getRoom(e);if(!a)throw new Error(`Cannot find room ${e}`);return new z.a(this,a,t,n,r,void 0,i||this.isVoipWithNoMediaAllowed,o,this.isVoipWithNoMediaAllowed).create()}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return null!==(e=null===(t=this.syncApi)||void 0===t?void 0:t.getSyncState())&&void 0!==e?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===s.b.Prepared||e===s.b.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),null!==(e=null===(t=this.syncApi)||void 0===t?void 0:t.retryImmediately())&&void 0!==e&&e}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const n=(new Date).getTime();return this.cachedCapabilities&&!t&&n(y.a.error(e),{}))).then((function(){const t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).capabilities||{},r=Object.keys(t).length?oe:6e4+5e3*Math.random();return e.cachedCapabilities={capabilities:t,expiration:n+r},y.a.log("Caching capabilities: ",t),t}))}async initCrypto(){if(!Object(w.d)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.cryptoBackend)return void y.a.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");y.a.log("Crypto: Starting up crypto store..."),await this.cryptoStore.startup(),y.a.log("Crypto: initialising roomlist..."),await 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 w.a(this,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,[w.b.KeyBackupFailed,w.b.KeyBackupSessionsRemaining,w.b.RoomKeyRequest,w.b.RoomKeyRequestCancellation,w.b.Warning,w.b.DevicesUpdated,w.b.WillUpdateDevices,w.b.DeviceVerificationChanged,w.b.UserTrustStatusChanged,w.b.KeysChanged]),y.a.log("Crypto: initialising crypto object..."),await t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=w.a.getOlmVersion(),t.registerEventHandlers(this),this.cryptoBackend=this.crypto=t,this.crypto.uploadDeviceKeys().catch((e=>{y.a.error("Error uploading device keys",e)}))}async initRustCrypto(){if(this.cryptoBackend)return void y.a.warn("Attempt to re-initialise e2e encryption on MatrixClient");const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const t=this.getDeviceId();if(null===t)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const r=await n.e(32).then(n.bind(null,1550)),i=await r.initRustCrypto(this.http,e,t);this.cryptoBackend=i,this.on(R.b.Membership,i.onRoomMembership.bind(i))}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var e,t;return null!==(e=null===(t=this.crypto)||void 0===t?void 0:t.getDeviceEd25519Key())&&void 0!==e?e:null}getDeviceCurve25519Key(){var e,t;return null!==(e=null===(t=this.crypto)||void 0===t?void 0:t.getDeviceCurve25519Key())&&void 0!==e?e:null}async uploadKeys(){y.a.warn("MatrixClient.uploadKeys is deprecated")}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const r=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),r}setDeviceBlocked(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return this.setDeviceVerification(e,t,null,null,n)}async setDeviceVerification(e,t,n,r,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.setDeviceVerification(e,t,n,r,i)}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.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=e,e}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:O.a.Master;if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.prepareToEncrypt(e)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,n)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,n)}getSecret(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(e)}isSecretStored(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}async getEventSenderDeviceInfo(e){return this.crypto?this.crypto.getEventSenderDeviceInfo(e):null}async isEventSenderVerified(e){const t=await this.getEventSenderDeviceInfo(e);return!!t&&t.isVerified()}getOutgoingRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");const t=e.getWireContent(),n={session_id:t.session_id,sender_key:t.sender_key,algorithm:t.algorithm,room_id:e.getRoomId()};return n.session_id&&n.sender_key&&n.algorithm&&n.room_id?this.crypto.cryptoStore.getOutgoingRoomKeyRequest(n):Promise.resolve(null)}cancelAndResendEventRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){const t=this.getRoom(e);if(!t)return!1;return!!t.currentState.getStateEvents(N.b.RoomEncryption,"")||this.roomList.isRoomEncrypted(e)}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");this.crypto.forceDiscardSession(e)}exportRoomKeys(){return this.cryptoBackend?this.cryptoBackend.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(e,t)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}async getKeyBackupVersion(){let e;try{e=await this.http.authedRequest(S.i.Get,"/room_keys/version",void 0,void 0,{prefix:S.a.V3})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}return B.a.checkBackupVersion(e),e}isKeyBackupTrusted(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}async prepareKeyBackupVersion(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{secureSecretStorage:!1};if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:n,auth_data:r,recovery_key:i,privateKey:o}=await this.crypto.backupManager.prepareKeyBackupVersion(e);return t.secureSecretStorage&&(await this.storeSecret("m.megolm_backup.v1",Object(_.encodeBase64)(o)),y.a.info("Key backup private key stored in secret storage")),{algorithm:n,auth_data:r,recovery_key:i}}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1"))}async createKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.createKeyBackupVersion(e);const t={algorithm:e.algorithm,auth_data:e.auth_data};await this.crypto.signObject(t.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&await this.crypto.crossSigningInfo.signObject(t.auth_data,"master");const n=await this.http.authedRequest(S.i.Post,"/room_keys/version",void 0,t,{prefix:S.a.V3});return await this.checkKeyBackup(),this.getKeyBackupEnabled()||y.a.error("Key backup not usable even though we just created it"),n}async deleteKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const t=p.o("/room_keys/version/$version",{$version:e});await this.http.authedRequest(S.i.Delete,t,void 0,void 0,{prefix:S.a.V3})}makeKeyBackupPath(e,t,n){let r;r=void 0!==t?p.o("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?p.o("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys";return{path:r,queryData:void 0===n?void 0:{version:n}}}async sendKeyBackup(e,t,n,r){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=this.makeKeyBackupPath(e,t,n);await this.http.authedRequest(S.i.Put,i.path,i.queryData,r,{prefix:S.a.V3})}async scheduleAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await 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 Object(T.a)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return Object(C.b)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return Object(T.a)(e)}async restoreKeyBackupWithPassword(e,t,n,r,i){const o=await Object(C.b)(r.auth_data,e);return this.restoreKeyBackup(o,t,n,r,i)}async restoreKeyBackupWithSecretStorage(e,t,n,r){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=await this.getSecret("m.megolm_backup.v1"),o=Object(w.c)(i);if(o){const e=await this.crypto.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",o,[e[0]])}const a=Object(_.decodeBase64)(o||i);return this.restoreKeyBackup(a,t,n,e,r)}restoreKeyBackupWithRecoveryKey(e,t,n,r,i){const o=Object(T.a)(e);return this.restoreKeyBackup(o,t,n,r,i)}async restoreKeyBackupWithCache(e,t,n,r){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=await this.crypto.getSessionBackupPrivateKey();if(!i)throw new Error("Couldn't get key");return this.restoreKeyBackup(i,e,t,n,r)}async restoreKeyBackup(e,t,n,r,i){const o=null==i?void 0:i.cacheCompleteCallback,a=null==i?void 0:i.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let s=0,l=[];const c=this.makeKeyBackupPath(t,n,r.version),u=await B.a.makeAlgorithm(r,(async()=>e)),d=u.untrusted;try{if(!await u.keyMatches(e))return Promise.reject(new S.f({errcode:ge.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{y.a.warn("Error caching session backup key:",e)})).then(o),a&&a({stage:"fetch"});const r=await this.http.authedRequest(S.i.Get,c.path,c.queryData,void 0,{prefix:S.a.V3});if(r.rooms){const e=r.rooms;for(const[t,n]of Object.entries(e)){if(!n.sessions)continue;s+=Object.keys(n.sessions).length;const e=await u.decryptSessions(n.sessions);for(const n of e)n.room_id=t,l.push(n)}}else if(r.sessions){const e=r.sessions;s=Object.keys(e).length,l=await u.decryptSessions(e);for(const e of l)e.room_id=t}else{s=1;try{const[e]=await u.decryptSessions({[n]:r});e.room_id=t,e.session_id=n,l.push(e)}catch(e){y.a.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return await this.importRoomKeys(l,{progressCallback:a,untrusted:d,source:"backup"}),await this.checkKeyBackup(),{total:s,imported:l.length}}async deleteKeysFromBackup(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,n);await this.http.authedRequest(S.i.Delete,r.path,r.queryData,void 0,{prefix:S.a.V3})}async sendSharedHistoryKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.roomList.getRoomEncryption(e);if(!n)return void y.a.error("Unknown room. Not sharing decryption keys");const r=await this.crypto.downloadKeys(t),i=new Map;for(const[e,t]of r)i.set(e,Array.from(t.values()));const o=this.crypto.getRoomDecryptor(e,n.algorithm);o.sendSharedHistoryInboundSessions?await o.sendSharedHistoryInboundSessions(i):y.a.warn("Algorithm does not support sharing previous keys",n.algorithm)}getMediaConfig(){return this.http.authedRequest(S.i.Get,"/config",void 0,void 0,{prefix:S.h.R0})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const t=this.store.getRooms(),n=new Set;for(const i of t){var r;const t=null===(r=i.findPredecessor(e))||void 0===r?void 0:r.roomId;t&&n.add(t)}return t.filter((e=>!e.currentState.getStateEvents(N.b.RoomTombstone,"")||!n.has(e.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){const n=p.o("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return Object(S.l)(5,(()=>this.http.authedRequest(S.i.Put,n,void 0,t)))}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const t=p.o("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(S.i.Get,t)}catch(e){var n;if("M_NOT_FOUND"===(null===(n=e.data)||void 0===n?void 0:n.errcode))return null;throw e}}async deleteAccountData(e){const t=this.canSupport.get(J.a.AccountDataDeletion);if(t===J.b.Unsupported)return void await this.setAccountData(e,{});const n=p.o("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),r=t===J.b.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return await this.http.authedRequest(S.i.Delete,n,void 0,void 0,r)}getIgnoredUsers(){const e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach((e=>{t.ignored_users[e]={}})),this.setAccountData("m.ignored_user_list",t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0===t.syncRoom&&(t.syncRoom=!0);const n=this.getRoom(e);if(null!=n&&n.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(n);let r=Promise.resolve();if(t.inviteSignUrl){const e=new URL(t.inviteSignUrl);e.searchParams.set("mxid",this.credentials.userId),r=this.http.requestOtherUrl(S.i.Post,e)}const i={};t.viaServers&&(i.server_name=t.viaServers);try{const n={},o=await r;o&&(n.third_party_signed=o);const a=p.o("/join/$roomid",{$roomid:e}),l=(await this.http.authedRequest(S.i.Post,a,i,n)).room_id,c=new s.a(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(l);return t.syncRoom,c}catch(e){throw e}}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,l.a.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![l.a.QUEUED,l.a.NOT_SENT,l.a.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===l.a.ENCRYPTING?this.pendingEventEncryption.delete(e.getId()):this.scheduler&&e.status===l.a.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,l.a.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,N.b.RoomName,{name:t})}setRoomTopic(e,t,n){const r=I.makeTopicContent(t,n);return this.sendStateEvent(e,N.b.RoomTopic,r)}getRoomTags(e){const t=p.o("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(S.i.Get,t)}setRoomTag(e,t,n){const r=p.o("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(S.i.Put,r,void 0,n)}deleteRoomTag(e,t){const n=p.o("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(S.i.Delete,n)}setRoomAccountData(e,t,n){const r=p.o("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(S.i.Put,r,void 0,n)}setPowerLevel(e,t,n,r){let i={users:{}};(null==r?void 0:r.getType())===N.b.RoomPowerLevels&&(i=p.k(r.getContent()));const o=Array.isArray(t)?t:[t];for(const e of o)null==n?delete i.users[e]:i.users[e]=n;const a=p.o("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(S.i.Put,a,void 0,i)}async unstable_createLiveBeacon(e,t){return this.unstable_setLiveBeacon(e,t)}async unstable_setLiveBeacon(e,t){return this.sendStateEvent(e,Y.b.name,t,this.getUserId())}sendEvent(e,t,n,r,i){var o;let a,s,l,c;if(null!=t&&t.startsWith(he)||null===t?(c=i,l=r,s=n,a=t):(c=r,l=n,s=t,a=null),a&&(null===(o=l["m.relates_to"])||void 0===o||!o.rel_type)){var u,d;const t=!(null===(u=l["m.relates_to"])||void 0===u||!u["m.in_reply_to"]);l["m.relates_to"]=re(re({},l["m.relates_to"]),{},{rel_type:W.d.name,event_id:a,is_falling_back:!t});const n=null===(d=this.getRoom(e))||void 0===d?void 0:d.getThread(a);var h,p;if(n&&!t)l["m.relates_to"]["m.in_reply_to"]={event_id:null!==(h=null===(p=n.lastReply((e=>e.isRelation(W.d.name)&&!e.status)))||void 0===p?void 0:p.getId())&&void 0!==h?h:a}}return this.sendCompleteEvent(e,a,{type:s,content:l},c)}sendCompleteEvent(e,t,n,r){r||(r=this.makeTxnId());const i=new l.b(Object.assign(n,{event_id:"~"+e+":"+r,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),o=this.getRoom(e),a=t?null==o?void 0:o.getThread(t):void 0;a&&i.setThread(a),this.reEmitter.reEmit(i,[l.c.Replaced,l.c.VisibilityChange]),null==o||o.reEmitter.reEmit(i,[l.c.BeforeRedaction]);const s=i.getAssociatedId();if(null!=s&&s.startsWith("~")){const e=null==o?void 0:o.getPendingEvents().find((e=>e.getId()===s));null==e||e.once(l.c.LocalEventIdReplaced,(()=>{i.updateAssociatedId(e.getId())}))}const c=i.getType();return y.a.log(`sendEvent of type ${c} in ${e} with txnId ${r}`),i.setTxnId(r),i.setStatus(l.a.SENDING),null==o||o.addPendingEvent(i,r),i.status===l.a.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(o,i)}encryptAndSendEvent(e,t){let n=!1;return Promise.resolve().then((()=>{const r=this.encryptEventIfNeeded(t,null!=e?e:void 0);return r?(this.pendingEventEncryption.set(t.getId(),r),this.updatePendingEventStatus(e,t,l.a.ENCRYPTING),r.then((()=>{this.pendingEventEncryption.has(t.getId())?this.updatePendingEventStatus(e,t,l.a.SENDING):n=!0}))):null})).then((()=>{if(n)return{};let r=null;return this.scheduler&&(r=this.scheduler.queueEvent(t),r&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,l.a.QUEUED)),r||(r=this.sendEventHttpRequest(t),e&&(r=r.then((n=>(e.updatePendingEvent(t,l.a.SENT,n.event_id),n))))),r})).catch((n=>{y.a.error("Error sending event",n.stack||n);try{t.error=n,this.updatePendingEventStatus(e,t,l.a.NOT_SENT)}catch(e){y.a.error("Exception in error handler!",e.stack||n)}throw n instanceof S.f&&(n.event=t),n}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(e.isRedaction())return null;if(!t||!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.cryptoBackend&&this.usingExternalCrypto)return null;if(e.getType()===N.b.Reaction)return null;if(!this.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.cryptoBackend.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===N.b.Reaction?t:this.isRoomEncrypted(e)?N.b.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 r;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),r=p.o(t,n)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";r=p.o(t,re({$redactsEventId:e.event.redacts},n))}else r=p.o("/rooms/$roomId/send/$eventType/$txnId",n);return this.http.authedRequest(S.i.Put,r,void 0,e.getWireContent()).then((t=>(y.a.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,n,r,i){var o,a,s,l,c;null!==(o=n)&&void 0!==o&&o.startsWith(he)||(i=r,r=n,n=t,t=null);const u=null===(a=i)||void 0===a?void 0:a.reason;if(null!==(s=i)&&void 0!==s&&s.with_relations&&this.canSupport.get(J.a.RelationBasedRedactions)===J.b.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${n} txnId: ${r} threadId ${t}`);const d=null!==(l=i)&&void 0!==l&&l.with_relations?{[this.canSupport.get(J.a.RelationBasedRedactions)===J.b.Stable?N.d.stable:N.d.unstable]:null===(c=i)||void 0===c?void 0:c.with_relations}:{};return this.sendCompleteEvent(e,t,{type:N.b.RoomRedaction,content:re(re({},d),{},{reason:u}),redacts:n},r)}sendMessage(e,t,n,r){"string"!=typeof t&&null!==t&&(r=n,n=t,t=null);const i=N.b.RoomMessage,o=n;return this.sendEvent(e,t,i,o,r)}sendTextMessage(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeTextMessage(n);return this.sendMessage(e,t,o,r)}sendNotice(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeNotice(n);return this.sendMessage(e,t,o,r)}sendEmoteMessage(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeEmoteMessage(n);return this.sendMessage(e,t,o,r)}sendImageMessage(e,t,n,r){var i;let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"Image";null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(o=r||"Image",r=n,n=t,t=null);const a={msgtype:N.e.Image,url:n,info:r,body:o};return this.sendMessage(e,t,a)}sendStickerMessage(e,t,n,r){var i;let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"Sticker";null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(o=r||"Sticker",r=n,n=t,t=null);const a={url:n,info:r,body:o};return this.sendEvent(e,t,N.b.Sticker,a)}sendHtmlMessage(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeHtmlMessage(n,r);return this.sendMessage(e,t,o)}sendHtmlNotice(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeHtmlNotice(n,r);return this.sendMessage(e,t,o)}sendHtmlEmote(e,t,n,r){var i;null!==(i=t)&&void 0!==i&&i.startsWith(he)||null===t||(r=n,n=t,t=null);const o=I.makeHtmlEmote(n,r);return this.sendMessage(e,t,o)}async sendReceipt(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this.isGuest())return Promise.resolve({});const i=p.o("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()});if(!r){const t=!!e.threadRootId;n=re(re({},n),{},{thread_id:t?e.threadRootId:$.a})}const o=this.http.authedRequest(S.i.Post,i,void 0,n||{}),a=this.getRoom(e.getRoomId());return a&&this.credentials.userId&&a.addLocalEchoReceipt(this.credentials.userId,e,t),o}async sendReadReceipt(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.b.Read,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!e)return;const r=e.getId(),i=this.getRoom(e.getRoomId());if(null!=i&&i.hasPendingEvent(r))throw new Error(`Cannot set read receipt to a pending event (${r})`);return this.sendReceipt(e,t,{},n)}async setRoomReadMarkers(e,t,n,r){const i=this.getRoom(e);if(i&&i.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let o,a;if(n){if(o=n.getId(),null!=i&&i.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);null==i||i.addLocalEchoReceipt(this.credentials.userId,n,$.b.Read)}if(r){if(a=r.getId(),null!=i&&i.hasPendingEvent(a))throw new Error(`Cannot set read receipt to a pending event (${a})`);null==i||i.addLocalEchoReceipt(this.credentials.userId,r,$.b.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(e,t,o,a)}getUrlPreview(e,t){t=6e4*Math.floor(t/6e4);const n=new URL(e);n.hash="";const r=t+"_"+(e=n.toString()),i=this.urlPreviewCache[r];if(i)return i;const o=this.http.authedRequest(S.i.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:S.h.R0});return this.urlPreviewCache[r]=o,o}sendTyping(e,t,n){if(this.isGuest())return Promise.resolve({});const r=p.o("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),i={typing:t};return t&&(i.timeout=n||2e4),this.http.authedRequest(S.i.Put,r,void 0,i)}getRoomUpgradeHistory(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=this.getRoom(e);if(!r)return[];return[...this.findPredecessorRooms(r,t,n),r,...this.findSuccessorRooms(r,t,n)]}findPredecessorRooms(e,t,n){var r;const i=[];let o=null===(r=e.findPredecessor(n))||void 0===r?void 0:r.roomId;for(;null!==o;){var a;const r=this.getRoom(o);if(null===r)break;if(t){const t=r.currentState.getStateEvents(N.b.RoomTombstone,"");if(!t||t.getContent().replacement_room!==e.roomId)break}i.splice(0,0,r),o=null===(a=(e=r).findPredecessor(n))||void 0===a?void 0:a.roomId}return i}findSuccessorRooms(e,t,n){const r=[];let i=e.currentState.getStateEvents(N.b.RoomTombstone,"");for(;i;){const a=this.getRoom(i.getContent().replacement_room);if(!a)break;if(a.roomId===e.roomId)break;if(t){var o;const t=null===(o=a.findPredecessor(n))||void 0===o?void 0:o.roomId;if(!t||t!==e.roomId)break}r.push(a);if(new Set(r.map((e=>e.roomId))).size1&&void 0!==arguments[1])||arguments[1];const n=this.getRoomUpgradeHistory(e);let r=n;if(!t){r=[];for(const t of n)if(r.push(t),t.roomId===e)break}const i={},o=[],a=e=>this.leave(e).then((()=>{delete i[e]})).catch((t=>{i[e]=t}));for(const e of r)o.push(a(e.roomId));return Promise.all(o).then((()=>i))}ban(e,t,n){return this.membershipChange(e,t,"ban",n)}forget(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.membershipChange(e,void 0,"forget");return t?n.then((t=>(this.store.removeRoom(e),this.emit(pe.DeleteRoom,e),t))):n}unban(e,t){const n=p.o("/rooms/$roomId/unban",{$roomId:e}),r={user_id:t};return this.http.authedRequest(S.i.Post,n,void 0,r)}kick(e,t,n){const r=p.o("/rooms/$roomId/kick",{$roomId:e}),i={user_id:t,reason:n};return this.http.authedRequest(S.i.Post,r,void 0,i)}membershipChange(e,t,n,r){const i=p.o("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(S.i.Post,i,void 0,{user_id:t,reason:r})}getPushActionsForEvent(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.getPushActions()&&!t||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t){const n=p.o("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(S.i.Put,n,void 0,t)}async setDisplayName(e){const t=await this.setProfileInfo("displayname",{displayname:e}),n=this.getUser(this.getUserId());return n&&(n.displayName=e,n.emit(x.b.DisplayName,n.events.presence,n)),t}async setAvatarUrl(e){const t=await this.setProfileInfo("avatar_url",{avatar_url:e}),n=this.getUser(this.getUserId());return n&&(n.avatarUrl=e,n.emit(x.b.AvatarUrl,n.events.presence,n)),t}mxcUrlToHttp(e,t,n,r,i){return Object(F.a)(this.baseUrl,e,t,n,r,i)}async setPresence(e){const t=p.o("/presence/$userId/status",{$userId:this.credentials.userId});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);await this.http.authedRequest(S.i.Put,t,void 0,e)}getPresence(e){const t=p.o("/presence/$userId/status",{$userId:e});return this.http.authedRequest(S.i.Get,t)}scrollback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:30,n=0,r=this.ongoingScrollbacks[e.roomId]||{};if(r.promise)return r.promise;if(r.errorTs){const e=Date.now()-r.errorTs;n=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const i=this.store.scrollback(e,t).length;if(i===t)return Promise.resolve(e);t-=i;const o=new Promise(((r,i)=>{Object(p.N)(n).then((()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,m.a.Backward))).then((t=>{var n,i;const o=t.chunk.map(this.getEventMapper());if(t.state){const n=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(n)}const[a,s]=e.partitionThreadedEvents(o);this.processAggregatedTimelineEvents(e,a),e.addEventsToTimeline(a,!0,e.getLiveTimeline()),this.processThreadEvents(e,s,!0),e.oldState.paginationToken=null!==(n=t.end)&&void 0!==n?n:null,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,o,null!==(i=t.end)&&void 0!==i?i:null,!0),delete this.ongoingScrollbacks[e.roomId],r(e)})).catch((t=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},i(t)}))}));return r={promise:o},this.ongoingScrollbacks[e.roomId]=r,o}getEventMapper(e){return Object(P.a)(this,e||{})}async getEventTimeline(e,t){var n,r,i,o;if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(null==e||!e.room)throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&this.supportsThreads())return this.getThreadTimeline(e,t);const a=p.o("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let s;null!==(n=this.clientOpts)&&void 0!==n&&n.lazyLoadMembers&&(s={filter:JSON.stringify(d.a.LAZY_LOADING_MESSAGES_FILTER)});const l=await this.http.authedRequest(S.i.Get,a,s);if(!l.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const c=this.getEventMapper(),u=c(l.event);if(u.isRelation(W.d.name))return void y.a.warn("Tried loading a regular timeline at the position of a thread event");const h=[...l.events_after.reverse().map(c),u,...l.events_before.map(c)];let g=e.getTimelineForEvent(h[0].getId());g?g.getState(m.b.BACKWARDS).setUnknownStateEvents(l.state.map(c)):(g=e.addTimeline(),g.initialiseState(l.state.map(c)),g.getState(m.b.FORWARDS).paginationToken=l.end);const[f,_]=e.room.partitionThreadedEvents(h);return e.addEventsToTimeline(f,!0,g,l.start),this.processThreadEvents(e.room,_,!0),this.processAggregatedTimelineEvents(e.room,f),null!==(r=null!==(i=e.getTimelineForEvent(t))&&void 0!==i?i:null===(o=e.room.findThreadForEvent(u))||void 0===o?void 0:o.liveTimeline)&&void 0!==r?r:g}async getThreadTimeline(e,t){var n;if(!this.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const r=p.o("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),i={limit:"0"};null!==(n=this.clientOpts)&&void 0!==n&&n.lazyLoadMembers&&(i.filter=JSON.stringify(d.a.LAZY_LOADING_MESSAGES_FILTER));const o=await this.http.authedRequest(S.i.Get,r,i),a=this.getEventMapper(),s=a(o.event);if(e.canContain(s)&&W.e.hasServerSideSupport){if(W.e.hasServerSideFwdPaginationSupport){var l,c,u;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const n=e.thread,r=await this.fetchRelations(e.room.roomId,n.id,W.d.name,null,{dir:m.a.Backward,from:o.start}),i=await this.fetchRelations(e.room.roomId,n.id,W.d.name,null,{dir:m.a.Forward,from:o.end}),d=[...i.chunk.reverse().map(a),s,...r.chunk.map(a)];for(const t of d){var h;await(null===(h=e.thread)||void 0===h?void 0:h.processEvent(t))}let p=e.getTimelineForEvent(s.getId());if(p?p.getState(m.b.BACKWARDS).setUnknownStateEvents(o.state.map(a)):(p=e.addTimeline(),p.initialiseState(o.state.map(a))),e.addEventsToTimeline(d,!0,p,i.next_batch),!r.next_batch){const t=await this.fetchRoomEvent(e.room.roomId,n.id);e.addEventsToTimeline([a(t)],!0,p,null)}return p.setPaginationToken(null!==(l=r.next_batch)&&void 0!==l?l:null,m.a.Backward),p.setPaginationToken(null!==(c=i.next_batch)&&void 0!==c?c:null,m.a.Forward),this.processAggregatedTimelineEvents(e.room,d),null!==(u=e.getTimelineForEvent(t))&&void 0!==u?u:p}{var g;const t=e.thread,n=await this.fetchRelations(e.room.roomId,t.id,W.d.name,null,{dir:m.a.Backward,from:o.start}),r=[];let i=o.end;for(;i;){var f;const n=await this.fetchRelations(e.room.roomId,t.id,W.d.name,null,{dir:m.a.Forward,from:i});i=null!==(f=n.next_batch)&&void 0!==f?f:null,r.push(...n.chunk)}const l=[...r.reverse().map(a),s,...n.chunk.map(a)];for(const t of l){var _;await(null===(_=e.thread)||void 0===_?void 0:_.processEvent(t))}const c=e.getLiveTimeline();if(c.getState(m.b.BACKWARDS).setUnknownStateEvents(o.state.map(a)),e.addEventsToTimeline(l,!0,c,null),!n.next_batch){const n=await this.fetchRoomEvent(e.room.roomId,t.id);e.addEventsToTimeline([a(n)],!0,c,null)}return c.setPaginationToken(null!==(g=n.next_batch)&&void 0!==g?g:null,m.a.Backward),c.setPaginationToken(null,m.a.Forward),this.processAggregatedTimelineEvents(e.room,l),c}}}async getLatestTimeline(e){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");let t;if(null!==e.threadListType){var n;t=null===(n=(await this.createThreadListMessagesRequest(e.room.roomId,null,1,m.a.Backward,e.threadListType,e.getFilter())).chunk)||void 0===n?void 0:n[0]}else if(e.thread&&W.e.hasServerSideSupport){var r;t=null===(r=(await this.fetchRelations(e.room.roomId,e.thread.id,W.d.name,null,{dir:m.a.Backward,limit:1})).chunk)||void 0===r?void 0:r[0]}else{var i,o;const n=p.o("/rooms/$roomId/messages",{$roomId:e.room.roomId}),r={dir:"b"};null!==(i=this.clientOpts)&&void 0!==i&&i.lazyLoadMembers&&(r.filter=JSON.stringify(d.a.LAZY_LOADING_MESSAGES_FILTER));t=null===(o=(await this.http.authedRequest(S.i.Get,n,r)).chunk)||void 0===o?void 0:o[0]}if(!t)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,t.event_id)}createMessagesRequest(e,t){var n;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30,i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;const a=p.o("/rooms/$roomId/messages",{$roomId:e}),s={limit:r.toString(),dir:i};t&&(s.from=t);let l=null;var c;(null!==(n=this.clientOpts)&&void 0!==n&&n.lazyLoadMembers&&(l=Object.assign({},d.a.LAZY_LOADING_MESSAGES_FILTER)),o)&&(l=l||{},Object.assign(l,null===(c=o.getRoomTimelineFilterComponent())||void 0===c?void 0:c.toJSON()));return l&&(s.filter=JSON.stringify(l)),this.http.authedRequest(S.i.Get,a,s)}createThreadListMessagesRequest(e,t){var n;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:m.a.Backward,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:W.g.All,a=arguments.length>5?arguments[5]:void 0;const s=p.o("/rooms/$roomId/threads",{$roomId:e}),l={limit:r.toString(),dir:i,include:Object(W.i)(o)};t&&(l.from=t);let c={};var u;(null!==(n=this.clientOpts)&&void 0!==n&&n.lazyLoadMembers&&(c=re({},d.a.LAZY_LOADING_MESSAGES_FILTER)),a)&&(c=re(re({},c),null===(u=a.getRoomTimelineFilterComponent())||void 0===u?void 0:u.toJSON()));Object.keys(c).length&&(l.filter=JSON.stringify(c));const h={prefix:W.e.hasServerSideListSupport===W.c.Stable?"/_matrix/client/v1":"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(S.i.Get,s,l,void 0,h).then((e=>{var t;return re(re({},e),{},{chunk:null===(t=e.chunk)||void 0===t?void 0:t.reverse(),start:e.prev_batch,end:e.next_batch})}))}paginateEventTimeline(e,t){const n=e.getTimelineSet()===this.notifTimelineSet,r=this.getRoom(e.getRoomId()),i=e.getTimelineSet().threadListType,o=e.getTimelineSet().thread,a=(t=t||{}).backwards||!1;if(n&&!a)throw new Error("paginateNotifTimeline can only paginate backwards");const s=a?m.b.BACKWARDS:m.b.FORWARDS,l=e.getPaginationToken(s),c=e.paginationRequests[s];if(c)return c;let u,d,h;var f;if(n)u="/notifications",d={limit:(null!==(f=t.limit)&&void 0!==f?f:30).toString(),only:"highlight"},l&&"end"!==l&&(d.from=l),h=this.http.authedRequest(S.i.Get,"/notifications",d).then((async t=>{const n=t.next_token,r=[];t.notifications=t.notifications.filter(p.A);for(let e=0;e{e.paginationRequests[s]=null})),e.paginationRequests[s]=h;else if(null!==i){if(!r)throw new Error("Unknown room "+e.getRoomId());if(!W.e.hasServerSideFwdPaginationSupport&&s===m.a.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");h=this.createThreadListMessagesRequest(e.getRoomId(),l,t.limit,s,i,e.getFilter()).then((t=>{if(t.state){const n=e.getState(s),r=t.state.filter(p.A).map(this.getEventMapper());n.setUnknownStateEvents(r)}const n=t.end,i=t.chunk.filter(p.A).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(i,a,e,n),this.processAggregatedTimelineEvents(r,i),this.processThreadRoots(r,i,a),a&&t.end==t.start&&e.setPaginationToken(null,s),t.end!==t.start})).finally((()=>{e.paginationRequests[s]=null})),e.paginationRequests[s]=h}else if(o){var _,b;const n=this.getRoom(null!==(_=e.getRoomId())&&void 0!==_?_:void 0);if(!n)throw new Error("Unknown room "+e.getRoomId());h=this.fetchRelations(null!==(b=e.getRoomId())&&void 0!==b?b:"",o.id,W.d.name,null,{dir:s,limit:t.limit,from:null!=l?l:void 0}).then((async t=>{const r=this.getEventMapper(),i=t.chunk.filter(p.A).map(r);for(const e of i.slice().reverse()){await(null==o?void 0:o.processEvent(e));const t=e.getSender();a&&null!==(null==o?void 0:o.getEventReadUpTo(t))||n.addLocalEchoReceipt(t,e,$.b.Read)}const l=t.next_batch,c=e.getTimelineSet();if(c.addEventsToTimeline(i,a,e,null!=l?l:null),!l&&a){var u;const t=await this.fetchRoomEvent(null!==(u=e.getRoomId())&&void 0!==u?u:"",o.id);c.addEventsToTimeline([r(t)],!0,e,null)}return this.processAggregatedTimelineEvents(c.room,i),a&&!l&&e.setPaginationToken(null,s),Boolean(l)})).finally((()=>{e.paginationRequests[s]=null})),e.paginationRequests[s]=h}else{if(!r)throw new Error("Unknown room "+e.getRoomId());h=this.createMessagesRequest(e.getRoomId(),l,t.limit,s,e.getFilter()).then((t=>{if(t.state){const n=e.getState(s),r=t.state.filter(p.A).map(this.getEventMapper());n.setUnknownStateEvents(r)}const n=t.end,i=t.chunk.filter(p.A).map(this.getEventMapper()),o=e.getTimelineSet(),[l]=r.partitionThreadedEvents(i);o.addEventsToTimeline(l,a,e,n),this.processAggregatedTimelineEvents(r,l),this.processThreadRoots(r,l.filter((e=>e.getServerAggregatedRelation(W.d.name))),!1);const c=void 0===t.end||t.end===t.start;return a&&c&&e.setPaginationToken(null,s),!c})).finally((()=>{e.paginationRequests[s]=null})),e.paginationRequests[s]=h}return h}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t;return null===(t=this.peekSync)||void 0===t||t.stopPeeking(),this.peekSync=new s.a(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const n=this.sendStateEvent(e,N.b.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let r=Promise.resolve(void 0);return t.allowRead&&(r=this.sendStateEvent(e,N.b.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([r,n]).then()}requestRegisterEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestRegisterMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}requestAdd3pidEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestAdd3pidMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}requestPasswordEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestPasswordMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}async requestTokenFromEndpoint(e,t){const n=Object.assign({},t);if(!await this.doesServerSupportSeparateAddAndBind()&&this.idBaseUrl){var r;const e=new URL(this.idBaseUrl);if(n.id_server=e.host,null!==(r=this.identityServer)&&void 0!==r&&r.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(S.i.Post,e,void 0,n)}getRoomPushRule(e,t){var n,r;if(this.pushRules)return null===(n=this.pushRules[e])||void 0===n||null===(r=n.room)||void 0===r?void 0:r.find((e=>e.rule_id===t));throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,n){let r,i=!1;const o=this.getRoomPushRule(e,t);if(null!=o&&o.actions.includes(G.d.DontNotify)&&(i=!0),n)if(o){if(!i){const n=p.m();this.deletePushRule(e,G.e.RoomSpecific,o.rule_id).then((()=>{this.addPushRule(e,G.e.RoomSpecific,t,{actions:[G.d.DontNotify]}).then((()=>{n.resolve()})).catch((e=>{n.reject(e)}))})).catch((e=>{n.reject(e)})),r=n.promise}}else r=this.addPushRule(e,G.e.RoomSpecific,t,{actions:[G.d.DontNotify]});else i&&(r=this.deletePushRule(e,G.e.RoomSpecific,o.rule_id));if(r)return new Promise(((e,t)=>{r.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){const t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:j.a.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,e.abortSignal).then((t=>this.processRoomEventsSearch(e,t))).finally((()=>{e.pendingRequest=void 0}));return e.pendingRequest=n,n}processRoomEventsSearch(e,t){var n,r;const i=t.search_categories.room_events;e.count=i.count,e.next_batch=i.next_batch;const o=new Set(i.highlights);e.highlights.forEach((e=>{o.add(e)})),e.highlights=Array.from(o);const a=this.getEventMapper(),s=null!==(n=null===(r=i.results)||void 0===r?void 0:r.length)&&void 0!==n?n:0;for(let t=0;t{y.a.log("Marking success of sync left room request"),this.syncedLeftRooms=!0})).finally((()=>{this.syncLeftRoomsPromise=void 0})),this.syncLeftRoomsPromise}createFilter(e){const t=p.o("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(S.i.Post,t,void 0,e).then((t=>{const n=d.a.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 r=p.o("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(S.i.Get,r).then((n=>{const r=d.a.fromJson(e,t,n);return this.store.storeFilter(r),r}))}async getOrCreateFilter(e,t){const n=this.store.getFilterIdByName(e);let r;if(n){try{const e=await this.getFilter(this.credentials.userId,n,!0);if(e){const i=e.getDefinition(),o=t.getDefinition();p.j(i,o)&&(r=n)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}r||this.store.setFilterIdByName(e,void 0)}if(r)return r;const i=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,i.filterId),i.filterId}getOpenIdToken(){const e=p.o("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(S.i.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(S.i.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return void 0!==this.checkTurnServersIntervalID}async checkTurnServers(){if(!this.canSupportVoip)return;let t=!1;const n=this.turnServersExpiry-Date.now();if(n>ae)y.a.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),t=!0;else{y.a.debug("Fetching new TURN credentials");try{const e=await this.turnServer();if(e.uris){y.a.log("Got TURN URIs: "+e.uris+" refresh in "+e.ttl+" secs");const n={urls:e.uris,username:e.username,credential:e.password};this.turnServers=[n],this.turnServersExpiry=Date.now()+1e3*e.ttl,t=!0,this.emit(pe.TurnServers,this.turnServers)}}catch(t){y.a.error("Failed to get TURN URIs",t),403===t.httpStatus?(y.a.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&e.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit(pe.TurnServersError,t,!0)):this.emit(pe.TurnServersError,t,!1)}}return t}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=p.o("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(S.i.Get,e,void 0,void 0,{prefix:""}).then((e=>e.admin))}whoisSynapseUser(e){const t=p.o("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(S.i.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=p.o("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(S.i.Post,t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){var e;this.clientWellKnownPromise=f.a.getRawClientConfig(null!==(e=this.getDomain())&&void 0!==e?e:void 0),this.clientWellKnown=await this.clientWellKnownPromise,this.emit(pe.ClientWellKnown,this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter((t=>{let[n,r]=t;return e.includes(typeof r)})).reduce(((e,t)=>{let[n,r]=t;return e[n]=r,e}),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){const t=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),n=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!t&&!n)throw Error("Server does not support mutual_rooms API");const r=p.o(`/uk.half-shot.msc2666/user/${n?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e});return(await this.http.authedRequest(S.i.Get,r,void 0,void 0,{prefix:S.a.Unstable})).joined}async getVersions(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.request(S.i.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch((e=>{throw this.serverVersionsPromise=void 0,e}));const e=await this.serverVersionsPromise;return this.canSupport=await Object(J.c)(e),this.serverVersionsPromise}async isVersionSupported(e){const{versions:t}=await this.getVersions();return t&&t.includes(e)}async doesServerSupportLazyLoading(){const e=await 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"]}async doesServerRequireIdServerParam(){const e=await 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"])}async doesServerAcceptIdentityAccessToken(){const e=await 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"]}async doesServerSupportSeparateAddAndBind(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return(null==t?void 0:t.includes("r0.6.0"))||(null==n?void 0:n["m.separate_add_and_bind"])}async doesServerSupportUnstableFeature(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features;return n&&!!n[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features,r=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return n&&!!n[`io.element.e2ee_forced.${r}`]}async doesServerSupportThread(){if(await this.isVersionSupported("v1.4"))return{threads:W.c.Stable,list:W.c.Stable,fwdPagination:W.c.Stable};try{const[e,t,n,r,i,o]=await Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:Object(W.h)(t,e),list:Object(W.h)(r,n),fwdPagination:Object(W.h)(o,i)}}catch(e){return{threads:W.c.None,list:W.c.None,fwdPagination:W.c.None}}}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){var e;return!(null===(e=this.clientOpts)||void 0===e||!e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,n,r){var i,o;let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{dir:m.a.Backward};const s=r?this.getEncryptedIfNeededEventType(e,r):null,[l,c]=await Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,n,s,a)]),u=this.getEventMapper(),d=l?u(l):void 0;let h=c.chunk.map(u);if(s===N.b.RoomMessageEncrypted){const e=d?h.concat(d):h;await Promise.all(e.map((e=>this.decryptEventIfNeeded(e)))),null!==r&&(h=h.filter((e=>e.getType()===r)))}return d&&n===N.h.Replace&&(h=h.filter((e=>e.getSender()===d.getSender()))),{originalEvent:null!=d?d:null,events:h,nextBatch:null!==(i=c.next_batch)&&void 0!==i?i:null,prevBatch:null!==(o=c.prev_batch)&&void 0!==o?o:null}}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return Object(L.b)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.isCryptoEnabled()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case E.a.IS:return this.http.getUrl("/terms",void 0,S.e.V2,t);case E.a.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,t;return arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&(null!==(e=this.idBaseUrl)&&void 0!==e&&e.startsWith("http://")||null!==(t=this.idBaseUrl)&&void 0!==t&&t.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=p.p(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}setAccessToken(e){this.http.opts.accessToken=e}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(S.i.Get,"/register/available",{username:e}).then((e=>e.available)).catch((e=>"M_USER_IN_USE"!==e.errcode&&Promise.reject(e)))}register(e,t,n,r,i,o,a){!0===i?i={email:!0}:null!=i&&!1!==i||(i={}),n&&(r.session=n);const s={auth:r,refresh_token:!0};return null!=e&&(s.username=e),null!=t&&(s.password=t),i.email&&(s.bind_email=!0),i.msisdn&&(s.bind_msisdn=!0),null!=o&&(s.guest_access_token=o),null!=a&&(s.inhibit_login=a),null!=t&&(s.x_show_msisdn=!0),this.registerRequest(s)}registerGuest(){let{body:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,t){const n={};return t&&(n.kind=t),this.http.request(S.i.Post,"/register",n,e)}refreshToken(e){return this.http.authedRequest(S.i.Post,"/refresh",void 0,{refresh_token:e},{prefix:S.a.V1,inhibitLogoutEmit:!0})}loginFlows(){return this.http.request(S.i.Get,"/login")}login(e,t){const n={type:e};return Object.assign(n,t),this.http.authedRequest(S.i.Post,"/login",void 0,n).then((e=>(e.access_token&&e.user_id&&(this.http.opts.accessToken=e.access_token,this.credentials={userId:e.user_id}),e)))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}loginWithSAML2(e){return this.login("m.login.saml2",{relay_state:e})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){let t=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,r="/login/"+(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sso")+"/redirect";t&&(r+="/"+t);const i={redirectUrl:e,[me.unstable]:n};return this.http.getUrl(r,i,S.a.R0).href}loginWithToken(e){return this.login("m.login.token",{token:e})}async logout(){var e,t;let n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(null!==(e=this.crypto)&&void 0!==e&&null!==(t=e.backupManager)&&void 0!==t&&t.getKeyBackupEnabled())try{for(;await this.crypto.backupManager.backupPendingKeys(200)>0;);}catch(e){y.a.error("Key backup request failed when logging out. Some keys may be missing from backup",e)}return n&&(this.stopClient(),this.http.abort()),this.http.authedRequest(S.i.Post,"/logout")}deactivateAccount(e,t){const n={};return e&&(n.auth=e),void 0!==t&&(n.erase=t),this.http.authedRequest(S.i.Post,"/account/deactivate",void 0,n)}requestLoginToken(e){const t={auth:e};return this.http.authedRequest(S.i.Post,"/org.matrix.msc3882/login/token",void 0,t,{prefix:S.a.Unstable})}getFallbackAuthUrl(e,t){const n=p.o("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t},S.a.R0).href}async createRoom(e){var t;const n=(e.invite_3pid||[]).filter((e=>!e.id_access_token));if(n.length>0&&null!==(t=this.identityServer)&&void 0!==t&&t.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();if(e)for(const t of n)t.id_access_token=e}return this.http.authedRequest(S.i.Post,"/createRoom",void 0,e)}fetchRelations(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{dir:m.a.Backward};W.e.hasServerSideFwdPaginationSupport===W.c.Experimental&&(i=Object(p.K)("dir","org.matrix.msc3715.dir",i));const o=p.n(i);let a="/rooms/$roomId/relations/$eventId";null!==n?(a+="/$relationType",null!==r&&(a+="/$eventType")):null!==r&&(y.a.warn(`eventType: ${r} ignored when fetching\n relations as relationType is null`),r=null);const s=p.o(a+"?"+o,{$roomId:e,$eventId:t,$relationType:n,$eventType:r});return this.http.authedRequest(S.i.Get,s,void 0,void 0,{prefix:S.a.V1})}roomState(e){const t=p.o("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(S.i.Get,t)}fetchRoomEvent(e,t){const n=p.o("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(S.i.Get,n)}members(e,t,n,r){const i={};t&&(i.membership=t),n&&(i.not_membership=n),r&&(i.at=r);const o=p.n(i),a=p.o("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(S.i.Get,a)}upgradeRoom(e,t){const n=p.o("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(S.i.Post,n,void 0,{new_version:t})}getStateEvent(e,t,n){const r={$roomId:e,$eventType:t,$stateKey:n};let i=p.o("/rooms/$roomId/state/$eventType",r);return void 0!==n&&(i=p.o(i+"/$stateKey",r)),this.http.authedRequest(S.i.Get,i)}sendStateEvent(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const o={$roomId:e,$eventType:t,$stateKey:r};let a=p.o("/rooms/$roomId/state/$eventType",o);return void 0!==r&&(a=p.o(a+"/$stateKey",o)),this.http.authedRequest(S.i.Put,a,void 0,n,i)}roomInitialSync(e,t){var n;const r=p.o("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(S.i.Get,r,{limit:null!==(n=null==t?void 0:t.toString())&&void 0!==n?n:"30"})}async setRoomReadMarkersHttpRequest(e,t,n,r){const i=p.o("/rooms/$roomId/read_markers",{$roomId:e}),o={[$.b.FullyRead]:t,[$.b.Read]:n};return(await this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")||await this.isVersionSupported("v1.4"))&&(o[$.b.ReadPrivate]=r),this.http.authedRequest(S.i.Post,i,void 0,o)}getJoinedRooms(){const e=p.o("/joined_rooms",{});return this.http.authedRequest(S.i.Get,e)}getJoinedRoomMembers(e){const t=p.o("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(S.i.Get,t)}publicRooms(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{server:t,limit:n,since:r}=e,o=i()(e,te);const a={server:t,limit:n,since:r};return 0===Object.keys(o).length?this.http.authedRequest(S.i.Get,"/publicRooms",a):this.http.authedRequest(S.i.Post,"/publicRooms",a,o)}createAlias(e,t){const n=p.o("/directory/room/$alias",{$alias:e}),r={room_id:t};return this.http.authedRequest(S.i.Put,n,void 0,r)}deleteAlias(e){const t=p.o("/directory/room/$alias",{$alias:e});return this.http.authedRequest(S.i.Delete,t)}getLocalAliases(e){const t=p.o("/rooms/$roomId/aliases",{$roomId:e}),n=S.a.V3;return this.http.authedRequest(S.i.Get,t,void 0,void 0,{prefix:n})}getRoomIdForAlias(e){const t=p.o("/directory/room/$alias",{$alias:e});return this.http.authedRequest(S.i.Get,t)}resolveRoomAlias(e){const t=p.o("/directory/room/$alias",{$alias:e});return this.http.request(S.i.Get,t)}getRoomDirectoryVisibility(e){const t=p.o("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(S.i.Get,t)}setRoomDirectoryVisibility(e,t){const n=p.o("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(S.i.Put,n,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,n){const r=p.o("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(S.i.Put,r,void 0,{visibility:n})}searchUserDirectory(e){let{term:t,limit:n}=e;const r={search_term:t};return void 0!==n&&(r.limit=n),this.http.authedRequest(S.i.Post,"/user_directory/search",void 0,r)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){const n=t?p.o("/profile/$userId/$info",{$userId:e,$info:t}):p.o("/profile/$userId",{$userId:e});return this.http.authedRequest(S.i.Get,n)}getThreePids(){return this.http.authedRequest(S.i.Get,"/account/3pid")}addThreePid(e,t){const n={threePidCreds:e,bind:t};return this.http.authedRequest(S.i.Post,"/account/3pid",void 0,n)}async addThreePidOnly(e){const t=await this.isVersionSupported("r0.6.0")?S.a.R0:S.a.Unstable;return this.http.authedRequest(S.i.Post,"/account/3pid/add",void 0,e,{prefix:t})}async bindThreePid(e){const t=await this.isVersionSupported("r0.6.0")?S.a.R0:S.a.Unstable;return this.http.authedRequest(S.i.Post,"/account/3pid/bind",void 0,e,{prefix:t})}async unbindThreePid(e,t){const n={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},r=await this.isVersionSupported("r0.6.0")?S.a.R0:S.a.Unstable;return this.http.authedRequest(S.i.Post,"/account/3pid/unbind",void 0,n,{prefix:r})}deleteThreePid(e,t){return this.http.authedRequest(S.i.Post,"/account/3pid/delete",void 0,{medium:e,address:t})}setPassword(e,t,n){const r={auth:e,new_password:t,logout_devices:n};return this.http.authedRequest(S.i.Post,"/account/password",void 0,r)}getDevices(){return this.http.authedRequest(S.i.Get,"/devices")}getDevice(e){const t=p.o("/devices/$device_id",{$device_id:e});return this.http.authedRequest(S.i.Get,t)}setDeviceDetails(e,t){const n=p.o("/devices/$device_id",{$device_id:e});return this.http.authedRequest(S.i.Put,n,void 0,t)}deleteDevice(e,t){const n=p.o("/devices/$device_id",{$device_id:e}),r={};return t&&(r.auth=t),this.http.authedRequest(S.i.Delete,n,void 0,r)}deleteMultipleDevices(e,t){const n={devices:e};t&&(n.auth=t);return this.http.authedRequest(S.i.Post,"/delete_devices",void 0,n)}async getPushers(){const e=await this.http.authedRequest(S.i.Get,"/pushers");return await this.doesServerSupportUnstableFeature("org.matrix.msc3881")||(e.pushers=e.pushers.map((e=>(e.hasOwnProperty(N.g.name)||(e[N.g.name]=!0),e)))),e}setPusher(e){return this.http.authedRequest(S.i.Post,"/pushers/set",void 0,e)}setLocalNotificationSettings(e,t){const n=`${N.c.name}.${e}`;return this.setAccountData(n,t)}getPushRules(){return this.http.authedRequest(S.i.Get,"/pushrules/").then((e=>(this.setPushRules(e),this.pushRules)))}setPushRules(e){this.pushRules=g.a.rewriteDefaultRules(e),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,n,r){const i=p.o("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(S.i.Put,i,void 0,r)}deletePushRule(e,t,n){const r=p.o("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(S.i.Delete,r)}setPushRuleEnabled(e,t,n,r){const i=p.o("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(S.i.Put,i,void 0,{enabled:r})}setPushRuleActions(e,t,n,r){const i=p.o("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(S.i.Put,i,void 0,{actions:r})}search(e,t){let{body:n,next_batch:r}=e;const i={};return r&&(i.next_batch=r),this.http.authedRequest(S.i.Post,"/search",i,n,{abortSignal:t})}uploadKeysRequest(e,t){return this.http.authedRequest(S.i.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(S.i.Post,"/keys/signatures/upload",void 0,e,{prefix:S.a.V3})}downloadKeysForUsers(e){let{token:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n={device_keys:{}};return void 0!==t&&(n.token=t),e.forEach((e=>{n.device_keys[e]=[]})),this.http.authedRequest(S.i.Post,"/keys/query",void 0,n)}claimOneTimeKeys(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"signed_curve25519",n=arguments.length>2?arguments[2]:void 0;const r={};void 0===t&&(t="signed_curve25519");for(const[n,i]of e){const e=r[n]||{};r[n]=e,e[i]=t}const i={one_time_keys:r};n&&(i.timeout=n);return this.http.authedRequest(S.i.Post,"/keys/claim",void 0,i)}getKeyChanges(e,t){const n={from:e,to:t};return this.http.authedRequest(S.i.Get,"/keys/changes",n)}uploadDeviceSigningKeys(e,t){const n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(S.i.Post,"/keys/device_signing/upload",void 0,n,{prefix:S.a.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.http.getUrl("/account/register",void 0,S.e.V2,this.idBaseUrl);return this.http.requestOtherUrl(S.i.Post,t,e)}requestEmailToken(e,t,n,r,i){const o={client_secret:t,email:e,send_attempt:null==n?void 0:n.toString()};return r&&(o.next_link=r),this.http.idServerRequest(S.i.Post,"/validate/email/requestToken",o,S.e.V2,i)}requestMsisdnToken(e,t,n,r,i,o){const a={client_secret:n,country:e,phone_number:t,send_attempt:null==r?void 0:r.toString()};return i&&(a.next_link=i),this.http.idServerRequest(S.i.Post,"/validate/msisdn/requestToken",a,S.e.V2,o)}submitMsisdnToken(e,t,n,r){const i={sid:e,client_secret:t,token:n};return this.http.idServerRequest(S.i.Post,"/validate/msisdn/submitToken",i,S.e.V2,r)}submitMsisdnTokenOtherUrl(e,t,n,r){const i={sid:t,client_secret:n,token:r};return this.http.requestOtherUrl(S.i.Post,e,i)}getIdentityHashDetails(e){return this.http.idServerRequest(S.i.Get,"/hash_details",void 0,S.e.V2,e)}async identityHashedLookup(t,n){const r={},i=await this.getIdentityHashDetails(n);if(!i||!i.lookup_pepper||!i.algorithms)throw new Error("Unsupported identity server: bad response");r.pepper=i.lookup_pepper;const o={};if(i.algorithms.includes("sha256")){const n=new e.Olm.Utility;r.addresses=t.map((e=>{const t=e[0].toLowerCase(),i=e[1].toLowerCase(),a=n.sha256(`${t} ${i} ${r.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return o[a]=e[0],a})),r.algorithm="sha256"}else{if(!i.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");r.addresses=t.map((e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return o[t]=e[0],t})),r.algorithm="none"}const a=await this.http.idServerRequest(S.i.Post,"/lookup",r,S.e.V2,n);if(null==a||!a.mappings)return[];const s=[];for(const e of Object.keys(a.mappings)){const t=a.mappings[e],n=o[e];if(!n)throw new Error("Identity server returned more results than expected");s.push({address:n,mxid:t})}return s}async lookupThreePid(e,t,n){const r=(await this.identityHashedLookup([[t,e]],n)).find((e=>e.address===t));if(!r)return{};return{address:t,medium:e,mxid:r.mxid}}async bulkLookupThreePids(e,t){const n=await this.identityHashedLookup(e.map((e=>[e[1],e[0]])),t),r=[];for(const t of n){const n=e.find((e=>e[1]===t.address));if(!n)throw new Error("Identity sever returned unexpected results");r.push([n[0],t.address,t.mxid])}return{threepids:r}}getIdentityAccount(e){return this.http.idServerRequest(S.i.Get,"/account",void 0,S.e.V2,e)}sendToDevice(e,t,n){const r=p.o("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),i={messages:p.F(t)},o=new Map;for(const[e,n]of t)o.set(e,Array.from(n.keys()));return y.a.log(`PUT ${r}`,o),this.http.authedRequest(S.i.Put,r,void 0,i)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(S.i.Get,"/thirdparty/protocols").then((e=>{if(!e||"object"!=typeof e)throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e}))}getThirdpartyLocation(e,t){const n=p.o("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(S.i.Get,n,t)}getThirdpartyUser(e,t){const n=p.o("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(S.i.Get,n,t)}getTerms(e,t){const n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(S.i.Get,n)}agreeToTerms(e,t,n,r){const i=this.termsUrlForService(e,t),o={Authorization:"Bearer "+n};return this.http.requestOtherUrl(S.i.Post,i,{user_accepts:r},{headers:o})}reportEvent(e,t,n,r){const i=p.o("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(S.i.Post,i,void 0,{score:n,reason:r})}getRoomHierarchy(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4?arguments[4]:void 0;const o=p.o("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(r),max_depth:null==n?void 0:n.toString(),from:i,limit:null==t?void 0:t.toString()};return this.http.authedRequest(S.i.Get,o,a,void 0,{prefix:S.a.V1}).catch((e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(S.i.Get,o,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw e}))}async unstableCreateFileTree(e){const{room_id:t}=await this.createRoom({name:e,preset:M.d.PrivateChat,power_level_content_override:re(re({},U.a),{},{users:{[this.getUserId()]:100}}),creation_content:{[N.i]:N.j.Space},initial_state:[{type:N.o.name,state_key:N.r.name,content:{[N.n.name]:!0}},{type:N.b.RoomEncryption,state_key:"",content:{algorithm:_.MEGOLM_ALGORITHM}}]});return new U.b(this,t)}unstableGetFileTreeSpace(e){var t,n;const r=this.getRoom(e);if("join"!==(null==r?void 0:r.getMyMembership()))return null;const i=r.currentState.getStateEvents(N.b.RoomCreate,""),o=r.currentState.getStateEvents(N.o.name,N.r.name);if(!i)throw new Error("Expected single room create event");return null!=o&&null!==(t=o.getContent())&&void 0!==t&&t[N.n.name]?(null===(n=i.getContent())||void 0===n?void 0:n[N.i])!==N.j.Space?null:new U.b(this,e):null}slidingSync(e,t,n){const r={};e.pos&&(r.pos=e.pos,delete e.pos),e.timeout&&(r.timeout=e.timeout,delete e.timeout);const i=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(S.i.Post,"/sync",r,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:i,abortSignal:n})}supportsExperimentalThreads(){var e;return y.a.warn("supportsExperimentalThreads() is deprecated, use supportThreads() instead"),(null===(e=this.clientOpts)||void 0===e?void 0:e.experimentalThreadSupport)||!1}supportsThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.threadSupport)||!1}async getRoomSummary(e,t){const n=p.o("/rooms/$roomid/summary",{$roomid:e});return this.http.authedRequest(S.i.Get,n,{via:t},void 0,{prefix:"/_matrix/client/unstable/im.nheko.summary"})}processThreadEvents(e,t,n){e.processThreadedEvents(t,n)}processThreadRoots(e,t,n){e.processThreadRoots(t,n)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){null!=t&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}async whoami(){return this.http.authedRequest(S.i.Get,"/account/whoami")}async timestampToEvent(e,t,n){const r=p.o("/rooms/$roomId/timestamp_to_event",{$roomId:e}),i={ts:t.toString(),dir:n};try{return await this.http.authedRequest(S.i.Get,r,i,void 0,{prefix:S.a.V1})}catch(e){if("M_UNRECOGNIZED"===e.errcode&&(400===e.httpStatus||404===e.httpStatus||405===e.httpStatus))return await this.http.authedRequest(S.i.Get,r,i,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw e}}}function fe(e,t){var n,r;const i=e.getUserId(),o=t.getId(),a=e.getRoom(t.getRoomId());if(!a||!i||!o)return;const s=t.getPushActions(),l=e.getPushActionsForEvent(t,!0),c=!!t.threadRootId&&!t.isThreadRoot,u=a.getUnreadCountForEventContext(A.b.Highlight,t),d=!(null==s||null===(n=s.tweaks)||void 0===n||!n.highlight),h=!(null==l||null===(r=l.tweaks)||void 0===r||!r.highlight);let p;if(c){const e=a.getThread(t.threadRootId);p=!e||e.hasUserReadEvent(i,o)}else p=a.hasUserReadEvent(i,o);if(p)return;if(d!==h||u>0){let e=u;h&&!d&&e++,!h&&d&&e--,c?a.setThreadUnreadNotificationCount(t.threadRootId,A.b.Highlight,e):a.setUnreadNotificationCount(A.b.Highlight,e)}const m=a.getUnreadCountForEventContext(A.b.Total,t);!(null==l||!l.notify)&&(c?a.setThreadUnreadNotificationCount(t.threadRootId,A.b.Total,m+1):a.setUnreadNotificationCount(A.b.Total,m+1))}a()(ge,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY")}).call(this,n(14))},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r=n(130),i=n.n(r),o=n(132),a=n.n(o),s=n(13),l=n.n(s),c=n(120),u=n.n(c),d=n(123),h=n(161);const p=["title","tooltip","children","tooltipClassName","forceHide","alignment","onHideTooltip"];class m extends u.a.PureComponent{constructor(e){super(e),l()(this,"showTooltip",(()=>{this.props.onHover&&this.props.onHover(!0),this.props.forceHide||this.setState({hover:!0})})),l()(this,"hideTooltip",(e=>{var t,n;this.props.onHover&&this.props.onHover(!1),this.setState({hover:!1}),null===(t=(n=this.props).onHideTooltip)||void 0===t||t.call(n,e)})),l()(this,"onFocus",(e=>{e.relatedTarget&&this.showTooltip()})),this.state={hover:!1}}componentDidUpdate(e){!e.forceHide&&this.props.forceHide&&this.state.hover&&this.setState({hover:!1})}render(){const e=this.props,{title:t,tooltip:n,children:r,tooltipClassName:o,forceHide:s,alignment:l,onHideTooltip:c}=e,m=a()(e,p),g=this.state.hover&&(t||n)&&u.a.createElement(h.b,{tooltipClassName:o,label:n||t,alignment:l});return u.a.createElement(d.a,i()({},m,{onMouseOver:this.showTooltip||m.onMouseOver,onMouseLeave:this.hideTooltip||m.onMouseLeave,onFocus:this.onFocus||m.onFocus,onBlur:this.hideTooltip||m.onBlur,"aria-label":t||m["aria-label"]}),r,this.props.label,(n||t)&&g)}}},function(e,t,n){(function(e,r){var i;(function(){var o,a=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",l="Expected a function",c="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",p=1,m=2,g=4,f=1,_=2,b=1,v=2,y=4,E=8,S=16,w=32,T=64,C=128,x=256,F=512,D=30,k="...",O=800,I=16,A=1,R=2,N=1/0,M=9007199254740991,P=17976931348623157e292,L=NaN,B=4294967295,U=B-1,j=B>>>1,G=[["ary",C],["bind",b],["bindKey",v],["curry",E],["curryRight",S],["flip",F],["partial",w],["partialRight",T],["rearg",x]],z="[object Arguments]",H="[object Array]",q="[object AsyncFunction]",V="[object Boolean]",$="[object Date]",K="[object DOMException]",W="[object Error]",Y="[object Function]",Q="[object GeneratorFunction]",X="[object Map]",Z="[object Number]",J="[object Null]",ee="[object Object]",te="[object Promise]",ne="[object Proxy]",re="[object RegExp]",ie="[object Set]",oe="[object String]",ae="[object Symbol]",se="[object Undefined]",le="[object WeakMap]",ce="[object WeakSet]",ue="[object ArrayBuffer]",de="[object DataView]",he="[object Float32Array]",pe="[object Float64Array]",me="[object Int8Array]",ge="[object Int16Array]",fe="[object Int32Array]",_e="[object Uint8Array]",be="[object Uint8ClampedArray]",ve="[object Uint16Array]",ye="[object Uint32Array]",Ee=/\b__p \+= '';/g,Se=/\b(__p \+=) '' \+/g,we=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Te=/&(?:amp|lt|gt|quot|#39);/g,Ce=/[&<>"']/g,xe=RegExp(Te.source),Fe=RegExp(Ce.source),De=/<%-([\s\S]+?)%>/g,ke=/<%([\s\S]+?)%>/g,Oe=/<%=([\s\S]+?)%>/g,Ie=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ae=/^\w*$/,Re=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ne=/[\\^$.*+?()[\]{}|]/g,Me=RegExp(Ne.source),Pe=/^\s+/,Le=/\s/,Be=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Ue=/\{\n\/\* \[wrapped with (.+)\] \*/,je=/,? & /,Ge=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ze=/[()=,{}\[\]\/\s]/,He=/\\(\\)?/g,qe=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ve=/\w*$/,$e=/^[-+]0x[0-9a-f]+$/i,Ke=/^0b[01]+$/i,We=/^\[object .+?Constructor\]$/,Ye=/^0o[0-7]+$/i,Qe=/^(?:0|[1-9]\d*)$/,Xe=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ze=/($^)/,Je=/['\n\r\u2028\u2029\\]/g,et="\\ud800-\\udfff",tt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",nt="\\u2700-\\u27bf",rt="a-z\\xdf-\\xf6\\xf8-\\xff",it="A-Z\\xc0-\\xd6\\xd8-\\xde",ot="\\ufe0e\\ufe0f",at="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",st="['’]",lt="["+et+"]",ct="["+at+"]",ut="["+tt+"]",dt="\\d+",ht="["+nt+"]",pt="["+rt+"]",mt="[^"+et+at+dt+nt+rt+it+"]",gt="\\ud83c[\\udffb-\\udfff]",ft="[^"+et+"]",_t="(?:\\ud83c[\\udde6-\\uddff]){2}",bt="[\\ud800-\\udbff][\\udc00-\\udfff]",vt="["+it+"]",yt="\\u200d",Et="(?:"+pt+"|"+mt+")",St="(?:"+vt+"|"+mt+")",wt="(?:['’](?:d|ll|m|re|s|t|ve))?",Tt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ct="(?:"+ut+"|"+gt+")"+"?",xt="["+ot+"]?",Ft=xt+Ct+("(?:"+yt+"(?:"+[ft,_t,bt].join("|")+")"+xt+Ct+")*"),Dt="(?:"+[ht,_t,bt].join("|")+")"+Ft,kt="(?:"+[ft+ut+"?",ut,_t,bt,lt].join("|")+")",Ot=RegExp(st,"g"),It=RegExp(ut,"g"),At=RegExp(gt+"(?="+gt+")|"+kt+Ft,"g"),Rt=RegExp([vt+"?"+pt+"+"+wt+"(?="+[ct,vt,"$"].join("|")+")",St+"+"+Tt+"(?="+[ct,vt+Et,"$"].join("|")+")",vt+"?"+Et+"+"+wt,vt+"+"+Tt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",dt,Dt].join("|"),"g"),Nt=RegExp("["+yt+et+tt+ot+"]"),Mt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Pt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Lt=-1,Bt={};Bt[he]=Bt[pe]=Bt[me]=Bt[ge]=Bt[fe]=Bt[_e]=Bt[be]=Bt[ve]=Bt[ye]=!0,Bt[z]=Bt[H]=Bt[ue]=Bt[V]=Bt[de]=Bt[$]=Bt[W]=Bt[Y]=Bt[X]=Bt[Z]=Bt[ee]=Bt[re]=Bt[ie]=Bt[oe]=Bt[le]=!1;var Ut={};Ut[z]=Ut[H]=Ut[ue]=Ut[de]=Ut[V]=Ut[$]=Ut[he]=Ut[pe]=Ut[me]=Ut[ge]=Ut[fe]=Ut[X]=Ut[Z]=Ut[ee]=Ut[re]=Ut[ie]=Ut[oe]=Ut[ae]=Ut[_e]=Ut[be]=Ut[ve]=Ut[ye]=!0,Ut[W]=Ut[Y]=Ut[le]=!1;var jt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Gt=parseFloat,zt=parseInt,Ht="object"==typeof e&&e&&e.Object===Object&&e,qt="object"==typeof self&&self&&self.Object===Object&&self,Vt=Ht||qt||Function("return this")(),$t=t&&!t.nodeType&&t,Kt=$t&&"object"==typeof r&&r&&!r.nodeType&&r,Wt=Kt&&Kt.exports===$t,Yt=Wt&&Ht.process,Qt=function(){try{var e=Kt&&Kt.require&&Kt.require("util").types;return e||Yt&&Yt.binding&&Yt.binding("util")}catch(e){}}(),Xt=Qt&&Qt.isArrayBuffer,Zt=Qt&&Qt.isDate,Jt=Qt&&Qt.isMap,en=Qt&&Qt.isRegExp,tn=Qt&&Qt.isSet,nn=Qt&&Qt.isTypedArray;function rn(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function on(e,t,n,r){for(var i=-1,o=null==e?0:e.length;++i-1}function dn(e,t,n){for(var r=-1,i=null==e?0:e.length;++r-1;);return n}function Nn(e,t){for(var n=e.length;n--&&yn(t,e[n],0)>-1;);return n}var Mn=Cn({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Pn=Cn({"&":"&","<":"<",">":">",'"':""","'":"'"});function Ln(e){return"\\"+jt[e]}function Bn(e){return Nt.test(e)}function Un(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function jn(e,t){return function(n){return e(t(n))}}function Gn(e,t){for(var n=-1,r=e.length,i=0,o=[];++n",""":'"',"'":"'"});var Wn=function e(t){var n,r=(t=null==t?Vt:Wn.defaults(Vt.Object(),t,Wn.pick(Vt,Pt))).Array,i=t.Date,Le=t.Error,et=t.Function,tt=t.Math,nt=t.Object,rt=t.RegExp,it=t.String,ot=t.TypeError,at=r.prototype,st=et.prototype,lt=nt.prototype,ct=t["__core-js_shared__"],ut=st.toString,dt=lt.hasOwnProperty,ht=0,pt=(n=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",mt=lt.toString,gt=ut.call(nt),ft=Vt._,_t=rt("^"+ut.call(dt).replace(Ne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),bt=Wt?t.Buffer:o,vt=t.Symbol,yt=t.Uint8Array,Et=bt?bt.allocUnsafe:o,St=jn(nt.getPrototypeOf,nt),wt=nt.create,Tt=lt.propertyIsEnumerable,Ct=at.splice,xt=vt?vt.isConcatSpreadable:o,Ft=vt?vt.iterator:o,Dt=vt?vt.toStringTag:o,kt=function(){try{var e=zo(nt,"defineProperty");return e({},"",{}),e}catch(e){}}(),At=t.clearTimeout!==Vt.clearTimeout&&t.clearTimeout,Nt=i&&i.now!==Vt.Date.now&&i.now,jt=t.setTimeout!==Vt.setTimeout&&t.setTimeout,Ht=tt.ceil,qt=tt.floor,$t=nt.getOwnPropertySymbols,Kt=bt?bt.isBuffer:o,Yt=t.isFinite,Qt=at.join,_n=jn(nt.keys,nt),Cn=tt.max,Yn=tt.min,Qn=i.now,Xn=t.parseInt,Zn=tt.random,Jn=at.reverse,er=zo(t,"DataView"),tr=zo(t,"Map"),nr=zo(t,"Promise"),rr=zo(t,"Set"),ir=zo(t,"WeakMap"),or=zo(nt,"create"),ar=ir&&new ir,sr={},lr=ma(er),cr=ma(tr),ur=ma(nr),dr=ma(rr),hr=ma(ir),pr=vt?vt.prototype:o,mr=pr?pr.valueOf:o,gr=pr?pr.toString:o;function fr(e){if(Is(e)&&!ys(e)&&!(e instanceof yr)){if(e instanceof vr)return e;if(dt.call(e,"__wrapped__"))return ga(e)}return new vr(e)}var _r=function(){function e(){}return function(t){if(!Os(t))return{};if(wt)return wt(t);e.prototype=t;var n=new e;return e.prototype=o,n}}();function br(){}function vr(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=o}function yr(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=B,this.__views__=[]}function Er(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function Br(e,t,n,r,i,a){var s,l=t&p,c=t&m,u=t&g;if(n&&(s=i?n(e,r,i,a):n(e)),s!==o)return s;if(!Os(e))return e;var d=ys(e);if(d){if(s=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&dt.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!l)return oo(e,s)}else{var h=Vo(e),f=h==Y||h==Q;if(Ts(e))return Ji(e,l);if(h==ee||h==z||f&&!i){if(s=c||f?{}:Ko(e),!l)return c?function(e,t){return ao(e,qo(e),t)}(e,function(e,t){return e&&ao(t,ll(t),e)}(s,e)):function(e,t){return ao(e,Ho(e),t)}(e,Nr(s,e))}else{if(!Ut[h])return i?e:{};s=function(e,t,n){var r=e.constructor;switch(t){case ue:return eo(e);case V:case $:return new r(+e);case de:return function(e,t){var n=t?eo(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case he:case pe:case me:case ge:case fe:case _e:case be:case ve:case ye:return to(e,n);case X:return new r;case Z:case oe:return new r(e);case re:return function(e){var t=new e.constructor(e.source,Ve.exec(e));return t.lastIndex=e.lastIndex,t}(e);case ie:return new r;case ae:return i=e,mr?nt(mr.call(i)):{}}var i}(e,h,l)}}a||(a=new Cr);var _=a.get(e);if(_)return _;a.set(e,s),Ps(e)?e.forEach((function(r){s.add(Br(r,t,n,r,e,a))})):As(e)&&e.forEach((function(r,i){s.set(i,Br(r,t,n,i,e,a))}));var b=d?o:(u?c?Mo:No:c?ll:sl)(e);return an(b||e,(function(r,i){b&&(r=e[i=r]),Ir(s,i,Br(r,t,n,i,e,a))})),s}function Ur(e,t,n){var r=n.length;if(null==e)return!r;for(e=nt(e);r--;){var i=n[r],a=t[i],s=e[i];if(s===o&&!(i in e)||!a(s))return!1}return!0}function jr(e,t,n){if("function"!=typeof e)throw new ot(l);return sa((function(){e.apply(o,n)}),t)}function Gr(e,t,n,r){var i=-1,o=un,s=!0,l=e.length,c=[],u=t.length;if(!l)return c;n&&(t=hn(t,On(n))),r?(o=dn,s=!1):t.length>=a&&(o=An,s=!1,t=new Tr(t));e:for(;++i-1},Sr.prototype.set=function(e,t){var n=this.__data__,r=Ar(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},wr.prototype.clear=function(){this.size=0,this.__data__={hash:new Er,map:new(tr||Sr),string:new Er}},wr.prototype.delete=function(e){var t=jo(this,e).delete(e);return this.size-=t?1:0,t},wr.prototype.get=function(e){return jo(this,e).get(e)},wr.prototype.has=function(e){return jo(this,e).has(e)},wr.prototype.set=function(e,t){var n=jo(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},Tr.prototype.add=Tr.prototype.push=function(e){return this.__data__.set(e,u),this},Tr.prototype.has=function(e){return this.__data__.has(e)},Cr.prototype.clear=function(){this.__data__=new Sr,this.size=0},Cr.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Cr.prototype.get=function(e){return this.__data__.get(e)},Cr.prototype.has=function(e){return this.__data__.has(e)},Cr.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Sr){var r=n.__data__;if(!tr||r.length0&&n(s)?t>1?Kr(s,t-1,n,r,i):pn(i,s):r||(i[i.length]=s)}return i}var Wr=uo(),Yr=uo(!0);function Qr(e,t){return e&&Wr(e,t,sl)}function Xr(e,t){return e&&Yr(e,t,sl)}function Zr(e,t){return cn(t,(function(t){return Fs(e[t])}))}function Jr(e,t){for(var n=0,r=(t=Yi(t,e)).length;null!=e&&nt}function ri(e,t){return null!=e&&dt.call(e,t)}function ii(e,t){return null!=e&&t in nt(e)}function oi(e,t,n){for(var i=n?dn:un,a=e[0].length,s=e.length,l=s,c=r(s),u=1/0,d=[];l--;){var h=e[l];l&&t&&(h=hn(h,On(t))),u=Yn(h.length,u),c[l]=!n&&(t||a>=120&&h.length>=120)?new Tr(l&&h):o}h=e[0];var p=-1,m=c[0];e:for(;++p=s?l:l*("desc"==n[r]?-1:1)}return e.index-t.index}(e,t,n)}))}function Ei(e,t,n){for(var r=-1,i=t.length,o={};++r-1;)s!==e&&Ct.call(s,l,1),Ct.call(e,l,1);return e}function wi(e,t){for(var n=e?t.length:0,r=n-1;n--;){var i=t[n];if(n==r||i!==o){var o=i;Yo(i)?Ct.call(e,i,1):Gi(e,i)}}return e}function Ti(e,t){return e+qt(Zn()*(t-e+1))}function Ci(e,t){var n="";if(!e||t<1||t>M)return n;do{t%2&&(n+=e),(t=qt(t/2))&&(e+=e)}while(t);return n}function xi(e,t){return la(ra(e,t,Rl),e+"")}function Fi(e){return Fr(fl(e))}function Di(e,t){var n=fl(e);return da(n,Lr(t,0,n.length))}function ki(e,t,n,r){if(!Os(e))return e;for(var i=-1,a=(t=Yi(t,e)).length,s=a-1,l=e;null!=l&&++io?0:o+t),(n=n>o?o:n)<0&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var a=r(o);++i>>1,a=e[o];null!==a&&!Bs(a)&&(n?a<=t:a=a){var u=t?null:xo(e);if(u)return zn(u);s=!1,i=An,c=new Tr}else c=t?[]:l;e:for(;++r=r?e:Ri(e,t,n)}var Zi=At||function(e){return Vt.clearTimeout(e)};function Ji(e,t){if(t)return e.slice();var n=e.length,r=Et?Et(n):new e.constructor(n);return e.copy(r),r}function eo(e){var t=new e.constructor(e.byteLength);return new yt(t).set(new yt(e)),t}function to(e,t){var n=t?eo(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function no(e,t){if(e!==t){var n=e!==o,r=null===e,i=e==e,a=Bs(e),s=t!==o,l=null===t,c=t==t,u=Bs(t);if(!l&&!u&&!a&&e>t||a&&s&&c&&!l&&!u||r&&s&&c||!n&&c||!i)return 1;if(!r&&!a&&!u&&e1?n[i-1]:o,s=i>2?n[2]:o;for(a=e.length>3&&"function"==typeof a?(i--,a):o,s&&Qo(n[0],n[1],s)&&(a=i<3?o:a,i=1),t=nt(t);++r-1?i[a?t[s]:s]:o}}function fo(e){return Ro((function(t){var n=t.length,r=n,i=vr.prototype.thru;for(e&&t.reverse();r--;){var a=t[r];if("function"!=typeof a)throw new ot(l);if(i&&!s&&"wrapper"==Lo(a))var s=new vr([],!0)}for(r=s?r:n;++r1&&y.reverse(),h&&ul))return!1;var u=a.get(e),d=a.get(t);if(u&&d)return u==t&&d==e;var h=-1,p=!0,m=n&_?new Tr:o;for(a.set(e,t),a.set(t,e);++h-1&&e%1==0&&e1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(Be,"{\n/* [wrapped with "+t+"] */\n")}(r,function(e,t){return an(G,(function(n){var r="_."+n[0];t&n[1]&&!un(e,r)&&e.push(r)})),e.sort()}(function(e){var t=e.match(Ue);return t?t[1].split(je):[]}(r),n)))}function ua(e){var t=0,n=0;return function(){var r=Qn(),i=I-(r-n);if(n=r,i>0){if(++t>=O)return arguments[0]}else t=0;return e.apply(o,arguments)}}function da(e,t){var n=-1,r=e.length,i=r-1;for(t=t===o?r:t;++n1?e[t-1]:o;return n="function"==typeof n?(e.pop(),n):o,Ma(e,n)}));function za(e){var t=fr(e);return t.__chain__=!0,t}function Ha(e,t){return t(e)}var qa=Ro((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,i=function(t){return Pr(t,e)};return!(t>1||this.__actions__.length)&&r instanceof yr&&Yo(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:Ha,args:[i],thisArg:o}),new vr(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(o),e}))):this.thru(i)}));var Va=so((function(e,t,n){dt.call(e,n)?++e[n]:Mr(e,n,1)}));var $a=go(va),Ka=go(ya);function Wa(e,t){return(ys(e)?an:zr)(e,Uo(t,3))}function Ya(e,t){return(ys(e)?sn:Hr)(e,Uo(t,3))}var Qa=so((function(e,t,n){dt.call(e,n)?e[n].push(t):Mr(e,n,[t])}));var Xa=xi((function(e,t,n){var i=-1,o="function"==typeof t,a=Ss(e)?r(e.length):[];return zr(e,(function(e){a[++i]=o?rn(t,e,n):ai(e,t,n)})),a})),Za=so((function(e,t,n){Mr(e,n,t)}));function Ja(e,t){return(ys(e)?hn:gi)(e,Uo(t,3))}var es=so((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var ts=xi((function(e,t){if(null==e)return[];var n=t.length;return n>1&&Qo(e,t[0],t[1])?t=[]:n>2&&Qo(t[0],t[1],t[2])&&(t=[t[0]]),yi(e,Kr(t,1),[])})),ns=Nt||function(){return Vt.Date.now()};function rs(e,t,n){return t=n?o:t,t=e&&null==t?e.length:t,Do(e,C,o,o,o,o,t)}function is(e,t){var n;if("function"!=typeof t)throw new ot(l);return e=qs(e),function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=o),n}}var os=xi((function(e,t,n){var r=b;if(n.length){var i=Gn(n,Bo(os));r|=w}return Do(e,r,t,n,i)})),as=xi((function(e,t,n){var r=b|v;if(n.length){var i=Gn(n,Bo(as));r|=w}return Do(t,r,e,n,i)}));function ss(e,t,n){var r,i,a,s,c,u,d=0,h=!1,p=!1,m=!0;if("function"!=typeof e)throw new ot(l);function g(t){var n=r,a=i;return r=i=o,d=t,s=e.apply(a,n)}function f(e){var n=e-u;return u===o||n>=t||n<0||p&&e-d>=a}function _(){var e=ns();if(f(e))return b(e);c=sa(_,function(e){var n=t-(e-u);return p?Yn(n,a-(e-d)):n}(e))}function b(e){return c=o,m&&r?g(e):(r=i=o,s)}function v(){var e=ns(),n=f(e);if(r=arguments,i=this,u=e,n){if(c===o)return function(e){return d=e,c=sa(_,t),h?g(e):s}(u);if(p)return Zi(c),c=sa(_,t),g(u)}return c===o&&(c=sa(_,t)),s}return t=$s(t)||0,Os(n)&&(h=!!n.leading,a=(p="maxWait"in n)?Cn($s(n.maxWait)||0,t):a,m="trailing"in n?!!n.trailing:m),v.cancel=function(){c!==o&&Zi(c),d=0,r=u=i=c=o},v.flush=function(){return c===o?s:b(ns())},v}var ls=xi((function(e,t){return jr(e,1,t)})),cs=xi((function(e,t,n){return jr(e,$s(t)||0,n)}));function us(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new ot(l);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=e.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(us.Cache||wr),n}function ds(e){if("function"!=typeof e)throw new ot(l);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}us.Cache=wr;var hs=Qi((function(e,t){var n=(t=1==t.length&&ys(t[0])?hn(t[0],On(Uo())):hn(Kr(t,1),On(Uo()))).length;return xi((function(r){for(var i=-1,o=Yn(r.length,n);++i=t})),vs=si(function(){return arguments}())?si:function(e){return Is(e)&&dt.call(e,"callee")&&!Tt.call(e,"callee")},ys=r.isArray,Es=Xt?On(Xt):function(e){return Is(e)&&ti(e)==ue};function Ss(e){return null!=e&&ks(e.length)&&!Fs(e)}function ws(e){return Is(e)&&Ss(e)}var Ts=Kt||$l,Cs=Zt?On(Zt):function(e){return Is(e)&&ti(e)==$};function xs(e){if(!Is(e))return!1;var t=ti(e);return t==W||t==K||"string"==typeof e.message&&"string"==typeof e.name&&!Ns(e)}function Fs(e){if(!Os(e))return!1;var t=ti(e);return t==Y||t==Q||t==q||t==ne}function Ds(e){return"number"==typeof e&&e==qs(e)}function ks(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=M}function Os(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Is(e){return null!=e&&"object"==typeof e}var As=Jt?On(Jt):function(e){return Is(e)&&Vo(e)==X};function Rs(e){return"number"==typeof e||Is(e)&&ti(e)==Z}function Ns(e){if(!Is(e)||ti(e)!=ee)return!1;var t=St(e);if(null===t)return!0;var n=dt.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&ut.call(n)==gt}var Ms=en?On(en):function(e){return Is(e)&&ti(e)==re};var Ps=tn?On(tn):function(e){return Is(e)&&Vo(e)==ie};function Ls(e){return"string"==typeof e||!ys(e)&&Is(e)&&ti(e)==oe}function Bs(e){return"symbol"==typeof e||Is(e)&&ti(e)==ae}var Us=nn?On(nn):function(e){return Is(e)&&ks(e.length)&&!!Bt[ti(e)]};var js=wo(mi),Gs=wo((function(e,t){return e<=t}));function zs(e){if(!e)return[];if(Ss(e))return Ls(e)?Vn(e):oo(e);if(Ft&&e[Ft])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[Ft]());var t=Vo(e);return(t==X?Un:t==ie?zn:fl)(e)}function Hs(e){return e?(e=$s(e))===N||e===-N?(e<0?-1:1)*P:e==e?e:0:0===e?e:0}function qs(e){var t=Hs(e),n=t%1;return t==t?n?t-n:t:0}function Vs(e){return e?Lr(qs(e),0,B):0}function $s(e){if("number"==typeof e)return e;if(Bs(e))return L;if(Os(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Os(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=kn(e);var n=Ke.test(e);return n||Ye.test(e)?zt(e.slice(2),n?2:8):$e.test(e)?L:+e}function Ks(e){return ao(e,ll(e))}function Ws(e){return null==e?"":Ui(e)}var Ys=lo((function(e,t){if(ea(t)||Ss(t))ao(t,sl(t),e);else for(var n in t)dt.call(t,n)&&Ir(e,n,t[n])})),Qs=lo((function(e,t){ao(t,ll(t),e)})),Xs=lo((function(e,t,n,r){ao(t,ll(t),e,r)})),Zs=lo((function(e,t,n,r){ao(t,sl(t),e,r)})),Js=Ro(Pr);var el=xi((function(e,t){e=nt(e);var n=-1,r=t.length,i=r>2?t[2]:o;for(i&&Qo(t[0],t[1],i)&&(r=1);++n1),t})),ao(e,Mo(e),n),r&&(n=Br(n,p|m|g,Io));for(var i=t.length;i--;)Gi(n,t[i]);return n}));var hl=Ro((function(e,t){return null==e?{}:function(e,t){return Ei(e,t,(function(t,n){return rl(e,n)}))}(e,t)}));function pl(e,t){if(null==e)return{};var n=hn(Mo(e),(function(e){return[e]}));return t=Uo(t),Ei(e,n,(function(e,n){return t(e,n[0])}))}var ml=Fo(sl),gl=Fo(ll);function fl(e){return null==e?[]:In(e,sl(e))}var _l=po((function(e,t,n){return t=t.toLowerCase(),e+(n?bl(t):t)}));function bl(e){return xl(Ws(e).toLowerCase())}function vl(e){return(e=Ws(e))&&e.replace(Xe,Mn).replace(It,"")}var yl=po((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),El=po((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Sl=ho("toLowerCase");var wl=po((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var Tl=po((function(e,t,n){return e+(n?" ":"")+xl(t)}));var Cl=po((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),xl=ho("toUpperCase");function Fl(e,t,n){return e=Ws(e),(t=n?o:t)===o?function(e){return Mt.test(e)}(e)?function(e){return e.match(Rt)||[]}(e):function(e){return e.match(Ge)||[]}(e):e.match(t)||[]}var Dl=xi((function(e,t){try{return rn(e,o,t)}catch(e){return xs(e)?e:new Le(e)}})),kl=Ro((function(e,t){return an(t,(function(t){t=pa(t),Mr(e,t,os(e[t],e))})),e}));function Ol(e){return function(){return e}}var Il=fo(),Al=fo(!0);function Rl(e){return e}function Nl(e){return di("function"==typeof e?e:Br(e,p))}var Ml=xi((function(e,t){return function(n){return ai(n,e,t)}})),Pl=xi((function(e,t){return function(n){return ai(e,n,t)}}));function Ll(e,t,n){var r=sl(t),i=Zr(t,r);null!=n||Os(t)&&(i.length||!r.length)||(n=t,t=e,e=this,i=Zr(t,sl(t)));var o=!(Os(n)&&"chain"in n&&!n.chain),a=Fs(e);return an(i,(function(n){var r=t[n];e[n]=r,a&&(e.prototype[n]=function(){var t=this.__chain__;if(o||t){var n=e(this.__wrapped__);return(n.__actions__=oo(this.__actions__)).push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,pn([this.value()],arguments))})})),e}function Bl(){}var Ul=yo(hn),jl=yo(ln),Gl=yo(fn);function zl(e){return Xo(e)?Tn(pa(e)):function(e){return function(t){return Jr(t,e)}}(e)}var Hl=So(),ql=So(!0);function Vl(){return[]}function $l(){return!1}var Kl=vo((function(e,t){return e+t}),0),Wl=Co("ceil"),Yl=vo((function(e,t){return e/t}),1),Ql=Co("floor");var Xl,Zl=vo((function(e,t){return e*t}),1),Jl=Co("round"),ec=vo((function(e,t){return e-t}),0);return fr.after=function(e,t){if("function"!=typeof t)throw new ot(l);return e=qs(e),function(){if(--e<1)return t.apply(this,arguments)}},fr.ary=rs,fr.assign=Ys,fr.assignIn=Qs,fr.assignInWith=Xs,fr.assignWith=Zs,fr.at=Js,fr.before=is,fr.bind=os,fr.bindAll=kl,fr.bindKey=as,fr.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return ys(e)?e:[e]},fr.chain=za,fr.chunk=function(e,t,n){t=(n?Qo(e,t,n):t===o)?1:Cn(qs(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var a=0,s=0,l=r(Ht(i/t));ai?0:i+n),(r=r===o||r>i?i:qs(r))<0&&(r+=i),r=n>r?0:Vs(r);n>>0)?(e=Ws(e))&&("string"==typeof t||null!=t&&!Ms(t))&&!(t=Ui(t))&&Bn(e)?Xi(Vn(e),0,n):e.split(t,n):[]},fr.spread=function(e,t){if("function"!=typeof e)throw new ot(l);return t=null==t?0:Cn(qs(t),0),xi((function(n){var r=n[t],i=Xi(n,0,t);return r&&pn(i,r),rn(e,this,i)}))},fr.tail=function(e){var t=null==e?0:e.length;return t?Ri(e,1,t):[]},fr.take=function(e,t,n){return e&&e.length?Ri(e,0,(t=n||t===o?1:qs(t))<0?0:t):[]},fr.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?Ri(e,(t=r-(t=n||t===o?1:qs(t)))<0?0:t,r):[]},fr.takeRightWhile=function(e,t){return e&&e.length?Hi(e,Uo(t,3),!1,!0):[]},fr.takeWhile=function(e,t){return e&&e.length?Hi(e,Uo(t,3)):[]},fr.tap=function(e,t){return t(e),e},fr.throttle=function(e,t,n){var r=!0,i=!0;if("function"!=typeof e)throw new ot(l);return Os(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),ss(e,t,{leading:r,maxWait:t,trailing:i})},fr.thru=Ha,fr.toArray=zs,fr.toPairs=ml,fr.toPairsIn=gl,fr.toPath=function(e){return ys(e)?hn(e,pa):Bs(e)?[e]:oo(ha(Ws(e)))},fr.toPlainObject=Ks,fr.transform=function(e,t,n){var r=ys(e),i=r||Ts(e)||Us(e);if(t=Uo(t,4),null==n){var o=e&&e.constructor;n=i?r?new o:[]:Os(e)&&Fs(o)?_r(St(e)):{}}return(i?an:Qr)(e,(function(e,r,i){return t(n,e,r,i)})),n},fr.unary=function(e){return rs(e,1)},fr.union=Ia,fr.unionBy=Aa,fr.unionWith=Ra,fr.uniq=function(e){return e&&e.length?ji(e):[]},fr.uniqBy=function(e,t){return e&&e.length?ji(e,Uo(t,2)):[]},fr.uniqWith=function(e,t){return t="function"==typeof t?t:o,e&&e.length?ji(e,o,t):[]},fr.unset=function(e,t){return null==e||Gi(e,t)},fr.unzip=Na,fr.unzipWith=Ma,fr.update=function(e,t,n){return null==e?e:zi(e,t,Wi(n))},fr.updateWith=function(e,t,n,r){return r="function"==typeof r?r:o,null==e?e:zi(e,t,Wi(n),r)},fr.values=fl,fr.valuesIn=function(e){return null==e?[]:In(e,ll(e))},fr.without=Pa,fr.words=Fl,fr.wrap=function(e,t){return ps(Wi(t),e)},fr.xor=La,fr.xorBy=Ba,fr.xorWith=Ua,fr.zip=ja,fr.zipObject=function(e,t){return $i(e||[],t||[],Ir)},fr.zipObjectDeep=function(e,t){return $i(e||[],t||[],ki)},fr.zipWith=Ga,fr.entries=ml,fr.entriesIn=gl,fr.extend=Qs,fr.extendWith=Xs,Ll(fr,fr),fr.add=Kl,fr.attempt=Dl,fr.camelCase=_l,fr.capitalize=bl,fr.ceil=Wl,fr.clamp=function(e,t,n){return n===o&&(n=t,t=o),n!==o&&(n=(n=$s(n))==n?n:0),t!==o&&(t=(t=$s(t))==t?t:0),Lr($s(e),t,n)},fr.clone=function(e){return Br(e,g)},fr.cloneDeep=function(e){return Br(e,p|g)},fr.cloneDeepWith=function(e,t){return Br(e,p|g,t="function"==typeof t?t:o)},fr.cloneWith=function(e,t){return Br(e,g,t="function"==typeof t?t:o)},fr.conformsTo=function(e,t){return null==t||Ur(e,t,sl(t))},fr.deburr=vl,fr.defaultTo=function(e,t){return null==e||e!=e?t:e},fr.divide=Yl,fr.endsWith=function(e,t,n){e=Ws(e),t=Ui(t);var r=e.length,i=n=n===o?r:Lr(qs(n),0,r);return(n-=t.length)>=0&&e.slice(n,i)==t},fr.eq=fs,fr.escape=function(e){return(e=Ws(e))&&Fe.test(e)?e.replace(Ce,Pn):e},fr.escapeRegExp=function(e){return(e=Ws(e))&&Me.test(e)?e.replace(Ne,"\\$&"):e},fr.every=function(e,t,n){var r=ys(e)?ln:qr;return n&&Qo(e,t,n)&&(t=o),r(e,Uo(t,3))},fr.find=$a,fr.findIndex=va,fr.findKey=function(e,t){return bn(e,Uo(t,3),Qr)},fr.findLast=Ka,fr.findLastIndex=ya,fr.findLastKey=function(e,t){return bn(e,Uo(t,3),Xr)},fr.floor=Ql,fr.forEach=Wa,fr.forEachRight=Ya,fr.forIn=function(e,t){return null==e?e:Wr(e,Uo(t,3),ll)},fr.forInRight=function(e,t){return null==e?e:Yr(e,Uo(t,3),ll)},fr.forOwn=function(e,t){return e&&Qr(e,Uo(t,3))},fr.forOwnRight=function(e,t){return e&&Xr(e,Uo(t,3))},fr.get=nl,fr.gt=_s,fr.gte=bs,fr.has=function(e,t){return null!=e&&$o(e,t,ri)},fr.hasIn=rl,fr.head=Sa,fr.identity=Rl,fr.includes=function(e,t,n,r){e=Ss(e)?e:fl(e),n=n&&!r?qs(n):0;var i=e.length;return n<0&&(n=Cn(i+n,0)),Ls(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&yn(e,t,n)>-1},fr.indexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var i=null==n?0:qs(n);return i<0&&(i=Cn(r+i,0)),yn(e,t,i)},fr.inRange=function(e,t,n){return t=Hs(t),n===o?(n=t,t=0):n=Hs(n),function(e,t,n){return e>=Yn(t,n)&&e=-M&&e<=M},fr.isSet=Ps,fr.isString=Ls,fr.isSymbol=Bs,fr.isTypedArray=Us,fr.isUndefined=function(e){return e===o},fr.isWeakMap=function(e){return Is(e)&&Vo(e)==le},fr.isWeakSet=function(e){return Is(e)&&ti(e)==ce},fr.join=function(e,t){return null==e?"":Qt.call(e,t)},fr.kebabCase=yl,fr.last=xa,fr.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var i=r;return n!==o&&(i=(i=qs(n))<0?Cn(r+i,0):Yn(i,r-1)),t==t?function(e,t,n){for(var r=n+1;r--;)if(e[r]===t)return r;return r}(e,t,i):vn(e,Sn,i,!0)},fr.lowerCase=El,fr.lowerFirst=Sl,fr.lt=js,fr.lte=Gs,fr.max=function(e){return e&&e.length?Vr(e,Rl,ni):o},fr.maxBy=function(e,t){return e&&e.length?Vr(e,Uo(t,2),ni):o},fr.mean=function(e){return wn(e,Rl)},fr.meanBy=function(e,t){return wn(e,Uo(t,2))},fr.min=function(e){return e&&e.length?Vr(e,Rl,mi):o},fr.minBy=function(e,t){return e&&e.length?Vr(e,Uo(t,2),mi):o},fr.stubArray=Vl,fr.stubFalse=$l,fr.stubObject=function(){return{}},fr.stubString=function(){return""},fr.stubTrue=function(){return!0},fr.multiply=Zl,fr.nth=function(e,t){return e&&e.length?vi(e,qs(t)):o},fr.noConflict=function(){return Vt._===this&&(Vt._=ft),this},fr.noop=Bl,fr.now=ns,fr.pad=function(e,t,n){e=Ws(e);var r=(t=qs(t))?qn(e):0;if(!t||r>=t)return e;var i=(t-r)/2;return Eo(qt(i),n)+e+Eo(Ht(i),n)},fr.padEnd=function(e,t,n){e=Ws(e);var r=(t=qs(t))?qn(e):0;return t&&rt){var r=e;e=t,t=r}if(n||e%1||t%1){var i=Zn();return Yn(e+i*(t-e+Gt("1e-"+((i+"").length-1))),t)}return Ti(e,t)},fr.reduce=function(e,t,n){var r=ys(e)?mn:xn,i=arguments.length<3;return r(e,Uo(t,4),n,i,zr)},fr.reduceRight=function(e,t,n){var r=ys(e)?gn:xn,i=arguments.length<3;return r(e,Uo(t,4),n,i,Hr)},fr.repeat=function(e,t,n){return t=(n?Qo(e,t,n):t===o)?1:qs(t),Ci(Ws(e),t)},fr.replace=function(){var e=arguments,t=Ws(e[0]);return e.length<3?t:t.replace(e[1],e[2])},fr.result=function(e,t,n){var r=-1,i=(t=Yi(t,e)).length;for(i||(i=1,e=o);++rM)return[];var n=B,r=Yn(e,B);t=Uo(t),e-=B;for(var i=Dn(r,t);++n=a)return e;var l=n-qn(r);if(l<1)return r;var c=s?Xi(s,0,l).join(""):e.slice(0,l);if(i===o)return c+r;if(s&&(l+=c.length-l),Ms(i)){if(e.slice(l).search(i)){var u,d=c;for(i.global||(i=rt(i.source,Ws(Ve.exec(i))+"g")),i.lastIndex=0;u=i.exec(d);)var h=u.index;c=c.slice(0,h===o?l:h)}}else if(e.indexOf(Ui(i),l)!=l){var p=c.lastIndexOf(i);p>-1&&(c=c.slice(0,p))}return c+r},fr.unescape=function(e){return(e=Ws(e))&&xe.test(e)?e.replace(Te,Kn):e},fr.uniqueId=function(e){var t=++ht;return Ws(e)+t},fr.upperCase=Cl,fr.upperFirst=xl,fr.each=Wa,fr.eachRight=Ya,fr.first=Sa,Ll(fr,(Xl={},Qr(fr,(function(e,t){dt.call(fr.prototype,t)||(Xl[t]=e)})),Xl),{chain:!1}),fr.VERSION="4.17.21",an(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){fr[e].placeholder=fr})),an(["drop","take"],(function(e,t){yr.prototype[e]=function(n){n=n===o?1:Cn(qs(n),0);var r=this.__filtered__&&!t?new yr(this):this.clone();return r.__filtered__?r.__takeCount__=Yn(n,r.__takeCount__):r.__views__.push({size:Yn(n,B),type:e+(r.__dir__<0?"Right":"")}),r},yr.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),an(["filter","map","takeWhile"],(function(e,t){var n=t+1,r=n==A||3==n;yr.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:Uo(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}})),an(["head","last"],(function(e,t){var n="take"+(t?"Right":"");yr.prototype[e]=function(){return this[n](1).value()[0]}})),an(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");yr.prototype[e]=function(){return this.__filtered__?new yr(this):this[n](1)}})),yr.prototype.compact=function(){return this.filter(Rl)},yr.prototype.find=function(e){return this.filter(e).head()},yr.prototype.findLast=function(e){return this.reverse().find(e)},yr.prototype.invokeMap=xi((function(e,t){return"function"==typeof e?new yr(this):this.map((function(n){return ai(n,e,t)}))})),yr.prototype.reject=function(e){return this.filter(ds(Uo(e)))},yr.prototype.slice=function(e,t){e=qs(e);var n=this;return n.__filtered__&&(e>0||t<0)?new yr(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==o&&(n=(t=qs(t))<0?n.dropRight(-t):n.take(t-e)),n)},yr.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},yr.prototype.toArray=function(){return this.take(B)},Qr(yr.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),i=fr[r?"take"+("last"==t?"Right":""):t],a=r||/^find/.test(t);i&&(fr.prototype[t]=function(){var t=this.__wrapped__,s=r?[1]:arguments,l=t instanceof yr,c=s[0],u=l||ys(t),d=function(e){var t=i.apply(fr,pn([e],s));return r&&h?t[0]:t};u&&n&&"function"==typeof c&&1!=c.length&&(l=u=!1);var h=this.__chain__,p=!!this.__actions__.length,m=a&&!h,g=l&&!p;if(!a&&u){t=g?t:new yr(this);var f=e.apply(t,s);return f.__actions__.push({func:Ha,args:[d],thisArg:o}),new vr(f,h)}return m&&g?e.apply(this,s):(f=this.thru(d),m?r?f.value()[0]:f.value():f)})})),an(["pop","push","shift","sort","splice","unshift"],(function(e){var t=at[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",r=/^(?:pop|shift)$/.test(e);fr.prototype[e]=function(){var e=arguments;if(r&&!this.__chain__){var i=this.value();return t.apply(ys(i)?i:[],e)}return this[n]((function(n){return t.apply(ys(n)?n:[],e)}))}})),Qr(yr.prototype,(function(e,t){var n=fr[t];if(n){var r=n.name+"";dt.call(sr,r)||(sr[r]=[]),sr[r].push({name:t,func:n})}})),sr[_o(o,v).name]=[{name:"wrapper",func:o}],yr.prototype.clone=function(){var e=new yr(this.__wrapped__);return e.__actions__=oo(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=oo(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=oo(this.__views__),e},yr.prototype.reverse=function(){if(this.__filtered__){var e=new yr(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},yr.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=ys(e),r=t<0,i=n?e.length:0,o=function(e,t,n){var r=-1,i=n.length;for(;++r=this.__values__.length;return{done:e,value:e?o:this.__values__[this.__index__++]}},fr.prototype.plant=function(e){for(var t,n=this;n instanceof br;){var r=ga(n);r.__index__=0,r.__values__=o,t?i.__wrapped__=r:t=r;var i=r;n=n.__wrapped__}return i.__wrapped__=e,t},fr.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof yr){var t=e;return this.__actions__.length&&(t=new yr(this)),(t=t.reverse()).__actions__.push({func:Ha,args:[Oa],thisArg:o}),new vr(t,this.__chain__)}return this.thru(Oa)},fr.prototype.toJSON=fr.prototype.valueOf=fr.prototype.value=function(){return qi(this.__wrapped__,this.__actions__)},fr.prototype.first=fr.prototype.head,Ft&&(fr.prototype[Ft]=function(){return this}),fr}();Vt._=Wn,(i=function(){return Wn}.call(t,n,t,r))===o||(r.exports=i)}).call(this)}).call(this,n(14),n(365)(e))},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return M})),n.d(t,"n",(function(){return P})),n.d(t,"p",(function(){return L})),n.d(t,"o",(function(){return U})),n.d(t,"i",(function(){return j})),n.d(t,"j",(function(){return G})),n.d(t,"l",(function(){return z})),n.d(t,"k",(function(){return H})),n.d(t,"q",(function(){return q})),n.d(t,"m",(function(){return V}));var r=n(130),i=n.n(r),o=n(132),a=n.n(o),s=n(13),l=n.n(s),c=n(120),u=n.n(c),d=n(186),h=n.n(d),p=n(126),m=n.n(p),g=n(427),f=n.n(g),_=n(195),b=n(169),v=n(142),y=n(152),E=n(127),S=n(550);n.d(t,"b",(function(){return S.a}));var w=n(328);n.d(t,"c",(function(){return w.a}));var T=n(734);n.d(t,"d",(function(){return T.a}));var C=n(735);n.d(t,"e",(function(){return C.a}));var x=n(445);n.d(t,"f",(function(){return x.a}));var F=n(736);n.d(t,"g",(function(){return F.a}));var D=n(737);n.d(t,"h",(function(){return D.a}));const k=["top","bottom","left","right","bottomAligned","rightAligned","menuClassName","menuHeight","menuWidth","menuPaddingLeft","menuPaddingRight","menuPaddingBottom","menuPaddingTop","zIndex","children","focusLock","managed","wrapperClassName","chevronFace","chevronOffset"],O=["hasBackground","onFinished"];function I(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function A(e){for(var t=1;t{var e,t;null===(e=(t=this.props).onFinished)||void 0===e||e.call(t)})),l()(this,"collectContextMenuRect",(e=>{if(!e)return;const t=e.querySelector('[role^="menuitem"]')||e.querySelector("[tab-index]");t&&t.focus(),this.setState({contextMenuElem:e})})),l()(this,"onContextMenu",(t=>{if(this.props.onFinished){this.props.onFinished(),t.preventDefault(),t.stopPropagation();const n=t.clientX,r=t.clientY;e((()=>{var e;const t=new MouseEvent("contextmenu",{clientX:n,clientY:r,screenX:0,screenY:0,button:0,relatedTarget:null});null===(e=document.elementFromPoint(n,r))||void 0===e||e.dispatchEvent(t)}))}})),l()(this,"onContextMenuPreventBubbling",(e=>{e.stopPropagation()})),l()(this,"onFinished",(e=>{var t,n;e.stopPropagation(),e.preventDefault(),null===(t=(n=this.props).onFinished)||void 0===t||t.call(n)})),l()(this,"onClick",(e=>{var t,n;(e.stopPropagation(),this.props.closeOnInteraction)&&(null===(t=(n=this.props).onFinished)||void 0===t||t.call(n))})),l()(this,"onKeyDown",(e=>{e.stopPropagation();const t=Object(y.a)().getAccessibilityAction(e);this.props.managed?Object(b.g)(e.target)&&t!==v.h.Escape||[v.h.Escape,v.h.Tab,v.h.ArrowLeft,v.h.ArrowRight].includes(t)&&this.props.onFinished():t===v.h.Escape&&this.props.onFinished()})),this.state={},this.initialFocus=document.activeElement}componentDidMount(){E.b.on(E.a.Opened,this.onModalOpen)}componentWillUnmount(){E.b.off(E.a.Opened,this.onModalOpen),this.initialFocus.focus()}renderMenu(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.props.hasBackground;const t={},n=this.props,{top:r,bottom:o,left:s,right:l,bottomAligned:c,rightAligned:d,menuClassName:h,menuHeight:p,menuWidth:g,menuPaddingLeft:v,menuPaddingRight:y,menuPaddingBottom:E,menuPaddingTop:S,zIndex:w,children:T,focusLock:C,managed:x,wrapperClassName:F,chevronFace:D,chevronOffset:I}=n,R=a()(n,k);let N;r?t.top=r:t.bottom=o,s?(t.left=s,N=M.Left):(t.right=l,N=M.Right);const P=this.state.contextMenuElem?this.state.contextMenuElem.getBoundingClientRect():null,L={};D&&(N=D);const B=N&&N!==M.None;N===M.Top||N===M.Bottom?L.left=I:L.top=I;const{windowWidth:U,windowHeight:j}=_.b.instance;if(P){if(void 0!==t.top){let e=j-10;c||(e-=P.height),t.top=Math.min(t.top,e),void 0!==L.top&&(L.top=I+r-t.top)}else void 0!==t.bottom&&(t.bottom=Math.min(t.bottom,j-P.height-10),void 0!==L.top&&(L.top=I+t.bottom-o));if(void 0!==t.left){let e=U-10;d||(e-=P.width),t.left=Math.min(t.left,e),void 0!==L.left&&(L.left=I+s-t.left)}else void 0!==t.right&&(t.right=Math.min(t.right,U-P.width-10),void 0!==L.left&&(L.left=I+t.right-l))}let G;B&&(G=u.a.createElement("div",{style:L,className:"mx_ContextualMenu_chevron_"+N}));const z=m()({mx_ContextualMenu:!0,mx_ContextualMenu_left:!B&&void 0!==t.left&&!t.right,mx_ContextualMenu_right:!B&&void 0!==t.right&&!t.left,mx_ContextualMenu_top:!B&&void 0!==t.top&&!t.bottom,mx_ContextualMenu_bottom:!B&&void 0!==t.bottom&&!t.top,mx_ContextualMenu_withChevron_left:N===M.Left,mx_ContextualMenu_withChevron_right:N===M.Right,mx_ContextualMenu_withChevron_top:N===M.Top,mx_ContextualMenu_withChevron_bottom:N===M.Bottom,mx_ContextualMenu_rightAligned:!0===d,mx_ContextualMenu_bottomAligned:!0===c},h),H={};g&&(H.width=g),p&&(H.height=p),isNaN(Number(S))||(H.paddingTop=S),isNaN(Number(v))||(H.paddingLeft=v),isNaN(Number(E))||(H.paddingBottom=E),isNaN(Number(y))||(H.paddingRight=y);const q={};let V;isNaN(Number(w))||(H.zIndex=w+1,q.zIndex=w),e&&(V=u.a.createElement("div",{className:"mx_ContextualMenu_background",style:q,onClick:this.onFinished,onContextMenu:this.onContextMenu}));let $=u.a.createElement(u.a.Fragment,null,G,T);C&&($=u.a.createElement(f.a,null,$));const{hasBackground:K,onFinished:W}=R,Y=a()(R,O);return u.a.createElement(b.d,{handleHomeEnd:!0,handleUpDown:!0,onKeyDown:this.onKeyDown},(e=>{let{onKeyDownHandler:n}=e;return u.a.createElement("div",{className:m()("mx_ContextualMenu_wrapper",F),style:A(A({},t),q),onClick:this.onClick,onKeyDown:n,onContextMenu:this.onContextMenuPreventBubbling},V,u.a.createElement("div",i()({className:z,style:H,ref:this.collectContextMenuRect,role:x?"menu":void 0},Y),$))}))}render(){return this.props.mountAsChild?this.renderMenu():h.a.createPortal(this.renderMenu(),N())}}l()(P,"defaultProps",{hasBackground:!0,managed:!0});const L=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:12;const n=e.right+window.scrollX+3;let r=e.top+e.height/2+window.scrollY;return r-=t+8,{left:n,top:r,chevronOffset:t}},B=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:12;const n=_.b.instance.windowWidth-e.left+window.scrollX-3;let r=e.top+e.height/2+window.scrollY;return r-=t+8,{right:n,top:r,chevronOffset:t}},U=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:12;return e.left>_.b.instance.windowWidth-e.right?B(e,t):L(e,t)},j=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M.None,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={chevronFace:t},i=e.right+window.scrollX,o=e.bottom+window.scrollY,a=e.top+window.scrollY;return r.right=_.b.instance.windowWidth-i,o<_.b.instance.windowHeight/2?r.top=o+n:r.bottom=_.b.instance.windowHeight-a+n,r},G=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M.None,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={chevronFace:t},i=e.left+window.scrollX,o=e.bottom+window.scrollY,a=e.top+window.scrollY;return r.left=i,o<_.b.instance.windowHeight/2?r.top=o+n:r.bottom=_.b.instance.windowHeight-a+n,r},z=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M.None,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={chevronFace:t},i=e.right+window.scrollX,o=e.top+window.scrollY;return r.right=_.b.instance.windowWidth-i,r.bottom=_.b.instance.windowHeight-o+n,r},H=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M.None,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={chevronFace:t},i=e.left+window.scrollX,o=e.top+window.scrollY;return r.left=i,r.bottom=_.b.instance.windowHeight-o+n,r},q=e=>{let t=Object(c.useRef)(null);e&&(t=e);const[n,r]=Object(c.useState)(!1);return[!!t.current&&n,t,e=>{null==e||e.preventDefault(),null==e||e.stopPropagation(),r(!0)},e=>{null==e||e.preventDefault(),null==e||e.stopPropagation(),r(!1)},r]};function V(e,t){const n=function(){var e;h.a.unmountComponentAtNode(N());for(var n=arguments.length,r=new Array(n),i=0;i1&&void 0!==arguments[1]?arguments[1]:{status:r.NotStarted};super(),this.roomId=e,this.oobMemberFlags=t,o()(this,"reEmitter",new m.b(this)),o()(this,"sentinels",{}),o()(this,"displayNameToUserIds",new Map),o()(this,"userIdsToDisplayNames",{}),o()(this,"tokenToInvite",{}),o()(this,"joinedMemberCount",null),o()(this,"summaryJoinedMemberCount",null),o()(this,"invitedMemberCount",null),o()(this,"summaryInvitedMemberCount",null),o()(this,"modified",-1),o()(this,"members",{}),o()(this,"events",new Map),o()(this,"paginationToken",null),o()(this,"beacons",new Map),o()(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return null!==this.summaryJoinedMemberCount?this.summaryJoinedMemberCount:(null===this.joinedMemberCount&&(this.joinedMemberCount=this.getMembers().reduce(((e,t)=>"join"===t.membership?e+1:e),0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return null!==this.summaryInvitedMemberCount?this.summaryInvitedMemberCount:(null===this.invitedMemberCount&&(this.invitedMemberCount=this.getMembers().reduce(((e,t)=>"invite"===t.membership?e+1:e),0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter((t=>!e.includes(t.userId)))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;let t=this.sentinels[e];if(void 0===t){t=new a.a(this.roomId,e);const n=this.members[e];null!=n&&n.events.member&&t.setMembershipEvent(n.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return void 0===t?[]:null;if(void 0===t)return Array.from(this.events.get(e).values());const n=this.events.get(e).get(t);return n||null}get hasLiveBeacons(){var e;return!(null===(e=this.liveBeaconIds)||void 0===e||!e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new v(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=r.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==r.Finished&&this.getMembers().forEach((t=>{var n;t.isOutOfBand()&&(null===(n=e.getMember(t.userId))||void 0===n||n.markOutOfBand())})),e}setUnknownStateEvents(e){const t=e.filter((e=>!this.events.has(e.getType())||!this.events.get(e.getType()).has(e.getStateKey())));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach((e=>{if(e.getRoomId()!==this.roomId||!e.isState())return;g.b.matches(e.getType())&&this.setBeacon(e);const t=this.getStateEventMatching(e);var n;(this.setStateEvent(e),e.getType()===c.b.RoomMember)&&(this.updateDisplayNameCache(e.getStateKey(),null!==(n=e.getContent().displayname)&&void 0!==n?n:""),this.updateThirdPartyTokenCache(e));this.emit(b.Events,e,this,t)})),this.onBeaconLivenessChange(),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===c.b.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(b.Members,e,this,n)}else if(e.getType()===c.b.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const n=t.getLastModifiedTime();t.setPowerLevelEvent(e),n!==t.getLastModifiedTime()&&this.emit(b.Members,e,this,t)})),this.sentinels={}}else c.m.matches(e.getType())&&this.emit(b.Marker,e,t)})),this.emit(b.Update,this)}processBeaconEvents(e,t){if(!e.length||!this.beacons.size)return;const n=[...this.beacons.values()].reduce(((e,t)=>_(_({},e),{},{[t.beaconInfoId]:t})),{}),r=(e,t)=>{if(!g.a.matches(t.getType()))return;const r=n[e];r&&r.addLocations([t])};e.forEach((e=>{var i;const o=null===(i=e.getRelation())||void 0===i?void 0:i.event_id;o&&n[o]&&(t.decryptEventIfNeeded(e),e.isBeingDecrypted()||e.isDecryptionFailure()?e.once(u.c.Decrypted,(async()=>{r(o,e)})):r(o,e))}))}getOrCreateMember(e,t){let n=this.members[e];return n||(n=new a.a(this.roomId,e),this.members[e]=n,this.emit(b.NewMember,t,this,n)),n}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){const t=Object(p.c)(e);if(this.beacons.has(t)){const r=this.beacons.get(t);var n;return e.isRedacted()?void(r.beaconInfoId===(null===(n=e.getRedactionEvent())||void 0===n?void 0:n.redacts)&&(r.destroy(),this.beacons.delete(t))):r.update(e)}if(e.isRedacted())return;const r=new p.a(e);this.reEmitter.reEmit(r,[p.b.New,p.b.Update,p.b.Destroy,p.b.LivenessChange]),this.emit(p.b.New,e,r),r.on(p.b.LivenessChange,this.onBeaconLivenessChange.bind(this)),r.on(p.b.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(r.identifier,r)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter((e=>e.isLive)).map((e=>e.identifier)),this.emit(b.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,n;return null!==(t=null===(n=this.events.get(e.getType()))||void 0===n?void 0:n.get(e.getStateKey()))&&void 0!==t?t:null}updateMember(e){const t=this.getStateEvents(c.b.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===r.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===r.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===r.NotStarted&&(this.oobMemberFlags.status=r.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===r.InProgress&&(this.oobMemberFlags.status=r.NotStarted)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach((t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])})),s.a.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=r.NotStarted}setOutOfBandMembers(e){s.a.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===r.InProgress&&(s.a.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=r.Finished,e.forEach((e=>this.setOutOfBandMember(e))),this.emit(b.Update,this))}setOutOfBandMember(e){if(e.getType()!==c.b.RoomMember)return;const t=e.getStateKey(),n=this.getMember(t);if(n&&!n.isOutOfBand())return;const r=this.getOrCreateMember(t,e);r.setMembershipEvent(e,this),r.markOutOfBand(),this.updateDisplayNameCache(r.userId,r.name),this.setStateEvent(e),this.updateMember(r),this.emit(b.Members,e,this,r)}setTypingEvent(e){Object.values(this.members).forEach((function(t){t.setTypingEvent(e)}))}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return null!==(t=this.displayNameToUserIds.get(l.J(e)))&&void 0!==t?t:[]}maySendRedactionForEvent(e,t){const n=this.getMember(t);if(!n||"leave"===n.membership)return!1;if(e.status||e.isRedacted())return!1;const r=this.maySendEvent(c.b.RoomRedaction,t);return e.getSender()===t?r:this.hasSufficientPowerLevelFor("redact",n.powerLevel)}hasSufficientPowerLevelFor(e,t){const n=this.getStateEvents(c.b.RoomPowerLevels,"");let r={};n&&(r=n.getContent());let i=50;return l.v(r[e])&&(i=r[e]),t>=i}maySendMessage(e){return this.maySendEventOfType(c.b.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!(t.isGuest()||!t.credentials.userId)&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){const r=this.getStateEvents(c.b.RoomPowerLevels,"");let i,o={},a=0,s=0,l=0;if(r){i=r.getContent(),o=i.events||{},a=Number.isSafeInteger(i.state_default)?i.state_default:50;const e=i.users&&i.users[t];Number.isSafeInteger(e)?l=e:Number.isSafeInteger(i.users_default)&&(l=i.users_default),Number.isSafeInteger(i.events_default)&&(s=i.events_default)}let u=n?a:s;return Number.isSafeInteger(o[e])&&(u=o[e]),l>=u}mayTriggerNotifOfType(e,t){const n=this.getMember(t);if(!n)return!1;const r=this.getStateEvents(c.b.RoomPowerLevels,"");let i=50;return r&&r.getContent()&&r.getContent().notifications&&l.v(r.getContent().notifications[e])&&(i=r.getContent().notifications[e]),n.powerLevel>=i}getJoinRule(){var e;const t=this.getStateEvents(c.b.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||d.c.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(c.b.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||d.b.Shared}getGuestAccess(){var e;const t=this.getStateEvents(c.b.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||d.a.Forbidden}findPredecessor(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]){const e=this.getStateEvents(c.b.RoomPredecessor,"");if(e){const t=e.getContent(),n=t.predecessor_room_id;let r=t.last_known_event_id;if("string"!=typeof r&&(r=void 0),"string"==typeof n)return{roomId:n,eventId:r}}}const e=this.getStateEvents(c.b.RoomCreate,"");if(e){const t=e.getContent().predecessor;if(t){const e=t.room_id;if("string"==typeof e){let n=t.event_id;return"string"==typeof n&&""!==n||(n=void 0),{roomId:e,eventId:n}}}}return null}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;if(!t)return;this.getStateEvents(c.b.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=l.J(n),r=this.displayNameToUserIds.get(t);if(r){const n=r.filter((t=>t!==e));this.displayNameToUserIds.set(t,n)}}this.userIdsToDisplayNames[e]=t;const r=t&&l.J(t);if(r){var i;const t=null!==(i=this.displayNameToUserIds.get(r))&&void 0!==i?i:[];t.push(e),this.displayNameToUserIds.set(r,t)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r=n(13),i=n.n(r),o=n(205),a=n(125),s=n(131),l=n(142),c=n(677);const u=e=>l.b[e].settingNames.reduce(((e,t)=>{var n;const r=null===(n=Object(c.c)()[t])||void 0===n?void 0:n.default;return r&&e.push({action:t,keyCombo:r}),e}),[]),d={getMessageComposerBindings:()=>{const e=u(l.c.COMPOSER);return a.b.getValue("MessageComposerInput.ctrlEnterToSend")?(e.push({action:l.h.SendMessage,keyCombo:{key:o.b.ENTER,ctrlOrCmdKey:!0}}),e.push({action:l.h.NewLine,keyCombo:{key:o.b.ENTER}}),e.push({action:l.h.NewLine,keyCombo:{key:o.b.ENTER,shiftKey:!0}})):(e.push({action:l.h.SendMessage,keyCombo:{key:o.b.ENTER}}),e.push({action:l.h.NewLine,keyCombo:{key:o.b.ENTER,shiftKey:!0}}),o.a&&e.push({action:l.h.NewLine,keyCombo:{key:o.b.ENTER,altKey:!0}})),e},getAutocompleteBindings:()=>{const e=u(l.c.AUTOCOMPLETE);return e.push({action:l.h.ForceCompleteAutocomplete,keyCombo:{key:o.b.TAB}}),e.push({action:l.h.ForceCompleteAutocomplete,keyCombo:{key:o.b.TAB,ctrlKey:!0}}),e.push({action:l.h.CompleteAutocomplete,keyCombo:{key:o.b.ENTER}}),e.push({action:l.h.CompleteAutocomplete,keyCombo:{key:o.b.ENTER,ctrlKey:!0}}),e},getRoomListBindings:()=>u(l.c.ROOM_LIST),getRoomBindings:()=>{const e=u(l.c.ROOM);return a.b.getValue("ctrlFForSearch")&&e.push({action:l.h.SearchInRoom,keyCombo:{key:o.b.F,ctrlOrCmdKey:!0}}),e},getNavigationBindings:()=>u(l.c.NAVIGATION),getAccessibilityBindings:()=>u(l.c.ACCESSIBILITY),getCallBindings:()=>u(l.c.CALLS),getLabsBindings:()=>s.b.get("show_labs_settings")?u(l.c.LABS):[]};function h(e,t,n){var r,i,o,a,s,l,c,u;if(void 0!==t.key)if(e.shiftKey){if(e.key.toLowerCase()!==t.key.toLowerCase())return!1}else if(e.key!==t.key)return!1;const d=null!==(r=t.ctrlKey)&&void 0!==r&&r,h=null!==(i=t.altKey)&&void 0!==i&&i,p=null!==(o=t.shiftKey)&&void 0!==o&&o,m=null!==(a=t.metaKey)&&void 0!==a&&a,g=null!==(s=e.ctrlKey)&&void 0!==s&&s,f=null!==(l=e.altKey)&&void 0!==l&&l,_=null!==(c=e.shiftKey)&&void 0!==c&&c,b=null!==(u=e.metaKey)&&void 0!==u&&u;if(t.ctrlOrCmdKey){if(n){if(!b||g!==d||f!==h||_!==p)return!1}else if(!g||b!==m||f!==h||_!==p)return!1;return!0}return b===m&&g===d&&f===h&&_===p}const p=new class{constructor(){i()(this,"bindingsProviders",[d])}getAction(e,t){for(const n of e){const e=n().find((e=>h(t,e.keyCombo,o.a)));if(e)return e.action}}getMessageComposerAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getMessageComposerBindings)),e)}getAutocompleteAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getAutocompleteBindings)),e)}getRoomListAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getRoomListBindings)),e)}getRoomAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getRoomBindings)),e)}getNavigationAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getNavigationBindings)),e)}getAccessibilityAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getAccessibilityBindings)),e)}getCallAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getCallBindings)),e)}getLabsAction(e){return this.getAction(this.bindingsProviders.map((e=>e.getLabsBindings)),e)}};function m(){return p}},function(e,t,n){"use strict";n.d(t,"b",(function(){return l})),n.d(t,"a",(function(){return c}));var r=n(13),i=n.n(r),o=n(17),a=n(1340),s=n.n(a);const l="update";class c extends o.EventEmitter{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.dispatcher=e,i()(this,"storeState",void 0),i()(this,"lock",new s.a),i()(this,"dispatcherRef",void 0),this.dispatcherRef=e.register(this.onDispatch.bind(this)),this.storeState=t}get state(){return this.storeState}stop(){this.dispatcherRef&&this.dispatcher.unregister(this.dispatcherRef)}async updateState(e){await this.lock.acquireAsync();try{this.storeState=Object.freeze(Object.assign({},this.storeState,e)),this.emit(l,this)}finally{await this.lock.release()}}async reset(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];await this.lock.acquireAsync();try{this.storeState=Object.freeze(e||{}),t||this.emit(l,this)}finally{await this.lock.release()}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return Y})),n.d(t,"b",(function(){return Q}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(124),l=n(183),c=n(189),u=n(523);class d{constructor(){i()(this,"password",void 0),i()(this,"passwordTimeoutId",void 0),i()(this,"clearPassword",(()=>{clearTimeout(this.passwordTimeoutId),this.passwordTimeoutId=void 0,this.password=void 0}))}setPassword(e){this.password=e,clearTimeout(this.passwordTimeoutId),this.passwordTimeoutId=setTimeout(this.clearPassword,3e5)}getPassword(){return this.password}}var h=n(125),p=n(131);const m=/[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+/g;class g{constructor(e){this.stores=e,i()(this,"sortNames",new Map),i()(this,"loadedRooms",new Set),i()(this,"collator",void 0)}async loadMemberList(e,t){if(!this.stores.client)return{joined:[],invited:[]};const n=h.b.getValue("language");this.collator=new Intl.Collator(n,{sensitivity:"base",ignorePunctuation:!1});const r=await this.loadMembers(e),i=this.filterMembers(r,t);return i.joined.sort(((e,t)=>this.sortMembers(e,t))),i.invited.sort(((e,t)=>this.sortMembers(e,t))),{joined:i.joined,invited:i.invited}}async loadMembers(e){const t=this.stores.client.getRoom(e);if(!t)return[];if(!this.isLazyLoadingEnabled(e)||this.loadedRooms.has(e))return this.loadMembersInRoom(t);if(this.isLazyMemberStorageEnabled())try{await t.loadMembersIfNeeded()}catch(e){}else{t.currentState.markOutOfBandMembersStarted();const n=(await this.stores.client.members(e,void 0,"leave")).chunk.map(this.stores.client.getEventMapper());t.currentState.setOutOfBandMembers(n)}return this.loadedRooms.add(e),this.loadMembersInRoom(t)}loadMembersInRoom(e){const t=Object.values(e.currentState.members);return t.forEach((e=>{e.user||(e.user=this.stores.client.getUser(e.userId)||void 0)})),t}isLazyLoadingEnabled(e){return h.b.getValue("feature_sliding_sync")?!this.stores.client.isRoomEncrypted(e):this.stores.client.hasLazyLoadMembersEnabled()}isLazyMemberStorageEnabled(){return!h.b.getValue("feature_sliding_sync")&&this.stores.client.hasLazyLoadMembersEnabled()}isPresenceEnabled(){var e;if(!this.stores.client)return!0;const t=p.b.get("enable_presence_by_hs_url");return null===(e=null==t?void 0:t[this.stores.client.baseUrl])||void 0===e||e}filterMembers(e,t){const n={joined:[],invited:[]};return e.forEach((e=>{if("join"===e.membership||"invite"===e.membership){if(t){t=t.toLowerCase();const n=e.name.toLowerCase().includes(t),r=e.userId.toLowerCase().includes(t);if(!n&&!r)return}switch(e.membership){case"join":n.joined.push(e);break;case"invite":n.invited.push(e)}}})),n}sortMembers(e,t){const n=e.user,r=t.user;if(!n&&!r)return 0;if(n&&!r)return-1;if(!n&&r)return 1;const i=this.isPresenceEnabled();if(i){const e=e=>"unavailable"===e?"online":e,t=t=>{const n=["active","online","offline"],r=n.indexOf(e(t));return-1===r?n.length:r},i=t(n.currentlyActive?"active":n.presence),o=t(r.currentlyActive?"active":r.presence);if(i!==o)return i-o}return e.powerLevel!==t.powerLevel?t.powerLevel-e.powerLevel:i&&n.getLastActiveTs()!==r.getLastActiveTs()?r.getLastActiveTs()-n.getLastActiveTs():this.collator.compare(this.canonicalisedName(e.name),this.canonicalisedName(t.name))}canonicalisedName(e){let t=this.sortNames.get(e);return t||(t=("@"===e[0]?e.slice(1):e).replace(m,""),this.sortNames.set(e,t),t)}}var f=n(220),_=n(173),b=n(16),v=n(1),y=n(160),E=n(17),S=n.n(E),w=n(122),T=n(127),C=n(121),x=n(389),F=n(128),D=n(390),k=n(138),O=n(164),I=n(208),A=n(144),R=n(391),N=n(153),M=n(306),P=n(192),L=n(800);function B(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function U(e){for(var t=1;t{if(null===e){var t;const e=null===(t=this.stores.client)||void 0===t?void 0:t.getRoom(this.state.roomId||void 0);e&&this.doMaybeSetCurrentVoiceBroadcastPlayback(e)}})),this.resetDispatcher(e),this.stores.voiceBroadcastRecordingsStore.addListener(P.y.CurrentChanged,this.onCurrentBroadcastRecordingChanged)}addRoomListener(e,t){this.on(e,t)}removeRoomListener(e,t){this.off(e,t)}emitForRoom(e,t){this.emit(e,t)}setState(e){let t=!1;for(const n of Object.keys(e))if(this.state[n]!==e[n]){t=!0;break}if(!t)return;var n;e.viewingCall&&(null===(n=this.stores.voiceBroadcastPlaybacksStore.getCurrent())||void 0===n||n.pause(),this.stores.voiceBroadcastRecordingsStore.getCurrent()&&(Object(L.a)(),e.viewingCall=!1));const r=this.state.roomId;this.state=Object.assign(this.state,e),r!==this.state.roomId&&(r&&this.emitForRoom(r,!1),this.state.roomId&&this.emitForRoom(this.state.roomId,!0),this.dis.dispatch({action:F.a.ActiveRoomChanged,oldRoomId:r,newRoomId:this.state.roomId})),this.emit(N.b)}doMaybeSetCurrentVoiceBroadcastPlayback(e){Object(P.G)(e,this.stores.client,this.stores.voiceBroadcastPlaybacksStore,this.stores.voiceBroadcastRecordingsStore)}onRoomStateEvents(e){var t,n;const r=null===(t=e.getRoomId)||void 0===t?void 0:t.call(e);if(!r||r!==this.state.roomId)return;const i=null===(n=this.stores.client)||void 0===n?void 0:n.getRoom(r);i&&this.doMaybeSetCurrentVoiceBroadcastPlayback(i)}onDispatch(e){switch(e.action){case F.a.ViewRoom:this.viewRoom(e);break;case F.a.ViewThread:this.viewThread(e);break;case"view_welcome_page":case F.a.ViewHomePage:this.setState({roomId:null,roomAlias:null,viaServers:[],wasContextSwitch:!1,viewingCall:!1}),Object(P.F)(this.stores.voiceBroadcastPlaybacksStore);break;case"MatrixActions.RoomState.events":this.onRoomStateEvents(e.event);break;case F.a.ViewRoomError:this.viewRoomError(e);break;case"will_join":this.setState({joining:!0});break;case"cancel_join":this.setState({joining:!1});break;case F.a.JoinRoom:this.joinRoom(e);break;case F.a.JoinRoomError:this.joinRoomError(e);break;case F.a.JoinRoomReady:this.state.roomId===e.roomId&&this.setState({shouldPeek:!1}),Object(R.a)(w.a.get(),e.roomId).then((t=>{const n=t.getJoinedMemberCount(),r=n>1e3?"MoreThanAThousand":n>100?"OneHundredAndOneToAThousand":n>10?"ElevenToOneHundred":n>2?"ThreeToTen":n>1?"Two":"One";this.stores.posthogAnalytics.trackEvent({eventName:"JoinedRoom",trigger:e.metricsTrigger,roomSize:r,isDM:!!O.a.shared().getUserIdForRoomId(t.roomId),isSpace:t.isSpaceRoom()})}));break;case"on_client_not_viable":case F.a.OnLoggedOut:this.reset();break;case"reply_to_event":k.a.Thread!==e.context&&(e.event&&e.event.getRoomId()!==this.state.roomId?this.dis.dispatch({action:F.a.ViewRoom,room_id:e.event.getRoomId(),replyingToEvent:e.event,metricsTrigger:void 0}):this.setState({replyingToEvent:e.event}))}}async viewRoom(e){if(e.room_id){var t,n,r,i,o,a,s,l,c;const p=w.a.get().getRoom(e.room_id);if(null!==e.metricsTrigger&&e.room_id!==this.state.roomId){let t;if(this.stores.spaceStore.activeSpace===I.a.Home)t="Home";else if(Object(I.h)(this.stores.spaceStore.activeSpace))t="Meta";else{var u;t=(null===(u=this.stores.spaceStore.activeSpaceRoom)||void 0===u?void 0:u.getJoinRule())===y.c.Public?"Public":"Private"}this.stores.posthogAnalytics.trackEvent({eventName:"ViewRoom",trigger:e.metricsTrigger,viaKeyboard:e.metricsViaKeyboard,isDM:!!O.a.shared().getUserIdForRoomId(e.room_id),isSpace:null==p?void 0:p.isSpaceRoom(),activeSpace:t})}var d;if(h.b.getValue("feature_sliding_sync")&&this.state.roomId!==e.room_id)return this.state.subscribingRoomId&&this.state.subscribingRoomId!==e.room_id&&this.stores.slidingSyncManager.setRoomVisible(this.state.subscribingRoomId,!1),this.setState({subscribingRoomId:e.room_id,roomId:e.room_id,initialEventId:null,initialEventPixelOffset:null,isInitialEventHighlighted:null,initialEventScrollIntoView:!0,roomAlias:null,roomLoading:!0,roomLoadError:null,viaServers:e.via_servers,wasContextSwitch:e.context_switch,viewingCall:null!==(d=e.view_call)&&void 0!==d&&d}),await this.stores.slidingSyncManager.setRoomVisible(e.room_id,!0),this.state.subscribingRoomId!==e.room_id?void this.stores.slidingSyncManager.setRoomVisible(e.room_id,!1):void this.dis.dispatch(U({},e));const m={roomId:e.room_id,roomAlias:null!==(t=e.room_alias)&&void 0!==t?t:null,initialEventId:null!==(n=e.event_id)&&void 0!==n?n:null,isInitialEventHighlighted:null!==(r=e.highlighted)&&void 0!==r&&r,initialEventScrollIntoView:null===(i=e.scroll_into_view)||void 0===i||i,roomLoading:!1,roomLoadError:null,shouldPeek:void 0===e.should_peek||e.should_peek,joining:e.joining||!1,replyingToEvent:null,viaServers:null!==(o=e.via_servers)&&void 0!==o?o:[],wasContextSwitch:null!==(a=e.context_switch)&&void 0!==a&&a,viewingCall:null!==(s=e.view_call)&&void 0!==s?s:e.room_id===this.state.roomId?this.state.viewingCall:null!==M.a.instance.getActiveCall(e.room_id)};(null===(l=e.replyingToEvent)||void 0===l?void 0:l.getRoomId())===e.room_id?m.replyingToEvent=e.replyingToEvent:(null===(c=this.state.replyingToEvent)||void 0===c?void 0:c.getRoomId())===e.room_id&&(m.replyingToEvent=this.state.replyingToEvent),this.setState(m),e.auto_join&&this.dis.dispatch(U(U({},e),{},{action:F.a.JoinRoom,roomId:e.room_id,metricsTrigger:e.metricsTrigger})),p&&(((e,t)=>{const n=t.getCurrent();n&&"live"!==(null==n?void 0:n.getLiveness())&&(null==n?void 0:n.infoEvent.getRoomId())!==e.roomId&&(t.clearCurrent(),n.pause())})(p,this.stores.voiceBroadcastPlaybacksStore),this.doMaybeSetCurrentVoiceBroadcastPlayback(p))}else if(e.room_alias){let t=Object(x.a)(e.room_alias);if(!t){var p;this.setState({roomId:null,initialEventId:null,initialEventPixelOffset:null,isInitialEventHighlighted:!1,initialEventScrollIntoView:!0,roomAlias:e.room_alias,roomLoading:!0,roomLoadError:null,viaServers:e.via_servers,wasContextSwitch:e.context_switch,viewingCall:null!==(p=e.view_call)&&void 0!==p&&p});try{const n=await w.a.get().getRoomIdForAlias(e.room_alias);Object(x.b)(e.room_alias,n.room_id),t=n.room_id}catch(t){return v.a.error("RVS failed to get room id for alias: ",t),void this.dis.dispatch({action:F.a.ViewRoomError,room_id:null,room_alias:e.room_alias,err:t})}}this.dis.dispatch(U(U({},e),{},{room_id:t}))}}viewThread(e){this.setState({threadId:e.thread_id})}viewRoomError(e){this.setState({roomId:e.room_id,roomAlias:e.room_alias,roomLoading:!1,roomLoadError:e.err})}async joinRoom(e){this.setState({joining:!0});const t=w.a.get(),{roomAlias:n,roomId:r}=this.state,i=n||r,o=this.state.viaServers||[];try{await Object(D.a)((()=>t.joinRoom(i,U({viaServers:o},e.opts||{}))),5,(e=>504===e.httpStatus)),this.dis.dispatch({action:F.a.JoinRoomReady,roomId:r,metricsTrigger:e.metricsTrigger})}catch(e){this.dis.dispatch({action:F.a.JoinRoomError,roomId:r,err:e})}}getInvitingUserId(e){const t=w.a.get(),n=t.getRoom(e);if("invite"===(null==n?void 0:n.getMyMembership())){const e=n.getMember(t.getUserId()),r=e?e.events.member:null;return r&&r.getSender()}}showJoinRoomError(e,t){let n=e.message?e.message:JSON.stringify(e);if(v.a.log("Failed to join room:",n),"ConnectionError"===e.name)n=Object(C.a)("There was an error joining.");else if("M_INCOMPATIBLE_ROOM_VERSION"===e.errcode)n=a.a.createElement("div",null,Object(C.a)("Sorry, your homeserver is too old to participate here."),a.a.createElement("br",null),Object(C.a)("Please contact your homeserver administrator."));else if(404===e.httpStatus){const e=this.getInvitingUserId(t);e&&(n=e.endsWith(`:${w.a.get().getDomain()}`)?Object(C.a)("The person who invited you has already left."):Object(C.a)("The person who invited you has already left, or their server is offline.")),t===this.state.roomId&&0===this.state.viaServers.length&&(n=a.a.createElement("div",null,Object(C.a)("You attempted to join using a room ID without providing a list of servers to join through. Room IDs are internal identifiers and cannot be used to join a room without additional information."),a.a.createElement("br",null),a.a.createElement("br",null),Object(C.a)("If you know a room address, try joining through that instead.")))}T.b.createDialog(A.a,{title:Object(C.a)("Failed to join"),description:n})}joinRoomError(e){this.setState({joining:!1,joinError:e.err}),e.err&&this.showJoinRoomError(e.err,e.roomId)}reset(){this.state=Object.assign({},j)}resetDispatcher(e){this.dispatchToken&&this.dis.unregister(this.dispatchToken),this.dis=e,e&&(this.dispatchToken=this.dis.register(this.onDispatch.bind(this)))}getRoomId(){return this.state.roomId}getThreadId(){return this.state.threadId}getInitialEventId(){return this.state.initialEventId}isInitialEventHighlighted(){return this.state.isInitialEventHighlighted}initialEventScrollIntoView(){return this.state.initialEventScrollIntoView}getRoomAlias(){return this.state.roomAlias}isRoomLoading(){return this.state.roomLoading}getRoomLoadError(){return this.state.roomLoadError}isJoining(){return this.state.joining}getJoinError(){return this.state.joinError}getQuotingEvent(){return this.state.replyingToEvent}shouldPeek(){return this.state.shouldPeek}getWasContextSwitch(){return this.state.wasContextSwitch}isViewingCall(){return this.state.viewingCall}}var z=n(178),H=n(217),q=n(329);class V{constructor(e){this.context=e,i()(this,"typingStates",void 0),this.reset()}reset(){this.typingStates={}}setSelfTyping(e,t,n){var r;if(Object(H.a)(e))return;if(!h.b.getValue("sendTypingNotifications"))return;if(h.b.getValue("lowBandwidth"))return;if(t)return;let i=this.typingStates[e];!n&&!i||i&&i.isTyping===n||(i||(i=this.typingStates[e]={isTyping:n,serverTimer:new q.a(3e4),userTimer:new q.a(1e4)}),i.isTyping=n,n&&(i.serverTimer.isRunning()?i.serverTimer.restart():i.serverTimer.restart().finished().then((()=>{const t=this.typingStates[e];t&&(t.isTyping=!1)})),i.userTimer.isRunning()?i.userTimer.restart():i.userTimer.restart().finished().then((()=>{this.setSelfTyping(e,t,!1)}))),null===(r=this.context.client)||void 0===r||r.sendTyping(e,n,3e4))}}var $=n(207),K=n(587),W=n(234);const Y=Object(o.createContext)(void 0);Y.displayName="SDKContext";class Q{constructor(){i()(this,"client",void 0),i()(this,"_WidgetPermissionStore",void 0),i()(this,"_MemberListStore",void 0),i()(this,"_RightPanelStore",void 0),i()(this,"_RoomNotificationStateStore",void 0),i()(this,"_RoomViewStore",void 0),i()(this,"_WidgetLayoutStore",void 0),i()(this,"_WidgetStore",void 0),i()(this,"_PosthogAnalytics",void 0),i()(this,"_SlidingSyncManager",void 0),i()(this,"_SpaceStore",void 0),i()(this,"_LegacyCallHandler",void 0),i()(this,"_TypingStore",void 0),i()(this,"_VoiceBroadcastRecordingsStore",void 0),i()(this,"_VoiceBroadcastPreRecordingStore",void 0),i()(this,"_VoiceBroadcastPlaybacksStore",void 0),i()(this,"_AccountPasswordStore",void 0)}constructEagerStores(){this._RoomViewStore=this.roomViewStore}get legacyCallHandler(){return this._LegacyCallHandler||(this._LegacyCallHandler=l.b.instance),this._LegacyCallHandler}get rightPanelStore(){return this._RightPanelStore||(this._RightPanelStore=_.a.instance),this._RightPanelStore}get roomNotificationStateStore(){return this._RoomNotificationStateStore||(this._RoomNotificationStateStore=f.a.instance),this._RoomNotificationStateStore}get roomViewStore(){return this._RoomViewStore||(this._RoomViewStore=new G(s.a,this)),this._RoomViewStore}get widgetLayoutStore(){return this._WidgetLayoutStore||(this._WidgetLayoutStore=$.d.instance),this._WidgetLayoutStore}get widgetPermissionStore(){return this._WidgetPermissionStore||(this._WidgetPermissionStore=new K.b(this)),this._WidgetPermissionStore}get widgetStore(){return this._WidgetStore||(this._WidgetStore=W.a.instance),this._WidgetStore}get posthogAnalytics(){return this._PosthogAnalytics||(this._PosthogAnalytics=c.a.instance),this._PosthogAnalytics}get memberListStore(){return this._MemberListStore||(this._MemberListStore=new g(this)),this._MemberListStore}get slidingSyncManager(){return this._SlidingSyncManager||(this._SlidingSyncManager=u.a.instance),this._SlidingSyncManager}get spaceStore(){return this._SpaceStore||(this._SpaceStore=z.a.instance),this._SpaceStore}get typingStore(){return this._TypingStore||(this._TypingStore=new V(this),window.mxTypingStore=this._TypingStore),this._TypingStore}get voiceBroadcastRecordingsStore(){return this._VoiceBroadcastRecordingsStore||(this._VoiceBroadcastRecordingsStore=new P.x),this._VoiceBroadcastRecordingsStore}get voiceBroadcastPreRecordingStore(){return this._VoiceBroadcastPreRecordingStore||(this._VoiceBroadcastPreRecordingStore=new P.q),this._VoiceBroadcastPreRecordingStore}get voiceBroadcastPlaybacksStore(){return this._VoiceBroadcastPlaybacksStore||(this._VoiceBroadcastPlaybacksStore=new P.n(this.voiceBroadcastRecordingsStore)),this._VoiceBroadcastPlaybacksStore}get accountPasswordStore(){return this._AccountPasswordStore||(this._AccountPasswordStore=new d),this._AccountPasswordStore}}i()(Q,"instance",new Q)},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(126),l=n.n(s),c=n(121),u=n(135),d=n(145);class h extends a.a.Component{constructor(){super(...arguments),i()(this,"onOk",(()=>{this.props.onFinished(!0)})),i()(this,"onCancel",(()=>{this.props.onFinished(!1)}))}render(){let e="";return this.props.danger&&(e="danger"),a.a.createElement(u.a,{className:l()("mx_QuestionDialog",this.props.className),onFinished:this.props.onFinished,title:this.props.title,contentId:"mx_Dialog_content",headerImage:this.props.headerImage,hasCancel:this.props.hasCancelButton,fixedWidth:this.props.fixedWidth},a.a.createElement("div",{className:"mx_Dialog_content",id:"mx_Dialog_content"},this.props.description),a.a.createElement(d.a,{primaryButton:this.props.button||Object(c.a)("OK"),primaryButtonClass:e,primaryDisabled:this.props.buttonDisabled,cancelButton:this.props.cancelButton,hasCancel:this.props.hasCancelButton&&!this.props.quitOnly,onPrimaryButtonClick:this.onOk,focus:this.props.focus,onCancel:this.onCancel},this.props.extraButtons))}}i()(h,"defaultProps",{title:"",description:"",extraButtons:null,focus:!0,hasCancelButton:!0,danger:!1,quitOnly:!1})},function(e,t,n){"use strict";let r,i;n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return i})),function(e){e.AdvancedEncryption="UIFeature.advancedEncryption",e.URLPreviews="UIFeature.urlPreviews",e.Widgets="UIFeature.widgets",e.Voip="UIFeature.voip",e.Feedback="UIFeature.feedback",e.Registration="UIFeature.registration",e.PasswordReset="UIFeature.passwordReset",e.Deactivate="UIFeature.deactivate",e.ShareQRCode="UIFeature.shareQrCode",e.ShareSocial="UIFeature.shareSocial",e.IdentityServer="UIFeature.identityServer",e.ThirdPartyID="UIFeature.thirdPartyId",e.AdvancedSettings="UIFeature.advancedSettings",e.RoomHistorySettings="UIFeature.roomHistorySettings",e.TimelineEnableRelativeDates="UIFeature.timelineEnableRelativeDates",e.BulkUnverifiedSessionsReminder="UIFeature.BulkUnverifiedSessionsReminder"}(r||(r={})),function(e){e.InviteUsers="UIComponent.sendInvites",e.CreateRooms="UIComponent.roomCreation",e.CreateSpaces="UIComponent.spaceCreation",e.ExploreRooms="UIComponent.exploreRooms",e.AddIntegrations="UIComponent.addIntegrations"}(i||(i={}))},function(e,t,n){"use strict";var r=n(13),i=n.n(r),o=n(124),a=n(128);class s{constructor(){i()(this,"platform",null)}get(){return this.platform}set(e){this.platform=e,o.a.dispatch({action:a.a.PlatformSet,platform:e})}}window.mxPlatformPeg||(window.mxPlatformPeg=new s),t.a=window.mxPlatformPeg},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return o}));var r=n(17);let i;!function(e){e.NewListener="newListener",e.RemoveListener="removeListener",e.Error="error"}(i||(i={}));class o extends r.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{if(!this.props.visible||!this.parent)return;const e=this.parent.getBoundingClientRect(),t=d.b.instance.windowWidth,n=this.props.maxParentWidth?Math.min(e.width,this.props.maxParentWidth):e.width,r=e.top+window.scrollY,i=e.top+window.scrollY+e.height/2,o=t-e.left-window.scrollX,a=e.right+window.scrollX,s=e.left-window.scrollX+n/2,l={};switch(this.props.alignment){case m.Natural:if(e.right>t/2){l.right=o+6,l.top=i,l.transform="translateY(-50%)";break}case m.Right:l.left=a+6,l.top=i,l.transform="translateY(-50%)";break;case m.Left:l.right=o+6,l.top=i,l.transform="translateY(-50%)";break;case m.Top:l.top=r-6,l.transform=`translate(max(10px, min(calc(${s}px - 50%), calc(100vw - 100% - 10px))), -100%)`;break;case m.Bottom:l.top=r+e.height+6,l.transform=`translate(max(10px, min(calc(${s}px - 50%), calc(100vw - 100% - 10px))))`;break;case m.InnerBottom:l.top=r+e.height-50,l.transform=`translate(max(10px, min(calc(${s}px - 50%), calc(100vw - 100% - 10px))))`;break;case m.TopRight:l.top=r-6,l.right=t-e.right-window.scrollX,l.transform="translateY(-100%)"}this.setState(l)})),this.state={},g.container||(g.container=document.createElement("div"),g.container.className="mx_Tooltip_wrapper",document.body.appendChild(g.container))}componentDidMount(){var e,t;window.addEventListener("scroll",this.updatePosition,{passive:!0,capture:!0}),this.parent=null!==(e=null===(t=l.a.findDOMNode(this))||void 0===t?void 0:t.parentNode)&&void 0!==e?e:null,this.updatePosition()}componentDidUpdate(e){Object(h.c)(e,this.props)&&this.updatePosition()}componentWillUnmount(){window.removeEventListener("scroll",this.updatePosition,{capture:!0})}render(){const e=u()("mx_Tooltip",this.props.tooltipClassName,{mx_Tooltip_visible:this.props.visible,mx_Tooltip_invisible:!this.props.visible}),t=function(e){for(var t=1;t{var t;e.getRoomId()===(null===(t=this.props.room)||void 0===t?void 0:t.roomId)&&e.getType()===m.b.RoomAvatar&&this.setState({urls:C.getImageUrls(this.props)})})),l()(this,"onRoomAvatarClick",(()=>{var e,t;const n={src:v.b(null!==(e=this.props.room)&&void 0!==e?e:null,void 0,void 0,void 0),name:null===(t=this.props.room)||void 0===t?void 0:t.name};b.b.createDialog(f.a,n,"mx_Dialog_lightbox",void 0,!0)})),this.state={urls:C.getImageUrls(this.props)}}componentDidMount(){_.a.get().on(d.b.Events,this.onRoomStateEvents)}componentWillUnmount(){var e;null===(e=_.a.get())||void 0===e||e.removeListener(d.b.Events,this.onRoomStateEvents)}static getDerivedStateFromProps(e){return{urls:C.getImageUrls(e)}}static getImageUrls(e){let t=null;return e.oobData.avatarUrl&&(t=Object(E.b)(e.oobData.avatarUrl).getThumbnailOfSourceHttp(e.width,e.height,e.resizeMethod)),Object(w.n)([t,C.getRoomAvatarUrl(e)])}static getRoomAvatarUrl(e){return e.room?v.b(e.room,e.width,e.height,e.resizeMethod):null}get roomIdName(){var e,t;const n=this.props.room;if(n){const e=y.a.shared().getUserIdForRoomId(n.roomId);if(e)return e;if(n instanceof S.b&&1===n.targets.length)return n.targets[0].userId}return(null===(e=this.props.room)||void 0===e?void 0:e.roomId)||(null===(t=this.props.oobData)||void 0===t?void 0:t.roomId)}render(){var e,t,n,r;const o=this.props,{room:s,oobData:l,viewAvatarOnClick:c,onClick:d,className:h}=o,f=a()(o,T),_=null!==(e=null!==(t=null==s?void 0:s.name)&&void 0!==t?t:l.name)&&void 0!==e?e:"?";return u.a.createElement(g.a,i()({},f,{className:p()(h,{mx_RoomAvatar_isSpaceRoom:(null!==(n=null==s?void 0:s.getType())&&void 0!==n?n:null===(r=this.props.oobData)||void 0===r?void 0:r.roomType)===m.j.Space}),name:_,idName:this.roomIdName,urls:this.state.urls,onClick:c&&this.state.urls[0]?this.onRoomAvatarClick:d}))}}l()(C,"defaultProps",{width:36,height:36,resizeMethod:"crop",oobData:{}})},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});const r=n(773),i=n(774),o=n(577),a=n(304),s=n(1373),l=n(263),c=n(455),u=n(776),d=n(1374),h=n(777),p=n(580),m=n(385),g=n(1375),f=n(1376),_=n(1377),b=n(1378),v=n(579),y=n(578),E=n(775),S=n(779),w=n(781),T=n(1379),C=n(778),x=n(782),F=n(1380),D=n(1381),k=n(1382),O=n(780);t.getDomElement=r.getDomElement,t.getLocationHref=r.getLocationHref,t.htmlTreeAsString=r.htmlTreeAsString,t.dsnFromString=i.dsnFromString,t.dsnToString=i.dsnToString,t.makeDsn=i.makeDsn,t.SentryError=o.SentryError,t.GLOBAL_OBJ=a.GLOBAL_OBJ,t.getGlobalObject=a.getGlobalObject,t.getGlobalSingleton=a.getGlobalSingleton,t.addInstrumentationHandler=s.addInstrumentationHandler,t.isDOMError=l.isDOMError,t.isDOMException=l.isDOMException,t.isElement=l.isElement,t.isError=l.isError,t.isErrorEvent=l.isErrorEvent,t.isEvent=l.isEvent,t.isInstanceOf=l.isInstanceOf,t.isNaN=l.isNaN,t.isPlainObject=l.isPlainObject,t.isPrimitive=l.isPrimitive,t.isRegExp=l.isRegExp,t.isString=l.isString,t.isSyntheticEvent=l.isSyntheticEvent,t.isThenable=l.isThenable,t.CONSOLE_LEVELS=c.CONSOLE_LEVELS,t.consoleSandbox=c.consoleSandbox,Object.defineProperty(t,"logger",{enumerable:!0,get:()=>c.logger}),t.memoBuilder=u.memoBuilder,t.addContextToFrame=d.addContextToFrame,t.addExceptionMechanism=d.addExceptionMechanism,t.addExceptionTypeValue=d.addExceptionTypeValue,t.arrayify=d.arrayify,t.checkOrSetAlreadyCaught=d.checkOrSetAlreadyCaught,t.getEventDescription=d.getEventDescription,t.parseSemver=d.parseSemver,t.uuid4=d.uuid4,t.dynamicRequire=h.dynamicRequire,t.isNodeEnv=h.isNodeEnv,t.loadModule=h.loadModule,t.normalize=p.normalize,t.normalizeToSize=p.normalizeToSize,t.walk=p.walk,t.addNonEnumerableProperty=m.addNonEnumerableProperty,t.convertToPlainObject=m.convertToPlainObject,t.dropUndefinedKeys=m.dropUndefinedKeys,t.extractExceptionKeysForMessage=m.extractExceptionKeysForMessage,t.fill=m.fill,t.getOriginalFunction=m.getOriginalFunction,t.markFunctionWrapped=m.markFunctionWrapped,t.objectify=m.objectify,t.urlEncode=m.urlEncode,t.basename=g.basename,t.dirname=g.dirname,t.isAbsolute=g.isAbsolute,t.join=g.join,t.normalizePath=g.normalizePath,t.relative=g.relative,t.resolve=g.resolve,t.makePromiseBuffer=f.makePromiseBuffer,t.addRequestDataToEvent=_.addRequestDataToEvent,t.addRequestDataToTransaction=_.addRequestDataToTransaction,t.extractPathForTransaction=_.extractPathForTransaction,t.extractRequestData=_.extractRequestData,t.severityFromString=b.severityFromString,t.severityLevelFromString=b.severityLevelFromString,t.validSeverityLevels=b.validSeverityLevels,t.createStackParser=v.createStackParser,t.getFunctionName=v.getFunctionName,t.nodeStackLineParser=v.nodeStackLineParser,t.stackParserFromStackParserOptions=v.stackParserFromStackParserOptions,t.stripSentryFramesAndReverse=v.stripSentryFramesAndReverse,t.escapeStringForRegex=y.escapeStringForRegex,t.isMatchingPattern=y.isMatchingPattern,t.safeJoin=y.safeJoin,t.snipLine=y.snipLine,t.stringMatchesSomePattern=y.stringMatchesSomePattern,t.truncate=y.truncate,t.isNativeFetch=E.isNativeFetch,t.supportsDOMError=E.supportsDOMError,t.supportsDOMException=E.supportsDOMException,t.supportsErrorEvent=E.supportsErrorEvent,t.supportsFetch=E.supportsFetch,t.supportsHistory=E.supportsHistory,t.supportsNativeFetch=E.supportsNativeFetch,t.supportsReferrerPolicy=E.supportsReferrerPolicy,t.supportsReportingObserver=E.supportsReportingObserver,t.SyncPromise=S.SyncPromise,t.rejectedSyncPromise=S.rejectedSyncPromise,t.resolvedSyncPromise=S.resolvedSyncPromise,Object.defineProperty(t,"_browserPerformanceTimeOriginMode",{enumerable:!0,get:()=>w._browserPerformanceTimeOriginMode}),t.browserPerformanceTimeOrigin=w.browserPerformanceTimeOrigin,t.dateTimestampInSeconds=w.dateTimestampInSeconds,t.timestampInSeconds=w.timestampInSeconds,t.timestampWithMs=w.timestampWithMs,t.usingPerformanceAPI=w.usingPerformanceAPI,t.TRACEPARENT_REGEXP=T.TRACEPARENT_REGEXP,t.extractTraceparentData=T.extractTraceparentData,t.getSDKSource=C.getSDKSource,t.isBrowserBundle=C.isBrowserBundle,t.addItemToEnvelope=x.addItemToEnvelope,t.createAttachmentEnvelopeItem=x.createAttachmentEnvelopeItem,t.createEnvelope=x.createEnvelope,t.createEventEnvelopeHeaders=x.createEventEnvelopeHeaders,t.envelopeContainsItemType=x.envelopeContainsItemType,t.envelopeItemTypeToDataCategory=x.envelopeItemTypeToDataCategory,t.forEachEnvelopeItem=x.forEachEnvelopeItem,t.getSdkMetadataForEnvelopeHeader=x.getSdkMetadataForEnvelopeHeader,t.parseEnvelope=x.parseEnvelope,t.serializeEnvelope=x.serializeEnvelope,t.createClientReportEnvelope=F.createClientReportEnvelope,t.DEFAULT_RETRY_AFTER=D.DEFAULT_RETRY_AFTER,t.disabledUntil=D.disabledUntil,t.isRateLimited=D.isRateLimited,t.parseRetryAfterHeader=D.parseRetryAfterHeader,t.updateRateLimits=D.updateRateLimits,t.BAGGAGE_HEADER_NAME=k.BAGGAGE_HEADER_NAME,t.MAX_BAGGAGE_STRING_LENGTH=k.MAX_BAGGAGE_STRING_LENGTH,t.SENTRY_BAGGAGE_KEY_PREFIX=k.SENTRY_BAGGAGE_KEY_PREFIX,t.SENTRY_BAGGAGE_KEY_PREFIX_REGEX=k.SENTRY_BAGGAGE_KEY_PREFIX_REGEX,t.baggageHeaderToDynamicSamplingContext=k.baggageHeaderToDynamicSamplingContext,t.dynamicSamplingContextToSentryBaggageHeader=k.dynamicSamplingContextToSentryBaggageHeader,t.getNumberOfUrlSegments=O.getNumberOfUrlSegments,t.parseUrl=O.parseUrl,t.stripUrlQueryAndFragment=O.stripUrlQueryAndFragment},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(13),i=n.n(r),o=n(149),a=n(147),s=n(1),l=n(129),c=n(122);function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function d(e){for(var t=1;t{e.getType()==l.b.Direct&&(this.mDirectEvent=d({},e.getContent()),this.userToRooms=null,this.roomToUser=null)})),this.hasSentOutPatchDirectAccountDataPatch=!1;const r=null!==(t=null===(n=e.getAccountData(l.b.Direct))||void 0===n?void 0:n.getContent())&&void 0!==t?t:{};this.mDirectEvent=d({},r)}static makeShared(){return h.sharedInstance=new h(c.a.get()),h.sharedInstance}static setShared(e){h.sharedInstance=e}static shared(){return h.sharedInstance}start(){this.populateRoomToUser(),this.matrixClient.on(a.b.AccountData,this.onAccountData)}stop(){this.matrixClient.removeListener(a.b.AccountData,this.onAccountData)}patchUpSelfDMs(e){const t=this.matrixClient.getUserId(),n=e[t];if(n){const r=n.map((e=>{const n=this.matrixClient.getRoom(e);if(n){const r=n.guessDMUserId();if(r&&r!==t)return{userId:r,roomId:e}}})).filter((e=>!!e));return!!r.length&&(e[t]=n.filter((e=>!r.some((t=>t.roomId===e)))),r.forEach((t=>{let{userId:n,roomId:r}=t;const i=e[n];i?(i.push(r),e[n]=Object(o.uniq)(i)):e[n]=[r]})),!0)}return!1}getDMRoomsForUserId(e){return this.getUserToRooms()[e]||[]}getDMRoomForIdentifiers(e){let t=this.getDMRoomsForUserId(e[0]);for(let n=1;nr.includes(e)))}return t.map((e=>c.a.get().getRoom(e))).filter((e=>e&&"join"===e.getMyMembership()))[0]}getUserIdForRoomId(e){if(null==this.roomToUser&&this.populateRoomToUser(),void 0===this.roomToUser[e]){const t=this.matrixClient.getRoom(e);if(t)return t.getDMInviter()}return this.roomToUser[e]}getUniqueRoomsWithIndividuals(){return this.roomToUser?Object.keys(this.roomToUser).map((e=>({userId:this.getUserIdForRoomId(e),room:this.matrixClient.getRoom(e)}))).filter((e=>e.userId&&e.room&&2===e.room.getInvitedAndJoinedMemberCount())).reduce(((e,t)=>(e[t.userId]=t.room)&&e),{}):{}}getRoomIds(){return Object.values(this.mDirectEvent).reduce(((e,t)=>(t.forEach((t=>e.add(t))),e)),new Set)}getUserToRooms(){if(!this.userToRooms){const e=this.mDirectEvent,t=e[this.matrixClient.getUserId()];if(null!=t&&t.length){const t=this.patchUpSelfDMs(e);s.a.warn("Invalid m.direct account data detected (self-chats that shouldn't be), patching it up."),t&&!this.hasSentOutPatchDirectAccountDataPatch&&(this.hasSentOutPatchDirectAccountDataPatch=!0,this.matrixClient.setAccountData(l.b.Direct,e))}this.userToRooms=e}return this.userToRooms}populateRoomToUser(){this.roomToUser={};for(const e of Object.keys(this.getUserToRooms()))for(const t of this.userToRooms[e])this.roomToUser[t]=e}}i()(h,"sharedInstance",void 0)},function(e,t,n){"use strict";n.d(t,"a",(function(){return l})),n.d(t,"g",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"h",(function(){return d})),n.d(t,"m",(function(){return h})),n.d(t,"l",(function(){return p})),n.d(t,"n",(function(){return m})),n.d(t,"o",(function(){return _})),n.d(t,"d",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"f",(function(){return y})),n.d(t,"k",(function(){return E})),n.d(t,"b",(function(){return C})),n.d(t,"j",(function(){return x})),n.d(t,"i",(function(){return F}));var r=n(121);function i(){return[Object(r.a)("Sun"),Object(r.a)("Mon"),Object(r.a)("Tue"),Object(r.a)("Wed"),Object(r.a)("Thu"),Object(r.a)("Fri"),Object(r.a)("Sat")]}function o(){return[Object(r.a)("Jan"),Object(r.a)("Feb"),Object(r.a)("Mar"),Object(r.a)("Apr"),Object(r.a)("May"),Object(r.a)("Jun"),Object(r.a)("Jul"),Object(r.a)("Aug"),Object(r.a)("Sep"),Object(r.a)("Oct"),Object(r.a)("Nov"),Object(r.a)("Dec")]}function a(e){return(e<10?"0":"")+e}function s(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.getHours()%12;const i=a(e.getMinutes()),o=e.getHours()>=12?Object(r.a)("PM"):Object(r.a)("AM");if(n=n||12,t){return`${n}:${i}:${a(e.getSeconds())}${o}`}return`${n}:${i}${o}`}function l(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=new Date,a=i(),s=o();return e.toDateString()===n.toDateString()?h(e,t):n.getTime()-e.getTime()<5184e5?Object(r.a)("%(weekDayName)s %(time)s",{weekDayName:a[e.getDay()],time:h(e,t)}):n.getFullYear()===e.getFullYear()?Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(time)s",{weekDayName:a[e.getDay()],monthName:s[e.getMonth()],day:e.getDate(),time:h(e,t)}):u(e,t)}function c(e){const t=i(),n=o();return Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s",{weekDayName:t[e.getDay()],monthName:n[e.getMonth()],day:e.getDate(),fullYear:e.getFullYear()})}function u(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const a=i(),s=o();return Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s",{weekDayName:a[e.getDay()],monthName:s[e.getMonth()],day:e.getDate(),fullYear:e.getFullYear(),time:n?d(e,t):h(e,t)})}function d(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?s(e,!0):a(e.getHours())+":"+a(e.getMinutes())+":"+a(e.getSeconds())}function h(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?s(e):a(e.getHours())+":"+a(e.getMinutes())}function p(e){const t=e<0;e=Math.abs(e);const n=Math.floor(e/3600).toFixed(0).padStart(2,"0");let r="";return"00"!==n&&(r+=`${n}:`),r+=`${Math.floor(e%3600/60).toFixed(0).padStart(2,"0")}:${Math.floor(e%3600%60).toFixed(0).padStart(2,"0")}`,t&&(r="-"+r),r}function m(e){const t=Math.floor(e/3600).toFixed(0),n=Math.floor(e%3600/60).toFixed(0),i=Math.floor(e%3600%60).toFixed(0);return"0"!==t?Object(r.a)("%(hours)sh %(minutes)sm %(seconds)ss left",{hours:t,minutes:n,seconds:i}):"0"!==n?Object(r.a)("%(minutes)sm %(seconds)ss left",{minutes:n,seconds:i}):Object(r.a)("%(seconds)ss left",{seconds:i})}const g=864e5;function f(e,t){return Math.abs(e.getTime()-t.getTime())<=g}function _(e,t){return!(!t||!e)&&(!f(e,t)||e.getDay()!==t.getDay())}function b(e){return Object(r.a)("%(date)s at %(time)s",{date:e.toLocaleDateString().replace(/\//g,"-"),time:e.toLocaleTimeString().replace(/:/g,"-")})}function v(e){return e.toISOString()}function y(e){return e.getFullYear()+"/"+a(e.getMonth()+1)+"/"+a(e.getDate())}function E(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=new Date(Date.now());if(f(e,n))return h(e,t);{let t=`${o()[e.getMonth()]} ${e.getDate()}`;return r=n,e.getFullYear()!==r.getFullYear()&&(t+=`, ${e.getFullYear()}`),t}var r}const S=6e4,w=60*S,T=24*w;function C(e){return e>=T?Object(r.a)("%(value)sd",{value:Math.round(e/T)}):e>=w?Object(r.a)("%(value)sh",{value:Math.round(e/w)}):e>=S?Object(r.a)("%(value)sm",{value:Math.round(e/S)}):Object(r.a)("%(value)ss",{value:Math.round(e/1e3)})}function x(e){const t=Math.floor(e/T),n=Math.floor(e%T/w),i=Math.floor(e%w/S),o=Math.floor(e%S/1e3);return t>0?Object(r.a)("%(days)sd %(hours)sh %(minutes)sm %(seconds)ss",{days:t,hours:n,minutes:i,seconds:o}):n>0?Object(r.a)("%(hours)sh %(minutes)sm %(seconds)ss",{hours:n,minutes:i,seconds:o}):i>0?Object(r.a)("%(minutes)sm %(seconds)ss",{minutes:i,seconds:o}):Object(r.a)("%(value)ss",{value:o})}const F=e=>new Intl.DateTimeFormat(void 0,{day:"2-digit",month:"2-digit",year:"2-digit"}).format(e)},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return l}));var r=n(13),i=n.n(r),o=n(122);class a{constructor(e,t){if(this.prepared=e,i()(this,"client",void 0),this.client=null!=t?t:o.a.get(),!this.client)throw new Error("No possible MatrixClient for media resolution. Please provide one or log in.")}get isEncrypted(){return!!this.prepared.file}get srcMxc(){return this.prepared.mxc}get thumbnailMxc(){var e;return null===(e=this.prepared.thumbnail)||void 0===e?void 0:e.mxc}get hasThumbnail(){return!!this.thumbnailMxc}get srcHttp(){return this.client.mxcUrlToHttp(this.srcMxc)}get thumbnailHttp(){return this.hasThumbnail?this.client.mxcUrlToHttp(this.thumbnailMxc):null}getThumbnailHttp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"scale";return this.hasThumbnail?(e=Math.floor(e*window.devicePixelRatio),t=Math.floor(t*window.devicePixelRatio),this.client.mxcUrlToHttp(this.thumbnailMxc,e,t,n)):null}getThumbnailOfSourceHttp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"scale";return e=Math.floor(e*window.devicePixelRatio),t=Math.floor(t*window.devicePixelRatio),this.client.mxcUrlToHttp(this.srcMxc,e,t,n)}getSquareThumbnailHttp(e){return e=Math.floor(e*window.devicePixelRatio),this.hasThumbnail?this.getThumbnailHttp(e,e,"crop"):this.getThumbnailOfSourceHttp(e,e,"crop")}downloadSource(){return fetch(this.srcHttp)}}function s(e,t){return new a(function(e){var t,n,r,i;let o;if(null!=e&&null!==(t=e.info)&&void 0!==t&&t.thumbnail_url?o={mxc:e.info.thumbnail_url,file:e.info.thumbnail_file}:null!=e&&null!==(n=e.info)&&void 0!==n&&null!==(r=n.thumbnail_file)&&void 0!==r&&r.url&&(o={mxc:e.info.thumbnail_file.url,file:e.info.thumbnail_file}),null!=e&&e.url)return{thumbnail:o,mxc:e.url,file:e.file};if(null!=e&&null!==(i=e.file)&&void 0!==i&&i.url)return{thumbnail:o,mxc:e.file.url,file:e.file};throw new Error("Invalid file provided: cannot determine MXC URI. Has it been redacted?")}(e),t)}function l(e,t){return s({url:e},t)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return a}));var r=n(120),i=n(125);const o=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const[o,a]=Object(r.useState)(i.b.getValue(e,t,n));return Object(r.useEffect)((()=>{const r=i.b.watchSetting(e,t,(()=>{a(i.b.getValue(e,t,n))}));return()=>{i.b.unwatchSetting(r)}}),[e,t,n]),o},a=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const[n,o]=Object(r.useState)(i.b.getValue(e,t));return Object(r.useEffect)((()=>{const n=i.b.watchSetting(e,t,(()=>{o(i.b.getValue(e,t))}));return()=>{i.b.unwatchSetting(n)}}),[e,t]),n}},function(e,t,n){"use strict";n.d(t,"a",(function(){return w})),n.d(t,"g",(function(){return T})),n.d(t,"i",(function(){return C})),n.d(t,"h",(function(){return x})),n.d(t,"f",(function(){return F})),n.d(t,"k",(function(){return D})),n.d(t,"l",(function(){return k})),n.d(t,"d",(function(){return O})),n.d(t,"j",(function(){return A})),n.d(t,"e",(function(){return R})),n.d(t,"c",(function(){return N})),n.d(t,"b",(function(){return L}));var r=n(13),i=n.n(r),o=n(1046),a=n.n(o),s=n(16),l=n(1),c=n(151),u=n(129),d=n(122);class h{forEvent(e,t){throw new Error("Not implemented")}forRoom(e){throw new Error("Not implemented")}forUser(e){throw new Error("Not implemented")}forEntity(e){throw new Error("Not implemented")}isPermalinkHost(e){throw new Error("Not implemented")}parsePermalink(e){throw new Error("Not implemented")}}class p{constructor(e,t,n,r){this.roomIdOrAlias=e,this.eventId=t,this.userId=n,this.viaServers=r}static forUser(e){return new p(null,null,e,null)}static forRoom(e){return new p(e,null,null,arguments.length>1&&void 0!==arguments[1]?arguments[1]:[])}static forEvent(e,t){return new p(e,t,null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:[])}get primaryEntityId(){return this.roomIdOrAlias||this.userId}get sigil(){var e;return(null===(e=this.primaryEntityId)||void 0===e?void 0:e[0])||"?"}}const m="matrix.to",g=`https://${m}`,f=`^(?:https?://)?${m.replace(".","\\.")}/#/(.*)`;class _ extends h{constructor(){super()}forEvent(e,t,n){return`${g}/#/${e}/${t}${this.encodeServerCandidates(n)}`}forRoom(e,t){return`${g}/#/${e}${this.encodeServerCandidates(t)}`}forUser(e){return`${g}/#/${e}`}forEntity(e){return`${g}/#/${e}`}isPermalinkHost(e){return e===m}encodeServerCandidates(e){return e&&0!==e.length?`?via=${e.map((e=>encodeURIComponent(e))).join("&via=")}`:""}parsePermalink(e){if(!e)throw new Error("Does not appear to be a permalink");const t=[...e.matchAll(new RegExp(f,"gi"))][0];if(!t||t.length<2)throw new Error("Does not appear to be a permalink");const n=t[1].split("/"),r=n[0];if("@"===r[0])return p.forUser(r);if("#"===r[0]||"!"===r[0]){if(1===n.length){const[e,t=""]=r.split("?"),n=t.split(/&?via=/g).filter((e=>!!e));return p.forRoom(e,n)}const e=n.length>1?n.slice(1).join("/"):"",[t,i=""]=e.split("?"),o=i.split(/&?via=/g).filter((e=>!!e));return p.forEvent(r,t,o)}throw new Error("Unknown entity type in permalink")}}class b extends h{constructor(e){if(super(),i()(this,"elementUrl",void 0),this.elementUrl=e,!this.elementUrl.startsWith("http:")&&!this.elementUrl.startsWith("https:"))throw new Error("Element prefix URL does not appear to be an HTTP(S) URL")}forEvent(e,t,n){return`${this.elementUrl}/#/room/${e}/${t}${this.encodeServerCandidates(n)}`}forRoom(e,t){return`${this.elementUrl}/#/room/${e}${this.encodeServerCandidates(t)}`}forUser(e){return`${this.elementUrl}/#/user/${e}`}forEntity(e){if("!"===e[0]||"#"===e[0])return this.forRoom(e);if("@"===e[0])return this.forUser(e);throw new Error("Unrecognized entity")}isPermalinkHost(e){const t=new URL(this.elementUrl);return e===(t.host||t.hostname)}encodeServerCandidates(e){return e&&0!==e.length?`?via=${e.map((e=>encodeURIComponent(e))).join("&via=")}`:""}parsePermalink(e){if(!e||!e.startsWith(this.elementUrl))throw new Error("Does not appear to be a permalink");const t=e.substring(`${this.elementUrl}/#/`.length);return b.parseAppRoute(t)}static parseAppRoute(e){const t=e.split("/");if(t.length<2)throw new Error("URL is missing parts");const[n]=t.splice(-1,1),[r,i=""]=n.split("?");t.push(r);const o=t[0],a=t[1];if("user"===o)return p.forUser(a);if("room"===o){const e=t.length>2?t.slice(2).join("/"):"",n=i.split(/&?via=/).filter((e=>!!e));return p.forEvent(a,e,n)}throw new Error("Unknown entity type in permalink")}}var v=n(131),y=n(368);class E extends h{constructor(){super()}encodeEntity(e){if("!"===e[0])return`roomid/${e.slice(1)}`;if("#"===e[0])return`r/${e.slice(1)}`;if("@"===e[0])return`u/${e.slice(1)}`;if("$"===e[0])return`e/${e.slice(1)}`;throw new Error("Cannot encode entity: "+e)}forEvent(e,t,n){return`matrix:${this.encodeEntity(e)}/${this.encodeEntity(t)}${this.encodeServerCandidates(n)}`}forRoom(e,t){return`matrix:${this.encodeEntity(e)}${this.encodeServerCandidates(t)}`}forUser(e){return`matrix:${this.encodeEntity(e)}`}forEntity(e){return`matrix:${this.encodeEntity(e)}`}isPermalinkHost(e){return""===e}encodeServerCandidates(e){return e&&0!==e.length?`?via=${e.map((e=>encodeURIComponent(e))).join("&via=")}`:""}parsePermalink(e){if(!e||!e.startsWith("matrix:"))throw new Error("Does not appear to be a permalink");const t=e.substring("matrix:".length).split("/"),n=t[0],r=t[1];if("u"===n)return p.forUser(`@${r}`);if("r"===n||"roomid"===n){const e="r"===n?"#":"!";if(2===t.length){const[t,n=""]=r.split("?"),i=n.split(/&?via=/g).filter((e=>!!e));return p.forRoom(`${e}${t}`,i)}if("e"===t[2]){const n=t.length>3?t.slice(3).join("/"):"",[i,o=""]=n.split("?"),a=o.split(/&?via=/g).filter((e=>!!e));return p.forEvent(`${e}${r}`,`$${i}`,a)}throw new Error("Faulty room permalink")}throw new Error("Unknown entity type in permalink")}}const S=/.*/;class w{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this.room=e,i()(this,"roomId",void 0),i()(this,"highestPlUserId",null),i()(this,"populationMap",null),i()(this,"bannedHostsRegexps",null),i()(this,"allowedHostsRegexps",null),i()(this,"_serverCandidates",void 0),i()(this,"started",!1),i()(this,"onRoomStateUpdate",(()=>{this.fullUpdate()})),i()(this,"updateServerCandidates",(()=>{const e=new Set;this.highestPlUserId&&e.add(R(this.highestPlUserId));const t=Object.keys(this.populationMap).sort(((e,t)=>this.populationMap[t]-this.populationMap[e]));for(let r=0;r{var t;let[n]=e;const r=this.room.getMember(n);if(!r||"join"!==r.membership)return!1;const i=R(n),o=null!==(t=N(i))&&void 0!==t?t:i;return!P(o)&&!M(o,this.bannedHostsRegexps)&&M(o,this.allowedHostsRegexps)})),n=t.reduce(((e,t)=>t[1]>e[1]?t:e),[null,0]),[r,i]=n;if(null!==r&&i>=50)return void(this.highestPlUserId=r)}}}this.highestPlUserId=null}updateAllowedServers(){const e=[];let t=[S];if(this.room.currentState){const n=this.room.currentState.getStateEvents(u.b.RoomServerAcl,"");if(n&&n.getContent()){const r=e=>new RegExp("^"+s.r(e,!1)+"$");(n.getContent().deny||[]).forEach((t=>e.push(r(t))));const i=n.getContent().allow||[];t=[],i.forEach((e=>t.push(r(e))))}}this.bannedHostsRegexps=e,this.allowedHostsRegexps=t}updatePopulationMap(){const e={};for(const t of this.room.getJoinedMembers()){const n=R(t.userId);e[n]||(e[n]=0),e[n]++}this.populationMap=e}}function T(e){return I().forEntity(e)}function C(e){return I().forUser(e)}function x(e){if(!e)throw new Error("can't permalink a falsy roomId");if("!"!==e[0])return I().forRoom(e,[]);const t=d.a.get().getRoom(e);if(!t)return I().forRoom(e,[]);const n=new w(t);return n.load(),n.forShareableRoom()}function F(e){return!!(new _).isPermalinkHost(e)||I().isPermalinkHost(e)}function D(e){if(!e)return null;if("#"===e[0]||"!"===e[0])return x(e);if("@"===e[0])return C(e);if("matrix:"===e.slice(0,7))try{const t=A(e);if(t){if(t.roomIdOrAlias){const e=t.eventId?`/${t.eventId}`:"";let n=g+`/#/${t.roomIdOrAlias}${e}`;return t.viaServers.length>0&&(n+=(new _).encodeServerCandidates(t.viaServers)),n}if(t.userId)return g+`/#/${t.userId}`}}catch{}return e}function k(e){if(!(e.startsWith("http:")||e.startsWith("https:")||e.startsWith("matrix:")||e.startsWith("vector:")))return e;try{const t=decodeURIComponent(e).match(y.a);if(t)return t[1]}catch(t){return e}try{const t=A(e);if(t)if(t.roomIdOrAlias){const n=t.eventId?`/${t.eventId}`:"";e=`#/room/${t.roomIdOrAlias}${n}`,t.viaServers.length>0&&(e+=(new _).encodeServerCandidates(t.viaServers))}else t.userId&&(e=`#/user/${t.userId}`)}catch(e){}return e}function O(e){try{let t=A(e);if(!t){const n=e.match(y.a);if(n){const e=new b("http://localhost"),r=n[1].split("#").slice(1).join("#");t=e.parsePermalink(`http://localhost/#${r}`)}}if(!t)return null;if(t.userId)return t.userId;if(t.roomIdOrAlias)return t.roomIdOrAlias}catch(e){}return null}function I(){const e=v.b.get("permalink_prefix");return e&&e!==g?new b(e):new _}function A(e){try{const t=v.b.get("permalink_prefix"),n=decodeURIComponent(e);if(new RegExp(f,"i").test(n))return(new _).parsePermalink(n);if(e.startsWith("matrix:"))return(new E).parsePermalink(e);if(t&&e.startsWith(t))return new b(t).parsePermalink(e)}catch(e){l.a.error("Failed to parse permalink",e)}return null}function R(e){return e.split(":").splice(1).join(":")}function N(e){if(!e)return null;try{return new URL(`https://${e}`).hostname}catch(e){return console.error("Error encountered while extracting hostname from server name",e),null}}function M(e,t){if(!e)return!0;if(t.length>0&&!t[0].test)throw new Error(t[0].toString());return t.some((t=>t.test(e)))}function P(e){return!!e&&(e.startsWith("[")&&e.endsWith("]")&&(e=e.substring(1,e.length-1)),a()(e))}const L=e=>{const t=new w(e);return t.load(),t.serverCandidates}},function(e,t,n){"use strict";n.d(t,"g",(function(){return S})),n.d(t,"c",(function(){return w})),n.d(t,"f",(function(){return T})),n.d(t,"h",(function(){return x})),n.d(t,"d",(function(){return F})),n.d(t,"i",(function(){return D})),n.d(t,"e",(function(){return c})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return v}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(152),l=n(142);const c=e=>{let{children:t,inputRef:n}=e;const[r,i,o]=D(n);return t({onFocus:r,isActive:i,ref:o})};var u=n(130),d=n.n(u),h=n(132),p=n.n(h),m=n(123);const g=["inputRef","onFocus"],f=e=>{let{inputRef:t,onFocus:n}=e,r=p()(e,g);const[i,o,s]=D(t);return a.a.createElement(m.a,d()({},r,{onFocus:e=>{i(),null==n||n(e)},inputRef:s,tabIndex:o?0:-1}))};var _=n(148);const b=["inputRef","onFocus"],v=e=>{let{inputRef:t,onFocus:n}=e,r=p()(e,b);const[i,o,s]=D(t);return a.a.createElement(_.a,d()({},r,{onFocus:e=>{i(),null==n||n(e)},inputRef:s,tabIndex:o?0:-1}))};function y(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function E(e){for(var t=1;t{}});let T;w.displayName="RovingTabIndexContext",function(e){e.Register="REGISTER",e.Unregister="UNREGISTER",e.SetFocus="SET_FOCUS"}(T||(T={}));const C=(e,t)=>{switch(t.type){case T.Register:return e.activeRef||(e.activeRef=t.payload.ref),e.refs.push(t.payload.ref),e.refs.sort(((e,t)=>{if(e===t)return 0;const n=e.current.compareDocumentPosition(t.current);return n&Node.DOCUMENT_POSITION_FOLLOWING||n&Node.DOCUMENT_POSITION_CONTAINED_BY?-1:n&Node.DOCUMENT_POSITION_PRECEDING||n&Node.DOCUMENT_POSITION_CONTAINS?1:0})),E({},e);case T.Unregister:{const i=e.refs.findIndex((e=>e===t.payload.ref));if(-1===i)return e;var n,r;if(e.refs.splice(i,1)[0]===e.activeRef)if(i>=e.refs.length?e.activeRef=x(e.refs,e.refs.length-1,!0):e.activeRef=x(e.refs,i)||x(e.refs,i,!0),document.activeElement===document.body)null===(n=e.activeRef)||void 0===n||null===(r=n.current)||void 0===r||r.focus();return E({},e)}case T.SetFocus:return e.activeRef===t.payload.ref?e:(e.activeRef=t.payload.ref,E({},e));default:return e}},x=function(e,t){if(arguments.length>2&&void 0!==arguments[2]&&arguments[2])for(let r=t;r=0;r--){var n;if(null!==(null===(n=e[r].current)||void 0===n?void 0:n.offsetParent))return e[r]}else for(let n=t;n=0;n++){var r;if(null!==(null===(r=e[n].current)||void 0===r?void 0:r.offsetParent))return e[n]}},F=e=>{let{children:t,handleHomeEnd:n,handleUpDown:r,handleLeftRight:i,onKeyDown:c}=e;const[u,d]=Object(o.useReducer)(C,{refs:[]}),h=Object(o.useMemo)((()=>({state:u,dispatch:d})),[u]),p=Object(o.useCallback)((e=>{if(c&&(c(e,h.state),e.defaultPrevented))return;let t=!1;const o=Object(s.a)().getAccessibilityAction(e);let a;if(S(e.target)){if(o===l.h.Tab)if(t=!0,h.state.refs.length>0){const t=h.state.refs.indexOf(h.state.activeRef);a=x(h.state.refs,t+(e.shiftKey?-1:1),e.shiftKey)}}else switch(o){case l.h.Home:n&&(t=!0,a=x(h.state.refs,0));break;case l.h.End:n&&(t=!0,a=x(h.state.refs,h.state.refs.length-1,!0));break;case l.h.ArrowDown:case l.h.ArrowRight:if((o===l.h.ArrowDown&&r||o===l.h.ArrowRight&&i)&&(t=!0,h.state.refs.length>0)){const e=h.state.refs.indexOf(h.state.activeRef);a=x(h.state.refs,e+1)}break;case l.h.ArrowUp:case l.h.ArrowLeft:if((o===l.h.ArrowUp&&r||o===l.h.ArrowLeft&&i)&&(t=!0,h.state.refs.length>0)){const e=h.state.refs.indexOf(h.state.activeRef);a=x(h.state.refs,e-1,!0)}}var u;(t&&(e.preventDefault(),e.stopPropagation()),a)&&(null===(u=a.current)||void 0===u||u.focus(),d({type:T.SetFocus,payload:{ref:a}}))}),[h,c,n,r,i]);return a.a.createElement(w.Provider,{value:h},t({onKeyDownHandler:p}))},D=e=>{const t=Object(o.useContext)(w);let n=Object(o.useRef)(null);e&&(n=e),Object(o.useLayoutEffect)((()=>(t.dispatch({type:T.Register,payload:{ref:n}}),()=>{t.dispatch({type:T.Unregister,payload:{ref:n}})})),[]);return[Object(o.useCallback)((()=>{t.dispatch({type:T.SetFocus,payload:{ref:n}})}),[]),t.state.activeRef===n,n]}},function(e,t,n){"use strict";n.d(t,"f",(function(){return b})),n.d(t,"c",(function(){return v})),n.d(t,"h",(function(){return y})),n.d(t,"e",(function(){return E})),n.d(t,"b",(function(){return S})),n.d(t,"a",(function(){return w})),n.d(t,"d",(function(){return T})),n.d(t,"g",(function(){return C})),n.d(t,"i",(function(){return x}));var r=n(13),i=n.n(r),o=n(147),a=n(287),s=n(129),l=n(143),c=n(179),u=n(353),d=n(140),h=n(15),p=n(1),m=n(662),g=n(18);function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _(e){for(var t=1;t{null!=e&&e.isRelation(T.name)&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(b.Update,this))})),i()(this,"onRedaction",(async e=>{if(e.threadRootId===this.id)if(this.replyCount<=0){for(const e of this.timeline)this.clearEventMetadata(e);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit(b.Delete,this)}else await this.updateThreadMetadata()})),i()(this,"onTimelineEvent",((e,t,n)=>{n||t.addLocalEchoReceipt(e.getSender(),e,g.b.Read),this.onEcho(e,null!=n&&n)})),i()(this,"onLocalEcho",(e=>{this.onEcho(e,!1)})),i()(this,"onEcho",(async(e,t)=>{e.threadRootId===this.id&&this.lastEvent!==e&&(await this.updateThreadMetadata(),e.isRelation(T.name)&&(t||this.emit(b.NewReply,this,e)))})),null==n||!n.room)throw new Error("element-web#22141: A thread requires a room in order to function");this.room=n.room,this.client=n.client,this.pendingEventOrdering=null!==(r=n.pendingEventOrdering)&&void 0!==r?r:o.e.Chronological,this.timelineSet=new u.b(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new a.b(this),this.reEmitter.reEmit(this.timelineSet,[d.d.Timeline,d.d.TimelineReset]),this.room.on(l.c.BeforeRedaction,this.onBeforeRedaction),this.room.on(d.d.Redaction,this.onRedaction),this.room.on(d.d.LocalEchoUpdated,this.onLocalEcho),this.timelineSet.on(d.d.Timeline,this.onTimelineEvent),this.processReceipts(n.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}async fetchRootEvent(){this.rootEvent=this.room.findEventById(this.id);try{const e=await this.client.fetchRoomEvent(this.roomId,this.id),t=this.client.getEventMapper();this.rootEvent=t(e)}catch(e){p.a.error("Failed to fetch thread root to construct thread with",e)}await this.processEvent(this.rootEvent)}static setServerSideSupport(e){E.hasServerSideSupport=e,e!==v.Stable&&(S.setPreferUnstable(!0),w.setPreferUnstable(!0),T.setPreferUnstable(!0))}static setServerSideListSupport(e){E.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){E.hasServerSideFwdPaginationSupport=e}get roomState(){return this.room.getLiveTimeline().getState(c.b.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||(this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState}),this.timeline=this.events)}addEvents(e,t){e.forEach((e=>this.addEvent(e,t,!1))),this.updateThreadMetadata()}async addEvent(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.setEventMetadata(e);const r=this.lastReply(),i=!r||e.localTimestamp>=r.localTimestamp;if(E.hasServerSideSupport){if(!t&&this.initialEventsFetched&&i)this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e);else if(e.isRelation(s.h.Annotation)||e.isRelation(s.h.Replace)){var o,a,l;if(this.initialEventsFetched)this.addEventToTimeline(e,t);else null===(l=this.replayEvents)||void 0===l||l.push(e);return null===(o=this.timelineSet.relations)||void 0===o||o.aggregateParentEvent(e),void(null===(a=this.timelineSet.relations)||void 0===a||a.aggregateChildEvent(e,this.timelineSet))}}else this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e,{});E.hasServerSideSupport&&this.rootEvent||!e.isRelation(T.name)||this.replyCount++,n&&(this.emit(b.NewReply,this,e),this.updateThreadMetadata())}async processEvent(e){e&&(this.setEventMetadata(e),await this.fetchEditsWhereNeeded(e)),this.timeline=this.events}processReceipts(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(const{eventId:t,receiptType:n,userId:r,receipt:i,synthetic:o}of e)this.addReceiptToStructure(t,n,r,i,o)}getRootEventBundledRelationship(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.rootEvent;return null==e?void 0:e.getServerAggregatedRelation(T.name)}async processRootEvent(){const e=this.getRootEventBundledRelationship();if(E.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=!!e.current_user_participated;const t=this.client.getEventMapper();this.lastEvent=t(_(_({},e.latest_event),{},{room_id:this.roomId})),this.updatePendingReplyCount(),await this.processEvent(this.lastEvent)}}updatePendingReplyCount(){const e=(this.pendingEventOrdering===o.e.Detached?this.room.getPendingEvents():this.events).filter((e=>{var t;return e.threadRootId===this.id&&e.isRelation(T.name)&&null!==e.status&&e.getId()!==(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())}));this.lastPendingEvent=e.length?e[e.length-1]:void 0,this.pendingReplyCount=e.length}async resetLiveTimeline(e,t){const n=this.liveTimeline;this.timelineSet.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);const r=this.liveTimeline;let i,o;if(e){i=(await this.client.createMessagesRequest(this.roomId,e,1,c.a.Forward)).end}if(t){o=(await this.client.createMessagesRequest(this.roomId,t,1,c.a.Backward)).start}var a,s;t&&n.getPaginationToken(c.a.Forward)===t&&n.setPaginationToken(null!==(a=o)&&void 0!==a?a:null,c.a.Forward);e&&r.getPaginationToken(c.a.Backward)===e&&r.setPaginationToken(null!==(s=i)&&void 0!==s?s:null,c.a.Backward)}async updateThreadMetadata(){if(this.updatePendingReplyCount(),E.hasServerSideSupport&&(this.initialEventsFetched||await this.processRootEvent(),await this.fetchRootEvent()),await this.processRootEvent(),!this.initialEventsFetched){this.initialEventsFetched=!0;try{0===this.replyCount&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,c.a.Backward)):await this.client.paginateEventTimeline(this.liveTimeline,{backwards:!0,limit:Math.max(1,this.length)});for(const e of this.replayEvents)this.addEvent(e,!1);this.replayEvents=null,this.emit(d.d.TimelineReset,this.room,this.timelineSet,!0)}catch(e){p.a.error("Failed to load start of newly created thread: ",e),this.initialEventsFetched=!1}}this.emit(b.Update,this)}async fetchEditsWhereNeeded(){for(var e=arguments.length,t=new Array(e),n=0;ne.isEncrypted())).map((e=>{if(!e.isRelation())return this.client.relations(this.roomId,e.getId(),s.h.Replace,e.getType(),{limit:1}).then((t=>{t.events.length&&e.makeReplaced(t.events[0])})).catch((e=>{p.a.error("Failed to load edits for encrypted thread event",e)}))})))}setEventMetadata(e){e&&(c.b.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){var t,n,r;e&&(e.setThread(void 0),null===(t=e.event)||void 0===t||(null===(n=t.unsigned)||void 0===n||(null===(r=n["m.relations"])||void 0===r||delete r[T.name])))}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>!0;for(let t=this.timeline.length-1;t>=0;t--){const n=this.timeline[t];if(e(n))return n}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return null!==(e=null!==(t=this.lastPendingEvent)&&void 0!==t?t:this.lastEvent)&&void 0!==e?e:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof l.b}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){const n=e===this.client.getUserId(),r=this.timeline[this.timeline.length-1];if(n&&r){const e=r.getTs()=0;--e){var o,a;const n=this.timeline[e];if(n.getId()===i)return i;if(n.getTs(){c.a.dispatch({action:u.a.ViewUser,member:S,push:T.isCard})}:w.onClick}))}class b extends l.a.Component{render(){return l.a.createElement(_,this.props,this.props.children)}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(13),i=n.n(r),o=n(1),a=n(174),s=n(124),l=n(925),c=n(125),u=n(182),d=n(137),h=n(153),p=n(566);function m(e){if(!e)return e;const t=[...e.history].map((e=>function(e){var t,n,r,i,o;const a=null!==(t=e.state)&&void 0!==t?t:{};return{state:{widgetId:a.widgetId,spaceId:a.spaceId,isInitialEventHighlighted:a.isInitialEventHighlighted,initialEventScrollIntoView:a.initialEventScrollIntoView,threadHeadEventId:null!=a&&null!==(n=a.threadHeadEvent)&&void 0!==n&&n.getId()?a.threadHeadEvent.getId():void 0,memberInfoEventId:null!=a&&null!==(r=a.memberInfoEvent)&&void 0!==r&&r.getId()?a.memberInfoEvent.getId():void 0,initialEventId:null!=a&&null!==(i=a.initialEvent)&&void 0!==i&&i.getId()?a.initialEvent.getId():void 0,memberId:null!=a&&null!==(o=a.member)&&void 0!==o&&o.userId?a.member.userId:void 0},phase:e.phase}}(e)));return{isOpen:e.isOpen,history:t}}function g(e,t){if(!e)return e;const n=[...e.history].map((e=>function(e,t){var n;const r=null!==(n=e.state)&&void 0!==n?n:{},i={widgetId:r.widgetId,spaceId:r.spaceId,isInitialEventHighlighted:r.isInitialEventHighlighted,initialEventScrollIntoView:r.initialEventScrollIntoView,threadHeadEvent:null!=r&&r.threadHeadEventId?t.findEventById(r.threadHeadEventId):void 0,memberInfoEvent:null!=r&&r.memberInfoEventId?t.findEventById(r.memberInfoEventId):void 0,initialEvent:null!=r&&r.initialEventId?t.findEventById(r.initialEventId):void 0,member:!(null==r||!r.memberId)&&t.getMember(r.memberId)||void 0};return{state:i,phase:e.phase}}(e,t)));return{history:n,isOpen:e.isOpen}}var f=n(128),_=n(154);class b extends p.a{constructor(){super(s.a),i()(this,"global",void 0),i()(this,"byRoom",void 0),i()(this,"viewedRoomId",void 0),i()(this,"onVerificationRequestUpdate",(()=>{var e;if(null===(e=this.currentCard)||void 0===e||!e.state)return;const{member:t}=this.currentCard.state;if(!t)return;const n=Object(l.b)(t);n&&(this.currentCard.state.verificationRequest=n,this.emitAndUpdateSettings())})),this.reset()}reset(){this.global=void 0,this.byRoom={},this.viewedRoomId=null}async onReady(){var e;this.viewedRoomId=_.b.instance.roomViewStore.getRoomId(),null===(e=this.matrixClient)||void 0===e||e.on(a.b.VerificationRequest,this.onVerificationRequestUpdate),this.loadCacheFromSettings(),this.emitAndUpdateSettings()}async onNotReady(){var e;null===(e=this.matrixClient)||void 0===e||e.off(a.b.VerificationRequest,this.onVerificationRequestUpdate)}onDispatcherAction(e){if(e.action!==f.a.ActiveRoomChanged)return;const t=e;this.handleViewedRoomChange(t.oldRoomId,t.newRoomId)}get isOpen(){var e,t;return null!==(e=null===(t=this.byRoom[this.viewedRoomId])||void 0===t?void 0:t.isOpen)&&void 0!==e&&e}isOpenForRoom(e){var t,n;return null!==(t=null===(n=this.byRoom[e])||void 0===n?void 0:n.isOpen)&&void 0!==t&&t}get roomPhaseHistory(){var e,t;return null!==(e=null===(t=this.byRoom[this.viewedRoomId])||void 0===t?void 0:t.history)&&void 0!==e?e:[]}get currentCard(){const e=this.roomPhaseHistory;return e.length>=1?e[e.length-1]:{state:{},phase:null}}currentCardForRoom(e){var t,n;const r=null!==(t=null===(n=this.byRoom[e])||void 0===n?void 0:n.history)&&void 0!==t?t:[];return r.length>0?r[r.length-1]:{state:{},phase:null}}get previousCard(){const e=this.roomPhaseHistory;return(null==e?void 0:e.length)>=2?e[e.length-2]:{state:{},phase:null}}setCard(e){var t,n,r,i,o;let a=arguments.length>2?arguments[2]:void 0;const s=null!=a?a:this.viewedRoomId,l=this.getVerificationRedirect(e),c=null!==(t=null==l?void 0:l.phase)&&void 0!==t?t:e.phase,u=null!==(n=null==l?void 0:l.state)&&void 0!==n?n:0===Object.keys(null!==(r=e.state)&&void 0!==r?r:{}).length?null:e.state;if(this.isPhaseValid(c,Boolean(s)))if(c===(null===(i=this.currentCardForRoom(s))||void 0===i?void 0:i.phase)&&u){var d,h;const e=null!==(d=null===(h=this.byRoom[s])||void 0===h?void 0:h.history)&&void 0!==d?d:[];e[e.length-1].state=u,this.emitAndUpdateSettings()}else if(c===(null===(o=this.currentCardForRoom(s))||void 0===o?void 0:o.phase)&&this.byRoom[s])this.show(s),this.emitAndUpdateSettings();else{const e=[{phase:c,state:null!=u?u:{}}];this.byRoom[s]={history:e,isOpen:!0},this.emitAndUpdateSettings()}}setCards(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const n=null!=t?t:this.viewedRoomId,r=e.map((e=>{var t;return{phase:e.phase,state:null!==(t=e.state)&&void 0!==t?t:{}}}));this.byRoom[n]={history:r,isOpen:!0},this.show(n),this.emitAndUpdateSettings()}pushCard(e){var t,n,r;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const a=null!=o?o:this.viewedRoomId,s=this.getVerificationRedirect(e),l=null!==(t=null==s?void 0:s.phase)&&void 0!==t?t:e.phase,c=null!==(n=null!==(r=null==s?void 0:s.state)&&void 0!==r?r:e.state)&&void 0!==n?n:{};if(!this.isPhaseValid(l,Boolean(a)))return;const u=this.byRoom[a];u?(u.history.push({state:c,phase:l}),u.isOpen=!i||u.isOpen):this.byRoom[a]={history:[{phase:l,state:c}],isOpen:!i},this.show(a),this.emitAndUpdateSettings()}popCard(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;const t=null!=e?e:this.viewedRoomId;if(!this.byRoom[t])return;const n=this.byRoom[t].history.pop();return this.emitAndUpdateSettings(),n}togglePanel(e){const t=null!=e?e:this.viewedRoomId;this.byRoom[t]&&(this.byRoom[t].isOpen=!this.byRoom[t].isOpen,this.emitAndUpdateSettings())}show(e){this.isOpenForRoom(null!=e?e:this.viewedRoomId)||this.togglePanel(e)}hide(e){this.isOpenForRoom(null!=e?e:this.viewedRoomId)&&this.togglePanel(e)}loadCacheFromSettings(){if(this.viewedRoomId){var e;const r=null===(e=this.mxClient)||void 0===e?void 0:e.getRoom(this.viewedRoomId);var t,n;if(r)this.global=null!==(t=this.global)&&void 0!==t?t:g(c.b.getValue("RightPanel.phasesGlobal"),r),this.byRoom[this.viewedRoomId]=null!==(n=this.byRoom[this.viewedRoomId])&&void 0!==n?n:g(c.b.getValue("RightPanel.phases",this.viewedRoomId),r);else o.a.warn("Could not restore the right panel after load because there was no associated room object.")}}emitAndUpdateSettings(){this.filterValidCards(this.global);const e=m(this.global);if(c.b.setValue("RightPanel.phasesGlobal",null,d.a.DEVICE,e),this.viewedRoomId){const e=this.byRoom[this.viewedRoomId];this.filterValidCards(e);const t=m(e);c.b.setValue("RightPanel.phases",this.viewedRoomId,d.a.ROOM_DEVICE,t)}this.emit(h.b,null)}filterValidCards(e){null!=e&&e.history&&(e.history=e.history.filter((e=>this.isCardStateValid(e))),e.history.length||(e.isOpen=!1))}isCardStateValid(e){switch(e.phase){case u.a.ThreadView:return e.state.threadHeadEvent||o.a.warn("removed card from right panel because of missing threadHeadEvent in card state"),!!e.state.threadHeadEvent;case u.a.RoomMemberInfo:case u.a.SpaceMemberInfo:case u.a.EncryptionPanel:return e.state.member||o.a.warn("removed card from right panel because of missing member in card state"),!!e.state.member;case u.a.Room3pidMemberInfo:case u.a.Space3pidMemberInfo:return e.state.memberInfoEvent||o.a.warn("removed card from right panel because of missing memberInfoEvent in card state"),!!e.state.memberInfoEvent;case u.a.Widget:return e.state.widgetId||o.a.warn("removed card from right panel because of missing widgetId in card state"),!!e.state.widgetId}return!0}getVerificationRedirect(e){if(e.phase===u.a.RoomMemberInfo&&e.state){const{member:t}=e.state,n=Object(l.b)(t);if(n)return{phase:u.a.EncryptionPanel,state:{verificationRequest:n,member:t}}}return null}isPhaseValid(e,t){return e&&u.a[e]?!!t||(o.a.warn(`Tried to switch right panel to a room phase: ${e}, but we are currently not viewing a room`),!1):(o.a.warn(`Tried to switch right panel to unknown phase: ${e}`),!1)}handleViewedRoomChange(e,t){var n,r;if(this.mxClient){if(this.viewedRoomId=t,this.loadCacheFromSettings(),(null===(n=this.currentCard)||void 0===n?void 0:n.phase)!==u.a.EncryptionPanel){const e=this.byRoom[this.viewedRoomId];null!=e&&e.history&&(e.history=e.history.filter((e=>e.phase!=u.a.RoomMemberInfo&&e.phase!=u.a.Room3pidMemberInfo)))}if(c.b.getValue("feature_right_panel_default_open")&&(null===(r=this.byRoom[this.viewedRoomId])||void 0===r||!r.isOpen)){var i;const e=[{phase:u.a.RoomMemberList}],t=this.viewedRoomId?null===(i=this.mxClient)||void 0===i?void 0:i.getRoom(this.viewedRoomId):void 0;null!=t&&t.isSpaceRoom()||e.unshift({phase:u.a.RoomSummary}),this.byRoom[this.viewedRoomId]={isOpen:!0,history:e}}this.emitAndUpdateSettings()}}static get instance(){return this.internalInstance||(this.internalInstance=new b,this.internalInstance.start()),this.internalInstance}}i()(b,"internalInstance",void 0),window.mxRightPanelStore=b.instance},function(e,t,n){"use strict";(function(e,r){n.d(t,"e",(function(){return q})),n.d(t,"d",(function(){return V})),n.d(t,"b",(function(){return $})),n.d(t,"a",(function(){return K})),n.d(t,"c",(function(){return W}));var i=n(13),o=n.n(i),a=n(416),s=n.n(a),l=n(359),c=n(129),u=n(287),d=n(1),h=n(511),p=n(199),m=n(978),g=n(358),f=n(654),_=n(360),b=n(980),v=n(981),y=n(669),E=n(225),S=n(419),w=n(512),T=n(421),C=n(422),x=n(239),F=n(984),D=n(985),k=n(986),O=n(288),I=n(322),A=n(671),R=n(672),N=n(140),M=n(184),P=n(143),L=n(147),B=n(158),U=n(151),j=n(16);function G(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}const z=g.a.DeviceVerification,H={[S.c.NAME]:S.c,[w.a.NAME]:w.a,[S.e]:k.a,[S.d]:k.a},q={RECIPROCATE_QR_CODE:S.c.NAME,SAS:w.a.NAME};function V(){return Boolean(e.Olm)}let $;!function(e){e.DeviceVerificationChanged="deviceVerificationChanged",e.UserTrustStatusChanged="userTrustStatusChanged",e.UserCrossSigningUpdated="userCrossSigningUpdated",e.RoomKeyRequest="crypto.roomKeyRequest",e.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",e.KeyBackupStatus="crypto.keyBackupStatus",e.KeyBackupFailed="crypto.keyBackupFailed",e.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",e.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",e.VerificationRequest="crypto.verification.request",e.Warning="crypto.warning",e.WillUpdateDevices="crypto.willUpdateDevices",e.DevicesUpdated="crypto.devicesUpdated",e.KeysChanged="crossSigning.keysChanged"}($||($={}));class K extends B.b{static getOlmVersion(){return h.a.getOlmVersion()}constructor(e,t,n,r,i,a,s){var l;if(super(),l=this,this.baseApis=e,this.userId=t,this.deviceId=n,this.clientStore=r,this.cryptoStore=i,this.roomList=a,o()(this,"backupManager",void 0),o()(this,"crossSigningInfo",void 0),o()(this,"olmDevice",void 0),o()(this,"deviceList",void 0),o()(this,"dehydrationManager",void 0),o()(this,"secretStorage",void 0),o()(this,"reEmitter",void 0),o()(this,"verificationMethods",void 0),o()(this,"supportedAlgorithms",void 0),o()(this,"outgoingRoomKeyRequestManager",void 0),o()(this,"toDeviceVerificationRequests",void 0),o()(this,"inRoomVerificationRequests",void 0),o()(this,"trustCrossSignedDevices",!0),o()(this,"lastOneTimeKeyCheck",null),o()(this,"oneTimeKeyCheckInProgress",!1),o()(this,"roomEncryptors",new Map),o()(this,"roomDecryptors",new Map),o()(this,"deviceKeys",{}),o()(this,"globalBlacklistUnverifiedDevices",!1),o()(this,"globalErrorOnUnknownDevices",!0),o()(this,"receivedRoomKeyRequests",[]),o()(this,"receivedRoomKeyRequestCancellations",[]),o()(this,"processingRoomKeyRequests",!1),o()(this,"lazyLoadMembers",!1),o()(this,"roomDeviceTrackingState",{}),o()(this,"lastNewSessionForced",new j.b((()=>new j.b((()=>0))))),o()(this,"sendKeyRequestsImmediately",!1),o()(this,"oneTimeKeyCount",void 0),o()(this,"needsNewFallback",void 0),o()(this,"fallbackCleanup",void 0),o()(this,"onDeviceListUserCrossSigningUpdated",(async e=>{if(e===this.userId){const t=this.deviceList.getStoredCrossSigningForUser(e),n=t?t.getId():null,r=this.crossSigningInfo.getId();r&&n&&!(r!==n)?await this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit($.KeysChanged,{}),this.emit($.UserTrustStatusChanged,this.userId,this.checkUserTrust(e)))}else{await 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))}})),o()(this,"onMembership",((e,t,n)=>{try{this.onRoomMembership(e,t,n)}catch(e){d.a.error("Error handling membership change:",e)}})),o()(this,"onToDeviceEvent",(e=>{try{d.a.log(`received to-device ${e.getType()} from: ${e.getSender()} id: ${e.getContent()[c.k]}`),"m.room_key"==e.getType()||"m.forwarded_room_key"==e.getType()?this.onRoomKeyEvent(e):"m.room_key_request"==e.getType()?this.onRoomKeyRequestEvent(e):"m.secret.request"===e.getType()?this.secretStorage.onRequestReceived(e):"m.secret.send"===e.getType()?this.secretStorage.onSecretReceived(e):"m.room_key.withheld"===e.getType()?this.onRoomKeyWithheldEvent(e):e.getContent().transaction_id?this.onKeyVerificationMessage(e):"m.bad.encrypted"===e.getContent().msgtype?this.onToDeviceBadEncrypted(e):(e.isBeingDecrypted()||e.shouldAttemptDecryption())&&(e.isBeingDecrypted()||e.attemptDecryption(this),e.once(P.c.Decrypted,(e=>{this.onToDeviceEvent(e)})))}catch(e){d.a.error("Error handling toDeviceEvent:",e)}})),o()(this,"onTimelineEvent",(function(e,t,n,r){let{liveEvent:i=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!F.a.validateEvent(e,l.baseApis))return;l.handleVerificationEvent(e,l.inRoomVerificationRequests,(e=>{const t=new F.a(l.baseApis,e.getRoomId());return new x.k(t,l.verificationMethods,l.baseApis)}),i)})),this.reEmitter=new u.b(this),s){this.verificationMethods=new Map;for(const e of s)"string"==typeof e?H[e]&&this.verificationMethods.set(e,H[e]):e.NAME?this.verificationMethods.set(e.NAME,e):d.a.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=new Map(Object.entries(H));this.backupManager=new R.a(e,(async()=>{const e=await this.getSessionBackupPrivateKey();if(e)return e;const t=await this.getSecret("m.megolm_backup.v1");if(t){const e=W(t);if(e){const t=await this.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",e,[t[0]])}return p.decodeBase64(e||t)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})),this.olmDevice=new h.a(i),this.deviceList=new m.a(e,i,this.olmDevice),this.deviceList.on($.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[$.DevicesUpdated,$.WillUpdateDevices]),this.supportedAlgorithms=Array.from(f.a.keys()),this.outgoingRoomKeyRequestManager=new y.a(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new D.b,this.inRoomVerificationRequests=new F.b;const g=this.baseApis.cryptoCallbacks||{},b=Object(_.d)(i,this.olmDevice);this.crossSigningInfo=new _.a(t,g,b),this.secretStorage=new v.b(e,g,e),this.dehydrationManager=new A.b(this),!g.getCrossSigningKey&&g.getSecretStorageKey&&(g.getCrossSigningKey=async e=>_.a.getFromSecretStorage(e,this.secretStorage))}async init(){let{exportedOlmDevice:t,pickleKey:n}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};d.a.log("Crypto: initialising Olm..."),await e.Olm.init(),d.a.log(t?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),await this.olmDevice.init({fromExportedDevice:t,pickleKey:n}),d.a.log("Crypto: loading device list..."),await this.deviceList.load(),this.deviceKeys["ed25519:"+this.deviceId]=this.olmDevice.deviceEd25519Key,this.deviceKeys["curve25519:"+this.deviceId]=this.olmDevice.deviceCurve25519Key,d.a.log("Crypto: fetching own devices...");let r=this.deviceList.getRawStoredDevicesForUser(this.userId);if(r||(r={}),!r[this.deviceId]){d.a.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:z.VERIFIED,known:!0};r[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,r),this.deviceList.saveIfDirty()}await this.cryptoStore.doTxn("readonly",[E.a.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(d.a.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),d.a.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)}}}}async createRecoveryKeyFromPassphrase(t){const n=new e.Olm.PkDecryption;try{const e={};if(t){const r=await Object(T.c)(t);e.passphrase={algorithm:"m.pbkdf2",iterations:r.iterations,salt:r.salt},e.pubkey=n.init_with_private_key(r.key)}else e.pubkey=n.generate_key();const r=n.get_private_key();return{keyInfo:e,encodedPrivateKey:Object(C.b)(r),privateKey:r}}finally{null==n||n.free()}}async userHasCrossSigningKeys(){return await this.downloadKeys([this.userId]),null!==this.deviceList.getStoredCrossSigningForUser(this.userId)}async isCrossSigningReady(){const e=this.crossSigningInfo.getId(),t=await this.crossSigningInfo.isStoredInKeyCache()||await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);return!(!e||!t)}async isSecretStorageReady(){const e=await this.secretStorage.hasKey(),t=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),n=!this.backupManager.getKeyBackupEnabled()||await this.baseApis.isKeyBackupKeyStored();return!!(e&&t&&n)}async bootstrapCrossSigning(){let{authUploadDeviceSigningKeys:e,setupNewCrossSigning:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};d.a.log("Bootstrapping cross-signing");const n=this.baseApis.cryptoCallbacks,r=new b.a(this.baseApis.store.accountData,n),i=new _.a(this.userId,r.crossSigningCallbacks,r.crossSigningCallbacks),o=async()=>{i.resetKeys(),await this.signObject(i.keys.master),r.addCrossSigningKeys(e,i.keys);const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=await i.signDevice(this.userId,t);r.addKeySignature(this.userId,this.deviceId,n),this.backupManager.backupInfo&&(await i.signObject(this.backupManager.backupInfo.auth_data,"master"),r.addSessionBackup(this.backupManager.backupInfo))},a=this.crossSigningInfo.getId(),s=await this.crossSigningInfo.isStoredInKeyCache(),l=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),c=s||l;d.a.log({setupNewCrossSigning:t,publicKeysOnDevice:a,privateKeysInCache:s,privateKeysInStorage:l,privateKeysExistSomewhere:c}),!c||t?(d.a.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),await o()):a&&s?d.a.log("Cross-signing public keys trusted and private keys found locally"):l&&(d.a.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),await this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const u=r.crossSigningCallbacks.privateKeys;if(u.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new v.b(r.accountDataClientAdapter,r.ssssCryptoCallbacks,void 0);await e.hasKey()&&(d.a.log("Storing new cross-signing private keys in secret storage"),await _.a.storeInSecretStorage(u,e))}const h=r.buildOperation();await h.apply(this),await r.persist(this),d.a.log("Cross-signing ready")}async bootstrapSecretStorage(){let{createSecretStorageKey:e=(async()=>({})),keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:r,getKeyBackupPassphrase:i}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};d.a.log("Bootstrapping Secure Secret Storage");const o=this.baseApis.cryptoCallbacks,a=new b.a(this.baseApis.store.accountData,o),s=new v.b(a.accountDataClientAdapter,a.ssssCryptoCallbacks,void 0);let l=null;const c=async(e,t)=>{t&&(e.key=t);const{keyId:n,keyInfo:r}=await s.addKey(v.a,e);return t&&a.ssssCryptoCallbacks.addPrivateKey(n,r,t),await s.setDefaultKeyId(n),n},u=async(e,t)=>{if(!t.mac){var n,r;const i=await(null===(n=(r=this.baseApis.cryptoCallbacks).getSecretStorageKey)||void 0===n?void 0:n.call(r,{keys:{[e]:t}},""));if(i){const n=i[1];a.ssssCryptoCallbacks.addPrivateKey(e,t,n);const{iv:r,mac:o}=await Object(I.a)(n);t.iv=r,t.mac=o,await a.setAccountData(`m.secret_storage.key.${e}`,t)}}},h=async e=>{if(this.crossSigningInfo.getId()&&await this.crossSigningInfo.isStoredInKeyCache("master"))try{d.a.log("Adding cross-signing signature to key backup"),await this.crossSigningInfo.signObject(e,"master")}catch(e){d.a.error("Signing key backup with cross-signing keys failed",e)}else d.a.warn("Cross-signing keys not available, skipping signature on key backup")},m=await this.getSecretStorageKey(),[g,f]=m||[null,null],y=!r&&f&&f.algorithm===v.a;if(d.a.log({keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:r,storageExists:y,oldKeyInfo:f}),y||t)if(!y&&t){d.a.log("Secret storage does not exist, using key backup key");const e=await this.getSessionBackupPrivateKey()||await(null==i?void 0:i()),n={};t.auth_data.private_key_salt&&t.auth_data.private_key_iterations&&(n.passphrase={algorithm:"m.pbkdf2",iterations:t.auth_data.private_key_iterations,salt:t.auth_data.private_key_salt,bits:256}),l=await c(n,e),await s.store("m.megolm_backup.v1",p.encodeBase64(e),[l]),await h(t.auth_data),a.addSessionBackup(t)}else d.a.log("Secret storage exists"),f&&f.algorithm===v.a&&await u(g,f);else{d.a.log("Secret storage does not exist, creating new storage key");const{keyInfo:t={},privateKey:n}=await e();l=await c(t,n)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&await this.isCrossSigningReady()&&(l||!await this.crossSigningInfo.isStoredInSecretStorage(s))){d.a.log("Copying cross-signing private keys from cache to secret storage");const e=await this.crossSigningInfo.getCrossSigningKeysFromCache();await _.a.storeInSecretStorage(e,s)}if(n&&!t){d.a.log("Creating new message key backup version");const e=await this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=Object(C.a)(e.recovery_key);await s.store("m.megolm_backup.v1",p.encodeBase64(t));const n={algorithm:e.algorithm,auth_data:e.auth_data};await h(n.auth_data),await this.signObject(n.auth_data),a.addSessionBackup(n)}const E=await s.get("m.megolm_backup.v1");if(E){d.a.info("Got session backup key from secret storage: caching");const e=W(E);if(e){const t=l||g;await s.store("m.megolm_backup.v1",e,t?[t]:null)}const t=new Uint8Array(p.decodeBase64(e||E));a.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=await this.getSessionBackupPrivateKey()||await(null==i?void 0:i());if(!e)return void d.a.error("Key backup is enabled but couldn't get key backup key!");d.a.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),await s.store("m.megolm_backup.v1",p.encodeBase64(e))}const S=a.buildOperation();await S.apply(this),await a.persist(this),d.a.log("Secure Secret Storage ready")}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(t,n){let r=null;try{r=new e.Olm.PkDecryption;return r.init_with_private_key(t)===n}finally{var i;null===(i=r)||void 0===i||i.free()}}async getSessionBackupPrivateKey(){let e=await new Promise((e=>{this.cryptoStore.doTxn("readonly",[E.a.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(p.decodeBase64(W(e)||e)),await this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=r.from(this.olmDevice.pickleKey),n=await Object(I.b)(e,t,"m.megolm_backup.v1");e=p.decodeBase64(n)}return e}async storeSessionBackupPrivateKey(e){if(!(e instanceof Uint8Array))throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${e}`);const t=r.from(this.olmDevice.pickleKey),n=await Object(I.c)(p.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[E.a.STORE_ACCOUNT],(e=>{this.cryptoStore.storeSecretStorePrivateKey(e,"m.megolm_backup.v1",n)}))}checkCrossSigningPrivateKey(t,n){let r=null;try{r=new e.Olm.PkSigning;return r.init_with_seed(t)===n}finally{var i;null===(i=r)||void 0===i||i.free()}}async afterCrossSigningLocalKeyChange(){d.a.info("Starting cross-signing key change post-processing");const e=this.deviceList.getStoredDevice(this.userId,this.deviceId),t=await this.crossSigningInfo.signDevice(this.userId,e);d.a.info(`Starting background key sig upload for ${this.deviceId}`);const n=e=>{let{shouldEmit:r=!1}=e;return this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:t}}).then((e=>{const{failures:t}=e||{};if(Object.keys(t||[]).length>0)throw r&&this.baseApis.emit($.KeySignatureUploadFailure,t,"afterCrossSigningLocalKeyChange",n),new O.e("Key upload failed",{failures:t});d.a.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{d.a.error(`Error during background key sig upload for ${this.deviceId}`,e)}))};n({shouldEmit:!0});const r=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(r){d.a.info("Starting device verification upgrade");const e={};for(const[t,n]of Object.entries(this.deviceList.crossSigningInfo)){const r=await this.checkForDeviceVerificationUpgrade(t,_.a.fromStorage(n,t));r&&(e[t]=r)}if(Object.keys(e).length>0){d.a.info(`Found ${Object.keys(e).length} verif users to upgrade`);try{const t=await r({users:e});if(t)for(const n of t)n in e&&await this.baseApis.setDeviceVerified(n,e[n].crossSigningInfo.getId())}catch(e){d.a.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}d.a.info("Finished device verification upgrade")}d.a.info("Finished cross-signing key change post-processing")}async checkForDeviceVerificationUpgrade(e,t){const n=this.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!n.isVerified()){const n=this.deviceList.getRawStoredDevicesForUser(e),r=await this.checkForValidDeviceSignature(e,t.keys.master,n);if(r.length)return{devices:r.map((e=>g.a.fromStorage(n[e],e))),crossSigningInfo:t}}}async checkForValidDeviceSignature(e,t,n){const r=[];if(n&&t.signatures&&t.signatures[e])for(const i of Object.keys(t.signatures[e])){const[,o]=i.split(":",2);if(o in n&&n[o].verified===z.VERIFIED)try{await p.verifySignature(this.olmDevice,t,e,o,n[o].keys[i]),r.push(o)}catch(e){}}return r}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 _.c(!1,!1,!1)}checkDeviceTrust(e,t){const n=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,n)}checkDeviceInfoTrust(e,t){const n=!(null==t||!t.isVerified()),r=this.deviceList.getStoredCrossSigningForUser(e);if(t&&r){const i=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(r,t,n,i)}return new _.b(!1,!1,n,!1)}checkIfOwnDeviceCrossSigned(e){var t;const n=this.deviceList.getStoredDevice(this.userId,e);if(!n)return!1;const r=this.deviceList.getStoredCrossSigningForUser(this.userId);return null!==(t=null==r?void 0:r.checkDeviceTrust(r,n,!1,!0).isCrossSigningVerified())&&void 0!==t&&t}async checkOwnCrossSigningTrust(){let{allowPrivateKeyRequests:e=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=this.userId;await this.downloadKeys([this.userId]);const n=await this.crossSigningInfo.getCrossSigningKeysFromCache(),r=this.deviceList.getStoredCrossSigningForUser(t);if(!r)return void d.a.error("Got cross-signing update event for user "+t+" but no new cross-signing information found!");const i=r.getId(),o=this.crossSigningInfo.getId()!==i,a=r.getId()&&!n.has("master");if(o&&d.a.info("Got new master public key",i),e&&(o||a)){d.a.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("master",i))[1],d.a.info("Got cross-signing master private key")}finally{var s;null===(s=e)||void 0===s||s.free()}}const l=this.crossSigningInfo.getId("self_signing"),c=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(r.keys);const u=l!==r.getId("self_signing"),h=c!==r.getId("user_signing"),p=r.getId("self_signing")&&!n.has("self_signing"),m=r.getId("user_signing")&&!n.has("user_signing"),g={};if(u&&d.a.info("Got new self-signing key",r.getId("self_signing")),e&&(u||p)){d.a.info("Attempting to retrieve cross-signing self-signing private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("self_signing",r.getId("self_signing")))[1],d.a.info("Got cross-signing self-signing private key")}finally{var f;null===(f=e)||void 0===f||f.free()}const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=await this.crossSigningInfo.signDevice(this.userId,t);g[this.deviceId]=n}if(h&&d.a.info("Got new user-signing key",r.getId("user_signing")),e&&(h||m)){d.a.info("Attempting to retrieve cross-signing user-signing private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("user_signing",r.getId("user_signing")))[1],d.a.info("Got cross-signing user-signing private key")}finally{var _;null===(_=e)||void 0===_||_.free()}}if(o){const e=this.crossSigningInfo.keys.master;await this.signObject(e);const t=e.signatures[this.userId]["ed25519:"+this.deviceId];g[this.crossSigningInfo.getId()]=Object.assign({},e,{signatures:{[this.userId]:{["ed25519:"+this.deviceId]:t}}})}const b=Object.keys(g);if(b.length){const e=t=>{let{shouldEmit:n=!1}=t;return d.a.info(`Starting background key sig upload for ${b}`),this.baseApis.uploadKeySignatures({[this.userId]:g}).then((t=>{const{failures:r}=t||{};if(d.a.info(`Finished background key sig upload for ${b}`),Object.keys(r||[]).length>0)throw n&&this.baseApis.emit($.KeySignatureUploadFailure,r,"checkOwnCrossSigningTrust",e),new O.e("Key upload failed",{failures:r})})).catch((e=>{d.a.error(`Error during background key sig upload for ${b}`,e)}))};e({shouldEmit:!0})}this.emit($.UserTrustStatusChanged,t,this.checkUserTrust(t)),o&&(this.emit($.KeysChanged,{}),await this.afterCrossSigningLocalKeyChange()),await this.backupManager.checkKeyBackup()}async storeTrustedSelfKeys(e){e?this.crossSigningInfo.setKeys(e):this.crossSigningInfo.clearKeys(),await this.cryptoStore.doTxn("readwrite",[E.a.STORE_ACCOUNT],(e=>{this.cryptoStore.storeCrossSigningKeys(e,this.crossSigningInfo.keys)}))}async checkDeviceVerifications(e){const t=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(t){if(d.a.info(`Starting device verification upgrade for ${e}`),this.crossSigningInfo.keys.user_signing){const n=this.deviceList.getStoredCrossSigningForUser(e);if(n){const r=await this.checkForDeviceVerificationUpgrade(e,n);if(r){(await t({users:{[e]:r}})).includes(e)&&await this.baseApis.setDeviceVerified(e,n.getId())}}}d.a.info(`Finished device verification upgrade for ${e}`)}}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(M.b.Membership,this.onMembership),e.on(L.b.ToDeviceEvent,this.onToDeviceEvent),e.on(N.d.Timeline,this.onTimelineEvent),e.on(P.c.Decrypted,this.onTimelineEvent)}start(){d.a.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){const e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then((()=>this.baseApis.uploadKeysRequest({device_keys:e})))}updateOneTimeKeyCount(e){if(!isFinite(e))throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");this.oneTimeKeyCount=e}setNeedsNewFallback(e){this.needsNewFallback=e}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){if(this.oneTimeKeyCheckInProgress)return;const e=Date.now();if(null!==this.lastOneTimeKeyCheck&&e-this.lastOneTimeKeyCheck<6e4)return;this.lastOneTimeKeyCheck=e;const t=this.olmDevice.maxNumberOfOneTimeKeys(),n=Math.floor(t/2),r=async e=>{for(;n>e||this.getNeedsNewFallback();){if(n>e){d.a.info("generating oneTimeKeys");const t=Math.min(n-e,5);await this.olmDevice.generateOneTimeKeys(t)}if(this.getNeedsNewFallback()){const e=await this.olmDevice.getFallbackKey();e.curve25519&&0!=Object.keys(e.curve25519).length||(d.a.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),await this.olmDevice.generateFallbackKey())}d.a.info("calling uploadOneTimeKeys");const t=await 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=>r(e))).catch((e=>{d.a.error("Error uploading one-time keys",e.stack||e)})).finally((()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1}))}async uploadOneTimeKeys(){const e=[];let t;if(this.getNeedsNewFallback()){t={};const n=await this.olmDevice.getFallbackKey();for(const[r,i]of Object.entries(n.curve25519)){const n={key:i,fallback:!0};t["signed_curve25519:"+r]=n,e.push(this.signObject(n))}this.setNeedsNewFallback(!1)}const n=await this.olmDevice.getOneTimeKeys(),r={};for(const t in n.curve25519)if(n.curve25519.hasOwnProperty(t)){const i={key:n.curve25519[t]};r["signed_curve25519:"+t]=i,e.push(this.signObject(i))}await Promise.all(e);const i={one_time_keys:r};t&&(i["org.matrix.msc2732.fallback_keys"]=t,i.fallback_keys=t);const o=await this.baseApis.uploadKeysRequest(i);return t&&(this.fallbackCleanup=setTimeout((()=>{delete this.fallbackCleanup,this.olmDevice.forgetOldFallbackKey()}),36e5)),await this.olmDevice.markKeysAsPublished(),o}downloadKeys(e,t){return this.deviceList.downloadKeys(e,!!t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}async setDeviceVerification(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;const a=this.deviceList.getStoredCrossSigningForUser(e);if(a&&a.getId()===t){if(null!==r||null!==i)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");const s=o?Object.values(o)[0]:null;if(o&&(1!==Object.values(o).length||s!==a.getId()))throw new Error(`Key did not match expected value: expected ${a.getId()}, got ${s}`);if(this.crossSigningInfo.getId()||e!==this.crossSigningInfo.userId||(this.storeTrustedSelfKeys(a.keys),this.emit($.UserTrustStatusChanged,this.userId,this.checkUserTrust(e))),e!==this.userId){d.a.info("Master key "+a.getId()+" for "+e+" marked verified. Signing...");const n=await this.crossSigningInfo.signUser(a);if(n){const r=async i=>{let{shouldEmit:o=!1}=i;d.a.info("Uploading signature for "+e+"...");const a=await this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:s}=a||{};if(Object.keys(s||[]).length>0)throw o&&this.baseApis.emit($.KeySignatureUploadFailure,s,"setDeviceVerification",r),new O.e("Key upload failed",{failures:s})};await r({shouldEmit:!0})}return n}return a}const s=this.deviceList.getRawStoredDevicesForUser(e);if(!s||!s[t])throw new Error("Unknown device "+e+":"+t);const l=s[t];let c=l.verified;if(n){if(o)for(const[e,t]of Object.entries(o))if(l.keys[e]!==t)throw new Error(`Key did not match expected value: expected ${t}, got ${l.keys[e]}`);c=z.VERIFIED}else null!==n&&c==z.VERIFIED&&(c=z.UNVERIFIED);r?c=z.BLOCKED:null!==r&&c==z.BLOCKED&&(c=z.UNVERIFIED);let u=l.known;if(null!==i&&(u=i),l.verified===c&&l.known===u||(l.verified=c,l.known=u,this.deviceList.storeDevicesForUser(e,s),this.deviceList.saveIfDirty()),n&&e===this.userId){let n;d.a.info("Own device "+t+" marked verified: signing");if(this.checkDeviceTrust(e,t).isCrossSigningVerified()?d.a.log(`Own device ${t} already cross-signing verified`):n=await this.crossSigningInfo.signDevice(e,g.a.fromStorage(l,t)),n){const r=async i=>{let{shouldEmit:o=!1}=i;d.a.info("Uploading signature for "+t);const a=await this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:s}=a||{};if(Object.keys(s||[]).length>0)throw o&&this.baseApis.emit($.KeySignatureUploadFailure,s,"setDeviceVerification",r),new O.e("Key upload failed",{failures:s})};await r({shouldEmit:!0})}}const h=g.a.fromStorage(l,t);return this.emit($.DeviceVerificationChanged,e,t,h),h}findVerificationRequestDMInProgress(e){return this.inRoomVerificationRequests.findRequestInProgress(e)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){const n=this.inRoomVerificationRequests.findRequestInProgress(t);if(n)return Promise.resolve(n);const r=new F.a(this.baseApis,t,e);return this.requestVerificationWithChannel(e,r,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 r=new D.a(this.baseApis,e,t,D.a.makeTransactionId());return this.requestVerificationWithChannel(e,r,this.toDeviceVerificationRequests)}async requestVerificationWithChannel(e,t,n){let r=new x.k(t,this.verificationMethods,this.baseApis);t.transactionId&&n.setRequestByChannel(t,r),await r.sendRequest();const i=n.getRequestByChannel(t);return i?r=i:(d.a.log(`Crypto: adding new request to requestsByTxnId with id ${t.transactionId} ${t.roomId}`),n.setRequestByChannel(t,r)),r}beginKeyVerification(e,t,n){let r,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(i){if(r=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,i),!r)throw new Error(`No request found for user ${t} with transactionId ${i}`)}else{i=D.a.makeTransactionId();const e=new D.a(this.baseApis,t,[n],i,n);r=new x.k(e,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,i,r)}return r.beginKeyVerification(e,{userId:t,deviceId:n})}async legacyDeviceVerification(e,t,n){const r=D.a.makeTransactionId(),i=new D.a(this.baseApis,e,[t],r,t),o=new x.k(i,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,r,o);const a=o.beginKeyVerification(n,{userId:e,deviceId:t});return await Promise.race([a.verify(),o.waitFor((e=>e.started))]),o}async getOlmSessionsForUser(e){const t=this.getStoredDevicesForUser(e)||[],n={};for(const e of t){const t=e.getIdentityKey(),r=await this.olmDevice.getSessionInfoForDevice(t);n[e.deviceId]={deviceIdKey:t,sessions:r}}return n}getEventSenderDeviceInfo(e){const t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n)return null;if(e.isKeySourceUntrusted())return null;const r=this.deviceList.getDeviceByIdentityKey(n,t);if(null===r)return null;const i=e.getClaimedEd25519Key();return i?i!==r.getFingerprint()?(d.a.warn("Event "+e.getId()+" claims ed25519 key "+i+" but sender device has key "+r.getFingerprint()),null):r:(d.a.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){var t,n;const r={};if(r.senderKey=null!==(t=e.getSenderKey())&&void 0!==t?t:void 0,r.algorithm=e.getWireContent().algorithm,!r.senderKey||!r.algorithm)return r.encrypted=!1,r;r.encrypted=!0,e.isKeySourceUntrusted()?r.authenticated=!1:r.authenticated=!0,r.sender=null!==(n=this.deviceList.getDeviceByIdentityKey(r.algorithm,r.senderKey))&&void 0!==n?n:void 0;const i=e.getClaimedEd25519Key();return i||(d.a.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),r.mismatchedSender=!0),r.sender&&i!==r.sender.getFingerprint()&&(d.a.warn("Event "+e.getId()+" claims ed25519 key "+i+"but sender device has key "+r.sender.getFingerprint()),r.mismatchedSender=!0),r}forceDiscardSession(e){const t=this.roomEncryptors.get(e);if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");t.forceDiscardSession()}async setRoomEncryption(e,t,n){const r=this.clientStore.getRoom(e);if(!r)throw new Error(`Unable to enable encryption tracking devices in unknown room ${e}`);await this.setRoomEncryptionImpl(r,t),this.lazyLoadMembers||n||this.deviceList.refreshOutdatedDeviceLists()}async setRoomEncryptionImpl(e,t){const n=e.roomId;if(!t.algorithm)return void d.a.log("Ignoring setRoomEncryption with no algorithm");const r=this.roomList.getRoomEncryption(n);if(r&&JSON.stringify(r)!=JSON.stringify(t))return void d.a.error("Ignoring m.room.encryption event which requests a change of config in "+n);if(this.roomEncryptors.get(n))return;let i=null;r||(i=this.roomList.setRoomEncryption(n,t));const o=f.c.get(t.algorithm);if(!o)throw new Error("Unable to encrypt with "+t.algorithm);const a=new o({userId:this.userId,deviceId:this.deviceId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:n,config:t});if(this.roomEncryptors.set(n,a),i&&await i,d.a.log(`Enabling encryption in ${n}`),e.membersLoaded())await this.trackRoomDevicesImpl(e);else{const t=r=>{e.off(U.b.Update,t),e.membersLoaded()&&this.trackRoomDevicesImpl(e).catch((e=>{d.a.error(`Error enabling device tracking in ${n}`,e)}))};e.on(U.b.Update,t)}}trackRoomDevices(e){const t=this.clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);return this.trackRoomDevicesImpl(t)}trackRoomDevicesImpl(e){const t=e.roomId,n=async()=>{if(!this.roomEncryptors.has(t))return;d.a.log(`Starting to track devices for room ${t} ...`);(await e.getEncryptionTargetMembers()).forEach((e=>{this.deviceList.startTrackingDeviceList(e.userId)}))};let r=this.roomDeviceTrackingState[t];return r||(r=n(),this.roomDeviceTrackingState[t]=r.catch((e=>{throw delete this.roomDeviceTrackingState[t],e}))),r}ensureOlmSessionsForUsers(e,t){const n=new Map;for(const t of e){const e=[];n.set(t,e);const r=this.getStoredDevicesForUser(t)||[];for(const t of r){t.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(t.verified!=z.BLOCKED&&e.push(t))}}return p.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,n,t)}async exportRoomKeys(){const e=[];return await this.cryptoStore.doTxn("readonly",[E.a.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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0;const i=e.length;function o(){var e;null===(e=t.progressCallback)||void 0===e||e.call(t,{stage:"load_keys",successes:n,failures:r,total:i})}return Promise.all(e.map((e=>{if(!e.room_id||!e.algorithm)return d.a.warn("ignoring room key entry with missing fields",e),r++,t.progressCallback&&o(),null;return this.getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e,t).finally((()=>{n++,t.progressCallback&&o()}))}))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){const t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}async encryptEvent(e,t){const n=e.getRoomId(),r=this.roomEncryptors.get(n);if(!r)throw new Error("Room "+n+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");await this.trackRoomDevicesImpl(t);let i=e.getContent();const o=i["m.relates_to"];o&&(i=Object.assign({},i),delete i["m.relates_to"]);const a=i["io.element.performance_metrics"];a&&(i=Object.assign({},i),delete i["io.element.performance_metrics"]);const s=await r.encryptMessage(t,e.getType(),i);o&&(s["m.relates_to"]=o),a&&(s["io.element.performance_metrics"]=a),e.makeEncrypted("m.room.encrypted",s,this.olmDevice.deviceCurve25519Key,this.olmDevice.deviceEd25519Key)}async decryptEvent(e){if(e.isRedacted()){const t=new P.b(function(e){for(var t=1;t2&&void 0!==arguments[2]&&arguments[2];return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,n).then((()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()})).catch((e=>{d.a.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{d.a.warn("Error clearing pending room key requests",e)}))}async cancelAndResendAllOutgoingKeyRequests(){await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}async onCryptoEvent(e,t){const n=t.getContent();await this.setRoomEncryptionImpl(e,n)}async onSyncWillProcess(e){e.oldSyncToken||(d.a.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}async onSyncCompleted(e){var t;this.deviceList.setSyncToken(null!==(t=e.nextSyncToken)&&void 0!==t?t:null),this.deviceList.saveIfDirty(),this.deviceList.startTrackingDeviceList(this.userId),this.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(this.maybeUploadOneTimeKeys(),this.processReceivedRoomKeyRequests(),this.outgoingRoomKeyRequestManager.sendQueuedRequests(),this.sendKeyRequestsImmediately=!0)}async evalDeviceListChanges(e){if(Array.isArray(null==e?void 0:e.changed)&&e.changed.forEach((e=>{this.deviceList.invalidateUserDeviceList(e)})),Array.isArray(null==e?void 0:e.left)&&e.left.length){const t=new Set(await this.getTrackedE2eUsers());e.left.forEach((e=>{t.has(e)||this.deviceList.stopTrackingDeviceList(e)}))}}async getTrackedE2eUsers(){const e=[];for(const t of this.getTrackedE2eRooms()){const n=await t.getEncryptionTargetMembers();for(const t of n)e.push(t.userId)}return e}getTrackedE2eRooms(){return this.clientStore.getRooms().filter((e=>{if(!this.roomEncryptors.get(e.roomId))return!1;if(!this.roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t}))}async encryptAndSendToDevices(e,t){const n={eventType:c.b.RoomMessageEncrypted,batch:[]};try{await Promise.all(e.map((async e=>{let{userId:r,deviceInfo:i}=e;const o=i.deviceId,a={algorithm:p.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.k]:Object(l.v4)()};n.batch.push({userId:r,deviceId:o,payload:a}),await p.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[r,[i]]])),await p.encryptMessageForDevice(a.ciphertext,this.userId,this.deviceId,this.olmDevice,r,i,t)}))),n.batch=n.batch.filter((e=>Object.keys(e.payload.ciphertext).length>0||(d.a.log(`No ciphertext for device ${e.userId}:${e.deviceId}: pruning`),!1)));try{await this.baseApis.queueToDevice(n)}catch(e){throw d.a.error("sendToDevice failed",e),e}}catch(e){throw d.a.error("encryptAndSendToDevices promises failed",e),e}}async preprocessToDeviceMessages(e){return e.filter((e=>{var t;return!(e.type===c.b.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes(null===(t=e.content)||void 0===t?void 0:t.algorithm))||(d.a.log("Ignoring invalid encrypted to-device event from "+e.sender),!1)}))}onRoomKeyEvent(e){const t=e.getContent();if(!t.room_id||!t.algorithm)return void d.a.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 d.a.error("key withheld event is missing fields");d.a.info(`Got room key withheld event from ${e.getSender()} for ${t.algorithm} session ${t.sender_key}|${t.session_id} in room ${t.room_id} with code ${t.code} (${t.reason})`);const 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(!D.a.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.toDeviceVerificationRequests,(e=>{if(!D.a.canCreateRequest(D.a.getEventType(e)))return;const t=e.getContent(),n=t&&t.from_device;if(!n)return;const r=e.getSender(),i=new D.a(this.baseApis,r,[n]);return new x.k(i,this.verificationMethods,this.baseApis)}))}async handleVerificationEvent(e,t,n){let r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];if(e.isSending()&&e.status!=P.a.SENT){let t,n;try{await new Promise(((r,i)=>{t=r,n=()=>{e.status==P.a.CANCELLED&&i(new Error("Event status set to CANCELLED."))},e.once(P.c.LocalEventIdReplaced,t),e.on(P.c.Status,n)}))}catch(e){return void d.a.error("error while waiting for the verification event to be sent: ",e)}finally{e.removeListener(P.c.LocalEventIdReplaced,t),e.removeListener(P.c.Status,n)}}let i=t.getRequest(e),o=!1;if(!i){if(i=n(e),!i)return void d.a.log(`Crypto: could not find VerificationRequest for ${e.getType()}, and could not create one, so ignoring.`);o=!0,t.setRequest(e,i)}e.setVerificationRequest(i);try{await i.channel.handleEvent(e,i,r)}catch(e){d.a.error("error while handling verification event",e)}o&&!i.initiatedByMe&&!i.invalid&&!i.observeOnly&&this.baseApis.emit($.VerificationRequest,i)}async onToDeviceBadEncrypted(e){const t=e.getWireContent(),n=e.getSender(),r=t.algorithm,i=t.sender_key;this.baseApis.emit(L.b.UndecryptableToDeviceEvent,e);const o=()=>{const e=this.getRoomDecryptors(p.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(i)};if(void 0===n||void 0===i||void 0===i)return;const a=this.lastNewSessionForced.getOrCreate(n),s=a.getOrCreate(i);if(s+36e5>Date.now())return d.a.debug("New session already forced with device "+n+":"+i+" at "+s+": not forcing another"),await this.olmDevice.recordSessionProblem(i,"wedged",!0),void o();let u=this.deviceList.getDeviceByIdentityKey(r,i);if(!u&&(await this.downloadKeys([n],!1),u=this.deviceList.getDeviceByIdentityKey(r,i),!u))return d.a.info("Couldn't find device for identity key "+i+": not re-establishing session"),await this.olmDevice.recordSessionProblem(i,"wedged",!1),void o();const h=new Map([[n,[u]]]);await p.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,h,!0),a.set(i,Date.now());const m={algorithm:p.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.k]:Object(l.v4)()};await p.encryptMessageForDevice(m.ciphertext,this.userId,this.deviceId,this.olmDevice,n,u,{type:"m.dummy"}),await this.olmDevice.recordSessionProblem(i,"wedged",!0),o(),await this.baseApis.sendToDevice("m.room.encrypted",new Map([[n,new Map([[u.deviceId,m]])]]));const g=await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,u.deviceId);for(const e of g)this.requestRoomKey(e.requestBody,e.recipients,!0)}onRoomMembership(e,t,n){const r=t.roomId,i=this.roomEncryptors.get(r);if(i){var o;if(r in this.roomDeviceTrackingState)"join"==t.membership?(d.a.log("Join event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&null!==(o=this.clientStore.getRoom(r))&&void 0!==o&&o.shouldEncryptForInvitedMembers()&&(d.a.log("Invite event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId));i.onRoomMembership(e,t,n)}}onRoomKeyRequestEvent(e){const t=e.getContent();if("request"===t.action){const t=new Y(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new Q(e);this.receivedRoomKeyRequestCancellations.push(t)}}async processReceivedRoomKeyRequests(){if(!this.processingRoomKeyRequests){this.processingRoomKeyRequests=!0;try{const e=this.receivedRoomKeyRequests;this.receivedRoomKeyRequests=[];const t=this.receivedRoomKeyRequestCancellations;this.receivedRoomKeyRequestCancellations=[],await Promise.all(e.map((e=>this.processReceivedRoomKeyRequest(e)))),await Promise.all(t.map((e=>this.processReceivedRoomKeyRequestCancellation(e))))}catch(e){d.a.error(`Error processing room key requsts: ${e}`)}finally{this.processingRoomKeyRequests=!1}}}async processReceivedRoomKeyRequest(e){const t=e.userId,n=e.deviceId,r=e.requestBody,i=r.room_id,o=r.algorithm;if(d.a.log(`m.room_key_request from ${t}:${n} for ${i} / ${r.session_id} (id ${e.requestId})`),t!==this.userId){if(!this.roomEncryptors.get(i))return void d.a.debug(`room key request for unencrypted room ${i}`);const e=this.roomEncryptors.get(i),o=this.deviceList.getStoredDevice(t,n);if(!o)return void d.a.debug(`Ignoring keyshare for unknown device ${t}:${n}`);try{await e.reshareKeyWithDevice(r.sender_key,r.session_id,t,o)}catch(e){d.a.warn("Failed to re-share keys for session "+r.session_id+" with device "+t+":"+o.deviceId,e)}return}if(n===this.deviceId)return void d.a.log("Ignoring room key request from ourselves");if(!this.roomDecryptors.has(i))return void d.a.log(`room key request for unencrypted room ${i}`);const a=this.roomDecryptors.get(i).get(o);if(a)if(await a.hasKeysForKeyRequest(e)){if(e.share=()=>{a.shareKeysWithDevice(e)},this.checkDeviceTrust(t,n).isVerified())return d.a.log("device is already verified: sharing keys"),void e.share();this.emit($.RoomKeyRequest,e)}else d.a.log(`room key request for unknown session ${i} / `+r.session_id);else d.a.log(`room key request for unknown alg ${o} in room ${i}`)}async processReceivedRoomKeyRequestCancellation(e){d.a.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit($.RoomKeyRequestCancellation,e)}getRoomDecryptor(e,t){let n,r;if(e&&(n=this.roomDecryptors.get(e),n||(n=new Map,this.roomDecryptors.set(e,n)),r=n.get(t),r))return r;const i=f.a.get(t);if(!i)throw new f.b("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return r=new i({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:null!=e?e:void 0}),n&&n.set(t,r),r}getRoomDecryptors(e){const t=[];for(const n of this.roomDecryptors.values())n.has(e)&&t.push(n.get(e));return t}async signObject(e){const t=new Map(Object.entries(e.signatures||{})),n=e.unsigned;delete e.signatures,delete e.unsigned;const r=t.get(this.userId)||{};t.set(this.userId,r),r["ed25519:"+this.deviceId]=await this.olmDevice.sign(s.a.stringify(e)),e.signatures=Object(j.F)(t),void 0!==n&&(e.unsigned=n)}}function W(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return p.encodeBase64(t)}class Y{constructor(e){o()(this,"userId",void 0),o()(this,"deviceId",void 0),o()(this,"requestId",void 0),o()(this,"requestBody",void 0),o()(this,"share",void 0);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")}}}class Q{constructor(e){o()(this,"userId",void 0),o()(this,"deviceId",void 0),o()(this,"requestId",void 0);const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}}).call(this,n(14),n(53).Buffer)},function(e,t,n){"use strict";var r=n(13),i=n.n(r),o=n(132),a=n.n(o),s=n(120),l=n.n(s),c=n(126),u=n.n(c);const d=["size","className","children"];function h(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function p(e){for(var t=1;t{let{size:t,className:n,children:r}=e,i=a()(e,d);return l.a.createElement(t||"h1",p(p({},i),{},{className:u()(`mx_Heading_${t}`,n),children:r}))}},function(e,t,n){"use strict";n.d(t,"d",(function(){return _})),n.d(t,"a",(function(){return b})),n.d(t,"b",(function(){return v})),n.d(t,"c",(function(){return y}));var r=n(130),i=n.n(r),o=n(132),a=n.n(o),s=n(120),l=n.n(s),c=n(126),u=n.n(c),d=n(150),h=n(121);const p=["label","iconClassName","active","className"],m=["label","iconClassName","active","className","words"],g=["label","className","iconClassName","children","isDestructive"],f=["className","children","compact"],_=e=>{let{label:t,iconClassName:n,active:r,className:o}=e,s=a()(e,p);return l.a.createElement(d.f,i()({},s,{className:u()(o,{mx_IconizedContextMenu_item:!0,mx_IconizedContextMenu_active:r}),active:r,label:t}),n&&l.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",n)}),l.a.createElement("span",{className:"mx_IconizedContextMenu_label"},t),r&&l.a.createElement("span",{className:"mx_IconizedContextMenu_icon mx_IconizedContextMenu_checked"}))},b=e=>{let t,{label:n,iconClassName:r,active:o,className:s,words:c}=e,p=a()(e,m);return t=c?l.a.createElement("span",{className:"mx_IconizedContextMenu_activeText"},o?Object(h.a)("On"):Object(h.a)("Off")):l.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",{mx_IconizedContextMenu_checked:o,mx_IconizedContextMenu_unchecked:!o})}),l.a.createElement(d.e,i()({},p,{className:u()(s,{mx_IconizedContextMenu_item:!0,mx_IconizedContextMenu_active:o}),active:o,label:n}),l.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",r)}),l.a.createElement("span",{className:"mx_IconizedContextMenu_label"},n),t)},v=e=>{let{label:t,className:n,iconClassName:r,children:o,isDestructive:s}=e,c=a()(e,g);return l.a.createElement(d.d,i()({},c,{className:u()(n,{mx_IconizedContextMenu_item:!0,mx_IconizedContextMenu_itemDestructive:s}),label:t}),r&&l.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",r)}),l.a.createElement("span",{className:"mx_IconizedContextMenu_label"},t),o)},y=e=>{let{first:t,red:n,className:r,label:i,children:o}=e;const a=u()("mx_IconizedContextMenu_optionList",r,{mx_IconizedContextMenu_optionList_notFirst:!t,mx_IconizedContextMenu_optionList_red:n});return l.a.createElement("div",{className:a},i&&l.a.createElement("div",null,l.a.createElement("span",{className:"mx_IconizedContextMenu_optionList_label"},i)),o)};t.e=e=>{let{className:t,children:n,compact:r}=e,o=a()(e,f);const s=u()("mx_IconizedContextMenu",t,{mx_IconizedContextMenu_compact:r});return l.a.createElement(d.n,i()({chevronFace:d.a.None},o),l.a.createElement("div",{className:s},n))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return g})),n.d(t,"b",(function(){return f}));var r=n(130),i=n.n(r),o=n(132),a=n.n(o),s=n(13),l=n.n(s),c=n(120),u=n.n(c),d=n(223),h=n(126),p=n.n(h);const m=["children","className","kind","inputRef"];let g;!function(e){e.Solid="solid",e.Outline="outline"}(g||(g={}));class f extends u.a.PureComponent{constructor(e){super(e),l()(this,"id",void 0),this.id=this.props.id||"checkbox_"+Object(d.b)(10)}render(){const e=this.props,{children:t,className:n,kind:r=g.Solid,inputRef:o}=e,s=a()(e,m),l=p()("mx_Checkbox",n,{mx_Checkbox_hasKind:r,[`mx_Checkbox_kind_${r}`]:r});return u.a.createElement("span",{className:l},u.a.createElement("input",i()({ref:o,id:this.id},s,{type:"checkbox"})),u.a.createElement("label",{htmlFor:this.id},u.a.createElement("div",{className:"mx_Checkbox_background"},u.a.createElement("div",{className:"mx_Checkbox_checkmark"})),!!this.props.children&&u.a.createElement("div",null,this.props.children)))}}l()(f,"defaultProps",{className:""})},function(e,t,n){"use strict";n.d(t,"b",(function(){return V})),n.d(t,"a",(function(){return W}));var r=n(13),i=n.n(r),o=n(149),a=n(129),s=n(140),l=n(147),c=n(1),u=n(151),d=n(202),h=n(124),p=n(226),m=n(125),g=n(164),f=n(197),_=n(146),b=n(278),v=n(190);class y extends b.a{constructor(e){super(),this.getRoomFn=e,i()(this,"rooms",[]),i()(this,"states",{}),i()(this,"onRoomNotificationStateUpdate",(()=>{this.calculateTotalState()}))}get symbol(){return this._color===f.a.Unsent?"!":null}setRooms(e){const t=this.rooms,n=Object(_.a)(t,e);this.rooms=e;for(const e of n.removed){const t=this.states[e.roomId];t&&(delete this.states[e.roomId],t.off(b.b.Update,this.onRoomNotificationStateUpdate))}for(const e of n.added){const t=this.getRoomFn(e);t.on(b.b.Update,this.onRoomNotificationStateUpdate),this.states[e.roomId]=t}this.calculateTotalState()}getFirstRoomWithNotifications(){var e;return null===(e=Object.values(this.states).find((e=>e.color>=this.color)))||void 0===e?void 0:e.room.roomId}destroy(){super.destroy();for(const e of Object.values(this.states))e.off(b.b.Update,this.onRoomNotificationStateUpdate);this.states={}}calculateTotalState(){const e=this.snapshot();this._count=0,this._color=f.a.None;for(const[e,t]of Object.entries(this.states)){p.c.instance.getTagsForRoom(this.rooms.find((t=>t.roomId===e))).includes(v.a.LowPriority)&&t.color===f.a.Bold||(this._count+=t.count,this._color=Math.max(this.color,t.color))}this.emitIfUpdated(e)}}var E=n(220),S=n(451),w=n(801),T=n(128),C=n(16);function x(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:C.a;const o=Math.min(Math.max(e.length,t.length),r),a=Object(C.c)(e,o,i),s=Object(C.c)(t,o,i),l=Object(C.P)(a,i),c=Object(C.P)(s,i);if(c-l-BigInt(1)Object(C.e)(d+BigInt(t)*u,i)))}const F=function(e,t,n){var r,i,o,a,s,l;let c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:50;if(t<0||n<0||t>e.length||n>e.length||t===n)return[];const u=e.map(((e,t)=>({index:t,order:e}))),d=Object(_.o)(u,t,n),h=void 0===(null===(r=d[n-1])||void 0===r?void 0:r.order);let p=n,m=n,g=!0;const f=void 0!==(null===(i=d[n+1])||void 0===i?void 0:i.order)?Object(C.P)(d[n+1].order):BigInt(Number.MAX_VALUE);for(let e=n-1,t=1;e>=0;e--,t++){var b;if(void 0!==(null===(b=d[e])||void 0===b?void 0:b.order)&&f-Object(C.P)(d[e].order)>t)break;p=e}const v=void 0===d[0].order?void 0:Object(C.P)(d[0].order),y=BigInt(n);0===p&&void 0!==v&&f-v<=y&&v<=y&&(g=!1);const E=!h;let S=E;if(E){var w;const e=void 0!==(null===(w=d[n-1])||void 0===w?void 0:w.order)?Object(C.P)(d[n-1].order):BigInt(Number.MIN_VALUE);for(let t=n+1,r=1;tr)break;m=t}m===d.length-1&&(d[m]?Object(C.P)(d[m].order):BigInt(Number.MAX_VALUE))-e<=m-n&&(S=!1)}const F=g?n-p:Number.MAX_SAFE_INTEGER,D=S?m-n:Number.MAX_SAFE_INTEGER;h||F({index:d[p+t].index,order:e})))};var D=n(933),k=n(208),O=n(389),I=n(242);const A=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;n.add(t);const r=e.get(t);return null==r||r.forEach((t=>{n.has(t)||A(e,t,n)})),n},R=(e,t,n)=>{const r=A(t,n),i=new Set;return r.forEach((t=>{const n=e.get(t);null==n||n.forEach(i.add,i)})),i},N=e=>function(t,n,r){if((!(arguments.length>3&&void 0!==arguments[3])||arguments[3])&&e.has(r))return e.get(r);const i=R(t,n,r);return e.set(r,i),i};var M=n(189),P=n(154);function L(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function B(e){for(var t=1;t`mx_space_context_${e}`,H=e=>e.reduce(((e,t)=>(e[t.isSpaceRoom()?0:1].push(t),e)),[[],[]]),q=e=>{if("string"==typeof e&&e.length<=50&&Array.from(e).every((e=>{const t=e.charCodeAt(0);return t>=32&&t<=126})))return e},V=(e,t,n)=>{var r;return[null!==(r=q(e))&&void 0!==r?r:NaN,t,n]},$=e=>E.a.instance.getRoomState(e);class K extends d.a{constructor(){var e;super(h.a,{}),e=this,i()(this,"rootSpaces",[]),i()(this,"parentMap",new S.a),i()(this,"notificationStateMap",new Map),i()(this,"roomIdsBySpace",new Map),i()(this,"childSpacesBySpace",new Map),i()(this,"userIdsBySpace",new Map),i()(this,"_aggregatedSpaceCache",{roomIdsBySpace:new Map,userIdsBySpace:new Map}),i()(this,"_activeSpace",k.a.Home),i()(this,"_suggestedRooms",[]),i()(this,"_invitedSpaces",new Set),i()(this,"spaceOrderLocalEchoMap",new Map),i()(this,"_allRoomsInHome",!1),i()(this,"_enabledMetaSpaces",[]),i()(this,"fetchSuggestedRooms",(async function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:G;try{const{rooms:r}=await e.matrixClient.getRoomHierarchy(t.roomId,n,1,!0),i=new S.a;return r.forEach((e=>{e.children_state.forEach((e=>{var t;e.type===a.b.SpaceChild&&null!==(t=e.content.via)&&void 0!==t&&t.length&&e.content.via.forEach((t=>{i.getOrCreate(e.state_key,new Set).add(t)}))}))})),r.filter((t=>{var n;return t.room_type!==a.j.Space&&"join"!==(null===(n=e.matrixClient.getRoom(t.room_id))||void 0===n?void 0:n.getMyMembership())})).map((e=>B(B({},e),{},{viaServers:Array.from(i.get(e.room_id)||[])})))}catch(e){c.a.error(e)}return[]})),i()(this,"getSpaceFilteredRoomIds",(function(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return t===k.a.Home&&e.allRoomsInHome?new Set(e.matrixClient.getVisibleRooms().map((e=>e.roomId))):!n||Object(k.h)(t)?e.roomIdsBySpace.get(t)||new Set:e.getAggregatedRoomIdsBySpace(e.roomIdsBySpace,e.childSpacesBySpace,t,r)})),i()(this,"getSpaceFilteredUserIds",(function(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!(t===k.a.Home&&e.allRoomsInHome||Object(k.h)(t)))return!n||Object(k.h)(t)?e.userIdsBySpace.get(t)||new Set:e.getAggregatedUserIdsBySpace(e.userIdsBySpace,e.childSpacesBySpace,t,r)})),i()(this,"getAggregatedRoomIdsBySpace",N(this._aggregatedSpaceCache.roomIdsBySpace)),i()(this,"getAggregatedUserIdsBySpace",N(this._aggregatedSpaceCache.userIdsBySpace)),i()(this,"markTreeChildren",((e,t)=>{const n=[e];for(;n.length;){const e=n.pop();t.delete(e),this.getChildSpaces(e.roomId).forEach((e=>{t.has(e)&&n.push(e)}))}})),i()(this,"findRootSpaces",(e=>{const t=new Set(e);e.forEach((e=>{this.getChildSpaces(e.roomId).forEach((e=>{t.delete(e)}))}));const n=Array.from(t),r=new Set(Object(o.sortBy)(e,(e=>e.roomId)));return n.forEach((e=>{this.markTreeChildren(e,r)})),Array.from(r).forEach((e=>{r.has(e)&&(n.push(e),this.markTreeChildren(e,r))})),n})),i()(this,"rebuildSpaceHierarchy",(()=>{const e=this.matrixClient.getVisibleRooms().filter((e=>e.isSpaceRoom())),[t,n]=e.reduce(((e,t)=>{let[n,r]=e;switch(Object(I.b)(t.getMyMembership())){case I.a.Join:n.push(t);break;case I.a.Invite:r.push(t)}return[n,r]}),[[],[]]),r=this.findRootSpaces(t),i=this.rootSpaces;this.rootSpaces=this.sortRootSpaces(r),this.onRoomsUpdate(),Object(_.e)(i,this.rootSpaces)&&this.emit(k.f,this.spacePanelSpaces,this.enabledMetaSpaces);const o=this._invitedSpaces;this._invitedSpaces=new Set(this.sortRootSpaces(n)),Object(w.b)(o,this._invitedSpaces)&&this.emit(k.c,this.invitedSpaces)})),i()(this,"rebuildParentMap",(()=>{const e=this.matrixClient.getVisibleRooms().filter((e=>e.isSpaceRoom()&&"join"===e.getMyMembership()));this.parentMap=new S.a,e.forEach((e=>{this.getChildren(e.roomId).forEach((t=>{this.parentMap.getOrCreate(t.roomId,new Set).add(e.roomId)}))})),M.a.instance.setProperty("numSpaces",e.length)})),i()(this,"rebuildHomeSpace",(()=>{if(this.allRoomsInHome)this.roomIdsBySpace.delete(k.a.Home);else{const e=new Set(this.matrixClient.getVisibleRooms().filter(this.showInHomeSpace).map((e=>e.roomId)));this.roomIdsBySpace.set(k.a.Home,e)}this.activeSpace===k.a.Home&&this.switchSpaceIfNeeded()})),i()(this,"rebuildMetaSpaces",(()=>{const e=new Set(this.enabledMetaSpaces),t=this.matrixClient.getVisibleRooms();if(e.has(k.a.Home)?this.rebuildHomeSpace():this.roomIdsBySpace.delete(k.a.Home),e.has(k.a.Favourites)){const e=t.filter((e=>e.tags[v.a.Favourite]));this.roomIdsBySpace.set(k.a.Favourites,new Set(e.map((e=>e.roomId))))}else this.roomIdsBySpace.delete(k.a.Favourites);if(e.has(k.a.Orphans)||e.has(k.a.Home)){const e=t.filter((e=>{var t;return!(null!==(t=this.parentMap.get(e.roomId))&&void 0!==t&&t.size||g.a.shared().getUserIdForRoomId(e.roomId))}));this.roomIdsBySpace.set(k.a.Orphans,new Set(e.map((e=>e.roomId))))}Object(k.h)(this.activeSpace)&&this.switchSpaceIfNeeded()})),i()(this,"updateNotificationStates",(e=>{const t=new Set(this.enabledMetaSpaces),n=this.matrixClient.getVisibleRooms();let r;t.has(k.a.People)?r=k.a.People:t.has(k.a.Home)&&(r=k.a.Home),e||(e=[...this.roomIdsBySpace.keys()],r===k.a.People&&e.push(k.a.People),t.has(k.a.Home)&&!this.allRoomsInHome&&e.push(k.a.Home)),e.forEach((e=>{if(this.allRoomsInHome&&e===k.a.Home)return;const t=this.getSpaceFilteredRoomIds(e,!0);this.getNotificationState(e).setRooms(n.filter((n=>e===k.a.People?this.isRoomInSpace(k.a.People,n.roomId):!(n.isSpaceRoom()||!t.has(n.roomId))&&(!r||!g.a.shared().getUserIdForRoomId(n.roomId)||e===r))))})),r!==k.a.People&&this.notificationStateMap.delete(k.a.People)})),i()(this,"showInHomeSpace",(e=>{var t;return!!this.allRoomsInHome||!e.isSpaceRoom()&&!(null!==(t=this.parentMap.get(e.roomId))&&void 0!==t&&t.size&&!g.a.shared().getUserIdForRoomId(e.roomId)&&"invite"!==e.getMyMembership())})),i()(this,"onMemberUpdate",((e,t)=>{const n=K.isInSpace(e.getMember(t));var r,i;n?null===(r=this.userIdsBySpace.get(e.roomId))||void 0===r||r.add(t):null===(i=this.userIdsBySpace.get(e.roomId))||void 0===i||i.delete(t);this._aggregatedSpaceCache.userIdsBySpace.clear();const o=this.getKnownParents(e.roomId,!0);this.emit(e.roomId),o.forEach((e=>this.emit(e))),n||this.switchSpaceIfNeeded()})),i()(this,"onRoomsUpdate",(()=>{const e=this.matrixClient.getVisibleRooms(),t=this.roomIdsBySpace,n=this.userIdsBySpace,r=this.childSpacesBySpace;this.roomIdsBySpace=new Map,this.userIdsBySpace=new Map,this.childSpacesBySpace=new Map,this.rebuildParentMap(),this.rebuildMetaSpaces();const i=new S.a;e.forEach((e=>{"join"===e.getMyMembership()&&this.getParents(e.roomId).forEach((t=>{i.getOrCreate(t.roomId,new Set).add(e.roomId)}))})),this.rootSpaces.forEach((e=>{const t=(e,n)=>{var r,o;if(n.has(e))return;if(this.roomIdsBySpace.has(e)&&this.userIdsBySpace.has(e))return[this.roomIdsBySpace.get(e),this.userIdsBySpace.get(e)];const[a,s]=H(this.getChildren(e));this.childSpacesBySpace.set(e,new Set(a.map((e=>e.roomId))));const l=new Set(s.map((e=>e.roomId))),c=null===(r=this.matrixClient)||void 0===r?void 0:r.getRoom(e),u=new Set(null==c?void 0:c.getMembers().filter((e=>"join"===e.membership||"invite"===e.membership)).map((e=>e.userId))),d=new Set(n).add(e);a.forEach((e=>{t(e.roomId,d)})),null===(o=i.get(e))||void 0===o||o.forEach((e=>{l.add(e)}));const h=new Set(Array.from(l).flatMap((e=>this.matrixClient.getRoomUpgradeHistory(e,!0).map((e=>e.roomId)))));return this.roomIdsBySpace.set(e,h),this.userIdsBySpace.set(e,u),[h,u]};t(e.roomId,new Set)}));const o=Object(S.b)(t,this.roomIdsBySpace),a=Object(S.b)(n,this.userIdsBySpace),s=Object(S.b)(r,this.childSpacesBySpace),l=o.changed.filter((e=>Object(w.b)(t.get(e),this.roomIdsBySpace.get(e)))),c=a.changed.filter((e=>Object(w.b)(n.get(e),this.userIdsBySpace.get(e)))),u=s.changed.filter((e=>Object(w.b)(r.get(e),this.childSpacesBySpace.get(e)))),d=new Set([...o.added,...a.added,...s.added,...o.removed,...a.removed,...s.removed,...l,...c,...u]);Array.from(d).flatMap((e=>[...this.getKnownParents(e,!0)])).forEach((e=>d.add(e))),this._aggregatedSpaceCache.roomIdsBySpace.clear(),this._aggregatedSpaceCache.userIdsBySpace.clear(),d.forEach((e=>{this.emit(e)})),d.has(this.activeSpace)&&this.switchSpaceIfNeeded();const h=[...d];this.enabledMetaSpaces.includes(k.a.People)&&a.added.length+a.removed.length+c.length>0&&h.push(k.a.People),this.updateNotificationStates(h)})),i()(this,"switchSpaceIfNeeded",(function(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:P.b.instance.roomViewStore.getRoomId();e.isRoomInSpace(e.activeSpace,n)||null!==(t=e.matrixClient.getRoom(n))&&void 0!==t&&t.isSpaceRoom()||e.switchToRelatedSpace(n)})),i()(this,"switchToRelatedSpace",(e=>{var t;if(this.suggestedRooms.find((t=>t.room_id===e)))return;let n=null===(t=this.getCanonicalParent(e))||void 0===t?void 0:t.roomId;var r;n||(n=null===(r=this.rootSpaces.find((t=>this.isRoomInSpace(t.roomId,e))))||void 0===r?void 0:r.roomId);n||(n=[...this.enabledMetaSpaces].reverse().find((t=>this.isRoomInSpace(t,e)))),n?this.setActiveSpace(n,!1):this.goToFirstSpace()})),i()(this,"onRoom",((e,t,n)=>{const r=e.getMyMembership();if(!r)return;const i=t||r;if(e.isSpaceRoom()){if("invite"===i){const t=this._invitedSpaces.size;this._invitedSpaces.add(e),t!==this._invitedSpaces.size&&this.emit(k.c,this.invitedSpaces)}else if("invite"===n&&"join"!==i)this._invitedSpaces.delete(e)&&this.emit(k.c,this.invitedSpaces);else{var o;this.rebuildSpaceHierarchy(),null===(o=this.parentMap.get(e.roomId))||void 0===o||o.forEach((e=>{this.emit(e)})),this.emit(e.roomId)}"join"===i&&e.roomId===P.b.instance.roomViewStore.getRoomId()?this.setActiveSpace(e.roomId,!1):"leave"===i&&e.roomId===this.activeSpace&&this.goToFirstSpace(!0)}else if(this.onRoomsUpdate(),"join"===i){const n=this._suggestedRooms.length;this._suggestedRooms=this._suggestedRooms.filter((t=>t.room_id!==e.roomId)),n!==this._suggestedRooms.length&&this.emit(k.e,this._suggestedRooms),"join"===t&&e.roomId===P.b.instance.roomViewStore.getRoomId()&&this.switchSpaceIfNeeded(e.roomId)}})),i()(this,"onRoomState",(e=>{const t=this.matrixClient.getRoom(e.getRoomId());if(t)switch(e.getType()){case a.b.SpaceChild:{const n=this.matrixClient.getRoom(e.getStateKey());t.isSpaceRoom()&&(null!=n&&n.isSpaceRoom()?(this.rebuildSpaceHierarchy(),this.emit(n.roomId)):this.onRoomsUpdate(),this.emit(t.roomId)),t.roomId===this.activeSpace&&"join"!==(null==n?void 0:n.getMyMembership())&&e.getPrevContent().suggested!==e.getContent().suggested&&this.loadSuggestedRooms(t);break}case a.b.SpaceParent:t.isSpaceRoom()?this.rebuildSpaceHierarchy():this.onRoomsUpdate(),this.emit(t.roomId);break;case a.b.RoomPowerLevels:t.isSpaceRoom()&&this.onRoomsUpdate()}})),i()(this,"onRoomStateMembers",(e=>{const t=this.matrixClient.getRoom(e.getRoomId()),n=e.getStateKey();null!=t&&t.isSpaceRoom()&&g.a.shared().getDMRoomsForUserId(n).length>0&&e.getPrevContent().membership!==e.getContent().membership&&this.onMemberUpdate(t,n)})),i()(this,"onRoomAccountData",((e,t,n)=>{if(t.isSpaceRoom()&&e.getType()===a.b.SpaceOrder){var r,i;this.spaceOrderLocalEchoMap.delete(t.roomId);(null===(r=e.getContent())||void 0===r?void 0:r.order)!==(null==n||null===(i=n.getContent())||void 0===i?void 0:i.order)&&this.notifyIfOrderChanged()}else if(e.getType()===a.b.Tag){var o,s;const r=(null==n||null===(o=n.getContent())||void 0===o?void 0:o.tags)||{},i=(null===(s=e.getContent())||void 0===s?void 0:s.tags)||{};!!r[v.a.Favourite]!=!!i[v.a.Favourite]&&this.onRoomFavouriteChange(t)}})),i()(this,"onAccountData",((e,t)=>{if(e.getType()===a.b.Direct){var n;const r=new Set(Object.values(null!==(n=null==t?void 0:t.getContent())&&void 0!==n?n:{}).flat()),i=new Set(Object.values(e.getContent()).flat()),o=Object(w.a)(r,i);[...o.added,...o.removed].forEach((e=>{var t;const n=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(e);n&&this.onRoomDmChange(n,i.has(e))})),o.removed.length>0&&this.switchSpaceIfNeeded()}})),i()(this,"getSpaceTagOrdering",(e=>{var t,n;return this.spaceOrderLocalEchoMap.has(e.roomId)?this.spaceOrderLocalEchoMap.get(e.roomId):q(null===(t=e.getAccountData(a.b.SpaceOrder))||void 0===t||null===(n=t.getContent())||void 0===n?void 0:n.order)})),m.b.monitorSetting("Spaces.allRoomsInHome",null),m.b.monitorSetting("Spaces.enabledMetaSpaces",null),m.b.monitorSetting("Spaces.showPeopleInSpace",null)}get invitedSpaces(){return Array.from(this._invitedSpaces)}get enabledMetaSpaces(){return this._enabledMetaSpaces}get spacePanelSpaces(){return this.rootSpaces}get activeSpace(){return this._activeSpace}get activeSpaceRoom(){var e;return Object(k.h)(this._activeSpace)?null:null===(e=this.matrixClient)||void 0===e?void 0:e.getRoom(this._activeSpace)}get suggestedRooms(){return this._suggestedRooms}get allRoomsInHome(){return this._allRoomsInHome}setActiveRoomInSpace(e){var t,n;if(Object(k.h)(e)||null!==(t=this.matrixClient)&&void 0!==t&&null!==(n=t.getRoom(e))&&void 0!==n&&n.isSpaceRoom())if(e!==this.activeSpace&&this.setActiveSpace(e,!1),e){const t=this.getNotificationState(e).getFirstRoomWithNotifications();h.a.dispatch({action:T.a.ViewRoom,room_id:t,context_switch:!0,metricsTrigger:"WebSpacePanelNotificationBadge"})}else{const e=p.c.instance.orderedLists;for(let t=0;t{if(this.showInHomeSpace(e)){return E.a.instance.getRoomState(e).isUnread}}));if(n){h.a.dispatch({action:T.a.ViewRoom,room_id:n.roomId,context_switch:!0,metricsTrigger:"WebSpacePanelNotificationBadge"});break}}}}setActiveSpace(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!e||!this.matrixClient||e===this.activeSpace)return;let n=null;var r;if(Object(k.h)(e)){if(!this.enabledMetaSpaces.includes(e))return}else if(n=this.matrixClient.getRoom(e),null===(r=n)||void 0===r||!r.isSpaceRoom())return;if(window.localStorage.setItem(U,this._activeSpace=e),t){var i,o;const t=window.localStorage.getItem(z(e));t&&"invite"!==(null===(i=n)||void 0===i?void 0:i.getMyMembership())&&"join"===(null===(o=this.matrixClient.getRoom(t))||void 0===o?void 0:o.getMyMembership())&&this.isRoomInSpace(e,t)?h.a.dispatch({action:T.a.ViewRoom,room_id:t,context_switch:!0,metricsTrigger:"WebSpaceContextSwitch"}):n?h.a.dispatch({action:T.a.ViewRoom,room_id:e,context_switch:!0,metricsTrigger:"WebSpaceContextSwitch"}):h.a.dispatch({action:T.a.ViewHomePage,context_switch:!0})}this.emit(k.d,this.activeSpace),this.emit(k.e,this._suggestedRooms=[]),n&&(this.loadSuggestedRooms(n),W.instance.traverseSpace(e,(e=>{var t;null===(t=this.matrixClient.getRoom(e))||void 0===t||t.loadMembersIfNeeded()}),!1))}async loadSuggestedRooms(e){const t=await this.fetchSuggestedRooms(e);this._activeSpace===e.roomId&&(this._suggestedRooms=t,this.emit(k.e,this._suggestedRooms))}addRoomToSpace(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return this.matrixClient.sendStateEvent(e.roomId,a.b.SpaceChild,{via:n,suggested:r},t)}getChildren(e){var t;const n=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(e),r=null==n?void 0:n.currentState.getStateEvents(a.b.SpaceChild).filter((e=>{var t;return null===(t=e.getContent())||void 0===t?void 0:t.via}));return Object(o.sortBy)(r,(e=>V(e.getContent().order,e.getTs(),e.getStateKey()))).map((e=>{const t=this.matrixClient.getRoomUpgradeHistory(e.getStateKey(),!0);return t[t.length-1]})).filter((e=>"join"===(null==e?void 0:e.getMyMembership())||"invite"===(null==e?void 0:e.getMyMembership())))||[]}getChildRooms(e){return this.getChildren(e).filter((e=>!e.isSpaceRoom()))}getChildSpaces(e){return this.getChildren(e).filter((e=>e.isSpaceRoom()&&"join"===e.getMyMembership()))}getParents(e){var t,n,r;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const o=null===(t=this.matrixClient)||void 0===t?void 0:t.getUserId(),s=null===(n=this.matrixClient)||void 0===n?void 0:n.getRoom(e),l=null!==(r=null==s?void 0:s.currentState.getStateEvents(a.b.SpaceParent))&&void 0!==r?r:[];return Object(_.n)(l.map((t=>{const n=t.getContent();if(!Array.isArray(n.via)||i&&!n.canonical)return;const r=this.matrixClient.getRoom(t.getStateKey()),s=null==r?void 0:r.currentState.getStateEvents(a.b.SpaceChild,e);return null==r||!r.currentState.maySendStateEvent(a.b.SpaceChild,o)||s&&!Array.isArray(s.getContent().via)?void 0:r})))}getCanonicalParent(e){var t;const n=this.getParents(e,!0);return(null===(t=Object(o.sortBy)(n,(e=>e.roomId)))||void 0===t?void 0:t[0])||null}getKnownParents(e,t){return t?R(this.parentMap,this.parentMap,e):this.parentMap.get(e)||new Set}isRoomInSpace(e,t){var n,r;let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(e===k.a.Home&&this.allRoomsInHome)return!0;if(null!==(n=this.getSpaceFilteredRoomIds(e,i))&&void 0!==n&&n.has(t))return!0;const o=g.a.shared().getUserIdForRoomId(t);return!!o&&(e===k.a.Home||e===k.a.People||!(Object(k.h)(e)||null===(r=this.getSpaceFilteredUserIds(e,i))||void 0===r||!r.has(o)||!m.b.getValue("Spaces.showPeopleInSpace",e)))}static isInSpace(e){return"join"===(null==e?void 0:e.membership)||"invite"===(null==e?void 0:e.membership)}notifyIfOrderChanged(){const e=this.sortRootSpaces(this.rootSpaces);Object(_.e)(this.rootSpaces,e)&&(this.rootSpaces=e,this.emit(k.f,this.spacePanelSpaces,this.enabledMetaSpaces))}onRoomFavouriteChange(e){this.enabledMetaSpaces.includes(k.a.Favourites)&&(e.tags[v.a.Favourite]?this.roomIdsBySpace.get(k.a.Favourites).add(e.roomId):this.roomIdsBySpace.get(k.a.Favourites).delete(e.roomId),this.emit(k.a.Favourites))}onRoomDmChange(e,t){const n=new Set(this.enabledMetaSpaces);if(!this.allRoomsInHome&&n.has(k.a.Home)){const t=this.roomIdsBySpace.get(k.a.Home);if(this.showInHomeSpace(e))null==t||t.add(e.roomId);else if(!this.roomIdsBySpace.get(k.a.Orphans).has(e.roomId)){var r;null===(r=this.roomIdsBySpace.get(k.a.Home))||void 0===r||r.delete(e.roomId)}this.emit(k.a.Home)}n.has(k.a.People)&&this.emit(k.a.People),(n.has(k.a.Orphans)||n.has(k.a.Home))&&t&&this.roomIdsBySpace.get(k.a.Orphans).delete(e.roomId)&&(this.emit(k.a.Orphans),this.emit(k.a.Home))}async reset(){this.rootSpaces=[],this.parentMap=new S.a,this.notificationStateMap=new Map,this.roomIdsBySpace=new Map,this.userIdsBySpace=new Map,this._aggregatedSpaceCache.roomIdsBySpace.clear(),this._aggregatedSpaceCache.userIdsBySpace.clear(),this._activeSpace=k.a.Home,this._suggestedRooms=[],this._invitedSpaces=new Set,this._enabledMetaSpaces=[]}async onNotReady(){this.matrixClient&&(this.matrixClient.removeListener(l.b.Room,this.onRoom),this.matrixClient.removeListener(s.d.MyMembership,this.onRoom),this.matrixClient.removeListener(s.d.AccountData,this.onRoomAccountData),this.matrixClient.removeListener(u.b.Events,this.onRoomState),this.matrixClient.removeListener(u.b.Members,this.onRoomStateMembers),this.matrixClient.removeListener(l.b.AccountData,this.onAccountData)),await this.reset()}async onReady(){this.matrixClient.on(l.b.Room,this.onRoom),this.matrixClient.on(s.d.MyMembership,this.onRoom),this.matrixClient.on(s.d.AccountData,this.onRoomAccountData),this.matrixClient.on(u.b.Events,this.onRoomState),this.matrixClient.on(u.b.Members,this.onRoomStateMembers),this.matrixClient.on(l.b.AccountData,this.onAccountData);const e=this._enabledMetaSpaces,t=m.b.getValue("Spaces.enabledMetaSpaces");this._enabledMetaSpaces=j.filter((e=>t[e])),this._allRoomsInHome=m.b.getValue("Spaces.allRoomsInHome"),this.sendUserProperties(),this.rebuildSpaceHierarchy(),Object(_.d)(e,this._enabledMetaSpaces)&&this.emit(k.f,this.spacePanelSpaces,this.enabledMetaSpaces);const n=window.localStorage.getItem(U);n&&(Object(k.h)(n)?t[n]:this.matrixClient.getRoom(n))?this.setActiveSpace(n,!1):this.switchSpaceIfNeeded()}sendUserProperties(){const e=new Set(this.enabledMetaSpaces);M.a.instance.setProperty("WebMetaSpaceHomeEnabled",e.has(k.a.Home)),M.a.instance.setProperty("WebMetaSpaceHomeAllRooms",this.allRoomsInHome),M.a.instance.setProperty("WebMetaSpacePeopleEnabled",e.has(k.a.People)),M.a.instance.setProperty("WebMetaSpaceFavouritesEnabled",e.has(k.a.Favourites)),M.a.instance.setProperty("WebMetaSpaceOrphansEnabled",e.has(k.a.Orphans))}goToFirstSpace(){var e,t;let n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.setActiveSpace(null!==(e=this.enabledMetaSpaces[0])&&void 0!==e?e:null===(t=this.spacePanelSpaces[0])||void 0===t?void 0:t.roomId,n)}async onAction(e){if(this.matrixClient)switch(e.action){case T.a.ViewRoom:{var t;const n=(null===(t=e.justCreatedOpts)||void 0===t?void 0:t.roomType)===a.j.Space;if(e.context_switch||e.justCreatedOpts&&!n)break;let r=e.room_id;if(e.room_alias&&!r&&(r=Object(O.a)(e.room_alias)),!r)return;const i=this.matrixClient.getRoom(r);null!=i&&i.isSpaceRoom()?this.setActiveSpace(i.roomId,!1):this.switchSpaceIfNeeded(r),window.localStorage.setItem(z(this.activeSpace),e.room_id);break}case T.a.ViewHomePage:!e.context_switch&&this.enabledMetaSpaces.includes(k.a.Home)&&(this.setActiveSpace(k.a.Home,!1),window.localStorage.setItem(z(this.activeSpace),""));break;case T.a.AfterLeaveRoom:Object(k.h)(this._activeSpace)||e.room_id!==this._activeSpace||this.goToFirstSpace(!0);break;case T.a.SwitchSpace:{if(e.num<1||e.num>9)break;const t=this.enabledMetaSpaces.length;e.num<=t?this.setActiveSpace(this.enabledMetaSpaces[e.num-1]):this.spacePanelSpaces.length>e.num-t-1&&this.setActiveSpace(this.spacePanelSpaces[e.num-t-1].roomId);break}case T.a.SettingUpdated:switch(e.settingName){case"Spaces.allRoomsInHome":{const e=m.b.getValue("Spaces.allRoomsInHome");this.allRoomsInHome!==e&&(this._allRoomsInHome=e,this.emit(k.b,this.allRoomsInHome),this.enabledMetaSpaces.includes(k.a.Home)&&this.rebuildHomeSpace(),this.sendUserProperties());break}case"Spaces.enabledMetaSpaces":{const e=m.b.getValue("Spaces.enabledMetaSpaces"),t=j.filter((t=>e[t]));if(Object(_.d)(this._enabledMetaSpaces,t)){const n=this.enabledMetaSpaces.some((e=>e===k.a.Home||e===k.a.People));this._enabledMetaSpaces=t;const r=this.enabledMetaSpaces.some((e=>e===k.a.Home||e===k.a.People));Object(k.h)(this.activeSpace)&&!e[this.activeSpace]&&this.switchSpaceIfNeeded(),this.rebuildMetaSpaces(),n!==r?this.updateNotificationStates():this.updateNotificationStates(t),this.emit(k.f,this.spacePanelSpaces,this.enabledMetaSpaces),this.sendUserProperties()}break}case"Spaces.showPeopleInSpace":this.emit(e.roomId),this.enabledMetaSpaces.some((e=>e===k.a.Home||e===k.a.People))||this.updateNotificationStates([e.roomId])}}}getNotificationState(e){if(this.notificationStateMap.has(e))return this.notificationStateMap.get(e);const t=new y($);return this.notificationStateMap.set(e,t),t}traverseSpace(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0;if(r&&r.has(e))return;t(e);const i=new Set(r).add(e),[o,a]=H(this.getChildren(e));n&&a.forEach((e=>t(e.roomId))),o.forEach((e=>this.traverseSpace(e.roomId,t,n,i)))}sortRootSpaces(e){return Object(o.sortBy)(e,[this.getSpaceTagOrdering,"roomId"])}async setRootSpaceOrder(e,t){this.spaceOrderLocalEchoMap.set(e.roomId,t);try{await this.matrixClient.setRoomAccountData(e.roomId,a.b.SpaceOrder,{order:t})}catch(n){c.a.warn("Failed to set root space order",n),this.spaceOrderLocalEchoMap.get(e.roomId)===t&&this.spaceOrderLocalEchoMap.delete(e.roomId)}}moveRootSpace(e,t){const n=this.rootSpaces.map(this.getSpaceTagOrdering);F(n,e,t).forEach((e=>{let{index:t,order:n}=e;this.setRootSpaceOrder(this.rootSpaces[t],n)})),this.notifyIfOrderChanged()}}class W{static get instance(){return W.internalInstance}}i()(W,"internalInstance",(()=>{const e=new K;return e.start(),e})()),window.mxSpaceStore=W.instance},function(e,t,n){"use strict";n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return c}));var r=n(13),i=n.n(r),o=n(1),a=n(151),s=n(129);let l;!function(e){e.Backward="b",e.Forward="f"}(l||(l={}));class c{static setEventMetadata(e,t,n){var r,i,o,a;null!==(r=e.sender)&&void 0!==r&&null!==(i=r.events)&&void 0!==i&&i.member||(e.sender=t.getSentinelMember(e.getSender())),null!==(o=e.target)&&void 0!==o&&null!==(a=o.events)&&void 0!==a&&a.member||e.getType()!==s.b.RoomMember||(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}constructor(e){var t,n;this.eventTimelineSet=e,i()(this,"roomId",void 0),i()(this,"name",void 0),i()(this,"events",[]),i()(this,"baseIndex",0),i()(this,"startState",void 0),i()(this,"endState",void 0),i()(this,"startToken",null),i()(this,"endToken",null),i()(this,"prevTimeline",null),i()(this,"nextTimeline",null),i()(this,"paginationRequests",{[l.Backward]:null,[l.Forward]:null}),this.roomId=null!==(t=null===(n=e.room)||void 0===n?void 0:n.roomId)&&void 0!==t?t:null,this.roomId&&(this.startState=new a.a(this.roomId),this.endState=new a.a(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}initialiseState(e){var t,n;let{timelineWasEmpty:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.events.length>0)throw new Error("Cannot initialise state after events are added");null===(t=this.startState)||void 0===t||t.setStateEvents(e,{timelineWasEmpty:r}),null===(n=this.endState)||void 0===n||n.setStateEvents(e,{timelineWasEmpty:r})}forkLive(e){const t=this.getState(e),n=new c(this.eventTimelineSet);return n.startState=null==t?void 0:t.clone(),n.endState=t,this.endState=null==t?void 0:t.clone(),n}fork(e){const t=this.getState(e),n=new c(this.eventTimelineSet);return n.startState=null==t?void 0:t.clone(),n.endState=null==t?void 0: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==c.BACKWARDS)return this.startState;if(e==c.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===l.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===l.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==c.BACKWARDS)return this.prevTimeline;if(e==c.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==c.BACKWARDS)this.prevTimeline=e;else{if(t!=c.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t,n){let r,i=!!t;"object"==typeof t?({toStartOfTimeline:i,roomState:n,timelineWasEmpty:r}=t):void 0!==t&&o.a.warn("Overload deprecated: `EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"),n||(n=i?this.startState:this.endState);const a=this.getTimelineSet();var l;a.room&&(c.setEventMetadata(e,n,i),e.isState()&&a.room.getUnfilteredTimelineSet()===a&&(null===(l=n)||void 0===l||l.setStateEvents([e],{timelineWasEmpty:r}),e.sender&&(e.getType()!==s.b.RoomMember||i)||c.setEventMetadata(e,n,i)));let u;u=i?0:this.events.length,this.events.splice(u,0,e),i&&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(null===S&&(S=h.b.getValue("feature_msc3531_hide_messages_pending_moderation")),S);function T(e,t){var n,r;if(t=null!==(n=t)&&void 0!==n?n:u.a.get(),!w())return E.VISIBLE_FOR_ALL;if(e.messageVisibility().visible)return E.VISIBLE_FOR_ALL;if((null===(r=e.sender)||void 0===r?void 0:r.userId)===t.getUserId())return E.SEE_THROUGH_FOR_CURRENT_USER;const o=t.getRoom(e.getRoomId());return i.a.name&&null!=o&&o.currentState.maySendStateEvent(i.a.name,t.getUserId())||i.a.altName&&null!=o&&o.currentState.maySendStateEvent(i.a.altName,t.getUserId())?E.SEE_THROUGH_FOR_CURRENT_USER:E.HIDDEN_TO_CURRENT_USER}function C(e){const t=e.getContent();return!!t["org.matrix.msc2516.voice"]||!!t["org.matrix.msc3245.voice"]}async function x(e,t,n){var i;let a;try{const i=await e.fetchRoomEvent(t,n);a=new r.b(i)}catch(e){o.a.warn("Could not find initial event: "+n),a=null}if(e.supportsThreads()&&null!==(i=a)&&void 0!==i&&i.isRelation(c.d.name)&&!a.getThread()){var s;const n=a.threadRootId,r=e.getRoom(t),i=e.getEventMapper(),l=null!==(s=null==r?void 0:r.findEventById(n))&&void 0!==s?s:i(await e.fetchRoomEvent(t,n));try{null==r||r.createThread(n,l,[a],!0)}catch(e){o.a.warn("Could not find root event: "+n)}}return a}function F(e,t,n){b(e)&&(a.e.matches(e.getType())?Object(m.g)(e,n):p.a.dispatch({action:g.a.EditEvent,event:e,timelineRenderingType:t}))}function D(e){return e===r.a.QUEUED||e===r.a.NOT_SENT||e===r.a.ENCRYPTING}const k=e=>{const t=e.getType();return s.c.matches(t)||t===i.b.RoomMessage&&s.c.matches(e.getContent().msgtype)};function O(e){var t;return e.isThreadRoot&&!(null===(t=e.getThread())||void 0===t||!t.length)&&!!e.getThread().replyToEvent}function I(e){return!l.b.matches(e.getType())}const A=(e,t)=>{p.a.dispatch({action:g.a.ViewRoom,event_id:t,highlighted:!0,room_id:e,metricsTrigger:void 0})}},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return v}));var r=n(255),i=n(757),o=n(1),a=n(136),s=n(188),l=n(223),c=n(122),u=n(157),d=n(131),h=n(124),p=n(379),m=n(283),g=n(201),f=n(565),_=n(185),b=n(121);class v{static canUserModifyWidgets(e){if(!e)return o.a.warn("No room ID specified"),!1;const t=c.a.get();if(!t)return o.a.warn("User must be be logged in"),!1;const n=t.getRoom(e);if(!n)return o.a.warn(`Room ID ${e} is not recognised`),!1;const r=t.credentials.userId;return r?"join"!==n.getMyMembership()?(o.a.warn(`User ${r} is not in room ${e}`),!1):n.currentState.maySendStateEvent("im.vector.modular.widgets",r):(o.a.warn("Failed to get user ID"),!1)}static isScalarUrl(e){if(!e)return o.a.error("Scalar URL check failed. No URL specified"),!1;const t=r.parse(e);let n=d.b.get().integrations_widgets_urls;if(!n||0===n.length){const e=m.a.sharedInstance().getPrimaryManager();n=e?[e.apiUrl]:[]}for(let e=0;e{function i(n){return!!n&&(t?void 0!==n.getContent()[e]:void 0===n.getContent()[e])}if(i(c.a.get().getAccountData("m.widgets")))return void n();function o(e){i(c.a.get().getAccountData("m.widgets"))&&(c.a.get().removeListener(a.ClientEvent.AccountData,o),clearTimeout(s),n())}const s=window.setTimeout((()=>{c.a.get().removeListener(a.ClientEvent.AccountData,o),r(new Error("Timed out waiting for widget ID "+e+" to appear"))}),2e4);c.a.get().on(a.ClientEvent.AccountData,o)}))}static waitForRoomWidget(e,t,n){return new Promise(((r,i)=>{function o(t){const r=null==t?void 0:t.some((t=>t.getContent()&&t.getContent().id===e));return n?!!r:!r}const s=c.a.get().getRoom(t);if(o(null==s?void 0:s.currentState.getStateEvents("im.vector.modular.widgets")))return void r();function l(e){if(e.getRoomId()!==t||"im.vector.modular.widgets"!==e.getType())return;o(null==s?void 0:s.currentState.getStateEvents("im.vector.modular.widgets"))&&(c.a.get().removeListener(a.RoomStateEvent.Events,l),clearTimeout(u),r())}const u=window.setTimeout((()=>{c.a.get().removeListener(a.RoomStateEvent.Events,l),i(new Error("Timed out waiting for widget ID "+e+" to appear"))}),2e4);c.a.get().on(a.RoomStateEvent.Events,l)}))}static setUserWidget(e,t,n,r,i){const a={type:t.preferred,url:n,name:r,data:i},s=c.a.get(),l=Object(_.a)(v.getUserWidgets());try{delete l[e]}catch(e){o.a.error("$widgetId is non-configurable")}const u=Boolean(n);return u&&(l[e]={content:a,sender:s.getUserId(),state_key:e,type:"m.widget",id:e}),s.setAccountData("m.widgets",l).then((()=>v.waitForUserWidget(e,u))).then((()=>{h.a.dispatch({action:"user_widget_updated"})}))}static setRoomWidget(e,t,n,r,i,o,a){let s;return s=Boolean(r)?{type:null==n?void 0:n.legacy,url:r,name:i,data:o,avatar_url:a}:{},v.setRoomWidgetContent(e,t,s)}static setRoomWidgetContent(e,t,n){const r=!!n.url;p.a.setRoomWidgetEcho(e,t,n);return c.a.get().sendStateEvent(e,"im.vector.modular.widgets",n,t).then((()=>v.waitForRoomWidget(t,e,r))).finally((()=>{p.a.removeRoomWidgetEcho(e,t)}))}static getRoomWidgets(e){const t=e.currentState.getStateEvents("im.vector.modular.widgets");return t?t.filter((e=>e.getContent().type&&e.getContent().url)):[]}static getUserWidgets(){const e=c.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");return t&&t.getContent()?t.getContent():{}}static getUserWidgetsArray(){return Object.values(v.getUserWidgets())}static getStickerpickerWidgets(){return v.getUserWidgetsArray().filter((e=>e.content&&"m.stickerpicker"===e.content.type))}static getIntegrationManagerWidgets(){return v.getUserWidgetsArray().filter((e=>e.content&&"m.integration_manager"===e.content.type))}static getRoomWidgetsOfType(e,t){return(v.getRoomWidgets(e)||[]).filter((e=>{const n=e.getContent();return n.url&&t.matches(n.type)}))}static async removeIntegrationManagerWidgets(){const e=c.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");if(!t)return;const n=t.getContent()||{};Object.entries(n).forEach((e=>{let[t,r]=e;r.content&&"m.integration_manager"===r.content.type&&delete n[t]})),await e.setAccountData("m.widgets",n)}static addIntegrationManagerWidget(e,t,n){return v.setUserWidget("integration_manager_"+(new Date).getTime(),g.a.INTEGRATION_MANAGER,t,"Integration manager: "+e,{api_url:n})}static async removeStickerpickerWidgets(){const e=c.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");if(!t)return;const n=t.getContent()||{};Object.entries(n).forEach((e=>{let[t,r]=e;r.content&&"m.stickerpicker"===r.content.type&&delete n[t]})),await e.setAccountData("m.widgets",n)}static async addJitsiWidget(t,n,r,o,a){var u;const d=f.a.getInstance().preferredDomain,h=await f.a.getInstance().getJitsiAuth(),p=Object(l.b)(24);let m;m="openidtoken-jwt"===h?i.base32.stringify(e.from(t),{pad:!1}):`Jitsi${Object(l.c)(1)}${Object(l.a)(23)}`;const _=new URL(v.getLocalJitsiWrapperUrl({auth:h}));_.search="",_.searchParams.set("confId",m),await v.setRoomWidget(t,p,g.a.JITSI,_.toString(),r,{conferenceId:m,roomName:null!=a?a:null===(u=c.a.get().getRoom(t))||void 0===u?void 0:u.name,isAudioOnly:n===s.g.Voice,isVideoChannel:o,domain:d,auth:h})}static makeAppConfig(e,t,n,r,i){if(!n)throw new Error("Widgets must be created by someone - provide a senderUserId");return t.creatorUserId=n,t.id=e,t.roomId=r,t.eventId=i,t.name=t.name||t.type,t}static getLocalJitsiWrapperUrl(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=["conferenceDomain=$domain","conferenceId=$conferenceId","isAudioOnly=$isAudioOnly","isVideoChannel=$isVideoChannel","displayName=$matrix_display_name","avatarUrl=$matrix_avatar_url","userId=$matrix_user_id","roomId=$matrix_room_id","theme=$theme","roomName=$roomName",`supportsScreensharing=${null===(e=u.a.get())||void 0===e?void 0:e.supportsJitsiScreensharing()}`,"language=$org.matrix.msc2873.client_language"];t.auth&&n.push(`auth=${t.auth}`);const r=n.join("&");let i=window.location.href;"https:"===window.location.protocol||t.forLocalRender||(i="https://app.element.io/");return new URL("jitsi.html#"+r,i).href}static getWidgetName(e){var t;return(null==e||null===(t=e.name)||void 0===t?void 0:t.trim())||Object(b.a)("Unknown App")}static getWidgetDataTitle(e){var t,n;return(null==e||null===(t=e.data)||void 0===t||null===(n=t.title)||void 0===n?void 0:n.trim())||""}static getWidgetUid(e){return e?v.calcWidgetUid(e.id,e.roomId):""}static calcWidgetUid(e,t){return t?`room_${t}_${e}`:`user_${e}`}static editWidget(e,t){var n;null===(n=m.a.sharedInstance().getPrimaryManager())||void 0===n||n.open(e,"type_"+t.type,t.id)}static isManagedByManager(e){if(v.isScalarUrl(e.url)){const e=m.a.sharedInstance();if(e.hasManager()){const t=e.getPrimaryManager();return v.isScalarUrl(null==t?void 0:t.apiUrl)}}return!1}}}).call(this,n(53).Buffer)},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return o}));var r=n(121);let i;function o(e){switch(e){case i.ThreadPanel:return Object(r.a)("Threads");case i.Timeline:return Object(r.a)("Back to chat");case i.RoomSummary:return Object(r.a)("Room information");case i.RoomMemberList:return Object(r.a)("Room members");case i.ThreadView:return Object(r.a)("Back to thread")}return null}!function(e){e.RoomMemberList="RoomMemberList",e.FilePanel="FilePanel",e.NotificationPanel="NotificationPanel",e.RoomMemberInfo="RoomMemberInfo",e.EncryptionPanel="EncryptionPanel",e.RoomSummary="RoomSummary",e.Widget="Widget",e.PinnedMessages="PinnedMessages",e.Timeline="Timeline",e.Room3pidMemberInfo="Room3pidMemberInfo",e.SpaceMemberList="SpaceMemberList",e.SpaceMemberInfo="SpaceMemberInfo",e.Space3pidMemberInfo="Space3pidMemberInfo",e.ThreadView="ThreadView",e.ThreadPanel="ThreadPanel"}(i||(i={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return ie})),n.d(t,"b",(function(){return oe}));var r=n(13),i=n.n(r),o=n(120),a=n.n(o),s=n(188),l=n(1),c=n(17),u=n.n(c),d=n(231),h=n(320),p=n(215),m=n(508),g=n(122),f=n(127),_=n(121),b=n(124),v=n(181),y=n(125),E=n(201),S=n(137),w=n(155),T=n(144),C=n(234),x=n(265),F=n(2),D=n(156),k=n(128),O=n(387),I=n(241),A=n(207),R=n(379),N=n(131);function M(){var e;return N.b.get().widget_build_url?N.b.get().widget_build_url:null===(e=Object(I.b)())||void 0===e?void 0:e.widget_build_url}var P=n(219),L=n(126),B=n.n(L),U=n(162),j=n(148),G=n(123);class z extends a.a.Component{constructor(e){super(e),i()(this,"componentDidMount",(()=>{oe.instance.addListener(ie.SilencedCallsChanged,this.onSilencedCallsChanged)})),i()(this,"onSilencedCallsChanged",(()=>{this.setState({silenced:oe.instance.isCallSilenced(this.props.call.callId)})})),i()(this,"onAnswerClick",(e=>{e.stopPropagation(),oe.instance.answerCall(oe.instance.roomIdForCall(this.props.call))})),i()(this,"onRejectClick",(e=>{e.stopPropagation(),oe.instance.hangupOrReject(oe.instance.roomIdForCall(this.props.call),!0)})),i()(this,"onSilenceClick",(e=>{e.stopPropagation();const t=this.props.call.callId;this.state.silenced?oe.instance.unSilenceCall(t):oe.instance.silenceCall(t)})),this.state={silenced:oe.instance.isCallSilenced(this.props.call.callId)}}componentWillUnmount(){oe.instance.removeListener(ie.SilencedCallsChanged,this.onSilencedCallsChanged)}render(){const e=this.props.call,t=g.a.get().getRoom(oe.instance.roomIdForCall(e)),n=e.type===s.g.Voice,r=oe.instance.isForcedSilent();let i=this.state.silenced?Object(_.a)("Sound on"):Object(_.a)("Silence call");r&&(i=Object(_.a)("Notifications silenced"));const o=B()("mx_IncomingLegacyCallToast_content",{mx_IncomingLegacyCallToast_content_voice:n,mx_IncomingLegacyCallToast_content_video:!n}),l=B()("mx_IncomingLegacyCallToast_iconButton",{mx_IncomingLegacyCallToast_unSilence:this.state.silenced,mx_IncomingLegacyCallToast_silence:!this.state.silenced});return a.a.createElement(a.a.Fragment,null,a.a.createElement(U.a,{room:null!=t?t:void 0,height:32,width:32}),a.a.createElement("div",{className:o},a.a.createElement("span",{className:"mx_LegacyCallEvent_caller"},t?t.name:Object(_.a)("Unknown caller")),a.a.createElement("div",{className:"mx_LegacyCallEvent_type"},a.a.createElement("div",{className:"mx_LegacyCallEvent_type_icon"}),n?Object(_.a)("Voice call"):Object(_.a)("Video call")),a.a.createElement("div",{className:"mx_IncomingLegacyCallToast_buttons"},a.a.createElement(G.a,{className:"mx_IncomingLegacyCallToast_button mx_IncomingLegacyCallToast_button_decline",onClick:this.onRejectClick,kind:"danger"},a.a.createElement("span",null," ",Object(_.a)("Decline")," ")),a.a.createElement(G.a,{className:"mx_IncomingLegacyCallToast_button mx_IncomingLegacyCallToast_button_accept",onClick:this.onAnswerClick,kind:"primary"},a.a.createElement("span",null," ",Object(_.a)("Accept")," ")))),a.a.createElement(j.a,{className:l,disabled:r,onClick:this.onSilenceClick,title:i}))}}var H=n(198),q=n(446),V=n(586),$=n(305),K=n(798),W=n(388),Y=n(154),Q=n(800);const X="m.protocol.pstn",Z="im.vector.protocol.pstn",J="im.vector.protocol.sip_native",ee="im.vector.protocol.sip_virtual",te=["error","emptied","stalled","suspend","waiting"],ne=[...te,"play","pause","playing","ended","loadeddata","loadedmetadata","canplay","canplaythrough","volumechange"];let re;!function(e){e.Ring="ringAudio",e.Ringback="ringbackAudio",e.CallEnd="callendAudio",e.Busy="busyAudio"}(re||(re={}));let ie;!function(e){e.CallsChanged="calls_changed",e.CallChangeRoom="call_change_room",e.SilencedCallsChanged="silenced_calls_changed",e.CallState="call_state"}(ie||(ie={}));class oe extends u.a{constructor(){super(...arguments),i()(this,"calls",new Map),i()(this,"transferees",new Map),i()(this,"audioPromises",new Map),i()(this,"audioElementsWithListeners",new Map),i()(this,"supportsPstnProtocol",null),i()(this,"pstnSupportPrefixed",null),i()(this,"supportsSipNativeVirtual",null),i()(this,"assertedIdentityNativeUsers",new Map),i()(this,"silencedCalls",new Set),i()(this,"onCallIncoming",(e=>{if(!g.a.get().supportsVoip())return;const t=oe.instance.roomIdForCall(e);if(this.getCallForRoom(t))return void l.a.log("Got incoming call for room "+t+" but there's already a call for this room: ignoring");this.addCallForRoom(t,e),this.setCallListeners(e),this.onCallStateChanged(e.state,null,e);const n=g.a.get();n.prepareToEncrypt(n.getRoom(e.roomId))})),i()(this,"onCallStateChanged",((e,t,n)=>{if(!this.matchesCallForThisRoom(n))return;const r=this.roomIdForCall(n);switch(this.setCallState(n,e),b.a.dispatch({action:"call_state",room_id:r,state:e}),t){case s.f.Ringing:this.pause(re.Ring);break;case s.f.InviteSent:this.pause(re.Ringback)}switch(e!==s.f.Ringing&&this.silencedCalls.delete(n.callId),e){case s.f.Ringing:{const e=new h.a(g.a.get()).getPushRuleById(d.f.IncomingCall),t=null==e?void 0:e.enabled,r=null==e?void 0:e.actions.some((e=>e.set_tweak===d.g.Sound&&"ring"===e.value));t&&r&&!this.isForcedSilent()?this.play(re.Ring):this.silenceCall(n.callId);break}case s.f.InviteSent:this.play(re.Ringback);break;case s.f.Ended:{const e=n.hangupReason;if(this.removeCallForRoom(r),t===s.f.InviteSent&&n.hangupParty===s.e.Remote){if(this.play(re.Busy),!e||[s.c.UserHangup,"user hangup"].includes(e))break;let t,r;n.hangupReason===s.c.UserBusy?(t=Object(_.a)("User Busy"),r=Object(_.a)("The user you called is busy.")):(t=Object(_.a)("Call Failed"),r=Object(_.a)("The call could not be established")),f.b.createDialog(T.a,{title:t,description:r})}else e===s.c.AnsweredElsewhere&&t===s.f.Connecting?f.b.createDialog(T.a,{title:Object(_.a)("Answered Elsewhere"),description:Object(_.a)("The call was answered on another device.")}):t!==s.f.Fledgling&&t!==s.f.Ringing&&this.play(re.CallEnd);this.logCallStats(n,r);break}}}))}static get instance(){return window.mxLegacyCallHandler||(window.mxLegacyCallHandler=new oe),window.mxLegacyCallHandler}roomIdForCall(e){var t,n;if(!e)return null;if(this.shouldObeyAssertedfIdentity()){const t=this.assertedIdentityNativeUsers.get(e.callId);if(t){const e=Object($.a)(g.a.get(),t);if(e)return e.roomId}}return null!==(t=null!==(n=O.a.sharedInstance().nativeRoomForVirtualRoom(e.roomId))&&void 0!==n?n:e.roomId)&&void 0!==t?t:null}start(){navigator.mediaSession&&(navigator.mediaSession.setActionHandler("play",(function(){})),navigator.mediaSession.setActionHandler("pause",(function(){})),navigator.mediaSession.setActionHandler("seekbackward",(function(){})),navigator.mediaSession.setActionHandler("seekforward",(function(){})),navigator.mediaSession.setActionHandler("previoustrack",(function(){})),navigator.mediaSession.setActionHandler("nexttrack",(function(){}))),y.b.getValue(D.b.Voip)&&g.a.get().on(m.b.Incoming,this.onCallIncoming),this.checkProtocols(3),Object.values(re).forEach((e=>{const t=document.getElementById(e);t?this.addEventListenersForAudioElement(t):l.a.warn(`LegacyCallHandler: missing