www.federated.computer/content/target/assets/main.5848f48b.js

37 lines
521 KiB
JavaScript

var Pd=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);import"./modulepreload-polyfill.b7f2da20.js";var GS=Pd((WS,Ke)=>{var Ao=/[\\\"\x00-\x1F]/g,He={};for(var or=0;or<32;++or)He[String.fromCharCode(or)]="\\U"+("0000"+or.toString(16)).slice(-4).toUpperCase();He["\b"]="\\b";He[" "]="\\t";He[`
`]="\\n";He["\f"]="\\f";He["\r"]="\\r";He['"']='\\"';He["\\"]="\\\\";function sc(s){return Ao.lastIndex=0,s.replace(Ao,function(e){return He[e]})}function _n(s){switch(typeof s){case"string":return'"'+sc(s)+'"';case"number":return isFinite(s)?s:"null";case"boolean":return s;case"object":return s===null?"null":Array.isArray(s)?Od(s):Ud(s);default:throw new Error("Cannot stringify: "+typeof s)}}function Od(s){for(var e="[",t="",i=0;i<s.length;++i)t+=e,e=",",t+=_n(s[i]);return e!=","?"[]":t+"]"}function Ud(s){var e="{",t="",i=Object.keys(s);i.sort();for(var r=0;r<i.length;++r){var n=i[r];t+=e+'"'+sc(n)+'":',e=",",t+=_n(s[n])}return e!=","?"{}":t+"}"}var nc={stringify:_n},Nt={};(function(){for(var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Uint8Array(256),t=0;t<s.length;t++)e[s.charCodeAt(t)]=t;Nt.encode=function(i){var r=new Uint8Array(i),n,o=r.length,a="";for(n=0;n<o;n+=3)a+=s[r[n]>>2],a+=s[(r[n]&3)<<4|r[n+1]>>4],a+=s[(r[n+1]&15)<<2|r[n+2]>>6],a+=s[r[n+2]&63];return o%3===2?a=a.substring(0,a.length-1)+"=":o%3===1&&(a=a.substring(0,a.length-2)+"=="),a},Nt.decode=function(i){var r=i.length*.75,n=i.length,o,a=0,c,l,d,u;i[i.length-1]==="="&&(r--,i[i.length-2]==="="&&r--);var h=new ArrayBuffer(r),m=new Uint8Array(h);for(o=0;o<n;o+=4)c=e[i.charCodeAt(o)],l=e[i.charCodeAt(o+1)],d=e[i.charCodeAt(o+2)],u=e[i.charCodeAt(o+3)],m[a++]=c<<2|l>>4,m[a++]=(l&15)<<4|d>>2,m[a++]=(d&3)<<6|u&63;return h}})();/*! @license DOMPurify 2.4.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.0/LICENSE */function it(s){return it=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},it(s)}function Ks(s,e){return Ks=Object.setPrototypeOf||function(i,r){return i.__proto__=r,i},Ks(s,e)}function Bd(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Ar(s,e,t){return Bd()?Ar=Reflect.construct:Ar=function(r,n,o){var a=[null];a.push.apply(a,n);var c=Function.bind.apply(r,a),l=new c;return o&&Ks(l,o.prototype),l},Ar.apply(null,arguments)}function ge(s){return Ld(s)||Fd(s)||Vd(s)||Kd()}function Ld(s){if(Array.isArray(s))return $s(s)}function Fd(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Vd(s,e){if(!!s){if(typeof s=="string")return $s(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return $s(s,e)}}function $s(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t<e;t++)i[t]=s[t];return i}function Kd(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var $d=Object.hasOwnProperty,Co=Object.setPrototypeOf,jd=Object.isFrozen,Gd=Object.getPrototypeOf,qd=Object.getOwnPropertyDescriptor,le=Object.freeze,Ne=Object.seal,zd=Object.create,oc=typeof Reflect<"u"&&Reflect,Or=oc.apply,js=oc.construct;Or||(Or=function(e,t,i){return e.apply(t,i)});le||(le=function(e){return e});Ne||(Ne=function(e){return e});js||(js=function(e,t){return Ar(e,ge(t))});var Hd=Ie(Array.prototype.forEach),No=Ie(Array.prototype.pop),yi=Ie(Array.prototype.push),Cr=Ie(String.prototype.toLowerCase),Wd=Ie(String.prototype.match),Xe=Ie(String.prototype.replace),Yd=Ie(String.prototype.indexOf),Jd=Ie(String.prototype.trim),ne=Ie(RegExp.prototype.test),Is=Xd(TypeError);function Ie(s){return function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Or(s,e,i)}}function Xd(s){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return js(s,t)}}function R(s,e,t){t=t||Cr,Co&&Co(s,null);for(var i=e.length;i--;){var r=e[i];if(typeof r=="string"){var n=t(r);n!==r&&(jd(e)||(e[i]=n),r=n)}s[r]=!0}return s}function wt(s){var e=zd(null),t;for(t in s)Or($d,s,[t])&&(e[t]=s[t]);return e}function ar(s,e){for(;s!==null;){var t=qd(s,e);if(t){if(t.get)return Ie(t.get);if(typeof t.value=="function")return Ie(t.value)}s=Gd(s)}function i(r){return console.warn("fallback value for",r),null}return i}var Mo=le(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ts=le(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xs=le(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Qd=le(["animate","color-profile","cursor","discard","fedropshadow","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ks=le(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),Zd=le(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Do=le(["#text"]),Po=le(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),Rs=le(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Oo=le(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),cr=le(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),eu=Ne(/\{\{[\w\W]*|[\w\W]*\}\}/gm),tu=Ne(/<%[\w\W]*|[\w\W]*%>/gm),iu=Ne(/^data-[\-\w.\u00B7-\uFFFF]/),ru=Ne(/^aria-[\-\w]+$/),su=Ne(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),nu=Ne(/^(?:\w+script|data):/i),ou=Ne(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),au=Ne(/^html$/i),cu=function(){return typeof window>"u"?null:window},lu=function(e,t){if(it(e)!=="object"||typeof e.createPolicy!="function")return null;var i=null,r="data-tt-policy-suffix";t.currentScript&&t.currentScript.hasAttribute(r)&&(i=t.currentScript.getAttribute(r));var n="dompurify"+(i?"#"+i:"");try{return e.createPolicy(n,{createHTML:function(a){return a},createScriptURL:function(a){return a}})}catch{return console.warn("TrustedTypes policy "+n+" could not be created."),null}};function ac(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:cu(),e=function(p){return ac(p)};if(e.version="2.4.0",e.removed=[],!s||!s.document||s.document.nodeType!==9)return e.isSupported=!1,e;var t=s.document,i=s.document,r=s.DocumentFragment,n=s.HTMLTemplateElement,o=s.Node,a=s.Element,c=s.NodeFilter,l=s.NamedNodeMap,d=l===void 0?s.NamedNodeMap||s.MozNamedAttrMap:l,u=s.HTMLFormElement,h=s.DOMParser,m=s.trustedTypes,_=a.prototype,f=ar(_,"cloneNode"),E=ar(_,"nextSibling"),I=ar(_,"childNodes"),T=ar(_,"parentNode");if(typeof n=="function"){var k=i.createElement("template");k.content&&k.content.ownerDocument&&(i=k.content.ownerDocument)}var w=lu(m,t),x=w?w.createHTML(""):"",C=i,O=C.implementation,Ft=C.createNodeIterator,wd=C.createDocumentFragment,bd=C.getElementsByTagName,Sd=t.importNode,oo={};try{oo=wt(i).documentMode?i.documentMode:{}}catch{}var xe={};e.isSupported=typeof T=="function"&&O&&typeof O.createHTMLDocument<"u"&&oo!==9;var cs=eu,ls=tu,Ed=iu,Id=ru,Td=nu,ao=ou,ds=su,z=null,co=R({},[].concat(ge(Mo),ge(Ts),ge(xs),ge(ks),ge(Do))),J=null,lo=R({},[].concat(ge(Po),ge(Rs),ge(Oo),ge(cr))),$=Object.seal(Object.create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),_i=null,us=null,uo=!0,hs=!0,ho=!1,Vt=!1,vt=!1,ps=!1,ms=!1,Kt=!1,tr=!1,ir=!1,po=!0,mo=!1,xd="user-content-",_s=!0,fi=!1,$t={},jt=null,_o=R({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),fo=null,go=R({},["audio","video","img","source","image","track"]),fs=null,yo=R({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gs="http://www.w3.org/1998/Math/MathML",ys="http://www.w3.org/2000/svg",Je="http://www.w3.org/1999/xhtml",rr=Je,vs=!1,Gt,kd=["application/xhtml+xml","text/html"],Rd="text/html",H,qt=null,Ad=i.createElement("form"),vo=function(p){return p instanceof RegExp||p instanceof Function},ws=function(p){qt&&qt===p||((!p||it(p)!=="object")&&(p={}),p=wt(p),Gt=kd.indexOf(p.PARSER_MEDIA_TYPE)===-1?Gt=Rd:Gt=p.PARSER_MEDIA_TYPE,H=Gt==="application/xhtml+xml"?function(g){return g}:Cr,z="ALLOWED_TAGS"in p?R({},p.ALLOWED_TAGS,H):co,J="ALLOWED_ATTR"in p?R({},p.ALLOWED_ATTR,H):lo,fs="ADD_URI_SAFE_ATTR"in p?R(wt(yo),p.ADD_URI_SAFE_ATTR,H):yo,fo="ADD_DATA_URI_TAGS"in p?R(wt(go),p.ADD_DATA_URI_TAGS,H):go,jt="FORBID_CONTENTS"in p?R({},p.FORBID_CONTENTS,H):_o,_i="FORBID_TAGS"in p?R({},p.FORBID_TAGS,H):{},us="FORBID_ATTR"in p?R({},p.FORBID_ATTR,H):{},$t="USE_PROFILES"in p?p.USE_PROFILES:!1,uo=p.ALLOW_ARIA_ATTR!==!1,hs=p.ALLOW_DATA_ATTR!==!1,ho=p.ALLOW_UNKNOWN_PROTOCOLS||!1,Vt=p.SAFE_FOR_TEMPLATES||!1,vt=p.WHOLE_DOCUMENT||!1,Kt=p.RETURN_DOM||!1,tr=p.RETURN_DOM_FRAGMENT||!1,ir=p.RETURN_TRUSTED_TYPE||!1,ms=p.FORCE_BODY||!1,po=p.SANITIZE_DOM!==!1,mo=p.SANITIZE_NAMED_PROPS||!1,_s=p.KEEP_CONTENT!==!1,fi=p.IN_PLACE||!1,ds=p.ALLOWED_URI_REGEXP||ds,rr=p.NAMESPACE||Je,p.CUSTOM_ELEMENT_HANDLING&&vo(p.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=p.CUSTOM_ELEMENT_HANDLING.tagNameCheck),p.CUSTOM_ELEMENT_HANDLING&&vo(p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Vt&&(hs=!1),tr&&(Kt=!0),$t&&(z=R({},ge(Do)),J=[],$t.html===!0&&(R(z,Mo),R(J,Po)),$t.svg===!0&&(R(z,Ts),R(J,Rs),R(J,cr)),$t.svgFilters===!0&&(R(z,xs),R(J,Rs),R(J,cr)),$t.mathMl===!0&&(R(z,ks),R(J,Oo),R(J,cr))),p.ADD_TAGS&&(z===co&&(z=wt(z)),R(z,p.ADD_TAGS,H)),p.ADD_ATTR&&(J===lo&&(J=wt(J)),R(J,p.ADD_ATTR,H)),p.ADD_URI_SAFE_ATTR&&R(fs,p.ADD_URI_SAFE_ATTR,H),p.FORBID_CONTENTS&&(jt===_o&&(jt=wt(jt)),R(jt,p.FORBID_CONTENTS,H)),_s&&(z["#text"]=!0),vt&&R(z,["html","head","body"]),z.table&&(R(z,["tbody"]),delete _i.tbody),le&&le(p),qt=p)},wo=R({},["mi","mo","mn","ms","mtext"]),bo=R({},["foreignobject","desc","title","annotation-xml"]),Cd=R({},["title","style","font","a","script"]),sr=R({},Ts);R(sr,xs),R(sr,Qd);var bs=R({},ks);R(bs,Zd);var Nd=function(p){var g=T(p);(!g||!g.tagName)&&(g={namespaceURI:Je,tagName:"template"});var v=Cr(p.tagName),N=Cr(g.tagName);return p.namespaceURI===ys?g.namespaceURI===Je?v==="svg":g.namespaceURI===gs?v==="svg"&&(N==="annotation-xml"||wo[N]):Boolean(sr[v]):p.namespaceURI===gs?g.namespaceURI===Je?v==="math":g.namespaceURI===ys?v==="math"&&bo[N]:Boolean(bs[v]):p.namespaceURI===Je?g.namespaceURI===ys&&!bo[N]||g.namespaceURI===gs&&!wo[N]?!1:!bs[v]&&(Cd[v]||!sr[v]):!1},Oe=function(p){yi(e.removed,{element:p});try{p.parentNode.removeChild(p)}catch{try{p.outerHTML=x}catch{p.remove()}}},Ss=function(p,g){try{yi(e.removed,{attribute:g.getAttributeNode(p),from:g})}catch{yi(e.removed,{attribute:null,from:g})}if(g.removeAttribute(p),p==="is"&&!J[p])if(Kt||tr)try{Oe(g)}catch{}else try{g.setAttribute(p,"")}catch{}},So=function(p){var g,v;if(ms)p="<remove></remove>"+p;else{var N=Wd(p,/^[\r\n\t ]+/);v=N&&N[0]}Gt==="application/xhtml+xml"&&(p='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+p+"</body></html>");var de=w?w.createHTML(p):p;if(rr===Je)try{g=new h().parseFromString(de,Gt)}catch{}if(!g||!g.documentElement){g=O.createDocument(rr,"template",null);try{g.documentElement.innerHTML=vs?"":de}catch{}}var Z=g.body||g.documentElement;return p&&v&&Z.insertBefore(i.createTextNode(v),Z.childNodes[0]||null),rr===Je?bd.call(g,vt?"html":"body")[0]:vt?g.documentElement:Z},Eo=function(p){return Ft.call(p.ownerDocument||p,p,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT,null,!1)},Md=function(p){return p instanceof u&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof d)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function")},gi=function(p){return it(o)==="object"?p instanceof o:p&&it(p)==="object"&&typeof p.nodeType=="number"&&typeof p.nodeName=="string"},Ue=function(p,g,v){!xe[p]||Hd(xe[p],function(N){N.call(e,g,v,qt)})},Io=function(p){var g;if(Ue("beforeSanitizeElements",p,null),Md(p)||ne(/[\u0080-\uFFFF]/,p.nodeName))return Oe(p),!0;var v=H(p.nodeName);if(Ue("uponSanitizeElement",p,{tagName:v,allowedTags:z}),p.hasChildNodes()&&!gi(p.firstElementChild)&&(!gi(p.content)||!gi(p.content.firstElementChild))&&ne(/<[/\w]/g,p.innerHTML)&&ne(/<[/\w]/g,p.textContent)||v==="select"&&ne(/<template/i,p.innerHTML))return Oe(p),!0;if(!z[v]||_i[v]){if(!_i[v]&&xo(v)&&($.tagNameCheck instanceof RegExp&&ne($.tagNameCheck,v)||$.tagNameCheck instanceof Function&&$.tagNameCheck(v)))return!1;if(_s&&!jt[v]){var N=T(p)||p.parentNode,de=I(p)||p.childNodes;if(de&&N)for(var Z=de.length,X=Z-1;X>=0;--X)N.insertBefore(f(de[X],!0),E(p))}return Oe(p),!0}return p instanceof a&&!Nd(p)||(v==="noscript"||v==="noembed")&&ne(/<\/no(script|embed)/i,p.innerHTML)?(Oe(p),!0):(Vt&&p.nodeType===3&&(g=p.textContent,g=Xe(g,cs," "),g=Xe(g,ls," "),p.textContent!==g&&(yi(e.removed,{element:p.cloneNode()}),p.textContent=g)),Ue("afterSanitizeElements",p,null),!1)},To=function(p,g,v){if(po&&(g==="id"||g==="name")&&(v in i||v in Ad))return!1;if(!(hs&&!us[g]&&ne(Ed,g))){if(!(uo&&ne(Id,g))){if(!J[g]||us[g]){if(!(xo(p)&&($.tagNameCheck instanceof RegExp&&ne($.tagNameCheck,p)||$.tagNameCheck instanceof Function&&$.tagNameCheck(p))&&($.attributeNameCheck instanceof RegExp&&ne($.attributeNameCheck,g)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(g))||g==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&ne($.tagNameCheck,v)||$.tagNameCheck instanceof Function&&$.tagNameCheck(v))))return!1}else if(!fs[g]){if(!ne(ds,Xe(v,ao,""))){if(!((g==="src"||g==="xlink:href"||g==="href")&&p!=="script"&&Yd(v,"data:")===0&&fo[p])){if(!(ho&&!ne(Td,Xe(v,ao,"")))){if(v)return!1}}}}}}return!0},xo=function(p){return p.indexOf("-")>0},ko=function(p){var g,v,N,de;Ue("beforeSanitizeAttributes",p,null);var Z=p.attributes;if(!!Z){var X={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J};for(de=Z.length;de--;){g=Z[de];var nr=g,ee=nr.name,Es=nr.namespaceURI;if(v=ee==="value"?g.value:Jd(g.value),N=H(ee),X.attrName=N,X.attrValue=v,X.keepAttr=!0,X.forceKeepAttr=void 0,Ue("uponSanitizeAttribute",p,X),v=X.attrValue,!X.forceKeepAttr&&(Ss(ee,p),!!X.keepAttr)){if(ne(/\/>/i,v)){Ss(ee,p);continue}Vt&&(v=Xe(v,cs," "),v=Xe(v,ls," "));var Ro=H(p.nodeName);if(!!To(Ro,N,v)){if(mo&&(N==="id"||N==="name")&&(Ss(ee,p),v=xd+v),w&&it(m)==="object"&&typeof m.getAttributeType=="function"&&!Es)switch(m.getAttributeType(Ro,N)){case"TrustedHTML":v=w.createHTML(v);break;case"TrustedScriptURL":v=w.createScriptURL(v);break}try{Es?p.setAttributeNS(Es,ee,v):p.setAttribute(ee,v),No(e.removed)}catch{}}}}Ue("afterSanitizeAttributes",p,null)}},Dd=function b(p){var g,v=Eo(p);for(Ue("beforeSanitizeShadowDOM",p,null);g=v.nextNode();)Ue("uponSanitizeShadowNode",g,null),!Io(g)&&(g.content instanceof r&&b(g.content),ko(g));Ue("afterSanitizeShadowDOM",p,null)};return e.sanitize=function(b){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},g,v,N,de,Z;if(vs=!b,vs&&(b="<!-->"),typeof b!="string"&&!gi(b)){if(typeof b.toString!="function")throw Is("toString is not a function");if(b=b.toString(),typeof b!="string")throw Is("dirty is not a string, aborting")}if(!e.isSupported){if(it(s.toStaticHTML)==="object"||typeof s.toStaticHTML=="function"){if(typeof b=="string")return s.toStaticHTML(b);if(gi(b))return s.toStaticHTML(b.outerHTML)}return b}if(ps||ws(p),e.removed=[],typeof b=="string"&&(fi=!1),fi){if(b.nodeName){var X=H(b.nodeName);if(!z[X]||_i[X])throw Is("root node is forbidden and cannot be sanitized in-place")}}else if(b instanceof o)g=So("<!---->"),v=g.ownerDocument.importNode(b,!0),v.nodeType===1&&v.nodeName==="BODY"||v.nodeName==="HTML"?g=v:g.appendChild(v);else{if(!Kt&&!Vt&&!vt&&b.indexOf("<")===-1)return w&&ir?w.createHTML(b):b;if(g=So(b),!g)return Kt?null:ir?x:""}g&&ms&&Oe(g.firstChild);for(var nr=Eo(fi?b:g);N=nr.nextNode();)N.nodeType===3&&N===de||Io(N)||(N.content instanceof r&&Dd(N.content),ko(N),de=N);if(de=null,fi)return b;if(Kt){if(tr)for(Z=wd.call(g.ownerDocument);g.firstChild;)Z.appendChild(g.firstChild);else Z=g;return J.shadowroot&&(Z=Sd.call(t,Z,!0)),Z}var ee=vt?g.outerHTML:g.innerHTML;return vt&&z["!doctype"]&&g.ownerDocument&&g.ownerDocument.doctype&&g.ownerDocument.doctype.name&&ne(au,g.ownerDocument.doctype.name)&&(ee="<!DOCTYPE "+g.ownerDocument.doctype.name+`>
`+ee),Vt&&(ee=Xe(ee,cs," "),ee=Xe(ee,ls," ")),w&&ir?w.createHTML(ee):ee},e.setConfig=function(b){ws(b),ps=!0},e.clearConfig=function(){qt=null,ps=!1},e.isValidAttribute=function(b,p,g){qt||ws({});var v=H(b),N=H(p);return To(v,N,g)},e.addHook=function(b,p){typeof p=="function"&&(xe[b]=xe[b]||[],yi(xe[b],p))},e.removeHook=function(b){if(xe[b])return No(xe[b])},e.removeHooks=function(b){xe[b]&&(xe[b]=[])},e.removeAllHooks=function(){xe={}},e}var du=ac(),Yr={exports:{}},uu=function(s){var e={};function t(i){if(e[i])return e[i].exports;var r=e[i]={i,l:!1,exports:{}};return s[i].call(r.exports,r,r.exports,t),r.l=!0,r.exports}return t.m=s,t.c=e,t.d=function(i,r,n){t.o(i,r)||Object.defineProperty(i,r,{enumerable:!0,get:n})},t.r=function(i){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},t.t=function(i,r){if(1&r&&(i=t(i)),8&r||4&r&&typeof i=="object"&&i&&i.__esModule)return i;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:i}),2&r&&typeof i!="string")for(var o in i)t.d(n,o,function(a){return i[a]}.bind(null,o));return n},t.n=function(i){var r=i&&i.__esModule?function(){return i.default}:function(){return i};return t.d(r,"a",r),r},t.o=function(i,r){return Object.prototype.hasOwnProperty.call(i,r)},t.p="",t(t.s=0)}([function(s,e,t){function i(l){let d,u;const h={light:function(){return!_()},dark:_,lighten:I,darken:E,saturate:T,desaturate:function(w=0){return T(w*=-1)},increaseContrast:function(w=0){return k(w*=-1)},decreaseContrast:k,active:function(){return k(.123)},highlight:function(){return k(.1)},selected:function(){return k(.066)},text:function(){return u=f()?r("#333333"):r("#FFFFFF"),h},shadow:function(){return u=f()?r("#000000"):r("#FFFFFF"),h},hex:function(){const w=u;return u=d,"#"+w.map(x=>parseInt(x+"",10).toString(16).padStart(2,"0")).join("")},rgb:function(){const w=u;return u=d,`rgb(${w.join()})`},rgba:function(w=1){const x=u;return u=d,`rgba(${x.join()}, ${w})`},setHex:m,setRgb:function(w=[0,0,0]){let[x,C,O]=w;return x=c(x,0,255),C=c(C,0,255),O=c(O,0,255),d=[x,C,O],u=[x,C,O],h}};function m(w="#000000"){return d=r(w),u=d,h}function _(){const[w,x,C]=u;return u=d,(299*w+587*x+114*C)/1e3<128}function f(){const[w,x,C]=u;return(299*w+587*x+114*C)/1e3>=128}function E(w=0){return I(w*=-1)}function I(w=0){let[x,C,O]=a(u);return O=c(O+w,0,1),u=n([x,C,O]),h}function T(w=0){let[x,C,O]=a(u);return C=c(C+w,0,1),u=n([x,C,O]),h}function k(w=0){return f()?E(w):I(w)}return m(l),h}function r(l){if(typeof l!="string")throw new TypeError("Expected a string");(l=l.replace(/^#/,"")).length===3&&(l=l[0]+l[0]+l[1]+l[1]+l[2]+l[2]);var d=parseInt(l,16);return[d>>16,d>>8&255,255&d]}function n(l){const[d,u,h]=l;let m,_,f;if(u===0)m=_=f=h;else{const E=function(k,w,x){return x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?k+6*(w-k)*x:x<.5?w:x<.6666666666666666?k+(w-k)*(.6666666666666666-x)*6:k},I=h<.5?h*(1+u):h+u-h*u,T=2*h-I;m=c(E(T,I,d+1/3),0,1),_=c(E(T,I,d),0,1),f=c(E(T,I,d-1/3),0,1)}return[Math.round(255*m),Math.round(255*_),Math.round(255*f)]}t.r(e),t.d(e,"offColor",function(){return i}),t.d(e,"hexRgb",function(){return r}),t.d(e,"hslToRgb",function(){return n}),t.d(e,"color",function(){return o}),t.d(e,"rgbToHsl",function(){return a});const o=i;function a(l){const d=l[0]/255,u=l[1]/255,h=l[2]/255,m=Math.max(d,u,h),_=Math.min(d,u,h);let f=(m+_)/2,E=(m+_)/2;const I=(m+_)/2;if(m===_)f=E=0;else{const T=m-_;switch(E=I>.5?T/(2-m-_):T/(m+_),m){case d:f=(u-h)/T+(u<h?6:0);break;case u:f=(h-d)/T+2;break;case h:f=(d-u)/T+4}f/=6}return[f,E,I]}function c(l,d,u){return l=(l=l<=u?l:u)>=d?l:d}}]);Yr.exports=uu;var cc=Yr.exports,hu=Object.defineProperty,pu=Object.defineProperties,mu=Object.getOwnPropertyDescriptors,Ur=Object.getOwnPropertySymbols,lc=Object.prototype.hasOwnProperty,dc=Object.prototype.propertyIsEnumerable,Uo=(s,e,t)=>e in s?hu(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Oi=(s,e)=>{for(var t in e||(e={}))lc.call(e,t)&&Uo(s,t,e[t]);if(Ur)for(var t of Ur(e))dc.call(e,t)&&Uo(s,t,e[t]);return s},_u=(s,e)=>pu(s,mu(e)),fu=(s,e)=>{var t={};for(var i in s)lc.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Ur)for(var i of Ur(s))e.indexOf(i)<0&&dc.call(s,i)&&(t[i]=s[i]);return t},Bo,Lo;class Me extends Error{get name(){return"AbortError"}}class uc extends Error{constructor(e,t){super(`${e}: ${t.message}`),this.cause=t}get name(){return"WrappedError"}}class hc extends Error{constructor(e,t,i,r){super(`${i?i.error:r} on ${e} ${t}`),this.errcode=i?i.errcode:null,this.retry_after_ms=i?i.retry_after_ms:0,this.statusCode=r}get name(){return"HomeServerError"}}class Se extends Error{constructor(e,t){super(e||"ConnectionError"),this.isTimeout=t}get name(){return"ConnectionError"}}class fn{constructor(){this._handlers=new Set}onSubscribeFirst(){}onUnsubscribeLast(){}subscribe(e){return this._handlers.add(e),this._handlers.size===1&&this.onSubscribeFirst(),()=>this.unsubscribe(e)}unsubscribe(e){e&&(this._handlers.delete(e),this._handlers.size===0&&this.onUnsubscribeLast())}unsubscribeAll(){this._handlers.size!==0&&(this._handlers.clear(),this.onUnsubscribeLast())}get hasSubscriptions(){return this._handlers.size!==0}}class di extends fn{emit(e){for(const t of this._handlers)t(e)}waitFor(e){return e(this.get())?new yu(Promise.resolve(this.get())):new gu(this,e)}flatMap(e){return new vu(this,e)}}class gu{constructor(e,t){this._promise=new Promise((i,r)=>{this._reject=r,this._subscription=e.subscribe(n=>{t(n)&&(this._reject=null,i(n),this.dispose())})})}get promise(){return this._promise}dispose(){this._subscription&&(this._subscription(),this._subscription=null),this._reject&&(this._reject(new Me),this._reject=null)}}class yu{constructor(e){this.promise=e}dispose(){}}class qe extends di{constructor(e){super(),this._value=e}get(){return this._value}set(e){e!==this._value&&(this._value=e,this.emit(this._value))}}class Gs extends qe{constructor(e,t){super(e),this._freeCallback=t}onUnsubscribeLast(){super.onUnsubscribeLast(),this._freeCallback()}}class vu extends di{constructor(e,t){super(),this.source=e,this.mapper=t}onUnsubscribeLast(){super.onUnsubscribeLast(),this.sourceSubscription=this.sourceSubscription(),this.targetSubscription&&(this.targetSubscription=this.targetSubscription())}onSubscribeFirst(){super.onSubscribeFirst(),this.sourceSubscription=this.source.subscribe(()=>{this.updateTargetSubscription(),this.emit(this.get())}),this.updateTargetSubscription()}updateTargetSubscription(){const e=this.source.get();if(e){const t=this.mapper(e);if(t){this.targetSubscription||(this.targetSubscription=t.subscribe(()=>this.emit(this.get())));return}}this.targetSubscription&&(this.targetSubscription=this.targetSubscription())}get(){const e=this.source.get();if(!e)return;const t=this.mapper(e);return t?.get()}}function wu(s,e,t,i){const r=s(e);let n=!1;return r.elapsed().then(()=>{n=!0,t.abort()},()=>{}),i.then(o=>(r.abort(),o),o=>{throw r.abort(),o.name==="AbortError"&&n?new Se(`Request timed out after ${e}ms`,!0):o})}function pc(s,e=Math.random){return s.includes("?")?s=s+"&":s=s+"?",s+`_cacheBuster=${Math.ceil(e()*Number.MAX_SAFE_INTEGER)}`}function mc(s){var e;const t=new FormData;for(const[i,r]of s)((e=r.blob)==null?void 0:e.nativeBlob)&&r.name?t.set(i,r.blob.nativeBlob,r.name):t.set(i,r);return t}class bu{constructor(e,t){this._promise=e,this._xhr=t}abort(){this._xhr.abort()}response(){return this._promise}}function Su(s,{method:e,headers:t,timeout:i,format:r,uploadProgress:n}){const o=new XMLHttpRequest;if(n&&o.upload.addEventListener("progress",a=>n(a.loaded)),o.open(e,s),r==="buffer"&&(o.responseType="arraybuffer"),t)for(const[a,c]of t.entries())try{o.setRequestHeader(a,c)}catch(l){console.info(`Could not set ${a} header: ${l.message}`)}return i&&(o.timeout=i),o}function Eu(s,e,t){return new Promise((i,r)=>{s.addEventListener("load",()=>i(s)),s.addEventListener("abort",()=>r(new Me)),s.addEventListener("error",()=>r(new Se(`Error ${e} ${t}`))),s.addEventListener("timeout",()=>r(new Se(`Timeout ${e} ${t}`,!0)))})}function _c(s,e){let{cache:t,format:i,body:r,method:n}=e;t||(s=pc(s));const o=Su(s,e),a=Eu(o,n,s).then(c=>{const{status:l}=c;let d=null;return i==="buffer"?d=c.response:c.getResponseHeader("Content-Type")==="application/json"&&(d=JSON.parse(c.responseText)),{status:l,body:d}});return r?.nativeBlob&&(r=r.nativeBlob),r instanceof Map&&(r=mc(r)),o.send(r||null),new bu(a,o)}class Fo{constructor(e,t){if(t)this.promise=e,this._controller=t;else{const i=new Promise((r,n)=>{this._controller={abort(){const o=new Error("fetch request aborted");o.name="AbortError",n(o)}}});this.promise=Promise.race([e,i])}}abort(){this._controller.abort()}response(){return this.promise}}function Iu(s,e){return function(i,r){if(e?.haltRequests)return new Fo(new Promise(()=>{}),{});if(r?.uploadProgress)return _c(i,r);let{method:n,headers:o,body:a,timeout:c,format:l,cache:d=!1}=r;const u=typeof AbortController=="function"?new AbortController:null;a?.nativeBlob&&(a=a.nativeBlob),a instanceof Map&&(a=mc(a));let h={method:n,body:a};if(u&&(h=Object.assign(h,{signal:u.signal})),d||(i=pc(i)),h=Object.assign(h,{mode:"cors",credentials:"omit",referrer:"no-referrer",cache:"default"}),o){const f=new Headers;for(const[E,I]of o.entries())f.append(E,I);h.headers=f}const m=fetch(i,h).then(async f=>{const{status:E}=f;let I;try{l==="json"?I=await f.json():l==="buffer"?I=await f.arrayBuffer():l==="text"&&(I=await f.text())}catch(T){if(!(T.name==="SyntaxError"&&E>=400))throw T}return{status:E,body:I}},f=>{throw f.name==="AbortError"?new Me:f instanceof TypeError?new Se(`${n} ${i}: ${f.message}`):f}),_=new Fo(m,u);return c&&(_.promise=wu(s,c,_,_.promise)),_}}var F=(s=>(s.session="session",s.roomState="roomState",s.roomSummary="roomSummary",s.archivedRoomSummary="archivedRoomSummary",s.invites="invites",s.roomMembers="roomMembers",s.timelineEvents="timelineEvents",s.timelineRelations="timelineRelations",s.timelineFragments="timelineFragments",s.pendingEvents="pendingEvents",s.userIdentities="userIdentities",s.deviceIdentities="deviceIdentities",s.olmSessions="olmSessions",s.inboundGroupSessions="inboundGroupSessions",s.outboundGroupSessions="outboundGroupSessions",s.groupSessionDecryptions="groupSessionDecryptions",s.operations="operations",s.accountData="accountData",s))(F||{});const Ui=Object.values(F);class $e extends Error{constructor(e,t=null){super(e),t&&(this.errcode=t.name),this.cause=t}get name(){return"StorageError"}}const K={get minStorageKey(){return 0},get middleStorageKey(){return 2147483647},get maxStorageKey(){return 4294967295}};function Tu(s){return"objectStore"in s?`${s.objectStore.name}.${s.name}`:s.name}function xu(s){var e,t,i,r,n;return"objectStore"in s?(i=(t=(e=s.objectStore)==null?void 0:e.transaction)==null?void 0:t.db)==null?void 0:i.name:(n=(r=s.transaction)==null?void 0:r.db)==null?void 0:n.name}class fc extends $e{constructor(e,t,i=null){const r=t&&"source"in t?t.source:t,n=r?Tu(r):"",o=r?xu(r):"";let a=`${e} on ${o}.${n}`;i&&(a+=": ",typeof i.name=="string"&&(a+=`(name: ${i.name}) `),typeof i.code=="number"&&(a+=`(code: ${i.code}) `)),i&&(a+=i.message),super(a,i),this.storeName=n,this.databaseName=o}}class gn extends fc{constructor(e){const t=e.target,i=t.source,r=t.error;super("IDBRequest failed",i,r),this.errorEvent=e}preventTransactionAbort(){this.errorEvent.preventDefault()}}class Be extends fc{constructor(e,t,i,r){super(`${e}(${r.map(n=>JSON.stringify(n)).join(", ")}) failed`,t,i)}}const Vo={done:!0},pt={done:!1};function Br(s){const e=s.toString(16);return"0".repeat(8-e.length)+e}function qs(s){return parseInt(s,16)}function yn(s,e,t,i=window.indexedDB){const r=i.open(s,t);return r.onupgradeneeded=async n=>{const o=n.target,a=o.result,c=o.transaction,l=n.oldVersion;try{await e(a,c,l,t)}catch{try{c.abort()}catch{}}},ce(r)}function ce(s){return new Promise((e,t)=>{s.addEventListener("success",i=>{e(i.target.result)}),s.addEventListener("error",i=>{const r=new gn(i);t(r)})})}function Bi(s){return new Promise((e,t)=>{s.addEventListener("complete",()=>{e()}),s.addEventListener("abort",i=>{t(new Me)})})}function W(s,e){return new Promise((t,i)=>{s.onerror=r=>{i(new gn(r))},s.onsuccess=r=>{const n=r.target.result;if(!n){t(!1);return}const o=e(n.value,n.key,n),a=o?.done,c=o?.jumpTo;a?t(!0):c?n.continue(c):n.continue()}}).catch(t=>{throw new $e("iterateCursor failed",t)})}async function ku(s,e){const t=[];return await W(s,i=>(t.push(i),{done:e(t)})),t}var we=(s=>(s[s.All=1]="All",s[s.Debug=2]="Debug",s[s.Detail=3]="Detail",s[s.Info=4]="Info",s[s.Warn=5]="Warn",s[s.Error=6]="Error",s[s.Fatal=7]="Fatal",s[s.Off=8]="Off",s))(we||{});class zs{constructor(e){this._parentFilter=e}filter(e,t){return!(this._parentFilter&&!this._parentFilter.filter(e,t)||this._min!==void 0&&!Array.isArray(t)&&e.logLevel<this._min)}minLevel(e){return this._min=e,this}}function Lr(){}class Ru{constructor(){this.item=new Au(this)}log(){}run(e,t){return t(this.item)}wrapOrRun(e,t,i){return e?e.wrap(t,i):this.run(t,i)}runDetached(e,t){return new Promise(i=>i(t(this.item))).then(Lr,Lr),this.item}async export(){}get level(){return we}}class Au{constructor(e){this.logger=e}wrap(e,t){return t(this)}log(){return this}set(){return this}runDetached(e,t){return new Promise(i=>i(t(this))).then(Lr,Lr),this}wrapDetached(e,t){return this.refDetached()}refDetached(){}ensureRefId(){}get level(){return we}get duration(){return 0}catch(e){return e}child(){return this}finish(){}serialize(){}}const Cu=new Ru;class Ko{constructor(e,t){this._target=e,this._transaction=t}get idbFactory(){return this._transaction.idbFactory}get IDBKeyRange(){return this._transaction.IDBKeyRange}get databaseName(){return this._transaction.databaseName}_openCursor(e,t){return e&&t?this._target.openCursor(e,t):e?this._target.openCursor(e):t?this._target.openCursor(null,t):this._target.openCursor()}supports(e){return this._target.supports(e)}count(e){return ce(this._target.count(e))}get(e){return ce(this._target.get(e))}getKey(e){return this._target.supports("getKey")?ce(this._target.getKey(e)):ce(this._target.get(e)).then(t=>{if(t){let i=this._target.keyPath;return typeof i=="string"&&(i=[i]),i.reduce((r,n)=>r[n],t)}})}reduce(e,t,i){return this._reduce(e,t,i,"next")}reduceReverse(e,t,i){return this._reduce(e,t,i,"prev")}selectLimit(e,t){return this._selectLimit(e,t,"next")}selectLimitReverse(e,t){return this._selectLimit(e,t,"prev")}selectWhile(e,t){return this._selectWhile(e,t,"next")}selectWhileReverse(e,t){return this._selectWhile(e,t,"prev")}async selectAll(e,t){const i=this._openCursor(e,t),r=[];return await W(i,n=>(r.push(n),pt)),r}selectFirst(e){return this._find(e,()=>!0,"next")}selectLast(e){return this._find(e,()=>!0,"prev")}find(e,t){return this._find(e,t,"next")}findReverse(e,t){return this._find(e,t,"prev")}async findMaxKey(e){const t=this._target.openKeyCursor(e,"prev");let i;return await W(t,(r,n)=>(i=n,Vo)),i}async iterateValues(e,t){const i=this._target.openCursor(e,"next");await W(i,(r,n,o)=>({done:t(r,n,o)}))}async iterateKeys(e,t){const i=this._target.openKeyCursor(e,"next");await W(i,(r,n,o)=>({done:t(n,o)}))}async findExistingKeys(e,t,i){const r=(u,h)=>t?-this.idbFactory.cmp(u,h):this.idbFactory.cmp(u,h),n=e.slice().sort(r),o=n[0],a=n[n.length-1],c=t?"prev":"next",l=this._target.openKeyCursor(this.IDBKeyRange.bound(o,a),c);let d=0;await W(l,(u,h,m)=>{for(;d<n.length&&r(n[d],h)<0;)d+=1;let _=!1;if(n[d]===h){const f=m.primaryKey;_=i(h,f),d+=1}return _||d>=n.length?Vo:{done:!1,jumpTo:n[d]}})}_reduce(e,t,i,r){let n=i;const o=this._openCursor(e,r);return W(o,a=>(n=t(n,a),pt))}_selectLimit(e,t,i){return this._selectUntil(e,r=>r.length===t,i)}async _selectUntil(e,t,i){const r=this._openCursor(e,i),n=[];return await W(r,o=>(n.push(o),{done:t(n,o)})),n}async _selectWhile(e,t,i){const r=this._openCursor(e,i),n=[];return await W(r,o=>{const a=t(o);return a&&n.push(o),{done:!a}}),n}async iterateWhile(e,t){const i=this._openCursor(e,"next");await W(i,r=>({done:!t(r)}))}async _find(e,t,i){const r=this._openCursor(e,i);let n;if(await W(r,a=>{const c=t(a);return c&&(n=a),{done:c}}))return n}}const Qe=!1;function Ze(s,e,t){var i,r;const n=t?.name,o=(r=(i=t?.transaction)==null?void 0:i.db)==null?void 0:r.name;console.info(`${o}.${n}.${s}(${e.map(a=>JSON.stringify(a)).join(", ")})`)}class $o{constructor(e){this._qt=e}get keyPath(){return this._qtStore.keyPath}get _qtStore(){return"objectStore"in this._qt?this._qt.objectStore:this._qt}supports(e){return!!this._qt[e]}openKeyCursor(e,t){try{return this._qt.openKeyCursor?(Qe&&Ze("openKeyCursor",[e,t],this._qt),this._qt.openKeyCursor(e,t)):(Qe&&Ze("openCursor",[e,t],this._qt),this.openCursor(e,t))}catch(i){throw new Be("openKeyCursor",this._qt,i,[e,t])}}openCursor(e,t){try{return Qe&&Ze("openCursor",[],this._qt),this._qt.openCursor(e,t)}catch(i){throw new Be("openCursor",this._qt,i,[e,t])}}put(e,t){try{return Qe&&Ze("put",[e,t],this._qt),this._qtStore.put(e,t)}catch(i){throw new Be("put",this._qt,i,[e,t])}}add(e,t){try{return Qe&&Ze("add",[e,t],this._qt),this._qtStore.add(e,t)}catch(i){throw new Be("add",this._qt,i,[e,t])}}get(e){try{return Qe&&Ze("get",[e],this._qt),this._qt.get(e)}catch(t){throw new Be("get",this._qt,t,[e])}}getKey(e){try{return Qe&&Ze("getKey",[e],this._qt),this._qt.getKey(e)}catch(t){throw new Be("getKey",this._qt,t,[e])}}delete(e){try{return Qe&&Ze("delete",[e],this._qt),this._qtStore.delete(e)}catch(t){throw new Be("delete",this._qt,t,[e])}}count(e){try{return this._qt.count(e)}catch(t){throw new Be("count",this._qt,t,[e])}}index(e){try{return this._qtStore.index(e)}catch(t){throw new Be("index",this._qt,t,[e])}}get indexNames(){return Array.from(this._qtStore.indexNames)}}class gc extends Ko{constructor(e,t){super(new $o(e),t)}get _idbStore(){return this._target}index(e){return new Ko(new $o(this._idbStore.index(e)),this._transaction)}put(e,t){const i=this._idbStore.put(e);this._prepareErrorLog(i,t,"put",void 0,e)}add(e,t){const i=this._idbStore.add(e);this._prepareErrorLog(i,t,"add",void 0,e)}async tryAdd(e,t){try{return await ce(this._idbStore.add(e)),!0}catch(i){if(i instanceof gn)return t.log({l:"could not write",id:this._getKeys(e),e:i},t.level.Warn),i.preventTransactionAbort(),!1;throw i}}delete(e,t){const i=this._idbStore.delete(e);this._prepareErrorLog(i,t,"delete",e,void 0)}_prepareErrorLog(e,t,i,r,n){t&&t.ensureRefId(),ce(e).catch(o=>{let a;n?a=this._getKeys(n):r&&(a=[r]),this._transaction.addWriteError(o,t,i,a)})}_getKeys(e){const t=[],{keyPath:i}=this._idbStore;try{t.push(this._readKeyPath(e,i))}catch{console.warn("could not read keyPath",i)}for(const r of this._idbStore.indexNames)try{const n=this._idbStore.index(r);t.push(this._readKeyPath(e,n.keyPath))}catch{console.warn("could not read index",r)}return t}_readKeyPath(e,t){if(Array.isArray(t)){let i=e;for(const r of t)if(typeof i=="object")i=i[r];else break;return i}else return e[t]}}function We(...s){const e={};for(const t of s)e[t]=t;return Object.freeze(e)}const Rt=We("Sync","Timeline","Retry"),me="e2ee:",vn="m.olm.v1.curve25519-aes-sha2",De="m.megolm.v1.aes-sha2";class te extends Error{constructor(e,t,i=null){super(`Decryption error ${e}${i?": "+JSON.stringify(i):""}`),this.code=e,this.event=t,this.details=i}}const yc="ed25519";function vc(s,e,t,i,r,n=void 0){var o,a;const c=Object.assign({},r);delete c.unsigned,delete c.signatures;const l=nc.stringify(c),d=(a=(o=r?.signatures)==null?void 0:o[e])==null?void 0:a[`${yc}:${t}`];try{if(!d)throw new Error("no signature");return s.ed25519_verify(i,l,d),!0}catch(u){if(n){const h=n.log({l:"Invalid signature, ignoring.",ed25519Key:i,canonicalJson:l,signature:d});h.error=u,h.logLevel=n.level.Warn}return!1}}function Nu(){return{type:"m.room.encryption",state_key:"",content:{algorithm:De,rotation_period_ms:6048e5,rotation_period_msgs:100}}}const lr=Object.freeze({Joined:"joined",Invited:"invited",WorldReadable:"world_readable",Shared:"shared"});function dr(s,e){switch(e){case lr.WorldReadable:return!0;case lr.Shared:return s!==void 0;case lr.Joined:return s==="join";case lr.Invited:return s==="invite"||s==="join";default:return!1}}function Mu(s){return JSON.stringify(wc(s))}function Du(s){return bc(JSON.parse(s))}function wc(s){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){if(s.byteLength)return{_type:s.constructor.name,value:Array.from(s)};let e={};for(const t in s)s.hasOwnProperty(t)&&(e[t]=wc(s[t]));return e}else return s}function bc(s){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){if(typeof s._type=="string")switch(s._type){case"Int8Array":return Int8Array.from(s.value);case"Uint8Array":return Uint8Array.from(s.value);case"Uint8ClampedArray":return Uint8ClampedArray.from(s.value);case"Int16Array":return Int16Array.from(s.value);case"Uint16Array":return Uint16Array.from(s.value);case"Int32Array":return Int32Array.from(s.value);case"Uint32Array":return Uint32Array.from(s.value);case"Float32Array":return Float32Array.from(s.value);case"Float64Array":return Float64Array.from(s.value);case"BigInt64Array":return BigInt64Array.from(s.value);case"BigUint64Array":return BigUint64Array.from(s.value);default:return s.value}let e={};for(const t in s)s.hasOwnProperty(t)&&(e[t]=bc(s[t]));return e}else return s}function Sc(s){return`${s}.session.`}function Pu(s,e){const t=[];for(let i=0;i<s.length;i++){const r=s.key(i);r?.startsWith(Sc(e))&&t.push(r)}for(const i of t)s.removeItem(i)}class wn{constructor(e,t){this._sessionStore=e,this._localStorage=t}get _localStorageKeyPrefix(){return Sc(this._sessionStore.databaseName)}async get(e){const t=await this._sessionStore.get(e);if(t)return t.value}_writeKeyToLocalStorage(e,t){try{const i=this._localStorageKeyPrefix+e,r=Mu(t);this._localStorage.setItem(i,r)}catch(i){console.error("could not write to localStorage",i)}}writeE2EEIdentityToLocalStorage(){this._sessionStore.iterateValues(void 0,(e,t)=>(t.startsWith(me)&&this._writeKeyToLocalStorage(t,e.value),!1))}async tryRestoreE2EEIdentityFromLocalStorage(e){let t=!1;const i=this._localStorageKeyPrefix,r=i+me;for(let n=0;n<this._localStorage.length;n+=1){const o=this._localStorage.key(n);if(o.startsWith(r)){const a=Du(this._localStorage.getItem(o)),c=o.substr(i.length),l=await this._sessionStore.getKey(c)===c;e.set(c,!l),l||(this._sessionStore.put({key:c,value:a}),t=!0)}}return t}set(e,t){e.startsWith(me)&&this._writeKeyToLocalStorage(e,t),this._sessionStore.put({key:e,value:t})}add(e,t){e.startsWith(me)&&this._writeKeyToLocalStorage(e,t),this._sessionStore.add({key:e,value:t})}remove(e){e.startsWith(me)&&this._localStorage.removeItem(this._localStorageKeyPrefix+e),this._sessionStore.delete(e)}}class jo{constructor(e){this._summaryStore=e}getAll(){return this._summaryStore.selectAll()}set(e){this._summaryStore.put(e)}get(e){return this._summaryStore.get(e)}async has(e){const t=await this._summaryStore.getKey(e);return e===t}remove(e){this._summaryStore.delete(e)}}class Ou{constructor(e){this._inviteStore=e}getAll(){return this._inviteStore.selectAll()}set(e){this._inviteStore.put(e)}remove(e){this._inviteStore.delete(e)}}class q{constructor(e,t){this.fragmentId=e,this.eventIndex=t}nextFragmentKey(){return new q(this.fragmentId+1,K.middleStorageKey)}nextKeyForDirection(e){return e.isForward?this.nextKey():this.previousKey()}previousKey(){return new q(this.fragmentId,this.eventIndex-1)}nextKey(){return new q(this.fragmentId,this.eventIndex+1)}static get maxKey(){return new q(K.maxStorageKey,K.maxStorageKey)}static get minKey(){return new q(K.minStorageKey,K.minStorageKey)}static get defaultLiveKey(){return q.defaultFragmentKey(K.minStorageKey)}static defaultFragmentKey(e){return new q(e,K.middleStorageKey)}toString(){return`[${this.fragmentId}/${this.eventIndex}]`}equals(e){return this.fragmentId===e?.fragmentId&&this.eventIndex===e?.eventIndex}}function Ec(s,e,t){return{fragmentId:s.fragmentId,eventIndex:s.eventIndex,roomId:e,event:t}}function Ri(s,e,t){t.isForward?s.push(e):s.unshift(e)}function Uu(s,e,t){return t.isForward?s.concat(e):e.concat(s)}function ye(s,e,t){return`${s}|${Br(e)}|${Br(t)}`}function Bu(s){const[e,t,i]=s.split("|");return{roomId:e,eventKey:new q(qs(t),qs(i))}}function ur(s,e){return`${s}|${e}`}function Go(s){const[e,t]=s.split("|");return{roomId:e,eventId:t}}class hr{constructor(e,t,i,r,n=!1,o=!1){this._IDBKeyRange=e,this._only=t,this._lower=i,this._upper=r,this._lowerOpen=n,this._upperOpen=o}asIDBKeyRange(e){try{if(this._only)return this._IDBKeyRange.only(ye(e,this._only.fragmentId,this._only.eventIndex));if(this._lower&&!this._upper)return this._IDBKeyRange.bound(ye(e,this._lower.fragmentId,this._lower.eventIndex),ye(e,this._lower.fragmentId,K.maxStorageKey),this._lowerOpen,!1);if(!this._lower&&this._upper)return this._IDBKeyRange.bound(ye(e,this._upper.fragmentId,K.minStorageKey),ye(e,this._upper.fragmentId,this._upper.eventIndex),!1,this._upperOpen);if(this._lower&&this._upper)return this._IDBKeyRange.bound(ye(e,this._lower.fragmentId,this._lower.eventIndex),ye(e,this._upper.fragmentId,this._upper.eventIndex),this._lowerOpen,this._upperOpen)}catch(t){throw new $e("IDBKeyRange failed with data: "+JSON.stringify(this),t)}}}class Lu{constructor(e){this._timelineStore=e}onlyRange(e){return new hr(this._timelineStore.IDBKeyRange,e)}upperBoundRange(e,t=!1){return new hr(this._timelineStore.IDBKeyRange,void 0,void 0,e,void 0,t)}lowerBoundRange(e,t=!1){return new hr(this._timelineStore.IDBKeyRange,void 0,e,void 0,t)}boundRange(e,t,i=!1,r=!1){return new hr(this._timelineStore.IDBKeyRange,void 0,e,t,i,r)}async lastEvents(e,t,i){const r=q.maxKey;return r.fragmentId=t,this.eventsBefore(e,r,i)}async firstEvents(e,t,i){const r=q.minKey;return r.fragmentId=t,this.eventsAfter(e,r,i)}eventsAfter(e,t,i){const r=this.lowerBoundRange(t,!0).asIDBKeyRange(e);return this._timelineStore.selectLimit(r,i)}async eventsBefore(e,t,i){const r=this.upperBoundRange(t,!0).asIDBKeyRange(e),n=await this._timelineStore.selectLimitReverse(r,i);return n.reverse(),n}async getEventKeysForIds(e,t){const i=this._timelineStore.index("byEventId"),r=t.map(o=>ur(e,o)),n=new Map;return await i.findExistingKeys(r,!1,(o,a)=>{const{eventId:c}=Go(o),{eventKey:l}=Bu(a);return n.set(c,l),!1}),n}async findFirstOccurringEventId(e,t){const i=this._timelineStore.index("byEventId"),r=t.map(c=>ur(e,c)),n=new Array(r.length);let o;function a(){for(let c=0;c<n.length;++c){if(n[c]===void 0)return;if(n[c]===!0)return r[c]}}return await i.findExistingKeys(r,!1,(c,l)=>{const d=r.indexOf(c);return n[d]=l,o=a(),!!o}),o&&Go(o).eventId}tryInsert(e,t){return e.key=ye(e.roomId,e.fragmentId,e.eventIndex),e.eventIdKey=ur(e.roomId,e.event.event_id),this._timelineStore.tryAdd(e,t)}update(e){this._timelineStore.put(e)}get(e,t){return this._timelineStore.get(ye(e,t.fragmentId,t.eventIndex))}getByEventId(e,t){return this._timelineStore.index("byEventId").get(ur(e,t))}removeAllForRoom(e){const t=ye(e,K.minStorageKey,K.minStorageKey),i=ye(e,K.maxStorageKey,K.maxStorageKey),r=this._timelineStore.IDBKeyRange.bound(t,i);this._timelineStore.delete(r)}}const ue="\0",ie="\u{10FFFF}";function ke(s,e,t,i){return`${s}|${e}|${t}|${i}`}function qo(s){const[e,t,i,r]=s.split("|");return{roomId:e,targetEventId:t,relType:i,sourceEventId:r}}class Fu{constructor(e){this._store=e}add(e,t,i,r){this._store.add({key:ke(e,t,i,r)})}remove(e,t,i,r){this._store.delete(ke(e,t,i,r))}removeAllForTarget(e,t){const i=this._store.IDBKeyRange.bound(ke(e,t,ue,ue),ke(e,t,ie,ie),!0,!0);this._store.delete(i)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(ke(e,ue,ue,ue),ke(e,ie,ie,ie),!0,!0);this._store.delete(t)}async getForTargetAndType(e,t,i){const r=this._store.IDBKeyRange.bound(ke(e,t,i,ue),ke(e,t,i,ie),!0,!0);return(await this._store.selectAll(r)).map(o=>qo(o.key))}async getAllForTarget(e,t){const i=this._store.IDBKeyRange.bound(ke(e,t,ue,ue),ke(e,t,ie,ie),!0,!0);return(await this._store.selectAll(i)).map(n=>qo(n.key))}}function zo(s,e,t){return`${s}|${e}|${t}`}class Vu{constructor(e){this._roomStateStore=e}get(e,t,i){const r=zo(e,t,i);return this._roomStateStore.get(r)}set(e,t){const i=zo(e,t.type,t.state_key),r={roomId:e,event:t,key:i};this._roomStateStore.put(r)}removeAllForRoom(e){const t=this._roomStateStore.IDBKeyRange.bound(e,`${e}|${ie}`,!0,!0);this._roomStateStore.delete(t)}}function pr(s,e){return`${s}|${e}`}function Ku(s){const[e,t]=s.split("|");return{roomId:e,userId:t}}class Ic{constructor(e){this._roomMembersStore=e}get(e,t){return this._roomMembersStore.get(pr(e,t))}set(e){e.key=pr(e.roomId,e.userId),this._roomMembersStore.put(e)}getAll(e){const t=this._roomMembersStore.IDBKeyRange.lowerBound(pr(e,""));return this._roomMembersStore.selectWhile(t,i=>i.roomId===e)}async getAllUserIds(e){const t=[],i=this._roomMembersStore.IDBKeyRange.lowerBound(pr(e,""));return await this._roomMembersStore.iterateKeys(i,r=>{const n=Ku(r);return n.roomId===e?(t.push(n.userId),!1):!0}),t}removeAllForRoom(e){const t=this._roomMembersStore.IDBKeyRange.bound(e,`${e}|${ie}`,!0,!0);this._roomMembersStore.delete(t)}}function mr(s,e){return`${s}|${Br(e)}`}class $u{constructor(e){this._store=e}_allRange(e){try{return this._store.IDBKeyRange.bound(mr(e,K.minStorageKey),mr(e,K.maxStorageKey))}catch(t){throw new $e(`error from IDBKeyRange with roomId ${e}`,t)}}all(e){return this._store.selectAll(this._allRange(e))}liveFragment(e){return this._store.findReverse(this._allRange(e),t=>typeof t.nextId!="number"&&typeof t.nextToken!="string")}add(e){e.key=mr(e.roomId,e.id),this._store.add(e)}update(e){this._store.put(e)}get(e,t){return this._store.get(mr(e,t))}removeAllForRoom(e){this._store.delete(this._allRange(e))}}function bt(s,e){return`${s}|${Br(e)}`}function ju(s){const[e,t]=s.split("|"),i=qs(t);return{roomId:e,queueIndex:i}}class Gu{constructor(e){this._eventStore=e}async getMaxQueueIndex(e){const t=this._eventStore.IDBKeyRange.bound(bt(e,K.minStorageKey),bt(e,K.maxStorageKey),!1,!1),i=await this._eventStore.findMaxKey(t);if(i)return ju(i).queueIndex}remove(e,t){const i=this._eventStore.IDBKeyRange.only(bt(e,t));this._eventStore.delete(i)}async exists(e,t){const i=this._eventStore.IDBKeyRange.only(bt(e,t));return!!await this._eventStore.getKey(i)}add(e){e.key=bt(e.roomId,e.queueIndex),this._eventStore.add(e)}update(e){this._eventStore.put(e)}getAll(){return this._eventStore.selectAll()}removeAllForRoom(e){const t=bt(e,K.minStorageKey),i=bt(e,K.maxStorageKey),r=this._eventStore.IDBKeyRange.bound(t,i);this._eventStore.delete(r)}}class qu{constructor(e){this._store=e}get(e){return this._store.get(e)}set(e){this._store.put(e)}remove(e){this._store.delete(e)}}function St(s,e){return`${s}|${e}`}function zu(s){const[e,t]=s.split("|");return{userId:e,deviceId:t}}class Hu{constructor(e){this._store=e}getAllForUserId(e){const t=this._store.IDBKeyRange.lowerBound(St(e,""));return this._store.selectWhile(t,i=>i.userId===e)}async getAllDeviceIds(e){const t=[],i=this._store.IDBKeyRange.lowerBound(St(e,""));return await this._store.iterateKeys(i,r=>{const n=zu(r);return n.userId===e?(t.push(n.deviceId),!1):!0}),t}get(e,t){return this._store.get(St(e,t))}set(e){e.key=St(e.userId,e.deviceId),this._store.put(e)}getByCurve25519Key(e){return this._store.index("byCurve25519Key").get(e)}remove(e,t){this._store.delete(St(e,t))}removeAllForUser(e){const t=this._store.IDBKeyRange.bound(St(e,ue),St(e,ie),!0,!0);this._store.delete(t)}}function vi(s,e){return`${s}|${e}`}function Wu(s){const[e,t]=s.split("|");return{senderKey:e,sessionId:t}}class Yu{constructor(e){this._store=e}async getSessionIds(e){const t=[],i=this._store.IDBKeyRange.lowerBound(vi(e,""));return await this._store.iterateKeys(i,r=>{const n=Wu(r);return n.senderKey===e?(t.push(n.sessionId),!1):!0}),t}getAll(e){const t=this._store.IDBKeyRange.lowerBound(vi(e,""));return this._store.selectWhile(t,i=>i.senderKey===e)}get(e,t){return this._store.get(vi(e,t))}set(e){e.key=vi(e.senderKey,e.sessionId),this._store.put(e)}remove(e,t){this._store.delete(vi(e,t))}}var Jr=(s=>(s[s.NotBackedUp=0]="NotBackedUp",s[s.BackedUp=1]="BackedUp",s))(Jr||{}),Yi=(s=>(s[s.DeviceMessage=1]="DeviceMessage",s[s.Backup=2]="Backup",s[s.Outbound=3]="Outbound",s))(Yi||{});function zt(s,e,t){return`${s}|${e}|${t}`}class Ju{constructor(e){this._store=e}async has(e,t,i){const r=zt(e,t,i),n=await this._store.getKey(r);return r===n}get(e,t,i){return this._store.get(zt(e,t,i))}set(e){const t=e;t.key=zt(e.roomId,e.senderKey,e.sessionId),this._store.put(t)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(zt(e,ue,ue),zt(e,ie,ie));this._store.delete(t)}countNonBackedUpSessions(){return this._store.index("byBackup").count(this._store.IDBKeyRange.only(0))}getFirstNonBackedUpSessions(e){return this._store.index("byBackup").selectLimit(this._store.IDBKeyRange.only(0),e)}async markAsBackedUp(e,t,i){const r=await this._store.get(zt(e,t,i));r&&(r.backup=1,this._store.put(r))}async markAllAsNotBackedUp(){const e=this._store.IDBKeyRange.only(1);let t=0;return await this._store.index("byBackup").iterateValues(e,(i,r,n)=>(i.backup=0,n.update(i),t+=1,!1)),t}}class Xu{constructor(e){this._store=e}remove(e){this._store.delete(e)}get(e){return this._store.get(e)}set(e){this._store.put(e)}}function _r(s,e,t){return`${s}|${e}|${t}`}class Qu{constructor(e){this._store=e}get(e,t,i){return this._store.get(_r(e,t,i))}set(e,t,i,r){r.key=_r(e,t,i),this._store.put(r)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(_r(e,ue,ue),_r(e,ie,ie));this._store.delete(t)}}function Ii(s,e){return`${s}|${e}`}class Zu{constructor(e){this._store=e}getAll(){return this._store.selectAll()}async getAllByTypeAndScope(e,t){const i=Ii(t,e),r=[];return await this._store.index("byScopeAndType").iterateWhile(i,n=>n.scopeTypeKey!==i?!1:(r.push(n),!0)),r}add(e){e.scopeTypeKey=Ii(e.scope,e.type),this._store.add(e)}update(e){this._store.put(e)}remove(e){this._store.delete(e)}async removeAllForScope(e){const t=this._store.IDBKeyRange.bound(Ii(e,ue),Ii(e,ie));await this._store.index("byScopeAndType").iterateValues(t,(r,n,o)=>(o.delete(),!0))}}class eh{constructor(e){this._store=e}async get(e){return await this._store.get(e)}set(e){this._store.put(e)}}class th{constructor(e,t,i,r){this.error=e,this.refItem=t,this.operationName=i,this.keys=r}}class Ho{constructor(e,t,i){this._txn=e,this._allowedStoreNames=t,this._stores={},this._storage=i,this._writeErrors=[]}get idbFactory(){return this._storage.idbFactory}get IDBKeyRange(){return this._storage.IDBKeyRange}get databaseName(){return this._storage.databaseName}get logger(){return this._storage.logger}_idbStore(e){if(!this._allowedStoreNames.includes(e))throw new $e(`Invalid store for transaction: ${e}, only ${this._allowedStoreNames.join(", ")} are allowed.`);return new gc(this._txn.objectStore(e),this)}_store(e,t){if(!this._stores[e]){const i=this._idbStore(e);this._stores[e]=t(i)}return this._stores[e]}get session(){return this._store(F.session,e=>new wn(e,this._storage.localStorage))}get roomSummary(){return this._store(F.roomSummary,e=>new jo(e))}get archivedRoomSummary(){return this._store(F.archivedRoomSummary,e=>new jo(e))}get invites(){return this._store(F.invites,e=>new Ou(e))}get timelineFragments(){return this._store(F.timelineFragments,e=>new $u(e))}get timelineEvents(){return this._store(F.timelineEvents,e=>new Lu(e))}get timelineRelations(){return this._store(F.timelineRelations,e=>new Fu(e))}get roomState(){return this._store(F.roomState,e=>new Vu(e))}get roomMembers(){return this._store(F.roomMembers,e=>new Ic(e))}get pendingEvents(){return this._store(F.pendingEvents,e=>new Gu(e))}get userIdentities(){return this._store(F.userIdentities,e=>new qu(e))}get deviceIdentities(){return this._store(F.deviceIdentities,e=>new Hu(e))}get olmSessions(){return this._store(F.olmSessions,e=>new Yu(e))}get inboundGroupSessions(){return this._store(F.inboundGroupSessions,e=>new Ju(e))}get outboundGroupSessions(){return this._store(F.outboundGroupSessions,e=>new Xu(e))}get groupSessionDecryptions(){return this._store(F.groupSessionDecryptions,e=>new Qu(e))}get operations(){return this._store(F.operations,e=>new Zu(e))}get accountData(){return this._store(F.accountData,e=>new eh(e))}async complete(e){try{await Bi(this._txn)}catch(t){throw this._writeErrors.length?(this._logWriteErrors(e),this._writeErrors[0].error):t}}getCause(e){return e instanceof $e&&e.errcode==="AbortError"&&this._writeErrors.length?this._writeErrors[0].error:e}abort(e){try{this._txn.abort()}catch{e?.set("couldNotAbortTxn",!0)}this._writeErrors.length&&this._logWriteErrors(e)}addWriteError(e,t,i,r){(e.errcode!=="AbortError"||this._writeErrors.length===0)&&this._writeErrors.push(new th(e,t,i,r))}_logWriteErrors(e){const t=r=>{e||r.set("allowedStoreNames",this._allowedStoreNames);for(const n of this._writeErrors)r.wrap({l:n.operationName,id:n.keys},o=>{n.refItem&&o.refDetached(n.refItem),o.catch(n.error)})},i=`${this._writeErrors.length} storage write operation(s) failed`;e?e.wrap(i,t):this.logger.run(i,t)}}const Wo="782rh281re38-boguskey";class ih{constructor(e,t,i,r,n,o){this._db=e,this.idbFactory=t,this.IDBKeyRange=i,this._hasWebkitEarlyCloseTxnBug=r,this.storeNames=F,this.localStorage=n,this.logger=o}_validateStoreNames(e){const t=e.findIndex(i=>!Ui.includes(i));if(t!==-1)throw new $e(`Tried top, a transaction unknown store ${e[t]}`)}async readTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readonly");return this._hasWebkitEarlyCloseTxnBug&&await ce(t.objectStore(e[0]).get(Wo)),new Ho(t,e,this)}catch(t){throw new $e("readTxn failed",t)}}async readWriteTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readwrite");return this._hasWebkitEarlyCloseTxnBug&&await ce(t.objectStore(e[0]).get(Wo)),new Ho(t,e,this)}catch(t){throw new $e("readWriteTxn failed",t)}}close(){this._db.close()}get databaseName(){return this._db.name}}async function rh(s){const e=s.transaction(Ui,"readonly"),t={};return await Promise.all(Ui.map(async i=>{const r=t[i]=[],n=e.objectStore(i);await W(n.openCursor(),o=>(r.push(o),pt))})),t}async function sh(s,e){const t=s.transaction(Ui,"readwrite");for(const i of Ui){const r=t.objectStore(i);for(const n of e[i])r.add(n)}await Bi(t)}function Hs(s){var e;return((e=s.unsigned)==null?void 0:e.prev_content)||s.prev_content}const Ce="m.room.redaction";function Ws(s){var e;return!!((e=s?.unsigned)!=null&&e.redacted_because)}var G=(s=>(s[s.None=1]="None",s[s.BeingCreated=2]="BeingCreated",s[s.Invited=4]="Invited",s[s.Joined=8]="Joined",s[s.Replaced=16]="Replaced",s[s.Archived=32]="Archived",s))(G||{}),je=(s=>(s[s.DirectMessage=0]="DirectMessage",s[s.Private=1]="Private",s[s.Public=2]="Public",s))(je||{});function nh(s,e){var t,i;let r;const n=c=>{const l=e(c);l instanceof Promise&&(r=r??[],r.push(l))},o=(t=s.state)==null?void 0:t.events;if(o)for(let c=0;c<o.length;c++)n(o[c]);let a=(i=s.timeline)==null?void 0:i.events;if(a)for(let c=0;c<a.length;c++){const l=a[c];typeof l.state_key=="string"&&n(l)}if(r)return Promise.all(r).then(()=>{})}const _e="m.room.member";class B{constructor(e){this._data=e}static fromUserId(e,t,i){return new B({roomId:e,userId:t,membership:i})}static fromMemberEvent(e,t){const i=t?.state_key;if(typeof i!="string")return;const r=t.content,n=Hs(t),o=r?.membership,a=r?.displayname||n?.displayname,c=r?.avatar_url||n?.avatar_url;return this._validateAndCreateMember(e,i,o,a,c)}static fromReplacingMemberEvent(e,t){const i=t&&t.state_key;if(typeof i!="string")return;const r=Hs(t);return this._validateAndCreateMember(e,i,r?.membership,r?.displayname,r?.avatar_url)}static _validateAndCreateMember(e,t,i,r,n){if(typeof i=="string")return new B({roomId:e,userId:t,membership:i,avatarUrl:n,displayName:r})}get membership(){return this._data.membership}get displayName(){return this._data.displayName}get name(){return this._data.displayName||this._data.userId}get avatarUrl(){return this._data.avatarUrl}get roomId(){return this._data.roomId}get userId(){return this._data.userId}serialize(){return this._data}equals(e){const t=this._data,i=e._data;return t.roomId===i.roomId&&t.userId===i.userId&&t.membership===i.membership&&t.displayName===i.displayName&&t.avatarUrl===i.avatarUrl}}class Tc{constructor(e,t){this.member=e,this.previousMembership=t}get roomId(){return this.member.roomId}get userId(){return this.member.userId}get membership(){return this.member.membership}get wasInvited(){return this.previousMembership==="invite"&&this.membership!=="invite"}get hasLeft(){return this.previousMembership==="join"&&this.membership!=="join"}get hasJoined(){return this.previousMembership!=="join"&&this.membership==="join"}}const xc=[ah,ch,lh,dh,uh,hh,ph,mh,_h,fh,gh,yh,vh,wh,bh,Sh];function oh(s){return{databaseName:s.name,get idbFactory(){throw new Error("unused")},get IDBKeyRange(){throw new Error("unused")},addWriteError(){}}}function ah(s){s.createObjectStore("session",{keyPath:"key"}),s.createObjectStore("roomSummary",{keyPath:"roomId"}),s.createObjectStore("timelineFragments",{keyPath:"key"}),s.createObjectStore("timelineEvents",{keyPath:"key"}).createIndex("byEventId","eventIdKey",{unique:!0}),s.createObjectStore("roomState",{keyPath:"key"}),s.createObjectStore("pendingEvents",{keyPath:"key"})}async function ch(s,e){const t=new Ic(s.createObjectStore("roomMembers",{keyPath:"key"})),i=e.objectStore("roomState");await W(i.openCursor(),r=>{if(r.event.type===_e){i.delete(r.key);const n=B.fromMemberEvent(r.roomId,r.event);n&&t.set(n.serialize())}return pt})}async function lh(s,e,t){const i=e.objectStore("session");try{const n=await ce(i.get(1));if(n){i.delete(1);const{syncToken:o,syncFilterId:a,serverVersions:c}=n.value,l=new wn(i,t);l.set("sync",{token:o,filterId:a}),l.set("serverVersions",c)}}catch(r){e.abort(),console.error("could not migrate session",r.stack)}}function dh(s){s.createObjectStore("userIdentities",{keyPath:"userId"}),s.createObjectStore("deviceIdentities",{keyPath:"key"}).createIndex("byCurve25519Key","curve25519Key",{unique:!0}),s.createObjectStore("olmSessions",{keyPath:"key"}),s.createObjectStore("inboundGroupSessions",{keyPath:"key"}),s.createObjectStore("outboundGroupSessions",{keyPath:"roomId"}),s.createObjectStore("groupSessionDecryptions",{keyPath:"key"}),s.createObjectStore("operations",{keyPath:"id"}).createIndex("byTypeAndScope","typeScopeKey",{unique:!1})}async function uh(s,e){var t;const i=e.objectStore("roomSummary"),r=e.objectStore("roomState"),n=[];await W(i.openCursor(),o=>(n.push(o),pt));for(const o of n){const a=await ce(r.get(`${o.roomId}|m.room.encryption|`));a&&(o.encryption=(t=a?.event)==null?void 0:t.content,delete o.isEncrypted,i.put(o))}}function hh(s){s.createObjectStore("accountData",{keyPath:"type"})}function ph(s){s.createObjectStore("invites",{keyPath:"roomId"})}function mh(s){s.createObjectStore("archivedRoomSummary",{keyPath:"summary.roomId"})}async function _h(s,e){try{const t=e.objectStore("operations");t.deleteIndex("byTypeAndScope"),await W(t.openCursor(),(i,r,n)=>{const{typeScopeKey:o}=i;delete i.typeScopeKey;const[a,c]=o.split("|");return i.scopeTypeKey=Ii(c,a),n.update(i),pt}),t.createIndex("byScopeAndType","scopeTypeKey",{unique:!1})}catch(t){e.abort(),console.error("could not migrate operations",t.stack)}}function fh(s){s.createObjectStore("timelineRelations",{keyPath:"key"})}function gh(){}async function yh(s,e){const t=e.objectStore("session"),i=await ce(t.get("ssssKey"));i&&t.put({key:`${me}ssssKey`,value:i.value})}async function vh(s,e,t,i){const r=e.objectStore("session"),n=new wn(new gc(r,oh(s)),t);n.writeE2EEIdentityToLocalStorage();const o=await n.tryRestoreE2EEIdentityFromLocalStorage(i);i.set("restored",o)}async function wh(s,e){for(const t of s.objectStoreNames){const i=e.objectStore(t);switch(t){case"inboundGroupSessions":case"outboundGroupSessions":case"olmSessions":case"operations":continue;case"session":{await W(i.openCursor(),(r,n,o)=>(n.startsWith(me)||o.delete(),pt));break}default:{i.clear();break}}}}async function bh(s,e,t,i){e.objectStore("inboundGroupSessions").createIndex("byBackup","backup",{unique:!1})}async function Sh(s,e,t,i){const r=e.objectStore("inboundGroupSessions");let n=0,o=0;await W(r.openCursor(),(a,c,l)=>(a.session?(a.backup=Jr.NotBackedUp,a.source=Yi.DeviceMessage,l.update(a),n+=1):o+=1,pt)),i.set("countWithoutSession",o),i.set("countWithSession",n)}async function Eh(s){const e="hydrogen_webkit_test_inactive_txn_bug";try{const t=await yn(e,n=>{n.createObjectStore("test",{keyPath:"key"})},1,s),i=t.transaction(["test"],"readonly");await ce(i.objectStore("test").get("somekey")),await new Promise(n=>setTimeout(n,0));const r=t.transaction(["test"],"readwrite");await Promise.resolve(),r.objectStore("test").add({key:"somekey",value:"foo"}),await Bi(r),t.close()}catch(t){if(t.name==="TransactionInactiveError")return!0}return!1}const kc=s=>`hydrogen_session_${s}`,As=function(s,e,t,i){const r=(n,o,a,c)=>xh(n,o,a,c,t,i);return yn(kc(s),r,xc.length,e)};async function Ih(){var s,e;const t=this;if((e=(s=t?.navigator)==null?void 0:s.storage)!=null&&e.persist)return await t.navigator.storage.persist();if(t?.document.requestStorageAccess)try{return await t.document.requestStorageAccess(),!0}catch(i){return console.warn("requestStorageAccess threw an error:",i),!1}else return!1}class Th{constructor(e,t=window.indexedDB,i=window.IDBKeyRange,r=window.localStorage){this._serviceWorkerHandler=e,this._idbFactory=t,this._IDBKeyRange=i,this._localStorage=r}async create(e,t){var i;await((i=this._serviceWorkerHandler)==null?void 0:i.preventConcurrentSessionAccess(e)),Ih().then(o=>{o||console.warn("no persisted storage, database can be evicted by browser")});const r=await Eh(this._idbFactory),n=await As(e,this._idbFactory,this._localStorage,t);return new ih(n,this._idbFactory,this._IDBKeyRange,r,this._localStorage,t.logger)}delete(e){const t=kc(e);Pu(this._localStorage,t);const i=this._idbFactory.deleteDatabase(t);return ce(i)}async export(e,t){const i=await As(e,this._idbFactory,this._localStorage,t);return await rh(i)}async import(e,t,i){const r=await As(e,this._idbFactory,this._localStorage,i);return await sh(r,t)}}async function xh(s,e,t,i,r,n){const o=t||0;return n.wrap({l:"storage migration",oldVersion:t,version:i},async a=>{for(let c=o;c<i;++c){const l=xc[c];await a.wrap(`v${c+1}`,d=>l(s,e,r,d))}})}class kh{constructor(e){this._name=e}getAll(){const e=localStorage.getItem(this._name);if(e){const t=JSON.parse(e);if(Array.isArray(t))return Promise.resolve(t)}return Promise.resolve([])}async updateLastUsed(e,t){const i=await this.getAll();if(i){const r=i.find(n=>n.id===e);r&&(r.lastUsed=t,localStorage.setItem(this._name,JSON.stringify(i)))}}async get(e){const t=await this.getAll();if(t)return t.find(i=>i.id===e)}async add(e){const t=await this.getAll();t.push(e),localStorage.setItem(this._name,JSON.stringify(t))}async delete(e){let t=await this.getAll();t=t.filter(i=>i.id!==e),localStorage.setItem(this._name,JSON.stringify(t))}}class Rh{constructor(e){this._prefix=e}async setInt(e,t){this._set(e,t)}async getInt(e,t=0){const i=window.localStorage.getItem(`${this._prefix}${e}`);return typeof i=="string"?parseInt(i,10):t}async setBool(e,t){this._set(e,t)}async getBool(e,t=!1){const i=window.localStorage.getItem(`${this._prefix}${e}`);return typeof i=="string"?i==="true":t}async setString(e,t){this._set(e,t)}async getString(e){return window.localStorage.getItem(`${this._prefix}${e}`)}async remove(e){window.localStorage.removeItem(`${this._prefix}${e}`)}async _set(e,t){window.localStorage.setItem(`${this._prefix}${e}`,t)}}class Ah{constructor(){this._encoder=null,this._decoder=null}encode(e){return this._encoder||(this._encoder=new TextEncoder),this._encoder.encode(e)}decode(e){return this._decoder||(this._decoder=new TextDecoder),this._decoder.decode(e)}}class Ch{encodeUnpadded(e){const t=Nt.encode(e),i=t.indexOf("=");return i!==-1?t.substr(0,i):t}encode(e){return Nt.encode(e)}decode(e){return Nt.decode(e)}}function Nh(s){if(s.__esModule)return s;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(s).forEach(function(t){var i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return s[t]}})}),e}var Rc={isBuffer:function(s){return s instanceof Uint8Array},from:function(s){return s},allocUnsafe:function(s){return Rc.alloc(s)},alloc:function(s){return new Uint8Array(s)}},Mh=Object.freeze(Object.defineProperty({__proto__:null,Buffer:Rc},Symbol.toStringTag,{value:"Module"})),Dh=Nh(Mh),fr=Dh.Buffer;function Ph(s){if(s.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t<e.length;t++)e[t]=255;for(var i=0;i<s.length;i++){var r=s.charAt(i),n=r.charCodeAt(0);if(e[n]!==255)throw new TypeError(r+" is ambiguous");e[n]=i}var o=s.length,a=s.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function d(m){if((Array.isArray(m)||m instanceof Uint8Array)&&(m=fr.from(m)),!fr.isBuffer(m))throw new TypeError("Expected Buffer");if(m.length===0)return"";for(var _=0,f=0,E=0,I=m.length;E!==I&&m[E]===0;)E++,_++;for(var T=(I-E)*l+1>>>0,k=new Uint8Array(T);E!==I;){for(var w=m[E],x=0,C=T-1;(w!==0||x<f)&&C!==-1;C--,x++)w+=256*k[C]>>>0,k[C]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");f=x,E++}for(var O=T-f;O!==T&&k[O]===0;)O++;for(var Ft=a.repeat(_);O<T;++O)Ft+=s.charAt(k[O]);return Ft}function u(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return fr.alloc(0);var _=0;if(m[_]!==" "){for(var f=0,E=0;m[_]===a;)f++,_++;for(var I=(m.length-_)*c+1>>>0,T=new Uint8Array(I);m[_];){var k=e[m.charCodeAt(_)];if(k===255)return;for(var w=0,x=I-1;(k!==0||w<E)&&x!==-1;x--,w++)k+=o*T[x]>>>0,T[x]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");E=w,_++}if(m[_]!==" "){for(var C=I-E;C!==I&&T[C]===0;)C++;var O=fr.allocUnsafe(f+(I-C));O.fill(0,0,f);for(var Ft=f;C!==I;)O[Ft++]=T[C++];return O}}}function h(m){var _=u(m);if(_)return _;throw new Error("Non-base"+o+" character")}return{encode:d,decodeUnsafe:u,decode:h}}var Oh=Ph,Uh=Oh,Bh="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Yo=Uh(Bh);class Lh{encode(e){return Yo.encode(e)}decode(e){return Yo.decode(e)}}class Fh{constructor(){this.utf8=new Ah,this.base64=new Ch,this.base58=new Lh}}class Vh{constructor(e){this._workerPool=e}megolmDecrypt(e,t){const i=e.export_session(e.first_known_index());return this._workerPool.send({type:"megolm_decrypt",ciphertext:t,sessionKey:i})}async createAccountAndOTKs(e,t){let i;window.msCrypto&&(i=[window.msCrypto.getRandomValues(new Uint8Array(64)),window.msCrypto.getRandomValues(new Uint8Array(t*32))]);const r=await this._workerPool.send({type:"olm_create_account_otks",randomValues:i,otkAmount:t}).response();e.unpickle("",r)}async createOutboundOlmSession(e,t,i,r){const n=e.pickle("");let o;window.msCrypto&&(o=[window.msCrypto.getRandomValues(new Uint8Array(64))]);const a=await this._workerPool.send({type:"olm_create_outbound",accountPickle:n,theirIdentityKey:i,theirOneTimeKey:r,randomValues:o}).response();t.unpickle("",a)}dispose(){this._workerPool.dispose()}}class Ai{constructor(e,t,i,r){this._logger=i,this.start=i._now(),this._values=typeof e=="string"?{l:e}:e,this.logLevel=t,this._filterCreator=r}runDetached(e,t,i,r){return this._logger.runDetached(e,t,i,r)}wrapDetached(e,t,i,r){this.refDetached(this.runDetached(e,t,i,r))}refDetached(e,t){e.ensureRefId(),this.log({ref:e.values.refId},t)}ensureRefId(){this._values.refId||this.set("refId",this._logger._createRefId())}wrap(e,t,i,r){return this.child(e,i,r).run(t)}get duration(){if(this.end)return this.end-this.start}durationWithoutType(e){const t=this.durationOfType(e);if(this.duration&&t)return this.duration-t}durationOfType(e){return this._values.t===e?this.duration:this._children?this._children.reduce((t,i)=>{const r=i.durationOfType(e);return t+(r??0)},0):0}log(e,t){const i=this.child(e,t);return i.end=i.start,i}set(e,t){if(typeof e=="object"){const i=e;Object.assign(this._values,i)}else this._values[e]=t;return this}serialize(e,t,i){if(this._filterCreator)try{e=this._filterCreator(new zs(e),this)}catch(o){console.error("Error creating log filter",o)}let r=null;if(this._children&&(r=this._children.reduce((o,a)=>{const c=a.serialize(e,this.start,!1);return c&&(o===null&&(o=[]),o.push(c)),o},null)),e&&!e.filter(this,r))return;const n={s:typeof t=="number"?this.start-t:this.start,d:this.duration,v:this._values,l:this.logLevel};return this.error&&(n.e={stack:this.error.stack,name:this.error.name,message:this.error.message.split(`
`)[0]}),i&&(n.f=!0),r&&(n.c=r),n}run(e){this.end!==void 0&&console.trace("log item is finished, additional logs will likely not be recorded");try{const t=e(this);return t instanceof Promise?t.then(i=>(this.finish(),i),i=>{throw this.catch(i)}):(this.finish(),t)}catch(t){throw this.catch(t)}}finish(){if(this.end===void 0){if(this._children)for(const e of this._children)e.finish();this.end=this._logger._now()}}get level(){return we}catch(e){return this.error=e,this.logLevel=we.Error,this.finish(),e}child(e,t,i){this.end&&console.trace("log item is finished, additional logs will likely not be recorded"),t||(t=this.logLevel||we.Info);const r=new Ai(e,t,this._logger,i);return this._children||(this._children=[]),this._children.push(r),r}get logger(){return this._logger}get values(){return this._values}get children(){return this._children}}class Ac{constructor({platform:e,serializedTransformer:t=i=>i}){this._openItems=new Set,this._platform=e,this._serializedTransformer=t}log(e,t=we.Info){const i=new Ai(e,t,this);i.end=i.start,this._persistItem(i,void 0,!1)}wrapOrRun(e,t,i,r,n){return e?e.wrap(t,i,r,n):this.run(t,i,r,n)}runDetached(e,t,i,r){i||(i=we.Info);const n=new Ai(e,i,this);return this._run(n,t,i,!1,r),n}run(e,t,i,r){i===void 0&&(i=we.Info);const n=new Ai(e,i,this);return this._run(n,t,i,!0,r)}_run(e,t,i,r,n){this._openItems.add(e);const o=()=>{let a=new zs;if(n)try{a=n(a,e)}catch(c){console.error("Error while creating log filter",c)}else a=a.minLevel(i);try{this._persistItem(e,a,!1)}catch(c){console.error("Could not persist log item",c)}this._openItems.delete(e)};try{let a=e.run(t);if(a instanceof Promise){if(a=a.then(c=>(o(),c),c=>{if(o(),r)throw c}),r)return a}else if(o(),r)return a}catch(a){if(o(),r)throw a}}_finishOpenItems(){for(const e of this._openItems){e.finish();try{this._persistItem(e,new zs,!0)}catch(t){console.error("Could not serialize log item",t)}}this._openItems.clear()}get level(){return we}_now(){return this._platform.clock.now()}_createRefId(){return Math.round(this._platform.random()*Number.MAX_SAFE_INTEGER)}}class Kh extends Ac{constructor(e){super(e);const{name:t,flushInterval:i=60*1e3,limit:r=3e3}=e;this._name=t,this._limit=r,this._queuedItems=this._loadQueuedItems(),window.addEventListener("pagehide",this,!1),this._flushInterval=this._platform.clock.createInterval(()=>this._tryFlush(),i)}dispose(){window.removeEventListener("pagehide",this,!1),this._flushInterval.dispose()}handleEvent(e){e.type==="pagehide"&&this._finishAllAndFlush()}async _tryFlush(){const e=await this._openDB();try{const t=e.transaction(["logs"],"readwrite"),i=t.objectStore("logs"),r=this._queuedItems.length;for(const o of this._queuedItems)i.add(o);const n=await ce(i.count());if(n>this._limit){let o=n-this._limit+Math.round(.1*this._limit);await W(i.openCursor(),(a,c,l)=>(l.delete(),o-=1,{done:o===0}))}await Bi(t),this._queuedItems.splice(0,r)}catch(t){console.error("Could not flush logs",t)}finally{try{e.close()}catch{}}}_finishAllAndFlush(){this._finishOpenItems(),this.log({l:"pagehide, closing logs",t:"navigation"}),this._persistQueuedItems(this._queuedItems)}_loadQueuedItems(){const e=`${this._name}_queuedItems`;try{const t=window.localStorage.getItem(e);if(t)return window.localStorage.removeItem(e),JSON.parse(t)}catch(t){console.error("Could not load queued log items",t)}return[]}_openDB(){return yn(this._name,e=>e.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),1)}_persistItem(e,t,i){const r=e.serialize(t,void 0,i);if(r){const n=this._serializedTransformer(r);this._queuedItems.push({json:JSON.stringify(n)})}}_persistQueuedItems(e){try{window.localStorage.setItem(`${this._name}_queuedItems`,JSON.stringify(e))}catch(t){console.error("Could not persist queued log items in localStorage, they will likely be lost",t)}}async export(){const e=await this._openDB();try{const i=e.transaction(["logs"],"readonly").objectStore("logs"),n=(await ku(i.openCursor(),()=>!1)).concat(this._queuedItems);return new $h(n,this,this._platform)}finally{try{e.close()}catch{}}}async _removeItems(e){const t=await this._openDB();try{const i=t.transaction(["logs"],"readwrite"),r=i.objectStore("logs");for(const n of e)if(typeof n.id=="number")r.delete(n.id);else{const o=this._queuedItems.indexOf(n);o===-1&&this._queuedItems.splice(o,1)}await Bi(i)}finally{try{t.close()}catch{}}}}class $h{constructor(e,t,i){this._items=e,this._logger=t,this._platform=i}get count(){return this._items.length}removeFromStore(){return this._logger._removeItems(this._items)}asBlob(){var e;const t={formatVersion:1,appVersion:(e=this._platform.updateService)==null?void 0:e.version,items:this._items.map(o=>JSON.parse(o.json))},i=JSON.stringify(t),r=this._platform.encoding.utf8.encode(i);return this._platform.createBlob(r,"application/json")}}class jh extends Ac{_persistItem(e){Cc(e)}async export(){}}const Gh=["l","id"];function qh(s){return Object.entries(s).filter(([e])=>!Gh.includes(e)).reduce((e,[t,i])=>(e=e||{},e[t]=i,e),null)}function Cc(s){const e=`${zh(s)} (${s.duration}ms)`,t=qh(s.values),i=s.children||t;if(i?(s.error?console.group(e):console.groupCollapsed(e),s.error&&console.error(s.error)):s.error?console.error(s.error):console.log(e),t&&console.table(t),s.children)for(const r of s.children)Cc(r);i&&console.groupEnd()}function zh(s){return s.values.t==="network"?`${s.values.method} ${s.values.url}`:s.values.l&&typeof s.values.id<"u"?`${s.values.l} ${s.values.id}`:s.values.l&&typeof s.values.status<"u"?`${s.values.l} (${s.values.status})`:s.values.l&&s.error?`${s.values.l} failed`:typeof s.values.ref<"u"?`ref ${s.values.ref}`:s.values.l||s.values.type}function Nc(s){return typeof s!="object"||"nodeType"in s||Array.isArray(s)}function ii(s,e){return Object.entries(s).reduce((t,[i,r])=>(typeof r=="function"&&(r=r(e)),r?t+(t.length?" ":"")+i:t),"")}function Xt(s,e,t){e==="className"&&(e="class"),t===!1?s.removeAttribute(e):(t===!0&&(t=e),s.setAttribute(e,t))}function Hh(s,e,t){return Mc(bn,s,e,t)}function Mc(s,e,t,i){t&&Nc(t)&&(i=t,t=void 0);const r=document.createElementNS(s,e);if(t)for(let[n,o]of Object.entries(t))typeof o=="object"&&(o=o!==null&&n==="className"?ii(o,void 0):!1),Xt(r,n,o);if(i){Array.isArray(i)||(i=[i]);for(let n of i)typeof n=="string"&&(n=Ge(n)),r.appendChild(n)}return r}function Ge(s){return document.createTextNode(s)}const bn="http://www.w3.org/1999/xhtml",Wh="http://www.w3.org/2000/svg",Dc={[bn]:["br","a","ol","ul","li","div","h1","h2","h3","h4","h5","h6","p","strong","em","span","img","section","header","main","footer","article","aside","del","blockquote","table","thead","tbody","tr","th","td","hr","pre","code","button","time","input","textarea","select","option","label","form","progress","output","video","style"],[Wh]:["svg","g","path","circle","ellipse","rect","use"]},A={};for(const[s,e]of Object.entries(Dc))for(const t of e)A[t]=function(i,r){return Mc(s,t,i,r)};function Li(s,e){let t;try{t=s.mount(e)}catch(i){console.error(i),t=Yh(i)}return t}function Yh(s){const e=new Error().stack;let t=null;return e&&(t=e.split(`
`)[1]),A.div([A.h2("Something went wrong\u2026"),A.h3(s.message),A.p(`This occurred while running ${t}.`),A.pre(s.stack)])}function Jo(s,e,t){if(e===s.childElementCount)s.appendChild(t);else{const r=s.children[e];s.insertBefore(t,r)}}function Jh(s){s.innerHTML=""}function Xh(s){return async e=>{var t,i;(t=e.target)==null||t.setAttribute("disabled","disabled"),await s(e),(i=e.target)==null||i.removeAttribute("disabled")}}class Ji{constructor({list:e,onItemClick:t,className:i,tagName:r="ul",parentProvidesUpdates:n=!0},o){this._onItemClick=t,this._list=e,this._className=i,this._tagName=r,this._root=void 0,this._subscription=void 0,this._childCreator=o,this._childInstances=void 0,this._mountArgs={parentProvidesUpdates:n}}root(){return this._root}update(e){if(e.list){if(this._subscription)for(this._unloadList();this._root.lastChild;)this._root.lastChild.remove();this._list=e.list,this.loadList()}}mount(){const e={};this._className&&(e.className=this._className);const t=this._root=Hh(this._tagName,e);return this.loadList(),this._onItemClick&&t.addEventListener("click",this),t}handleEvent(e){e.type==="click"&&this._handleClick(e)}unmount(){this._list&&this._unloadList()}_handleClick(e){if(e.target===this._root||!this._onItemClick)return;let t=e.target;for(;t.parentNode!==this._root;)t=t.parentNode;const i=Array.prototype.indexOf.call(this._root.childNodes,t),r=this._childInstances[i];r&&this._onItemClick(r,e)}_unloadList(){this._subscription=this._subscription();for(let e of this._childInstances)e.unmount();this._childInstances=void 0}loadList(){if(!this._list)return;this._subscription=this._list.subscribe(this),this._childInstances=[];const e=document.createDocumentFragment();for(let t of this._list){const i=this._childCreator(t);this._childInstances.push(i),e.appendChild(Li(i,this._mountArgs))}this._root.appendChild(e)}onReset(){for(const e of this._childInstances)e.root().remove(),e.unmount();this._childInstances.length=0}onAdd(e,t){this.addChild(e,t)}onRemove(e,t){this.removeChild(e)}onMove(e,t,i){this.moveChild(e,t)}onUpdate(e,t,i){this.updateChild(e,t,i)}addChild(e,t){const i=this._childCreator(t);this._childInstances.splice(e,0,i),Jo(this._root,e,Li(i,this._mountArgs))}removeChild(e){const[t]=this._childInstances.splice(e,1);t.root().remove(),t.unmount()}moveChild(e,t){const[i]=this._childInstances.splice(e,1);this._childInstances.splice(t,0,i),i.root().remove(),Jo(this._root,t,i.root())}updateChild(e,t,i){if(this._childInstances){const r=this._childInstances[e];r&&r.update(t,i)}}recreateItem(e,t){if(this._childInstances){const i=this._childCreator(t);if(!i)this.onRemove(e,t);else{const[r]=this._childInstances.splice(e,1,i);this._root.replaceChild(i.mount(this._mountArgs),r.root()),r.unmount()}}}getChildInstanceByIndex(e){var t;return(t=this._childInstances)==null?void 0:t[e]}}class Pc{constructor(e){this._value=e,this._boundUpdateFromValue=null}subscribeOnMount(e){e&&e.parentProvidesUpdates||this._subscribe()}unmount(){this._unsubscribe()}get value(){return this._value}_updateFromValue(e){this.update(this._value,e)}_subscribe(){var e;typeof((e=this._value)==null?void 0:e.on)=="function"&&(this._boundUpdateFromValue=this._updateFromValue.bind(this),this._value.on("change",this._boundUpdateFromValue))}_unsubscribe(){this._boundUpdateFromValue&&(typeof this._value.off=="function"&&this._value.off("change",this._boundUpdateFromValue),this._boundUpdateFromValue=null)}}function Qh(s){for(const e of Object.values(s))if(typeof e=="function")return!0;return!1}class S extends Pc{constructor(){super(...arguments),this._eventListeners=void 0,this._bindings=void 0,this._root=void 0,this._subViews=void 0}_attach(){if(this._eventListeners)for(let{node:e,name:t,fn:i,useCapture:r}of this._eventListeners)e.addEventListener(t,i,r)}_detach(){if(this._eventListeners)for(let{node:e,name:t,fn:i,useCapture:r}of this._eventListeners)e.removeEventListener(t,i,r)}mount(e){const t=new Oc(this);try{this._root=this.render(t,this._value)}finally{t.close()}return this.subscribeOnMount(e),this._attach(),this._root}unmount(){if(this._detach(),super.unmount(),this._subViews)for(const e of this._subViews)e.unmount()}root(){return this._root}update(e,t){if(this._value=e,this._bindings)for(const i of this._bindings)i()}_addEventListener(e,t,i,r=!1){this._eventListeners||(this._eventListeners=[]),this._eventListeners.push({node:e,name:t,fn:i,useCapture:r})}_addBinding(e){this._bindings||(this._bindings=[]),this._bindings.push(e)}addSubView(e){this._subViews||(this._subViews=[]),this._subViews.push(e)}removeSubView(e){if(!this._subViews)return;const t=this._subViews.indexOf(e);t!==-1&&this._subViews.splice(t,1)}updateSubViews(e,t){if(this._subViews)for(const i of this._subViews)i.update(e,t)}}class Oc{constructor(e){this._closed=!1,this._templateView=e}close(){this._closed=!0}_addBinding(e){this._closed&&console.trace("Adding a binding after render will likely cause memory leaks"),this._templateView._addBinding(e)}get _value(){return this._templateView.value}addEventListener(e,t,i,r=!1){this._templateView._addEventListener(e,t,i,r)}_addAttributeBinding(e,t,i){let r;const n=()=>{const o=i(this._value);r!==o&&(r=o,Xt(e,t,o))};this._addBinding(n),n()}_addClassNamesBinding(e,t){this._addAttributeBinding(e,"className",i=>ii(t,i))}_addTextBinding(e){const t=e(this._value)+"",i=Ge(t);let r=t;const n=()=>{const o=e(this._value)+"";r!==o&&(r=o,i.textContent=o)};return this._addBinding(n),i}_isEventHandler(e,t){return e.startsWith("on")&&e.length>2&&typeof t=="function"}_setNodeAttributes(e,t){for(let[i,r]of Object.entries(t))if(typeof r=="object"){if(i!=="className"||r===null)continue;Qh(r)?this._addClassNamesBinding(e,r):Xt(e,i,ii(r,this._value))}else if(this._isEventHandler(i,r)){const n=i.substr(2,1).toLowerCase()+i.substr(3),o=r;this._templateView._addEventListener(e,n,o)}else typeof r=="function"?this._addAttributeBinding(e,i,r):Xt(e,i,r)}_setNodeChildren(e,t){Array.isArray(t)||(t=[t]);for(let i of t)typeof i=="function"?i=this._addTextBinding(i):typeof i=="string"&&(i=Ge(i)),e.appendChild(i)}_addReplaceNodeBinding(e,t){let i=e(this._value),r=t(null);const n=()=>{const o=e(this._value);if(i!==o){i=o;const a=t(r);r.parentNode&&r.parentNode.replaceChild(a,r),r=a}};return this._addBinding(n),r}el(e,t,i){return this.elNS(bn,e,t,i)}elNS(e,t,i,r){let n;i&&(Nc(i)?r=i:n=i);const o=document.createElementNS(e,t);return n&&this._setNodeAttributes(o,n),r&&this._setNodeChildren(o,r),o}view(e,t){return this._templateView.addSubView(e),Li(e,t)}mapView(e,t){return this._addReplaceNodeBinding(e,i=>{if(i&&i.nodeType!==Node.COMMENT_NODE){const n=this._templateView._subViews;if(n){const o=n.findIndex(a=>a.root()===i);if(o!==-1){const[a]=n.splice(o,1);a.unmount()}}}const r=t(e(this._value));return r?this.view(r):document.createComment("node binding placeholder")})}map(e,t){return this.mapView(e,i=>new Fr(this._value,(r,n)=>{const o=t(i,r,n);return o||document.createComment("map placeholder")}))}ifView(e,t){return this.mapView(i=>!!e(i),i=>i?t(this._value):null)}if(e,t){return this.ifView(e,i=>new Fr(i,t))}mapSideEffect(e,t){let i=e(this._value);const r=()=>{const n=e(this._value);i!==n&&(t(n,i),i=n)};this._addBinding(r),t(i,void 0)}}for(const[s,e]of Object.entries(Dc))for(const t of e)Oc.prototype[t]=function(i,r){return this.elNS(s,t,i,r)};class Fr extends S{constructor(e,t){super(e),this._render=t}render(e,t){return this._render(e,t)}}function At(s,e,t=void 0){const i=!!s.avatarUrl(e);let r=ii({avatar:!0,[`size-${e}`]:!0,[`usercolor${s.avatarColorNumber}`]:!i});t&&(r+=` ${t}`);const n=i?Uc(s,e):Ge(s.avatarLetter),o=A.div({className:r,"data-testid":"avatar"},[n]);return i&&(Xt(o,"data-avatar-letter",s.avatarLetter),Xt(o,"data-avatar-color",s.avatarColorNumber)),o}function Uc(s,e){const t=e.toString();return A.img({src:s.avatarUrl(e),width:t,height:t,title:s.avatarTitle})}function Zh(s){const e=s.target,t=e.parentElement;return e.tagName==="IMG"&&t.classList.contains("avatar")}function Xo(s){if(!Zh(s))return;const e=s.target.parentElement,t=e.getAttribute("data-avatar-color");e.classList.add(`usercolor${t}`);const i=e.getAttribute("data-avatar-letter");e.textContent=i}class gt extends Pc{constructor(e,t){super(e),this._root=null,this._avatarUrl=null,this._avatarTitle=null,this._avatarLetter=null,this._size=t}_avatarUrlChanged(){return this.value.avatarUrl(this._size)!==this._avatarUrl?(this._avatarUrl=this.value.avatarUrl(this._size),!0):!1}_avatarTitleChanged(){return this.value.avatarTitle!==this._avatarTitle?(this._avatarTitle=this.value.avatarTitle,!0):!1}_avatarLetterChanged(){return this.value.avatarLetter!==this._avatarLetter?(this._avatarLetter=this.value.avatarLetter,!0):!1}mount(e){return this._avatarUrlChanged(),this._avatarLetterChanged(),this._avatarTitleChanged(),this._root=At(this.value,this._size),this.subscribeOnMount(e),this._root}root(){return this._root}update(e){if(this._avatarUrlChanged()){const i=`usercolor${e.avatarColorNumber}`;e.avatarUrl(this._size)?(this._root.replaceChild(Uc(e,this._size),this._root.firstChild),this._root.classList.remove(i)):(this._root.textContent=e.avatarLetter,this._root.classList.add(i))}const t=!!e.avatarUrl(this._size);if(this._avatarTitleChanged()&&t){const i=this._root.firstChild;i.tagName==="IMG"&&i.setAttribute("title",e.avatarTitle)}this._avatarLetterChanged()&&!t&&(this._root.textContent=e.avatarLetter)}}let gr;function Te(s,e=void 0){gr===void 0&&(gr=document.querySelector(".hydrogen"));const t=Object.assign({spinner:!0},e);return gr?.classList.contains("legacy")?s.div({className:t},[s.div(),s.div(),s.div(),s.div()]):s.svg({className:t,viewBox:"0 0 100 100"},s.circle({cx:"50%",cy:"50%",r:"45%",pathLength:"100"}))}class ep extends S{render(e,t){const i={active:r=>r.isOpen,hidden:r=>r.hidden};return e.li({className:i},[e.a({href:t.url},[e.view(new gt(t,32),{parentProvidesUpdates:!0}),e.div({className:"description"},[e.div({className:{name:!0,unread:r=>r.isUnread}},r=>r.name),e.map(r=>r.busy,r=>r?Te(e):e.div({className:{badge:!0,highlighted:n=>n.isHighlighted,hidden:n=>!n.badgeCount}},n=>n.badgeCount))])])])}update(e,t){super.update(e),this.updateSubViews(e,t)}}class Y extends S{static option(e,t){return new tp(e,t)}constructor(e){super(),this._options=e}render(e){return e.ul({className:"menu",role:"menu"},this._options.map(t=>t.toDOM(e)))}}class tp{constructor(e,t){this.label=e,this.callback=t,this.icon=null,this.destructive=!1}setIcon(e){return this.icon=e,this}setDestructive(){return this.destructive=!0,this}toDOM(e){const t={destructive:this.destructive};return this.icon&&(t.icon=!0,t[this.icon]=!0),e.li({className:t},e.button({className:"menu-item",onClick:this.callback},this.label))}}class Xr{constructor(e,t=null){this._view=e,this._target=null,this._arrangement=null,this._scroller=null,this._fakeRoot=null,this._trackingTemplateView=null,this._closeCallback=t}_getPopupContainer(){const e=this._target.closest(".hydrogen");let t=e.querySelector(".popupContainer");return t||(t=A.div({className:"popupContainer"}),e.appendChild(t)),t}trackInTemplateView(e){this._trackingTemplateView=e,this._trackingTemplateView.addSubView(this)}showRelativeTo(e,t=0){this._target=e,this._verticalPadding=t,this._scroller=ip(this._target),this._view.mount(),this._getPopupContainer().appendChild(this._popup),this._position(),this._scroller&&document.body.addEventListener("scroll",this,!0),setTimeout(()=>{document.body.addEventListener("click",this,!1)},10)}get isOpen(){return!!this._view}close(){this._view&&(this._view.unmount(),this._trackingTemplateView.removeSubView(this),this._scroller&&document.body.removeEventListener("scroll",this,!0),document.body.removeEventListener("click",this,!1),this._popup.remove(),this._view=null,this._closeCallback&&this._closeCallback())}get _popup(){return this._view.root()}handleEvent(e){e.type==="scroll"?this._position()||this.close():e.type==="click"&&this._onClick(e)}_onClick(){this.close()}_position(){const e=this._target.getBoundingClientRect(),t=this._popup.clientWidth,i=this._popup.clientHeight,r=(this._scroller?this._scroller:document.documentElement).getBoundingClientRect();if(e.top>r.bottom||e.left>r.right||e.bottom<r.top||e.right<r.left)return!1;if(r.bottom>=e.bottom+i)this._popup.style.top=`${e.bottom+this._verticalPadding}px`;else if(r.top<=e.top-i)this._popup.style.top=`${e.top-i-this._verticalPadding}px`;else return!1;if(r.right>=e.right+t)this._popup.style.left=`${e.left}px`;else if(r.left<=e.left-t)this._popup.style.left=`${e.right-t}px`;else return!1;return!0}root(){return this._fakeRoot}mount(){return this._fakeRoot=document.createComment("popup"),this._fakeRoot}unmount(){this.close()}update(){}}function ip(s){let e=s;do if(e=e.parentElement,e.scrollHeight>e.clientHeight){const i=window.getComputedStyle(e).getPropertyValue("overflow-y");if(i==="auto"||i==="scroll")return e}while(e!==document.body)}class rp extends S{render(e,t){const i=()=>{r.value="",r.blur(),n.blur(),t.clear()},r=e.input({type:"text",placeholder:t?.label,"aria-label":t?.label,autocomplete:t?.autocomplete,enterkeyhint:"search",name:t?.name,onInput:o=>t.set(o.target.value),onKeydown:o=>{(o.key==="Escape"||o.key==="Esc")&&i()},onFocus:()=>r.select()}),n=e.button({onClick:i,title:t.i18n`Clear`,"aria-label":t.i18n`Clear`});return e.div({className:"FilterField"},[r,n])}}class sp extends S{constructor(e){super(e),this._createMenuPopup=null}render(e,t){const i=o=>o.gridEnabled?o.i18n`Show single room`:o.i18n`Enable grid layout`,r=e.view(new Ji({className:"RoomList",list:t.tileViewModels},o=>new ep(o))),n=e.div({className:"utilities"},[e.a({className:"button-utility close-session",href:t.closeUrl,"aria-label":t.i18n`Back to account list`,title:t.i18n`Back to account list`}),e.view(new rp({i18n:t.i18n,label:t.i18n`Filter rooms…`,name:"room-filter",autocomplete:!0,set:o=>{t.setFilter(o)&&(r.scrollTop=0)},clear:()=>t.clearFilter()})),e.button({onClick:()=>t.toggleGrid(),className:{"button-utility":!0,grid:!0,on:o=>o.gridEnabled},title:i,"aria-label":i}),e.a({className:"button-utility settings",href:t.settingsUrl,"aria-label":t.i18n`Settings`,title:t.i18n`Settings`}),e.button({className:"button-utility create","aria-label":t.i18n`Create room`,onClick:o=>this._toggleCreateMenu(o)})]);return e.div({className:"LeftPanel"},[n,r])}_toggleCreateMenu(e){if(this._createMenuPopup&&this._createMenuPopup.isOpen)this._createMenuPopup.close();else{const t=this.value,i=[];i.push(Y.option(t.i18n`Create Room`,()=>t.showCreateRoomView())),i.push(Y.option(t.i18n`Join Room`,()=>t.showJoinRoomView())),this._createMenuPopup=new Xr(new Y(i)),this._createMenuPopup.trackInTemplateView(this),this._createMenuPopup.showRelativeTo(e.target,10)}}}function Qo(s){return s.offsetTop+s.clientHeight}function Zo(s,e,t=s.children.length-1){for(var i=t;i>=0;i--)if(s.children[i].offsetTop<e)return i;return 0}class Bc extends S{constructor(e,t){super(e),this.viewClassForTile=t,this.anchoredBottom=0,this.stickToBottom=!0}render(e,t){requestAnimationFrame(()=>{this.restoreScrollPosition()}),this.tilesView=new np(t.tiles,()=>this.restoreScrollPosition(),this.viewClassForTile);const i=e.div({className:"Timeline"},[e.div({className:"Timeline_scroller bottom-aligned-scroll",onScroll:()=>this.onScroll()},e.view(this.tilesView)),e.button({className:{Timeline_jumpDown:!0,hidden:r=>!r.showJumpDown},title:"Jump down",onClick:()=>this.jumpDown()})]);return typeof ResizeObserver=="function"&&(this.resizeObserver=new ResizeObserver(()=>{this.restoreScrollPosition()}),this.resizeObserver.observe(i)),i}get scrollNode(){return this.root().firstElementChild}get tilesNode(){return this.tilesView.root()}jumpDown(){const{scrollNode:e}=this;this.stickToBottom=!0,e.scrollTop=e.scrollHeight}unmount(){super.unmount(),this.resizeObserver&&(this.resizeObserver.unobserve(this.root()),this.resizeObserver=void 0)}restoreScrollPosition(){const{scrollNode:e,tilesNode:t}=this,i=e.clientHeight-t.clientHeight;if(i>0){t.style.setProperty("margin-top",`${i}px`);const r=this.value.tiles.length;this.updateVisibleRange(0,r-1)}else if(t.style.removeProperty("margin-top"),this.stickToBottom)e.scrollTop=e.scrollHeight;else if(this.anchoredNode){const r=Qo(this.anchoredNode);if(r!==this.anchoredBottom){const n=r-this.anchoredBottom;typeof e.scrollBy=="function"?e.scrollBy(0,n):e.scrollTop=e.scrollTop+n,this.anchoredBottom=r}}}onScroll(){const{scrollNode:e,tilesNode:t}=this,{scrollHeight:i,scrollTop:r,clientHeight:n}=e;let o;if(this.stickToBottom=Math.abs(i-(r+n))<1,this.stickToBottom)o=this.value.tiles.length-1;else{const c=r+n,l=Zo(t,c);this.anchoredNode=t.childNodes[l],this.anchoredBottom=Qo(this.anchoredNode),o=l}let a=Zo(t,r,o);this.updateVisibleRange(a,o)}updateVisibleRange(e,t){const i=this.tilesView.getChildInstanceByIndex(e),r=this.tilesView.getChildInstanceByIndex(t);this.value.setVisibleTileRange(i?.value,r?.value)}}class np extends Ji{constructor(e,t,i){super({list:e,onItemClick:(r,n)=>r.onClick(n)},r=>{const n=i(r);return new n(r,i)}),this.viewClassForTile=i,this.onChanged=t}onReset(){super.onReset(),this.onChanged()}onUpdate(e,t,i){if(i==="shape"){const r=this.viewClassForTile(t),n=this.getChildInstanceByIndex(e);if(!r||!(n instanceof r)){super.recreateItem(e,t);return}}super.onUpdate(e,t,i),this.onChanged()}onAdd(e,t){super.onAdd(e,t),this.onChanged()}onRemove(e,t){super.onRemove(e,t),this.onChanged()}onMove(e,t,i){super.onMove(e,t,i),this.onChanged()}}class op extends S{render(e,t){return e.div({className:"TimelineLoadingView"},[Te(e),e.div(t.isEncrypted?t.i18n`Loading encrypted messages…`:t.i18n`Loading messages…`)])}}class Lc extends S{constructor(e,t){super(e),this._viewClassForTile=t,this._input=null,this._attachmentPopup=null,this._focusInput=null,this._rafResizeHandle=void 0}render(e,t){this._input=e.textarea({onKeydown:n=>this._onKeyDown(n),onInput:()=>{t.setInput(this._input.value),this._input.value?this._adjustHeight():this._clearHeight()},placeholder:n=>n.isEncrypted?"Send an encrypted message\u2026":"Send a message\u2026",rows:"1"}),this._focusInput=()=>this._input.focus(),this.value.on("focus",this._focusInput);const i=e.map(n=>n.replyViewModel,(n,o)=>{const a=n&&this._viewClassForTile(n);return a?o.div({className:"MessageComposer_replyPreview"},[o.span({className:"replying"},"Replying"),o.button({className:"cancel",onClick:()=>this._clearReplyingTo()},"Close"),o.view(new a(n,this._viewClassForTile,{interactive:!1},"div"))]):null}),r=e.div({className:"MessageComposer_input"},[this._input,e.button({className:"sendFile",title:t.i18n`Pick attachment`,onClick:n=>this._toggleAttachmentMenu(n)},t.i18n`Send file`),e.button({className:"send",title:t.i18n`Send`,onClick:()=>this._trySend()},t.i18n`Send`)]);return e.div({className:{MessageComposer:!0,MessageComposer_canSend:n=>n.canSend}},[i,r])}unmount(){this._focusInput&&this.value.off("focus",this._focusInput),super.unmount()}_clearReplyingTo(){this.value.clearReplyingTo()}async _trySend(){this._input.focus();const{value:e}=this._input,t=()=>{this._input.value=e,this._adjustHeight()};this._input.value="",this._clearHeight();try{await this.value.sendMessage(e)||t()}catch(i){t(),console.error(i)}}_onKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this._trySend())}_toggleAttachmentMenu(e){if(this._attachmentPopup&&this._attachmentPopup.isOpen)this._attachmentPopup.close();else{const t=this.value;this._attachmentPopup=new Xr(new Y([Y.option(t.i18n`Send video`,()=>t.sendVideo()).setIcon("video"),Y.option(t.i18n`Send picture`,()=>t.sendPicture()).setIcon("picture"),Y.option(t.i18n`Send file`,()=>t.sendFile()).setIcon("file")])),this._attachmentPopup.trackInTemplateView(this),this._attachmentPopup.showRelativeTo(e.target,12)}}_adjustHeight(){this._rafResizeHandle||(this._rafResizeHandle=window.requestAnimationFrame(()=>{const e=this._input.scrollHeight;this._input.style.height=`${e}px`,this._rafResizeHandle=void 0}))}_clearHeight(){this._input.style.removeProperty("height")}}class ap extends S{render(e){return e.div({className:"DisabledComposerView"},e.h3(t=>t.description))}}class Fc extends S{constructor(e,t){super(e),this._viewClassForTile=t,this._optionsPopup=null}render(e,t){return e.main({className:"RoomView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close room`}),e.view(new gt(t,32)),e.div({className:"room-description"},[e.h2(i=>i.name)]),e.button({className:"button-utility room-options","aria-label":t.i18n`Room options`,onClick:i=>this._toggleOptionsMenu(i)})]),e.div({className:"RoomView_body"},[e.div({className:"RoomView_error"},[e.if(i=>i.error,i=>i.div([i.p({},r=>r.error),i.button({className:"RoomView_error_closerButton",onClick:r=>t.dismissError(r)})]))]),e.mapView(i=>i.timelineViewModel,i=>i?new Bc(i,this._viewClassForTile):new op(t)),e.mapView(i=>i.composerViewModel,i=>{switch(i?.kind){case"composer":return new Lc(t.composerViewModel,this._viewClassForTile);case"disabled":return new ap(t.composerViewModel)}})])])}_toggleOptionsMenu(e){if(this._optionsPopup&&this._optionsPopup.isOpen)this._optionsPopup.close();else{const t=this.value,i=[];if(i.push(Y.option(t.i18n`Room details`,()=>t.openDetailsPanel())),t.canLeave&&i.push(Y.option(t.i18n`Leave room`,()=>this._confirmToLeaveRoom()).setDestructive()),t.canForget&&i.push(Y.option(t.i18n`Forget room`,()=>t.forgetRoom()).setDestructive()),t.canRejoin&&i.push(Y.option(t.i18n`Rejoin room`,()=>t.rejoinRoom())),!i.length)return;this._optionsPopup=new Xr(new Y(i)),this._optionsPopup.trackInTemplateView(this),this._optionsPopup.showRelativeTo(e.target,10)}}_confirmToLeaveRoom(){confirm(this.value.i18n`Are you sure you want to leave "${this.value.name}"?`)&&this.value.leaveRoom()}}class cp extends S{render(e,t){return e.main({className:"UnknownRoomView middle"},e.div([e.h2([t.i18n`You are currently not in ${t.roomIdOrAlias}.`,e.br(),t.i18n`Want to join it?`]),e.button({className:"button-action primary",onClick:()=>t.join(),disabled:i=>i.busy},t.i18n`Join room`),e.if(i=>i.error,i=>i.p({className:"error"},t.error))]))}}class ri{constructor(e,t=void 0){typeof e=="function"&&!t&&(t=e,e=null),this._root=t?t(A,e):this.render(A,e)}mount(){return this._root}root(){return this._root}unmount(){}update(){}}class Vc extends ri{constructor(e="Loading"){super(e,(t,i)=>t.div({className:"LoadingView"},[Te(t),i]))}}class Kc extends S{render(e,t){return e.main({className:"RoomView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close room`}),e.view(new gt(t,32)),e.div({className:"room-description"},[e.h2(i=>i.name)])]),e.div({className:"RoomView_body"},[e.mapView(i=>i.error,i=>i?new lp(t):new Vc(t.i18n`Setting up the room…`))])])}}class lp extends S{render(e,t){return e.div({className:"RoomBeingCreated_error centered-column"},[e.h3(t.i18n`Could not create the room, something went wrong:`),e.div({className:"RoomView_error form-group"},t.error),e.div({className:"button-row"},e.button({className:"button-action primary destructive",onClick:()=>t.cancel()},t.i18n`Cancel`))])}}class $c extends S{render(e,t){var i;let r=[];t.isDirectMessage&&r.push(At(t,128,"InviteView_dmAvatar"));let n;return t.isDirectMessage?n=[e.strong(t.name),` (${(i=t.inviter)==null?void 0:i.id}) wants to chat with you.`]:t.inviter?n=[At(t.inviter,24),e.strong(t.inviter.name),` (${t.inviter.id}) invited you.`]:n="You were invited to join.",r.push(e.p({className:"InviteView_inviter"},n)),t.isDirectMessage||r.push(e.div({className:"InviteView_roomProfile"},[At(t,64,"InviteView_roomAvatar"),e.h3(t.name),e.p({className:"InviteView_roomDescription"},t.roomDescription)])),e.main({className:"InviteView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close invite`}),At(t,32),e.div({className:"room-description"},[e.h2(o=>o.name)])]),e.if(o=>o.error,o=>o.div({className:"RoomView_error"},a=>a.error)),e.div({className:"InviteView_body"},[e.div({className:"InviteView_invite"},[...r,e.div({className:"InviteView_buttonRow"},e.button({className:"button-action primary",disabled:o=>o.busy,onClick:()=>t.accept()},t.i18n`Accept`)),e.div({className:"InviteView_buttonRow"},e.button({className:"button-action primary destructive",disabled:o=>o.busy,onClick:()=>t.reject()},t.i18n`Reject`))])])])}}class dp extends S{render(e,t){const i=e.a({href:t.closeUrl,title:t.i18n`Close`,className:"close"}),r=e.div({role:"img","aria-label":c=>c.name,title:c=>c.name,className:{picture:!0,hidden:c=>!c.imageUrl},style:c=>`background-image: url('${c.imageUrl}'); max-width: ${c.imageWidth}px; max-height: ${c.imageHeight}px;`}),n=e.div({className:{loading:!0,hidden:c=>!!c.imageUrl}},[Te(e),e.div(t.i18n`Loading image…`)]),o=e.div({className:"details"},[e.strong(c=>c.name),e.br(),"uploaded by ",e.strong(c=>c.sender),c=>` at ${c.time} on ${c.date}.`]),a=e.div({role:"dialog",className:"lightbox",onClick:c=>this.clickToClose(c),onKeydown:c=>this.closeOnEscKey(c)},[r,n,o,i]);return up(e,a),a}clickToClose(e){e.target===this.root()&&this.value.close()}closeOnEscKey(e){(e.key==="Escape"||e.key==="Esc")&&this.value.close()}}function up(s,e){const t=hp(e),i=t[0],r=t[t.length-1];s.addEventListener(e,"keydown",n=>{n.key==="Tab"&&(n.shiftKey?document.activeElement===i&&(r.focus(),n.preventDefault()):document.activeElement===r&&(i.focus(),n.preventDefault()))},!0),Promise.resolve().then(()=>{i.focus()})}function hp(s){return s.querySelectorAll("a[href], button, textarea, input, select")}class pp extends S{render(e,t){return e.div({className:{SessionStatusView:!0,hidden:i=>!i.isShown}},[Te(e,{hidden:i=>!i.isWaiting}),e.p(i=>i.statusLabel),e.if(i=>i.isConnectNowShown,i=>i.button({className:"link",onClick:()=>t.connectNow()},"Retry now")),e.if(i=>i.isSecretStorageShown,i=>i.a({href:t.setupKeyBackupUrl},"Go to settings")),e.if(i=>i.canDismiss,i=>i.div({className:"end"},i.button({className:"dismiss",onClick:()=>t.dismiss()})))])}}class mp extends S{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const i=[];for(let r=0;r<t.height*t.width;r+=1)i.push(e.div({onClick:()=>t.focusTile(r),onFocusin:()=>t.focusTile(r),className:{container:!0,[`tile${r}`]:!0,focused:n=>n.focusIndex===r}},e.mapView(n=>n.roomViewModelAt(r),n=>n?n.kind==="roomBeingCreated"?new Kc(n):n.kind==="invite"?new $c(n):new Fc(n,this._viewClassForTile):new ri(o=>o.div({className:"room-placeholder"},[o.h2({className:"focused"},t.i18n`Select a room on the left`),o.h2({className:"unfocused"},t.i18n`Click to select this tile`)])))));return i.push(e.div({className:r=>`focus-ring tile${r.focusIndex}`})),e.div({className:"RoomGridView middle layout3x2"},i)}}class jc extends S{render(e){return e.div([e.map(t=>t.status,(t,i,r)=>{switch(t){case"Enabled":return _p(i,r);case"NewVersionAvailable":return fp(i,r);case"SetupKey":return gp(i,r);case"SetupPhrase":return yp(i,r);case"Pending":return i.p(r.i18n`Waiting to go online…`)}}),e.map(t=>t.backupWriteStatus,(t,i,r)=>{switch(t){case"Writing":{const n=i.progress({min:0,max:100,value:o=>o.backupPercentage});return i.div(["Backup in progress ",n," ",o=>o.backupInProgressLabel])}case"Stopped":{let n;return r.backupError?n=`Backup has stopped because of an error: ${r.backupError}`:n="Backup has stopped",i.p(n," ",i.button({onClick:()=>r.startBackup()},"Backup now"))}case"Done":return i.p("All keys are backed up.");default:return null}})])}}function _p(s,e){const t=[s.p([e.i18n`Key backup is enabled, using backup version ${e.backupVersion}. `,s.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return e.dehydratedDeviceId&&t.push(s.p(e.i18n`A dehydrated device id was set up with id ${e.dehydratedDeviceId} which you can use during your next login with your secret storage key.`)),s.div(t)}function fp(s,e){const t=[s.p([e.i18n`A new backup version has been created from another device. Disable key backup and enable it again with the new key.`,s.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return s.div(t)}function gp(s,e){const t=s.button({className:"link",onClick:()=>e.showPhraseSetup()},e.i18n`use a security phrase`);return s.div([s.p(e.i18n`Enter your secret storage security key below to ${e.purpose}, which will enable you to decrypt messages received before you logged into this session. The security key is a code of 12 groups of 4 characters separated by a space that Element created for you when setting up security.`),qc(s),Gc(s,e,e.i18n`Security key`,(i,r)=>e.enterSecurityKey(i,r)),s.p([e.i18n`Alternatively, you can `,t,e.i18n` if you have one.`])])}function yp(s,e){const t=s.button({className:"link",onClick:()=>e.showKeySetup()},e.i18n`use your security key`);return s.div([s.p(e.i18n`Enter your secret storage security phrase below to ${e.purpose}, which will enable you to decrypt messages received before you logged into this session. The security phrase is a freeform secret phrase you optionally chose when setting up security in Element. It is different from your password to login, unless you chose to set them to the same value.`),qc(s),Gc(s,e,e.i18n`Security phrase`,(i,r)=>e.enterSecurityPhrase(i,r)),s.p([e.i18n`You can also `,t,e.i18n`.`])])}function Gc(s,e,t,i){let r;const n=()=>i(o.value,r?.checked||!1),o=s.input({type:"password",disabled:c=>c.isBusy,placeholder:t}),a=[s.p([o,s.button({disabled:c=>c.isBusy,onClick:n},e.decryptAction)])];if(e.offerDehydratedDeviceSetup){r=s.input({type:"checkbox",id:"enable-dehydrated-device"});const c=s.a({href:"https://github.com/uhoreg/matrix-doc/blob/dehydration/proposals/2697-device-dehydration.md",target:"_blank",rel:"noopener"},"more info");a.push(s.p([r,s.label({for:r.id},[e.i18n`Back up my device as well (`,c,")"])]))}return s.div({className:"row"},[s.div({className:"label"},t),s.div({className:"content"},a)])}function qc(s){return s.if(e=>e.error,(e,t)=>e.div([e.p({className:"error"},i=>i.i18n`Could not enable key backup: ${i.error}.`),e.p(t.i18n`Try double checking that you did not mix up your security key, security phrase and login password as explained above.`)]))}class vp extends S{render(e,t){let i=t.version;t.showUpdateButton&&(i=e.span([t.version,e.button({onClick:()=>t.checkForUpdate()},t.i18n`Check for updates`)]));const r=(a,c,l,d="")=>a.div({className:`row ${d}`},[a.div({className:"label"},c),a.div({className:"content"},l)]),n=[];n.push(e.h3("Session"),r(e,t.i18n`User ID`,t.userId),r(e,t.i18n`Session ID`,t.deviceId,"code"),r(e,t.i18n`Session key`,t.fingerprintKey,"code"),r(e,"",e.button({onClick:()=>t.logout(),disabled:a=>a.isLoggingOut},t.i18n`Log out`))),n.push(e.h3("Key backup"),e.view(new jc(t.keyBackupViewModel))),n.push(e.h3("Notifications"),e.map(a=>a.pushNotifications.supported,(a,c)=>{if(a===null)return c.p(t.i18n`Loading…`);if(a){const l=u=>u.pushNotifications.enabled?u.i18n`Push notifications are enabled`:u.i18n`Push notifications are disabled`,d=u=>u.pushNotifications.enabled?u.i18n`Disable`:u.i18n`Enable`;return r(c,l,c.button({onClick:()=>t.togglePushNotifications(),disabled:u=>u.pushNotifications.updating},d))}else return c.p(t.i18n`Push notifications are not supported on this browser`)}),e.if(a=>a.pushNotifications.supported&&a.pushNotifications.enabled,a=>a.div([a.p(["If you think push notifications are not being delivered, ",a.button({className:"link",onClick:()=>t.checkPushEnabledOnServer()},"check")," if they got disabled on the server"]),a.map(c=>c.pushNotifications.enabledOnServer,(c,l)=>{if(c===!0)return l.p("Push notifications are still enabled on the server, so everything should be working. Sometimes notifications can get dropped if they can't be delivered within a given time.");if(c===!1)return l.p("Push notifications have been disabled on the server, likely due to a bug. Please re-enable them by clicking Disable and then Enable again above.")}),a.map(c=>c.pushNotifications.serverError,(c,l)=>{if(c)return l.p("Couldn't not check on server: "+c.message)})]))),n.push(e.h3("Preferences"),r(e,t.i18n`Scale down images when sending`,this._imageCompressionRange(e,t)),e.if(a=>a.activeTheme,(a,c)=>r(a,c.i18n`Use the following theme`,this._themeOptions(a,c))));const o=[];return t.canSendLogsToServer&&o.push(e.button({onClick:Xh(()=>t.sendLogsToServer())},`Submit logs to ${t.logsServer}`)),o.push(e.button({onClick:()=>t.exportLogs()},"Download logs")),n.push(e.h3("Application"),r(e,t.i18n`Version`,i),r(e,t.i18n`Storage usage`,a=>`${a.storageUsage} / ${a.storageQuota}`),r(e,t.i18n`Debug logs`,o),e.p({className:{hidden:a=>!a.logsFeedbackMessage}},a=>a.logsFeedbackMessage),e.p(["Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited, the usernames of other users and the names of files you send. They do not contain messages. For more information, review our ",e.a({href:"https://element.io/privacy",target:"_blank",rel:"noopener"},"privacy policy"),"."])),e.main({className:"Settings middle"},[e.div({className:"middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close settings`}),e.h2("Settings")]),e.div({className:"SettingsBody"},n)])}_imageCompressionRange(e,t){const r=Math.ceil(t.minSentImageSizeLimit/32)*32,n=(Math.floor(t.maxSentImageSizeLimit/32)+1)*32,o=a=>t.setSentImageSizeLimit(parseInt(a.target.value,10));return[e.input({type:"range",step:32,min:r,max:n,value:a=>a.sentImageSizeLimit||n,onInput:o,onChange:o})," ",e.output(a=>a.sentImageSizeLimit?a.i18n`resize to ${a.sentImageSizeLimit}px`:a.i18n`no resizing`)]}_themeOptions(e,t){const{themeName:i,themeVariant:r}=t.activeTheme,n=[];for(const _ of Object.keys(t.themeMapping))n.push(e.option({value:_,selected:_===i},_));const o=e.select({onChange:_=>{const f=_.target.value;if(!("id"in t.themeMapping[f])){const E=d.checked?"dark":h.checked?"light":"default";a(E);return}t.changeThemeOption(f)}},n),a=_=>{const f=o.options[o.selectedIndex].value;t.changeThemeOption(f,_)},c=r==="dark",l=r==="light",d=e.input({type:"radio",name:"radio-chooser",value:"dark",id:"dark",checked:c}),u=e.input({type:"radio",name:"radio-chooser",value:"default",id:"default",checked:!(c||l)}),h=e.input({type:"radio",name:"radio-chooser",value:"light",id:"light",checked:l}),m=e.form({className:{hidden:()=>{const _=o.options[o.selectedIndex].value;return"id"in t.themeMapping[_]}},onChange:_=>a(_.target.value)},[u,e.label({for:"default"},"Match system theme"),d,e.label({for:"dark"},"dark"),h,e.label({for:"light"},"light")]);return e.div({className:"theme-chooser"},[o,m])}}class wp extends S{render(e,t){return e.main({className:"middle"},e.div({className:"CreateRoomView centered-column"},[e.h2("Create room"),e.form({className:"CreateRoomView_detailsForm form",onChange:i=>this.onFormChange(i),onSubmit:i=>this.onSubmit(i)},[e.div({className:"vertical-layout"},[e.button({type:"button",className:"CreateRoomView_selectAvatar",onClick:()=>t.selectAvatar()},e.mapView(i=>i.hasAvatar,i=>i?new gt(t,64):new ri(void 0,r=>r.div({className:"CreateRoomView_selectAvatarPlaceholder"})))),e.div({className:"stretch form-row text"},[e.label({for:"name"},t.i18n`Room name`),e.input({onInput:i=>t.setName(i.target.value),type:"text",name:"name",id:"name",placeholder:t.i18n`Enter a room name`})])]),e.div({className:"form-row text"},[e.label({for:"topic"},t.i18n`Topic (optional)`),e.textarea({onInput:i=>t.setTopic(i.target.value),name:"topic",id:"topic",placeholder:t.i18n`Topic`})]),e.div({className:"form-group"},[e.div({className:"form-row check"},[e.input({type:"radio",name:"isPublic",id:"isPrivate",value:"false",checked:!t.isPublic}),e.label({for:"isPrivate"},t.i18n`Private room, only upon invitation.`)]),e.div({className:"form-row check"},[e.input({type:"radio",name:"isPublic",id:"isPublic",value:"true",checked:t.isPublic}),e.label({for:"isPublic"},t.i18n`Public room, anyone can join`)])]),e.div({className:{"form-row check":!0,hidden:i=>i.isPublic}},[e.input({type:"checkbox",name:"isEncrypted",id:"isEncrypted",checked:t.isEncrypted}),e.label({for:"isEncrypted"},t.i18n`Enable end-to-end encryption`)]),e.div({className:{"form-row text":!0,hidden:i=>!i.isPublic}},[e.label({for:"roomAlias"},t.i18n`Room alias`),e.input({onInput:i=>t.setRoomAlias(i.target.value),type:"text",name:"roomAlias",id:"roomAlias",placeholder:t.i18n`Room alias (<alias>, or #<alias> or #<alias>:hs.tld`})]),e.div({className:"form-group"},[e.div(e.button({className:"link",type:"button",onClick:()=>t.toggleAdvancedShown()},i=>i.isAdvancedShown?i.i18n`Hide advanced settings`:i.i18n`Show advanced settings`)),e.div({className:{"form-row check":!0,hidden:i=>!i.isAdvancedShown}},[e.input({type:"checkbox",name:"isFederationDisabled",id:"isFederationDisabled",checked:t.isFederationDisabled}),e.label({for:"isFederationDisabled"},[t.i18n`Disable federation`,e.p({className:"form-row-description"},t.i18n`Can't be changed later. This will prevent people on other homeservers from joining the room. This is typically used when only people from your own organisation (if applicable) should be allowed in the room, and is otherwise not needed.`)])])]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:i=>!i.canCreate},t.i18n`Create room`)])])]))}onFormChange(e){switch(e.target.name){case"isEncrypted":this.value.setEncrypted(e.target.checked);break;case"isPublic":this.value.setPublic(e.currentTarget.isPublic.value==="true");break;case"isFederationDisabled":this.value.setFederationDisabled(e.target.checked);break}}onSubmit(e){e.preventDefault(),this.value.create()}}class bp extends S{render(e,t){const i=()=>t.isEncrypted?t.i18n`On`:t.i18n`Off`;return e.div({className:"RoomDetailsView"},[e.div({className:"RoomDetailsView_avatar"},[e.view(new gt(t,52)),e.mapView(r=>r.isEncrypted,r=>new Sp(r))]),e.div({className:"RoomDetailsView_name"},[e.h2(r=>r.name)]),this._createRoomAliasDisplay(t),e.div({className:"RoomDetailsView_rows"},[this._createRightPanelButtonRow(e,t.i18n`People`,{MemberCount:!0},r=>r.memberCount,()=>t.openPanel("members")),this._createRightPanelRow(e,t.i18n`Encryption`,{EncryptionStatus:!0},i)])])}_createRoomAliasDisplay(e){return e.canonicalAlias?A.div({className:"RoomDetailsView_id"},[e.canonicalAlias]):""}_createRightPanelRow(e,t,i,r){const n=ii(Oi({RoomDetailsView_label:!0},i));return e.div({className:"RoomDetailsView_row"},[e.div({className:n},[t]),e.div({className:"RoomDetailsView_value"},r)])}_createRightPanelButtonRow(e,t,i,r,n){const o=ii(Oi({RoomDetailsView_label:!0},i));return e.button({className:"RoomDetailsView_row",onClick:n},[e.div({className:o},[t]),e.div({className:"RoomDetailsView_value"},r)])}}class Sp extends S{render(e,t){return e.div({className:"EncryptionIconView"},[e.div({className:t?"EncryptionIconView_encrypted":"EncryptionIconView_unencrypted"})])}}class Ep{constructor(e,t){this.start=e,this.end=t}get length(){return this.end-this.start}contains(e){return e.start>=this.start&&e.end<=this.end}containsIndex(e){return e>=this.start&&e<this.end}toLocalIndex(e){return e-this.start}intersects(e){return e.start<this.end&&this.start<e.end}forEachInIterator(e,t){let i=0;for(i=0;i<this.start;i+=1)e.next();for(i=0;i<this.length;i+=1){const r=e.next();if(r.done)break;t(r.value,this.start+i)}}[Symbol.iterator](){return new Ip(this)}reverseIterable(){return new Tp(this)}clampIndex(e,t=this.end-1){return Math.min(Math.max(this.start,e),t)}getIndexZone(e){return e<this.start?Mt.Before:e<this.end?Mt.Inside:Mt.After}}var Mt=(s=>(s[s.Before=1]="Before",s[s.Inside=2]="Inside",s[s.After=3]="After",s))(Mt||{});class Ip{constructor(e){this.range=e,this.idx=e.start-1}next(){return this.idx<this.range.end-1?(this.idx+=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}class Tp{constructor(e){this.range=e,this.idx=e.end}[Symbol.iterator](){return this}next(){return this.idx>this.range.start?(this.idx-=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}class ui extends fn{emitReset(){for(let e of this._handlers)e.onReset(this)}emitAdd(e,t){for(let i of this._handlers)i.onAdd(e,t,this)}emitUpdate(e,t,i){for(let r of this._handlers)r.onUpdate(e,t,i,this)}emitRemove(e,t){for(let i of this._handlers)i.onRemove(e,t,this)}emitMove(e,t,i){for(let r of this._handlers)r.onMove(e,t,i,this)}}class xp extends ui{constructor(e=[]){super(),this._items=e}append(e){this._items.push(e),this.emitAdd(this._items.length-1,e)}remove(e){const[t]=this._items.splice(e,1);this.emitRemove(e,t)}insertMany(e,t){for(let i of t)this.insert(e,i),e+=1}insert(e,t){this._items.splice(e,0,t),this.emitAdd(e,t)}move(e,t){if(e<this._items.length&&t<this._items.length){const[i]=this._items.splice(e,1);this._items.splice(t,0,i),this.emitMove(e,t,i)}}update(e,t,i=null){e<this._items.length&&(this._items[e]=t,this.emitUpdate(e,t,i))}get array(){return this._items}at(e){if(this._items&&e>=0&&e<this._items.length)return this._items[e]}get length(){return this._items.length}[Symbol.iterator](){return this._items.values()}}function kp(s,e){let t=0;for(;t<e;)if(t+=1,s.next().done)return!1;return!0}function yr(s,e){if(kp(s,e)){const t=s.next();if(!t.done)return t.value}}var Ht=(s=>(s[s.Move=0]="Move",s[s.Add=1]="Add",s[s.Remove=2]="Remove",s[s.RemoveAndAdd=3]="RemoveAndAdd",s[s.UpdateRange=4]="UpdateRange",s))(Ht||{});class Ci extends Ep{constructor(e,t,i,r=t-e){super(e,t),this._totalLength=i,this._viewportItemCount=r}expand(e){if(this.length===0)return this;const t=Math.max(0,this.start-e),i=Math.min(this.totalLength,this.end+e);return new Ci(t,i,this.totalLength,this._viewportItemCount)}get totalLength(){return this._totalLength}get viewportItemCount(){return this._viewportItemCount}static fromViewport(e,t,i,r){const n=Math.min(Math.max(0,Math.floor(r/t)),e),o=e-n,a=i!==0?Math.ceil(i/t):0,c=Math.min(a,o);return new Ci(n,n+c,e,a)}queryAdd(e,t,i){const r=this.viewportItemCount>this.length?this.end:this.end-1;if(e<=r){const n=this.clampIndex(e,r),o=n===e?t:yr(i[Symbol.iterator](),n);return this.createAddResult(n,o)}else return{type:4,newRange:this.deriveRange(1,0)}}queryRemove(e,t){if(e<this.end){const i=this.clampIndex(e);return this.createRemoveResult(i,t)}else return{type:4,newRange:this.deriveRange(-1,0)}}queryMove(e,t,i,r){const n=this.getIndexZone(e),o=this.getIndexZone(t);if(n===o){if(n===Mt.Before||n===Mt.After)return;if(n===Mt.Inside)return{type:0,fromIdx:e,toIdx:t}}else{const a=this.clampIndex(t),c=this.clampIndex(e),l=a===t?i:yr(r[Symbol.iterator](),a);return{type:3,removeIdx:c,addIdx:a,value:l}}}createAddResult(e,t){if(this.viewportItemCount>this.length)return{type:1,addIdx:e,value:t,newRange:this.deriveRange(1,1)};{const i=this.clampIndex(Number.MAX_SAFE_INTEGER);return{type:3,removeIdx:i,addIdx:e,value:t,newRange:this.deriveRange(1,0)}}}createRemoveResult(e,t){if(this.end<this.totalLength){const i=this.clampIndex(Number.MAX_SAFE_INTEGER),r=yr(t[Symbol.iterator](),i);return{type:3,removeIdx:e,value:r,addIdx:i,newRange:this.deriveRange(-1,0)}}else if(this.start!==0){const i=this.deriveRange(-1,0,1),r=i.start,n=yr(t[Symbol.iterator](),r);return{type:3,removeIdx:e,value:n,addIdx:r,newRange:i}}else return{type:2,removeIdx:e,newRange:this.deriveRange(-1,0)}}deriveRange(e,t,i=0){const r=this.start-i,n=this.totalLength+e,o=Math.min(Math.max(r,this.end-i+t),n);return new Ci(r,o,n,this.viewportItemCount)}}class Rp extends Ji{constructor(e,t){var i=e,{itemHeight:r,overflowItems:n=20}=i,o=fu(i,["itemHeight","overflowItems"]);super(o,t),this.itemHeight=r,this.overflowItems=n}handleEvent(e){e.type==="scroll"?this.handleScroll():super.handleEvent(e)}handleScroll(){const e=this._getVisibleRange();if(e.length!==0&&!this.renderRange.contains(e)){const t=this.renderRange;this.renderRange=e.expand(this.overflowItems),this.renderUpdate(t,this.renderRange)}}async loadList(){if(await new Promise(t=>requestAnimationFrame(t)),await new Promise(t=>requestAnimationFrame(t)),!this._list)return;this._subscription=this._list.subscribe(this);const e=this._getVisibleRange();this.renderRange=e.expand(this.overflowItems),this._childInstances=[],this.reRenderFullRange(this.renderRange)}_getVisibleRange(){const{clientHeight:e,scrollTop:t}=this.root();if(e===0)throw new Error("LazyListView height is 0");return Ci.fromViewport(this._list.length,this.itemHeight,e,t)}reRenderFullRange(e){Jh(this._listElement);const t=document.createDocumentFragment(),i=this._list[Symbol.iterator]();this._childInstances.length=0,e.forEachInIterator(i,r=>{const n=this._childCreator(r);this._childInstances.push(n),t.appendChild(Li(n,this._mountArgs))}),this._listElement.appendChild(t),this.adjustPadding(e)}renderUpdate(e,t){if(t.intersects(e)){for(const i of e.reverseIterable())if(!t.containsIndex(i)){const r=i-e.start;this.removeChild(r)}t.forEachInIterator(this._list[Symbol.iterator](),(i,r)=>{if(!e.containsIndex(r)){const n=r-t.start;this.addChild(n,i)}}),this.adjustPadding(t)}else this.reRenderFullRange(t)}adjustPadding(e){const t=e.start*this.itemHeight,i=(e.totalLength-e.end)*this.itemHeight,r=this._listElement.style;r.paddingTop=`${t}px`,r.paddingBottom=`${i}px`}mount(){const e=super.mount();return this.scrollContainer=A.div({className:"LazyListParent"},e),this.scrollContainer.addEventListener("scroll",this),this.scrollContainer}unmount(){this.root().removeEventListener("scroll",this),this.scrollContainer=void 0,super.unmount()}root(){return this.scrollContainer}get _listElement(){return super.root()}onAdd(e,t){const i=this.renderRange.queryAdd(e,t,this._list);this.applyRemoveAddResult(i)}onRemove(e,t){const i=this.renderRange.queryRemove(e,this._list);this.applyRemoveAddResult(i)}onMove(e,t,i){const r=this.renderRange.queryMove(e,t,i,this._list);r&&(r.type===Ht.Move?this.moveChild(this.renderRange.toLocalIndex(r.fromIdx),this.renderRange.toLocalIndex(r.toIdx)):this.applyRemoveAddResult(r))}onUpdate(e,t,i){this.renderRange.containsIndex(e)&&this.updateChild(this.renderRange.toLocalIndex(e),t,i)}applyRemoveAddResult(e){(e.type===Ht.Remove||e.type===Ht.RemoveAndAdd)&&this.removeChild(this.renderRange.toLocalIndex(e.removeIdx)),e.newRange&&(this.renderRange=e.newRange,this.adjustPadding(this.renderRange)),(e.type===Ht.Add||e.type===Ht.RemoveAndAdd)&&this.addChild(this.renderRange.toLocalIndex(e.addIdx),e.value)}}class Ap extends S{render(e,t){return e.li({className:"MemberTileView"},e.a({href:t.detailsUrl},[e.view(new gt(t,32)),e.div({className:"MemberTileView_name"},i=>i.name)]))}}class Cp extends Rp{constructor(e){super({list:e.memberTileViewModels,className:"MemberListView",itemHeight:40},t=>new Ap(t))}}class Np extends S{render(e,t){return e.div({className:"MemberDetailsView"},[e.view(new gt(t,128)),e.div({className:"MemberDetailsView_name"},e.h2(i=>i.name)),e.div({className:"MemberDetailsView_id"},t.userId),this._createSection(e,t.i18n`Role`,i=>i.role),this._createSection(e,t.i18n`Security`,t.isEncrypted?t.i18n`Messages in this room are end-to-end encrypted.`:t.i18n`Messages in this room are not end-to-end encrypted.`),this._createOptions(e,t)])}_createSection(e,t,i){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t),e.div({className:"MemberDetailsView_value"},i)])}_createOptions(e,t){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t.i18n`Options`),e.div({className:"MemberDetailsView_options"},[e.a({href:t.linkToUser,target:"_blank",rel:"noopener"},t.i18n`Open Link to User`),e.button({className:"text",onClick:()=>t.openDirectMessage()},t.i18n`Open direct message`)])])}}class Mp extends S{render(e){return e.div({className:"RightPanelView"},[e.ifView(t=>t.activeViewModel,t=>new Dp(t)),e.mapView(t=>t.activeViewModel,t=>this._viewFromType(t))])}_viewFromType(e){switch(e?.type){case"room-details":return new bp(e);case"member-list":return new Cp(e);case"member-details":return new Np(e);default:return new Vc}}}class Dp extends S{render(e,t){return e.div({className:"RightPanelView_buttons"},[e.button({className:{back:!0,"button-utility":!0,hide:!t.activeViewModel.shouldShowBackButton},onClick:()=>t.showPreviousPanel()}),e.button({className:"close button-utility",onClick:()=>t.closePanel()})])}}class Pp extends Ji{constructor(e){const t={className:"Timeline_messageReactions",tagName:"div",list:e.reactions,onItemClick:i=>i.onClick()};super(t,i=>new Op(i))}}class Op extends S{render(e,t){return e.button({className:{active:i=>i.isActive,pending:i=>i.isPending}},[t.key," ",i=>`${i.count}`])}onClick(){this.value.toggle()}}class hi extends S{constructor(e,t,i,r="li"){super(e),this._menuPopup=null,this._tagName=r,this._viewClassForTile=t,this._renderFlags=i}get _interactive(){var e,t;return(t=(e=this._renderFlags)==null?void 0:e.interactive)!=null?t:!0}get _isReplyPreview(){var e;return(e=this._renderFlags)==null?void 0:e.reply}render(e,t){const i=[this.renderMessageBody(e,t)];this._interactive&&i.push(e.button({className:"Timeline_messageOptions"},"\u22EF"));const r=e.el(this._tagName,{className:{Timeline_message:!0,own:t.isOwn,unsent:t.isUnsent,unverified:t.isUnverified,disabled:!this._interactive,continuation:o=>o.isContinuation},"data-event-id":t.eventId},i);e.mapSideEffect(o=>o.isContinuation,(o,a)=>{if(o&&a===!1)r.removeChild(r.querySelector(".Timeline_messageAvatar")),r.removeChild(r.querySelector(".Timeline_messageSender"));else if(!o&&!this._isReplyPreview){const c=A.a({href:t.memberPanelLink,className:"Timeline_messageAvatar"},[At(t,30)]),l=A.div({className:`Timeline_messageSender usercolor${t.avatarColorNumber}`},t.displayName);r.insertBefore(c,r.firstChild),r.insertBefore(l,r.firstChild)}});let n=null;return e.mapSideEffect(o=>o.reactions,o=>{o&&this._interactive&&!n?(n=new Pp(o),this.addSubView(n),r.appendChild(Li(n))):!o&&n&&(r.removeChild(n.root()),n.unmount(),this.removeSubView(n),n=null)}),r}onClick(e){e.target.className==="Timeline_messageOptions"&&this._toggleMenu(e.target)}_toggleMenu(e){if(this._menuPopup&&this._menuPopup.isOpen)this._menuPopup.close();else{const t=this.createMenuOptions(this.value);if(!t.length)return;this.root().classList.add("menuOpen");const i=()=>this.root().classList.remove("menuOpen");this._menuPopup=new Xr(new Y(t),i),this._menuPopup.trackInTemplateView(this),this._menuPopup.showRelativeTo(e,2)}}createMenuOptions(e){const t=[];return e.canReact&&e.shape!=="redacted"&&!e.isPending&&(t.push(new Up(e)),t.push(Y.option(e.i18n`Reply`,()=>e.startReply()))),e.canAbortSending?t.push(Y.option(e.i18n`Cancel`,()=>e.abortSending())):e.canRedact&&t.push(Y.option(e.i18n`Delete`,()=>e.redact()).setDestructive()),t}renderMessageBody(){}}class Up{constructor(e){this._vm=e}toDOM(e){const t=["\u{1F44D}","\u{1F44E}","\u{1F604}","\u{1F389}","\u{1F615}","\u2764\uFE0F","\u{1F680}","\u{1F440}"].map(r=>e.button({onClick:()=>this._vm.react(r)},r)),i=e.button({onClick:()=>{const r=prompt("Enter your reaction (emoji)");r&&this._vm.react(r)}},"\u2026");return e.li({className:"quick-reactions"},[...t,i])}}class Bp extends S{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const i=this._viewClassForTile(t);if(!i)throw new Error(`Shape ${t.shape} is unrecognized.`);const r=new i(t,this._viewClassForTile,{reply:!0,interactive:!1});return e.div({className:"ReplyPreviewView"},e.blockquote([e.a({className:"link",href:t.permaLink},"In reply to"),e.a({className:"pill",href:t.senderProfileLink},[At(t,12,void 0),t.displayName]),e.br(),e.view(r)]))}}class Lp extends S{render(e){return e.blockquote({className:"ReplyPreviewView"},[e.div({className:"Timeline_messageBody statusMessage"},"This reply could not be found.")])}}class Fp extends hi{renderMessageBody(e,t){const i=e.time({className:{hidden:!t.date}},t.date+" "+t.time),r=e.div({className:{Timeline_messageBody:!0,statusMessage:o=>o.shape==="message-status"}},e.mapView(o=>o.replyTile,o=>this._isReplyPreview?null:t.isReply&&!o?new Lp:o?new Bp(o,this._viewClassForTile):null)),n=o=>o?.nodeType!==Node.COMMENT_NODE&&o.className!=="ReplyPreviewView";return e.mapSideEffect(o=>o.body,o=>{for(;n(r.lastChild);)r.removeChild(r.lastChild);for(const a of o.parts)r.appendChild(zc(a));r.appendChild(i)}),r}}function Vp(s){const e=s.items.map(i=>A.li(Dt(i))),t=s.startOffset;return t?A.ol({start:t},e):A.ul(e)}function Kp(s){const e={src:s.src};return s.width&&(e.width=s.width),s.height&&(e.height=s.height),s.alt&&(e.alt=s.alt),s.title&&(e.title=s.title),A.img(e)}function $p(s){const e=`avatar size-12 usercolor${s.avatarColorNumber}`,t=A.div({class:e},Ge(s.avatarInitials)),i=Dt(s.children);return i.unshift(t),A.a({class:"pill",href:s.href,rel:"noopener",target:"_blank"},i)}function jp(s){const e=[];if(s.head){const i=s.head.map(r=>A.th(Dt(r)));e.push(A.thead(A.tr(i)))}const t=[];for(const i of s.body){const r=i.map(n=>A.td(Dt(n)));t.push(A.tr(r))}return e.push(A.tbody(t)),A.table(e)}const Gp={header:s=>A["h"+Math.min(6,s.level)](Dt(s.inlines)),codeblock:s=>A.pre(A.code(Ge(s.text))),table:s=>jp(s),code:s=>A.code(Ge(s.text)),text:s=>Ge(s.text),link:s=>A.a({href:s.url,className:"link",target:"_blank",rel:"noopener"},Dt(s.inlines)),pill:$p,format:s=>A[s.format](Dt(s.children)),rule:()=>A.hr(),list:Vp,image:Kp,newline:()=>A.br()};function zc(s){const e=Gp[s.type];return e?e(s):Ge(`[unknown part type ${s.type}]`)}function Dt(s){return Array.from(s,zc)}class Hc extends hi{renderMessageBody(e,t){let r=`padding-top: ${t.height/t.width*100}%;`;t.platform.isIE11&&(r=`height: ${t.height}px`);const n=[e.div({className:"spacer",style:r}),this.renderMedia(e,t),e.time(t.date+" "+t.time)],o=e.div({className:{status:!0,hidden:a=>!a.status}},a=>a.status);if(n.push(o),t.isPending){const a=e.progress({min:0,max:100,value:c=>c.uploadPercentage,className:{hidden:c=>!c.isUploading}});n.push(a)}return e.div({className:"Timeline_messageBody"},[e.div({className:"media",style:`max-width: ${t.width}px`,"data-testid":"media"},n),e.if(a=>a.error,a=>a.p({className:"error"},t.error))])}createMenuOptions(e){const t=super.createMenuOptions(e);if(!e.isPending){let i;switch(e.shape){case"image":i=e.i18n`Download image`;break;case"video":i=e.i18n`Download video`;break;default:i=e.i18n`Download media`;break}t.push(Y.option(i,()=>e.downloadMedia()))}return t}}class qp extends Hc{renderMedia(e,t){const i=e.img({src:r=>r.thumbnailUrl,alt:r=>r.label,title:r=>r.label,style:`max-width: ${t.width}px; max-height: ${t.height}px;`});return t.isPending||!t.lightboxUrl?i:e.a({href:t.lightboxUrl},i)}}function Vr(s,e){return new Promise((t,i)=>{let r;const n=a=>{r(),i(a.target.error)},o=()=>{r(),t()};r=()=>{s.removeEventListener(e,o),s.removeEventListener("error",n)},s.addEventListener(e,o),s.addEventListener("error",n)})}class zp extends Hc{renderMedia(e){const t=e.video({src:i=>i.videoUrl||`data:${i.mimeType},`,title:i=>i.label,controls:!0,preload:"none",poster:i=>i.thumbnailUrl,onPlay:this._onPlay.bind(this),style:i=>`max-width: ${i.width}px; max-height: ${i.height}px;${i.isPending?"z-index: -1":""}`});return t.addEventListener("error",this._onError.bind(this)),t}async _onPlay(e){const t=this.value;if(!t.videoUrl)try{const i=e.target;await t.loadVideo();const r=Vr(i,"loadeddata");i.load(),await r,i.play()}catch{}}_onError(e){const t=this.value,i=e.target,r=i.error;if(r instanceof window.MediaError&&r.code===4)if(!i.src.startsWith("data:"))t.setViewError(new Error(`this browser does not support videos of type ${t.mimeType}.`));else return;else t.setViewError(r)}}class Hp extends hi{renderMessageBody(e,t){const i=[];return t.isPending?i.push(r=>r.label):i.push(e.button({className:"link",onClick:()=>t.download()},r=>r.label),e.time(t.date+" "+t.time)),e.p({className:"Timeline_messageBody statusMessage"},i)}}class Wp extends hi{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},[e.span(t.label),e.a({className:"Timeline_locationLink",href:t.mapsLink,target:"_blank",rel:"noopener"},t.i18n`Open in maps`),e.time(t.date+" "+t.time)])}}class Yp extends hi{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},t.label)}}class Jp extends S{constructor(e){super(e)}render(e,t){return e.li({className:"AnnouncementView","data-event-id":t.eventId},e.div(i=>i.announcement))}onClick(){}}class Xp extends hi{renderMessageBody(e){return e.p({className:"Timeline_messageBody statusMessage"},t=>t.description)}createMenuOptions(e){const t=super.createMenuOptions(e);return e.isRedacting&&t.push(Y.option(e.i18n`Cancel`,()=>e.abortPendingRedaction())),t}}class Qp extends S{constructor(e){super(e)}render(e){const t={GapView:!0,isLoading:i=>i.isLoading,isAtTop:i=>i.isAtTop};return e.li({className:t},[e.if(i=>i.showSpinner,i=>Te(i)),e.span(i=>i.currentAction)])}onClick(){}}function Ys(s){switch(s.shape){case"gap":return Qp;case"announcement":return Jp;case"message":case"message-status":return Fp;case"image":return qp;case"video":return zp;case"file":return Hp;case"location":return Wp;case"missing-attachment":return Yp;case"redacted":return Xp;default:throw new Error(`Tiles of shape "${s.shape}" are not supported, check the tileClassForEntry function in the view model`)}}class Zp extends S{render(e,t){const i=e.input({type:"text",name:"id",id:"id",placeholder:t.i18n`Enter a room id or alias`,disabled:r=>r.joinInProgress});return e.main({className:"middle"},e.div({className:"JoinRoomView centered-column"},[e.h2("Join room"),e.form({className:"JoinRoomView_detailsForm form",onSubmit:r=>this.onSubmit(r,i.value)},[e.div({className:"vertical-layout"},[e.div({className:"stretch form-row text"},[e.label({for:"id"},t.i18n`Room id`),i])]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:r=>r.joinInProgress},t.i18n`Join`)]),e.map(r=>r.status,(r,n)=>n.div({className:"JoinRoomView_status"},[Te(n,{hidden:o=>!o.joinInProgress}),n.span(r)]))])]))}onSubmit(e,t){e.preventDefault(),this.value.join(t)}}class em extends S{render(e,t){return e.div({className:{SessionView:!0,"middle-shown":i=>!!i.activeMiddleViewModel,"right-shown":i=>!!i.rightPanelViewModel}},[e.view(new pp(t.sessionStatusViewModel)),e.view(new sp(t.leftPanelViewModel)),e.mapView(i=>i.activeMiddleViewModel,()=>t.roomGridViewModel?new mp(t.roomGridViewModel,Ys):t.settingsViewModel?new vp(t.settingsViewModel):t.createRoomViewModel?new wp(t.createRoomViewModel):t.joinRoomViewModel?new Zp(t.joinRoomViewModel):t.currentRoomViewModel?t.currentRoomViewModel.kind==="invite"?new $c(t.currentRoomViewModel):t.currentRoomViewModel.kind==="room"?new Fc(t.currentRoomViewModel,Ys):t.currentRoomViewModel.kind==="roomBeingCreated"?new Kc(t.currentRoomViewModel):new cp(t.currentRoomViewModel):new ri(i=>i.div({className:"room-placeholder"},i.h2(t.i18n`Choose a room on the left side.`)))),e.mapView(i=>i.lightboxViewModel,i=>i?new dp(i):null),e.mapView(i=>i.rightPanelViewModel,i=>i?new Mp(i):null)])}}function Wc(s){return s.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web"},"Hydrogen on Github")}class tm extends S{render(e,t){const i=o=>!!o.isBusy,r=e.input({id:"username",type:"text",placeholder:t.i18n`Username`,disabled:i}),n=e.input({id:"password",type:"password",placeholder:t.i18n`Password`,disabled:i});return e.div({className:"PasswordLoginView form"},[e.if(o=>o.error,o=>o.div({className:"error"},a=>a.error)),e.form({onSubmit:o=>{o.preventDefault(),t.login(r.value,n.value)}},[e.if(o=>o.errorMessage,(o,a)=>o.p({className:"error"},a.i18n(a.errorMessage))),e.div({className:"form-row text"},[e.label({for:"username"},t.i18n`Username`),r]),e.div({className:"form-row text"},[e.label({for:"password"},t.i18n`Password`),n]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:i},t.i18n`Log In`)])])])}}class im extends S{render(e,t){return e.div({className:"Settings"},[e.h3(t.i18n`Restore your encrypted history?`),e.ifView(i=>i.decryptDehydratedDeviceViewModel,i=>new jc(i.decryptDehydratedDeviceViewModel)),e.map(i=>i.deviceDecrypted,(i,r)=>i?r.p(t.i18n`That worked out, you're good to go!`):r.p(t.i18n`This will claim the dehydrated device ${t.dehydratedDeviceId}, and will set up a new one.`)),e.div({className:"button-row"},[e.button({className:"button-action primary",onClick:()=>{t.finish()},type:"button"},i=>i.deviceDecrypted?i.i18n`Continue`:i.i18n`Continue without restoring`)])])}}class Qr extends S{render(e){const t=e.if(r=>r.hasError,(r,n)=>r.button({onClick:()=>n.exportLogs()},n.i18n`Export logs`)),i=e.if(r=>r.hasError,(r,n)=>r.button({onClick:()=>n.logout()},n.i18n`Log out`));return e.div({className:"SessionLoadStatusView"},[e.p({className:"status"},[Te(e,{hidden:r=>!r.loading}),e.p(r=>r.loadLabel),t,i]),e.ifView(r=>r.accountSetupViewModel,r=>new im(r.accountSetupViewModel))])}}class rm extends S{render(e){return e.div({className:"CompleteSSOView"},[e.p({className:"CompleteSSOView_title"},"Finishing up your SSO Login"),e.if(t=>t.errorMessage,(t,i)=>t.p({className:"error"},i.i18n(i.errorMessage))),e.mapView(t=>t.loadViewModel,t=>t?new Qr(t):null)])}}class sm extends S{render(e,t){const i=r=>r.isBusy;return e.div({className:"PreSessionScreen"},[e.button({className:"button-utility LoginView_back",onClick:()=>t.goBack(),disabled:i}),e.div({className:"logo"}),e.h1([t.i18n`Sign In`]),e.mapView(r=>r.completeSSOLoginViewModel,r=>r?new rm(r):null),e.if(r=>r.showHomeserver,(r,n)=>r.div({className:"LoginView_sso form-row text"},[r.label({for:"homeserver"},n.i18n`Homeserver`),r.input({id:"homeserver",type:"text",placeholder:n.i18n`Your matrix homeserver`,value:n.homeserver,disabled:i,onInput:o=>n.setHomeserver(o.target.value),onChange:()=>n.queryHomeserver()}),r.p({className:{LoginView_forwardInfo:!0,hidden:o=>!o.resolvedHomeserver}},o=>o.i18n`You will connect to ${o.resolvedHomeserver}.`),r.if(o=>o.errorMessage,(o,a)=>o.p({className:"error"},a.i18n(a.errorMessage)))])),e.if(r=>r.isFetchingLoginOptions,r=>r.div({className:"LoginView_query-spinner"},[Te(r),r.p("Fetching available login options...")])),e.mapView(r=>r.passwordLoginViewModel,r=>r?new tm(r):null),e.if(r=>r.passwordLoginViewModel&&r.startSSOLoginViewModel,r=>r.p({className:"LoginView_separator"},t.i18n`or`)),e.mapView(r=>r.startSSOLoginViewModel,r=>r?new nm(r):null),e.mapView(r=>r.loadViewModel,r=>r?new Qr(r):null),e.p(Wc(e))])}}class nm extends S{render(e,t){return e.div({className:"StartSSOLoginView"},e.button({className:"StartSSOLoginView_button button-action secondary",type:"button",onClick:()=>t.startSSOLogin(),disabled:i=>i.isBusy},t.i18n`Log in with SSO`))}}class om extends S{render(e,t){const i=new Fr(t,n=>n.div([n.p("Are you sure you want to log out?"),n.div({className:"button-row"},[n.a({className:"button-action",type:"submit",href:t.cancelUrl},["Cancel"]),n.button({className:"button-action primary destructive",type:"submit",onClick:()=>t.logout()},t.i18n`Log out`)])])),r=new Fr(t,n=>n.p({className:"status",hidden:o=>!o.showStatus},[Te(n,{hidden:o=>!o.busy}),n.span(o=>o.status)]));return e.div({className:"LogoutScreen"},[e.div({className:"content"},[e.mapView(n=>n.showConfirm,n=>n?i:r)])])}}class am extends S{render(e){return e.div({className:"LogoutScreen"},[e.div({className:"content"},e.map(t=>t.showStatus,(t,i,r)=>t?i.p({className:"status"},[Te(i,{hidden:n=>!n.showSpinner}),i.span(n=>n.status)]):i.div([i.p("Your access token is no longer valid! You can reauthenticate in the next screen."),i.div({className:"button-row"},[i.button({className:"button-action primary",type:"submit",onClick:()=>r.proceed()},r.i18n`Proceed`)])])))])}}class cm extends S{render(e,t){return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionLoadView"},[e.view(new Qr(t))]),e.div({className:{"button-row":!0,hidden:i=>i.loading}},e.a({className:"button-action primary",href:t.backUrl},t.i18n`Go back`))])}}class lm extends S{_onDeleteClick(){confirm("Are you sure?")&&this.value.delete()}_onClearClick(){confirm("Are you sure?")&&this.value.clear()}render(e,t){return e.li([e.a({className:"session-info",href:t.openUrl},[e.div({className:`avatar usercolor${t.avatarColorNumber}`},i=>i.avatarInitials),e.div({className:"user-id"},i=>i.label)])])}}class dm extends S{render(e,t){const i=new Ji({list:t.sessions,parentProvidesUpdates:!1},r=>new lm(r));return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionPickerView"},[e.h1(["Continue as \u2026"]),e.view(i),e.div({className:"button-row"},[e.a({className:"button-action primary",href:t.cancelUrl},t.i18n`Sign In`)]),e.ifView(r=>r.loadViewModel,()=>new Qr(t.loadViewModel)),e.p(Wc(e))])])}}class um extends S{render(e,t){return e.mapView(i=>i.activeSection,i=>{switch(i){case"error":return new ri(r=>r.div({className:"StatusView"},[r.h1("Something went wrong"),r.p(t.errorText)]));case"session":return new em(t.sessionViewModel);case"login":return new sm(t.loginViewModel);case"logout":return new om(t.logoutViewModel);case"forced-logout":return new am(t.forcedLogoutViewModel);case"picker":return new dm(t.sessionPickerViewModel);case"redirecting":return new ri(r=>r.p("Redirecting..."));case"loading":return new cm(t.sessionLoadViewModel);default:throw new Error(`Unknown section: ${t.activeSection}`)}})}}class hm{constructor(e){this._reject=null,this._handle=null,this._promise=new Promise((t,i)=>{this._reject=i,this._handle=setTimeout(()=>{this._reject=null,t()},e)})}elapsed(){return this._promise}abort(){this._reject&&(this._reject(new Me),clearTimeout(this._handle),this._handle=null,this._reject=null)}dispose(){this.abort()}}class pm{constructor(e,t){this._handle=setInterval(t,e)}dispose(){this._handle&&(clearInterval(this._handle),this._handle=null)}}class mm{constructor(){this._start=window.performance.now()}measure(){return window.performance.now()-this._start}}class _m{createMeasure(){return new mm}createTimeout(e){return new hm(e)}createInterval(e,t){return new pm(t,e)}now(){return Date.now()}}class fm{constructor(){this._waitingForReply=new Map,this._messageIdCounter=0,this._navigation=null,this._registration=null,this._registrationPromise=null,this._currentController=null,this.haltRequests=!1}setNavigation(e){this._navigation=e}registerAndStart(e){this._registrationPromise=(async()=>{navigator.serviceWorker.addEventListener("message",this),navigator.serviceWorker.addEventListener("controllerchange",this),this._registration=await navigator.serviceWorker.register(e),await navigator.serviceWorker.ready,this._currentController=navigator.serviceWorker.controller,this._registration.addEventListener("updatefound",this),this._registrationPromise=null,this._registration.waiting&&this._registration.active&&this._proposeUpdate(),console.log("Service Worker registered")})()}_onMessage(e){const{data:t}=e,i=t.replyTo;if(i){const r=this._waitingForReply.get(i);r&&(this._waitingForReply.delete(i),r(t.payload))}if(t.type==="hasSessionOpen"){const r=this._navigation.observe("session").get()===t.payload.sessionId;e.source.postMessage({replyTo:t.id,payload:r})}else if(t.type==="hasRoomOpen"){const r=this._navigation.observe("session").get()===t.payload.sessionId,n=this._navigation.observe("room").get()===t.payload.roomId;e.source.postMessage({replyTo:t.id,payload:r&&n})}else if(t.type==="closeSession"){const{sessionId:r}=t.payload;this._closeSessionIfNeeded(r).finally(()=>{e.source.postMessage({replyTo:t.id})})}else t.type==="haltRequests"?(this.haltRequests=!0,e.source.postMessage({replyTo:t.id})):t.type==="openRoom"&&this._navigation.push("room",t.payload.roomId)}_closeSessionIfNeeded(e){var t;const i=(t=this._navigation)==null?void 0:t.path.get("session");return e&&i?.value===e?new Promise(r=>{const n=this._navigation.pathObservable.subscribe(o=>{const a=o.get("session");(!a||a.value!==e)&&(n(),r())});this._navigation.push("session")}):Promise.resolve()}async _proposeUpdate(){if(document.hidden)return;const e=await this._sendAndWaitForReply("version",null,this._registration.waiting);confirm(`Version ${e.version} (${e.buildHash}) is available. Reload to apply?`)&&(await this._sendAndWaitForReply("haltRequests"),this._send("skipWaiting",null,this._registration.waiting))}handleEvent(e){switch(e.type){case"message":this._onMessage(e);break;case"updatefound":this._registration.installing.addEventListener("statechange",this);break;case"statechange":{e.target.state==="installed"&&(this._proposeUpdate(),e.target.removeEventListener("statechange",this));break}case"controllerchange":this._currentController?document.location.reload():this._currentController=navigator.serviceWorker.controller;break}}async _send(e,t,i=void 0){this._registrationPromise&&await this._registrationPromise,i||(i=this._registration.active),i.postMessage({type:e,payload:t})}async _sendAndWaitForReply(e,t,i=void 0){this._registrationPromise&&await this._registrationPromise,i||(i=this._registration.active),this._messageIdCounter+=1;const r=this._messageIdCounter,n=new Promise(o=>{this._waitingForReply.set(r,o)});return i.postMessage({type:e,id:r,payload:t}),await n}async checkForUpdate(){this._registrationPromise&&await this._registrationPromise,this._registration.update()}get version(){return"0.3.2"}get buildHash(){return null}async preventConcurrentSessionAccess(e){return this._sendAndWaitForReply("closeSession",{sessionId:e})}async getRegistration(){return this._registrationPromise&&await this._registrationPromise,this._registration}}class gm{constructor(e,t){this._serviceWorkerHandler=e,this._pushConfig=t}async enablePush(e,t){var i;const r=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());if(r?.pushManager){const o=(await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this._pushConfig.applicationServerKey})).toJSON(),a=o.keys.p256dh,c={endpoint:o.endpoint,auth:o.keys.auth,events_only:!0,default_payload:t};return e.httpPusher(this._pushConfig.gatewayUrl,this._pushConfig.appId,a,c)}}async disablePush(){var e;const t=await((e=this._serviceWorkerHandler)==null?void 0:e.getRegistration());if(t?.pushManager){const i=await t.pushManager.getSubscription();i&&await i.unsubscribe()}}async isPushEnabled(){var e;const t=await((e=this._serviceWorkerHandler)==null?void 0:e.getRegistration());return t?.pushManager?!!await t.pushManager.getSubscription():!1}async supportsPush(){var e;if(!this._pushConfig)return!1;const t=await((e=this._serviceWorkerHandler)==null?void 0:e.getRegistration());return t&&"pushManager"in t}async enableNotifications(){return"Notification"in window?await Notification.requestPermission()==="granted":!1}async supportsNotifications(){return"Notification"in window}async areNotificationsEnabled(){return"Notification"in window?Notification.permission==="granted":!1}async showNotification(e,t=void 0){var i;if("Notification"in window){new Notification(e,{body:t});return}const r=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());r?.showNotification(e,{body:t})}}class ym extends di{constructor(){super(),this._lastSessionHash=void 0}handleEvent(e){e.type==="hashchange"&&(this.emit(this.get()),this._storeHash(this.get()))}get(){return document.location.search.includes("loginToken")?document.location.search:document.location.hash}replaceUrlSilently(e){window.history.replaceState(null,null,e),this._storeHash(e)}pushUrlSilently(e){window.history.pushState(null,null,e),this._storeHash(e)}pushUrl(e){document.location.hash=e}urlAsPath(e){return e.startsWith("#")?e.substr(1):e}pathAsUrl(e){return`#${e}`}onSubscribeFirst(){var e;this._lastSessionHash=(e=window.localStorage)==null?void 0:e.getItem("hydrogen_last_url_hash"),window.addEventListener("hashchange",this)}onUnsubscribeLast(){window.removeEventListener("hashchange",this)}_storeHash(e){var t;(t=window.localStorage)==null||t.setItem("hydrogen_last_url_hash",e)}getLastSessionUrl(){return this._lastSessionHash}}class vm extends di{constructor(){super(),this._onOffline=this._onOffline.bind(this),this._onOnline=this._onOnline.bind(this)}_onOffline(){this.emit(!1)}_onOnline(){this.emit(!0)}get(){return navigator.onLine}onSubscribeFirst(){window.addEventListener("offline",this._onOffline),window.addEventListener("online",this._onOnline)}onUnsubscribeLast(){window.removeEventListener("offline",this._onOffline),window.removeEventListener("online",this._onOnline)}}function ae(s,e){return s instanceof Promise?s:new Promise((t,i)=>{s.oncomplete=r=>t(r.target.result),s.onerror=()=>i(new Error("Crypto error on "+e))})}class wm{constructor(e){this._subtleCrypto=e}async verify(e,t,i,r){const n={name:"HMAC",hash:{name:Pt(r)}},o=await ae(this._subtleCrypto.importKey("raw",e,n,!1,["verify"]),"importKey");return await ae(this._subtleCrypto.verify(n,o,t,i),"verify")}async compute(e,t,i){const r={name:"HMAC",hash:{name:Pt(i)}},n=await ae(this._subtleCrypto.importKey("raw",e,r,!1,["sign"]),"importKey"),o=await ae(this._subtleCrypto.sign(r,n,t),"sign");return new Uint8Array(o)}}class bm{constructor(e,t,i){this._subtleCrypto=e,this._crypto=t,this._cryptoExtras=i}async pbkdf2(e,t,i,r,n){if(!this._subtleCrypto.deriveBits)throw new Error("PBKDF2 is not supported");const o=await ae(this._subtleCrypto.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),"importKey"),a=await ae(this._subtleCrypto.deriveBits({name:"PBKDF2",salt:i,iterations:t,hash:Pt(r)},o,n),"deriveBits");return new Uint8Array(a)}async hkdf(e,t,i,r,n){if(!this._subtleCrypto.deriveBits)return this._cryptoExtras.hkdf(this._crypto,e,t,i,r,n);const o=await ae(this._subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),"importKey"),a=await ae(this._subtleCrypto.deriveBits({name:"HKDF",salt:t,info:i,hash:Pt(r)},o,n),"deriveBits");return new Uint8Array(a)}}class Sm{constructor(e,t){this._subtleCrypto=e,this._crypto=t}async decryptCTR({key:e,jwkKey:t,iv:i,data:r,counterLength:n=64}){const o={name:"AES-CTR",counter:i,length:n};let a;try{const c=e||t,l=t?"jwk":"raw";a=await ae(this._subtleCrypto.importKey(l,c,o,!1,["decrypt"]),"importKey")}catch(c){throw new Error(`Could not import key for AES-CTR decryption: ${c.message}`)}try{const c=await ae(this._subtleCrypto.decrypt(o,a,r),"decrypt");return new Uint8Array(c)}catch(c){throw new Error(`Could not decrypt with AES-CTR: ${c.message}`)}}async encryptCTR({key:e,jwkKey:t,iv:i,data:r}){const n={name:"AES-CTR",counter:i,length:64};let o;const a=e||t,c=t?"jwk":"raw";try{o=await ae(this._subtleCrypto.importKey(c,a,n,!1,["encrypt"]),"importKey")}catch(l){throw new Error(`Could not import key for AES-CTR encryption: ${l.message}`)}try{const l=await ae(this._subtleCrypto.encrypt(n,o,r),"encrypt");return new Uint8Array(l)}catch(l){throw new Error(`Could not encrypt with AES-CTR: ${l.message}`)}}async generateKey(e,t=256){const i=await ae(this._subtleCrypto.generateKey({name:"AES-CTR",length:t},!0,["encrypt","decrypt"]));return ae(this._subtleCrypto.exportKey(e,i))}async generateIV(){return Yc(this._crypto)}}function Yc(s){const e=s.getRandomValues(new Uint8Array(8)),t=new Uint8Array(16);for(let i=0;i<e.length;i+=1)t[i]=e[i];return t}function ea(s){if(s.alg!=="A256CTR")throw new Error(`Unknown algorithm: ${s.alg}`);if(!s.key_ops.includes("decrypt"))throw new Error("decrypt missing from key_ops");if(s.kty!=="oct")throw new Error(`Invalid key type, "oct" expected: ${s.kty}`);const t=s.k.replace(/-/g,"+").replace(/_/g,"/");return Nt.decode(t)}function Em(s){const e=Nt.encode(s),t=e.indexOf("=");return t!==-1?e.substr(0,t):e}function Im(s){return Em(s).replace(/\+/g,"-").replace(/\//g,"_")}function Tm(s){return{alg:"A256CTR",ext:!0,k:Im(s),key_ops:["encrypt","decrypt"],kty:"oct"}}class xm{constructor(e,t){this._aesjs=e,this._crypto=t}async decryptCTR({key:e,jwkKey:t,iv:i,data:r,counterLength:n=64}){if(n!==64)throw new Error(`Unsupported counter length: ${n}`);t&&(e=ea(t));const o=this._aesjs;var a=new o.ModeOfOperation.ctr(new Uint8Array(e),new o.Counter(new Uint8Array(i)));return a.decrypt(new Uint8Array(r))}async encryptCTR({key:e,jwkKey:t,iv:i,data:r}){t&&(e=ea(t));const n=this._aesjs;var o=new n.ModeOfOperation.ctr(new Uint8Array(e),new n.Counter(new Uint8Array(i)));return o.encrypt(new Uint8Array(r))}async generateKey(e,t=256){let i=crypto.getRandomValues(new Uint8Array(t/8));return e==="jwk"&&(i=Tm(i)),i}async generateIV(){return Yc(this._crypto)}}function Pt(s){if(s!=="SHA-256"&&s!=="SHA-512")throw new Error(`Invalid hash name: ${s}`);return s}class km{constructor(e){const t=window.crypto||window.msCrypto,i=t.subtle||t.webkitSubtle;this._subtleCrypto=i,!i.deriveBits&&e?.aesjs?this.aes=new xm(e.aesjs,t):this.aes=new Sm(i,t),this.hmac=new wm(i),this.derive=new bm(i,this,e)}async digest(e,t){return await ae(this._subtleCrypto.digest(Pt(e),t))}digestSize(e){switch(Pt(e)){case"SHA-512":return 64;case"SHA-256":return 32;default:throw new Error(`Not implemented for ${Pt(e)}`)}}}async function Rm(){var s;if((s=navigator?.storage)!=null&&s.estimate){const{quota:e,usage:t}=await navigator.storage.estimate();return{quota:e,usage:t}}else return{quota:null,usage:null}}class Am{constructor(e){this.worker=e,this.busy=!1}attach(e){this.worker.addEventListener("message",e),this.worker.addEventListener("error",e)}detach(e){this.worker.removeEventListener("message",e),this.worker.removeEventListener("error",e)}}class Cm{constructor(e,t){this._promise=new Promise((i,r)=>{this._resolve=i,this._reject=r}),this._message=e,this._pool=t,this._worker=null}abort(){this._isNotDisposed&&(this._pool._abortRequest(this),this._dispose())}response(){return this._promise}_dispose(){this._reject=null,this._resolve=null}get _isNotDisposed(){return this._resolve&&this._reject}}class Nm{constructor(e,t){this._workers=[];for(let i=0;i<t;++i){const r=new Am(new Worker(e));r.attach(this),this._workers[i]=r}this._requests=new Map,this._counter=0,this._pendingFlag=!1,this._init=null}init(){const e=new Promise((t,i)=>{this._init={resolve:t,reject:i}});return this.sendAll({type:"ping"}).then(this._init.resolve,this._init.reject).finally(()=>{this._init=null}),e}handleEvent(e){if(e.type==="message"){const t=e.data,i=this._requests.get(t.replyToId);if(i){if(i._worker.busy=!1,i._isNotDisposed){if(t.type==="success")i._resolve(t.payload);else if(t.type==="error"){const r=new Error(t.message);r.stack=t.stack,i._reject(r)}i._dispose()}this._requests.delete(t.replyToId)}this._sendPending()}else e.type==="error"&&(this._init&&this._init.reject(new Error("worker error during init")),console.error("worker error",e))}_getPendingRequest(){for(const e of this._requests.values())if(!e._worker)return e}_getFreeWorker(){for(const e of this._workers)if(!e.busy)return e}_sendPending(){this._pendingFlag=!1;let e;do{e=!1;const t=this._getPendingRequest();if(t){const i=this._getFreeWorker();i&&(this._sendWith(t,i),e=!0)}}while(e)}_sendWith(e,t){e._worker=t,t.busy=!0,t.worker.postMessage(e._message)}_enqueueRequest(e){this._counter+=1,e.id=this._counter;const t=new Cm(e,this);return this._requests.set(e.id,t),t}send(e){const t=this._enqueueRequest(e),i=this._getFreeWorker();return i&&this._sendWith(t,i),t}sendAll(e){const t=this._workers.map(i=>{const r=this._enqueueRequest(Object.assign({},e));return this._sendWith(r,i),r.response()});return Promise.all(t)}dispose(){for(const e of this._workers)e.detach(this),e.worker.terminate()}_trySendPendingInNextTick(){this._pendingFlag||(this._pendingFlag=!0,Promise.resolve().then(()=>{this._sendPending()}))}_abortRequest(e){e._reject(new Me),e._worker&&(e._worker.busy=!1),this._requests.delete(e._message.id),this._trySendPendingInNextTick()}}const Mm={"image/jpeg":!0,"image/gif":!0,"image/png":!0,"video/mp4":!0,"video/webm":!0,"video/ogg":!0,"video/quicktime":!0,"video/VP8":!0,"audio/mp4":!0,"audio/webm":!0,"audio/aac":!0,"audio/mpeg":!0,"audio/ogg":!0,"audio/wave":!0,"audio/wav":!0,"audio/x-wav":!0,"audio/x-pn-wav":!0,"audio/flac":!0,"audio/x-flac":!0},ta="application/octet-stream";class Bt{constructor(e,t=null){this._blob=e,this._buffer=t,this._url=null}static fromBuffer(e,t){return t=t?t.split(";")[0].trim():"",Mm[t]||(t=ta),new Bt(new Blob([e],{type:t}),e)}static fromBlob(e){return new Bt(e)}get nativeBlob(){return this._blob}async readAsBuffer(){if(this._buffer)return this._buffer;{const e=new FileReader,t=new Promise((i,r)=>{e.addEventListener("load",n=>i(n.target.result)),e.addEventListener("error",n=>r(n.target.error))});return e.readAsArrayBuffer(this._blob),t}}get url(){return this._url||(this._url=URL.createObjectURL(this._blob)),this._url}get size(){return this._blob.size}get mimeType(){return this._blob.type||ta}dispose(){this._url&&(URL.revokeObjectURL(this._url),this._url=null)}}class Fi{static async fromBlob(e){const t=await ia(e),{width:i,height:r}=t;return new Fi(e,i,r,t)}constructor(e,t,i,r){this.blob=e,this.width=t,this.height=i,this._domElement=r}get maxDimension(){return Math.max(this.width,this.height)}async _getDomElement(){return this._domElement||(this._domElement=await ia(this.blob)),this._domElement}async scale(e){const t=this.width/this.height,i=Math.min(1,e/(t>=1?this.width:this.height)),r=Math.round(this.width*i),n=Math.round(this.height*i),o=document.createElement("canvas");o.width=r,o.height=n;const a=o.getContext("2d"),c=await this._getDomElement();a.drawImage(c,0,0,r,n);let l=this.blob.mimeType==="image/jpeg"?"image/jpeg":"image/png",d;if(o.toBlob)d=await new Promise(h=>o.toBlob(h,l));else if(o.msToBlob)l="image/png",d=o.msToBlob();else throw new Error("canvas can't be turned into blob");const u=Bt.fromBlob(d);return new Fi(u,r,n,null)}dispose(){this.blob.dispose()}}class Sn extends Fi{get duration(){if(typeof this._domElement.duration=="number")return Math.round(this._domElement.duration*1e3)}static async fromBlob(e){const t=await Pm(e),{videoWidth:i,videoHeight:r}=t;return new Sn(e,i,r,t)}}function Dm(){const s=document.createElement("canvas");s.width=1,s.height=1;const e=s.getContext("2d"),t=[Math.round(Math.random()*255),Math.round(Math.random()*255),Math.round(Math.random()*255)];e.fillStyle=`rgb(${t[0]}, ${t[1]}, ${t[2]})`,e.fillRect(0,0,1,1);const i=e.getImageData(0,0,1,1).data;return i[0]===t[0]&&i[1]===t[1]&&i[2]===t[2]}async function ia(s){const e=document.createElement("img"),t=Vr(e,"load");return e.src=s.url,await t,e}async function Pm(s){const e=document.createElement("video");e.muted=!0;const t=Vr(e,"loadedmetadata");e.src=s.url,e.load(),await t;const i=Vr(e,"seeked");return await new Promise(r=>setTimeout(r,200)),e.currentTime=.1,await i,e}async function Om(s,e,t,i,r){let n=s.querySelector("iframe.downloadSandbox");if(!n){n=document.createElement("iframe"),n.setAttribute("sandbox","allow-scripts allow-downloads allow-downloads-without-user-activation"),n.setAttribute("src",e),n.className="hidden downloadSandbox",s.appendChild(n);let o;await new Promise((a,c)=>{o=()=>{n.removeEventListener("load",a),n.removeEventListener("error",c)},n.addEventListener("load",a),n.addEventListener("error",c)}),o()}if(r){const o=await t.readAsBuffer();n.contentWindow.postMessage({type:"downloadBuffer",buffer:o,mimeType:t.mimeType,filename:i},"*")}else n.contentWindow.postMessage({type:"downloadBlob",blob:t.nativeBlob,filename:i},"*")}function Cs(s){typeof s=="function"?s():s.dispose()}function Um(s){return s&&(typeof s=="function"||typeof s.dispose=="function")}class En{constructor(){this._disposables=[]}track(e){if(!Um(e))throw new Error("Not a disposable");return this.isDisposed?(console.warn("Disposables already disposed, disposing new value"),Cs(e),e):(this._disposables.push(e),e)}untrack(e){if(this.isDisposed){console.warn("Disposables already disposed, cannot untrack");return}const t=this._disposables.indexOf(e);t>=0&&this._disposables.splice(t,1)}dispose(){if(this._disposables){for(const e of this._disposables)Cs(e);this._disposables=void 0}}get isDisposed(){return this._disposables===void 0}disposeTracked(e){if(e==null||this.isDisposed)return;const t=this._disposables.indexOf(e);if(t!==-1){const[i]=this._disposables.splice(t,1);Cs(i)}else console.warn("disposable not found, did it leak?",e)}}class Bm{constructor(e){this._bodyNode=e}get rootNodes(){return Array.from(this._bodyNode.childNodes)}getChildNodes(e){return Array.from(e.childNodes)}getAttributeNames(e){return Array.from(e.getAttributeNames())}getAttributeValue(e,t){return e.getAttribute(t)}isTextNode(e){return e.nodeType===Node.TEXT_NODE}getNodeText(e){return e.textContent}isElementNode(e){return e.nodeType===Node.ELEMENT_NODE}getNodeElementName(e){return e.tagName}}const Lm={ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx|mxc):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i,FORBID_TAGS:["mx-reply"],KEEP_CONTENT:!1};function Fm(s){const e=du.sanitize(s,Lm),t=new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${e}</body></html>`,"text/html").body;return new Bm(t)}var rt=(s=>(s[s.Dark=0]="Dark",s[s.Light=1]="Light",s))(rt||{});function Vm(s,e,t){let i=s.replaceAll("#ff00ff",e);if(i=i.replaceAll("#00ffff",t),s===i)throw new Error("svg-colorizer made no color replacements! The input svg should only contain colors #ff00ff (primary, case-sensitive) and #00ffff (secondary, case-sensitive).");return i}class Km{constructor(e,t,i,r){this._platform=e,this._iconVariables=t,this._resolvedVariables=i,this._manifestLocation=r}async toVariables(){const{parsedStructure:e,promises:t}=await this._fetchAndParseIcons();return await Promise.all(t),this._produceColoredIconVariables(e)}async _fetchAndParseIcons(){const e=[],t={};for(const[i,r]of Object.entries(this._iconVariables)){const n=new URL(`https://${r}`),o=n.hostname,a=new URL(o,new URL(this._manifestLocation,window.location.origin)),c=this._platform.request(a,{method:"GET",format:"text",cache:!0}).response();e.push(c);const l=n.searchParams;t[i]={svg:c,primary:l.get("primary"),secondary:l.get("secondary")}}return{parsedStructure:t,promises:e}}async _produceColoredIconVariables(e){let t={};for(const[i,{svg:r,primary:n,secondary:o}]of Object.entries(e)){const{body:a}=await r;if(!n)throw new Error(`Primary color variable ${n} not in list of variables!`);const c=this._resolvedVariables[n],l=this._resolvedVariables[o],d=Vm(a,c,l),u=`url('data:image/svg+xml;utf8,${encodeURIComponent(d)}')`;t[i]=u}return t}}const ra=(Bo=Yr.exports.offColor)!=null?Bo:cc.offColor;function sa(s,e,t,i){const r=parseInt(t);switch(i&&(e==="darker"?e="lighter":e==="lighter"&&(e="darker")),e){case"darker":return ra(s).darken(r/100).hex();case"lighter":return ra(s).lighten(r/100).hex()}}class $m{constructor(e,t,i){this._aliases={},this._derivedAliases=[],this._baseVariables=e,this._variablesToDerive=t,this._isDark=i}toVariables(){var e;const t={};this._detectAliases();for(const i of this._variablesToDerive){const r=this._derive(i);r&&(t[i]=r)}for(const[i,r]of Object.entries(this._aliases))t[i]=(e=this._baseVariables[r])!=null?e:t[r];for(const i of this._derivedAliases){const r=this._deriveAlias(i,t);r&&(t[i]=r)}return t}_detectAliases(){const e=[];for(const t of this._variablesToDerive){const[i,r]=t.split("=");r?this._aliases[i]=r:e.push(t)}this._variablesToDerive=e}_derive(e){const t=/(.+)--(.+)-(.+)/,i=e.match(t);if(i){const[,r,n,o]=i,a=this._baseVariables[r];if(!a)if(this._aliases[r]){this._derivedAliases.push(e);return}else throw new Error(`Cannot find value for base variable "${r}"!`);return sa(a,n,o,this._isDark)}}_deriveAlias(e,t){const i=/(.+)--(.+)-(.+)/,r=e.match(i);if(r){const[,n,o,a]=r,c=t[n];if(!c)throw new Error(`Cannot find value for alias "${n}" when trying to derive ${e}!`);return sa(c,o,a,this._isDark)}}}(Lo=Yr.exports.offColor)!=null||cc.offColor;class jm{constructor(e,t){this._themeMapping={},this._preferredColorScheme=t,this._platform=e}async parse(e,t,i,r){await r.wrap("RuntimeThemeParser.parse",async()=>{var n;const{cssLocation:o,derivedVariables:a,icons:c}=this._getSourceData(t,i,r),l=e.name;if(!l)throw new Error("Theme name not found in manifest!");let d={},u={};for(const[h,m]of Object.entries((n=e.values)==null?void 0:n.variants))try{const _=`${e.id}-${h}`,{name:f,default:E,dark:I,variables:T}=m,k=new $m(T,a,I).toVariables();Object.assign(T,k);const w=await new Km(this._platform,c,T,i).toVariables();Object.assign(T,k,w);const x=`${l} ${f}`;if(E){Object.assign(I?d:u,{variantName:f,id:_,cssLocation:o,variables:T});continue}this._themeMapping[x]={cssLocation:o,id:_,variables:T}}catch(_){console.error(_);continue}if(d.id&&u.id){const h=this._preferredColorScheme===rt.Dark?d:u;this._themeMapping[l]={dark:d,light:u,default:h}}else{const h=d.id?d:u;this._themeMapping[`${l} ${h.variantName}`]={id:h.id,cssLocation:h.cssLocation}}})}_getSourceData(e,t,i){return i.wrap("getSourceData",()=>{var r,n,o;const a=(r=e.source)==null?void 0:r["runtime-asset"];if(!a)throw new Error(`Run-time asset not found in source section for theme at ${t}`);const c=new URL(a,new URL(t,window.location.origin)).href,l=(n=e.source)==null?void 0:n["derived-variables"];if(!l)throw new Error(`Derived variables not found in source section for theme at ${t}`);const d=(o=e.source)==null?void 0:o.icon;if(!d)throw new Error(`Icon mapping not found in source section for theme at ${t}`);return{cssLocation:c,derivedVariables:l,icons:d}})}get themeMapping(){return this._themeMapping}}class Gm{constructor(e){this._themeMapping={},this._preferredColorScheme=e}parse(e,t,i){i.wrap("BuiltThemeParser.parse",()=>{var r,n,o;const a=(r=e.source)==null?void 0:r["built-assets"],c=e.name;if(!c)throw new Error(`Theme name not found in manifest at ${t}`);let l={},d={};for(let[u,h]of Object.entries(a)){try{h=new URL(h,new URL(t,window.location.origin)).href}catch{continue}const m=(n=u.match(/.+-(.+)/))==null?void 0:n[1],_=(o=e.values)==null?void 0:o.variants[m];if(!_)throw new Error(`Variant ${m} is missing in manifest at ${t}`);const{name:f,default:E,dark:I}=_,T=`${c} ${f}`;if(E){const k=I?l:d;k.variantName=f,k.id=u,k.cssLocation=h;continue}this._themeMapping[T]={cssLocation:h,id:u}}if(l.id&&d.id){const u=this._preferredColorScheme===rt.Dark?l:d;this._themeMapping[c]={dark:l,light:d,default:u}}else{const u=l.id?l:d;this._themeMapping[`${c} ${u.variantName}`]={id:u.id,cssLocation:u.cssLocation}}})}get themeMapping(){return this._themeMapping}}class qm{constructor(e){this._platform=e}async init(e,t){await this._platform.logger.wrapOrRun(t,"ThemeLoader.init",async i=>{let r=!0;const n=[],o=[],a=await Promise.all(e.map(u=>this._platform.request(u,{method:"GET",format:"json",cache:!0}).response())),c=new jm(this._platform,this.preferredColorScheme),l=new Gm(this.preferredColorScheme),d=[];for(let u=0;u<a.length;++u){const h=a[u],{status:m,body:_}=h;if(!(m>=200&&m<=299)){console.error(`Failed to load manifest at ${e[u]}, status: ${m}`),i.log({l:"Manifest fetch failed",location:e[u],status:m},we.Error),n.push(e[u]);continue}r=!1;try{if(_.extends){const f=a.findIndex(k=>"value"in k&&k.value.body.id===_.extends);if(f===-1)throw new Error(`Base manifest for derived theme at ${e[u]} not found!`);const{body:E}=a[f].value,I=e[f],T=c.parse(_,E,I,i);d.push(T)}else l.parse(_,e[u],i)}catch(f){console.error(f),o.push(f.message)}}if(await Promise.all(d),this._themeMapping=Oi(Oi({},l.themeMapping),c.themeMapping),r)throw new Error(`All configured theme manifests failed to load, the following were tried: ${n.join(", ")}`);if(Object.keys(this._themeMapping).length===0&&o.length)throw new Error(`Failed to parse theme manifests, the following errors were encountered: ${o.join(", ")}`);this._addDefaultThemeToMapping(i),i.log({l:"Preferred colorscheme",scheme:this.preferredColorScheme===rt.Dark?"dark":"light"}),i.log({l:"Result",themeMapping:this._themeMapping})})}async setTheme(e,t,i){await this._platform.logger.wrapOrRun(i,{l:"change theme",name:e,variant:t},async r=>{let n,o,a=this._themeMapping[e];if("id"in a)n=a.cssLocation,o=a.variables;else{if(!t)throw new Error("themeVariant is undefined!");n=a[t].cssLocation,o=a[t].variables}await this._platform.replaceStylesheet(n,r),o?(i?.log({l:"Derived Theme",variables:o}),this._injectCSSVariables(o)):this._removePreviousCSSVariables(),this._platform.settingsStorage.setString("theme-name",e),t?this._platform.settingsStorage.setString("theme-variant",t):this._platform.settingsStorage.remove("theme-variant")})}_injectCSSVariables(e){const t=document.documentElement;for(const[i,r]of Object.entries(e))t.style.setProperty(`--${i}`,r);this._injectedVariables=e}_removePreviousCSSVariables(){if(!this._injectedVariables)return;const e=document.documentElement;for(const t of Object.keys(this._injectedVariables))e.style.removeProperty(`--${t}`);this._injectedVariables=void 0}get themeMapping(){return this._themeMapping}async getActiveTheme(){let e=await this._platform.settingsStorage.getString("theme-name"),t=await this._platform.settingsStorage.getString("theme-variant");return(!e||!this._themeMapping[e])&&(e="Default"in this._themeMapping?"Default":Object.keys(this._themeMapping)[0],this._themeMapping[e][t]||(t="default"in this._themeMapping[e]?"default":void 0)),{themeName:e,themeVariant:t}}getDefaultTheme(){var e,t;switch(this.preferredColorScheme){case rt.Dark:return(e=this._platform.config.defaultTheme)==null?void 0:e.dark;case rt.Light:return(t=this._platform.config.defaultTheme)==null?void 0:t.light}}_findThemeDetailsFromId(e){var t,i;for(const[r,n]of Object.entries(this._themeMapping)){if("id"in n&&n.id===e)return{themeName:r,themeData:n};if("light"in n&&((t=n.light)==null?void 0:t.id)===e)return{themeName:r,themeData:n.light};if("dark"in n&&((i=n.dark)==null?void 0:i.id)===e)return{themeName:r,themeData:n.dark}}}_addDefaultThemeToMapping(e){e.wrap("addDefaultThemeToMapping",t=>{const i=this.getDefaultTheme();if(i){const r=this._findThemeDetailsFromId(i);if(r){this._themeMapping.Default={id:"default",cssLocation:r.themeData.cssLocation};const n=r.themeData.variables;n&&(this._themeMapping.Default.variables=n)}}t.log({l:"Default Theme",theme:i})})}get preferredColorScheme(){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return rt.Dark;if(window.matchMedia("(prefers-color-scheme: light)").matches)return rt.Light}}function na(s){return new Promise(function(e,t){var i=document.createElement("script");i.setAttribute("src",s),i.onload=e,i.onerror=t,document.body.appendChild(i)})}async function zm(s){return window.msCrypto&&!window.crypto&&(window.crypto=window.msCrypto),s?(window.WebAssembly?(await na(s.wasmBundle),await window.Olm.init({locateFile:()=>s.wasm})):(await na(s.legacyBundle),await window.Olm.init()),window.Olm):null}function Hm(s){return s.startsWith("/")?s:new URL(s,document.location.href).pathname}async function Wm(s){const e=new Nm(s.worker,4);return await e.init(),await e.sendAll({type:"load_olm",path:Hm(s.olm.legacyBundle)}),new Vh(e)}function Ym(s){if(!window.visualViewport)return;const e=()=>{const t=s.querySelector(".SessionView");if(!t)return;const i=s.querySelector(".bottom-aligned-scroll");let r,n,o;i&&(r=i.scrollTop,n=i.offsetHeight);const a=t.offsetTop+t.offsetHeight-window.visualViewport.height;s.style.setProperty("--ios-viewport-height",window.visualViewport.height.toString()+"px"),s.style.setProperty("--ios-viewport-top",a.toString()+"px"),i&&(o=i.offsetHeight,i.scrollTop=r+n-o)};return window.visualViewport.addEventListener("resize",e),()=>{window.visualViewport.removeEventListener("resize",e)}}class Jm{constructor({container:e,assetPaths:t,config:i,configURL:r,options:n=null,cryptoExtras:o=null}){this._container=e,this._assetPaths=t,this._config=i,this._configURL=r,this.settingsStorage=new Rh("hydrogen_setting_v1_"),this.clock=new _m,this.encoding=new Fh,this.random=Math.random,this._createLogger(n?.development),this.history=new ym,this.onlineStatus=new vm,this._serviceWorkerHandler=null,t.serviceWorker&&"serviceWorker"in navigator&&(this._serviceWorkerHandler=new fm,this._serviceWorkerHandler.registerAndStart(t.serviceWorker)),this.notificationService=void 0,this._assetPaths.olm&&(this.crypto=new km(o)),this.storageFactory=new Th(this._serviceWorkerHandler),this.sessionInfoStorage=new kh("hydrogen_sessions_v1"),this.estimateStorageUsage=Rm,typeof fetch=="function"?this.request=Iu(this.clock.createTimeout,this._serviceWorkerHandler):this.request=_c;const a=!!window.MSInputMethodContext&&!!document.documentMode;this.isIE11=a;const c=/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1&&!window.MSStream;this.isIOS=c,this._disposables=new En,this._olmPromise=void 0,this._workerPromise=void 0,this._themeLoader=new qm(this)}async init(){try{await this.logger.run("Platform init",async e=>{var t;if(!this._config){if(!this._configURL)throw new Error("Neither config nor configURL was provided!");const{status:i,body:r}=await this.request(this._configURL,{method:"GET",format:"json",cache:!0}).response();if(i===404)throw new Error(`Could not find ${this._configURL}. Did you copy over config.sample.json?`);if(i>=400)throw new Error(`Got status ${i} while trying to fetch ${this._configURL}`);this._config=r}if(this.notificationService=new gm(this._serviceWorkerHandler,this._config.push),this._themeLoader){const i=this.config.themeManifests;await((t=this._themeLoader)==null?void 0:t.init(i,e));const{themeName:r,themeVariant:n}=await this._themeLoader.getActiveTheme();e.log({l:"Active theme",name:r,variant:n}),await this._themeLoader.setTheme(r,n,e)}})}catch(e){throw this._container.innerText=e.message,e}}_createLogger(e){const t=i=>{var r;return(r=i.e)!=null&&r.stack&&(i.e.stack=i.e.stack.replace(/\/\?loginToken=(.+)/,"?loginToken=<snip>")),i};e?this.logger=new jh({platform:this}):this.logger=new Kh({name:"hydrogen_logs",platform:this,serializedTransformer:t})}get updateService(){return this._serviceWorkerHandler}loadOlm(){return this._olmPromise||(this._olmPromise=zm(this._assetPaths.olm)),this._olmPromise}get config(){return this._config}async loadOlmWorker(){if(!window.WebAssembly)return this._workerPromise||(this._workerPromise=Wm(this._assetPaths)),this._workerPromise}createAndMountRootView(e){if(this.isIE11&&(this._container.className+=" legacy"),this.isIOS){this._container.className+=" ios";const i=Ym(this._container);i&&this._disposables.track(i)}this._container.addEventListener("error",Xo,!0),this._disposables.track(()=>this._container.removeEventListener("error",Xo,!0)),window.__hydrogenViewModel=e;const t=new um(e);this._container.appendChild(t.mount())}setNavigation(e){var t;(t=this._serviceWorkerHandler)==null||t.setNavigation(e)}createBlob(e,t){return Bt.fromBuffer(e,t)}saveFileAs(e,t){navigator.msSaveBlob?navigator.msSaveBlob(e.nativeBlob,t):Om(this._container,this._assetPaths.downloadSandbox,e,t,this.isIOS)}openFile(e=null){const t=document.createElement("input");t.setAttribute("type","file"),t.className="hidden",e&&t.setAttribute("accept",e);const i=new Promise(r=>{const n=()=>{t.removeEventListener("change",n,!0);const o=t.files[0];this._container.removeChild(t),o?r({name:o.name,blob:Bt.fromBlob(o)}):r()};t.addEventListener("change",n,!0)});return this._container.appendChild(t),t.click(),i}openUrl(e){location.href=e}parseHTML(e){return Fm(e)}async loadImage(e){return Fi.fromBlob(e)}async loadVideo(e){return Sn.fromBlob(e)}hasReadPixelPermission(){return Dm()}get devicePixelRatio(){return window.devicePixelRatio||1}get version(){return"0.3.2"}get themeLoader(){return this._themeLoader}async replaceStylesheet(e,t){const i=await this.logger.wrapOrRun(t,{l:"replaceStylesheet",location:e},async r=>{let n;const o=document.querySelector("head");document.querySelectorAll(".theme").forEach(l=>l.remove());const a=document.createElement("link");a.href=e,a.rel="stylesheet",a.type="text/css",a.className="theme";const c=new Promise(l=>{a.onerror=()=>{n=new Error(`Failed to load stylesheet from ${e}`),r.catch(n),l()},a.onload=()=>{l()}});return o.appendChild(a),await c,n});if(i)throw i}get description(){var e;return(e=navigator.userAgent)!=null?e:"<unknown>"}dispose(){this._disposables.dispose()}}function oa(s){try{return new URL(s).origin}catch{return new URL(`https://${s}`).origin}}async function Xm(s,e){const t={format:"json",timeout:3e4,method:"GET"};try{const i=`${s}/.well-known/matrix/client`;return await e(i,t).response()}catch(i){if(i.name==="ConnectionError")return null;throw i}}async function Qm(s,e){var t;s=oa(s);const i=await Xm(s,e);if(i&&i.status===200){const{body:r}=i,n=(t=r["m.homeserver"])==null?void 0:t.base_url;typeof n=="string"&&(s=oa(n))}return s}class Jc{constructor(e){this._abortable=void 0;const t=r=>(this._abortable=r,r);this._progress=new qe(void 0);const i=r=>{this._progress.set(r)};this.result=e(t,i)}get progress(){return this._progress}abort(){var e;(e=this._abortable)==null||e.abort(),this._abortable=void 0}}function Xc(s){return Object.entries(s||{}).filter(([,e])=>e!==void 0).map(([e,t])=>(typeof t=="object"&&(t=JSON.stringify(t)),`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join("&")}function Zm(s){if(s instanceof Bt){const e=s;return{mimeType:e.mimeType,body:e}}else{if(s instanceof Map)return{mimeType:"multipart/form-data",body:s};if(typeof s=="object"){const e=JSON.stringify(s);return{mimeType:"application/json",body:e}}else throw new Error("Unknown body type: "+s)}}class e_{constructor(e,t,i,r){let n;if(r?.log){const o=r?.log;n=o.child({t:"network",url:t,method:e},o.level.Info)}this._log=n,this._sourceRequest=i,this._promise=i.response().then(o=>{var a,c;if(n?.set("status",o.status),o.status>=200&&o.status<300||((a=r?.allowedStatusCodes)==null?void 0:a.includes(o.status)))return n?.finish(),o.body;if(o.status>=500){const l=new Se("Internal Server Error");throw n?.catch(l),l}else if(o.status>=400&&!((c=o.body)!=null&&c.errcode)){const l=new Se(`HTTP error status ${o.status} without errcode in body, assume this is a load balancer complaining the server is offline.`);throw n?.catch(l),l}else{const l=new hc(e,t,o.body,o.status);throw n?.set("errcode",l.errcode),n?.catch(l),l}},o=>{if(o.name==="AbortError"&&this._sourceRequest){const a=new Se("Service worker aborted, either updating or hit #187.");throw n?.catch(a),a}else throw o.name==="ConnectionError"&&n?.set("timeout",o.isTimeout),n?.catch(o),o})}abort(){var e;this._sourceRequest&&((e=this._log)==null||e.set("aborted",!0),this._sourceRequest.abort(),this._sourceRequest=void 0)}response(){return this._promise}async responseCode(){return(await this._sourceRequest.response()).status}}const vr="/_matrix/client/r0",t_="/_matrix/client/v3",Ns="/_matrix/client/unstable/org.matrix.msc2697.v2";class Tt{constructor({homeserver:e,accessToken:t,request:i,reconnector:r}){this._homeserver=e,this._accessToken=t,this._requestFn=i,this._reconnector=r}_url(e,t=vr){return this._homeserver+t+e}_baseRequest(e,t,i,r,n,o){const a=Xc(i);t=`${t}?${a}`;let c;const l=new Map;if(o&&l.set("Authorization",`Bearer ${o}`),l.set("Accept","application/json"),r){const h=Zm(r);l.set("Content-Type",h.mimeType),c=h.body}const d=this._requestFn(t,{method:e,headers:l,body:c,timeout:n?.timeout,uploadProgress:n?.uploadProgress,format:"json",cache:e!=="GET"}),u=new e_(e,t,d,n);return this._reconnector&&u.response().catch(h=>{h.name==="ConnectionError"&&this._reconnector.onRequestFailed(this)}),u}_unauthedRequest(e,t,i,r,n){return this._baseRequest(e,t,i,r,n)}_authedRequest(e,t,i,r,n){return this._baseRequest(e,t,i,r,n,this._accessToken)}_post(e,t,i,r){return this._authedRequest("POST",this._url(e,r?.prefix||vr),t,i,r)}_put(e,t,i,r){return this._authedRequest("PUT",this._url(e,r?.prefix||vr),t,i,r)}_get(e,t,i,r){return this._authedRequest("GET",this._url(e,r?.prefix||vr),t,i,r)}sync(e,t,i,r){return this._get("/sync",{since:e,timeout:i,filter:t},void 0,r)}context(e,t,i,r){return this._get(`/rooms/${encodeURIComponent(e)}/context/${encodeURIComponent(t)}`,{filter:r,limit:i})}messages(e,t,i){return this._get(`/rooms/${encodeURIComponent(e)}/messages`,t,void 0,i)}members(e,t,i){return this._get(`/rooms/${encodeURIComponent(e)}/members`,t,void 0,i)}send(e,t,i,r,n){return this._put(`/rooms/${encodeURIComponent(e)}/send/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{},r,n)}redact(e,t,i,r,n){return this._put(`/rooms/${encodeURIComponent(e)}/redact/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{},r,n)}receipt(e,t,i,r){return this._post(`/rooms/${encodeURIComponent(e)}/receipt/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{},{},r)}state(e,t,i,r){return this._get(`/rooms/${encodeURIComponent(e)}/state/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{},void 0,r)}getLoginFlows(){return this._unauthedRequest("GET",this._url("/login"))}register(e,t,i,r,n=!1,o={}){o.allowedStatusCodes=[401];const a={auth:r,password:t,initial_device_displayname:i,inhibit_login:n};return e&&(a.username=e),this._unauthedRequest("POST",this._url("/register",t_),void 0,a,o)}passwordLogin(e,t,i,r){return this._unauthedRequest("POST",this._url("/login"),void 0,{type:"m.login.password",identifier:{type:"m.id.user",user:e},password:t,initial_device_display_name:i},r)}tokenLogin(e,t,i,r){return this._unauthedRequest("POST",this._url("/login"),void 0,{type:"m.login.token",identifier:{type:"m.id.user"},token:e,txn_id:t,initial_device_display_name:i},r)}createFilter(e,t,i){return this._post(`/user/${encodeURIComponent(e)}/filter`,{},t,i)}versions(e){return this._unauthedRequest("GET",`${this._homeserver}/_matrix/client/versions`,void 0,void 0,e)}uploadKeys(e,t,i){let r="/keys/upload";return e&&(r=r+`/${encodeURIComponent(e)}`),this._post(r,{},t,i)}queryKeys(e,t){return this._post("/keys/query",{},e,t)}claimKeys(e,t){return this._post("/keys/claim",{},e,t)}sendToDevice(e,t,i,r){return this._put(`/sendToDevice/${encodeURIComponent(e)}/${encodeURIComponent(i)}`,{},t,r)}roomKeysVersion(e,t){let i="";return e&&(i=`/${encodeURIComponent(e)}`),this._get(`/room_keys/version${i}`,void 0,void 0,t)}roomKeyForRoomAndSession(e,t,i,r){return this._get(`/room_keys/keys/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{version:e},void 0,r)}uploadRoomKeysToBackup(e,t,i){return this._put("/room_keys/keys",{version:e},t,i)}uploadAttachment(e,t,i){return this._authedRequest("POST",`${this._homeserver}/_matrix/media/r0/upload`,{filename:t},e,i)}setPusher(e,t){return this._post("/pushers/set",{},e,t)}getPushers(e){return this._get("/pushers",void 0,void 0,e)}join(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/join`,{},{},t)}joinIdOrAlias(e,t){return this._post(`/join/${encodeURIComponent(e)}`,{},{},t)}leave(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/leave`,{},{},t)}forget(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/forget`,{},{},t)}logout(e){return this._post("/logout",{},{},e)}getDehydratedDevice(e={}){return e.prefix=Ns,this._get("/dehydrated_device",void 0,void 0,e)}createDehydratedDevice(e,t={}){return t.prefix=Ns,this._put("/dehydrated_device",{},e,t)}claimDehydratedDevice(e,t={}){return t.prefix=Ns,this._post("/dehydrated_device/claim",{},{device_id:e},t)}profile(e,t){return this._get(`/profile/${encodeURIComponent(e)}`)}createRoom(e,t){return this._post("/createRoom",{},e,t)}setAccountData(e,t,i,r){return this._put(`/user/${encodeURIComponent(e)}/account_data/${encodeURIComponent(t)}`,{},i,r)}}class Qc{constructor(e){this._start=2e3,this._current=2e3;const t=2e3;this._start=t,this._current=t,this._createTimeout=e,this._max=60*5*1e3}async waitForRetry(){this._timeout=this._createTimeout(this._current);try{await this._timeout.elapsed();const e=2*this._current;this._current=Math.min(this._max,e)}catch(e){if(!(e instanceof Me))throw e}finally{this._timeout=void 0}}abort(){this._timeout&&this._timeout.abort()}reset(){this._current=this._start,this.abort()}get nextValue(){return this._current}}var In=(s=>(s[s.Waiting=0]="Waiting",s[s.Reconnecting=1]="Reconnecting",s[s.Online=2]="Online",s))(In||{});class i_{constructor({retryDelay:e,createMeasure:t,onlineStatus:i}){this._onlineStatus=i,this._retryDelay=e,this._createTimeMeasure=t,this._state=new qe(2),this._isReconnecting=!1}get lastVersionsResponse(){return this._versionsResponse}get connectionStatus(){return this._state}get retryIn(){return this._state.get()===0?this._retryDelay.nextValue-this._stateSince.measure():0}async onRequestFailed(e){if(!this._isReconnecting){this._isReconnecting=!0;const t=this._onlineStatus&&this._onlineStatus.subscribe(i=>{i&&this.tryNow()});try{await this._reconnectLoop(e)}catch(i){console.error(i)}finally{t&&t(),this._isReconnecting=!1}}}tryNow(){this._retryDelay&&this._retryDelay.abort()}_setState(e){e!==this._state.get()&&(e===0?this._stateSince=this._createTimeMeasure():this._stateSince=null,this._state.set(e))}async _reconnectLoop(e){for(this._versionsResponse=void 0,this._retryDelay.reset();!this._versionsResponse;)try{this._setState(1);const t=e.versions({timeout:3e4});this._versionsResponse=await t.response(),this._setState(2)}catch(t){if(t.name==="ConnectionError")this._setState(0),await this._retryDelay.waitForRetry();else throw t}}}async function r_(s,e,t){if(t===void 0||t.key===void 0||t.iv===void 0||t.hashes===void 0||t.hashes.sha256===void 0)throw new Error("Invalid info. Missing info.key, info.iv or info.hashes.sha256 key");const{crypto:i}=s,{base64:r}=s.encoding;var n=r.decode(t.iv),o=r.encode(r.decode(t.hashes.sha256));const a=await i.digest("SHA-256",e);if(r.encode(new Uint8Array(a))!=o)throw new Error("Mismatched SHA-256 digest");var c;return t.v=="v1"||t.v=="v2"?c=64:c=128,await i.aes.decryptCTR({jwkKey:t.key,iv:n,data:e,counterLength:c})}async function s_(s,e){const{crypto:t}=s,{base64:i}=s.encoding,r=await t.aes.generateIV(),n=await t.aes.generateKey("jwk",256),o=await e.readAsBuffer(),a=await t.aes.encryptCTR({jwkKey:n,iv:r,data:o}),c=await t.digest("SHA-256",a);return{blob:s.createBlob(a,"application/octet-stream"),info:{v:"v2",key:n,iv:i.encodeUnpadded(r),hashes:{sha256:i.encodeUnpadded(c)}}}}class n_{constructor({homeserver:e,platform:t}){this._homeserver=e,this._platform=t}mxcUrlThumbnail(e,t,i,r){const n=this._parseMxcUrl(e);if(n){const[o,a]=n;return`${this._homeserver}/_matrix/media/r0/thumbnail/${encodeURIComponent(o)}/${encodeURIComponent(a)}`+"?"+Xc({width:Math.round(t),height:Math.round(i),method:r})}return null}mxcUrl(e){const t=this._parseMxcUrl(e);if(t){const[i,r]=t;return`${this._homeserver}/_matrix/media/r0/download/${encodeURIComponent(i)}/${encodeURIComponent(r)}`}else return null}_parseMxcUrl(e){const t="mxc://";return e.startsWith(t)?e.substr(t.length).split("/",2):null}async downloadEncryptedFile(e,t=!1){const i=this.mxcUrl(e.url),{body:r}=await this._platform.request(i,{method:"GET",format:"buffer",cache:t}).response(),n=await r_(this._platform,r,e);return this._platform.createBlob(n,e.mimetype)}async downloadPlaintextFile(e,t,i=!1){const r=this.mxcUrl(e),{body:n}=await this._platform.request(r,{method:"GET",format:"buffer",cache:i}).response();return this._platform.createBlob(n,t)}async downloadAttachment(e,t=!1){var i;return e.file?this.downloadEncryptedFile(e.file,t):this.downloadPlaintextFile(e.url,(i=e.info)==null?void 0:i.mimetype,t)}}class o_{constructor(e,t){this.methodName=e,this.args=t,this._responsePromise=new Promise((i,r)=>{this.responseResolve=i,this.responseReject=r})}abort(){var e;this._requestResult?this._requestResult.abort():(this.responseReject(new Me),(e=this.responseCodeReject)==null||e.call(this,new Me))}response(){return this._responsePromise}responseCode(){return this.requestResult?this.requestResult.responseCode():(this._responseCodePromise||(this._responseCodePromise=new Promise((e,t)=>{this.responseCodeResolve=e,this.responseCodeReject=t})),this._responseCodePromise)}async setRequestResult(e){var t,i,r;this._requestResult=e;const n=await((t=this._requestResult)==null?void 0:t.response());this.responseResolve(n);const o=await((i=this._requestResult)==null?void 0:i.responseCode());(r=this.responseCodeResolve)==null||r.call(this,o)}get requestResult(){return this._requestResult}}class Zc{constructor(e){this._scheduler=e}}for(const s of Object.getOwnPropertyNames(Tt.prototype))s!=="constructor"&&!s.startsWith("_")&&(Zc.prototype[s]=function(...e){return this._scheduler._hsApiRequest(s,e)});class a_{constructor({hsApi:e,clock:t}){this._requests=new Set,this._stopped=!1,this._wrapper=new Zc(this),this._hsApi=e,this._clock=t}get hsApi(){return this._wrapper}stop(){this._stopped=!0;for(const e of this._requests)e.abort();this._requests.clear()}start(){this._stopped=!1}_hsApiRequest(e,t){const i=new o_(e,t);return this._doSend(i),i}async _doSend(e){this._requests.add(e);try{let t;for(;!this._stopped;)try{const i=this._hsApi[e.methodName].apply(this._hsApi,e.args);await e.setRequestResult(i);return}catch(i){if(i instanceof hc&&i.errcode==="M_LIMIT_EXCEEDED")Number.isSafeInteger(i.retry_after_ms)?await this._clock.createTimeout(i.retry_after_ms).elapsed():(t||(t=new Qc(this._clock.createTimeout)),await t.waitForRetry());else{e.responseReject(i);return}}this._stopped&&e.abort()}finally{this._requests.delete(e)}}}const c_=3e4,j=We("InitialSync","CatchupSync","Syncing","Stopped");function l_(s){var e;try{const t=(e=s?.timeline)==null?void 0:e.events;return Array.isArray(t)&&t.length===0}catch{return!0}}class d_{constructor({hsApi:e,session:t,storage:i,logger:r}){this._hsApi=e,this._logger=r,this._session=t,this._storage=i,this._currentRequest=null,this._status=new qe(j.Stopped),this._error=null}get status(){return this._status}get error(){return this._error}start(){if(this._status.get()!==j.Stopped)return;this._error=null;let e=this._session.syncToken;e?this._status.set(j.CatchupSync):this._status.set(j.InitialSync),this._syncLoop(e)}async _syncLoop(e){for(;this._status.get()!==j.Stopped;){let t,i,r=this._status.get()===j.CatchupSync||this._status.get()===j.InitialSync;await this._logger.run("sync",async n=>{n.set("token",e),n.set("status",this._status.get());try{const o=this._status.get()===j.Syncing?c_:0,a=await this._syncRequest(e,o,n);e=a.syncToken,t=a.roomStates,i=a.sessionChanges,this._status.get()!==j.Syncing&&a.hadToDeviceMessages?this._status.set(j.CatchupSync):this._status.set(j.Syncing)}catch(o){if(o.name==="ConnectionError"&&o.isTimeout)return;this._error=o,o.name!=="AbortError"&&(n.error=o,n.logLevel=n.level.Fatal),n.set("stopping",!0),this._status.set(j.Stopped)}this._status.get()!==j.Stopped&&await n.wrap("afterSyncCompleted",o=>this._runAfterSyncCompleted(i,t,o))},this._logger.level.Info,(n,o)=>o.durationWithoutType("network")>=2e3||o.error||r?n.minLevel(o.level.Detail):n.minLevel(o.level.Info))}}async _runAfterSyncCompleted(e,t,i){const r=this._status.get()===j.CatchupSync,n=(async()=>{try{await i.wrap("session",c=>this._session.afterSyncCompleted(e,r,c),i.level.Detail)}catch{}})(),a=t.filter(c=>c.room.needsAfterSyncCompleted(c.changes)).map(async c=>{try{await i.wrap("room",l=>c.room.afterSyncCompleted(c.changes,l),i.level.Detail)}catch{}});await Promise.all(a.concat(n))}async _syncRequest(e,t,i){var r;let{syncFilterId:n}=this._session;typeof n!="string"&&(this._currentRequest=this._hsApi.createFilter(this._session.user.id,{room:{state:{lazy_load_members:!0}}},{log:i}),n=(await this._currentRequest.response()).filter_id);const o=t+80*1e3;this._currentRequest=this._hsApi.sync(e,n,t,{timeout:o,log:i});const a=await this._currentRequest.response(),c=!e,l=new u_,d=this._parseInvites(a.rooms),{roomStates:u,archivedRoomStates:h}=await this._parseRoomsResponse(a.rooms,d,c,i);try{l.lock=await i.wrap("obtainSyncLock",()=>this._session.obtainSyncLock(a)),await i.wrap("prepare",_=>this._prepareSync(l,u,a,_)),await i.wrap("afterPrepareSync",_=>Promise.all(u.map(f=>f.room.afterPrepareSync(f.preparation,_)))),await i.wrap("write",async _=>this._writeSync(l,d,u,h,a,n,c,_))}finally{l.dispose()}i.wrap("after",_=>this._afterSync(l,d,u,h,_));const m=(r=a.to_device)==null?void 0:r.events;return{syncToken:a.next_batch,roomStates:u,sessionChanges:l.changes,hadToDeviceMessages:Array.isArray(m)&&m.length>0}}_openPrepareSyncTxn(){const e=this._storage.storeNames;return this._storage.readTxn([e.olmSessions,e.inboundGroupSessions,e.timelineFragments,e.timelineEvents])}async _prepareSync(e,t,i,r){var n,o;const a=await this._openPrepareSyncTxn();e.preparation=await r.wrap("session",l=>this._session.prepareSync(i,e.lock,a,l));const c=(n=e.preparation)==null?void 0:n.newKeysByRoom;if(c){const{hasOwnProperty:l}=Object.prototype;for(const d of c.keys())if(!(((o=i.rooms)==null?void 0:o.join)&&l.call(i.rooms.join,d))){let h=this._session.rooms.get(d);h&&t.push(new aa(h,!1,{},h.membership))}}await Promise.all(t.map(async l=>{const d=c?.get(l.room.id);l.preparation=await r.wrap("room",async u=>(l.isNewRoom&&await l.room.load(null,a,u),l.room.prepareSync(l.roomResponse,l.membership,d,a,u)),r.level.Detail)})),await a.complete()}async _writeSync(e,t,i,r,n,o,a,c){const l=await this._openSyncTxn();try{e.changes=await c.wrap("session",d=>this._session.writeSync(n,o,e.preparation,l,d)),await Promise.all(t.map(async d=>{d.changes=await c.wrap("invite",u=>d.invite.writeSync(d.membership,d.roomResponse,l,u))})),await Promise.all(i.map(async d=>{d.changes=await c.wrap("room",u=>d.room.writeSync(d.roomResponse,a,d.preparation,l,u))})),await Promise.all(r.map(async d=>{var u;const h=(u=d.roomState)==null?void 0:u.summaryChanges;d.changes=await c.wrap("archivedRoom",m=>d.archivedRoom.writeSync(h,d.roomResponse,d.membership,l,m))}))}catch(d){throw l.abort(c),l.getCause(d)}await l.complete(c)}_afterSync(e,t,i,r,n){n.wrap("session",o=>this._session.afterSync(e.changes,o),n.level.Detail);for(let o of r)n.wrap("archivedRoom",a=>{o.archivedRoom.afterSync(o.changes,a),o.archivedRoom.release()},n.level.Detail);for(let o of i)n.wrap("room",a=>o.room.afterSync(o.changes,a),n.level.Detail);for(let o of t)n.wrap("invite",a=>o.invite.afterSync(o.changes,a),n.level.Detail);this._session.applyRoomCollectionChangesAfterSync(t,i,r,n)}_openSyncTxn(){const e=this._storage.storeNames;return this._storage.readWriteTxn([e.session,e.roomSummary,e.archivedRoomSummary,e.invites,e.roomState,e.roomMembers,e.timelineEvents,e.timelineRelations,e.timelineFragments,e.pendingEvents,e.userIdentities,e.groupSessionDecryptions,e.deviceIdentities,e.outboundGroupSessions,e.operations,e.accountData,e.olmSessions,e.inboundGroupSessions])}async _parseRoomsResponse(e,t,i,r){const n=[],o=[];if(e){const a=["join","leave"];for(const c of a){const l=e[c];if(l)for(const[d,u]of Object.entries(l)){if(i&&l_(u))continue;const h=this._session.invites.get(d);h&&t.push(new ca(h,!1,null,c));const m=this._createRoomSyncState(d,u,c,i);m&&n.push(m);const _=await this._createArchivedRoomSyncState(d,m,u,c,i,r);_&&o.push(_)}}}return{roomStates:n,archivedRoomStates:o}}_createRoomSyncState(e,t,i,r){let n=!1,o=this._session.rooms.get(e);if(!o&&(i==="join"||r&&i==="leave")&&(o=this._session.createJoinedRoom(e),n=!0),o)return new aa(o,n,t,i)}async _createArchivedRoomSyncState(e,t,i,r,n,o){let a;if(t?.shouldAdd&&!n?a=this._session.createOrGetArchivedRoomForSync(e):r==="leave"&&(t?a=this._session.createOrGetArchivedRoomForSync(e):a=await this._session.loadArchivedRoom(e,o)),a)return new h_(a,t,i,r)}_parseInvites(e){const t=[];if(e?.invite)for(const[i,r]of Object.entries(e.invite)){let n=this._session.invites.get(i),o=!1;n||(n=this._session.createInvite(i),o=!0),t.push(new ca(n,o,r,"invite"))}return t}stop(){this._status.get()!==j.Stopped&&(this._status.set(j.Stopped),this._currentRequest&&(this._currentRequest.abort(),this._currentRequest=null))}}class u_{constructor(){this.lock=null,this.preparation=null,this.changes=null}dispose(){var e;(e=this.lock)==null||e.release()}}class aa{constructor(e,t,i,r){this.room=e,this.isNewRoom=t,this.roomResponse=i,this.membership=r,this.preparation=null,this.changes=null}get id(){return this.room.id}get shouldAdd(){return this.isNewRoom&&this.membership==="join"}get shouldRemove(){return!this.isNewRoom&&this.membership!=="join"}get summaryChanges(){var e;return(e=this.changes)==null?void 0:e.summaryChanges}}class h_{constructor(e,t,i,r,n){this.archivedRoom=e,this.roomState=t,this.roomResponse=i,this.membership=r,this.isInitialSync=n,this.changes=null}get id(){return this.archivedRoom.id}get shouldAdd(){return(this.roomState||this.isInitialSync)&&this.membership==="leave"}get shouldRemove(){return this.membership==="join"}}class ca{constructor(e,t,i,r){this.invite=e,this.isNewInvite=t,this.membership=r,this.roomResponse=i,this.changes=null}get id(){return this.invite.id}get shouldAdd(){return this.isNewInvite}get shouldRemove(){return this.membership!=="invite"}}class Xi{constructor(){this._handlersByName={}}emit(e,t){const i=this._handlersByName[e];i&&i.forEach(r=>r(t))}disposableOn(e,t){return this.on(e,t),()=>{this.off(e,t)}}on(e,t){let i=this._handlersByName[e];i||(this.onFirstSubscriptionAdded(e),this._handlersByName[e]=i=new Set),i.add(t)}off(e,t){const i=this._handlersByName[e];i&&(i.delete(t),i.size===0&&(delete this._handlersByName[e],this.onLastSubscriptionRemoved(e)))}onFirstSubscriptionAdded(e){}onLastSubscriptionRemoved(e){}}function p_(s,e,t,i,r){return e.length&&(s=e.reduce((n,o)=>g_(n,o,t,i,r),s)),s}function el(s,e,t){var i,r;const n=(i=s?.state)==null?void 0:i.events;Array.isArray(n)&&(t=n.reduce(e,t));const o=(r=s?.timeline)==null?void 0:r.events;return Array.isArray(o)&&(t=o.reduce((a,c)=>(typeof c.state_key=="string"&&(t=e(t,c)),t),t)),t}function m_(s,e,t,i){e.summary&&(s=y_(s,e.summary)),t!==s.membership&&(s=s.cloneIfNeeded(),s.membership=t),e.account_data&&(s=e.account_data.events.reduce(f_,s)),s=el(e,(n,o)=>tl(n,o,i),s);const r=e.unread_notifications;return r&&(s=__(s,r)),s}function __(s,e){const t=e.highlight_count||0;t!==s.highlightCount&&(s=s.cloneIfNeeded(),s.highlightCount=t);const i=e.notification_count;return i!==s.notificationCount&&(s=s.cloneIfNeeded(),s.notificationCount=i),s}function f_(s,e){var t;if(e?.type==="m.tag"){let i=(t=e?.content)==null?void 0:t.tags;(!i||Array.isArray(i)||typeof i!="object")&&(i=null),s=s.cloneIfNeeded(),s.tags=i}return s}function tl(s,e,t){var i,r,n;if(e.type==="m.room.create")s=s.cloneIfNeeded(),s.lastMessageTimestamp=e.origin_server_ts;else if(e.type==="m.room.encryption"){const o=(i=e.content)==null?void 0:i.algorithm;!s.encryption&&o===De&&(s=s.cloneIfNeeded(),s.encryption=e.content)}else if(e.type==="m.room.name"){const o=(r=e.content)==null?void 0:r.name;o!==s.name&&(s=s.cloneIfNeeded(),s.name=o)}else if(e.type==="m.room.avatar"){const o=(n=e.content)==null?void 0:n.url;o!==s.avatarUrl&&(s=s.cloneIfNeeded(),s.avatarUrl=o)}else if(e.type==="m.room.canonical_alias"){const o=e.content;s=s.cloneIfNeeded(),s.canonicalAlias=o.alias}else if(e.type==="m.room.member"){const o=e.content;if(o.is_direct===!0&&o.membership==="invite"&&!s.isDirectMessage){let a;e.sender===t?a=e.state_key:e.state_key===t&&(a=e.sender),a&&(s=s.cloneIfNeeded(),s.isDirectMessage=!0,s.dmUserId=a)}else o.membership==="leave"&&s.isDirectMessage&&s.dmUserId===e.state_key&&(s=s.cloneIfNeeded(),s.isDirectMessage=!1,s.dmUserId=null)}return s}function g_(s,e,t,i,r){return e.eventType==="m.room.message"&&((!s.lastMessageTimestamp||e.timestamp>s.lastMessageTimestamp)&&(s=s.cloneIfNeeded(),s.lastMessageTimestamp=e.timestamp),!t&&e.sender!==r&&i&&(s=s.cloneIfNeeded(),s.isUnread=!0)),s}function y_(s,e){const t=e["m.heroes"],i=e["m.joined_member_count"],r=e["m.invited_member_count"];return t&&Array.isArray(t)&&(s=s.cloneIfNeeded(),s.heroes=t),Number.isInteger(r)&&(s=s.cloneIfNeeded(),s.inviteCount=r),Number.isInteger(i)&&(s=s.cloneIfNeeded(),s.joinCount=i),s}class Fe{constructor(e,t){this.roomId=e?e.roomId:t,this.name=e?e.name:null,this.lastMessageTimestamp=e?e.lastMessageTimestamp:null,this.isUnread=e?e.isUnread:!1,this.encryption=e?e.encryption:null,this.membership=e?e.membership:null,this.inviteCount=e?e.inviteCount:0,this.joinCount=e?e.joinCount:0,this.heroes=e?e.heroes:null,this.canonicalAlias=e?e.canonicalAlias:null,this.hasFetchedMembers=e?e.hasFetchedMembers:!1,this.isTrackingMembers=e?e.isTrackingMembers:!1,this.avatarUrl=e?e.avatarUrl:null,this.notificationCount=e?e.notificationCount:0,this.highlightCount=e?e.highlightCount:0,this.tags=e?e.tags:null,this.isDirectMessage=e?e.isDirectMessage:!1,this.dmUserId=e?e.dmUserId:null,this.cloned=!!e}changedKeys(e){return Object.getOwnPropertyNames(this).filter(i=>i!=="cloned"&&this[i]!==e[i])}cloneIfNeeded(){return this.cloned?this:new Fe(this)}serialize(){return Object.entries(this).reduce((e,[t,i])=>(t!=="cloned"&&i!==null&&(e[t]=i),e),{})}applyTimelineEntries(e,t,i,r){return p_(this,e,t,i,r)}applySyncResponse(e,t,i){return m_(this,e,t,i)}get needsHeroes(){return!this.name&&!this.canonicalAlias&&this.heroes&&this.heroes.length>0}isNewJoin(e){return this.membership==="join"&&e.membership!=="join"}}class v_{constructor(e){this._data=null,this.applyChanges(new Fe(null,e))}get data(){return this._data}writeClearUnread(e){const t=new Fe(this._data);return t.isUnread=!1,t.notificationCount=0,t.highlightCount=0,e.roomSummary.set(t.serialize()),t}writeHasFetchedMembers(e,t){const i=new Fe(this._data);return i.hasFetchedMembers=e,t.roomSummary.set(i.serialize()),i}writeIsTrackingMembers(e,t){const i=new Fe(this._data);return i.isTrackingMembers=e,t.roomSummary.set(i.serialize()),i}writeData(e,t){if(e!==this._data)return t.roomSummary.set(e.serialize()),e}writeArchivedData(e,t){if(e!==this._data)return t.archivedRoomSummary.set(e.serialize()),e}async writeAndApplyData(e,t){if(e===this._data)return!1;const i=await t.readWriteTxn([t.storeNames.roomSummary]);try{i.roomSummary.set(e.serialize())}catch(r){throw i.abort(),r}return await i.complete(),this.applyChanges(e),!0}applyChanges(e){this._data=e,this._data.cloned=!1}async load(e){this.applyChanges(new Fe(e))}}const Js=Number.MAX_SAFE_INTEGER;class il{constructor(e){this._fragmentIdComparer=e}compare(e){return this.fragmentId===e.fragmentId?this.entryIndex-e.entryIndex:this.fragmentId===Js?1:e.fragmentId===Js?-1:this._fragmentIdComparer.compare(this.fragmentId,e.fragmentId)}asEventKey(){return new q(this.fragmentId,this.entryIndex)}}const w_="m.reaction",at="m.annotation";function b_(s,e){return{"m.relates_to":{event_id:s,key:e,rel_type:at}}}function Tn(s){var e;return s.event_id||((e=s["m.in_reply_to"])==null?void 0:e.event_id)}function rl(s,e){s.event_id!==void 0?s.event_id=e:s["m.in_reply_to"]&&(s["m.in_reply_to"].event_id=e)}function S_(s){if(s.type===Ce)return s.redacts;{const e=et(s);if(e)return Tn(e)}return null}function mt(s){return s?.["m.relates_to"]}function et(s){return mt(s.content)}class E_{constructor(){this._entries=[]}get firstTimestamp(){return this._entries.reduce((e,t)=>t.isRedaction?e:Math.min(t.timestamp,e),Number.MAX_SAFE_INTEGER)}get annotationEntry(){return this._entries.find(e=>!e.isRedaction)}get redactionEntry(){return this._entries.find(e=>e.isRedaction)}get count(){return this._entries.reduce((e,t)=>e+(t.isRedaction?-1:1),0)}add(e){this._entries.push(e)}remove(e){const t=this._entries.indexOf(e);return t===-1?!1:(this._entries.splice(t,1),!0)}get willAnnotate(){const e=this._entries.reduce((t,i)=>!t||i.pendingEvent.queueIndex>t.pendingEvent.queueIndex?i:t,null);return e?!e.isRedaction:!1}get isEmpty(){return this._entries.length===0}}function la(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function I_(s){switch(s){case"m.file":return"sent a file.";case"m.image":return"sent an image.";case"m.video":return"sent a video.";case"m.audio":return"sent an audio file."}return null}function T_(s){return s==="m.emote"?"* ":""}function x_(s,e,t,i){return{msgtype:e,body:t,format:"org.matrix.custom.html",formatted_body:i,"m.relates_to":{"m.in_reply_to":{event_id:s}}}}function k_(s,e,t){const i=I_(s.content.msgtype),r=T_(s.content.msgtype),n=s.sender,o=s.displayName||n,a=i||s.content.formatted_body||s.content.body&&la(s.content.body)||"",c=`<mx-reply><blockquote>In reply to ${r}<a href="https://matrix.to/#/${n}">${o}</a><br />${a}</blockquote></mx-reply>`,d=(i||s.content.body||"").split(`
`);d[0]=`> ${r}<${n}> ${d[0]}`;const h=d.join(`
> `)+`
`+t,m=c+la(t);return x_(s.id,e,h,m)}class sl extends il{constructor(e){super(e),this._pendingRedactions=null,this._pendingAnnotations=null,this._contextEntry=null,this._contextForEntries=null}get isReply(){var e;return!!((e=this.relation)!=null&&e["m.in_reply_to"])}get isRedacting(){return!!this._pendingRedactions}get isRedacted(){return this.isRedacting}get isRedaction(){return this.eventType===Ce}get redactionReason(){var e;return this._pendingRedactions?(e=this._pendingRedactions[0].content)==null?void 0:e.reason:null}setContextEntry(e){this._contextEntry=e,e._setAsContextOf(this)}_setAsContextOf(e){this._contextForEntries||(this._contextForEntries=[]),this._contextForEntries.push(e)}get contextForEntries(){return this._contextForEntries}get contextEntry(){return this._contextEntry}addLocalRelation(e){if(e.eventType===Ce&&e.isRelatedToId(this.id)){if(this._pendingRedactions||(this._pendingRedactions=[]),this._pendingRedactions.push(e),this._pendingRedactions.length===1)return"isRedacted"}else{const t=e.redactingEntry||e;if(t.isRelatedToId(this.id)&&t.relation.rel_type===at&&this._addPendingAnnotation(e))return"pendingAnnotations"}}removeLocalRelation(e){var t;if(e.eventType===Ce&&e.isRelatedToId(this.id)&&this._pendingRedactions){const i=this._pendingRedactions.length;if(this._pendingRedactions=this._pendingRedactions.filter(r=>r!==e),this._pendingRedactions.length===0&&(this._pendingRedactions=null,i!==0))return"isRedacted"}else{const i=e.redactingEntry||e;if(i.isRelatedToId(this.id)&&((t=i.relation)==null?void 0:t.rel_type)===at&&this._pendingAnnotations&&this._removePendingAnnotation(e))return"pendingAnnotations"}}_addPendingAnnotation(e){this._pendingAnnotations||(this._pendingAnnotations=new Map);const{key:t}=(e.redactingEntry||e).relation;if(t){let i=this._pendingAnnotations.get(t);return i||(i=new E_,this._pendingAnnotations.set(t,i)),i.add(e),!0}return!1}_removePendingAnnotation(e){const{key:t}=(e.redactingEntry||e).relation;if(t){let i=this._pendingAnnotations.get(t);return i.remove(e)&&i.isEmpty&&this._pendingAnnotations.delete(t),this._pendingAnnotations.size===0&&(this._pendingAnnotations=null),!0}return!1}async abortPendingRedaction(){if(this._pendingRedactions)for(const e of this._pendingRedactions)await e.pendingEvent.abort()}get pendingRedaction(){return this._pendingRedactions?this._pendingRedactions[0]:null}annotate(e){return b_(this.id,e)}reply(e,t){return k_(this,e,t)}isRelatedToId(e){return e&&this.relatedEventId===e}haveAnnotation(e){var t,i,r;const n=((i=(t=this.annotations)==null?void 0:t[e])==null?void 0:i.me)||!1,o=(r=this.pendingAnnotations)==null?void 0:r.get(e),a=o?.willAnnotate||!1;return n&&(!o||a)||!n&&a}get relation(){return mt(this.content)}get pendingAnnotations(){return this._pendingAnnotations}get annotations(){return null}}class R_ extends sl{constructor({pendingEvent:e,member:t,clock:i,redactingEntry:r}){super(null),this._pendingEvent=e,this._member=t,this._timestamp=i.now()-(100-e.queueIndex),this._redactingEntry=r}get fragmentId(){return Js}get entryIndex(){return this._pendingEvent.queueIndex}get content(){return this._pendingEvent.content}get event(){return null}get eventType(){return this._pendingEvent.eventType}get stateKey(){return null}get sender(){var e;return(e=this._member)==null?void 0:e.userId}get displayName(){var e;return(e=this._member)==null?void 0:e.name}get avatarUrl(){var e;return(e=this._member)==null?void 0:e.avatarUrl}get timestamp(){return this._timestamp}get isPending(){return!0}get id(){return this._pendingEvent.txnId}get pendingEvent(){return this._pendingEvent}notifyUpdate(){}isRelatedToId(e){return e&&e===this._pendingEvent.relatedTxnId?!0:super.isRelatedToId(e)}get relatedEventId(){return this._pendingEvent.relatedEventId}get redactingEntry(){return this._redactingEntry}get contextEventId(){var e;return this.isReply?(e=this._pendingEvent.relatedEventId)!=null?e:this._pendingEvent.relatedTxnId:null}}const P=We("Waiting","EncryptingAttachments","UploadingAttachments","Encrypting","Sending","Sent","Error"),da=["m.relates_to"];class A_{constructor({data:e,remove:t,emitUpdate:i,attachments:r}){this._data=e,this._attachments=r,this._emitUpdate=i,this._removeFromQueueCallback=t,this._aborted=!1,this._status=P.Waiting,this._sendRequest=null,this._attachmentsTotalBytes=0,this._attachments&&(this._attachmentsTotalBytes=Object.values(this._attachments).reduce((n,o)=>n+o.size,0))}get roomId(){return this._data.roomId}get queueIndex(){return this._data.queueIndex}get eventType(){return this._data.eventType}get txnId(){return this._data.txnId}get remoteId(){return this._data.remoteId}get content(){return this._data.content}get relatedTxnId(){return this._data.relatedTxnId}get relatedEventId(){const e=mt(this.content);return e?Tn(e):this._data.relatedEventId}setRelatedEventId(e){const t=mt(this.content);t?rl(t,e):this._data.relatedEventId=e}get data(){return this._data}getAttachment(e){return this._attachments&&this._attachments[e]}get needsSending(){return!this.remoteId&&!this.aborted}get needsEncryption(){return this._data.needsEncryption&&!this.aborted}get needsUpload(){return this._data.needsUpload&&!this.aborted}get isMissingAttachments(){return this.needsUpload&&!this._attachments}setEncrypting(){this._status=P.Encrypting,this._emitUpdate("status")}get contentForEncryption(){const e=Object.assign({},this._data.content);for(const t of da)delete e[t];return e}_preserveContentFields(e){const t=this._data.content;for(const i of da)t[i]!==void 0&&(e[i]=t[i])}setEncrypted(e,t){this._preserveContentFields(t),this._data.encryptedEventType=e,this._data.encryptedContent=t,this._data.needsEncryption=!1}setError(e){this._status=P.Error,this._error=e,this._emitUpdate("status")}setWaiting(){this._status=P.Waiting,this._emitUpdate("status")}get status(){return this._status}get error(){return this._error}get hasStartedSending(){return this._status===P.Sending||this._status===P.Sent}get attachmentsTotalBytes(){return this._attachmentsTotalBytes}get attachmentsSentBytes(){return this._attachments&&Object.values(this._attachments).reduce((e,t)=>e+t.sentBytes,0)}async uploadAttachments(e,t){if(!this.needsUpload)return;if(!this._attachments)throw new Error("attachments missing");if(this.needsEncryption){this._status=P.EncryptingAttachments,this._emitUpdate("status");for(const r of Object.values(this._attachments))if(await t.wrap("encrypt",()=>(t.set("size",r.size),r.encrypt())),this.aborted)throw new Me}this._status=P.UploadingAttachments,this._emitUpdate("status");const i=Object.entries(this._attachments);i.sort(([,r],[,n])=>r.size-n.size);for(const[r,n]of i)await t.wrap("upload",o=>(o.set("size",n.size),n.upload(e,()=>{this._emitUpdate("attachmentsSentBytes")},o))),n.applyToContent(r,this.content);this._data.needsUpload=!1}async abort(){var e;if(!this._aborted){if(this._aborted=!0,this._attachments)for(const t of Object.values(this._attachments))t.abort();(e=this._sendRequest)==null||e.abort(),await this._removeFromQueueCallback()}}get aborted(){return this._aborted}async send(e,t){this._status=P.Sending,this._emitUpdate("status");const i=this._data.encryptedEventType||this._data.eventType,r=this._data.encryptedContent||this._data.content;i===Ce?this._sendRequest=e.redact(this.roomId,this._data.relatedEventId,this.txnId,r,{log:t}):this._sendRequest=e.send(this.roomId,i,this.txnId,r,{log:t});const n=await this._sendRequest.response();this._sendRequest=null,this._data.remoteId=n.event_id,t.set("id",this._data.remoteId),this._status=P.Sent,this._emitUpdate("status")}dispose(){if(this._attachments)for(const e of Object.values(this._attachments))e.dispose()}}class fe extends sl{constructor(e,t){super(t),this._eventEntry=e,this._decryptionError=null,this._decryptionResult=null}clone(){const e=new fe(this._eventEntry,this._fragmentIdComparer);return e.updateFrom(this),e}updateFrom(e){e._decryptionResult&&!this._decryptionResult&&(this._decryptionResult=e._decryptionResult),e._decryptionError&&!this._decryptionError&&(this._decryptionError=e._decryptionError),this._contextForEntries=e.contextForEntries,this._contextEntry=e.contextEntry}get event(){return this._eventEntry.event}get fragmentId(){return this._eventEntry.fragmentId}get entryIndex(){return this._eventEntry.eventIndex}get content(){var e,t;return((t=(e=this._decryptionResult)==null?void 0:e.event)==null?void 0:t.content)||this._eventEntry.event.content}get prevContent(){return Hs(this._eventEntry.event)}get eventType(){var e,t;return((t=(e=this._decryptionResult)==null?void 0:e.event)==null?void 0:t.type)||this._eventEntry.event.type}get stateKey(){return this._eventEntry.event.state_key}get sender(){return this._eventEntry.event.sender}get displayName(){return this._eventEntry.displayName}get avatarUrl(){return this._eventEntry.avatarUrl}get timestamp(){return this._eventEntry.event.origin_server_ts}get id(){return this._eventEntry.event.event_id}setDecryptionResult(e){this._decryptionResult=e}get isEncrypted(){return this._eventEntry.event.type==="m.room.encrypted"}get isDecrypted(){var e;return!!((e=this._decryptionResult)!=null&&e.event)}get isVerified(){var e;return this.isEncrypted&&((e=this._decryptionResult)==null?void 0:e.isVerified)}get isUnverified(){var e;return this.isEncrypted&&((e=this._decryptionResult)==null?void 0:e.isUnverified)}setDecryptionError(e){this._decryptionError=e}get decryptionError(){return this._decryptionError}get relatedEventId(){return S_(this.event)}get isRedacted(){return super.isRedacted||Ws(this._eventEntry.event)}get redactionReason(){var e,t;const i=(e=this._eventEntry.event.unsigned)==null?void 0:e.redacted_because;return i?(t=i.content)==null?void 0:t.reason:super.redactionReason}get annotations(){return this._eventEntry.annotations}get relation(){const e=this._eventEntry.event.content;return e&&mt(e)||mt(this.content)}get contextEventId(){return this.isReply?this.relatedEventId:null}}function xn(s){return typeof s=="number"}const C_=["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"].reduce(function(s,e){return s[e]=1,s},{}),N_={"m.room.member":{membership:1},"m.room.create":{creator:1},"m.room.join_rules":{join_rule:1},"m.room.power_levels":{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1},"m.room.aliases":{aliases:1}};function M_(s,e){for(const r of Object.keys(e))C_[r]||delete e[r];const{content:t}=e,i=N_[e.type];for(const r of Object.keys(t))i?.[r]||delete t[r];e.unsigned=e.unsigned||{},e.unsigned.redacted_because=s}function D_(s,e){const t=[];for(;xn(s.previousId);){const i=e.get(s.previousId);if(!i)break;if(i.nextId!==s.id)throw new Error(`Previous fragment ${i.id} doesn't point back to ${s.id}`);e.delete(s.previousId),t.unshift(i),s=i}return t}function P_(s,e){const t=[];for(;xn(s.nextId);){const i=e.get(s.nextId);if(!i)break;if(i.previousId!==s.id)throw new Error(`Next fragment ${i.id} doesn't point back to ${s.id}`);e.delete(s.nextId),t.push(i),s=i}return t}function O_(s){const e=new Map;for(let i of s)e.set(i.id,i);const t=[];for(;e.size;){const i=e.values().next().value;e.delete(i.id);const r=D_(i,e),n=P_(i,e),o=r.concat(i,n);t.push(o)}return t.map(i=>new U_(i))}class Ms{constructor(e,t,i){this.id=e,this.previousId=t,this.nextId=i}}class U_{constructor(e){this._idToSortIndex=new Map,e.forEach((t,i)=>{this._idToSortIndex.set(t.id,i)})}compare(e,t){const i=this._idToSortIndex.get(e);if(i===void 0)throw new Error(`first id ${e} isn't part of this island`);const r=this._idToSortIndex.get(t);if(r===void 0)throw new Error(`second id ${t} isn't part of this island`);return i-r}get fragmentIds(){return this._idToSortIndex.keys()}}class ua extends Error{get name(){return"CompareError"}}class B_{constructor(e){this._fragmentsById=e.reduce((t,i)=>(t.set(i.id,i),t),new Map),this.rebuild(e)}_getIsland(e){const t=this._idToIsland.get(e);if(t===void 0)throw new ua(`Unknown fragment id ${e}`);return t}compare(e,t){if(e===t)return 0;const i=this._getIsland(e),r=this._getIsland(t);if(i!==r)throw new ua(`${e} and ${t} are on different islands, can't tell order`);return i.compare(e,t)}rebuild(e){const t=O_(e);this._idToIsland=new Map;for(let i of t)for(let r of i.fragmentIds)this._idToIsland.set(r,i)}add(e){const t=new Ms(e.id,e.previousId,e.nextId);this._fragmentsById.set(e.id,t),this.rebuild(this._fragmentsById.values())}append(e,t){const i=new Ms(e,t,null),r=this._fragmentsById.get(t);r&&(r.nextId=e),this._fragmentsById.set(e,i),this.rebuild(this._fragmentsById.values())}prepend(e,t){const i=new Ms(e,null,t),r=this._fragmentsById.get(t);r&&(r.previousId=e),this._fragmentsById.set(e,i),this.rebuild(this._fragmentsById.values())}}class nl{constructor({roomId:e,ownUserId:t,fragmentIdComparer:i}){this._roomId=e,this._ownUserId=t,this._fragmentIdComparer=i}async writeRelation(e,t,i){const{relatedEventId:r}=e;if(r){const n=et(e.event);n&&n.rel_type&&t.timelineRelations.add(this._roomId,n.event_id,n.rel_type,e.id);const o=await t.timelineEvents.getByEventId(this._roomId,r);if(o){const a=await this._applyRelation(e,o,t,i);if(a)return a.map(c=>(t.timelineEvents.update(c),new fe(c,this._fragmentIdComparer)))}}return null}async writeGapRelation(e,t,i,r){const n=new fe(e,this._fragmentIdComparer),o=await this.writeRelation(n,i,r);if(t.isBackward&&!Ws(e.event)){const a=await i.timelineRelations.getAllForTarget(this._roomId,n.id);if(a.length)for(const c of a){const l=await i.timelineEvents.getByEventId(this._roomId,c.sourceEventId);if(l){const d=new fe(l,this._fragmentIdComparer);await this._applyRelation(d,e,i,r)}}}return o}async _applyRelation(e,t,i,r){if(e.eventType===Ce)return r.wrap("redact",async n=>{const o=t.event,a=et(o);if(this._applyRedaction(e.event,t,i,n)){const l=[t];if(a){const d=await this._reaggregateRelation(o,a,i,n);d&&l.push(d)}return l}return null});{const n=et(e.event);if(n&&!Ws(t.event)&&n.rel_type===at&&r.wrap("react",c=>this._aggregateAnnotation(e.event,t,c)))return[t]}return null}_applyRedaction(e,t,i,r){const n=t.event;r.set("redactionId",e.event_id),r.set("id",n.event_id);const o=et(n);return o&&o.rel_type&&i.timelineRelations.remove(this._roomId,o.event_id,o.rel_type,n.event_id),i.timelineRelations.removeAllForTarget(this._roomId,n.event_id),M_(e,n),delete t.annotations,!0}_aggregateAnnotation(e,t){const i=et(e);if(!i)return!1;let{annotations:r}=t;r||(t.annotations=r={});let n=r[i.key];n||(r[i.key]=n={count:0,me:!1,firstTimestamp:Number.MAX_SAFE_INTEGER});const o=e.sender===this._ownUserId;return n.me=n.me||o,n.count+=1,n.firstTimestamp=Math.min(n.firstTimestamp,e.origin_server_ts),!0}async _reaggregateRelation(e,t,i,r){return t.rel_type===at?r.wrap("reaggregate annotations",n=>this._reaggregateAnnotation(t.event_id,t.key,i,n)):null}async _reaggregateAnnotation(e,t,i,r){const n=await i.timelineEvents.getByEventId(this._roomId,e);if(!n||!n.annotations)return null;r.set("id",e);const o=await i.timelineRelations.getForTargetAndType(this._roomId,e,at);return r.set("relations",o.length),delete n.annotations[t],L_(n.annotations)&&delete n.annotations,await Promise.all(o.map(async a=>{const c=await i.timelineEvents.getByEventId(this._roomId,a.sourceEventId);c||r.log({l:"missing annotation",id:a.sourceEventId}),et(c.event).key===t&&this._aggregateAnnotation(c.event,n,r)})),n}}function L_(s){for(const e in s)if(s.hasOwnProperty(e))return!1;return!0}class ze{constructor(e){this.isForward=e}get isBackward(){return!this.isForward}asApiString(){return this.isForward?"f":"b"}reverse(){return this.isForward?ze.Backward:ze.Forward}static get Forward(){return F_}static get Backward(){return V_}}const F_=new ze(!0),V_=new ze(!1);class be extends il{constructor(e,t,i){super(i),this._fragment=e,this._isFragmentStart=t}static start(e,t){return new be(e,!0,t)}static end(e,t){return new be(e,!1,t)}get started(){return this._isFragmentStart}get hasEnded(){return!this.started}get fragment(){return this._fragment}get fragmentId(){return this._fragment.id}get entryIndex(){return this.started?K.minStorageKey:K.maxStorageKey}get isGap(){return!!this.token&&!this.edgeReached}get token(){return this.started?this.fragment.previousToken:this.fragment.nextToken}set token(e){this.started?this.fragment.previousToken=e:this.fragment.nextToken=e}get edgeReached(){return this.started?this.fragment.startReached:this.fragment.endReached}set edgeReached(e){this.started?this.fragment.startReached=e:this.fragment.endReached=e}get linkedFragmentId(){return this.started?this.fragment.previousId:this.fragment.nextId}set linkedFragmentId(e){this.started?this.fragment.previousId=e:this.fragment.nextId=e}get hasLinkedFragment(){return xn(this.linkedFragmentId)}get direction(){return this.started?ze.Backward:ze.Forward}withUpdatedFragment(e){return new be(e,this._isFragmentStart,this._fragmentIdComparer)}createNeighbourEntry(e){return new be(e,!this._isFragmentStart,this._fragmentIdComparer)}addLocalRelation(){}removeLocalRelation(){}}function K_(s){const e=new Set;return s.filter(t=>e.has(t.event_id)?!1:(e.add(t.event_id),!0))}class $_{constructor({roomId:e,fragmentIdComparer:t,memberWriter:i,relationWriter:r}){this._roomId=e,this._memberWriter=i,this._relationWriter=r,this._fragmentIdComparer=t,this._lastLiveKey=null}async load(e,t){const i=await e.timelineFragments.liveFragment(this._roomId);if(i){const[r]=await e.timelineEvents.lastEvents(this._roomId,i.id,1),n=r?r.eventIndex:q.defaultLiveKey.eventIndex;this._lastLiveKey=new q(i.id,n)}this._lastLiveKey&&t.set("live key",this._lastLiveKey.toString())}async _createLiveFragment(e,t){const i=await e.timelineFragments.liveFragment(this._roomId);if(i)return i;{t||(t=null);const r={roomId:this._roomId,id:q.defaultLiveKey.fragmentId,previousId:null,nextId:null,previousToken:t,nextToken:null};return e.timelineFragments.add(r),this._fragmentIdComparer.add(r),r}}async _replaceLiveFragment(e,t,i,r){const n=await r.timelineFragments.get(this._roomId,e);if(!n)throw new Error(`old live fragment doesn't exist: ${e}`);n.nextId=t,r.timelineFragments.update(n);const o={roomId:this._roomId,id:t,previousId:e,nextId:null,previousToken:i,nextToken:null};return r.timelineFragments.add(o),this._fragmentIdComparer.append(t,e),{oldFragment:n,newFragment:o}}async _ensureLiveFragment(e,t,i,r,n){if(e){if(i.limited){const o=e.fragmentId;e=e.nextFragmentKey();const{oldFragment:a,newFragment:c}=await this._replaceLiveFragment(o,e.fragmentId,i.prev_batch,r);t.push(be.end(a,this._fragmentIdComparer)),t.push(be.start(c,this._fragmentIdComparer)),n.log({l:"live fragment",limited:!0,id:e.fragmentId})}}else{let o=await this._createLiveFragment(r,i.prev_batch);e=new q(o.id,q.defaultLiveKey.eventIndex),t.push(be.start(o,this._fragmentIdComparer)),n.log({l:"live fragment",first:!0,id:e.fragmentId})}return e}async _writeStateEvents(e,t,i){let r=0;for(const n of e)n.type!==_e&&(t.roomState.set(this._roomId,n),r+=1);i.set("stateEvents",r)}async _writeTimeline(e,t,i,r,n,o){const a=[],c=[];if(e?.length){r=await this._ensureLiveFragment(r,a,t,n,o),o.set("timelineEvents",e.length);let l=0;for(const d of e){r=r.nextKey();const u=Ec(r,this._roomId,d);let h=await i.lookupMemberAtEvent(d.sender,d,n);if(h&&(u.displayName=h.displayName,u.avatarUrl=h.avatarUrl),!await n.timelineEvents.tryInsert(u,o))continue;const _=new fe(u,this._fragmentIdComparer);a.push(_);const f=await this._relationWriter.writeRelation(_,n,o);f&&c.push(...f),typeof d.state_key=="string"&&d.type!==_e&&(l+=1,n.roomState.set(this._roomId,d))}o.set("timelineStateEventCount",l)}return{currentKey:r,entries:a,updatedEntries:c}}async _handleRejoinOverlap(e,t,i){if(this._lastLiveKey){const{fragmentId:r}=this._lastLiveKey,[n]=await t.timelineEvents.lastEvents(this._roomId,r,1);if(n){const o=n.event.event_id,{events:a}=e,c=a.findIndex(l=>l.event_id===o);if(c!==-1)return i.set("overlap_event_id",o),Object.assign({},e,{limited:!1,events:a.slice(c+1)})}}return e.limited?e:(i.set("force_limited_without_overlap",!0),Object.assign({},e,{limited:!0}))}async writeSync(e,t,i,r,n){let{timeline:o}=e;n.set("isRejoin",t),t&&(o=await this._handleRejoinOverlap(o,r,n));let a;Array.isArray(o?.events)&&(a=K_(o.events));const{state:c}=e;let l;Array.isArray(c?.events)&&(l=c.events);const d=this._memberWriter.prepareMemberSync(l,a,i);l&&await this._writeStateEvents(l,r,n);const{currentKey:u,entries:h,updatedEntries:m}=await this._writeTimeline(a,o,d,this._lastLiveKey,r,n),_=await d.write(r);return{entries:h,updatedEntries:m,newLiveKey:u,memberChanges:_}}afterSync(e){this._lastLiveKey=e}get lastMessageKey(){return this._lastLiveKey}}class ol{constructor(e){this.limit=e,this._entries=[]}get size(){return this._entries.length}_get(e){return this._getByIndexAndMoveUp(this._entries.findIndex(e))}_getByIndexAndMoveUp(e){if(e!==-1){const t=this._entries[e];return e>0&&(this._entries.splice(e,1),this._entries.unshift(t)),t}}_set(e,t){let i=t?this._entries.findIndex(t):-1;this._entries.unshift(e),i===-1?this._entries.length>this.limit&&(i=this._entries.length-1):i+=1,i!==-1&&(this.onEvictEntry(this._entries[i]),this._entries.splice(i,1))}onEvictEntry(e){}}class j_ extends ol{constructor(e,t){super(e),this._keyFn=t}get(e){return this._get(t=>this._keyFn(t)===e)}set(e){const t=this._keyFn(e);this._set(e,i=>this._keyFn(i)===t)}}class G_{constructor(e){this._roomId=e,this._cache=new j_(5,t=>t.userId)}prepareMemberSync(e,t,i){return new q_(this,e,t,i)}async _writeMember(e,t){let i=this._cache.get(e.userId);if(!i){const r=await t.roomMembers.get(this._roomId,e.userId);r&&(i=new B(r))}if(!i||!i.equals(e))return t.roomMembers.set(e.serialize()),this._cache.set(e),new Tc(e,i?.membership)}async lookupMember(e,t){let i=this._cache.get(e);if(!i){const r=await t.roomMembers.get(this._roomId,e);r&&(i=new B(r),this._cache.set(i))}return i}}class q_{constructor(e,t,i,r){this._memberWriter=e,this._timelineEvents=i,this._hasFetchedMembers=r,this._newStateMembers=null,t&&(this._newStateMembers=this._stateEventsToMembers(t))}get _roomId(){return this._memberWriter._roomId}_stateEventsToMembers(e){let t;for(const i of e)if(i.type===_e){const r=B.fromMemberEvent(this._roomId,i);r&&(t||(t=new Map),t.set(r.userId,r))}return t}_timelineEventsToMembers(e){let t;for(let i=e.length-1;i>=0;i--){const r=e[i],n=r.state_key;if(r.type===_e&&!t?.has(n)){const o=B.fromMemberEvent(this._roomId,r);o&&(t||(t=new Map),t.set(o.userId,o))}}return t}async lookupMemberAtEvent(e,t,i){var r;let n;return this._timelineEvents&&(n=this._findPrecedingMemberEventInTimeline(e,t),n)||(n=(r=this._newStateMembers)==null?void 0:r.get(e),n)?n:await this._memberWriter.lookupMember(e,i)}async write(e){const t=new Map;let i;if(this._timelineEvents&&(i=this._timelineEventsToMembers(this._timelineEvents)),this._newStateMembers){for(const r of this._newStateMembers.values())if(!i?.has(r.userId)){const n=await this._memberWriter._writeMember(r,e);n&&(!this._hasFetchedMembers&&!n.previousMembership&&(n.previousMembership=r.membership),t.set(n.userId,n))}}if(i)for(const r of i.values()){const n=await this._memberWriter._writeMember(r,e);n&&t.set(n.userId,n)}return t}_findPrecedingMemberEventInTimeline(e,t){let i=-1;for(let r=this._timelineEvents.length-1;r>=0;r--)if(this._timelineEvents[r].event_id===t.event_id){i=r;break}for(let r=i-1;r>=0;r--){const n=this._timelineEvents[r];if(n.type===_e&&n.state_key===e){const o=B.fromMemberEvent(this._roomId,n);if(o)return o}}}}class z_{constructor({roomId:e,storage:t,fragmentIdComparer:i,relationWriter:r}){this._roomId=e,this._storage=t,this._fragmentIdComparer=i,this._relationWriter=r}async _findOverlappingEvents(e,t,i,r){const n=t.map(l=>l.event_id),o=await i.timelineEvents.getEventKeysForIds(this._roomId,n);r.set("existingEvents",o.size);const a=t.filter(l=>!o.has(l.event_id));r.set("nonOverlappingEvents",a.length);let c;if(e.hasLinkedFragment){r.set("linkedFragmentId",e.linkedFragmentId);for(const l of o.values())if(l.fragmentId===e.linkedFragmentId){r.set("foundLinkedFragment",!0);const d=await i.timelineFragments.get(this._roomId,e.linkedFragmentId);c=e.createNeighbourEntry(d);break}}return{nonOverlappingEvents:a,neighbourFragmentEntry:c}}async _findFragmentEdgeEventKey(e,t){const{fragmentId:i,direction:r}=e,n=await this._findFragmentEdgeEvent(i,r,t);return n?new q(n.fragmentId,n.eventIndex):q.defaultFragmentKey(e.fragmentId)}async _findFragmentEdgeEvent(e,t,i){if(t.isBackward){const[r]=await i.timelineEvents.firstEvents(this._roomId,e,1);return r}else{const[r]=await i.timelineEvents.lastEvents(this._roomId,e,1);return r}}async _storeEvents(e,t,i,r,n,o){const a=[],c=[];let l=t;for(let d=0;d<e.length;++d){const u=e[d];l=l.nextKeyForDirection(i);const h=Ec(l,this._roomId,u),m=this._findMember(u.sender,r,e,d,i);m&&(h.displayName=m.displayName,h.avatarUrl=m.avatarUrl);const _=await this._relationWriter.writeGapRelation(h,i,n,o);if(_&&c.push(..._),await n.timelineEvents.tryInsert(h,o)){const f=new fe(h,this._fragmentIdComparer);Ri(a,f,i)}}return{entries:a,updatedEntries:c}}_findMember(e,t,i,r,n){function o(l){return l.type===_e&&l.state_key===e}const a=n.isBackward?1:-1;for(let l=r+a;l>=0&&l<i.length;l+=a){const d=i[l];if(o(d))return B.fromMemberEvent(this._roomId,d)}for(let l=r;l>=0&&l<i.length;l-=a){const d=i[l];if(o(d))return B.fromReplacingMemberEvent(this._roomId,d)}const c=t?.find(o);if(c)return B.fromMemberEvent(this._roomId,c)}async _updateFragments(e,t,i,r,n,o){const{direction:a}=e,c=[];return Ri(r,e,a),t?(o.set("closedGapWith",t.fragmentId),t.token=null,e.token=null,n.timelineFragments.update(t.fragment),Ri(r,t,a),c.push(e.fragment),c.push(t.fragment)):e.token=i,n.timelineFragments.update(e.fragment),c}async writeFragmentFill(e,t,i,r){const{fragmentId:n,direction:o}=e,{chunk:a,start:c,state:l}=t;let{end:d}=t;if(!Array.isArray(a))throw new Error("Invalid chunk in response");if(typeof d!="string"&&typeof d<"u")throw new Error("Invalid end token in response");const u=await i.timelineFragments.get(this._roomId,n);if(!u)throw new Error(`Unknown fragment: ${n}`);if(e=e.withUpdatedFragment(u),e.token!==c)throw new Error("start is not equal to prev_batch or next_batch");if(a.length===0)return e.edgeReached=!0,await i.timelineFragments.update(e.fragment),{entries:[e],updatedEntries:[],fragments:[]};let h=await this._findFragmentEdgeEventKey(e,i);r.set("lastKey",h.toString());const{nonOverlappingEvents:m,neighbourFragmentEntry:_}=await this._findOverlappingEvents(e,a,i,r),{entries:f,updatedEntries:E}=await this._storeEvents(m,h,o,l,i,r),I=await this._updateFragments(e,_,d,f,i,r);return{entries:f,updatedEntries:E,fragments:I}}}/**
* @license
* Based off baseSortedIndex function in Lodash <https://lodash.com/>
* Copyright JS Foundation and other contributors <https://js.foundation/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/function ct(s,e,t){let i=0,r=s.length;for(;i<r;){let n=i+r>>>1,o=t(e,s[n]);o>0?i=n+1:o<0?r=n:i=r=n}return r}class H_ extends ui{constructor(e,t){super(),this._sourceMap=e,this._comparator=(i,r)=>t(i.value,r.value),this._sortedPairs=null,this._mapSubscription=null}onAdd(e,t){const i={key:e,value:t},r=ct(this._sortedPairs,i,this._comparator);this._sortedPairs.splice(r,0,i),this.emitAdd(r,t)}onRemove(e,t){const i={key:e,value:t},r=ct(this._sortedPairs,i,this._comparator);this._sortedPairs.splice(r,1),this.emitRemove(r,t)}onUpdate(e,t,i){if(!this._sortedPairs)return;const r=this._sortedPairs.findIndex(a=>a.key===e);this._sortedPairs.splice(r,1);const n={key:e,value:t},o=ct(this._sortedPairs,n,this._comparator);this._sortedPairs.splice(o,0,n),r!==o&&this.emitMove(r,o,t),this.emitUpdate(o,t,i)}onReset(){this._sortedPairs=[],this.emitReset()}onSubscribeFirst(){this._mapSubscription=this._sourceMap.subscribe(this),this._sortedPairs=new Array(this._sourceMap.size);let e=0;for(let[t,i]of this._sourceMap)this._sortedPairs[e]={key:t,value:i},++e;this._sortedPairs.sort(this._comparator),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._sortedPairs=null,this._mapSubscription=this._mapSubscription()}get(e){return this._sortedPairs[e].value}get length(){return this._sourceMap.size}[Symbol.iterator](){const e=this._sortedPairs.values();return{next(){const t=e.next();return t.value&&(t.value=t.value.value),t}}}}class Zr extends fn{constructor(){super()}emitReset(){for(let e of this._handlers)e.onReset()}emitAdd(e,t){for(let i of this._handlers)i.onAdd(e,t)}emitUpdate(e,t,i){for(let r of this._handlers)r.onUpdate(e,t,i)}emitRemove(e,t){for(let i of this._handlers)i.onRemove(e,t)}join(...e){return new J_([this].concat(e))}mapValues(e,t){return new Z_(this,e,t)}sortValues(e){return new H_(this,e)}filterValues(e){return new W_(this,e)}}class W_ extends Zr{constructor(e,t){super(),this._source=e,this._filter=t}setFilter(e){this._filter=e,this._subscription&&this._reapplyFilter()}_reapplyFilter(e=!1){if(this._filter){const t=this._included;this._included=this._included||new Map;for(const[i,r]of this._source){const n=this._filter(r,i);if(this._included.set(i,n),!e){const o=t?t.get(i):!0;this._emitForUpdate(o,n,i,r)}}}else{if(this._included&&!e)for(const[t,i]of this._source)this._included.get(t)||this.emitAdd(t,i);this._included=void 0}}onAdd(e,t){if(this._filter)if(this._included){const i=this._filter(t,e);if(this._included.set(e,i),!i)return}else throw new Error("Internal logic error: FilteredMap._included used before initialized");this.emitAdd(e,t)}onRemove(e,t){var i;const r=!this._filter||((i=this._included)==null?void 0:i.get(e));if(this._included)this._included.delete(e),r&&this.emitRemove(e,t);else throw new Error("Internal logic error: FilteredMap._included used before initialized")}onUpdate(e,t,i){if(!!this._included)if(this._filter){const r=this._included.get(e),n=this._filter(t,e);this._included.set(e,n),this._emitForUpdate(r,n,e,t,i)}else this.emitUpdate(e,t,i)}_emitForUpdate(e,t,i,r,n=null){e&&!t?this.emitRemove(i,r):!e&&t?this.emitAdd(i,r):e&&t&&this.emitUpdate(i,r,n)}onSubscribeFirst(){this._subscription=this._source.subscribe(this),this._reapplyFilter(!0),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._included=void 0,this._subscription&&(this._subscription=this._subscription())}onReset(){this._reapplyFilter(),this.emitReset()}[Symbol.iterator](){return new Y_(this._source,this._included)}get size(){var e;let t=0;return(e=this._included)==null||e.forEach(i=>{i&&(t+=1)}),t}get(e){const t=this._source.get(e);if(t&&this._filter(t,e))return t}}class Y_{constructor(e,t){this._included=t,this._sourceIterator=e[Symbol.iterator]()}next(){for(var e;;){const t=this._sourceIterator.next();if(t.done)return t;const i=t.value[0];if((e=this._included)!=null&&e.get(i))return t}}}class J_ extends Zr{constructor(e){super(),this._sources=e}onAdd(e,t,i){if(!this._isKeyAtSourceOccluded(e,t)){const r=this._getValueFromOccludedSources(e,t);r!==void 0&&this.emitRemove(t,r),this.emitAdd(t,i)}}onRemove(e,t,i){if(!this._isKeyAtSourceOccluded(e,t)){this.emitRemove(t,i);const r=this._getValueFromOccludedSources(e,t);r!==void 0&&this.emitAdd(t,r)}}onUpdate(e,t,i,r){!this._subscriptions||this._isKeyAtSourceOccluded(e,t)||this.emitUpdate(t,i,r)}onReset(){this.emitReset()}onSubscribeFirst(){this._subscriptions=this._sources.map(e=>new Q_(e,this).subscribe()),super.onSubscribeFirst()}_isKeyAtSourceOccluded(e,t){const i=this._sources.indexOf(e);for(let r=0;r<i;r+=1)if(this._sources[r].get(t)!==void 0)return!0;return!1}_getValueFromOccludedSources(e,t){const i=this._sources.indexOf(e);for(let r=i+1;r<this._sources.length;r+=1){const o=this._sources[r].get(t);if(o!==void 0)return o}}onUnsubscribeLast(){if(super.onUnsubscribeLast(),this._subscriptions)for(const e of this._subscriptions)e.dispose()}[Symbol.iterator](){return new X_(this._sources)}get size(){return this._sources.reduce((e,t)=>e+t.size,0)}get(e){for(const t of this._sources){const i=t.get(e);if(i)return i}}}class X_{constructor(e){this._sourceIndex=-1,this._encounteredKeys=new Set,this._sources=e}next(){var e;let t;for(;!t;){if(!this._currentIterator){if(this._sourceIndex+=1,this._sources.length<=this._sourceIndex)return{done:!0,value:null};this._currentIterator=this._sources[this._sourceIndex][Symbol.iterator]()}const i=(e=this._currentIterator)==null?void 0:e.next();if(!i||i.done){this._currentIterator=void 0;continue}else{const r=i.value[0];this._encounteredKeys.has(r)||(this._encounteredKeys.add(r),t=i)}}return t}}class Q_{constructor(e,t){this._source=e,this._joinedMap=t,this._subscription=void 0}subscribe(){return this._subscription=this._source.subscribe(this),this}dispose(){this._subscription&&(this._subscription=this._subscription())}onAdd(e,t){this._joinedMap.onAdd(this._source,e,t)}onRemove(e,t){this._joinedMap.onRemove(this._source,e,t)}onUpdate(e,t,i){this._joinedMap.onUpdate(this._source,e,t,i)}onReset(){this._joinedMap.onReset()}}class Z_ extends Zr{constructor(e,t,i){super(),this._source=e,this._mapper=t,this._updater=i,this._mappedValues=new Map}_emitSpontaneousUpdate(e,t){const i=this._mappedValues.get(e);i&&this.emitUpdate(e,i,t)}onAdd(e,t){const i=this._emitSpontaneousUpdate.bind(this,e),r=this._mapper(t,i);this._mappedValues.set(e,r),this.emitAdd(e,r)}onRemove(e){const t=this._mappedValues.get(e);this._mappedValues.delete(e)&&t&&this.emitRemove(e,t)}onUpdate(e,t,i){var r;if(!this._mappedValues)return;const n=this._mappedValues.get(e);n!==void 0&&((r=this._updater)==null||r.call(this,i,n,t),this.emitUpdate(e,n,i))}onSubscribeFirst(){this._subscription=this._source.subscribe(this);for(let[e,t]of this._source){const i=this._emitSpontaneousUpdate.bind(this,e),r=this._mapper(t,i);this._mappedValues.set(e,r)}super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._subscription&&(this._subscription=this._subscription()),this._mappedValues.clear()}onReset(){this._mappedValues.clear(),this.emitReset()}[Symbol.iterator](){return this._mappedValues.entries()}get size(){return this._mappedValues.size}get(e){return this._mappedValues.get(e)}}class Ni extends Zr{constructor(e){super(),this._values=new Map(e)}update(e,t){const i=this._values.get(e);return i!==void 0?(this._values.set(e,i),this.emitUpdate(e,i,t),!0):!1}add(e,t){return this._values.has(e)?!1:(this._values.set(e,t),this.emitAdd(e,t),!0)}remove(e){const t=this._values.get(e);return t!==void 0?(this._values.delete(e),this.emitRemove(e,t),!0):!1}set(e,t){return this._values.has(e)?(this._values.set(e,t),this.update(e,void 0)):this.add(e,t)}reset(){this._values.clear(),this.emitReset()}get(e){return this._values.get(e)}get size(){return this._values.size}[Symbol.iterator](){return this._values.entries()}values(){return this._values.values()}keys(){return this._values.keys()}}function al(s,e,t,i){const r=e.findIndex(s);if(r!==-1){const n=e[r],o=i(n);return o!==!1&&t.emitUpdate(r,n,o),!0}return!1}class cl extends ui{constructor(e){super(),this._items=[],this._comparator=e}setManyUnsorted(e){this.setManySorted(e)}setManySorted(e){for(let t of e)this.set(t)}findAndUpdate(e,t){return al(e,this._items,this,t)}getAndUpdate(e,t,i=null){const r=this.indexOf(e);if(r!==-1){const n=this._items[r],o=t(n,e);this._items[r]=o,this.emitUpdate(r,o,i)}}update(e,t=null){const i=this.indexOf(e);i!==-1&&(this._items[i]=e,this.emitUpdate(i,e,t))}indexOf(e){const t=ct(this._items,e,this._comparator);return t<this._items.length&&this._comparator(this._items[t],e)===0?t:-1}_getNext(e){let t=ct(this._items,e,this._comparator);for(;t<this._items.length&&this._comparator(this._items[t],e)<=0;)t+=1;return this.get(t)}set(e,t=null){const i=ct(this._items,e,this._comparator);i>=this._items.length||this._comparator(this._items[i],e)!==0?(this._items.splice(i,0,e),this.emitAdd(i,e)):(this._items[i]=e,this.emitUpdate(i,e,t))}get(e){return this._items[e]}remove(e){const t=this._items[e];this._items.splice(e,1),this.emitRemove(e,t)}get array(){return this._items}get length(){return this._items.length}[Symbol.iterator](){return new ef(this)}}class ef{constructor(e){this._consumed=!1,this._sortedArray=e,this._current=null}next(){return this._consumed?{value:void 0,done:!0}:(this._current=this._current?this._sortedArray._getNext(this._current):this._sortedArray.get(0),this._current||(this._consumed=!0),{value:this._current,done:this._consumed})}}class tf extends ui{constructor(e,t,i,r){super(),this._sourceUnsubscribe=null,this._mappedValues=null,this._sourceList=e,this._mapper=t,this._updater=i,this._removeCallback=r}findAndUpdate(e,t){return al(e,this._mappedValues,this,t)}get length(){return this._mappedValues.length}[Symbol.iterator](){return this._mappedValues.values()}}function rf(s,e,t){s._mappedValues.splice(e,0,t),s.emitAdd(e,t)}function sf(s,e,t,i){const r=s._mappedValues[e];s._updater&&s._updater(r,i,t),s.emitUpdate(e,r,i)}function nf(s,e){const t=s._mappedValues[e];s._mappedValues.splice(e,1),s._removeCallback&&s._removeCallback(t),s.emitRemove(e,t)}function of(s,e,t){const i=s._mappedValues[e];s._mappedValues.splice(e,1),s._mappedValues.splice(t,0,i),s.emitMove(e,t,i)}function af(s){s._mappedValues=[],s.emitReset()}class cf extends tf{constructor(){super(...arguments),this._eventQueue=null,this._flushing=!1}onSubscribeFirst(){this._sourceUnsubscribe=this._sourceList.subscribe(this),this._eventQueue=[],this._mappedValues=[];let e=0;for(const t of this._sourceList)this._eventQueue.push(new ha(e,t)),e+=1;this._flush()}async _flush(){if(!this._flushing){this._flushing=!0;try{for(;this._eventQueue.length;)await this._eventQueue.shift().run(this)}finally{this._flushing=!1}}}onReset(){this._eventQueue&&(this._eventQueue.push(new hf),this._flush())}onAdd(e,t){this._eventQueue&&(this._eventQueue.push(new ha(e,t)),this._flush())}onUpdate(e,t,i){this._eventQueue&&(this._eventQueue.push(new lf(e,t,i)),this._flush())}onRemove(e){this._eventQueue&&(this._eventQueue.push(new df(e)),this._flush())}onMove(e,t){this._eventQueue&&(this._eventQueue.push(new uf(e,t)),this._flush())}onUnsubscribeLast(){this._sourceUnsubscribe(),this._eventQueue=null,this._mappedValues=null}}class ha{constructor(e,t){this.index=e,this.value=t}async run(e){const t=await e._mapper(this.value);rf(e,this.index,t)}}class lf{constructor(e,t,i){this.index=e,this.value=t,this.params=i}async run(e){sf(e,this.index,this.value,this.params)}}class df{constructor(e){this.index=e}async run(e){nf(e,this.index)}}class uf{constructor(e,t){this.fromIdx=e,this.toIdx=t}async run(e){of(e,this.fromIdx,this.toIdx)}}class hf{async run(e){af(e)}}class pf extends ui{constructor(...e){super(),this._sourceUnsubscribes=null,this._sourceLists=e}_offsetForSource(e){const t=this._sourceLists.indexOf(e);let i=0;for(let r=0;r<t;++r)i+=this._sourceLists[r].length;return i}onSubscribeFirst(){this._sourceUnsubscribes=this._sourceLists.map(e=>e.subscribe(this))}onUnsubscribeLast(){for(const e of this._sourceUnsubscribes)e()}onReset(){this.emitReset();let e=0;for(const t of this)this.emitAdd(e,t),e+=1}onAdd(e,t,i){this.emitAdd(this._offsetForSource(i)+e,t)}onUpdate(e,t,i,r){!this._sourceUnsubscribes||this.emitUpdate(this._offsetForSource(r)+e,t,i)}onRemove(e,t,i){this.emitRemove(this._offsetForSource(i)+e,t)}onMove(e,t,i,r){const n=this._offsetForSource(r);this.emitMove(n+e,n+t,i)}get length(){let e=0;for(let t=0;t<this._sourceLists.length;++t)e+=this._sourceLists[t].length;return e}[Symbol.iterator](){let e=0,t=this._sourceLists[0][Symbol.iterator]();return{next:()=>{let i=t.next();for(;i.done;){if(e+=1,e>=this._sourceLists.length)return i;t=this._sourceLists[e][Symbol.iterator](),i=t.next()}return i}}}}class pa{constructor(e,t){this.decryptRequest=null,this._promise=e(this,t)}complete(){return this._promise}dispose(){this.decryptRequest&&(this.decryptRequest.dispose(),this.decryptRequest=null)}}async function mf(s,e,t,i,r,n){let o=[];const a=n.timelineEvents,c=n.timelineFragments;for(;o.length<i&&e;){let l;t.isForward?l=await a.eventsAfter(s,e,i):l=await a.eventsBefore(s,e,i);let d=l.map(u=>new fe(u,r));if(o=Uu(o,d,t),o.length<i){const u=await c.get(s,e.fragmentId);let h=new be(u,t.isBackward,r);if(Ri(o,h,t),!h.token&&h.hasLinkedFragment){const m=await c.get(s,h.linkedFragmentId);r.add(m);const _=new be(m,t.isForward,r);Ri(o,_,t),e=_.asEventKey()}else e=null}}return o}class ll{constructor({roomId:e,storage:t,fragmentIdComparer:i}){this._roomId=e,this._storage=t,this._fragmentIdComparer=i,this._decryptEntries=null}enableEncryption(e){this._decryptEntries=e}get readTxnStores(){const e=[this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineFragments];return this._decryptEntries&&e.push(this._storage.storeNames.inboundGroupSessions),e}readFrom(e,t,i,r){return new pa(async(n,o)=>{const a=await this._storage.readTxn(this.readTxnStores);return await this._readFrom(e,t,i,n,a,o)},r)}readFromEnd(e,t=null,i){return new pa(async(r,n)=>{const o=t||await this._storage.readTxn(this.readTxnStores),a=await o.timelineFragments.liveFragment(this._roomId);let c;if(!a)c=[];else{this._fragmentIdComparer.add(a);const l=be.end(a,this._fragmentIdComparer),d=l.asEventKey();c=await this._readFrom(d,ze.Backward,e,r,o,n),c.unshift(l)}return c},i)}async readById(e,t){let i=[this._storage.storeNames.timelineEvents];this._decryptEntries&&i.push(this._storage.storeNames.inboundGroupSessions);const r=await this._storage.readTxn(i),n=await r.timelineEvents.getByEventId(this._roomId,e);if(n){const o=new fe(n,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o],r,t).complete(),o}}async _readFrom(e,t,i,r,n,o){const a=await mf(this._roomId,e,t,i,this._fragmentIdComparer,n);if(this._decryptEntries){r.decryptRequest=this._decryptEntries(a,n,o);try{await r.decryptRequest.complete()}finally{r.decryptRequest=null}}return a}}class _f extends fe{get fragmentId(){throw new Error("Cannot access fragmentId for non-persisted EventEntry")}get entryIndex(){throw new Error("Cannot access entryIndex for non-persisted EventEntry")}get isNonPersisted(){return!0}get isRedacting(){return!1}get isRedacted(){return super.isRedacting}}class ff{constructor(e){this._userId=e}get id(){return this._userId}}class Kr{constructor({roomId:e,storage:t,closeCallback:i,fragmentIdComparer:r,pendingEvents:n,clock:o,powerLevelsObservable:a,hsApi:c}){this._roomId=e,this._storage=t,this._closeCallback=i,this._fragmentIdComparer=r,this._disposables=new En,this._pendingEvents=n,this._clock=o,this._remoteEntries=new cl((l,d)=>l.compare(d)),this._ownMember=null,this._timelineReader=new ll({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}),this._readerRequest=null,this._allEntries=null,this._contextEntriesNotInTimeline=new Map,this._decryptEntries=null,this._hsApi=c,this.initializePowerLevels(a)}initializePowerLevels(e){e&&(this._powerLevels=e.get(),this._disposables.track(e.subscribe(t=>this._powerLevels=t)))}async load(e,t,i){const r=await this._storage.readTxn(this._timelineReader.readTxnStores.concat(this._storage.storeNames.roomMembers,this._storage.storeNames.roomState)),n=await r.roomMembers.get(this._roomId,e.id);n?this._ownMember=new B(n):this._ownMember=B.fromUserId(this._roomId,e.id,t);const o=this._disposables.track(this._timelineReader.readFromEnd(20,r,i));try{const a=await o.complete();this._loadContextEntriesWhereNeeded(a),this._setupEntries(a)}finally{this._disposables.disposeTracked(o)}}_setupEntries(e){this._remoteEntries.setManySorted(e),this._pendingEvents?this._localEntries=new cf(this._pendingEvents,t=>this._mapPendingEventToEntry(t),(t,i)=>{t.notifyUpdate(i)},t=>this._applyAndEmitLocalRelationChange(t,i=>i.removeLocalRelation(t))):this._localEntries=new xp,this._allEntries=new pf(this._remoteEntries,this._localEntries)}async _mapPendingEventToEntry(e){let t;e.eventType===Ce&&(t=await this._getOrLoadEntry(e.relatedTxnId,e.relatedEventId));const i=new R_({pendingEvent:e,member:this._ownMember,clock:this._clock,redactingEntry:t});return this._loadContextEntriesWhereNeeded([i]),this._applyAndEmitLocalRelationChange(i,r=>r.addLocalRelation(i)),i}_applyAndEmitLocalRelationChange(e,t){var i,r;const n=o=>{const a=t(o);return a||!1};if(this._findAndUpdateEntryById(e.pendingEvent.relatedTxnId,e.relatedEventId,n),e.redactingEntry){const o=(i=e.redactingEntry.pendingEvent)==null?void 0:i.relatedTxnId;this._findAndUpdateEntryById(o,e.redactingEntry.relatedEventId,n),(r=e.redactingEntry.contextForEntries)==null||r.forEach(a=>this._emitUpdateForEntry(a,"contextEntry"))}}_findAndUpdateEntryById(e,t,i){let r=!1;e&&(r=this._localEntries.findAndUpdate(n=>n.id===e,i)),!r&&t&&this._remoteEntries.findAndUpdate(n=>n.id===t,i)}async getOwnAnnotationEntry(e,t){const i=await this._storage.readWriteTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations]),r=await i.timelineRelations.getForTargetAndType(this._roomId,e,at);for(const n of r){const o=await i.timelineEvents.getByEventId(this._roomId,n.sourceEventId);if(o&&o.event.sender===this._ownMember.userId&&et(o.event).key===t){const a=new fe(o,this._fragmentIdComparer);return this._addLocalRelationsToNewRemoteEntries([a]),a}}return null}updateOwnMember(e){this._ownMember=e}_addLocalRelationsToNewRemoteEntries(e){var t;if(!!((t=this._localEntries)!=null&&t.hasSubscriptions))for(const i of this._localEntries){if(i.relatedEventId){const r=e.find(n=>n.id===i.relatedEventId);r?.addLocalRelation(i)}if(i.redactingEntry){const r=i.redactingEntry.relatedEventId,n=e.find(o=>o.id===r);n?.addLocalRelation(i)}}}static _entryUpdater(e,t){var i;return(i=e.contextForEntries)==null||i.forEach(r=>r.setContextEntry(t)),t.updateFrom(e),t}replaceEntries(e){var t;this._addLocalRelationsToNewRemoteEntries(e);for(const i of e)try{this._remoteEntries.getAndUpdate(i,Kr._entryUpdater);const r=this._contextEntriesNotInTimeline.get(i.id);r&&(Kr._entryUpdater(r,i),this._contextEntriesNotInTimeline.set(i.id,i)),(t=i.contextForEntries)==null||t.forEach(n=>this._emitUpdateForEntry(n,"contextEntry"))}catch(r){if(r.name==="CompareError")continue;throw r}}addEntries(e){this._addLocalRelationsToNewRemoteEntries(e),this._updateEntriesFetchedFromHomeserver(e),this._moveEntryToRemoteEntries(e),this._loadContextEntriesWhereNeeded(e),this._remoteEntries.setManySorted(e)}_updateEntriesFetchedFromHomeserver(e){var t;for(const i of e){const r=this._contextEntriesNotInTimeline.get(i.relatedEventId);r?.isNonPersisted&&r?.addLocalRelation(i)&&((t=r.contextForEntries)==null||t.forEach(n=>this._emitUpdateForEntry(n,"contextEntry")))}}_moveEntryToRemoteEntries(e){for(const t of e){const i=this._contextEntriesNotInTimeline.get(t.id);i&&(i.contextForEntries.forEach(r=>{r.setContextEntry(t),this._emitUpdateForEntry(r,"contextEntry")}),this._contextEntriesNotInTimeline.delete(t.id))}}_emitUpdateForEntry(e,t){const i=e.isPending?e.id:null,r=e.isPending?null:e.id;this._findAndUpdateEntryById(i,r,()=>t)}async _loadContextEntriesWhereNeeded(e){for(const t of e){if(!t.contextEventId)continue;const i=t.contextEventId;let r=e.find(n=>n.id===i);r||(r=this._findLoadedEventById(i)),r?t.setContextEntry(r):this._loadContextEntryNotInTimeline(t)}}async _loadContextEntryNotInTimeline(e){const t=e.contextEventId;let i=await this._getEventFromStorage(t);i||(i=await this._getEventFromHomeserver(t)),i&&(this._contextEntriesNotInTimeline.set(t,i),e.setContextEntry(i),this._emitUpdateForEntry(e,"contextEntry"))}_findLoadedEventById(e){var t;return(t=this.getByEventId(e))!=null?t:this._contextEntriesNotInTimeline.get(e)}async _getEventFromStorage(e){return await this._timelineReader.readById(e)}async _getEventFromHomeserver(e){const t=await this._hsApi.context(this._roomId,e,0).response(),i=t.event.sender,r=t.state.find(a=>a.type===_e&&a.user_id===i),n={event:t.event,displayName:r.content.displayname,avatarUrl:r.content.avatar_url},o=new _f(n,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o]).complete(),o}async loadAtTop(e){if(this._disposables.isDisposed)return!0;const t=this._remoteEntries.array.find(r=>!!r.eventType);if(!t)return!0;const i=this._disposables.track(this._timelineReader.readFrom(t.asEventKey(),ze.Backward,e));try{const r=await i.complete();return this.addEntries(r),r.length<e}finally{this._disposables.disposeTracked(i)}}async _getOrLoadEntry(e,t){var i;if(e){for(const r of this._localEntries)if(r.id===e)return r}return t?(i=this.getByEventId(t))!=null?i:await this._getEventFromStorage(t):null}getByEventId(e){for(let t=0;t<this._remoteEntries.length;t+=1){const i=this._remoteEntries.get(t);if(i.id===e)return i}return null}get entries(){return this._allEntries}get remoteEntries(){return this._remoteEntries.array}dispose(){this._closeCallback&&(this._disposables.dispose(),this._closeCallback(),this._closeCallback=null)}enableEncryption(e){this._decryptEntries=e,this._timelineReader.enableEncryption(e)}get powerLevels(){return this._powerLevels}get me(){return this._ownMember}}async function gf({roomId:s,storage:e,txn:t}){return t||(t=await e.readTxn([e.storeNames.roomMembers])),(await t.roomMembers.getAll(s)).map(r=>new B(r))}async function yf({summary:s,syncToken:e,roomId:t,hsApi:i,storage:r,setChangedMembersMap:n},o){const a=new Map;n(a);const c=await i.members(t,{at:e},{log:o}).response(),l=await r.readWriteTxn([r.storeNames.roomSummary,r.storeNames.roomMembers]);let d,u;try{d=s.writeHasFetchedMembers(!0,l);const{roomMembers:h}=l,m=c.chunk;if(!Array.isArray(m))throw new Error("malformed");o.set("members",m.length),u=await Promise.all(m.map(async _=>{const f=_?.state_key;if(!f)throw new Error("malformed");const E=a.get(f);if(E)return E;{const I=B.fromMemberEvent(t,_);return I&&h.set(I.serialize()),I}}))}catch(h){throw l.abort(),h}finally{n(null)}return await l.complete(),s.applyChanges(d),u}async function vf(s,e){const{summary:t}=s;return t.data.hasFetchedMembers?gf(s):e.wrapOrRun(s.log,"fetchMembers",i=>yf(s,i))}async function wf(s,e){const t=await bf(s),{summary:i}=s;return!i.data.hasFetchedMembers&&!t?e.wrapOrRun(s.log,"fetchMember",r=>Sf(s,r)):t}async function bf({roomId:s,userId:e,storage:t}){const r=await(await t.readTxn([t.storeNames.roomMembers])).roomMembers.get(s,e);return r?new B(r):null}async function Sf({roomId:s,userId:e,hsApi:t,storage:i},r){let n;try{n=await t.state(s,"m.room.member",e,{log:r}).response()}catch(c){if(c.name==="HomeServerError"&&c.errcode==="M_NOT_FOUND")return null;throw c}const o=new B({roomId:s,userId:e,membership:n.membership,avatarUrl:n.avatar_url,displayName:n.displayname}),a=await i.readWriteTxn([i.storeNames.roomMembers]);try{a.roomMembers.set(o.serialize())}catch(c){throw a.abort(),c}return await a.complete(),o}class Ef{constructor(e){this._retentionCount=1,this._freeCallback=e}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._freeCallback()}}class If extends Ef{constructor({members:e,closeCallback:t}){super(t),this._members=new Ni;for(const i of e)this._members.add(i.userId,i)}afterSync(e){for(const[t,i]of e.entries())this._members.set(t,i.member)}get members(){return this._members}}function Xs(s,e,t){const i=e.joinCount+e.inviteCount-1;if(s.length>=i)if(s.length>1){const r=s[s.length-1];return s.slice(0,s.length-1).map(o=>o.name).join(", ")+" and "+r.name}else{const r=s[0];return r?r.name:(t.log({l:"could get get other member name",length:s.length,otherMember:!!r,otherMemberMembership:r?.membership}),"Unknown DM Name")}else return s.length<i?s.map(r=>r.name).join(", ")+` and ${i} others`:null}class kn{constructor(e){this._roomId=e,this._members=new Map}async calculateChanges(e,t,i){const r=new Map,n=[];for(const o of this._members.keys())e.indexOf(o)===-1&&n.push(o);for(const[o,a]of t.entries())(this._members.has(o)||e.indexOf(o)!==-1)&&r.set(o,a.member);for(const o of e)if(!this._members.has(o)&&!r.has(o)){const a=await i.roomMembers.get(this._roomId,o);if(a){const c=new B(a);r.set(c.userId,c)}}return{updatedHeroMembers:r.values(),removedUserIds:n}}applyChanges({updatedHeroMembers:e,removedUserIds:t},i,r){for(const o of t)this._members.delete(o);for(const o of e)this._members.set(o.userId,o);const n=Array.from(this._members.values()).sort((o,a)=>o.name.localeCompare(a.name));this._roomName=Xs(n,i,r)}get roomName(){return this._roomName}get roomAvatarUrl(){if(this._members.size===1)for(const e of this._members.values())return e.avatarUrl;return null}get roomAvatarColorId(){if(this._members.size===1)for(const e of this._members.keys())return e;return null}}class Tf{constructor(e){this._map=new Map,this._notifyEmpty=e}observe(e,t=null){let i=this._map.get(e);return i||(i=new xf(this,t,e),this._map.set(e,i)),i}updateEvents(e){for(let t=0;t<e.length;t+=1){const i=e[t],r=this._map.get(i.id);r?.update(i)}}_remove(e){this._map.delete(e),this._map.size===0&&this._notifyEmpty()}}class xf extends di{constructor(e,t,i){super(),this._eventMap=e,this._entry=t,this._id=i,Promise.resolve().then(()=>{this.hasSubscriptions||(this._eventMap._remove(this._id),this._eventMap=null)})}subscribe(e){if(!this._eventMap)throw new Error("ObservedEvent expired, subscribe right after calling room.observeEvent()");return super.subscribe(e)}onUnsubscribeLast(){this._eventMap._remove(this._id),this._eventMap=null,super.onUnsubscribeLast()}update(e){this._entry=e,this.emit(this._entry)}get(){return this._entry}}function kf(s){return s||Cu.item}const Rf="m.room.power_levels";class Nr{constructor({powerLevelEvent:e,createEvent:t,ownUserId:i,membership:r}){this._plEvent=e,this._createEvent=t,this._ownUserId=i,this._membership=r}canRedactFromSender(e){return e===this._ownUserId&&this._membership==="join"?!0:this.canRedact}canSendType(e){return this._myLevel>=this._getEventTypeLevel(e)}get canRedact(){return this._myLevel>=this._getActionLevel("redact")}get _myLevel(){return this._membership!=="join"?Number.MIN_SAFE_INTEGER:this.getUserLevel(this._ownUserId)}getUserLevel(e){var t,i,r,n;if(this._plEvent){let o=(i=(t=this._plEvent.content)==null?void 0:t.users)==null?void 0:i[e];if(typeof o!="number"&&(o=(r=this._plEvent.content)==null?void 0:r.users_default),typeof o=="number")return o}else if(this._createEvent&&e===((n=this._createEvent.content)==null?void 0:n.creator))return 100;return 0}_getActionLevel(e){var t;const i=(t=this._plEvent)==null?void 0:t.content[e];return typeof i=="number"?i:50}_getEventTypeLevel(e){var t,i,r;const n=(i=(t=this._plEvent)==null?void 0:t.content.events)==null?void 0:i[e];if(typeof n=="number")return n;{const o=(r=this._plEvent)==null?void 0:r.content.events_default;return typeof o=="number"?o:0}}}const Af="m.room.encrypted";class dl extends Xi{constructor({roomId:e,storage:t,hsApi:i,mediaRepository:r,emitCollectionChange:n,user:o,createRoomEncryption:a,getSyncToken:c,platform:l}){super(),this._roomId=e,this._storage=t,this._hsApi=i,this._mediaRepository=r,this._summary=new v_(e),this._fragmentIdComparer=new B_([]),this._emitCollectionChange=n,this._timeline=null,this._user=o,this._changedMembersDuringSync=null,this._memberList=null,this._createRoomEncryption=a,this._roomEncryption=null,this._getSyncToken=c,this._platform=l,this._observedEvents=null,this._powerLevels=null,this._powerLevelLoading=null,this._observedMembers=null}async _eventIdsToEntries(e,t){const i=[];return await Promise.all(e.map(async r=>{const n=await t.timelineEvents.getByEventId(this._roomId,r);n&&i.push(new fe(n,this._fragmentIdComparer))})),i}_getAdditionalTimelineRetryEntries(e,t){let i=this._roomEncryption.filterUndecryptedEventEntriesForKeys(this._timeline.remoteEntries,t);const r=e.reduce((n,o)=>(n.add(o.id),n),new Set);return i=i.filter(n=>!r.has(n.id)),i}async notifyRoomKey(e,t,i){var r;if(!this._roomEncryption)return;const n=await this._storage.readTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.inboundGroupSessions]);let o=await this._eventIdsToEntries(t,n);if(this._timeline){const a=this._getAdditionalTimelineRetryEntries(o,[e]);o=o.concat(a)}if(o.length){await this._decryptEntries(Rt.Retry,o,n,i).complete(),(r=this._timeline)==null||r.replaceEntries(o);const c=this._summary.data.applyTimelineEntries(o,!1,!1);await this._summary.writeAndApplyData(c,this._storage)&&this._emitUpdate()}}_setEncryption(e){return e&&!this._roomEncryption?(this._roomEncryption=e,this._timeline&&this._timeline.enableEncryption(this._decryptEntries.bind(this,Rt.Timeline)),!0):!1}_decryptEntries(e,t,i,r=null){return new Cf(async(o,a)=>{if(i||(i=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions])),o.cancelled)return;const c=t.filter(_=>_.eventType===Af).map(_=>_.event);if(o.preparation=await this._roomEncryption.prepareDecryptAll(c,null,e,i),o.cancelled)return;const l=await o.preparation.decrypt();if(o.preparation=null,o.cancelled)return;const d=[this._storage.storeNames.groupSessionDecryptions],u=this._isTimelineOpen;u&&d.push(this._storage.storeNames.deviceIdentities);const h=await this._storage.readWriteTxn(d);let m;try{m=await l.write(h,a),u&&await m.verifySenders(h)}catch(_){throw h.abort(),_}await h.complete(),m.applyToEntries(t),this._observedEvents&&this._observedEvents.updateEvents(t)},kf(r))}async _getSyncRetryDecryptEntries(e,t,i){let n=(await Promise.all(e.map(async o=>{const a=await t.getEventIdsForMissingKey(o,i);if(a)return this._eventIdsToEntries(a,i)}))).reduce((o,a)=>a?o.concat(a):o,[]);if(this._timeline){const a=this._getAdditionalTimelineRetryEntries(n,e).map(c=>c.clone());n=n.concat(a)}return n}async load(e,t,i){i.set("id",this.id);try{if(e&&this._summary.load(e),this._summary.data.encryption){const r=this._createRoomEncryption(this,this._summary.data.encryption);this._setEncryption(r)}if(this._summary.data.needsHeroes){this._heroes=new kn(this._roomId);const r=await this._heroes.calculateChanges(this._summary.data.heroes,[],t);this._heroes.applyChanges(r,this._summary.data,i)}}catch(r){throw new uc(`Could not load room ${this._roomId}`,r)}}async observeMember(e){this._observedMembers||(this._observedMembers=new Map);const t=this._observedMembers.get(e);if(t)return t;const i=await wf({summary:this._summary,roomId:this._roomId,userId:e,storage:this._storage,hsApi:this._hsApi},this._platform.logger);if(!i)return null;const r=new Gs(i,()=>this._observedMembers.delete(e));return this._observedMembers.set(e,r),r}async loadMemberList(e=void 0,t=null){if(this._memberList)return this._memberList.retain(),this._memberList;{const i=await vf({summary:this._summary,roomId:this._roomId,hsApi:this._hsApi,storage:this._storage,txn:e,syncToken:this._getSyncToken(),setChangedMembersMap:r=>this._changedMembersDuringSync=r,log:t},this._platform.logger);return this._memberList=new If({members:i,closeCallback:()=>{this._memberList=null}}),this._memberList}}fillGap(e,t,i=null){return this._platform.logger.wrapOrRun(i,"fillGap",async r=>{if(r.set("id",this.id),r.set("fragment",e.fragmentId),r.set("dir",e.direction.asApiString()),e.edgeReached){r.set("edgeReached",!0);return}const n=await this._hsApi.messages(this._roomId,{from:e.token,dir:e.direction.asApiString(),limit:t,filter:{lazy_load_members:!0,include_redundant_members:!0}},{log:r}).response(),o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents,this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations,this._storage.storeNames.timelineFragments]);let a,c;try{a=await this._writeGapFill(n.chunk,o,r);const l=new nl({roomId:this._roomId,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});c=await new z_({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,relationWriter:l}).writeFragmentFill(e,n,o,r)}catch(l){throw o.abort(),l}await o.complete(),this._roomEncryption&&await this._decryptEntries(Rt.Timeline,c.entries,null,r).complete();for(const l of c.fragments)this._fragmentIdComparer.add(l);a&&this._applyGapFill(a),this._timeline&&(this._timeline.replaceEntries(c.updatedEntries),this._timeline.addEntries(c.entries))})}async _writeGapFill(e,t,i){}_applyGapFill(){}get name(){if(this._heroes)return this._heroes.roomName;const e=this._summary.data;return e.name?e.name:e.canonicalAlias?e.canonicalAlias:null}get id(){return this._roomId}get avatarUrl(){return this._summary.data.avatarUrl?this._summary.data.avatarUrl:this._heroes?this._heroes.roomAvatarUrl:null}get avatarColorId(){return this._roomId}get lastMessageTimestamp(){return this._summary.data.lastMessageTimestamp}get isLowPriority(){const e=this._summary.data.tags;return!!(e&&e["m.lowpriority"])}get isEncrypted(){return!!this._summary.data.encryption}get isJoined(){return this.membership==="join"}get isLeft(){return this.membership==="leave"}get canonicalAlias(){return this._summary.data.canonicalAlias}get joinedMemberCount(){return this._summary.data.joinCount}get mediaRepository(){return this._mediaRepository}get membership(){return this._summary.data.membership}isDirectMessageForUserId(e){if(this._summary.data.dmUserId===e)return!0;{const{heroes:t,joinCount:i,inviteCount:r}=this._summary.data;if(t&&t.includes(e)&&i+r===2)return!0}return!1}async _loadPowerLevels(){const e=await this._storage.readTxn([this._storage.storeNames.roomState]),t=await e.roomState.get(this._roomId,"m.room.power_levels","");if(t)return new Nr({powerLevelEvent:t.event,ownUserId:this._user.id,membership:this.membership});const i=await e.roomState.get(this._roomId,"m.room.create","");if(i)return new Nr({createEvent:i.event,ownUserId:this._user.id,membership:this.membership});{const r=this.membership;return new Nr({ownUserId:this._user.id,membership:r})}}async observePowerLevels(){this._powerLevelLoading&&await this._powerLevelLoading;let e=this._powerLevels;if(!e){this._powerLevelLoading=this._loadPowerLevels();const t=await this._powerLevelLoading;e=new Gs(t,()=>{this._powerLevels=null}),this._powerLevels=e,this._powerLevelLoading=null}return e}enableKeyBackup(e){var t;(t=this._roomEncryption)==null||t.enableKeyBackup(e),this._timeline&&e&&this._platform.logger.run("enableKeyBackup",i=>this._roomEncryption.restoreMissingSessionsFromBackup(this._timeline.remoteEntries,i))}get _isTimelineOpen(){return!!this._timeline}_emitUpdate(){this.emit("change"),this._emitCollectionChange(this)}openTimeline(e=null){return this._platform.logger.wrapOrRun(e,"open timeline",async t=>{if(t.set("id",this.id),this._timeline)throw new Error("not dealing with load race here for now");this._timeline=new Kr({roomId:this.id,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,pendingEvents:this._getPendingEvents(),closeCallback:()=>{this._timeline=null,this._roomEncryption&&this._roomEncryption.notifyTimelineClosed()},clock:this._platform.clock,logger:this._platform.logger,powerLevelsObservable:await this.observePowerLevels(),hsApi:this._hsApi});try{this._roomEncryption&&this._timeline.enableEncryption(this._decryptEntries.bind(this,Rt.Timeline)),await this._timeline.load(this._user,this.membership,t)}catch(i){throw this._timeline.dispose(),i}return this._timeline})}_getPendingEvents(){return null}observeEvent(e){this._observedEvents||(this._observedEvents=new Tf(()=>{this._observedEvents=null}));let t=null;this._timeline&&(t=this._timeline.getByEventId(e));const i=this._observedEvents.observe(e,t);return t||this._readEventById(e).then(r=>{i.update(r)}).catch(r=>{console.warn(`could not load event ${e} from storage`,r)}),i}async _readEventById(e){return await new ll({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}).readById(e)}dispose(){var e,t;(e=this._roomEncryption)==null||e.dispose(),(t=this._timeline)==null||t.dispose()}}class Cf{constructor(e,t){this._cancelled=!1,this.preparation=null,this._promise=t.wrap("decryptEntries",i=>e(this,i))}complete(){return this._promise}get cancelled(){return this._cancelled}dispose(){this._cancelled=!0,this.preparation&&this.preparation.dispose()}}function $r(){const e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16);return"t"+"0".repeat(14-e.length)+e}function ma(s){return s.startsWith("t")&&s.length===15}class Nf{constructor({roomId:e,storage:t,hsApi:i,pendingEvents:r}){r=r||[],this._roomId=e,this._storage=t,this._hsApi=i,this._pendingEvents=new cl((n,o)=>n.queueIndex-o.queueIndex),this._pendingEvents.setManyUnsorted(r.map(n=>this._createPendingEvent(n))),this._isSending=!1,this._offline=!1,this._roomEncryption=null,this._currentQueueIndex=0}_createPendingEvent(e,t=null){const i=new A_({data:e,remove:()=>this._removeEvent(i),emitUpdate:r=>this._pendingEvents.update(i,r),attachments:t});return i}enableEncryption(e){this._roomEncryption=e}_sendLoop(e){this._isSending=!0,this._sendLoopLogItem=e.runDetached("send queue flush",async t=>{try{for(const i of this._pendingEvents)await t.wrap("send event",async r=>{r.set("queueIndex",i.queueIndex);try{this._currentQueueIndex=i.queueIndex,await this._sendEvent(i,r)}catch(n){n instanceof Se?(this._offline=!0,r.set("offline",!0),i.setWaiting()):(r.catch(n),n.name==="HomeServerError"&&(n.statusCode===400||n.statusCode===403||n.statusCode===404)?(r.set("remove",!0),await i.abort()):i.setError(n))}finally{this._currentQueueIndex=0}})}finally{this._isSending=!1,this._sendLoopLogItem=null}})}async _sendEvent(e,t){if(e.needsUpload&&(await t.wrap("upload attachments",i=>e.uploadAttachments(this._hsApi,i)),await this._tryUpdateEvent(e)),e.needsEncryption){e.setEncrypting();const i=e.contentForEncryption,{type:r,content:n}=await t.wrap("encrypt",o=>this._roomEncryption.encrypt(e.eventType,i,this._hsApi,o));e.setEncrypted(r,n),await this._tryUpdateEvent(e)}if(e.needsSending){await e.send(this._hsApi,t);const i=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{await this._tryUpdateEventWithTxn(e,i),await this._resolveRemoteIdInPendingRelations(e.txnId,e.remoteId,i)}catch(r){throw i.abort(),r}await i.complete()}}async _resolveRemoteIdInPendingRelations(e,t,i){const r=this._pendingEvents.array.filter(n=>n.relatedTxnId===e&&n.relatedEventId!==t);for(const n of r)n.setRelatedEventId(t),await this._tryUpdateEventWithTxn(n,i);return r}async removeRemoteEchos(e,t,i){const r=[];for(const n of e){const o=n.unsigned&&n.unsigned.transaction_id;let a;if(o?a=this._pendingEvents.array.findIndex(c=>c.txnId===o):a=this._pendingEvents.array.findIndex(c=>c.remoteId===n.event_id),a!==-1){const c=this._pendingEvents.get(a),l=n.event_id;i.log({l:"removeRemoteEcho",queueIndex:c.queueIndex,remoteId:l,txnId:o}),t.pendingEvents.remove(c.roomId,c.queueIndex),r.push(c),await this._resolveRemoteIdInPendingRelations(o,l,t)}}return r}async _removeEvent(e){if(this._pendingEvents.array.indexOf(e)!==-1){const i=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{i.pendingEvents.remove(e.roomId,e.queueIndex)}catch{i.abort()}await i.complete();const r=this._pendingEvents.array.indexOf(e);r!==-1&&this._pendingEvents.remove(r)}e.dispose()}emitRemovals(e){for(const t of e){const i=this._pendingEvents.array.indexOf(t);i!==-1&&this._pendingEvents.remove(i),t.dispose()}}resumeSending(e){this._offline=!1,this._pendingEvents.length&&e.wrap("resumeSending",t=>{t.set("id",this._roomId),t.set("pendingEvents",this._pendingEvents.length),this._isSending||this._sendLoop(t),this._sendLoopLogItem&&t.refDetached(this._sendLoopLogItem)})}async enqueueEvent(e,t,i,r){const n=mt(t);let o=null;if(n){const a=Tn(n);if(ma(a)&&(o=a,rl(n,null)),n.rel_type===at&&this._pendingEvents.array.some(l=>{const d=mt(l.content);return l.eventType===e&&d&&d.key===n.key&&(l.relatedTxnId===o||d.event_id===n.event_id)})){r.set("already_annotating",!0);return}}await this._enqueueEvent(e,t,i,o,null,r)}async _enqueueEvent(e,t,i,r,n,o){const a=await this._createAndStoreEvent(e,t,r,n,i);this._pendingEvents.set(a),o.set("queueIndex",a.queueIndex),o.set("pendingEvents",this._pendingEvents.length),!this._isSending&&!this._offline&&this._sendLoop(o),this._sendLoopLogItem&&o.refDetached(this._sendLoopLogItem)}async enqueueRedaction(e,t,i){if(this._pendingEvents.array.some(a=>a.eventType===Ce&&(a.relatedTxnId===e||a.relatedEventId===e))){i.set("already_redacting",!0);return}let n,o;if(ma(e)){n=e;const a=e,c=this._pendingEvents.array.find(l=>l.txnId===a);if(c&&!c.remoteId&&c.status!==P.Sending){i.set("remove",n),await c.abort();return}else if(c)o=c.remoteId;else return}else{o=e;const a=this._pendingEvents.array.find(c=>c.remoteId===o);a&&(n=a.txnId)}i.set("relatedTxnId",n),i.set("relatedEventId",o),await this._enqueueEvent(Ce,{reason:t},null,n,o,i)}get pendingEvents(){return this._pendingEvents}async _tryUpdateEvent(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{this._tryUpdateEventWithTxn(e,t)}catch(i){throw t.abort(),i}await t.complete()}async _tryUpdateEventWithTxn(e,t){await t.pendingEvents.exists(e.roomId,e.queueIndex)&&t.pendingEvents.update(e.data)}async _createAndStoreEvent(e,t,i,r,n){const o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);let a;try{const c=o.pendingEvents,l=await c.getMaxQueueIndex(this._roomId)||0,u=Math.max(l,this._currentQueueIndex)+1,h=e!==Ce&&e!==w_&&!!this._roomEncryption;a=this._createPendingEvent({roomId:this._roomId,queueIndex:u,eventType:e,content:t,relatedTxnId:i,relatedEventId:r,txnId:$r(),needsEncryption:h,needsUpload:!!n},n),c.add(a.data)}catch(c){throw o.abort(),c}return await o.complete(),a}dispose(){for(const e of this._pendingEvents)e.dispose()}}class ul{constructor({filename:e,blob:t,platform:i}){this._filename=e,this._unencryptedBlob=t,this._transferredBlob=this._unencryptedBlob,this._platform=i,this._mxcUrl=null,this._encryptionInfo=null,this._uploadRequest=null,this._aborted=!1,this._error=null,this._sentBytes=0}get size(){return this._transferredBlob.size}get sentBytes(){return this._sentBytes}abort(){var e;(e=this._uploadRequest)==null||e.abort()}get localPreview(){return this._unencryptedBlob}async encrypt(){if(this._encryptionInfo)throw new Error("already encrypted");const{info:e,blob:t}=await s_(this._platform,this._transferredBlob);this._transferredBlob=t,this._encryptionInfo=e}async upload(e,t,i){this._uploadRequest=e.uploadAttachment(this._transferredBlob,this._filename,{uploadProgress:n=>{this._sentBytes=n,t()},log:i});const{content_uri:r}=await this._uploadRequest.response();this._mxcUrl=r}applyToContent(e,t){if(!this._mxcUrl)throw new Error("upload has not finished");let i=e.substr(0,e.lastIndexOf("url"));wr(`${i}info.size`,t,this._transferredBlob.size),wr(`${i}info.mimetype`,t,this._unencryptedBlob.mimeType),this._encryptionInfo?wr(`${i}file`,t,Object.assign(this._encryptionInfo,{mimetype:this._unencryptedBlob.mimeType,url:this._mxcUrl})):wr(`${i}url`,t,this._mxcUrl)}dispose(){this._unencryptedBlob.dispose(),this._transferredBlob.dispose()}}function wr(s,e,t){const i=s.split(".");let r=e;for(let o=0;o<i.length-1;o+=1){const a=i[o];r[a]||(r[a]={}),r=r[a]}const n=i[i.length-1];r[n]=t}const Mf="m.room.encrypted";class Df extends dl{constructor(e){super(e);const{pendingEvents:t}=e,i=new nl({roomId:this.id,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});this._syncWriter=new $_({roomId:this.id,fragmentIdComparer:this._fragmentIdComparer,relationWriter:i,memberWriter:new G_(this.id)}),this._sendQueue=new Nf({roomId:this.id,storage:this._storage,hsApi:this._hsApi,pendingEvents:t})}_setEncryption(e){return super._setEncryption(e)?(this._sendQueue.enableEncryption(this._roomEncryption),!0):!1}async prepareSync(e,t,i,r,n){var o;n.set("id",this.id),i&&n.set("newKeys",i.length);let a=this._summary.data.applySyncResponse(e,t,this._user.id),c=this._roomEncryption;!c&&a.encryption&&(n.set("enableEncryption",!0),c=this._createRoomEncryption(this,a.encryption));let l,d;if(c){let u=((o=e?.timeline)==null?void 0:o.events)||[];i&&(l=await this._getSyncRetryDecryptEntries(i,c,r),l.length&&(n.set("retry",l.length),u=u.concat(l.map(h=>h.event)))),u=u.filter(h=>h?.type===Mf),u.length&&(d=await c.prepareDecryptAll(u,i,Rt.Sync,r))}return{roomEncryption:c,summaryChanges:a,decryptPreparation:d,decryptChanges:null,retryEntries:l}}async afterPrepareSync(e,t){e.decryptPreparation&&await t.wrap("decrypt",async i=>{i.set("id",this.id),e.decryptChanges=await e.decryptPreparation.decrypt(),e.decryptPreparation=null},t.level.Detail)}async writeSync(e,t,{summaryChanges:i,decryptChanges:r,roomEncryption:n,retryEntries:o},a,c){var l;c.set("id",this.id);const d=i.isNewJoin(this._summary.data);d&&(a.roomState.removeAllForRoom(this.id),a.roomMembers.removeAllForRoom(this.id));const{entries:u,updatedEntries:h,newLiveKey:m,memberChanges:_}=await c.wrap("syncWriter",w=>this._syncWriter.writeSync(e,d,i.hasFetchedMembers,a,w),c.level.Detail);if(r){const w=await c.wrap("decryptChanges",x=>r.write(a,x));c.set("decryptionResults",w.results.size),c.set("decryptionErrors",w.errors.size),this._isTimelineOpen&&await w.verifySenders(a),w.applyToEntries(u),o?.length&&(w.applyToEntries(o),h.push(...o))}c.set("newEntries",u.length),c.set("updatedEntries",h.length);let f;n&&(f=await n.writeSync(e,_,a,c),c.set("shouldFlushKeyShares",f.shouldFlush));const E=u.concat(h);i=i.applyTimelineEntries(E,t,!this._isTimelineOpen,this._user.id),i.membership!=="join"?a.roomSummary.remove(this.id):i=this._summary.writeData(i,a),i&&c.set("summaryChanges",i.changedKeys(this._summary.data));let I;i?.needsHeroes&&(this._heroes||(this._heroes=new kn(this._roomId)),I=await this._heroes.calculateChanges(i.heroes,_,a));let T;Array.isArray((l=e.timeline)==null?void 0:l.events)&&(T=await this._sendQueue.removeRemoteEchos(e.timeline.events,a,c));const k=this._getPowerLevelsEvent(e);return{summaryChanges:i,roomEncryption:n,newEntries:u,updatedEntries:h,newLiveKey:m,removedPendingEvents:T,memberChanges:_,heroChanges:I,powerLevelsEvent:k,encryptionChanges:f}}afterSync(e,t){const{summaryChanges:i,newEntries:r,updatedEntries:n,newLiveKey:o,removedPendingEvents:a,memberChanges:c,powerLevelsEvent:l,heroChanges:d,roomEncryption:u,encryptionChanges:h}=e;if(t.set("id",this.id),this._syncWriter.afterSync(o),this._setEncryption(u),this._roomEncryption&&this._roomEncryption.afterSync(h),c.size){if(this._changedMembersDuringSync)for(const[_,f]of c.entries())this._changedMembersDuringSync.set(_,f.member);if(this._memberList&&this._memberList.afterSync(c),this._observedMembers&&this._updateObservedMembers(c),this._timeline){for(const[_,f]of c.entries())if(_===this._user.id){this._timeline.updateOwnMember(f.member);break}}}let m=!1;if(i&&(this._summary.applyChanges(i),this._summary.data.needsHeroes||(this._heroes=null),m=!0),this._heroes&&d){const _=this.name;this._heroes.applyChanges(d,this._summary.data,t),_!==this.name&&(m=!0)}l&&this._updatePowerLevels(l),m&&this._emitUpdate(),this._timeline&&(this._timeline.replaceEntries(n),this._timeline.addEntries(r)),this._observedEvents&&(this._observedEvents.updateEvents(n),this._observedEvents.updateEvents(r)),a&&this._sendQueue.emitRemovals(a)}_updateObservedMembers(e){for(const[t,i]of e){const r=this._observedMembers.get(t);r&&r.set(i.member)}}_getPowerLevelsEvent(e){var t,i,r;const n=a=>a.state_key===""&&a.type===Rf;return(r=(t=e.timeline)==null?void 0:t.events.find(n))!=null?r:(i=e.state)==null?void 0:i.events.find(n)}_updatePowerLevels(e){if(this._powerLevels){const t=new Nr({powerLevelEvent:e,ownUserId:this._user.id,membership:this.membership});this._powerLevels.set(t)}}needsAfterSyncCompleted({encryptionChanges:e}){return e?.shouldFlush}async afterSyncCompleted(e,t){t.set("id",this.id),this._roomEncryption&&await this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,null,t)}start(e,t){if(this._roomEncryption){const i=e?.get("share_room_key");i&&t.wrapDetached("flush room keys",r=>(r.set("id",this.id),this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,i,r)))}this._sendQueue.resumeSending(t)}async load(e,t,i){try{await super.load(e,t,i),await this._syncWriter.load(t,i)}catch(r){throw new uc(`Could not load room ${this._roomId}`,r)}}async _writeGapFill(e,t,i){return await this._sendQueue.removeRemoteEchos(e,t,i)}_applyGapFill(e){this._sendQueue.emitRemovals(e)}sendEvent(e,t,i,r=null){return this._platform.logger.wrapOrRun(r,"send",n=>(n.set("id",this.id),this._sendQueue.enqueueEvent(e,t,i,n)))}sendRedaction(e,t,i=null){return this._platform.logger.wrapOrRun(i,"redact",r=>(r.set("id",this.id),this._sendQueue.enqueueRedaction(e,t,r)))}async ensureMessageKeyIsShared(e=null){if(!!this._roomEncryption)return this._platform.logger.wrapOrRun(e,"ensureMessageKeyIsShared",t=>(t.set("id",this.id),this._roomEncryption.ensureMessageKeyIsShared(this._hsApi,t)))}get avatarColorId(){var e;return((e=this._heroes)==null?void 0:e.roomAvatarColorId)||this._roomId}get isUnread(){return this._summary.data.isUnread}get notificationCount(){return this._summary.data.notificationCount}get highlightCount(){return this._summary.data.highlightCount}get isTrackingMembers(){return this._summary.data.isTrackingMembers}async _getLastEventId(){var e;const t=this._syncWriter.lastMessageKey;if(t){const r=await(await this._storage.readTxn([this._storage.storeNames.timelineEvents])).timelineEvents.get(this._roomId,t);return(e=r?.event)==null?void 0:e.event_id}}async clearUnread(e=null){if(this.isUnread||this.notificationCount)return await this._platform.logger.wrapOrRun(e,"clearUnread",async t=>{t.set("id",this.id);const i=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary]);let r;try{r=this._summary.writeClearUnread(i)}catch(n){throw i.abort(),n}await i.complete(),this._summary.applyChanges(r),this._emitUpdate();try{const n=await this._getLastEventId();n&&await this._hsApi.receipt(this._roomId,"m.read",n)}catch(n){if(n.name!=="ConnectionError")throw n}})}leave(e=null){return this._platform.logger.wrapOrRun(e,"leave room",async t=>{t.set("id",this.id),await this._hsApi.leave(this.id,{log:t}).response()})}_getPendingEvents(){return this._sendQueue.pendingEvents}writeIsTrackingMembers(e,t){return this._summary.writeIsTrackingMembers(e,t)}applyIsTrackingMembersChanges(e){this._summary.applyChanges(e)}createAttachment(e,t){return new ul({blob:e,filename:t,platform:this._platform})}dispose(){super.dispose(),this._sendQueue.dispose()}}class Pf extends dl{constructor(e){super(e),this._releaseCallback=e.releaseCallback,this._forgetCallback=e.forgetCallback,this._retentionCount=1,this._kickDetails=null,this._kickedBy=null}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._releaseCallback()}async _getKickAuthor(e,t){const i=await t.roomMembers.get(this.id,e);return i?new B(i):B.fromUserId(this.id,e,"join")}async load(e,t,i){const{summary:r,kickDetails:n}=e;return this._kickDetails=n,this._kickDetails&&(this._kickedBy=await this._getKickAuthor(this._kickDetails.sender,t)),super.load(r,t,i)}async writeSync(e,t,i,r,n){if(n.set("id",this.id),i==="leave"){const o=Of(t,this._user.id);if(o||e){const a=o||this._kickDetails;let c;o&&(c=await this._getKickAuthor(o.sender,r));const l=e||this._summary.data;return r.archivedRoomSummary.set({summary:l.serialize(),kickDetails:a}),{kickDetails:a,kickedBy:c,summaryData:l}}}else i==="join"&&r.archivedRoomSummary.remove(this.id);return{}}afterSync({summaryData:e,kickDetails:t,kickedBy:i},r){r.set("id",this.id),e&&this._summary.applyChanges(e),t&&(this._kickDetails=t),i&&(this._kickedBy=i),this._emitUpdate()}get isKicked(){var e;return((e=this._kickDetails)==null?void 0:e.membership)==="leave"}get isBanned(){var e;return((e=this._kickDetails)==null?void 0:e.membership)==="ban"}get kickedBy(){return this._kickedBy}get kickReason(){var e;return(e=this._kickDetails)==null?void 0:e.reason}isArchived(){return!0}forget(e=null){return this._platform.logger.wrapOrRun(e,"forget room",async t=>{t.set("id",this.id),await this._hsApi.forget(this.id,{log:t}).response();const i=this._storage.storeNames,r=await this._storage.readWriteTxn([i.roomState,i.archivedRoomSummary,i.roomMembers,i.timelineEvents,i.timelineFragments,i.timelineRelations,i.pendingEvents,i.inboundGroupSessions,i.groupSessionDecryptions,i.operations]);r.roomState.removeAllForRoom(this.id),r.archivedRoomSummary.remove(this.id),r.roomMembers.removeAllForRoom(this.id),r.timelineEvents.removeAllForRoom(this.id),r.timelineFragments.removeAllForRoom(this.id),r.timelineRelations.removeAllForRoom(this.id),r.pendingEvents.removeAllForRoom(this.id),r.inboundGroupSessions.removeAllForRoom(this.id),r.groupSessionDecryptions.removeAllForRoom(this.id),await r.operations.removeAllForScope(this.id),await r.complete(),this._retentionCount=0,this._releaseCallback(),this._forgetCallback(this.id)})}join(e=null){return this._platform.logger.wrapOrRun(e,"rejoin archived room",async t=>{await this._hsApi.join(this.id,{log:t}).response()})}}function Of(s,e){var t,i;const r=el(s,(n,o)=>(o.type===_e&&o.state_key===e&&o.sender!==o.state_key&&(n=o),n),null);if(r)return{membership:(t=r.content)==null?void 0:t.membership,reason:(i=r.content)==null?void 0:i.reason,sender:r.sender}}async function Uf(s,e,t){const i=await Promise.all(s.map(async r=>{const n=await e.profile(r,{log:t}).response();return new Bf(r,n.displayname,n.avatar_url)}));return i.sort((r,n)=>r.name.localeCompare(n.name)),i}class Bf{constructor(e,t,i){this.userId=e,this.displayName=t,this.avatarUrl=i}get name(){return this.displayName||this.userId}}class Lf{constructor(e){this.userId=e}get displayName(){}get name(){return this.userId}get avatarUrl(){}}function Ff(s){switch(s){case je.DirectMessage:case je.Private:return!0;case je.Public:return!1}}function Vf(s){switch(s){case je.DirectMessage:return"trusted_private_chat";case je.Private:return"private_chat";case je.Public:return"public_chat"}}class Kf extends Xi{constructor(e,t,i,r,n,o){var a;if(super(),this.id=e,this.options=t,this.updateCallback=i,this.mediaRepository=r,this.platform=n,this.profiles=[],this._isCancelled=!1,this.isEncrypted=t.isEncrypted===void 0?Ff(t.type):t.isEncrypted,t.name)this._calculatedName=t.name;else{const c={joinCount:1,inviteCount:((a=t.invites)==null?void 0:a.length)||0},l=(t.invites||[]).map(d=>new Lf(d));this._calculatedName=Xs(l,c,o)}}async create(e,t){try{let i;if(this.options.avatar){const{avatar:o}=this.options,a=new ul({filename:o.name,blob:o.blob,platform:this.platform});await a.upload(e,()=>{},t),i={info:o.info},a.applyToContent("url",i)}const r={is_direct:this.options.type===je.DirectMessage,preset:Vf(this.options.type),initial_state:[]};this.options.name&&(r.name=this.options.name),this.options.topic&&(r.topic=this.options.topic),this.options.invites&&(r.invite=this.options.invites),this.options.alias&&(r.room_alias_name=this.options.alias),this.options.isFederationDisabled===!0&&(r.creation_content={"m.federate":!1}),this.options.powerLevelContentOverride&&(r.power_level_content_override=this.options.powerLevelContentOverride),this.isEncrypted&&r.initial_state.push(Nu()),i&&r.initial_state.push({type:"m.room.avatar",state_key:"",content:i});const n=await e.createRoom(r,{log:t}).response();this._roomId=n.room_id}catch(i){this._error=i}this.emitChange()}async loadProfiles(e,t){try{if(!this.options.name&&this.options.invites){this.profiles=await Uf(this.options.invites,e,t);const i={joinCount:1,inviteCount:this.options.invites.length};this._calculatedName=Xs(this.profiles,i,t),this.emitChange()}}catch{}}emitChange(e){this.updateCallback(this,e),this.emit("change")}get avatarColorId(){var e,t,i;return(i=(t=(e=this.options.invites)==null?void 0:e[0])!=null?t:this._roomId)!=null?i:this.id}get avatarUrl(){var e,t;return(t=(e=this.profiles)==null?void 0:e[0])==null?void 0:t.avatarUrl}get avatarBlobUrl(){var e,t;return(t=(e=this.options.avatar)==null?void 0:e.blob)==null?void 0:t.url}get roomId(){return this._roomId}get name(){return this._calculatedName}get isBeingCreated(){return!0}get error(){return this._error}cancel(){this._isCancelled||(this.dispose(),this._isCancelled=!0,this.emitChange("isCancelled"))}get isCancelled(){return this._isCancelled}dispose(){this.options.avatar&&this.options.avatar.blob.dispose()}async adjustDirectMessageMapIfNeeded(e,t,i,r){if(!this.options.invites||this.options.type!==je.DirectMessage)return;const n=this.options.invites[0],o="m.direct";await r.wrap("set "+o,async a=>{try{const c=await t.readWriteTxn([t.storeNames.accountData]);let l;try{l=await c.accountData.get(o),l||(l={type:o,content:{}});const d=l.content;let u=d[n];u||(d[n]=u=[]),u.push(this._roomId),c.accountData.set(l),await c.complete()}catch(d){throw c.abort(),d}await i.setAccountData(e.id,o,l.content,{log:a}).response()}catch(c){a.catch(c)}})}}class $f extends Xi{constructor({roomId:e,user:t,hsApi:i,mediaRepository:r,emitCollectionRemove:n,emitCollectionUpdate:o,platform:a}){super(),this._roomId=e,this._user=t,this._hsApi=i,this._emitCollectionRemove=n,this._emitCollectionUpdate=o,this._mediaRepository=r,this._platform=a,this._inviteData=null,this._accepting=!1,this._rejecting=!1,this._accepted=!1,this._rejected=!1}get isInvite(){return!0}get id(){return this._roomId}get name(){return this._inviteData.name||this._inviteData.canonicalAlias}get isDirectMessage(){return this._inviteData.isDirectMessage}get avatarUrl(){return this._inviteData.avatarUrl}get avatarColorId(){return this._inviteData.avatarColorId||this.id}get timestamp(){return this._inviteData.timestamp}get isEncrypted(){return this._inviteData.isEncrypted}get inviter(){return this._inviter}isDirectMessageForUserId(e){return this.isDirectMessage&&this._inviter.userId===e}get isPublic(){return this._inviteData.joinRule==="public"}get canonicalAlias(){return this._inviteData.canonicalAlias}async accept(e=null){await this._platform.logger.wrapOrRun(e,"acceptInvite",async t=>{this._accepting=!0,this._emitChange("accepting"),await this._hsApi.join(this._roomId,{log:t}).response()})}async reject(e=null){await this._platform.logger.wrapOrRun(e,"rejectInvite",async t=>{this._rejecting=!0,this._emitChange("rejecting"),await this._hsApi.leave(this._roomId,{log:t}).response()})}get accepting(){return this._accepting}get accepted(){return this._accepted}get rejecting(){return this._rejecting}get rejected(){return this._rejected}get mediaRepository(){return this._mediaRepository}_emitChange(e){this.emit("change"),this._emitCollectionUpdate(this,e)}load(e,t){t.set("id",this.id),this._inviteData=e,this._inviter=e.inviter?new B(e.inviter):null}async writeSync(e,t,i,r){var n;if(e==="invite"){r.set("id",this.id),r.set("add",!0);const o=(n=t.invite_state)==null?void 0:n.events;if(!Array.isArray(o))return null;const a=this._createSummaryData(o);let c;!a.name&&!a.canonicalAlias&&(c=await this._createHeroes(o,r));const l=this._getMyInvite(o);if(!l)return null;const d=this._getInviter(l,o),u=this._createData(o,l,d,a,c);return i.invites.set(u),{inviteData:u,inviter:d}}else return r.set("id",this.id),r.set("membership",e),i.invites.remove(this.id),{removed:!0,membership:e}}afterSync(e,t){t.set("id",this.id),e&&(e.removed?(this._accepting=!1,this._rejecting=!1,e.membership==="join"?this._accepted=!0:this._rejected=!0,this.emit("change")):(this._inviteData=e.inviteData,this._inviter=e.inviter))}_createData(e,t,i,r,n){const o=n?n.roomName:r.name,a=n?n.roomAvatarUrl:r.avatarUrl,c=n?.roomAvatarColorId||this.id;return{roomId:this.id,isEncrypted:!!r.encryption,isDirectMessage:r.isDirectMessage,name:o,avatarUrl:a,avatarColorId:c,canonicalAlias:r.canonicalAlias,timestamp:this._platform.clock.now(),joinRule:this._getJoinRule(e),inviter:i?.serialize()}}_createSummaryData(e){return e.reduce((t,i)=>tl(t,i,this._user.id),new Fe(null,this.id))}async _createHeroes(e,t){const i=e.filter(d=>d.type===_e),r=i.filter(d=>d.state_key!==this._user.id),n=r.reduce((d,u)=>{const h=B.fromMemberEvent(this.id,u);return d.set(h.userId,new Tc(h,null)),d},new Map),o=r.map(d=>d.state_key),a=new kn(this.id),c=await a.calculateChanges(o,n,null),l=new Fe(null,this.id);return l.joinCount=i.reduce((d,u)=>{var h;return d+(((h=u.content)==null?void 0:h.membership)==="join"?1:0)},0),l.inviteCount=i.reduce((d,u)=>{var h;return d+(((h=u.content)==null?void 0:h.membership)==="invite"?1:0)},0),a.applyChanges(c,l,t),a}_getMyInvite(e){return e.find(t=>t.type===_e&&t.state_key===this._user.id)}_getInviter(e,t){const i=t.find(r=>r.type===_e&&r.state_key===e.sender);if(i)return B.fromMemberEvent(this.id,i)}_getJoinRule(e){var t;const i=e.find(r=>r.type==="m.room.join_rules");return i?(t=i.content)==null?void 0:t.join_rule:null}}class kt{constructor(e){this._description=e}static httpPusher(e,t,i,r){return new kt({kind:"http",append:!0,data:Object.assign({},r,{url:e+"/_matrix/push/v1/notify"}),pushkey:i,app_id:t,app_display_name:"Hydrogen",device_display_name:"Hydrogen",lang:"en"})}static createDefaultPayload(e){return{session_id:e}}async enable(e,t){try{t.set("endpoint",new URL(this._description.data.endpoint).host)}catch{t.set("endpoint",null)}await e.setPusher(this._description,{log:t}).response()}async disable(e,t){const i=Object.assign({},this._description,{kind:null});await e.setPusher(i,{log:t}).response()}serialize(){return this._description}equals(e){return this._description.app_id!==e._description.app_id||this._description.pushkey!==e._description.pushkey?!1:JSON.stringify(this._description.data)===JSON.stringify(e._description.data)}}function si(s,e){return Rn(s,e,()=>[],(t,i)=>t.push(i))}function Rn(s,e,t,i){return s.reduce((r,n)=>{const o=e(n);let a=r.get(o);return a||(a=t(),r.set(o,a)),i(a,n),r},new Map)}function _a(s,e){return s.reduce((t,i)=>{const r=e(i);return t[r]?t[r]+=1:t[r]=1,t},{})}class jf{constructor({storage:e}){this._storage=e,this._olmDecryption=null,this._megolmDecryption=null}enableEncryption({olmDecryption:e,megolmDecryption:t}){this._olmDecryption=e,this._megolmDecryption=t}obtainSyncLock(e){var t;return(t=this._olmDecryption)==null?void 0:t.obtainDecryptionLock(e)}async prepareSync(e,t,i,r){r.set("messageTypes",_a(e,a=>a.type));const n=e.filter(a=>a.type==="m.room.encrypted");if(!this._olmDecryption){r.log("can't decrypt, encryption not enabled",r.level.Warn);return}const o=n.filter(a=>{var c;return((c=a.content)==null?void 0:c.algorithm)===vn});if(o.length){const a=await this._olmDecryption.decryptAll(o,t,i);r.set("decryptedTypes",_a(a.results,l=>{var d;return(d=l.event)==null?void 0:d.type}));for(const l of a.errors)r.child("decrypt_error").catch(l);const c=this._megolmDecryption.roomKeysFromDeviceMessages(a.results,r);return new Gf(a,c)}}async writeSync(e,t){return e.olmDecryptChanges.write(t),(await Promise.all(e.newRoomKeys.map(r=>this._megolmDecryption.writeRoomKey(r,t)))).some(r=>!!r)}}class Gf{constructor(e,t){this.olmDecryptChanges=e,this.newRoomKeys=t,this.newKeysByRoom=si(t,i=>i.roomId)}}const Ti=me+"olmAccount",Qs=me+"areDeviceKeysUploaded",Mr=me+"serverOTKCount";async function fa(s,e,t,i,r){const n=s.pickle(e),o=await r.readWriteTxn([r.storeNames.session]);try{o.session.add(Ti,n),o.session.add(Qs,t),o.session.add(Mr,i)}catch(a){throw o.abort(),a}await o.complete()}class Ot{static async load({olm:e,pickleKey:t,hsApi:i,userId:r,deviceId:n,olmWorker:o,txn:a}){const c=await a.session.get(Ti);if(c){const l=new e.Account,d=await a.session.get(Qs);l.unpickle(t,c);const u=await a.session.get(Mr);return new Ot({pickleKey:t,hsApi:i,account:l,userId:r,deviceId:n,areDeviceKeysUploaded:d,serverOTKCount:u,olm:e,olmWorker:o})}}static async adoptDehydratedDevice({olm:e,dehydratedDevice:t,pickleKey:i,hsApi:r,userId:n,olmWorker:o,storage:a}){const c=t.adoptUnpickledOlmAccount(),l=JSON.parse(c.one_time_keys()),u=Object.entries(l.curve25519).length,h=!0;return await fa(c,i,h,u,a),new Ot({pickleKey:i,hsApi:r,account:c,userId:n,deviceId:t.deviceId,areDeviceKeysUploaded:h,serverOTKCount:u,olm:e,olmWorker:o})}static async create({olm:e,pickleKey:t,hsApi:i,userId:r,deviceId:n,olmWorker:o,storage:a}){const c=new e.Account;o?await o.createAccountAndOTKs(c,c.max_number_of_one_time_keys()):(c.create(),c.generate_one_time_keys(c.max_number_of_one_time_keys()));const l=!1,d=0;return a&&await fa(c,t,l,d,a),new Ot({pickleKey:t,hsApi:i,account:c,userId:r,deviceId:n,areDeviceKeysUploaded:l,serverOTKCount:d,olm:e,olmWorker:o})}constructor({pickleKey:e,hsApi:t,account:i,userId:r,deviceId:n,areDeviceKeysUploaded:o,serverOTKCount:a,olm:c,olmWorker:l}){this._olm=c,this._pickleKey=e,this._hsApi=t,this._account=i,this._userId=r,this._deviceId=n,this._areDeviceKeysUploaded=o,this._serverOTKCount=a,this._olmWorker=l,this._identityKeys=JSON.parse(this._account.identity_keys())}get identityKeys(){return this._identityKeys}setDeviceId(e){this._deviceId=e}async uploadKeys(e,t,i){var r;const n=JSON.parse(this._account.one_time_keys()),o=Object.entries(n.curve25519);if(o.length||!this._areDeviceKeysUploaded){const a={};if(!this._areDeviceKeysUploaded){i.set("identity",!0);const d=JSON.parse(this._account.identity_keys());a.device_keys=this._deviceKeysPayload(d)}o.length&&(i.set("otks",!0),a.one_time_keys=this._oneTimeKeysPayload(o));const c=t?this._deviceId:void 0,l=await this._hsApi.uploadKeys(c,a,{log:i}).response();this._serverOTKCount=(r=l?.one_time_key_counts)==null?void 0:r.signed_curve25519,i.set("serverOTKCount",this._serverOTKCount),await this._updateSessionStorage(e,d=>{o.length&&(this._account.mark_keys_as_published(),d?.set(Ti,this._account.pickle(this._pickleKey)),d?.set(Mr,this._serverOTKCount)),this._areDeviceKeysUploaded||(this._areDeviceKeysUploaded=!0,d?.set(Qs,this._areDeviceKeysUploaded))})}}async generateOTKsIfNeeded(e,t){const i=this._account.max_number_of_one_time_keys(),r=Math.floor(i/2);if(this._serverOTKCount<r){const n=JSON.parse(this._account.one_time_keys()),a=Object.entries(n.curve25519).length,c=r-a-this._serverOTKCount;return c>0&&await t.wrap("generate otks",l=>{l.set("max",i),l.set("server",this._serverOTKCount),l.set("unpublished",a),l.set("new",c),l.set("limit",r),this._account.generate_one_time_keys(c),this._updateSessionStorage(e,d=>{d.set(Ti,this._account.pickle(this._pickleKey))})}),!0}return!1}createInboundOlmSession(e,t){const i=new this._olm.Session;try{return i.create_inbound_from(this._account,e,t),i}catch(r){throw i.free(),r}}async createOutboundOlmSession(e,t){const i=new this._olm.Session;try{return this._olmWorker?await this._olmWorker.createOutboundOlmSession(this._account,i,e,t):i.create_outbound(this._account,e,t),i}catch(r){throw i.free(),r}}writeRemoveOneTimeKey(e,t){this._account.remove_one_time_keys(e),t.session.set(Ti,this._account.pickle(this._pickleKey))}writeSync(e,t,i){const r=e.signed_curve25519;if(Number.isSafeInteger(r)&&r!==this._serverOTKCount)return t.session.set(Mr,r),i.set("otkCount",r),r}afterSync(e){Number.isSafeInteger(e)&&(this._serverOTKCount=e)}_deviceKeysPayload(e){const t={user_id:this._userId,device_id:this._deviceId,algorithms:[vn,De],keys:{}};for(const[i,r]of Object.entries(e))t.keys[`${i}:${this._deviceId}`]=r;return this.signObject(t),t}_oneTimeKeysPayload(e){const t={};for(const[i,r]of e){const n={key:r};this.signObject(n),t[`signed_curve25519:${i}`]=n}return t}async _updateSessionStorage(e,t){if(e){const i=await e.readWriteTxn([e.storeNames.session]);try{await t(i.session)}catch(r){throw i.abort(),r}await i.complete()}else await t(void 0)}signObject(e){const t=e.signatures||{},i=e.unsigned;delete e.signatures,delete e.unsigned,t[this._userId]=t[this._userId]||{},t[this._userId]["ed25519:"+this._deviceId]=this._account.sign(nc.stringify(e)),e.signatures=t,i!==void 0&&(e.unsigned=i)}pickleWithKey(e){return this._account.pickle(e)}dispose(){this._account.free(),this._account=void 0}}class An{constructor(e,t){this._id=e,this._keyDescription=t}get id(){return this._id}get passphraseParams(){var e;return(e=this._keyDescription)==null?void 0:e.passphrase}get algorithm(){var e;return(e=this._keyDescription)==null?void 0:e.algorithm}async isCompatible(e,t){if(this.algorithm==="m.secret_storage.v1.aes-hmac-sha2"){const i=this._keyDescription;if(i.mac){const r=await qf(e.binaryKey,i.iv,t);return i.mac===r}else if(i.passphrase){const r=e.description._keyDescription;return r.passphrase?i.passphrase.algorithm===r.passphrase.algorithm&&i.passphrase.iterations===r.passphrase.iterations&&i.passphrase.salt===r.passphrase.salt:!1}}return!1}}class Qi{constructor(e,t){this._keyDescription=e,this._binaryKey=t}withDescription(e){return new Qi(e,this._binaryKey)}get description(){return this._keyDescription}get id(){return this._keyDescription.id}get binaryKey(){return this._binaryKey}get algorithm(){return this._keyDescription.algorithm}}async function qf(s,e,t){const{crypto:i,encoding:r}=t,{utf8:n,base64:o}=r,{derive:a,aes:c,hmac:l}=i,d=o.decode(e),u=new Uint8Array(8),h="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",m=n.encode(""),_=await a.hkdf(s,u,m,"SHA-256",512),f=_.slice(0,32),E=_.slice(32),I=await c.encryptCTR({key:f,iv:d,data:n.encode(h)}),T=await l.compute(E,I,"SHA-256");return o.encode(T)}const zf=5e5,Hf=256;async function Wf(s,e,t){const{passphraseParams:i}=s;if(!i)throw new Error("not a passphrase key");if(i.algorithm!=="m.pbkdf2")throw new Error(`Unsupported passphrase algorithm: ${i.algorithm}`);const{utf8:r}=t.encoding,n=await t.crypto.derive.pbkdf2(r.encode(e),i.iterations||zf,r.encode(i.salt),"SHA-512",i.bits||Hf);return new Qi(s,n)}const wi=[139,1];function Yf(s,e,t,i){const r=i.encoding.base58.decode(e.replace(/ /g,""));let n=0;for(const a of r)n^=a;if(n!==0)throw new Error("Incorrect parity");for(let a=0;a<wi.length;++a)if(r[a]!==wi[a])throw new Error("Incorrect prefix");if(r.length!==wi.length+t.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");const o=Uint8Array.from(r.slice(wi.length,wi.length+t.PRIVATE_KEY_LENGTH));return new Qi(s,o)}const Cn=`${me}ssssKey`,ga=`${me}keyBackupVersion`;async function hl(s){var e;const t=await s.readTxn([s.storeNames.accountData]),i=await t.accountData.get("m.secret_storage.default_key"),r=(e=i?.content)==null?void 0:e.key;if(!r)return;const n=await t.accountData.get(`m.secret_storage.key.${r}`);if(!!n)return new An(r,n.content)}async function Jf(s,e,t){const i=await t.session.get(ga);return t.session.set(ga,e),t.session.set(Cn,{id:s.id,binaryKey:s.binaryKey}),i}async function Xf(s){const e=await s.session.get(Cn);if(!e)return;const t=await s.accountData.get(`m.secret_storage.key.${e.id}`);if(t)return new Qi(new An(e.id,t.content),e.binaryKey)}async function Qf(s){s.session.remove(Cn)}async function Zf(s,e,t,i,r){const n=await hl(t);if(!n)throw new Error("Could not find a default secret storage key in account data");return await pl(s,e,n,i,r)}async function pl(s,e,t,i,r){let n;if(s===1)n=await Wf(t,e,i);else if(s===0)n=Yf(t,e,r,i);else throw new Error(`Invalid type: ${s}`);return n}async function eg(s,e,t){const i=await hl(e);if(await i?.isCompatible(s,t))return s.withDescription(i)}const ml="org.matrix.msc2697.v1.olm.libolm_pickle";async function tg(s,e,t,i){try{const r=await s.getDehydratedDevice({log:i}).response();if(r.device_data.algorithm===ml)return new rg(r,e,t)}catch(r){r.name!=="HomeServerError"&&(i.error=r);return}}async function ig(s,e,t,i,r){var n;const a=(await e.createDehydratedDevice({device_data:{algorithm:ml,account:s.pickleWithKey(t.binaryKey.slice()),passphrase:((n=t.description)==null?void 0:n.passphraseParams)||{}},initial_device_display_name:i}).response()).device_id;return s.setDeviceId(a),await s.uploadKeys(void 0,!0,r),a}class rg{constructor(e,t,i){this._dehydratedDevice=e,this._olm=t,this._platform=i}async decrypt(e,t){const i=new An("dehydrated_device",this._dehydratedDevice.device_data.passphrase),r=await pl(e,t,i,this._platform,this._olm),n=new this._olm.Account;try{const o=this._dehydratedDevice.device_data.account;return n.unpickle(r.binaryKey.slice(),o),new sg(this._dehydratedDevice,n,r)}catch(o){if(n.free(),o.message==="OLM.BAD_ACCOUNT_KEY")return;throw o}}get deviceId(){return this._dehydratedDevice.device_id}}class sg{constructor(e,t,i){this._dehydratedDevice=e,this._account=t,this._key=i}async claim(e,t){try{return(await e.claimDehydratedDevice(this.deviceId,{log:t}).response()).success}catch{return!1}}adoptUnpickledOlmAccount(){const e=this._account;return this._account=void 0,e}get deviceId(){return this._dehydratedDevice.device_id}get key(){return this._key}dispose(){var e;(e=this._account)==null||e.free(),this._account=void 0}}class ng{tryTake(){return this._promise?!1:(this._promise=new Promise(e=>{this._resolve=e}),!0)}async take(){for(;!this.tryTake();)await this.released()}get isTaken(){return!!this._promise}release(){if(this._resolve){this._promise=void 0;const e=this._resolve;this._resolve=void 0,e()}}released(){return this._promise}}class og{constructor(e){this.locks=e}release(){for(const e of this.locks)e.release()}}function _l(s,e,t,i){return{session:s.pickle(i),sessionId:s.session_id(),senderKey:e,lastUsed:t}}class jr{constructor(e,t,i,r=!1){this.data=e,this.pickleKey=t,this.olm=i,this.isNew=r,this.isModified=r}static create(e,t,i,r,n){const o=_l(t,e,n,r);return new jr(o,r,i,!0)}get id(){return this.data.sessionId}load(){const e=new this.olm.Session;return e.unpickle(this.pickleKey,this.data.session),e}unload(e){e.free()}save(e){this.data.session=e.pickle(this.pickleKey),this.isModified=!0}}class fl{constructor(e,t,i){this.event=e,this.senderCurve25519Key=t,this.claimedEd25519Key=i,this.roomTracked=!0}setDevice(e){this.device=e}setRoomNotTrackedYet(){this.roomTracked=!1}get isVerified(){return this.device?this.device.ed25519Key===this.claimedEd25519Key:!1}get isUnverified(){return this.device?!this.isVerified:!this.isVerificationUnknown}get isVerificationUnknown(){return!this.device&&!this.roomTracked}}var Gr=(s=>(s[s.PreKey=0]="PreKey",s[s.Normal=1]="Normal",s))(Gr||{});const ya=4;function gl(s){s.sort((e,t)=>t.data.lastUsed-e.data.lastUsed)}class ag{constructor(e,t,i,r,n,o){this.account=e,this.pickleKey=t,this.now=i,this.ownUserId=r,this.olm=n,this.senderKeyLock=o}async obtainDecryptionLock(e){var t;const i=new Set;for(const n of e){const o=(t=n.content)==null?void 0:t.sender_key;o&&i.add(o)}const r=await Promise.all(Array.from(i).map(n=>this.senderKeyLock.takeLock(n)));return new og(r)}async decryptAll(e,t,i){try{const r=si(e,d=>{var u;return(u=d.content)==null?void 0:u.sender_key}),n=this.now(),o=await Promise.all(Array.from(r.entries()).map(([d,u])=>this._decryptAllForSenderKey(d,u,n,i))),a=o.reduce((d,u)=>d.concat(u.results),[]),c=o.reduce((d,u)=>d.concat(u.errors),[]),l=o.map(d=>d.senderKeyDecryption);return new lg(l,a,c,this.account,t)}catch(r){throw t.release(),r}}async _decryptAllForSenderKey(e,t,i,r){const n=await this._getSessions(e,r),o=new cg(e,n,i),a=[],c=[];for(const l of t)try{const d=this._decryptForSenderKey(o,l,i);a.push(d)}catch(d){c.push(d)}return{results:a,errors:c,senderKeyDecryption:o}}_decryptForSenderKey(e,t,i){const r=e.senderKey,n=this._getMessageAndValidateEvent(t);let o;try{o=e.decrypt(n)}catch(a){throw new te("OLM_BAD_ENCRYPTED_MESSAGE",t,{senderKey:r,error:a.message})}if(typeof o!="string"&&n.type===Gr.PreKey){let a;try{a=this._createSessionAndDecrypt(r,n,i)}catch(c){throw new te(`Could not create inbound olm session: ${c.message}`,t,{senderKey:r,error:c})}e.addNewSession(a.session),o=a.plaintext}if(typeof o=="string"){let a;try{a=JSON.parse(o)}catch(c){throw new te("PLAINTEXT_NOT_JSON",t,{plaintext:o,error:c})}return this._validatePayload(a,t),new fl(a,r,a.keys.ed25519)}else throw new te("OLM_NO_MATCHING_SESSION",t,{knownSessionIds:e.sessions.map(a=>a.id)})}_createSessionAndDecrypt(e,t,i){let r;const n=this.account.createInboundOlmSession(e,t.body);try{r=n.decrypt(t.type,t.body);const o=jr.create(e,n,this.olm,this.pickleKey,i);return o.unload(n),{session:o,plaintext:r}}catch(o){throw n.free(),o}}_getMessageAndValidateEvent(e){var t;const i=(t=e.content)==null?void 0:t.ciphertext;if(!i)throw new te("OLM_MISSING_CIPHERTEXT",e);const r=i?.[this.account.identityKeys.curve25519];if(!r)throw new te("OLM_NOT_INCLUDED_IN_RECIPIENTS",e);return r}async _getSessions(e,t){const r=(await t.olmSessions.getAll(e)).map(n=>new jr(n,this.pickleKey,this.olm));return gl(r),r}_validatePayload(e,t){var i,r,n;if(e.sender!==t.sender)throw new te("OLM_FORWARDED_MESSAGE",t,{sentBy:t.sender,encryptedBy:e.sender});if(e.recipient!==this.ownUserId)throw new te("OLM_BAD_RECIPIENT",t,{recipient:e.recipient});if(((i=e.recipient_keys)==null?void 0:i.ed25519)!==this.account.identityKeys.ed25519)throw new te("OLM_BAD_RECIPIENT_KEY",t,{key:(r=e.recipient_keys)==null?void 0:r.ed25519});if(!e.type)throw new te("missing type on payload",t,{payload:e});if(typeof((n=e.keys)==null?void 0:n.ed25519)!="string")throw new te("Missing or invalid claimed ed25519 key on payload",t,{payload:e})}}class cg{constructor(e,t,i){this.senderKey=e,this.sessions=t,this.timestamp=i}addNewSession(e){this.sessions.unshift(e)}decrypt(e){for(const t of this.sessions){const i=this.decryptWithSession(t,e);if(typeof i=="string")return gl(this.sessions),i}}getModifiedSessions(){return this.sessions.filter(e=>e.isModified)}get hasNewSessions(){return this.sessions.some(e=>e.isNew)}decryptWithSession(e,t){if(t.type===void 0||t.body===void 0)throw new Error("Invalid message without type or body");const i=e.load();try{if(t.type===Gr.PreKey&&!i.matches_inbound(t.body))return;try{const r=i.decrypt(t.type,t.body);return e.save(i),e.data.lastUsed=this.timestamp,r}catch(r){if(t.type===Gr.PreKey)throw new Error(`Error decrypting prekey message with existing session id ${e.id}: ${r.message}`);return}}finally{e.unload(i)}}}class lg{constructor(e,t,i,r,n){this.senderKeyDecryptions=e,this.results=t,this.errors=i,this.account=r,this.lock=n}get hasNewSessions(){return this.senderKeyDecryptions.some(e=>e.hasNewSessions)}write(e){try{for(const t of this.senderKeyDecryptions){for(const i of t.getModifiedSessions())if(e.olmSessions.set(i.data),i.isNew){const r=i.load();try{this.account.writeRemoveOneTimeKey(r,e)}finally{i.unload(r)}}if(t.sessions.length>ya){const{senderKey:i,sessions:r}=t;for(let n=r.length-1;n>=ya;n-=1){const o=r[n];e.olmSessions.remove(i,o.id)}}}}finally{this.lock.release()}}}function dg(s){return s.reduce((e,t)=>!e||t<e?t:e,null)}const va="signed_curve25519",wa=20;class ug{constructor(e,t,i,r,n,o,a,c){this.account=e,this.pickleKey=t,this.olm=i,this.storage=r,this.now=n,this.ownUserId=o,this.olmUtil=a,this.senderKeyLock=c}async encrypt(e,t,i,r,n){let o=[];for(let a=0;a<i.length;a+=wa){const c=i.slice(a,a+wa),l=await this._encryptForMaxDevices(e,t,c,r,n);o=o.concat(l)}return o}async _encryptForMaxDevices(e,t,i,r,n){const o=await Promise.all(i.map(a=>this.senderKeyLock.takeLock(a.curve25519Key)));try{const{devicesWithoutSession:a,existingEncryptionTargets:c}=await this._findExistingSessions(i),l=this.now();let d=[];try{if(a.length){const m=await n.wrap("create sessions",_=>this._createNewSessions(a,r,l,_));d=d.concat(m)}await this._loadSessions(c),d=d.concat(c);const u={l:"encrypt",targets:d.length},h=n.wrap(u,()=>d.map(m=>{const _=this._encryptForDevice(e,t,m);return new hg(_,m.device)}));return await this._storeSessions(d,l),h}finally{for(const u of d)u.dispose()}}finally{for(const a of o)a.release()}}async _findExistingSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]),i=await Promise.all(e.map(async o=>await t.olmSessions.getSessionIds(o.curve25519Key))),r=e.filter((o,a)=>{const c=i[a];return!c?.length}),n=e.map((o,a)=>{const c=i[a];if(c?.length>0){const l=dg(c);return Vi.fromSessionId(o,l)}}).filter(o=>!!o);return{devicesWithoutSession:r,existingEncryptionTargets:n}}_encryptForDevice(e,t,i){const{session:r,device:n}=i,o=JSON.stringify(this._buildPlainTextMessageForDevice(e,t,n)),a=r.encrypt(o);return{algorithm:vn,sender_key:this.account.identityKeys.curve25519,ciphertext:{[n.curve25519Key]:a}}}_buildPlainTextMessageForDevice(e,t,i){return{keys:{ed25519:this.account.identityKeys.ed25519},recipient_keys:{ed25519:i.ed25519Key},recipient:i.userId,sender:this.ownUserId,content:t,type:e}}async _createNewSessions(e,t,i,r){const n=await r.wrap("claim",o=>this._claimOneTimeKeys(t,e,o));try{for(const o of n){const{device:a,oneTimeKey:c}=o;o.session=await this.account.createOutboundOlmSession(a.curve25519Key,c)}await this._storeSessions(n,i)}catch(o){for(const a of n)a.dispose();throw o}return n}async _claimOneTimeKeys(e,t,i){const r=Rn(t,c=>c.userId,()=>new Map,(c,l)=>c.set(l.deviceId,l)),n=Array.from(r.entries()).reduce((c,[l,d])=>(c[l]=Array.from(d.values()).reduce((u,h)=>(u[h.deviceId]=va,u),{}),c),{}),o=await e.claimKeys({timeout:1e4,one_time_keys:n},{log:i}).response();Object.keys(o.failures).length&&i.log({l:"failures",servers:Object.keys(o.failures)},i.level.Warn);const a=o?.one_time_keys;return this._verifyAndCreateOTKTargets(a,r,i)}_verifyAndCreateOTKTargets(e,t,i){var r;const n=[];for(const[o,a]of Object.entries(e))for(const[c,l]of Object.entries(a)){const[d,u]=Object.entries(l)[0],[h]=d.split(":");if(h===va){const m=(r=t.get(o))==null?void 0:r.get(c);if(m&&vc(this.olmUtil,o,c,m.ed25519Key,u,i)){const f=Vi.fromOTK(m,u.key);n.push(f)}}}return n}async _loadSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]);let i=!1;try{await Promise.all(e.map(async r=>{const n=await t.olmSessions.get(r.device.curve25519Key,r.sessionId);if(n&&!i){const o=new this.olm.Session;o.unpickle(this.pickleKey,n.session),r.session=o}}))}catch(r){i=!0;for(const n of e)n.dispose();throw r}}async _storeSessions(e,t){const i=await this.storage.readWriteTxn([this.storage.storeNames.olmSessions]);try{for(const r of e){const n=_l(r.session,r.device.curve25519Key,t,this.pickleKey);i.olmSessions.set(n)}}catch(r){throw i.abort(),r}await i.complete()}}class Vi{constructor(e,t,i){this.device=e,this.oneTimeKey=t,this.sessionId=i,this.session=null}static fromOTK(e,t){return new Vi(e,t,null)}static fromSessionId(e,t){return new Vi(e,null,t)}dispose(){this.session&&this.session.free()}}class hg{constructor(e,t){this.content=e,this.device=t}}class pg{constructor(e,t,i,r){this._roomId=e,this._results=t,this._errors=i,this._replayEntries=r}async write(e){return await Promise.all(this._replayEntries.map(async t=>{try{this._handleReplayAttack(this._roomId,t,e)}catch(i){this._errors.set(t.eventId,i)}})),{results:this._results,errors:this._errors}}async _handleReplayAttack(e,t,i){const{messageIndex:r,sessionId:n,eventId:o,timestamp:a}=t,c=await i.groupSessionDecryptions.get(e,n,r);if(c&&c.eventId!==o){const d=c.timestamp<a?o:c.eventId;throw this._results.delete(o),new te("MEGOLM_REPLAYED_INDEX",event,{messageIndex:r,badEventId:d,otherEventId:c.eventId})}c||i.groupSessionDecryptions.set(e,n,r,{eventId:o,timestamp:a})}}function Zs(s,e){if(s)for(const[t,i]of s.entries())e.set(t,i)}class mg{constructor(e,t,i){this._roomId=e,this._sessionDecryptions=t,this._initialErrors=i}async decrypt(){try{const e=this._initialErrors,t=new Map,i=[];return await Promise.all(this._sessionDecryptions.map(async r=>{const n=await r.decryptAll();Zs(n.errors,e),Zs(n.results,t),i.push(...n.replayEntries)})),new pg(this._roomId,t,e,i)}finally{this.dispose()}}dispose(){for(const e of this._sessionDecryptions)e.dispose()}}class _g{constructor(e,t,i){this.sessionId=e,this.messageIndex=t,this.event=i}get eventId(){return this.event.event_id}get timestamp(){return this.event.origin_server_ts}}class fg{constructor(e,t,i,r){this.key=e,this.events=t,this.olmWorker=i,this.keyLoader=r,this.decryptionRequests=i?[]:void 0}async decryptAll(){const e=[],t=new Map;let i;return await this.keyLoader.useKey(this.key,async r=>{for(const n of this.events)try{const o=n.content.ciphertext;let a;if(this.olmWorker){const u=this.olmWorker.megolmDecrypt(r,o);this.decryptionRequests.push(u),a=await u.response()}else a=r.decrypt(o);const{plaintext:c}=a;let l;try{l=JSON.parse(c)}catch(u){throw new te("PLAINTEXT_NOT_JSON",n,{plaintext:c,err:u})}if(l.room_id!==this.key.roomId)throw new te("MEGOLM_WRONG_ROOM",n,{encryptedRoomId:l.room_id,eventRoomId:this.key.roomId});e.push(new _g(this.key.sessionId,a.message_index,n));const d=new fl(l,this.key.senderKey,this.key.claimedEd25519Key);t.set(n.event_id,d)}catch(o){if(o.name==="AbortError")return;i||(i=new Map),i.set(n.event_id,o)}}),{results:t,errors:i,replayEntries:e}}dispose(){if(this.decryptionRequests)for(const e of this.decryptionRequests)e.abort()}}function Nn(s){var e;return(e=s.content)==null?void 0:e.sender_key}function Mn(s){var e;return(e=s.content)==null?void 0:e.session_id}function gg(s){var e;return(e=s.content)==null?void 0:e.ciphertext}function yg(s){return typeof Nn(s)=="string"&&typeof Mn(s)=="string"&&typeof gg(s)=="string"}class vg{constructor(){this.events=[]}get senderKey(){return Nn(this.events[0])}get sessionId(){return Mn(this.events[0])}}function en(s){return Rn(s,e=>`${Nn(e)}|${Mn(e)}`,()=>new vg,(e,t)=>e.events.push(t))}class yl{isForSession(e,t,i){return this.roomId===e&&this.senderKey===t&&this.sessionId===i}get isBetter(){return this._isBetter}set isBetter(e){this._isBetter=e}}function vl(s,e){return s.first_known_index()<e.first_known_index()}class Dn extends yl{checkBetterThanKeyInStorage(e,t){return this._checkBetterThanKeyInStorage(e,void 0,t)}async write(e,t){let i;if(this.isBetter===void 0&&await this._checkBetterThanKeyInStorage(e,(n,o)=>{i=n.pickle(o)},t),this.isBetter===!1)return!1;i||(i=await e.useKey(this,(n,o)=>n.pickle(o)));const r={roomId:this.roomId,senderKey:this.senderKey,sessionId:this.sessionId,session:i,backup:this.backupStatus,source:this.keySource,claimedKeys:{ed25519:this.claimedEd25519Key}};return t.inboundGroupSessions.set(r),!0}get eventIds(){return this._eventIds}async _checkBetterThanKeyInStorage(e,t,i){if(this.isBetter!==void 0)return this.isBetter;let r=e.getCachedKey(this.roomId,this.senderKey,this.sessionId);if(!r){const n=await Sl(this.roomId,this.senderKey,this.sessionId,i);n&&(n.hasSession?r=n:n.eventIds&&(this._eventIds=n.eventIds))}if(r){const n=r;await e.useKey(this,async o=>{await e.useKey(n,(a,c)=>{this.isBetter=vl(o,a),n.isBetter=!this.isBetter,this.isBetter&&t&&t(o,c)})})}else this.isBetter=!0;return this.isBetter}get backupStatus(){return Jr.NotBackedUp}}class wg extends Dn{constructor(e){super(),this._decryptionResult=e}get roomId(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.room_id}get senderKey(){return this._decryptionResult.senderCurve25519Key}get sessionId(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.session_id}get claimedEd25519Key(){return this._decryptionResult.claimedEd25519Key}get serializationKey(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.session_key}get serializationType(){return"create"}get keySource(){return Yi.DeviceMessage}loadInto(e){e.create(this.serializationKey)}}class bg extends Dn{constructor(e,t,i){super(),this._roomId=e,this.outboundSession=t,this.identityKeys=i,this.isBetter=!0,this._sessionKey=this.outboundSession.session_key()}get roomId(){return this._roomId}get senderKey(){return this.identityKeys.curve25519}get sessionId(){return this.outboundSession.session_id()}get claimedEd25519Key(){return this.identityKeys.ed25519}get serializationKey(){return this._sessionKey}get serializationType(){return"create"}get keySource(){return Yi.Outbound}loadInto(e){e.create(this.serializationKey)}}class Sg extends Dn{constructor(e,t,i){super(),this._roomId=e,this._sessionId=t,this._backupInfo=i}get roomId(){return this._roomId}get senderKey(){return this._backupInfo.sender_key}get sessionId(){return this._sessionId}get claimedEd25519Key(){var e;return(e=this._backupInfo.sender_claimed_keys)==null?void 0:e.ed25519}get serializationKey(){return this._backupInfo.session_key}get serializationType(){return"import_session"}get keySource(){return Yi.Backup}loadInto(e){e.import_session(this.serializationKey)}get backupStatus(){return Jr.BackedUp}}class wl extends yl{constructor(e){super(),this.isBetter=!0,this.storageEntry=e}get roomId(){return this.storageEntry.roomId}get senderKey(){return this.storageEntry.senderKey}get sessionId(){return this.storageEntry.sessionId}get claimedEd25519Key(){return this.storageEntry.claimedKeys.ed25519}get eventIds(){return this.storageEntry.eventIds}get serializationKey(){return this.storageEntry.session||""}get serializationType(){return"unpickle"}loadInto(e,t){e.unpickle(t,this.serializationKey)}get hasSession(){return!!this.serializationKey}}function Eg(s){var e;const t=(e=s.event.content)==null?void 0:e.session_key,i=new wg(s);if(typeof i.roomId=="string"&&typeof i.sessionId=="string"&&typeof i.senderKey=="string"&&typeof t=="string")return i}function bl(s,e,t){var i;const r=t.session_key,n=t.sender_key,o=(i=t.sender_claimed_keys)==null?void 0:i.ed25519;if(typeof s=="string"&&typeof e=="string"&&typeof n=="string"&&typeof r=="string"&&typeof o=="string")return new Sg(s,e,t)}async function Sl(s,e,t,i){const r=await i.inboundGroupSessions.get(s,e,t);if(r)return new wl(r)}class Ig{constructor(e,t){this.keyLoader=e,this.olmWorker=t}async addMissingKeyEventIds(e,t,i,r,n){let o=await n.inboundGroupSessions.get(e,t,i);if(!o?.session){if(o){const a=new Set(o.eventIds);for(const c of r)a.add(c);o.eventIds=Array.from(a)}else o={roomId:e,senderKey:t,sessionId:i,eventIds:r};n.inboundGroupSessions.set(o)}}async getEventIdsForMissingKey(e,t,i,r){const n=await r.inboundGroupSessions.get(e,t,i);if(n&&!n.session)return n.eventIds}async hasSession(e,t,i,r){const n=await r.inboundGroupSessions.get(e,t,i);return typeof n?.session=="string"}async prepareDecryptAll(e,t,i,r){const n=new Map,o=[];for(const l of t)yg(l)?o.push(l):n.set(l.event_id,new te("MEGOLM_INVALID_EVENT",l));const a=en(o),c=[];return await Promise.all(Array.from(a.values()).map(async l=>{const d=await this.getRoomKey(e,l.senderKey,l.sessionId,i,r);if(d)c.push(new fg(d,l.events,this.olmWorker,this.keyLoader));else for(const u of l.events)n.set(u.event_id,new te("MEGOLM_NO_SESSION",u))})),new mg(e,c,n)}async getRoomKey(e,t,i,r,n){if(r){const c=r.find(l=>l.isForSession(e,t,i));if(c&&await c.checkBetterThanKeyInStorage(this.keyLoader,n))return c}const o=this.keyLoader.getCachedKey(e,t,i);if(o)return o;const a=await Sl(e,t,i,n);if(a&&a.serializationKey)return a}writeRoomKey(e,t){return e.write(this.keyLoader,t)}roomKeysFromDeviceMessages(e,t){var i,r;const n=[];for(const o of e)((i=o.event)==null?void 0:i.type)!=="m.room_key"||((r=o.event.content)==null?void 0:r.algorithm)!==De||t.wrap("room_key",a=>{const c=Eg(o);c?(a.set("roomId",c.roomId),a.set("id",c.sessionId),n.push(c)):(a.logLevel=a.level.Warn,a.set("invalid",!0))},t.level.Detail);return n}roomKeyFromBackup(e,t,i){return bl(e,t,i)}dispose(){this.keyLoader.dispose()}}class Tg extends ol{constructor(e,t,i){super(i),this.pickleKey=t,this.olm=e}getCachedKey(e,t,i){const r=this.findCachedKeyIndex(e,t,i);if(r!==-1)return this._getByIndexAndMoveUp(r).key}async useKey(e,t){const i=await this.allocateOperation(e);try{return await t(i.session,this.pickleKey)}finally{this.releaseOperation(i)}}get running(){return this._entries.some(e=>e.refCount!==0)}dispose(){for(let e=0;e<this._entries.length;e+=1)this._entries[e].dispose();this._entries.splice(0,this._entries.length)}async allocateOperation(e){let t;for(;(t=this.findIndexForAllocation(e))===-1;)await this.operationBecomesUnused();if(t<this.size){const i=this._getByIndexAndMoveUp(t);return i.isForKey(e)?(i.refCount+=1,i):(i.refCount=1,i.key=e,e.loadInto(i.session,this.pickleKey),i)}else{const i=new this.olm.InboundGroupSession;e.loadInto(i,this.pickleKey);const r=new xg(e,i);return this._set(r),r}}releaseOperation(e){e.refCount-=1,e.refCount<=0&&this.resolveUnusedOperation&&(this.resolveUnusedOperation(),this.operationBecomesUnusedPromise=this.resolveUnusedOperation=void 0)}operationBecomesUnused(){return this.operationBecomesUnusedPromise||(this.operationBecomesUnusedPromise=new Promise(e=>{this.resolveUnusedOperation=e})),this.operationBecomesUnusedPromise}findIndexForAllocation(e){let t=this.findIndexSameKey(e);return t===-1&&(this.size<this.limit?t=this.size:(t=this.findIndexSameSessionUnused(e),t===-1&&(t=this.findIndexOldestUnused()))),t}findCachedKeyIndex(e,t,i){return this._entries.reduce((r,n,o,a)=>{const c=r===-1?void 0:a[r];return n.isBest===!0&&n.isForSameSession(e,t,i)&&(!c||n.isBetter(c))?o:r},-1)}findIndexSameKey(e){return this._entries.findIndex(t=>t.isForSameSession(e.roomId,e.senderKey,e.sessionId)&&t.isForKey(e))}findIndexSameSessionUnused(e){return this._entries.reduce((t,i,r,n)=>{const o=t===-1?void 0:n[t];return i.refCount===0&&i.isForSameSession(e.roomId,e.senderKey,e.sessionId)&&(!o||!i.isBetter(o))?r:t},-1)}findIndexOldestUnused(){for(let e=this._entries.length-1;e>=0;e-=1)if(this._entries[e].refCount===0)return e;return-1}}class xg{constructor(e,t){this.key=e,this.session=t,this.refCount=1}isForSameSession(e,t,i){return this.key.roomId===e&&this.key.senderKey===t&&this.key.sessionId===i}isBetter(e){return vl(this.session,e.session)}isForKey(e){return this.key.serializationKey===e.serializationKey&&this.key.serializationType===e.serializationType}dispose(){this.session.free(),this.session=void 0}get isBest(){return this.key.isBetter}}const kg="m.megolm_backup.v1.curve25519-aes-sha2";class Pn{constructor(e,t){this.encryption=e,this.decryption=t}static fromAuthData(e,t,i){const r=e.public_key,n=new i.PkDecryption,o=new i.PkEncryption;try{const a=n.init_with_private_key(t);if(a!==r)throw new Error(`Bad backup key, public key does not match. Calculated ${a} but expected ${r}`);o.set_recipient_key(a)}catch(a){throw n.free(),a}return new Pn(o,n)}decryptRoomKey(e){const t=this.decryption.decrypt(e.ephemeral,e.mac,e.ciphertext);return JSON.parse(t)}encryptRoomKey(e,t){const i={algorithm:De,sender_key:e.senderKey,sender_claimed_keys:{ed25519:e.claimedEd25519Key},forwarding_curve25519_key_chain:[],session_key:t};return this.encryption.encrypt(JSON.stringify(i))}dispose(){var e,t;(e=this.decryption)==null||e.free(),this.decryption=void 0,(t=this.encryption)==null||t.free(),this.encryption=void 0}}const Rg=200;class On{constructor(e,t,i,r,n,o,a=1e4){this.backupInfo=e,this.crypto=t,this.hsApi=i,this.keyLoader=r,this.storage=n,this.platform=o,this.maxDelay=a,this.operationInProgress=new qe(void 0),this._stopped=!1,this._needsNewKey=!1,this._hasBackedUpAllKeys=!1}get hasStopped(){return this._stopped}get error(){return this._error}get version(){return this.backupInfo.version}get needsNewKey(){return this._needsNewKey}get hasBackedUpAllKeys(){return this._hasBackedUpAllKeys}async getRoomKey(e,t,i){const r=await this.hsApi.roomKeyForRoomAndSession(this.backupInfo.version,e,t,{log:i}).response();if(!r.session_data)return;const n=this.crypto.decryptRoomKey(r.session_data);if(n?.algorithm===De)return bl(e,t,n);n?.algorithm&&i.set("unknown algorithm",n.algorithm)}markAllForBackup(e){return e.inboundGroupSessions.markAllAsNotBackedUp()}flush(e){this.operationInProgress.get()||e.wrapDetached("flush key backup",async t=>{if(this._needsNewKey){t.set("needsNewKey",this._needsNewKey);return}this._stopped=!1,this._error=void 0,this._hasBackedUpAllKeys=!1;const i=this._runFlushOperation(t);this.operationInProgress.set(i);try{await i.result,this._hasBackedUpAllKeys=!0}catch(r){this._stopped=!0,r.name==="HomeServerError"&&(r.errcode==="M_WRONG_ROOM_KEYS_VERSION"||r.errcode==="M_NOT_FOUND")?(t.set("wrong_version",!0),this._needsNewKey=!0):(r.name!=="AbortError"||r.name==="StorageError"&&r.errcode==="AbortError")&&(this._error=r),t.catch(r)}this.operationInProgress.set(void 0)})}_runFlushOperation(e){return new Jc(async(t,i)=>{let r=0,n=0;for(;;){const o=this.platform.random()*this.maxDelay,a=this.platform.clock.createTimeout(o);t(a),await a.elapsed();const c=await this.storage.readTxn([F.inboundGroupSessions]);t(c),r=n+await c.inboundGroupSessions.countNonBackedUpSessions(),i(new ba(r,n));const l=(await c.inboundGroupSessions.getFirstNonBackedUpSessions(Rg)).map(h=>new wl(h));if(l.length===0){e.set("total",r);return}const d=await this.encodeKeysForBackup(l),u=this.hsApi.uploadRoomKeysToBackup(this.backupInfo.version,d,{log:e});t(u),await u.response(),await this.markKeysAsBackedUp(l,t),n+=l.length,i(new ba(r,n))}})}async encodeKeysForBackup(e){const t={rooms:{}},i=t.rooms;for(const r of e){let n=i[r.roomId];n||(n=i[r.roomId]={sessions:{}}),n.sessions[r.sessionId]=await this.encodeRoomKey(r)}return t}async markKeysAsBackedUp(e,t){const i=await this.storage.readWriteTxn([F.inboundGroupSessions]);t(i);try{await Promise.all(e.map(r=>i.inboundGroupSessions.markAsBackedUp(r.roomId,r.senderKey,r.sessionId)))}catch(r){throw i.abort(),r}await i.complete()}async encodeRoomKey(e){return await this.keyLoader.useKey(e,t=>{const i=t.first_known_index(),r=t.export_session(i);return{first_message_index:i,forwarded_count:0,is_verified:!1,session_data:this.crypto.encryptRoomKey(e,r)}})}dispose(){this.crypto.dispose()}static async fromSecretStorage(e,t,i,r,n,o,a){const c=await i.readSecret("m.megolm_backup.v1",a);if(c){const l=new Uint8Array(e.encoding.base64.decode(c)),d=await r.roomKeysVersion().response();if(d.algorithm===kg){const u=Pn.fromAuthData(d.auth_data,l,t);return new On(d,u,r,n,o,e)}else throw new Error(`Unknown backup algorithm: ${d.algorithm}`)}}}class ba{constructor(e,t){this.total=e,this.finished=t}}class Ag{constructor({pickleKey:e,olm:t,account:i,keyLoader:r,storage:n,now:o,ownDeviceId:a}){this._pickleKey=e,this._olm=t,this._account=i,this._keyLoader=r,this._storage=n,this._now=o,this._ownDeviceId=a}discardOutboundSession(e,t){t.outboundGroupSessions.remove(e)}async createRoomKeyMessage(e,t){let i=await t.outboundGroupSessions.get(e);if(i){const r=new this._olm.OutboundGroupSession;try{return r.unpickle(this._pickleKey,i.session),this._createRoomKeyMessage(r,e)}finally{r.free()}}}createWithheldMessage(e,t,i){return{algorithm:e.algorithm,code:t,reason:i,room_id:e.room_id,sender_key:this._account.identityKeys.curve25519,session_id:e.session_id}}async ensureOutboundSession(e,t){let i=new this._olm.OutboundGroupSession;try{const r=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let n;try{let o=await r.outboundGroupSessions.get(e);n=await this._readOrCreateSession(i,o,e,t,r),n&&this._writeSession(this._now(),i,e,r)}catch(o){throw r.abort(),o}return await r.complete(),n}finally{i.free()}}async _readOrCreateSession(e,t,i,r,n){if(t&&e.unpickle(this._pickleKey,t.session),!t||this._needsToRotate(e,t.createdAt,r)){t&&(e.free(),e=new this._olm.OutboundGroupSession),e.create();const o=this._createRoomKeyMessage(e,i);return await new bg(i,e,this._account.identityKeys).write(this._keyLoader,n),o}}_writeSession(e,t,i,r){r.outboundGroupSessions.set({roomId:i,session:t.pickle(this._pickleKey),createdAt:e})}async encrypt(e,t,i,r){let n=new this._olm.OutboundGroupSession;try{const o=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let a,c;try{let l=await o.outboundGroupSessions.get(e);a=await this._readOrCreateSession(n,l,e,r,o),c=this._encryptContent(e,n,t,i);const d=a?this._now():l.createdAt;this._writeSession(d,n,e,o)}catch(l){throw o.abort(),l}return await o.complete(),new Cg(c,a)}finally{n&&n.free()}}_needsToRotate(e,t,i){let r=6048e5;Number.isSafeInteger(i?.rotation_period_ms)&&(r=i?.rotation_period_ms);let n=100;if(Number.isSafeInteger(i?.rotation_period_msgs)&&(n=i?.rotation_period_msgs),this._now()>t+r||e.message_index()>=n)return!0}_encryptContent(e,t,i,r){const n=JSON.stringify({room_id:e,type:i,content:r}),o=t.encrypt(n);return{algorithm:De,sender_key:this._account.identityKeys.curve25519,ciphertext:o,session_id:t.session_id(),device_id:this._ownDeviceId}}_createRoomKeyMessage(e,t){return{room_id:t,session_id:e.session_id(),session_key:e.session_key(),algorithm:De,chain_index:e.message_index()}}}class Cg{constructor(e,t){this.content=e,this.roomKeyMessage=t}}const Sa="m.room.encrypted",Ea="m.room.history_visibility",Ng=60*1e3;class Mg{constructor({room:e,deviceTracker:t,olmEncryption:i,megolmEncryption:r,megolmDecryption:n,encryptionParams:o,storage:a,keyBackup:c,notifyMissingMegolmSession:l,clock:d}){this._room=e,this._deviceTracker=t,this._olmEncryption=i,this._megolmEncryption=r,this._megolmDecryption=n,this._encryptionParams=o,this._senderDeviceCache=new Map,this._storage=a,this._keyBackup=c,this._notifyMissingMegolmSession=l,this._clock=d,this._isFlushingRoomKeyShares=!1,this._lastKeyPreShareTime=null,this._keySharePromise=null,this._historyVisibility=void 0,this._disposed=!1}enableKeyBackup(e){this._keyBackup&&!!e||(this._keyBackup=e)}async restoreMissingSessionsFromBackup(e,t){const i=e.filter(d=>d.isEncrypted&&!d.isDecrypted&&d.event).map(d=>d.event),r=en(i),n=Array.from(r.values()),o=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]),a=await Promise.all(n.map(async d=>this._megolmDecryption.hasSession(this._room.id,d.senderKey,d.sessionId,o))),c=n.filter((d,u)=>!a[u]);if(c.length)for(var l=c.length-1;l>=0;l--){const d=c[l];await t.wrap("session",u=>this._requestMissingSessionFromBackup(d.senderKey,d.sessionId,u))}}notifyTimelineClosed(){this._senderDeviceCache=new Map}async writeSync(e,t,i,r){let n=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility,i);const o=[],a=[];if(await nh(e,l=>{var d;if(l.state_key===""&&l.type===Ea){const u=(d=l?.content)==null?void 0:d.history_visibility;if(u!==n)return r.wrap({l:"history_visibility changed",from:n,to:u},async h=>{n=u;const m=await this._deviceTracker.writeHistoryVisibility(this._room,n,i,h);o.push(...m.added),a.push(...m.removed)})}}),t.size){const l=await this._deviceTracker.writeMemberChanges(this._room,t,n,i);o.push(...l.added),a.push(...l.removed)}a.length&&(r.log({l:"discardOutboundSession",leftUsers:a}),this._megolmEncryption.discardOutboundSession(this._room.id,i));let c=!1;return o.length&&(c=await this._addShareRoomKeyOperationForMembers(o,i,r)),{shouldFlush:c,historyVisibility:n}}afterSync({historyVisibility:e}){this._historyVisibility=e}async _loadHistoryVisibilityIfNeeded(e,t=void 0){var i,r;if(!e){t||(t=await this._storage.readTxn([this._storage.storeNames.roomState]));const n=await t.roomState.get(this._room.id,Ea,"");if(n)return(r=(i=n.event)==null?void 0:i.content)==null?void 0:r.history_visibility}return e}async prepareDecryptAll(e,t,i,r){var n,o,a;const c=new Map,l=[];for(const u of e)u.redacted_because||((n=u.unsigned)==null?void 0:n.redacted_because)||(((o=u.content)==null?void 0:o.algorithm)!==De&&c.set(u.event_id,new Error("Unsupported algorithm: "+((a=u.content)==null?void 0:a.algorithm))),l.push(u));const d=await this._megolmDecryption.prepareDecryptAll(this._room.id,l,t,r);return new Dg(d,c,i,this,e)}async _processDecryptionResults(e,t,i,r,n,o){const a=e.filter(l=>{const d=i.get(l.event_id);return d?.code==="MEGOLM_NO_SESSION"});if(!a.length)return;const c=en(a);r===Rt.Sync&&await Promise.all(Array.from(c.values()).map(async l=>{const d=l.events.map(u=>u.event_id);return this._megolmDecryption.addMissingKeyEventIds(this._room.id,l.senderKey,l.sessionId,d,n)})),this._keyBackup&&o.wrapDetached("check key backup",async l=>{if(l.set("source",r),l.set("events",a.length),l.set("sessions",c.size),r===Rt.Sync){if(await this._clock.createTimeout(1e4).elapsed(),this._disposed)return;const d=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);await Promise.all(Array.from(c).map(async([u,h])=>{await this._megolmDecryption.hasSession(this._room.id,h.senderKey,h.sessionId,d)&&c.delete(u)}))}await Promise.all(Array.from(c.values()).map(d=>l.wrap("session",u=>this._requestMissingSessionFromBackup(d.senderKey,d.sessionId,u))))})}async _verifyDecryptionResult(e,t){let i=this._senderDeviceCache.get(e.senderCurve25519Key);i||(i=await this._deviceTracker.getDeviceByCurve25519Key(e.senderCurve25519Key,t),this._senderDeviceCache.set(e.senderCurve25519Key,i)),i?e.setDevice(i):this._room.isTrackingMembers||e.setRoomNotTrackedYet()}async _requestMissingSessionFromBackup(e,t,i){if(!this._keyBackup){i.set("enabled",!1),this._notifyMissingMegolmSession();return}i.set("id",t),i.set("senderKey",e);try{const r=await this._keyBackup.getRoomKey(this._room.id,t,i);if(r){if(r.senderKey!==e){i.set("wrong_sender_key",r.senderKey),i.logLevel=i.level.Warn;return}let n=!1,o;const a=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions]);try{n=await this._megolmDecryption.writeRoomKey(r,a),i.set("isBetter",n),n&&(o=r.eventIds)}catch(c){throw a.abort(),c}await a.complete(),n&&await i.wrap("retryDecryption",c=>this._room.notifyRoomKey(r,o||[],c))}}catch(r){r.name==="HomeServerError"&&r.errcode==="M_NOT_FOUND"?(i.error=r,i.logLevel=i.level.Error):i.set("not_found",!0)}}getEventIdsForMissingKey(e,t){return this._megolmDecryption.getEventIdsForMissingKey(this._room.id,e.senderKey,e.sessionId,t)}async ensureMessageKeyIsShared(e,t){var i;if(!(((i=this._lastKeyPreShareTime)==null?void 0:i.measure())<Ng)){this._lastKeyPreShareTime=this._clock.createMeasure();try{this._keySharePromise=(async()=>{var r;const n=await this._megolmEncryption.ensureOutboundSession(this._room.id,this._encryptionParams);n&&((r=this._keyBackup)==null||r.flush(t),await t.wrap("share key",o=>this._shareNewRoomKey(n,e,o)))})(),await this._keySharePromise}finally{this._keySharePromise=null}}}async encrypt(e,t,i,r){var n;this._keySharePromise&&(r.set("waitForRunningKeyShare",!0),await this._keySharePromise);const o=await r.wrap("megolm encrypt",()=>this._megolmEncryption.encrypt(this._room.id,e,t,this._encryptionParams));return o.roomKeyMessage&&((n=this._keyBackup)==null||n.flush(r),await r.wrap("share key",a=>this._shareNewRoomKey(o.roomKeyMessage,i,a))),{type:Sa,content:o.content}}needsToShareKeys(e){for(const t of e.values())if(t.hasJoined)return!0;return!1}async _shareNewRoomKey(e,t,i){this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,i);const r=await this._deviceTracker.devicesForTrackedRoom(this._room.id,t,i),n=Array.from(r.reduce((c,l)=>c.add(l.userId),new Set));let o=await this._storage.readWriteTxn([this._storage.storeNames.operations]),a;try{a=this._writeRoomKeyShareOperation(e,n,o)}catch(c){throw o.abort(),c}await this._processShareRoomKeyOperation(a,t,i)}async _addShareRoomKeyOperationForMembers(e,t,i){const r=await this._megolmEncryption.createRoomKeyMessage(this._room.id,t);return r?(i.log({l:"share key for new members",userIds:e,id:r.session_id,chain_index:r.chain_index}),this._writeRoomKeyShareOperation(r,e,t),!0):!1}async flushPendingRoomKeyShares(e,t,i){if(!this._isFlushingRoomKeyShares){this._isFlushingRoomKeyShares=!0;try{t||(t=await(await this._storage.readTxn([this._storage.storeNames.operations])).operations.getAllByTypeAndScope("share_room_key",this._room.id));for(const r of t)r.type==="share_room_key"&&await i.wrap("operation",n=>this._processShareRoomKeyOperation(r,e,n))}finally{this._isFlushingRoomKeyShares=!1}}}_writeRoomKeyShareOperation(e,t,i){const n={id:Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(),type:"share_room_key",scope:this._room.id,userIds:t,roomKeyMessage:e};return i.operations.add(n),n}async _processShareRoomKeyOperation(e,t,i){i.set("id",e.id),this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,i);const r=await this._deviceTracker.devicesForRoomMembers(this._room.id,e.userIds,t,i),n=await i.wrap("olm encrypt",a=>this._olmEncryption.encrypt("m.room_key",e.roomKeyMessage,r,t,a)),o=r.filter(a=>!n.some(c=>c.device===a));await i.wrap("send",a=>this._sendMessagesToDevices(Sa,n,t,a)),o.length&&await i.wrap("missingDevices",async a=>{a.set("devices",o.map(d=>d.deviceId));const c=e.userIds.filter(d=>o.some(u=>u.userId===d));a.set("unsentUserIds",c),e.userIds=c,await this._updateOperationsStore(d=>d.update(e));const l=this._megolmEncryption.createWithheldMessage(e.roomKeyMessage,"m.no_olm","OTKs exhausted");await this._sendSharedMessageToDevices("org.matrix.room_key.withheld",l,o,t,a)}),await this._updateOperationsStore(a=>a.remove(e.id))}async _updateOperationsStore(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.operations]);try{e(t.operations)}catch(i){throw t.abort(),i}await t.complete()}async _sendSharedMessageToDevices(e,t,i,r,n){const o=si(i,l=>l.userId),a={messages:Array.from(o.entries()).reduce((l,[d,u])=>(l[d]=u.reduce((h,m)=>(h[m.deviceId]=t,h),{}),l),{})},c=$r();await r.sendToDevice(e,a,c,{log:n}).response()}async _sendMessagesToDevices(e,t,i,r){r.set("messages",t.length);const n=si(t,c=>c.device.userId),o={messages:Array.from(n.entries()).reduce((c,[l,d])=>(c[l]=d.reduce((u,h)=>(u[h.device.deviceId]=h.content,u),{}),c),{})},a=$r();await i.sendToDevice(e,o,a,{log:r}).response()}filterUndecryptedEventEntriesForKeys(e,t){return e.filter(i=>{var r,n;if(i.isEncrypted&&!i.isDecrypted){const{event:o}=i;if(o){const a=(r=o.content)==null?void 0:r.sender_key,c=(n=o.content)==null?void 0:n.session_id;return t.some(l=>a===l.senderKey&&c===l.sessionId)}}return!1})}dispose(){this._disposed=!0}}class Dg{constructor(e,t,i,r,n){this._megolmDecryptionPreparation=e,this._extraErrors=t,this._source=i,this._roomEncryption=r,this._events=n}async decrypt(){return new Pg(await this._megolmDecryptionPreparation.decrypt(),this._extraErrors,this._source,this._roomEncryption,this._events)}dispose(){this._megolmDecryptionPreparation.dispose()}}class Pg{constructor(e,t,i,r,n){this._megolmDecryptionChanges=e,this._extraErrors=t,this._source=i,this._roomEncryption=r,this._events=n}async write(e,t){const{results:i,errors:r}=await this._megolmDecryptionChanges.write(e);return Zs(this._extraErrors,r),await this._roomEncryption._processDecryptionResults(this._events,i,r,this._source,e,t),new Og(i,r,this._roomEncryption)}}class Og{constructor(e,t,i){this.results=e,this.errors=t,this._roomEncryption=i}applyToEntries(e){for(const t of e){const i=this.results.get(t.id);if(i)t.setDecryptionResult(i);else{const r=this.errors.get(t.id);r&&t.setDecryptionError(r)}}}verifySenders(e){return Promise.all(Array.from(this.results.values()).map(t=>this._roomEncryption._verifyDecryptionResult(t,e)))}}const tn=0,Ia=1;function Ug(s,e,t){if(s){if(!s.roomIds.includes(t))return s.roomIds.push(t),s}else return s={userId:e,roomIds:[t],deviceTrackingStatus:tn},s}function Bg(s){var e;const t=s.device_id;return{userId:s.user_id,deviceId:t,ed25519Key:s.keys[`ed25519:${t}`],curve25519Key:s.keys[`curve25519:${t}`],algorithms:s.algorithms,displayName:(e=s.unsigned)==null?void 0:e.device_display_name}}class Lg{constructor({storage:e,getSyncToken:t,olmUtil:i,ownUserId:r,ownDeviceId:n}){this._storage=e,this._getSyncToken=t,this._identityChangedForRoom=null,this._olmUtil=i,this._ownUserId=r,this._ownDeviceId=n}async writeDeviceChanges(e,t,i){const{userIdentities:r}=t;i.set("changed",e.length),await Promise.all(e.map(async n=>{const o=await r.get(n);o&&(i.log({l:"outdated",id:n}),o.deviceTrackingStatus=tn,r.set(o))}))}async writeMemberChanges(e,t,i,r){const n=[],o=[];return await Promise.all(Array.from(t.values()).map(async a=>{if(dr(a.membership,i))await this._addRoomToUserIdentity(a.roomId,a.userId,r)&&n.push(a.userId);else if(dr(a.previousMembership,i)){const{roomId:c}=a;if(a.userId===this._ownUserId){const l=await r.roomMembers.getAllUserIds(c);await Promise.all(l.map(d=>this._removeRoomFromUserIdentity(c,d,r)))}else await this._removeRoomFromUserIdentity(c,a.userId,r);o.push(a.userId)}})),{added:n,removed:o}}async trackRoom(e,t,i){if(e.isTrackingMembers||!e.isEncrypted)return;const r=await e.loadMemberList(void 0,i),n=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary,this._storage.storeNames.userIdentities]);try{let o;try{o=e.writeIsTrackingMembers(!0,n);const a=Array.from(r.members.values());i.set("members",a.length),await Promise.all(a.map(async c=>{dr(c.membership,t)&&await this._addRoomToUserIdentity(c.roomId,c.userId,n)}))}catch(a){throw n.abort(),a}await n.complete(),e.applyIsTrackingMembersChanges(o)}finally{r.release()}}async writeHistoryVisibility(e,t,i,r){const n=[],o=[];return e.isTrackingMembers&&e.isEncrypted&&await r.wrap("rewriting userIdentities",async a=>{const c=await e.loadMemberList(i,a);try{const l=Array.from(c.members.values());a.set("members",l.length),await Promise.all(l.map(async d=>{dr(d.membership,t)?await this._addRoomToUserIdentity(d.roomId,d.userId,i)&&n.push(d.userId):await this._removeRoomFromUserIdentity(d.roomId,d.userId,i)&&o.push(d.userId)}))}finally{c.release()}}),{added:n,removed:o}}async _addRoomToUserIdentity(e,t,i){const{userIdentities:r}=i,n=await r.get(t),o=Ug(n,t,e);return o?(r.set(o),!0):!1}async _removeRoomFromUserIdentity(e,t,i){const{userIdentities:r,deviceIdentities:n}=i,o=await r.get(t);return o?(o.roomIds=o.roomIds.filter(a=>a!==e),o.roomIds.length===0?(r.remove(t),n.removeAllForUser(t)):r.set(o),!0):!1}async _queryKeys(e,t,i){const r=await t.queryKeys({timeout:1e4,device_keys:e.reduce((c,l)=>(c[l]=[],c),{}),token:this._getSyncToken()},{log:i}).response(),n=i.wrap("verify",c=>this._filterVerifiedDeviceKeys(r.device_keys,c)),o=await this._storage.readWriteTxn([this._storage.storeNames.userIdentities,this._storage.storeNames.deviceIdentities]);let a;try{a=(await Promise.all(n.map(async({userId:l,verifiedKeys:d})=>{const u=d.map(Bg);return await this._storeQueriedDevicesForUserId(l,u,o)}))).reduce((l,d)=>l.concat(d),[]),i.set("devices",a.length)}catch(c){throw o.abort(),c}return await o.complete(),a}async _storeQueriedDevicesForUserId(e,t,i){const r=await i.deviceIdentities.getAllDeviceIds(e);for(const c of r)t.every(l=>l.deviceId!==c)&&i.deviceIdentities.remove(e,c);const n=[],o=[];await Promise.all(t.map(async c=>{if(r.includes(c.deviceId)){const l=await i.deviceIdentities.get(c.userId,c.deviceId);if(l.ed25519Key!==c.ed25519Key){n.push(l);return}}n.push(c),o.push(c)}));for(const c of o)i.deviceIdentities.set(c);const a=await i.userIdentities.get(e);return a.deviceTrackingStatus=Ia,i.userIdentities.set(a),n}_filterVerifiedDeviceKeys(e,t){const i=new Set;return Object.entries(e).map(([n,o])=>{const c=Object.entries(o).filter(([l,d])=>{var u,h;const m=d.device_id;if(d.user_id!==n||m!==l)return!1;const f=(u=d.keys)==null?void 0:u[`ed25519:${l}`],E=(h=d.keys)==null?void 0:h[`curve25519:${l}`];if(typeof f!="string"||typeof E!="string")return!1;if(i.has(E))return t.log({l:"ignore device with duplicate curve25519 key",keys:d},t.level.Warn),!1;i.add(E);const I=this._hasValidSignature(d,t);return I||t.log({l:"ignore device with invalid signature",keys:d},t.level.Warn),I}).map(([,l])=>l);return{userId:n,verifiedKeys:c}})}_hasValidSignature(e,t){var i;const r=e.device_id,n=e.user_id,o=(i=e?.keys)==null?void 0:i[`${yc}:${r}`];return vc(this._olmUtil,n,r,o,e,t)}async devicesForTrackedRoom(e,t,i){const r=await this._storage.readTxn([this._storage.storeNames.roomMembers,this._storage.storeNames.userIdentities]),n=await r.roomMembers.getAllUserIds(e);return await this._devicesForUserIds(e,n,r,t,i)}async devicesForRoomMembers(e,t,i,r){const n=await this._storage.readTxn([this._storage.storeNames.userIdentities]);return await this._devicesForUserIds(e,t,n,i,r)}async _devicesForUserIds(e,t,i,r,n){const a=(await Promise.all(t.map(f=>i.userIdentities.get(f)))).filter(f=>f&&f.roomIds.includes(e)),c=a.filter(f=>f.deviceTrackingStatus===Ia),l=a.filter(f=>f.deviceTrackingStatus===tn);n.set("uptodate",c.length),n.set("outdated",l.length);let d;l.length&&(d=await this._queryKeys(l.map(f=>f.userId),r,n));const u=await this._storage.readTxn([this._storage.storeNames.deviceIdentities]);let m=(await Promise.all(c.map(f=>u.deviceIdentities.getAllForUserId(f.userId)))).reduce((f,E)=>f.concat(E),[]);return d&&d.length&&(m=m.concat(d)),m.filter(f=>!(f.userId===this._ownUserId&&f.deviceId===this._ownDeviceId))}async getDeviceByCurve25519Key(e,t){return await t.deviceIdentities.getByCurve25519Key(e)}}class Fg{constructor(){this._map=new Map}async takeLock(e){let t=this._map.get(e);return t?await t.take():(t=new ng,t.tryTake(),this._map.set(e,t)),t.released().then(()=>{Promise.resolve().then(()=>{t.isTaken||this._map.delete(e)})}),t}}class Vg{constructor({key:e,platform:t}){this._key=e,this._platform=t}async readSecret(e,t){var i,r;const n=await t.accountData.get(e);if(!n)return;const o=(r=(i=n?.content)==null?void 0:i.encrypted)==null?void 0:r[this._key.id];if(!o)throw new Error(`Secret ${n.type} is not encrypted for key ${this._key.id}`);if(this._key.algorithm==="m.secret_storage.v1.aes-hmac-sha2")return await this._decryptAESSecret(n.type,o);throw new Error(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`)}async _decryptAESSecret(e,t){const{base64:i,utf8:r}=this._platform.encoding,n=await this._platform.crypto.derive.hkdf(this._key.binaryKey,new Uint8Array(8).buffer,r.encode(e),"SHA-256",512),o=n.slice(0,32),a=n.slice(32),c=i.decode(t.ciphertext);if(!await this._platform.crypto.hmac.verify(a,i.decode(t.mac),c,"SHA-256"))throw new Error("Bad MAC");const d=await this._platform.crypto.aes.decryptCTR({key:o,iv:i.decode(t.iv),data:c});return r.decode(d)}}const Et="DEFAULT_KEY",bi="pusher";class Kg{constructor({storage:e,hsApi:t,sessionInfo:i,olm:r,olmWorker:n,platform:o,mediaRepository:a}){this._platform=o,this._storage=e,this._hsApi=t,this._mediaRepository=a,this._syncInfo=null,this._sessionInfo=i,this._rooms=new Ni,this._roomUpdateCallback=(c,l)=>this._rooms.update(c.id,l),this._activeArchivedRooms=new Map,this._invites=new Ni,this._inviteUpdateCallback=(c,l)=>this._invites.update(c.id,l),this._roomsBeingCreatedUpdateCallback=(c,l)=>{c.isCancelled?this._roomsBeingCreated.remove(c.id):this._roomsBeingCreated.update(c.id,l)},this._roomsBeingCreated=new Ni,this._user=new ff(i.userId),this._deviceMessageHandler=new jf({storage:e}),this._olm=r,this._olmUtil=null,this._e2eeAccount=null,this._deviceTracker=null,this._olmEncryption=null,this._keyLoader=null,this._megolmEncryption=null,this._megolmDecryption=null,this._getSyncToken=()=>this.syncToken,this._olmWorker=n,this._keyBackup=new qe(void 0),this._observedRoomStatus=new Map,r&&(this._olmUtil=new r.Utility,this._deviceTracker=new Lg({storage:e,getSyncToken:this._getSyncToken,olmUtil:this._olmUtil,ownUserId:i.userId,ownDeviceId:i.deviceId})),this._createRoomEncryption=this._createRoomEncryption.bind(this),this._forgetArchivedRoom=this._forgetArchivedRoom.bind(this),this.needsKeyBackup=new qe(!1)}get fingerprintKey(){var e;return(e=this._e2eeAccount)==null?void 0:e.identityKeys.ed25519}get hasSecretStorageKey(){return this._hasSecretStorageKey}get deviceId(){return this._sessionInfo.deviceId}get userId(){return this._sessionInfo.userId}_setupEncryption(){const e=new Fg,t=new ag(this._e2eeAccount,Et,this._platform.clock.now,this._user.id,this._olm,e);this._olmEncryption=new ug(this._e2eeAccount,Et,this._olm,this._storage,this._platform.clock.now,this._user.id,this._olmUtil,e),this._keyLoader=new Tg(this._olm,Et,20),this._megolmEncryption=new Ag({account:this._e2eeAccount,pickleKey:Et,olm:this._olm,storage:this._storage,keyLoader:this._keyLoader,now:this._platform.clock.now,ownDeviceId:this._sessionInfo.deviceId}),this._megolmDecryption=new Ig(this._keyLoader,this._olmWorker),this._deviceMessageHandler.enableEncryption({olmDecryption:t,megolmDecryption:this._megolmDecryption})}_createRoomEncryption(e,t){var i;if(!this._olmEncryption)throw new Error("creating room encryption before encryption got globally enabled");return t.algorithm!==De?null:new Mg({room:e,deviceTracker:this._deviceTracker,olmEncryption:this._olmEncryption,megolmEncryption:this._megolmEncryption,megolmDecryption:this._megolmDecryption,storage:this._storage,keyBackup:(i=this._keyBackup)==null?void 0:i.get(),encryptionParams:t,notifyMissingMegolmSession:()=>{this._keyBackup.get()||this.needsKeyBackup.set(!0)},clock:this._platform.clock})}enableSecretStorage(e,t,i=void 0){return this._platform.logger.wrapOrRun(i,"enable secret storage",async r=>{if(!this._olm)throw new Error("olm required");this._keyBackup.get()&&(this._keyBackup.get().dispose(),this._keyBackup.set(null));const n=await Zf(e,t,this._storage,this._platform,this._olm),o=await this._storage.readTxn([this._storage.storeNames.accountData]);if(await this._createKeyBackup(n,o,r))return await this._writeSSSSKey(n,r),this._keyBackup.get().flush(r),n;throw new Error("Could not read key backup with the given key")})}async _writeSSSSKey(e,t){const i=this._keyBackup.get();if(!i)return;const r=i.version,n=await this._storage.readWriteTxn([this._storage.storeNames.session,this._storage.storeNames.inboundGroupSessions]);try{const o=await Jf(e,r,n);if(t.set("previousBackupVersion",o),t.set("backupVersion",r),!!o&&o!==r){const a=await i.markAllForBackup(n);t.set("amountMarkedForBackup",a)}}catch(o){throw n.abort(),o}await n.complete()}async disableSecretStorage(){const e=await this._storage.readWriteTxn([this._storage.storeNames.session]);try{Qf(e)}catch(t){throw e.abort(),t}if(await e.complete(),this._keyBackup.get()){for(const t of this._rooms.values())t.isEncrypted&&t.enableKeyBackup(void 0);this._keyBackup.get().dispose(),this._keyBackup.set(null)}}_createKeyBackup(e,t,i){return i.wrap("enable key backup",async r=>{try{const n=new Vg({key:e,platform:this._platform}),o=await On.fromSecretStorage(this._platform,this._olm,n,this._hsApi,this._keyLoader,this._storage,t);if(o){for(const a of this._rooms.values())a.isEncrypted&&a.enableKeyBackup(o);return this._keyBackup.set(o),!0}}catch(n){r.catch(n)}return!1})}get keyBackup(){return this._keyBackup}get hasIdentity(){return!!this._e2eeAccount}async createIdentity(e){this._olm&&(this._e2eeAccount||(this._e2eeAccount=await this._createNewAccount(this._sessionInfo.deviceId,this._storage),e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption()),await this._e2eeAccount.generateOTKsIfNeeded(this._storage,e),await e.wrap("uploadKeys",t=>this._e2eeAccount.uploadKeys(this._storage,!1,t)))}async dehydrateIdentity(e,t){return t.set("deviceId",e.deviceId),this._olm?e.deviceId!==this.deviceId?(t.set("wrong_device",!0),!1):this._e2eeAccount?(t.set("account_already_setup",!0),!1):await e.claim(this._hsApi,t)?(this._e2eeAccount=await Ot.adoptDehydratedDevice({dehydratedDevice:e,hsApi:this._hsApi,olm:this._olm,pickleKey:Et,userId:this._sessionInfo.userId,olmWorker:this._olmWorker,deviceId:this.deviceId,storage:this._storage}),t.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption(),!0):(t.set("already_claimed",!0),!1):(t.set("no_olm",!0),!1)}_createNewAccount(e,t=void 0){return Ot.create({hsApi:this._hsApi,olm:this._olm,pickleKey:Et,userId:this._sessionInfo.userId,olmWorker:this._olmWorker,deviceId:e,storage:t})}setupDehydratedDevice(e,t=null){return this._platform.logger.wrapOrRun(t,"setupDehydratedDevice",async i=>{const r=await this._createNewAccount("temp-device-id");try{const n=await ig(r,this._hsApi,e,"Dehydrated device",i);return i.set("deviceId",n),n}finally{r.dispose()}})}async load(e){const t=await this._storage.readTxn([this._storage.storeNames.session,this._storage.storeNames.roomSummary,this._storage.storeNames.invites,this._storage.storeNames.roomMembers,this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineFragments,this._storage.storeNames.pendingEvents]);this._syncInfo=await t.session.get("sync"),this._olm&&(this._e2eeAccount=await Ot.load({hsApi:this._hsApi,olm:this._olm,pickleKey:Et,userId:this._sessionInfo.userId,deviceId:this._sessionInfo.deviceId,olmWorker:this._olmWorker,txn:t}),this._e2eeAccount&&(e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption()));const i=await this._getPendingEventsByRoom(t),r=await t.invites.getAll(),n=Promise.all(r.map(async c=>{const l=this.createInvite(c.roomId);e.wrap("invite",d=>l.load(c,d)),this._invites.add(l.id,l)})),o=await t.roomSummary.getAll(),a=Promise.all(o.map(async c=>{const l=this.createJoinedRoom(c.roomId,i.get(c.roomId));await e.wrap("room",d=>l.load(c,t,d)),this._rooms.add(l.id,l)}));await Promise.all([n,a]);for(const[c,l]of this.invites){const d=this.rooms.get(c);d&&d.setInvite(l)}}dispose(){var e,t,i,r;(e=this._olmWorker)==null||e.dispose(),this._olmWorker=void 0,(t=this._keyBackup.get())==null||t.dispose(),this._keyBackup.set(void 0),(i=this._megolmDecryption)==null||i.dispose(),this._megolmDecryption=void 0,(r=this._e2eeAccount)==null||r.dispose(),this._e2eeAccount=void 0;for(const n of this._rooms.values())n.dispose();this._rooms=void 0}async start(e,t,i){var r;if(e){const c=await this._storage.readWriteTxn([this._storage.storeNames.session]);c.session.set("serverVersions",e),await c.complete()}if(!this._keyBackup.get()){t&&await i.wrap("SSSSKeyFromDehydratedDeviceKey",async d=>{const u=await eg(t.key,this._storage,this._platform);u&&(d.set("success",!0),await this._writeSSSSKey(u))});const c=await this._storage.readTxn([this._storage.storeNames.session,this._storage.storeNames.accountData]),l=await Xf(c);l&&await this._createKeyBackup(l,c,i)&&((r=this._keyBackup.get())==null||r.flush(i)),this._keyBackup.get()||this._keyBackup.set(null)}const o=await(await this._storage.readWriteTxn([this._storage.storeNames.operations])).operations.getAll(),a=si(o,c=>c.scope);for(const c of this._rooms.values()){let l;const d=a.get(c.id);d&&(l=si(d,u=>u.type)),c.start(l,i)}}async _getPendingEventsByRoom(e){return(await e.pendingEvents.getAll()).reduce((i,r)=>{const n=i.get(r.roomId);return n?n.push(r):i.set(r.roomId,[r]),i},new Map)}get rooms(){return this._rooms}findDirectMessageForUserId(e){for(const[,t]of this._rooms)if(t.isDirectMessageForUserId(e))return t;for(const[,t]of this._invites)if(t.isDirectMessageForUserId(e))return t}createJoinedRoom(e,t){return new Df({roomId:e,getSyncToken:this._getSyncToken,storage:this._storage,emitCollectionChange:this._roomUpdateCallback,hsApi:this._hsApi,mediaRepository:this._mediaRepository,pendingEvents:t,user:this._user,createRoomEncryption:this._createRoomEncryption,platform:this._platform})}_createArchivedRoom(e){const t=new Pf({roomId:e,getSyncToken:this._getSyncToken,storage:this._storage,emitCollectionChange:()=>{},releaseCallback:()=>this._activeArchivedRooms.delete(e),forgetCallback:this._forgetArchivedRoom,hsApi:this._hsApi,mediaRepository:this._mediaRepository,user:this._user,createRoomEncryption:this._createRoomEncryption,platform:this._platform});return this._activeArchivedRooms.set(e,t),t}get invites(){return this._invites}createInvite(e){return new $f({roomId:e,hsApi:this._hsApi,emitCollectionUpdate:this._inviteUpdateCallback,mediaRepository:this._mediaRepository,user:this._user,platform:this._platform})}get roomsBeingCreated(){return this._roomsBeingCreated}createRoom(e){let t;return this._platform.logger.runDetached("create room",async i=>{const r=`local-${Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER)}`;t=new Kf(r,e,this._roomsBeingCreatedUpdateCallback,this._mediaRepository,this._platform,i),this._roomsBeingCreated.set(r,t);const n=[t.create(this._hsApi,i)];e.loadProfiles!==!1&&n.push(t.loadProfiles(this._hsApi,i)),await Promise.all(n),t.roomId&&(this.rooms.get(t.roomId)&&this._tryReplaceRoomBeingCreated(t.roomId,i),await t.adjustDirectMessageMapIfNeeded(this._user,this._storage,this._hsApi,i))}),t}async obtainSyncLock(e){var t;const i=(t=e.to_device)==null?void 0:t.events;if(Array.isArray(i)&&i.length)return await this._deviceMessageHandler.obtainSyncLock(i)}async prepareSync(e,t,i,r){var n;const o=(n=e.to_device)==null?void 0:n.events;if(Array.isArray(o)&&o.length)return await r.wrap("deviceMsgs",a=>this._deviceMessageHandler.prepareSync(o,t,i,a))}async writeSync(e,t,i,r,n){const o={syncInfo:null,e2eeAccountChanges:null},a=e.next_batch;if(a!==this.syncToken){const u={token:a,filterId:t};r.session.set("sync",u),o.syncInfo=u}const c=e.device_one_time_keys_count;this._e2eeAccount&&c&&(o.e2eeAccountChanges=this._e2eeAccount.writeSync(c,r,n));const l=e.device_lists;this._deviceTracker&&Array.isArray(l?.changed)&&l.changed.length&&await n.wrap("deviceLists",u=>this._deviceTracker.writeDeviceChanges(l.changed,r,u)),i&&(o.hasNewRoomKeys=await n.wrap("deviceMsgs",u=>this._deviceMessageHandler.writeSync(i,r,u)));const d=e.account_data;if(Array.isArray(d?.events))for(const u of d.events)typeof u.type=="string"&&r.accountData.set(u);return o}afterSync({syncInfo:e,e2eeAccountChanges:t}){e&&(this._syncInfo=e),this._e2eeAccount&&this._e2eeAccount.afterSync(t)}async afterSyncCompleted(e,t,i){var r;t||await this._e2eeAccount.generateOTKsIfNeeded(this._storage,i)&&await i.wrap("uploadKeys",o=>this._e2eeAccount.uploadKeys(this._storage,!1,o)),e.hasNewRoomKeys&&((r=this._keyBackup.get())==null||r.flush(i))}_tryReplaceRoomBeingCreated(e,t){for(const[,i]of this._roomsBeingCreated)if(i.roomId===e){const r=this._observedRoomStatus.get(i.id);r&&(t.log("replacing room being created").set("localId",i.id).set("roomId",i.roomId),r.set(r.get()|G.Replaced)),i.dispose(),this._roomsBeingCreated.remove(i.id);return}}applyRoomCollectionChangesAfterSync(e,t,i,r){var n,o;for(const a of t)a.shouldAdd?(this._rooms.add(a.id,a.room),this._tryReplaceRoomBeingCreated(a.id,r)):a.shouldRemove&&this._rooms.remove(a.id);for(const a of e)a.shouldAdd?this._invites.add(a.id,a.invite):a.shouldRemove&&this._invites.remove(a.id);if(this._observedRoomStatus.size!==0){for(const a of i)a.shouldAdd&&((n=this._observedRoomStatus.get(a.id))==null||n.set(G.Archived));for(const a of t)a.shouldAdd&&((o=this._observedRoomStatus.get(a.id))==null||o.set(G.Joined));for(const a of e){const c=this._observedRoomStatus.get(a.id);if(c){const l=c.get()|G.Invited;if(a.shouldAdd)c.set(l);else if(a.shouldRemove){const d=l^G.Invited;c.set(d)}}}}}_forgetArchivedRoom(e){const t=this._observedRoomStatus.get(e);t&&t.set((t.get()|G.Archived)^G.Archived)}get syncToken(){var e;return(e=this._syncInfo)==null?void 0:e.token}get syncFilterId(){var e;return(e=this._syncInfo)==null?void 0:e.filterId}get user(){return this._user}get mediaRepository(){return this._mediaRepository}enablePushNotifications(e){return e?this._enablePush():this._disablePush()}async _enablePush(){return this._platform.logger.run("enablePush",async e=>{const t=kt.createDefaultPayload(this._sessionInfo.id),i=await this._platform.notificationService.enablePush(kt,t);if(!i)return e.set("no_pusher",!0),!1;await i.enable(this._hsApi,e);const r=await this._storage.readWriteTxn([this._storage.storeNames.session]);return r.session.set(bi,i.serialize()),await r.complete(),!0})}async _disablePush(){return this._platform.logger.run("disablePush",async e=>{await this._platform.notificationService.disablePush();const i=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(bi);if(!i)return!0;await new kt(i).disable(this._hsApi,e);const n=await this._storage.readWriteTxn([this._storage.storeNames.session]);return n.session.remove(bi),await n.complete(),!0})}async arePushNotificationsEnabled(){return await this._platform.notificationService.isPushEnabled()?!!await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(bi):!1}async checkPusherEnabledOnHomeserver(){const t=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(bi);if(!t)return!1;const i=new kt(t),r=await this._hsApi.getPushers().response();return(r?.pushers||[]).map(o=>new kt(o)).some(o=>o.equals(i))}async getRoomStatus(e){if(!!this._roomsBeingCreated.get(e))return G.BeingCreated;if(!!this._rooms.get(e))return G.Joined;{const r=!!this._invites.get(e),o=await(await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary])).archivedRoomSummary.has(e);return r&&o?G.Invited|G.Archived:r?G.Invited:o?G.Archived:G.None}}async observeRoomStatus(e){let t=this._observedRoomStatus.get(e);if(!t){const i=await this.getRoomStatus(e);t=new Gs(i,()=>{this._observedRoomStatus.delete(e)}),this._observedRoomStatus.set(e,t)}return t}createOrGetArchivedRoomForSync(e){let t=this._activeArchivedRooms.get(e);return t?t.retain():t=this._createArchivedRoom(e),t}loadArchivedRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"loadArchivedRoom",async i=>{i.set("id",e);const r=this._activeArchivedRooms.get(e);if(r)return r.retain(),r;const n=await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary,this._storage.storeNames.roomMembers]),o=await n.archivedRoomSummary.get(e);if(o){const a=this._createArchivedRoom(e);return await a.load(o,n,i),a}})}joinRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"joinRoom",async i=>(await this._hsApi.joinIdOrAlias(e,{log:i}).response()).room_id)}}class $g{constructor({username:e,password:t,homeserver:i}){this._username=e,this._password=t,this.homeserver=i}async login(e,t,i){return await e.passwordLogin(this._username,this._password,t,{log:i}).response()}}class jg{constructor({homeserver:e,loginToken:t}){this.homeserver=e,this._loginToken=t}async login(e,t,i){return await e.tokenLogin(this._loginToken,$r(),t,{log:i}).response()}}class Gg{constructor(e){this._homeserver=e}get homeserver(){return this._homeserver}createSSORedirectURL(e){return`${this._homeserver}/_matrix/client/r0/login/sso/redirect?redirectUrl=${e}`}}class Un{constructor(e,t){this._session=e,this._params=t}setNextStage(e){this._nextStage=e}get nextStage(){return this._nextStage}}class qg extends Un{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.dummy"}}class zg extends Un{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.terms"}get privacyPolicy(){var e;return(e=this._params)==null?void 0:e.policies.privacy_policy}get termsOfService(){var e;return(e=this._params)==null?void 0:e.policies.terms_of_service}}class Hg extends Un{constructor(e,t,i){super(e,t),this._type=i}generateAuthenticationData(){if(!this._token)throw new Error("No token provided for TokenAuth");return{session:this._session,type:this._type,token:this._token}}setToken(e){this._token=e}get type(){return this._type}}class Wg{constructor(e,t,i,r){this.homeserver=e,this._hsApi=t,this._accountDetails=i,this._flowSelector=r??(n=>n[0])}async start(){const e=await this._hsApi.register(this._accountDetails.username,this._accountDetails.password,this._accountDetails.initialDeviceDisplayName,void 0,this._accountDetails.inhibitLogin).response();return this.parseStagesFromResponse(e)}async submitStage(e){const t=e.generateAuthenticationData(),{username:i,password:r,initialDeviceDisplayName:n,inhibitLogin:o}=this._accountDetails,a=this._hsApi.register(i,r,n,t,o),c=await a.response(),l=await a.responseCode(),d=_u(Oi({},c),{status:l});return this.parseRegistrationResponse(d,e)}parseStagesFromResponse(e){const{session:t,params:i}=e,r=this._flowSelector(e.flows);if(!r)throw new Error("flowSelector did not return any flow!");let n,o;for(const a of r.stages){const c=this._createRegistrationStage(a,t,i);n?(o.setNextStage(c),o=c):(n=c,o=c)}return n}async parseRegistrationResponse(e,t){var i;switch(e.status){case 200:this._registerResponse=e;return;case 401:if((i=e.completed)!=null&&i.includes(t.type))return t.nextStage;throw new Error("This stage could not be completed!")}}_createRegistrationStage(e,t,i){switch(e){case"m.login.dummy":return new qg(t,i?.[e]);case"m.login.terms":return new zg(t,i?.[e]);case"org.matrix.msc3231.login.registration_token":case"m.login.registration_token":return new Hg(t,i?.[e],e);default:throw new Error(`Unknown stage: ${e}`)}}get authData(){if(this._registerResponse)return{accessToken:this._registerResponse.access_token,homeserver:this.homeserver,userId:this._registerResponse.user_id,deviceId:this._registerResponse.device_id}}}const L=We("NotLoading","Login","LoginFailed","QueryAccount","AccountSetup","Loading","SessionSetup","Migrating","FirstSync","Error","Ready"),Ds=We("Connection","Credentials","Unknown");class Yg{constructor(e){this._platform=e,this._sessionStartedByReconnector=!1,this._status=new qe(L.NotLoading),this._error=null,this._loginFailure=null,this._reconnector=null,this._session=null,this._sync=null,this._sessionId=null,this._storage=null,this._requestScheduler=null,this._olmPromise=e.loadOlm(),this._workerPromise=e.loadOlmWorker(),this._accountSetup=void 0}createNewSessionId(){return Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER).toString()}get sessionId(){return this._sessionId}async startWithExistingSession(e){this._status.get()===L.NotLoading&&(this._status.set(L.Loading),await this._platform.logger.run("load session",async t=>{t.set("id",e);try{const i=await this._platform.sessionInfoStorage.get(e);if(!i)throw new Error("Invalid session id: "+e);await this._loadSessionInfo(i,null,t),t.set("status",this._status.get())}catch(i){t.catch(i),this._error=i,this._status.set(L.Error)}}))}_parseLoginOptions(e,t){const i=e.flows,r={homeserver:t};for(const n of i)n.type==="m.login.password"?r.password=(o,a)=>new $g({homeserver:t,username:o,password:a}):n.type==="m.login.sso"&&i.find(o=>o.type==="m.login.token")?r.sso=new Gg(t):n.type==="m.login.token"&&(r.token=o=>new jg({homeserver:t,loginToken:o}));return r}queryLogin(e){return new Jc(async t=>{e=await Qm(e,(n,o)=>t(this._platform.request(n,o)));const i=new Tt({homeserver:e,request:this._platform.request}),r=await t(i.getLoginFlows()).response();return this._parseLoginOptions(r,e)})}async startRegistration(e,t,i,r,n){const o=this._platform.request,a=new Tt({homeserver:e,request:o});return new Wg(e,a,{username:t,password:i,initialDeviceDisplayName:r},n)}async startWithAuthData({accessToken:e,deviceId:t,userId:i,homeserver:r}){await this._platform.logger.run("startWithAuthData",async n=>{await this._createSessionAfterAuth({accessToken:e,deviceId:t,userId:i,homeserver:r},!0,n)})}async startWithLogin(e,{inspectAccountSetup:t}={}){const i=this._status.get();i!==L.LoginFailed&&i!==L.NotLoading&&i!==L.Error||(this._resetStatus(),await this._platform.logger.run("login",async r=>{this._status.set(L.Login);let n;try{const o=this._platform.request,a=new Tt({homeserver:e.homeserver,request:o}),c=await e.login(a,"Hydrogen",r);n={deviceId:c.device_id,userId:c.user_id,homeserver:e.homeserver,accessToken:c.access_token}}catch(o){this._error=o,o.name==="HomeServerError"?(o.errcode==="M_FORBIDDEN"?this._loginFailure=Ds.Credentials:this._loginFailure=Ds.Unknown,r.set("loginFailure",this._loginFailure),this._status.set(L.LoginFailed)):o.name==="ConnectionError"?(this._loginFailure=Ds.Connection,this._status.set(L.LoginFailed)):this._status.set(L.Error);return}await this._createSessionAfterAuth(n,t,r)}))}async _createSessionAfterAuth({deviceId:e,userId:t,accessToken:i,homeserver:r},n,o){const a=this.createNewSessionId(),c=this._platform.clock.now(),l={id:a,deviceId:e,userId:t,homeServer:r,homeserver:r,accessToken:i,lastUsed:c};let d;n&&(d=await this._inspectAccountAfterLogin(l,o),d&&(l.deviceId=d.deviceId)),await this._platform.sessionInfoStorage.add(l);try{await this._loadSessionInfo(l,d,o),o.set("status",this._status.get())}catch(u){o.catch(u),d?.dispose(),this._error=u,this._status.set(L.Error)}}async _loadSessionInfo(e,t,i){i.set("appVersion",this._platform.version);const r=this._platform.clock;this._sessionStartedByReconnector=!1,this._status.set(L.Loading),this._reconnector=new i_({onlineStatus:this._platform.onlineStatus,retryDelay:new Qc(r.createTimeout),createMeasure:r.createMeasure});const n=new Tt({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request,reconnector:this._reconnector});this._sessionId=e.id,this._storage=await this._platform.storageFactory.create(e.id,i);const o={id:e.id,deviceId:e.deviceId,userId:e.userId,homeserver:e.homeServer},a=await this._olmPromise;let c=null;this._workerPromise&&(c=await this._workerPromise),this._requestScheduler=new a_({hsApi:n,clock:r}),this._requestScheduler.start();const l=new n_({homeserver:e.homeServer,platform:this._platform});if(this._session=new Kg({storage:this._storage,sessionInfo:o,hsApi:this._requestScheduler.hsApi,olm:a,olmWorker:c,mediaRepository:l,platform:this._platform}),await this._session.load(i),t?(await i.wrap("dehydrateIdentity",d=>this._session.dehydrateIdentity(t,d)),await this._session.setupDehydratedDevice(t.key,i)):this._session.hasIdentity||(this._status.set(L.SessionSetup),await i.wrap("createIdentity",d=>this._session.createIdentity(d))),this._sync=new d_({hsApi:this._requestScheduler.hsApi,storage:this._storage,session:this._session,logger:this._platform.logger}),this._reconnectSubscription=this._reconnector.connectionStatus.subscribe(d=>{d===In.Online&&this._platform.logger.runDetached("reconnect",async u=>{this._requestScheduler.start(),this._sync.start(),this._sessionStartedByReconnector=!0;const h=t;t=void 0,await u.wrap("session start",m=>this._session.start(this._reconnector.lastVersionsResponse,h,m))})}),await i.wrap("wait first sync",()=>this._waitForFirstSync()),!this._isDisposed&&(this._status.set(L.Ready),!this._sessionStartedByReconnector)){const d=await n.versions({timeout:1e4,log:i}).response();if(this._isDisposed)return;const u=t;t=void 0,await i.wrap("session start",h=>this._session.start(d,u,h))}}async _waitForFirstSync(){this._sync.start(),this._status.set(L.FirstSync),this._waitForFirstSyncHandle=this._sync.status.waitFor(e=>{var t;return e===j.Stopped?((t=this._sync.error)==null?void 0:t.name)!=="ConnectionError":e===j.Syncing});try{if(await this._waitForFirstSyncHandle.promise,this._sync.status.get()===j.Stopped&&this._sync.error)throw this._sync.error}catch(e){if(e.name==="AbortError")return;throw e}finally{this._waitForFirstSyncHandle=null}}_inspectAccountAfterLogin(e,t){return t.wrap("inspectAccount",async i=>{var r;this._status.set(L.QueryAccount);const n=new Tt({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request}),o=await this._olmPromise;let a;try{a=await tg(n,o,this._platform,i)}catch(c){if(c.name==="HomeServerError")i.set("not_supported",!0);else throw c}if(a){let c;const l=new Promise(u=>c=u);this._accountSetup=new Jg(a,c),this._status.set(L.AccountSetup),await l;const d=(r=this._accountSetup)==null?void 0:r._dehydratedDevice;return this._accountSetup=null,d}})}get accountSetup(){return this._accountSetup}get loadStatus(){return this._status}get loadError(){return this._error}get loginFailure(){return this._loginFailure}get sync(){return this._sync}get session(){return this._session}get reconnector(){return this._reconnector}get _isDisposed(){return!this._reconnector}startLogout(e){return this._platform.logger.run("logout",async t=>{this._sessionId=e,t.set("id",this._sessionId);const i=await this._platform.sessionInfoStorage.get(this._sessionId);if(!i)throw new Error(`Could not find session for id ${this._sessionId}`);try{await new Tt({homeserver:i.homeServer,accessToken:i.accessToken,request:this._platform.request}).logout({log:t}).response()}catch{}await this.deleteSession(t)})}startForcedLogout(e){return this._platform.logger.run("forced-logout",async t=>{this._sessionId=e,t.set("id",this._sessionId),await this.deleteSession(t)})}dispose(){this._reconnectSubscription&&(this._reconnectSubscription(),this._reconnectSubscription=null),this._reconnector=null,this._requestScheduler&&(this._requestScheduler.stop(),this._requestScheduler=null),this._sync&&(this._sync.stop(),this._sync=null),this._session&&(this._session.dispose(),this._session=null),this._waitForFirstSyncHandle&&(this._waitForFirstSyncHandle.dispose(),this._waitForFirstSyncHandle=null),this._storage&&(this._storage.close(),this._storage=null)}async deleteSession(e){this._sessionId&&(this.dispose(),await Promise.all([e.wrap("storageFactory",()=>this._platform.storageFactory.delete(this._sessionId)),e.wrap("sessionInfoStorage",()=>this._platform.sessionInfoStorage.delete(this._sessionId))]),this._sessionId=null)}_resetStatus(){this._status.set(L.NotLoading),this._error=null,this._loginFailure=null}}class Jg{constructor(e,t){this._encryptedDehydratedDevice=e,this._dehydratedDevice=void 0,this._finishStage=t}get encryptedDehydratedDevice(){return this._encryptedDehydratedDevice}finish(e){this._dehydratedDevice=e,this._finishStage()}}class Xg{constructor(e){this._observables=new Map,this._allowsChild=e,this._path=new Ve([],e),this._pathObservable=new qe(this._path)}get pathObservable(){return this._pathObservable}get path(){return this._path}push(e,...t){const i=this.path.with(new pe(e,...t));i&&this.applyPath(i)}applyPath(e){const t=this._path;this._path=e;for(let i=t.segments.length-1;i>=0;i-=1){const r=t.segments[i];if(!this._path.get(r.type)){const n=this._observables.get(r.type);n?.emitIfChanged()}}for(const i of this._path.segments){const r=this._observables.get(i.type);r?.emitIfChanged()}this._pathObservable.set(this._path)}observe(e){let t=this._observables.get(e);return t||(t=new Zg(this,e),this._observables.set(e,t)),t}pathFrom(e){let t,i;for(i=0;i<e.length;i+=1){if(!this._allowsChild(t,e[i]))return new Ve(e.slice(0,i),this._allowsChild);t=e[i]}return new Ve(e,this._allowsChild)}segment(e,...t){return new pe(e,...t)}}function Qg(s,e){if(s===e)return!0;if(Array.isArray(s)&&Array.isArray(e)){const t=Math.max(s.length,e.length);for(let i=0;i<t;i+=1)if(s[i]!==e[i])return!1;return!0}return!1}class pe{constructor(e,...t){this.type=e,this.value=t[0]===void 0?!0:t[0]}}class Ve{constructor(e=[],t){this._segments=e,this._allowsChild=t}clone(){return new Ve(this._segments.slice(),this._allowsChild)}with(e){let t=this._segments.length-1;do{if(this._allowsChild(this._segments[t],e)){const i=this._segments.slice(0,t+1);return i.push(e),new Ve(i,this._allowsChild)}t-=1}while(t>=-1)}until(e){const t=this._segments.findIndex(i=>i.type===e);return t!==-1?new Ve(this._segments.slice(0,t+1),this._allowsChild):new Ve([],this._allowsChild)}get(e){return this._segments.find(t=>t.type===e)}replace(e){const t=this._segments.findIndex(i=>i.type===e.type);if(t!==-1){const i=this._segments[t-1];if(this._allowsChild(i,e)){const r=this._segments[t+1];if(!r||this._allowsChild(e,r)){const n=this._segments.slice();return n[t]=e,new Ve(n,this._allowsChild)}}}}get segments(){return this._segments}}class Zg extends di{constructor(e,t){var i;super(),this._navigation=e,this._type=t,this._lastSetValue=(i=e.path.get(t))==null?void 0:i.value}get(){const t=this._navigation.path.get(this._type);return t?.value}emitIfChanged(){const e=this.get();Qg(e,this._lastSetValue)||(this._lastSetValue=e,this.emit(e))}}class ey{constructor(e,t,i,r){this._isApplyingUrl=!1,this._history=e,this._navigation=t,this._parseUrlPath=i,this._stringifyPath=r,this._defaultSessionId=this._getLastSessionId()}_getLastSessionId(){var e;const i=(e=this._urlAsNavPath(this._history.getLastSessionUrl()||"").get("session"))==null?void 0:e.value;if(typeof i=="string")return i}attach(){this._subscription=this._history.subscribe(e=>this._applyUrl(e)),this._pathSubscription=this._navigation.pathObservable.subscribe(e=>this._applyNavPathToHistory(e)),this._applyUrl(this._history.get())}dispose(){this._subscription&&(this._subscription=this._subscription()),this._pathSubscription&&(this._pathSubscription=this._pathSubscription())}_applyNavPathToHistory(e){const t=this.urlForPath(e);t!==this._history.get()&&(this._isApplyingUrl?this._history.replaceUrlSilently(t):this._history.pushUrlSilently(t))}_applyNavPathToNavigation(e){this._isApplyingUrl=!0,this._navigation.applyPath(e),this._isApplyingUrl=!1}_urlAsNavPath(e){const t=this._history.urlAsPath(e);return this._navigation.pathFrom(this._parseUrlPath(t,this._navigation.path,this._defaultSessionId))}_applyUrl(e){const t=this._urlAsNavPath(e);this._applyNavPathToNavigation(t)}pushUrl(e){this._history.pushUrl(e)}tryRestoreLastUrl(){const e=this._urlAsNavPath(this._history.getLastSessionUrl()||"");return e.segments.length!==0?(this._applyNavPathToNavigation(e),!0):!1}urlForSegments(e){let t=this._navigation.path;for(const i of e)if(t=t.with(i),!t)return;return this.urlForPath(t)}urlForSegment(e,...t){return this.urlForSegments([this._navigation.segment(e,...t)])}urlUntilSegment(e){return this.urlForPath(this._navigation.path.until(e))}urlForPath(e){return this._history.pathAsUrl(this._stringifyPath(e))}openRoomActionUrl(e){const t=`${this._stringifyPath(this._navigation.path.until("session"))}/open-room/${e}`;return this._history.pathAsUrl(t)}createSSOCallbackURL(){return window.location.origin}normalizeUrl(){this._history.replaceUrlSilently(`${window.location.origin}/${window.location.hash}`)}}function ty({history:s,navigation:e}){return new ey(s,e,ry,sy)}function iy(s,e,t){if(s.value.includes(e))return s;{const i=t.get("empty-grid-tile"),r=t.get("room");let n=0;i?n=i.value:r&&(n=s.value.indexOf(r.value));const o=s.value.slice();return o[n]=e,new pe("rooms",o)}}function Ta(s,e,...t){s.push(new pe("right-panel")),s.push(new pe(e,...t))}function ry(s,e,t){const i=s.substring(1).split("/"),r=i[Symbol.iterator](),n=[];let o;for(;!(o=r.next()).done;){const a=o.value;if(a==="rooms"){const c=r.next().value;if(c===void 0)break;const l=c.split(",");n.push(new pe(a,l));const d=parseInt(r.next().value||"0",10),u=l[d];u?n.push(new pe("room",u)):n.push(new pe("empty-grid-tile",d))}else if(a==="open-room"){const c=r.next().value;if(!c)break;const l=e.get("rooms");if(l&&n.push(iy(l,c,e)),n.push(new pe("room",c)),i.findIndex(h=>h==="open-room")>=i.length-2){const h=e.segments,m=h.findIndex(_=>_.type==="right-panel");m!==-1&&n.push(...h.slice(m))}}else if(a==="last-session"){let c=e.get("session");typeof c?.value!="string"&&t&&(c=new pe("session",t)),c&&n.push(c)}else if(a==="details"||a==="members")Ta(n,a);else if(a==="member"){const c=r.next().value;if(!c)break;Ta(n,a,c)}else if(a.includes("loginToken")){const c=a.split("=").pop();n.push(new pe("sso",c))}else{const c=r.next().value;n.push(new pe(a,c))}}return n}function sy(s){let e="",t;for(const i of s.segments){switch(i.type){case"rooms":e+=`/rooms/${i.value.join(",")}`;break;case"empty-grid-tile":e+=`/${i.value}`;break;case"room":t?.type==="rooms"?e+=`/${t.value.indexOf(i.value)}`:e+=`/${i.type}/${i.value}`;break;case"right-panel":case"sso":continue;default:e+=`/${i.type}`,i.value&&i.value!==!0&&(e+=`/${i.value}`)}t=i}return e}class Pe extends Xi{constructor(e){super(),this._isDisposed=!1,this._options=e}childOptions(e){return Object.assign({},this._options,e)}get options(){return this._options}getOption(e){return this._options[e]}observeNavigation(e,t){const r=this.navigation.observe(e).subscribe(n=>{t(n,e)});this.track(r)}track(e){return this.disposables||(this.disposables=new En),this.disposables.track(e)}untrack(e){if(this.disposables)return this.disposables.untrack(e)}dispose(){this.disposables&&this.disposables.dispose(),this._isDisposed=!0}get isDisposed(){return this._isDisposed}disposeTracked(e){if(this.disposables)return this.disposables.disposeTracked(e)}i18n(e,...t){let i="";for(let r=0;r<e.length;++r)i=i+e[r],r<t.length&&(i=i+t[r]);return i}emitChange(e){this._options.emitChange?this._options.emitChange(e):this.emit("change",e)}get platform(){return this._options.platform}get clock(){return this._options.platform.clock}get logger(){return this.platform.logger}get urlCreator(){return this._options.urlCreator}get navigation(){return this._options.navigation}}function Bn(s){let e=s.charAt(0);return(e==="!"||e==="@"||e==="#")&&(e=s.charAt(1)),e.toUpperCase()}function ny(s){let e=0,t,i;if(s.length===0)return e;for(t=0;t<s.length;t++)i=s.charCodeAt(t),e=(e<<5)-e+i,e|=0;return Math.abs(e)}function Ln(s){return ny(s)%8+1}function El(s,e,t,i){if(s){const r=e*t.devicePixelRatio;return i.mxcUrlThumbnail(s,r,r,"crop")}return null}class Ae{constructor(e,t,i,r){this._remove=e,this._update=t,this._replace=i,this._updateParams=r}get shouldReplace(){return this._replace}get shouldRemove(){return this._remove}get shouldUpdate(){return this._update}get updateParams(){return this._updateParams}static Remove(){return new Ae(!0,!1,!1,null)}static Update(e){return new Ae(!1,!0,!1,e)}static Nothing(){return new Ae(!1,!1,!1,null)}static Replace(e){return new Ae(!1,!1,!0,e)}}class oy extends ui{constructor(e,t){super(),this._entries=e,this._tiles=null,this._entrySubscription=null,this._tileOptions=t,this._emitSpontanousUpdate=this._emitSpontanousUpdate.bind(this)}_createTile(e){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}_emitSpontanousUpdate(e,t){const i=e.lowerEntry,r=this._findTileIdx(i);this.emitUpdate(r,e,t)}onSubscribeFirst(){this._entrySubscription=this._entries.subscribe(this),this._populateTiles()}_populateTiles(){this._tiles=[];let e=null;for(let i of this._entries)(!e||!e.tryIncludeEntry(i))&&(e=this._createTile(i),e&&this._tiles.push(e));let t=null;for(let i of this._tiles)t&&t.updateNextSibling(i),i.updatePreviousSibling(t),t=i;t&&t.updateNextSibling(null);for(const i of this._tiles)i.setUpdateEmit(this._emitSpontanousUpdate)}_findTileIdx(e){return ct(this._tiles,e,(t,i)=>-i.compareEntry(t))}_findTileAtIdx(e,t){const i=this._getTileAtIdx(t);if(i&&i.compareEntry(e)===0)return i}_getTileAtIdx(e){return e>=0&&e<this._tiles.length?this._tiles[e]:null}onUnsubscribeLast(){this._entrySubscription=this._entrySubscription();for(let e=0;e<this._tiles.length;e+=1)this._tiles[e].dispose();this._tiles=null}onReset(){this._buildInitialTiles(),this.emitReset()}onAdd(e,t){const i=this._findTileIdx(t),r=this._getTileAtIdx(i-1);if(r&&r.tryIncludeEntry(t)){this.emitUpdate(i-1,r);return}const n=this._getTileAtIdx(i);if(n&&n.tryIncludeEntry(t)){this.emitUpdate(i,n);return}const o=this._createTile(t);o&&(r&&(r.updateNextSibling(o),o.updatePreviousSibling(r)),n&&(o.updateNextSibling(n),n.updatePreviousSibling(o)),this._tiles.splice(i,0,o),this.emitAdd(i,o),o.setUpdateEmit(this._emitSpontanousUpdate))}onUpdate(e,t,i){if(!this._tiles)return;const r=this._findTileIdx(t),n=this._findTileAtIdx(t,r);if(n){const o=n.updateEntry(t,i);if(o.shouldReplace){const a=this._createTile(t);a?(this._replaceTile(r,n,a,o.updateParams),a.setUpdateEmit(this._emitSpontanousUpdate)):this._removeTile(r,n)}o.shouldRemove&&this._removeTile(r,n),o.shouldUpdate&&this.emitUpdate(r,n,o.updateParams)}}_replaceTile(e,t,i,r){t.dispose();const n=this._getTileAtIdx(e-1),o=this._getTileAtIdx(e+1);this._tiles[e]=i,n?.updateNextSibling(i),i.updatePreviousSibling(n),i.updateNextSibling(o),o?.updatePreviousSibling(i),this.emitUpdate(e,i,r)}_removeTile(e,t){const i=this._getTileAtIdx(e-1),r=this._getTileAtIdx(e+1);this._tiles.splice(e,1),t.dispose(),this.emitRemove(e,t),i?.updateNextSibling(r),r?.updatePreviousSibling(i)}onRemove(e,t){const i=this._findTileIdx(t),r=this._findTileAtIdx(t,i);r&&(r.removeEntry(t)?this._removeTile(i,r):this.emitUpdate(i,r))}onMove(){}[Symbol.iterator](){return this._tiles.values()}get length(){return this._tiles.length}getFirst(){return this._tiles[0]}getTileIndex(e){const t=ct(this._tiles,e,(r,n)=>r.compare(n)),i=this._tiles[t];return i?.compare(e)===0?t:-1}sliceIterator(e,t){return this._tiles.slice(e,t)[Symbol.iterator]()}}class ay extends Pe{constructor(e){super(e);const{timeline:t,tileOptions:i}=e;this._timeline=this.track(t),this._tiles=new oy(t.entries,i),this._startTile=null,this._endTile=null,this._topLoadingPromise=null,this._requestedStartTile=null,this._requestedEndTile=null,this._requestScheduled=!1,this._showJumpDown=!1}setVisibleTileRange(e,t){this._requestedStartTile=e,this._requestedEndTile=t,this._requestScheduled||(Promise.resolve().then(()=>{this._setVisibleTileRange(this._requestedStartTile,this._requestedEndTile),this._requestScheduled=!1}),this._requestScheduled=!0)}_setVisibleTileRange(e,t){let i;if(e&&t){this._startTile=e,this._endTile=t;const r=this._tiles.getTileIndex(this._startTile),n=this._tiles.getTileIndex(this._endTile);for(const o of this._tiles.sliceIterator(r,n+1))o.notifyVisible();i=r<10,this._setShowJumpDown(n<this._tiles.length-1)}else i=!0,this._setShowJumpDown(!1);i&&!this._topLoadingPromise&&(this._topLoadingPromise=this._timeline.loadAtTop(10).then(r=>{this._topLoadingPromise=null,r||this.setVisibleTileRange(this._requestedStartTile,this._requestedEndTile)}))}get tiles(){return this._tiles}_setShowJumpDown(e){this._showJumpDown!==e&&(this._showJumpDown=e,this.emitChange("showJumpDown"))}get showJumpDown(){return this._showJumpDown}}class cy extends Pe{constructor(e){super(e.options),this._roomVM=e,this._isEmpty=!0,this._replyVM=null}setReplyingTo(e){var t;(new Boolean(e)!==new Boolean(this._replyVM)||!((t=this._replyVM)!=null&&t.id.equals(e.asEventKey())))&&(this._replyVM=this.disposeTracked(this._replyVM),e&&(this._replyVM=this.track(this._roomVM._createTile(e)),this._replyVM.notifyVisible()),this.emitChange("replyViewModel"),this.emit("focus"))}clearReplyingTo(){this.setReplyingTo(null)}get replyViewModel(){return this._replyVM}get isEncrypted(){return this._roomVM.isEncrypted}async sendMessage(e){const t=await this._roomVM._sendMessage(e,this._replyVM);return t&&(this._isEmpty=!0,this.emitChange("canSend"),this.clearReplyingTo()),t}sendPicture(){this._roomVM._pickAndSendPicture()}sendFile(){this._roomVM._pickAndSendFile()}sendVideo(){this._roomVM._pickAndSendVideo()}get canSend(){return!this._isEmpty}async setInput(e){const t=this._isEmpty;this._isEmpty=e.length===0,t&&!this._isEmpty&&this._roomVM._room.ensureMessageKeyIsShared(),t!==this._isEmpty&&this.emitChange("canSend")}get kind(){return"composer"}}function Dr(s){return{w:s.width,h:s.height,mimetype:s.blob.mimeType,size:s.blob.size}}class Zi extends Pe{constructor(e,t){super(t),this._entry=e,this._emitUpdate=void 0}get shape(){return null}get isContinuation(){return!1}get hasDateSeparator(){return!1}get id(){return this._entry.asEventKey()}get eventId(){return this._entry.id}get isPending(){return this._entry.isPending}get isUnsent(){return this._entry.isPending&&this._entry.pendingEvent.status!==P.Sent}get canAbortSending(){return this._entry.isPending&&!this._entry.pendingEvent.hasStartedSending}abortSending(){var e;(e=this._entry.pendingEvent)==null||e.abort()}setUpdateEmit(e){this._emitUpdate=e}emitChange(e){this._emitUpdate&&this._emitUpdate(this,e),super.emitChange(e)}get upperEntry(){return this._entry}get lowerEntry(){return this._entry}compare(e){return this.upperEntry.compare(e.upperEntry)}compareEntry(e){return this._entry.compare(e)}updateEntry(e,t){const i=this.shape==="redacted";return!e.isGap&&e.isRedacted!==i?Ae.Replace("shape"):(this._entry=e,Ae.Update(t))}removeEntry(){return!0}tryIncludeEntry(){return!1}updatePreviousSibling(){}updateNextSibling(){}notifyVisible(){}dispose(){this.setUpdateEmit(null),super.dispose()}get _room(){return this._roomVM.room}get _roomVM(){return this._options.roomVM}get _timeline(){return this._options.timeline}get _powerLevels(){return this._timeline.powerLevels}get _ownMember(){return this._options.timeline.me}}class ly extends Zi{constructor(e,t){super(e,t),this._loading=!1,this._error=null,this._isAtTop=!0,this._siblingChanged=!1,this._showSpinner=!1}async fill(){if(!this._loading&&!this._entry.edgeReached){this._loading=!0,this._error=null,this._showSpinner=!0,this.emitChange("isLoading");try{await this._room.fillGap(this._entry,10)}catch(e){throw console.error(`room.fillGap(): ${e.message}:
${e.stack}`),this._error=e,e instanceof Se&&(this.emitChange("error"),await this._waitForReconnection()),e}finally{this._loading=!1,this._showSpinner=!1,this.emitChange("isLoading")}return!0}return!1}async notifyVisible(){let e=0,t;this._siblingChanged=!1;do{try{t=await this.fill()}catch(i){if(i instanceof Se){t=!0;continue}else t=!1}e=e+1}while(e<10&&!this._siblingChanged&&t&&!this.isDisposed)}get isAtTop(){return this._isAtTop}updatePreviousSibling(e){super.updatePreviousSibling(e);const t=!e;this._isAtTop!==t&&(this._isAtTop=t,this.emitChange("isAtTop")),this._siblingChanged=!0}updateNextSibling(){this._siblingChanged=!0}updateEntry(e,t){return super.updateEntry(e,t),e.isGap?Ae.Nothing():Ae.Remove()}async _waitForReconnection(){await this.options.client.reconnector.connectionStatus.waitFor(e=>e===In.Online).promise}get shape(){return"gap"}get isLoading(){return this._loading}get showSpinner(){return this._showSpinner}get error(){return this._error?this._error instanceof Se?"Waiting for reconnection":`Could not load ${this._entry.prev_batch?"previous":"next"} messages: ${this._error.message}`:null}get currentAction(){return this.error?this.error:this.isLoading?"Loading":"Not Loading"}}class dy{constructor(e){this._parentTile=e,this._map=new Ni,this._reactions=this._map.sortValues((t,i)=>t._compare(i))}update(e,t){if(e){for(const i in e)if(e.hasOwnProperty(i)){const r=e[i],n=this._map.get(i);n?n._tryUpdate(r)&&this._map.update(i):this._map.add(i,new xa(i,r,null,this._parentTile))}}if(t)for(const[i,r]of t.entries()){const n=this._map.get(i);n?(n._tryUpdatePending(r),this._map.update(i)):this._map.add(i,new xa(i,null,r,this._parentTile))}for(const i of this._map.keys()){const r=t?.has(i),n=e?.hasOwnProperty(i);!n&&!r?this._map.remove(i):n?r||this._map.get(i)._tryUpdatePending(null)&&this._map.update(i):this._map.get(i)._tryUpdate(null)&&this._map.update(i)}}get reactions(){return this._reactions}getReaction(e){return this._map.get(e)}}class xa{constructor(e,t,i,r){this._key=e,this._annotation=t,this._pending=i,this._parentTile=r,this._isToggling=!1}_tryUpdate(e){const t=!!this._annotation!=!!e,r=this._annotation&&e&&(e.me!==this._annotation.me||e.count!==this._annotation.count||e.firstTimestamp!==this._annotation.firstTimestamp);return t||r?(this._annotation=e,!0):!1}_tryUpdatePending(e){return!e&&!this._pending?!1:(this._pending=e,!0)}get key(){return this._key}get count(){var e,t;return(((e=this._pending)==null?void 0:e.count)||0)+(((t=this._annotation)==null?void 0:t.count)||0)}get isPending(){return this._pending!==null}get isActive(){var e;return((e=this._annotation)==null?void 0:e.me)||this.isPending}get firstTimestamp(){let e=Number.MAX_SAFE_INTEGER;return this._annotation&&(e=Math.min(e,this._annotation.firstTimestamp)),this._pending&&(e=Math.min(e,this._pending.firstTimestamp)),e}_compare(e){if(e===this)return 0;if(this.count!==e.count)return e.count-this.count;{const t=this.firstTimestamp-e.firstTimestamp;return t===0?this.key<e.key?-1:1:t}}async toggle(e=null){if(this._isToggling){console.log("busy toggling reaction already");return}this._isToggling=!0;try{await this._parentTile.toggleReaction(this.key,e)}finally{this._isToggling=!1}}}class yt extends Zi{constructor(e,t){super(e,t),this._date=this._entry.timestamp?new Date(this._entry.timestamp):null,this._isContinuation=!1,this._reactions=null,this._replyTile=null,(this._entry.annotations||this._entry.pendingAnnotations)&&this._updateReactions(),this._updateReplyTileIfNeeded(void 0)}notifyVisible(){var e;super.notifyVisible(),(e=this._replyTile)==null||e.notifyVisible()}get _mediaRepository(){return this._room.mediaRepository}get permaLink(){return`https://matrix.to/#/${encodeURIComponent(this._room.id)}/${encodeURIComponent(this._entry.id)}`}get senderProfileLink(){return`https://matrix.to/#/${encodeURIComponent(this.sender)}`}get displayName(){return this._entry.displayName||this.sender}get sender(){return this._entry.sender}get memberPanelLink(){return`${this.urlCreator.urlUntilSegment("room")}/member/${this.sender}`}get avatarColorNumber(){return Ln(this._entry.sender)}avatarUrl(e){return El(this._entry.avatarUrl,e,this.platform,this._mediaRepository)}get avatarLetter(){return Bn(this.sender)}get avatarTitle(){return this.displayName}get date(){return this._date&&this._date.toLocaleDateString({},{month:"numeric",day:"numeric"})}get time(){return this._date&&this._date.toLocaleTimeString({},{hour:"numeric",minute:"2-digit"})}get isOwn(){return this._entry.sender===this._ownMember.userId}get isContinuation(){return this._isContinuation}get isUnverified(){return this._entry.isUnverified}get isReply(){return this._entry.isReply}_getContent(){return this._entry.content}updatePreviousSibling(e){super.updatePreviousSibling(e);let t=!1;if(e&&e instanceof yt&&e.sender===this.sender){const i=this._entry.timestamp,r=e._entry.timestamp;t=i-r<5*60*1e3}t!==this._isContinuation&&(this._isContinuation=t,this.emitChange("isContinuation"))}updateEntry(e,t){const i=super.updateEntry(e,t);return i.shouldUpdate&&this._updateReactions(),this._updateReplyTileIfNeeded(t),i}_updateReplyTileIfNeeded(e){var t,i;const r=this._entry.contextEntry;if(r){const n=(t=this._replyTile)==null?void 0:t.updateEntry(r,e);if(n?.shouldReplace||!this._replyTile){this.disposeTracked(this._replyTile);const o=this._options.tileClassForEntry,a=o(r);a&&(this._replyTile=new a(r,this._options))}n?.shouldUpdate&&((i=this._replyTile)==null||i.emitChange())}}startReply(){this._roomVM.startReply(this._entry)}reply(e,t,i=null){return this._room.sendEvent("m.room.message",this._entry.reply(e,t),null,i)}redact(e,t){return this._room.sendRedaction(this._entry.id,e,t)}get canRedact(){return this._powerLevels.canRedactFromSender(this._entry.sender)}get reactions(){return this.shape!=="redacted"?this._reactions:null}get canReact(){return this._powerLevels.canSendType("m.reaction")}react(e,t=null){return this.logger.wrapOrRun(t,"react",async i=>{var r,n;if(!this.canReact){i.set("powerlevel_lacking",!0);return}if(this._entry.haveAnnotation(e)){i.set("already_reacted",!0);return}const o=(n=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:n.redactionEntry;o&&!o.pendingEvent.hasStartedSending?(i.set("abort_redaction",!0),await o.pendingEvent.abort()):await this._room.sendEvent("m.reaction",this._entry.annotate(e),null,i)})}redactReaction(e,t=null){return this.logger.wrapOrRun(t,"redactReaction",async i=>{var r,n;if(!this._powerLevels.canRedactFromSender(this._ownMember.userId)){i.set("powerlevel_lacking",!0);return}if(!this._entry.haveAnnotation(e)){i.set("not_yet_reacted",!0);return}let o=(n=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:n.annotationEntry;o||(o=await this._timeline.getOwnAnnotationEntry(this._entry.id,e)),o?await this._room.sendRedaction(o.id,null,i):i.set("no_reaction",!0)})}toggleReaction(e,t=null){return this.logger.wrapOrRun(t,"toggleReaction",async i=>{this._entry.haveAnnotation(e)?await this.redactReaction(e,i):await this.react(e,i)})}_updateReactions(){const{annotations:e,pendingAnnotations:t}=this._entry;!e&&!t?this._reactions&&(this._reactions=null):(this._reactions||(this._reactions=new dy(this)),this._reactions.update(e,t))}get replyTile(){return this._entry.contextEventId?this._replyTile:null}}const uy="(?:https|http|ftp):\\/\\/",Il="[^\\s.,?!)]",ka="[a-zA-Z0-9:.\\[\\]-]",hy=`${ka}*(?=${ka})${Il}`,py=`(?:[\\/#](?:[^\\s]*${Il})?)`,my=`${uy}${hy}${py}?`,_y=new RegExp(my,"gi");function Tl(s,e){const t=s.matchAll(_y);let i=0;for(let n of t){const o=s.slice(i,n.index);e(o,!1),e(n[0],!0);const a=n[0].length;i=n.index+a}const r=s.slice(i);e(r,!1)}function fy(s){const e=[],t=s.split(`
`),i=(r,n)=>{n?e.push(new rn(r,[new ni(r)])):e.push(new ni(r))};for(let r=0;r<t.length;r+=1){const n=t[r];n.length&&Tl(n,i),r>=t.length-1||e.push(new xl)}return new Fn(s,e)}function gy(s){return new Fn(s,[new ni(s)])}class yy{constructor(e,t){this.level=e,this.inlines=t}get type(){return"header"}}class Ra{constructor(e,t){this.language=e,this.text=t}get type(){return"codeblock"}}class vy{constructor(e,t){this.items=t,this.startOffset=e}get type(){return"list"}}class wy{constructor(e,t){this.head=e,this.body=t}get type(){return"table"}}class by{get type(){return"rule"}}class xl{get type(){return"newline"}}class br{constructor(e,t){this.format=e.toLowerCase(),this.children=t}get type(){return"format"}}class Sy{constructor(e,t,i,r,n){this.src=e,this.width=t,this.height=i,this.alt=r,this.title=n}get type(){return"image"}}class Ey{constructor(e,t,i){this.id=e,this.href=t,this.children=i}get type(){return"pill"}get avatarColorNumber(){return Ln(this.id)}get avatarInitials(){return Bn(this.id)}}class rn{constructor(e,t){this.url=e,this.inlines=t}get type(){return"link"}}class ni{constructor(e){this.text=e}get type(){return"text"}}function Iy(s){return s.type==="format"&&s.format==="blockquote"}class Fn{constructor(e,t){this.sourceString=e,this.parts=t}insertEmote(e){let t=0;for(;t<this.parts.length&&Iy(this.parts[t]);t++);this.parts.splice(t,0,new ni(e))}}const xi=We("Plain","Html");class kl extends yt{constructor(e,t){super(e,t),this._messageBody=null,this._format=null}get shape(){return"message"}_parseBody(e){return gy(e)}_getBodyFormat(){return xi.Plain}get body(){const e=this._getBody(),t=this._getBodyFormat();return(!this._messageBody||this._messageBody.sourceString!==e||this._format!==t)&&(this._messageBody=this._parseBody(e,t),this._format=t),this._messageBody}}const Ty=["EM","STRONG","CODE","DEL","SPAN"],xy=["DIV","BLOCKQUOTE"],ky=["https","http","ftp","mailto","magnet"].map(s=>`${s}://`),Ry="https://matrix.to",Aa=`${Ry}/#/`;class Ay{constructor(e,t){this.result=e,this.mediaRepository=t}parsePillLink(e){if(!e.startsWith(Aa))return null;const t=e.substring(Aa.length);return t[0]==="@"?t:null}parseLink(e,t){const i=this.result.getAttributeValue(e,"href"),r=i?.toLowerCase();if(!r||!ky.some(o=>r.startsWith(o)))return new br("span",t);const n=this.parsePillLink(i);return n?new Ey(n,i,t):new rn(i,t)}parseList(e){const t=this.result;let i=null;t.getNodeElementName(e)==="OL"&&(i=parseInt(t.getAttributeValue(e,"start"))||1);const r=[];for(const n of t.getChildNodes(e)){if(t.getNodeElementName(n)!=="LI")continue;const o=this.parseAnyNodes(t.getChildNodes(n));r.push(o)}return new vy(i,r)}_ensureElement(e,t){return e&&this.result.isElementNode(e)&&this.result.getNodeElementName(e)===t}parseCodeBlock(e){const t=this.result;let i;for(const o of t.getChildNodes(e)){i=o;break}let r=null;if(!this._ensureElement(i,"CODE"))return new Ra(r,this.result.getNodeText(e));const n=t.getAttributeValue(i,"class")||"";for(const o of n.split(" "))if(o.startsWith("language-")&&!o.startsWith("language-_")){r=o.substring(9);break}return new Ra(r,this.result.getNodeText(i))}parseImage(e){const t=this.result,i=t.getAttributeValue(e,"src")||"",r=this.mediaRepository.mxcUrl(i);if(!r)return null;const n=parseInt(t.getAttributeValue(e,"width"))||null,o=parseInt(t.getAttributeValue(e,"height"))||null,a=t.getAttributeValue(e,"alt"),c=t.getAttributeValue(e,"title");return new Sy(r,n,o,a,c)}parseTableRow(e,t){const i=[];for(const r of this.result.getChildNodes(e)){if(!this._ensureElement(r,t))continue;const n=this.result.getChildNodes(r),o=this.parseInlineNodes(n);i.push(o)}return i}parseTableHead(e){let t=null;for(const i of this.result.getChildNodes(e)){t=i;break}return this._ensureElement(t,"TR")?this.parseTableRow(t,"TH"):null}parseTableBody(e){const t=[];for(const i of this.result.getChildNodes(e))!this._ensureElement(i,"TR")||t.push(this.parseTableRow(i,"TD"));return t}parseTable(e){const t=Array.from(this.result.getChildNodes(e));let i,r;return this._ensureElement(t[0],"THEAD")&&this._ensureElement(t[1],"TBODY")?(i=this.parseTableHead(t[0]),r=this.parseTableBody(t[1])):this._ensureElement(t[0],"TBODY")&&(i=null,r=this.parseTableBody(t[0])),new wy(i,r)}parseInlineElement(e){const t=this.result,i=t.getNodeElementName(e),r=t.getChildNodes(e);switch(i){case"A":{const n=this.parseInlineNodes(r);return this.parseLink(e,n)}case"BR":return new xl;default:{if(!Ty.includes(i))return null;const n=this.parseInlineNodes(r);return new br(i,n)}}}parseInlineNode(e){return this.result.isElementNode(e)?this.parseInlineElement(e):null}parseBlockElement(e){const t=this.result,i=t.getNodeElementName(e),r=t.getChildNodes(e);switch(i){case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":{const n=this.parseInlineNodes(r);return new yy(parseInt(i[1]),n)}case"UL":case"OL":return this.parseList(e);case"PRE":return this.parseCodeBlock(e);case"HR":return new by;case"IMG":return this.parseImage(e);case"P":{const n=this.parseInlineNodes(r);return new br(i,n)}case"TABLE":return this.parseTable(e);default:{if(!xy.includes(i))return null;const n=this.parseAnyNodes(r);return new br(i,n)}}}parseBlockNode(e){return this.result.isElementNode(e)?this.parseBlockElement(e):null}_parseTextParts(e,t){if(!this.result.isTextNode(e))return!1;const i=(r,n)=>{n?t.push(new rn(r,[new ni(r)])):t.push(new ni(r))};return Tl(this.result.getNodeText(e),i),!0}_isAllowedNode(e){return!this._ensureElement(e,"MX-REPLY")}_parseInlineNodes(e,t){for(const i of e){if(this._parseTextParts(i,t))continue;const r=this.parseInlineNode(i);if(r){t.push(r);continue}this._isAllowedNode(i)&&this._parseInlineNodes(this.result.getChildNodes(i),t)}}parseInlineNodes(e){const t=[];return this._parseInlineNodes(e,t),t}_parseAnyNodes(e,t){for(const i of e){if(this._parseTextParts(i,t))continue;const r=this.parseInlineNode(i)||this.parseBlockNode(i);if(r){t.push(r);continue}this._isAllowedNode(i)&&this._parseAnyNodes(this.result.getChildNodes(i),t)}}parseAnyNodes(e){const t=[];return this._parseAnyNodes(e,t),t}}function Cy(s,e,t){const i=s.parseHTML(t),n=new Ay(i,e).parseAnyNodes(i.rootNodes);return new Fn(t,n)}class Rl extends kl{_getContentString(e){var t;return((t=this._getContent())==null?void 0:t[e])||""}_getPlainBody(){return this._getContentString("body")}_getFormattedBody(){return this._getContentString("formatted_body")}_getBody(){return this._getBodyFormat()===xi.Html?this._getFormattedBody():this._getPlainBody()}_getBodyFormat(){var e;return((e=this._getContent())==null?void 0:e.format)==="org.matrix.custom.html"?xi.Html:xi.Plain}_parseBody(e,t){var i;let r;return t===xi.Html?r=Cy(this.platform,this._mediaRepository,e):r=fy(e),((i=this._getContent())==null?void 0:i.msgtype)==="m.emote"&&r.insertEmote(`* ${this.displayName} `),r}}class sn extends yt{get shape(){return"redacted"}get description(){const{redactionReason:e}=this._entry;return this.isRedacting?e?this.i18n`This message is being deleted (${e})…`:this.i18n`This message is being deleted…`:e?this.i18n`This message has been deleted (${e}).`:this.i18n`This message has been deleted.`}get isRedacting(){return this._entry.isRedacting}get canRedact(){return!1}abortPendingRedaction(){return this._entry.abortPendingRedaction()}}const Ny=300,My=400;class Al extends yt{constructor(e,t){super(e,t),this._decryptedThumbnail=null,this._decryptedFile=null,this._isVisible=!1,this._error=null,this._downloading=!1,this._downloadError=null}async downloadMedia(){if(this._downloading||this.isPending)return;const e=this._getContent(),t=e.body;this._downloading=!0,this.emitChange("status");let i;try{i=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(i,t)}catch(r){this._downloadError=r}finally{i?.dispose(),this._downloading=!1}this.emitChange("status")}get isUploading(){return this.isPending&&this._entry.pendingEvent.status===P.UploadingAttachments}get uploadPercentage(){const{pendingEvent:e}=this._entry;return e&&Math.round(e.attachmentsSentBytes/e.attachmentsTotalBytes*100)}get status(){const{pendingEvent:e}=this._entry;switch(e?.status){case P.Waiting:return this.i18n`Waiting…`;case P.EncryptingAttachments:case P.Encrypting:return this.i18n`Encrypting…`;case P.UploadingAttachments:return this.i18n`Uploading…`;case P.Sending:return this.i18n`Sending…`;case P.Error:return this.i18n`Error: ${e.error.message}`;default:return this._downloadError?"Download failed":this._downloading?this.i18n`Downloading…`:""}}get thumbnailUrl(){var e,t;if(!this._isVisible)return"";if(this._decryptedThumbnail)return this._decryptedThumbnail.url;{const i=(e=this._getContent().info)==null?void 0:e.thumbnail_url;if(i)return this._mediaRepository.mxcUrlThumbnail(i,this.width,this.height,"scale")}if(this._entry.isPending){const i=this._entry.pendingEvent.getAttachment("info.thumbnail_url");return i&&i.localPreview.url}if(this._isMainResourceImage()){if(this._decryptedFile)return this._decryptedFile.url;{const i=(t=this._getContent())==null?void 0:t.url;if(typeof i=="string")return this._mediaRepository.mxcUrlThumbnail(i,this.width,this.height,"scale")}}return""}notifyVisible(){super.notifyVisible(),this._isVisible=!0,this.emitChange("thumbnailUrl"),this.isPending||this._tryLoadEncryptedThumbnail()}get width(){var e;const t=(e=this._getContent())==null?void 0:e.info;return Math.round(t?.w*this._scaleFactor())}get height(){var e;const t=(e=this._getContent())==null?void 0:e.info;return Math.round(t?.h*this._scaleFactor())}get mimeType(){var e;const t=(e=this._getContent())==null?void 0:e.info;return t?.mimetype}get label(){return this._getContent().body}get error(){return this._error?`Could not load media: ${this._error.message}`:null}setViewError(e){this._error=e,this.emitChange("error")}async _loadEncryptedFile(e){const t=await this._mediaRepository.downloadEncryptedFile(e,!0);if(this.isDisposed){t.dispose();return}return this.track(t)}async _tryLoadEncryptedThumbnail(){var e;try{const t=(e=this._getContent().info)==null?void 0:e.thumbnail_file,i=this._getContent().file;t?(this._decryptedThumbnail=await this._loadEncryptedFile(t),this.emitChange("thumbnailUrl")):i&&this._isMainResourceImage()&&(this._decryptedFile=await this._loadEncryptedFile(i),this.emitChange("thumbnailUrl"))}catch(t){this._error=t,this.emitChange("error")}}_scaleFactor(){var e;const t=(e=this._getContent())==null?void 0:e.info,i=Ny/t?.h,r=My/t?.w;return Math.min(r,i,1)}_isMainResourceImage(){return!0}}class Cl extends Al{constructor(e,t){super(e,t),this._lightboxUrl=this.urlCreator.urlForSegments([this.navigation.segment("room",this._room.id),this.navigation.segment("lightbox",this._entry.id)])}get lightboxUrl(){return this.isPending?"":this._lightboxUrl}get shape(){return"image"}}class Nl extends Al{async loadVideo(){const e=this._getContent().file;e&&!this._decryptedFile&&(this._decryptedFile=await this._loadEncryptedFile(e),this.emitChange("videoUrl"))}get videoUrl(){var e;if(this._decryptedFile)return this._decryptedFile.url;const t=(e=this._getContent())==null?void 0:e.url;return typeof t=="string"?this._mediaRepository.mxcUrl(t):""}get shape(){return"video"}_isMainResourceImage(){return!1}}function Dy(s,e=2){if(Number.isSafeInteger(s)){const t=Math.min(3,Math.floor(Math.log(s)/Math.log(1024))),i=Math.round(s/Math.pow(1024,t)).toFixed(e);switch(t){case 0:return`${i} bytes`;case 1:return`${i} KB`;case 2:return`${i} MB`;case 3:return`${i} GB`}}return""}class Ml extends yt{constructor(e,t){super(e,t),this._downloadError=null,this._downloading=!1}async download(){if(this._downloading||this.isPending)return;const e=this._getContent(),t=e.body;this._downloading=!0,this.emitChange("label");let i;try{i=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(i,t)}catch(r){this._downloadError=r}finally{i?.dispose(),this._downloading=!1}this.emitChange("label")}get label(){var e;if(this._downloadError)return`Could not download file: ${this._downloadError.message}`;const i=this._getContent().body;if(this._entry.isPending){const{pendingEvent:r}=this._entry;switch(r?.status){case P.Waiting:return this.i18n`Waiting to send ${i}`;case P.EncryptingAttachments:case P.Encrypting:return this.i18n`Encrypting ${i}`;case P.UploadingAttachments:{const n=Math.round(r.attachmentsSentBytes/r.attachmentsTotalBytes*100);return this.i18n`Uploading ${i}: ${n}%`}case P.Sending:case P.Sent:return this.i18n`Sending ${i}`;case P.Error:return this.i18n`Error: could not send ${i}: ${r.error.message}`;default:return`Unknown send status for ${i}`}}else{const r=Dy((e=this._getContent().info)==null?void 0:e.size);return this._downloading?this.i18n`Downloading ${i} (${r})…`:this.i18n`Download ${i} (${r})`}}get shape(){return"file"}}class Dl extends yt{get shape(){return"location"}get mapsLink(){try{const e=new URL(this._getContent().geo_uri);if(e.protocol!=="geo:")return"";const[t,...i]=e.pathname.split(";"),[r,n]=t.split(","),o=parseFloat(r),a=parseFloat(n);let c;for(const l of i){const[d,u]=l.split("=");d==="u"&&(c=parseFloat(u))}if(this.platform.isIOS)return`http://maps.apple.com/?ll=${o},${a}`;{let l=`geo:${o},${a}`;return c&&(l=l+`;u=${c}`),l}}catch{return""}}get label(){return this.i18n`${this.displayName} sent their location`}}class Py extends Zi{get shape(){return"announcement"}get announcement(){const e=this._entry.content;return`${this._entry.displayName||this._entry.sender} named the room "${e?.name}"`}}class Oy extends Zi{get shape(){return"announcement"}get announcement(){var e,t;const{sender:i,content:r,prevContent:n,stateKey:o}=this._entry,a=this._entry.displayName||i,c=i===o?a:((e=this._entry.content)==null?void 0:e.displayname)||o,l=r&&r.membership,d=n&&n.membership;if(d==="join"&&l==="join"){if(r.avatar_url!==n.avatar_url)return`${a} changed their avatar`;if(r.displayname!==n.displayname)return r.displayname?`${(t=n.displayname)!=null?t:o} changed their name to ${r.displayname}`:`${o} removed their name (${n.displayname})`}else{if(l==="join")return`${c} joined the room`;if(l==="invite")return`${c} was invited to the room by ${a}`;if(d==="invite"){if(l==="join")return`${c} accepted the invitation to join the room`;if(l==="leave")return`${c} declined the invitation to join the room`}else if(l==="leave"){if(o===i)return`${c} left the room`;{const u=r.reason;return`${c} was kicked from the room by ${a}${u?`: ${u}`:""}`}}else if(l==="ban")return`${c} was banned from the room by ${a}`}return`${i} membership changed to ${r.membership}`}}class Uy extends kl{updateEntry(e,t){const i=super.updateEntry(e,t);return e.eventType!=="m.room.encrypted"?Ae.Replace("shape"):i}get shape(){return"message-status"}_getBody(){const e=this._entry.decryptionError,t=e?.code;let i;return t==="MEGOLM_NO_SESSION"?i=this.i18n`The sender hasn't sent us the key for this message yet.`:i=e?.message||this.i18n`Could not decrypt message because of unknown reason.`,i}}class Pl extends Zi{get shape(){return"announcement"}get announcement(){const e=this._entry.displayName||this._entry.sender;return this.i18n`${e} has enabled end-to-end encryption`}}class By extends yt{get shape(){return"missing-attachment"}get label(){const e=this._getContent().body;return this._getContent().msgtype==="m.image"?this.i18n`The image ${e} wasn't fully sent previously and could not be recovered.`:this.i18n`The file ${e} wasn't fully sent previously and could not be recovered.`}}function nn(s){if(s.isGap)return ly;if(s.isPending&&s.pendingEvent.isMissingAttachments)return By;if(s.eventType)switch(s.eventType){case"m.room.message":{if(s.isRedacted)return sn;const e=s.content;switch(e&&e.msgtype){case"m.text":case"m.notice":case"m.emote":return Rl;case"m.image":return Cl;case"m.video":return Nl;case"m.file":return Ml;case"m.location":return Dl;default:return}}case"m.room.name":return Py;case"m.room.member":return Oy;case"m.room.encrypted":return s.isRedacted?sn:Uy;case"m.room.encryption":return Pl;default:return}}async function Ly(s,e){var t,i,r,n;try{const o=await e.joinRoom(s);return await(await e.observeRoomStatus(o)).waitFor(c=>c===G.Joined),o}catch(o){throw((t=o.statusCode)!=null?t:o.status)===400?new Error(`'${s}' is not a legal room ID or alias`):((i=o.statusCode)!=null?i:o.status)===404||((r=o.statusCode)!=null?r:o.status)===502||o.message=="Internal Server eor"?new Error(`Room '${s}' could not be found`):((n=o.statusCode)!=null?n:o.status)===403?new Error(`You are not invited to join '${s}'`):o}}class Fy extends Pe{constructor(e){super(e);const{room:t,tileClassForEntry:i}=e;this._room=t,this._timelineVM=null,this._tileClassForEntry=i??nn,this._tileOptions=void 0,this._onRoomChange=this._onRoomChange.bind(this),this._timelineError=null,this._sendError=null,this._composerVM=null,t.isArchived?this._composerVM=this.track(new Ky(this.childOptions({archivedRoom:t}))):this._recreateComposerOnPowerLevelChange(),this._clearUnreadTimout=null,this._closeUrl=this.urlCreator.urlUntilSegment("session")}async load(){this._room.on("change",this._onRoomChange);try{const e=await this._room.openTimeline();this._tileOptions=this.childOptions({roomVM:this,timeline:e,tileClassForEntry:this._tileClassForEntry}),this._timelineVM=this.track(new ay(this.childOptions({tileOptions:this._tileOptions,timeline:e}))),this.emitChange("timelineViewModel")}catch(e){console.error(`room.openTimeline(): ${e.message}:
${e.stack}`),this._timelineError=e,this.emitChange("error")}this._clearUnreadAfterDelay()}async _recreateComposerOnPowerLevelChange(){const e=await this._room.observePowerLevels(),t=()=>e.get().canSendType("m.room.message");let i=t();const r=n=>{this._composerVM=this.disposeTracked(this._composerVM),n?this._composerVM=this.track(new cy(this)):this._composerVM=this.track(new $y(this.childOptions())),this.emitChange("powerLevelObservable")};this.track(e.subscribe(()=>{const n=t();i!==n&&(r(n),i=n)})),r(i)}async _clearUnreadAfterDelay(){if(!(this._room.isArchived||this._clearUnreadTimout)){this._clearUnreadTimout=this.clock.createTimeout(2e3);try{await this._clearUnreadTimout.elapsed(),await this._room.clearUnread(),this._clearUnreadTimout=null}catch(e){if(e.name!=="AbortError")throw e}}}focus(){this._clearUnreadAfterDelay()}dispose(){super.dispose(),this._room.off("change",this._onRoomChange),this._room.isArchived&&this._room.release(),this._clearUnreadTimout&&(this._clearUnreadTimout.abort(),this._clearUnreadTimout=null)}_onRoomChange(){var e;(e=this._composerVM)==null||e.emitChange(),this.emitChange()}get kind(){return"room"}get closeUrl(){return this._closeUrl}get name(){return this._room.name||this.i18n`Empty Room`}get id(){return this._room.id}get timelineViewModel(){return this._timelineVM}get isEncrypted(){return this._room.isEncrypted}get error(){return this._timelineError?`Something went wrong loading the timeline: ${this._timelineError.message}`:this._sendError?`Something went wrong sending your message: ${this._sendError.message}`:""}get avatarLetter(){return Bn(this.name)}get avatarColorNumber(){return Ln(this._room.avatarColorId)}avatarUrl(e){return El(this._room.avatarUrl,e,this.platform,this._room.mediaRepository)}get avatarTitle(){return this.name}get canLeave(){return this._room.isJoined}leaveRoom(){this._room.leave()}get canForget(){return this._room.isArchived}forgetRoom(){this._room.forget()}get canRejoin(){return this._room.isArchived}rejoinRoom(){this._room.join()}_createTile(e){if(this._tileOptions){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}}async _processCommandJoin(e){try{const t=this._options.client.session,i=await Ly(e,t);this.navigation.push("room",i)}catch(t){this._sendError=t,this._timelineError=null,this.emitChange("error")}}async _processCommand(e){let t;const[i,...r]=e.substring(1).split(" ");switch(i){case"me":e=r.join(" "),t="m.emote";break;case"join":if(r.length===1){const n=r[0];await this._processCommandJoin(n)}else this._sendError=new Error("join syntax: /join <room-id>"),this._timelineError=null,this.emitChange("error");break;case"shrug":e="\xAF\\_(\u30C4)_/\xAF "+r.join(" "),t="m.text";break;case"tableflip":e="(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B "+r.join(" "),t="m.text";break;case"unflip":e="\u252C\u2500\u2500\u252C \u30CE( \u309C-\u309C\u30CE) "+r.join(" "),t="m.text";break;case"lenny":e="( \u0361\xB0 \u035C\u0296 \u0361\xB0) "+r.join(" "),t="m.text";break;default:this._sendError=new Error(`no command name "${i}". To send the message instead of executing, please type "/${e}"`),this._timelineError=null,this.emitChange("error"),e=void 0}return{type:t,message:e}}async _sendMessage(e,t){if(!this._room.isArchived&&e){let i={type:"m.text",message:e};e.startsWith("//")?i.message=e.substring(1).trim():e.startsWith("/")&&(i=await this._processCommand(e));try{const r=i.type,n=i.message;r&&n&&(t?await t.reply(r,n):await this._room.sendEvent("m.room.message",{msgtype:r,body:n}))}catch(r){return console.error(`room.sendMessage(): ${r.message}:
${r.stack}`),this._sendError=r,this._timelineError=null,this.emitChange("error"),!1}return!0}return!1}async _pickAndSendFile(){try{const e=await this.platform.openFile();return e?this._sendFile(e):void 0}catch(e){console.error(e)}}async _sendFile(e){const t={body:e.name,msgtype:"m.file"};await this._room.sendEvent("m.room.message",t,{url:this._room.createAttachment(e.blob,e.name)})}async _pickAndSendVideo(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("video/*");if(!e)return;if(!e.blob.mimeType.startsWith("video/"))return this._sendFile(e);let t;try{t=await this.platform.loadVideo(e.blob)}catch(c){throw c instanceof window.MediaError&&c.code===4?new Error(`this browser does not support videos of type ${e?.blob.mimeType}.`):c}const i={body:e.name,msgtype:"m.video",info:Vy(t)},r={url:this._room.createAttachment(t.blob,e.name)},o=await this.platform.settingsStorage.getInt("sentImageSizeLimit")||Math.min(t.maxDimension,800),a=await t.scale(o);i.info.thumbnail_info=Dr(a),r["info.thumbnail_url"]=this._room.createAttachment(a.blob,e.name),await this._room.sendEvent("m.room.message",i,r)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}async _pickAndSendPicture(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("image/*");if(!e)return;if(!e.blob.mimeType.startsWith("image/"))return this._sendFile(e);let t=await this.platform.loadImage(e.blob);const i=await this.platform.settingsStorage.getInt("sentImageSizeLimit");if(i&&t.maxDimension>i){const o=await t.scale(i);t.dispose(),t=o}const r={body:e.name,msgtype:"m.image",info:Dr(t)},n={url:this._room.createAttachment(t.blob,e.name)};if(t.maxDimension>600){const o=await t.scale(400);r.info.thumbnail_info=Dr(o),n["info.thumbnail_url"]=this._room.createAttachment(o.blob,e.name)}await this._room.sendEvent("m.room.message",r,n)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}get room(){return this._room}get composerViewModel(){return this._composerVM}openDetailsPanel(){let e=this.navigation.path.until("room");e=e.with(this.navigation.segment("right-panel",!0)),e=e.with(this.navigation.segment("details",!0)),this.navigation.applyPath(e)}startReply(e){this._room.isArchived||this._composerVM.setReplyingTo(e)}dismissError(){this._sendError=null,this.emitChange("error")}}function Vy(s){const e=Dr(s);return e.duration=s.duration,e}class Ky extends Pe{constructor(e){super(e),this._archivedRoom=e.archivedRoom}get description(){return this._archivedRoom.isKicked?this._archivedRoom.kickReason?this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`:this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name}.`:this._archivedRoom.isBanned?this._archivedRoom.kickReason?this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`:this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name}.`:this.i18n`You left this room`}get kind(){return"disabled"}}class $y extends Pe{get description(){return this.i18n`You do not have the powerlevel necessary to send messages`}get kind(){return"disabled"}}We("Disconnected","Connecting","FirstSync","Sending","Syncing","SyncError");We("Enabled","SetupKey","SetupPhrase","Pending","NewVersionAvailable");We("Writing","Stopped","Done","Pending");class jy extends Rl{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class Gy extends Cl{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class qy extends Nl{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class zy extends Ml{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class Hy extends Dl{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class Wy extends sn{get displayName(){return this.isOwn?"me":super.displayName}get avatarLetter(){return""}avatarUrl(e){return this.isOwn?this._options.config.avatar??null:super.avatarUrl(e)}}class Yy extends Pl{get announcement(){return this.i18n`This room is end-to-end encrypted 🔒`}}function Jy(s){return function(t){switch(t.eventType){case"m.room.message":if(t.isRedacted)return Wy;const i=t.content;switch(i&&i.msgtype){case"m.text":case"m.notice":case"m.emote":return jy;case"m.image":return Gy;case"m.video":return qy;case"m.file":return zy;case"m.location":return Hy;default:return}case"m.room.member":return(t.content?.membership==="join"||t.content?.membership==="leave")&&t.sender!==s?nn(t):void 0;case"m.room.encryption":return Yy;default:return nn(t)}}}class Xy extends Pe{_roomViewModel;_loginPromise;constructor(e){super(e),this._client=e.client,this._loginPromise=e.loginPromise,this.emitOnRoomViewModelChange=this.emitOnRoomViewModelChange.bind(this)}async load(){await this._loginPromise;let e;if(this._options.config.invite_user)e=await this.createRoomWithUserSpecifiedInConfig();else if(this._options.config.auto_join_room)e=await this.joinRoomSpecifiedInConfig();else throw new Error("ConfigError: You must either specify 'invite_user' or 'auto_join_room'");this._roomViewModel=this.track(new Fy(this.childOptions({room:e,ownUserId:this._session.userId,platform:this.platform,urlCreator:this.urlCreator,navigation:this.navigation,tileClassForEntry:Jy(this._session.userId)}))),await this._roomViewModel.load(),this._roomViewModel.on("change",this.emitOnRoomViewModelChange),this.emitChange("roomViewModel")}emitOnRoomViewModelChange(){this.emitChange("roomViewModel")}async createRoomWithUserSpecifiedInConfig(){const e=this._options.config.invite_user,t=this._session.userId;let i=await this.findPreviouslyCreatedRoom();if(i)return i;const r=this._options.config.disable_composer_until_operator_join?{users:{[e]:100,[t]:60},events:{"m.room.message":80},redact:90}:null,n=this._session.createRoom({type:1,name:void 0,topic:void 0,isEncrypted:this._options.config.encrypt_room??!1,isFederationDisabled:!1,alias:void 0,avatar:void 0,invites:[e],powerLevelContentOverride:r});await(await this._session.observeRoomStatus(n.id)).waitFor(c=>c===(G.BeingCreated|G.Replaced)).promise;const a=n.roomId;return await this.platform.settingsStorage.setString("created-room-id",a),await this.platform.settingsStorage.setString("invite-user",e),i=this._session.rooms.get(a),i}async joinRoomSpecifiedInConfig(){const e=this._options.config.auto_join_room;let t=this._session.rooms.get(e);return t||(await this._session.joinRoom(e),await this._waitForRoomFromSync(e),t=this._session.rooms.get(e)),t}_waitForRoomFromSync(e){let t;const i=new Promise(n=>{t=n}),r={onAdd:(n,o)=>{o.id===e&&(this._session.rooms.unsubscribe(r),t())},onUpdate:()=>{},onRemove:()=>{}};return this._session.rooms.subscribe(r),i}async findPreviouslyCreatedRoom(){const e=await this.platform.settingsStorage.getString("created-room-id"),t=await this.platform.settingsStorage.getString("invite-user"),i=this._options.config.invite_user;return e&&t===i?this._session.rooms.get(e):null}dispose(){super.dispose(),this._roomViewModel.off("change",this.emitOnRoomViewModelChange)}minimize(){window.sendMinimizeToParent(),this.navigation.push("minimize")}get timelineViewModel(){return this._roomViewModel?.timelineViewModel}get messageComposerViewModel(){return this._roomViewModel?.composerViewModel}get roomViewModel(){return this._roomViewModel}get roomName(){return this._options.config.header?.title??""}get customAvatarURL(){return this._options.config.header?.avatar}get _session(){return this._client.session}get footerViewModel(){return this.options.footerVM}}function Ol(s,e){let t="";const i=e.length;for(let r=0;r<s;r++)t+=e.charAt(Math.floor(Math.random()*i));return t}function Qy(s){return Ol(s," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~")}function Zy(s){return Ol(s,"abcdefghijklmnopqrstuvwxyz0123456789_-.=/")}class ev extends Pe{_config;_client;_startStage;_registration;_privacyPolicyLink;_showButtonSpinner=!1;constructor(e){super(e),this._client=e.client,this._config=e.config,this._startRegistration()}async _startRegistration(){const e=Qy(10),t=10;for(let i=0;i<t;++i)try{const r=`${this._config.username_prefix}-${Zy(10)}`,n=a=>{const c=["m.login.registration_token","org.matrix.msc3231.login.registration_token","m.login.terms","m.login.dummy"];for(const l of a){const d=l.stages.some(h=>!c.includes(h)),u=l.stages.includes("m.login.registration_token")||l.stages.includes("org.matrix.msc3231.login.registration_token");if(!d&&u)return l}};this._registration=await this._client.startRegistration(this._homeserver,r,e,"Chatterbox",n),this._startStage=await this._registration.start();let o=this._startStage;for(;o&&o.type!=="m.login.terms";)o=o.nextStage;if(!o){this.completeRegistration();return}this._privacyPolicyLink=o.privacyPolicy.en?.url,this.emitChange("privacyPolicyLink");break}catch(r){if(r.errcode!=="M_USER_IN_USE")throw r}}async completeRegistration(){this._showButtonSpinner=!0,this.emitChange("showButtonSpinner");let e=this._startStage;for(;e;)(e.type==="m.login.registration_token"||e.type==="org.matrix.msc3231.login.registration_token")&&e.setToken(this._config.token),e=await this._registration.submitStage(e);const t=this.setupSession();this.navigation.push("timeline",t)}async setupSession(){if(this._client.startWithAuthData(this._registration.authData),await this._client.loadStatus.waitFor(e=>e===L.Ready||e===L.Error||e===L.LoginFailed).promise,this._client.loginFailure)throw new Error("login failed: "+this._client.loginFailure);if(this._client.loadError)throw new Error("load failed: "+this._client.loadError.message)}minimize(){window.sendMinimizeToParent(),this.navigation.push("minimize")}get _homeserver(){return this._config.homeserver}get privacyPolicyLink(){return this._privacyPolicyLink}get footerViewModel(){return this.options.footerVM}get showButtonSpinner(){return this._showButtonSpinner}}class tv extends Pe{_config;constructor(e){super(e),this._config=e.config}get chatterboxLink(){return this._config.footer?.chatterbox_link??null}get matrixLink(){return this._config.footer?.matrix_link??null}}class iv extends Xi{constructor(){super(),window.addEventListener("message",e=>{const{action:t}=e.data;this.emit(t,e.data)})}}class rv extends Pe{_config;_client;_chatterBoxViewModel;_accountSetupViewModel;_activeSection;_messageFromParent=new iv;_startMinimized;_isWatchingNotificationCount;_footerViewModel;constructor(e,t){super(t),this._startMinimized=t.startMinimized,this._config=e,this._client=new Yg(this.platform),this._footerViewModel=new tv(this.childOptions({config:this._config})),this._setupNavigation(),this._messageFromParent.on("maximize",()=>this.start()),this._messageFromParent.on("minimize",()=>this.navigation.push("minimize"))}_setupNavigation(){this.navigation.observe("account-setup").subscribe(()=>this._showAccountSetup()),this.navigation.observe("timeline").subscribe(e=>this._showTimeline(e)),this.navigation.observe("minimize").subscribe(()=>this.minimizeChatterbox())}async start(){if(await this.attemptStartWithExistingSession()){if(this._isWatchingNotificationCount||this._watchNotificationCount(),this._startMinimized){this._startMinimized=!1;return}this.navigation.push("timeline");return}this.navigation.push("account-setup")}async _showTimeline(e){this._activeSection="timeline",this._chatterBoxViewModel||(this._chatterBoxViewModel=this.track(new Xy(this.childOptions({client:this._client,config:this._config,state:this._state,footerVM:this._footerViewModel,loginPromise:e}))),await this._chatterBoxViewModel.load(),this._isWatchingNotificationCount||this._watchNotificationCount()),this.emitChange("activeSection")}_showAccountSetup(){this._activeSection="account-setup",this._accountSetupViewModel=this.track(new ev(this.childOptions({client:this._client,config:this._config,state:this._state,footerVM:this._footerViewModel}))),this.emitChange("activeSection")}async attemptStartWithExistingSession(){const t=(await this.platform.sessionInfoStorage.getAll()).pop();if(t){const{id:i}=t;return await this._client.startWithExistingSession(i),!0}return!1}async _watchNotificationCount(){await this._client.loadStatus.waitFor(o=>o===L.Ready).promise;const e=await this.platform.settingsStorage.getString("created-room-id")??this._config.auto_join_room;await(await this._client.session.observeRoomStatus(e)).waitFor(o=>o===G.Joined).promise;let r=this._client.session.rooms.get(e).notificationCount;window.sendNotificationCount(r);const n={onUpdate(o,a){const c=a.notificationCount;if(c!==r){if(!a.isUnread&&c!==0){a.clearUnread();return}window.sendNotificationCount(c),r=c}}};this.track(this._client.session.rooms.subscribe(n)),this._isWatchingNotificationCount=!0}minimizeChatterbox(){this._chatterBoxViewModel=this.disposeTracked(this._chatterBoxViewModel),this._accountSetupViewModel=this.disposeTracked(this._chatterBoxViewModel),this._activeSection="",this.emitChange("chatterboxViewModel")}get chatterboxViewModel(){return this._chatterBoxViewModel}get accountSetupViewModel(){return this._accountSetupViewModel}get activeSection(){return this._activeSection}}class Ul extends S{render(e){return e.div({className:"ChatterboxLoadingView"},[e.div({className:"chatterbox-spinner"},[e.div({className:"loader"})]),e.span({className:"LoadingText"},"Loading")])}}var sv="/assets/chat-bubbles.be66ba17.svg";class Bl extends S{constructor(e){super(e)}render(e,t){return e.div({className:"FooterView"},[e.div([e.img({src:sv,className:"FooterView_logo"}),e.a({className:"FooterView_chatterbox-branding",href:t.chatterboxLink,target:"_top",rel:"noopener"},"Chatterbox")]),e.a({className:"FooterView_matrix-branding",href:t.matrixLink,target:"_top",rel:"noopener"},"Powered by Matrix")])}}class nv extends S{constructor(e){super(e)}render(e,t){return e.div({className:"AccountSetupView"},[e.mapView(i=>i.privacyPolicyLink,i=>i?new ov(t):new Ul),e.view(new Bl(t.footerViewModel))])}}class ov extends S{constructor(e){super(e)}render(e,t){return e.div({className:"PolicyAgreementView"},[e.div({className:"PolicyAgreementView_title"},"Your privacy comes first"),e.div({className:"PolicyAgreementView_text"},["Please accept our ",e.a({href:t.privacyPolicyLink},"Privacy Policy")," before proceeding to the chat."]),e.div({className:"PolicyAgreementView_btn-collection"},[e.button({onClick:()=>t.completeRegistration(),className:"PolicyAgreementView_next",disabled:i=>i.showButtonSpinner},e.map(i=>i.showButtonSpinner,(i,r)=>i?r.div({className:"loader"}):r.span("Accept and continue to chat"))),e.button({onClick:()=>t.minimize(),className:"button-action PolicyAgreementView_cancel"},"Cancel")])])}}class av extends S{constructor(e){super(e)}render(e,t){return e.div({className:"ChatterboxView"},[e.mapView(i=>i.roomViewModel?i:null,i=>i?new cv(i):null),e.mapView(i=>i.timelineViewModel,i=>i?new Bc(i,Ys):new Ul),e.mapView(i=>i.messageComposerViewModel,i=>i?.kind==="composer"?new Lc(i):new lv),e.view(new Bl(t.footerViewModel))])}}class cv extends S{constructor(e){super(e)}render(e,t){const i=t.customAvatarURL?e.img({className:"avatar",src:t.customAvatarURL}):e.view(new gt(t.roomViewModel,30));return e.div({className:"RoomHeaderView"},[i,e.div({className:"RoomHeaderView_name"},r=>r.roomName),e.div({className:"RoomHeaderView_menu"},[e.button({className:"RoomHeaderView_menu_minimize",onClick:()=>{t.minimize()}})])])}}class lv extends S{render(e){return e.div({className:"WaitingForOperatorJoinView"},[e.div({className:"FakeComposerContainer"},[e.span("Waiting for operator to join "),e.div({className:"loader"})])])}}class dv extends S{constructor(e){super(e)}render(e,t){return e.mapView(i=>i.activeSection,i=>{switch(window.sendViewChangeToParent(i),i){case"account-setup":return new nv(t.accountSetupViewModel);case"timeline":return new av(t.chatterboxViewModel)}return null})}}var uv="/assets/download-sandbox.48a866e9.html",hv="/assets/main.bdb9a925.js",pv="/assets/olm.b3e0f9b4.wasm",mv="/assets/olm.92f1ccd0.js",_v="/assets/olm_legacy.9dc48f49.js";function fv(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}function es(){return!fv()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}function ot(s,e){return s.require(e)}function gv(s){let e;try{e=ot(Ke,s)}catch{}try{const{cwd:t}=ot(Ke,"process");e=ot(Ke,`${t()}/node_modules/${s}`)}catch{}return e}var yv={};function M(){return es()?global:typeof window<"u"?window:typeof self<"u"?self:yv}function Vn(s,e,t){var i=t||M(),r=i.__SENTRY__=i.__SENTRY__||{},n=r[s]||(r[s]=e());return n}var Ll=Object.prototype.toString;function Fl(s){switch(Ll.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return Ye(s,Error)}}function pi(s,e){return Ll.call(s)===`[object ${e}]`}function Vl(s){return pi(s,"ErrorEvent")}function Ca(s){return pi(s,"DOMError")}function vv(s){return pi(s,"DOMException")}function _t(s){return pi(s,"String")}function Kl(s){return s===null||typeof s!="object"&&typeof s!="function"}function oi(s){return pi(s,"Object")}function Kn(s){return typeof Event<"u"&&Ye(s,Event)}function wv(s){return typeof Element<"u"&&Ye(s,Element)}function bv(s){return pi(s,"RegExp")}function $n(s){return Boolean(s&&s.then&&typeof s.then=="function")}function Sv(s){return oi(s)&&"nativeEvent"in s&&"preventDefault"in s&&"stopPropagation"in s}function $l(s){return typeof s=="number"&&s!==s}function Ye(s,e){try{return s instanceof e}catch{return!1}}function Ki(s,e){try{let a=s;var t=5,i=80,r=[];let c=0,l=0;var n=" > ",o=n.length;let d;for(;a&&c++<t&&(d=Ev(a,e),!(d==="html"||c>1&&l+r.length*o+d.length>=i));)r.push(d),l+=d.length,a=a.parentNode;return r.reverse().join(n)}catch{return"<unknown>"}}function Ev(s,e){var t=s,i=[];let r,n,o,a,c;if(!t||!t.tagName)return"";i.push(t.tagName.toLowerCase());var l=e&&e.length?e.filter(u=>t.getAttribute(u)).map(u=>[u,t.getAttribute(u)]):null;if(l&&l.length)l.forEach(u=>{i.push(`[${u[0]}="${u[1]}"]`)});else if(t.id&&i.push(`#${t.id}`),r=t.className,r&&_t(r))for(n=r.split(/\s+/),c=0;c<n.length;c++)i.push(`.${n[c]}`);var d=["type","name","title","alt"];for(c=0;c<d.length;c++)o=d[c],a=t.getAttribute(o),a&&i.push(`[${o}="${a}"]`);return i.join("")}function Iv(){var s=M();try{return s.document.location.href}catch{return""}}class re extends Error{constructor(e){super(e),this.message=e,this.name=new.target.prototype.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}}var Tv=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;function xv(s){return s==="http"||s==="https"}function jn(s,e=!1){const{host:t,path:i,pass:r,port:n,projectId:o,protocol:a,publicKey:c}=s;return`${a}://${c}${e&&r?`:${r}`:""}@${t}${n?`:${n}`:""}/${i&&`${i}/`}${o}`}function kv(s){var e=Tv.exec(s);if(!e)throw new re(`Invalid Sentry Dsn: ${s}`);const[t,i,r="",n,o="",a]=e.slice(1);let c="",l=a;var d=l.split("/");if(d.length>1&&(c=d.slice(0,-1).join("/"),l=d.pop()),l){var u=l.match(/^\d+/);u&&(l=u[0])}return jl({host:n,pass:r,path:c,projectId:l,port:o,protocol:t,publicKey:i})}function jl(s){return{protocol:s.protocol,publicKey:s.publicKey||"",pass:s.pass||"",host:s.host,port:s.port||"",path:s.path||"",projectId:s.projectId}}function Rv(s){if(!(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__))return;const{port:e,projectId:t,protocol:i}=s;var r=["protocol","publicKey","host","projectId"];if(r.forEach(n=>{if(!s[n])throw new re(`Invalid Sentry Dsn: ${n} missing`)}),!t.match(/^\d+$/))throw new re(`Invalid Sentry Dsn: Invalid projectId ${t}`);if(!xv(i))throw new re(`Invalid Sentry Dsn: Invalid protocol ${i}`);if(e&&isNaN(parseInt(e,10)))throw new re(`Invalid Sentry Dsn: Invalid port ${e}`);return!0}function Av(s){var e=typeof s=="string"?kv(s):jl(s);return Rv(e),e}var Cv=M(),Nv="Sentry Logger ",qr=["debug","info","warn","error","log","assert","trace"];function Gl(s){var e=M();if(!("console"in e))return s();var t=e.console,i={};qr.forEach(r=>{var n=t[r]&&t[r].__sentry_original__;r in e.console&&n&&(i[r]=t[r],t[r]=n)});try{return s()}finally{Object.keys(i).forEach(r=>{t[r]=i[r]})}}function Na(){let s=!1;var e={enable:()=>{s=!0},disable:()=>{s=!1}};return typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__?qr.forEach(t=>{e[t]=(...i)=>{s&&Gl(()=>{Cv.console[t](`${Nv}[${t}]:`,...i)})}}):qr.forEach(t=>{e[t]=()=>{}}),e}let y;typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__?y=Vn("logger",Na):y=Na();function Mi(s,e=0){return typeof s!="string"||e===0||s.length<=e?s:`${s.substr(0,e)}...`}function Ma(s,e){if(!Array.isArray(s))return"";var t=[];for(let r=0;r<s.length;r++){var i=s[r];try{t.push(String(i))}catch{t.push("[value cannot be serialized]")}}return t.join(e)}function $i(s,e){return _t(s)?bv(e)?e.test(s):typeof e=="string"?s.indexOf(e)!==-1:!1:!1}function se(s,e,t){if(e in s){var i=s[e],r=t(i);if(typeof r=="function")try{ql(r,i)}catch{}s[e]=r}}function Gn(s,e,t){Object.defineProperty(s,e,{value:t,writable:!0,configurable:!0})}function ql(s,e){var t=e.prototype||{};s.prototype=e.prototype=t,Gn(s,"__sentry_original__",e)}function qn(s){return s.__sentry_original__}function Mv(s){return Object.keys(s).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(s[e])}`).join("&")}function zl(s){if(Fl(s))return{message:s.message,name:s.name,stack:s.stack,...Pa(s)};if(Kn(s)){var e={type:s.type,target:Da(s.target),currentTarget:Da(s.currentTarget),...Pa(s)};return typeof CustomEvent<"u"&&Ye(s,CustomEvent)&&(e.detail=s.detail),e}else return s}function Da(s){try{return wv(s)?Ki(s):Object.prototype.toString.call(s)}catch{return"<unknown>"}}function Pa(s){if(typeof s=="object"&&s!==null){var e={};for(var t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=s[t]);return e}else return{}}function Dv(s,e=40){var t=Object.keys(zl(s));if(t.sort(),!t.length)return"[object has no keys]";if(t[0].length>=e)return Mi(t[0],e);for(let r=t.length;r>0;r--){var i=t.slice(0,r).join(", ");if(!(i.length>e))return r===t.length?i:Mi(i,e)}return""}function lt(s){var e=new Map;return on(s,e)}function on(s,e){if(oi(s)){var t=e.get(s);if(t!==void 0)return t;var i={};e.set(s,i);for(var r of Object.keys(s))typeof s[r]<"u"&&(i[r]=on(s[r],e));return i}if(Array.isArray(s)){var t=e.get(s);if(t!==void 0)return t;var i=[];return e.set(s,i),s.forEach(a=>{i.push(on(a,e))}),i}return s}function st(s,e){return s??e()}var Pv=50;function Hl(...s){var e=s.sort((t,i)=>t[0]-i[0]).map(t=>t[1]);return(t,i=0)=>{var r=[];for(var n of t.split(`
`).slice(i))for(var o of e){var a=o(n);if(a){r.push(a);break}}return Uv(r)}}function Ov(s){return Array.isArray(s)?Hl(...s):s}function Uv(s){if(!s.length)return[];let e=s;var t=e[0].function||"",i=e[e.length-1].function||"";return(t.indexOf("captureMessage")!==-1||t.indexOf("captureException")!==-1)&&(e=e.slice(1)),i.indexOf("sentryWrapped")!==-1&&(e=e.slice(0,-1)),e.slice(0,Pv).map(r=>({...r,filename:r.filename||e[0].filename,function:r.function||"?"})).reverse()}var Ps="<anonymous>";function ft(s){try{return!s||typeof s!="function"?Ps:s.name||Ps}catch{return Ps}}function zn(){if(!("fetch"in M()))return!1;try{return new Headers,new Request(""),new Response,!0}catch{return!1}}function an(s){return s&&/^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(s.toString())}function Bv(){if(!zn())return!1;var s=M();if(an(s.fetch))return!0;let e=!1;var t=s.document;if(t&&typeof t.createElement=="function")try{var i=t.createElement("iframe");i.hidden=!0,t.head.appendChild(i),i.contentWindow&&i.contentWindow.fetch&&(e=an(i.contentWindow.fetch)),t.head.removeChild(i)}catch(r){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",r)}return e}function Lv(){var s=M(),e=s.chrome,t=e&&e.app&&e.app.runtime,i="history"in s&&!!s.history.pushState&&!!s.history.replaceState;return!t&&i}var U=M(),Di={},Oa={};function Fv(s){if(!Oa[s])switch(Oa[s]=!0,s){case"console":Vv();break;case"dom":Yv();break;case"xhr":Gv();break;case"fetch":Kv();break;case"history":qv();break;case"error":Jv();break;case"unhandledrejection":Xv();break;default:(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("unknown instrumentation type:",s);return}}function he(s,e){Di[s]=Di[s]||[],Di[s].push(e),Fv(s)}function Ee(s,e){if(!(!s||!Di[s]))for(var t of Di[s]||[])try{t(e)}catch(i){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error(`Error while triggering instrumentation handler.
Type: ${s}
Name: ${ft(t)}
Error:`,i)}}function Vv(){"console"in U&&qr.forEach(function(s){s in U.console&&se(U.console,s,function(e){return function(...t){Ee("console",{args:t,level:s}),e&&e.apply(U.console,t)}})})}function Kv(){!Bv()||se(U,"fetch",function(s){return function(...e){var t={args:e,fetchData:{method:$v(e),url:jv(e)},startTimestamp:Date.now()};return Ee("fetch",{...t}),s.apply(U,e).then(i=>(Ee("fetch",{...t,endTimestamp:Date.now(),response:i}),i),i=>{throw Ee("fetch",{...t,endTimestamp:Date.now(),error:i}),i})}})}function $v(s=[]){return"Request"in U&&Ye(s[0],Request)&&s[0].method?String(s[0].method).toUpperCase():s[1]&&s[1].method?String(s[1].method).toUpperCase():"GET"}function jv(s=[]){return typeof s[0]=="string"?s[0]:"Request"in U&&Ye(s[0],Request)?s[0].url:String(s[0])}function Gv(){if("XMLHttpRequest"in U){var s=XMLHttpRequest.prototype;se(s,"open",function(e){return function(...t){var i=this,r=t[1],n=i.__sentry_xhr__={method:_t(t[0])?t[0].toUpperCase():t[0],url:t[1]};_t(r)&&n.method==="POST"&&r.match(/sentry_key/)&&(i.__sentry_own_request__=!0);var o=function(){if(i.readyState===4){try{n.status_code=i.status}catch{}Ee("xhr",{args:t,endTimestamp:Date.now(),startTimestamp:Date.now(),xhr:i})}};return"onreadystatechange"in i&&typeof i.onreadystatechange=="function"?se(i,"onreadystatechange",function(a){return function(...c){return o(),a.apply(i,c)}}):i.addEventListener("readystatechange",o),e.apply(i,t)}}),se(s,"send",function(e){return function(...t){return this.__sentry_xhr__&&t[0]!==void 0&&(this.__sentry_xhr__.body=t[0]),Ee("xhr",{args:t,startTimestamp:Date.now(),xhr:this}),e.apply(this,t)}})}}let Sr;function qv(){if(!Lv())return;var s=U.onpopstate;U.onpopstate=function(...t){var i=U.location.href,r=Sr;if(Sr=i,Ee("history",{from:r,to:i}),s)try{return s.apply(this,t)}catch{}};function e(t){return function(...i){var r=i.length>2?i[2]:void 0;if(r){var n=Sr,o=String(r);Sr=o,Ee("history",{from:n,to:o})}return t.apply(this,i)}}se(U.history,"pushState",e),se(U.history,"replaceState",e)}var zv=1e3;let Er,Ir;function Hv(s,e){if(!s||s.type!==e.type)return!0;try{if(s.target!==e.target)return!0}catch{}return!1}function Wv(s){if(s.type!=="keypress")return!1;try{var e=s.target;if(!e||!e.tagName)return!0;if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable)return!1}catch{}return!0}function Ua(s,e=!1){return t=>{if(!(!t||Ir===t)&&!Wv(t)){var i=t.type==="keypress"?"input":t.type;Er===void 0?(s({event:t,name:i,global:e}),Ir=t):Hv(Ir,t)&&(s({event:t,name:i,global:e}),Ir=t),clearTimeout(Er),Er=U.setTimeout(()=>{Er=void 0},zv)}}}function Yv(){if("document"in U){var s=Ee.bind(null,"dom"),e=Ua(s,!0);U.document.addEventListener("click",e,!1),U.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(t=>{var i=U[t]&&U[t].prototype;!i||!i.hasOwnProperty||!i.hasOwnProperty("addEventListener")||(se(i,"addEventListener",function(r){return function(n,o,a){if(n==="click"||n=="keypress")try{var c=this,l=c.__sentry_instrumentation_handlers__=c.__sentry_instrumentation_handlers__||{},d=l[n]=l[n]||{refCount:0};if(!d.handler){var u=Ua(s);d.handler=u,r.call(this,n,u,a)}d.refCount+=1}catch{}return r.call(this,n,o,a)}}),se(i,"removeEventListener",function(r){return function(n,o,a){if(n==="click"||n=="keypress")try{var c=this,l=c.__sentry_instrumentation_handlers__||{},d=l[n];d&&(d.refCount-=1,d.refCount<=0&&(r.call(this,n,d.handler,a),d.handler=void 0,delete l[n]),Object.keys(l).length===0&&delete c.__sentry_instrumentation_handlers__)}catch{}return r.call(this,n,o,a)}}))})}}let Os=null;function Jv(){Os=U.onerror,U.onerror=function(s,e,t,i,r){return Ee("error",{column:i,error:r,line:t,msg:s,url:e}),Os?Os.apply(this,arguments):!1}}let Us=null;function Xv(){Us=U.onunhandledrejection,U.onunhandledrejection=function(s){return Ee("unhandledrejection",s),Us?Us.apply(this,arguments):!0}}function Qv(){var s=typeof WeakSet=="function",e=s?new WeakSet:[];function t(r){if(s)return e.has(r)?!0:(e.add(r),!1);for(let o=0;o<e.length;o++){var n=e[o];if(n===r)return!0}return e.push(r),!1}function i(r){if(s)e.delete(r);else for(let n=0;n<e.length;n++)if(e[n]===r){e.splice(n,1);break}}return[t,i]}function dt(){var s=M(),e=s.crypto||s.msCrypto;if(e!==void 0&&e.getRandomValues){var t=new Uint16Array(8);e.getRandomValues(t),t[3]=t[3]&4095|16384,t[4]=t[4]&16383|32768;var i=r=>{let n=r.toString(16);for(;n.length<4;)n=`0${n}`;return n};return i(t[0])+i(t[1])+i(t[2])+i(t[3])+i(t[4])+i(t[5])+i(t[6])+i(t[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,r=>{var n=Math.random()*16|0,o=r==="x"?n:n&3|8;return o.toString(16)})}function Bs(s){if(!s)return{};var e=s.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var t=e[6]||"",i=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],relative:e[5]+t+i}}function Wl(s){return s.exception&&s.exception.values?s.exception.values[0]:void 0}function Ct(s){const{message:e,event_id:t}=s;if(e)return e;var i=Wl(s);return i?i.type&&i.value?`${i.type}: ${i.value}`:i.type||i.value||t||"<unknown>":t||"<unknown>"}function cn(s,e,t){var i=s.exception=s.exception||{},r=i.values=i.values||[],n=r[0]=r[0]||{};n.value||(n.value=e||""),n.type||(n.type=t||"Error")}function ji(s,e){var t=Wl(s);if(!!t){var i={type:"generic",handled:!0},r=t.mechanism;if(t.mechanism={...i,...r,...e},e&&"data"in e){var n={...r&&r.data,...e.data};t.mechanism.data=n}}}function Ba(s){if(s&&s.__sentry_captured__)return!0;try{Gn(s,"__sentry_captured__",!0)}catch{}return!1}function xt(s,e=1/0,t=1/0){try{return ln("",s,e,t)}catch(i){return{ERROR:`**non-serializable** (${i})`}}}function Yl(s,e=3,t=100*1024){var i=xt(s,e);return tw(i)>t?Yl(s,e-1,t):i}function ln(s,e,t=1/0,i=1/0,r=Qv()){const[n,o]=r;if(e===null||["number","boolean","string"].includes(typeof e)&&!$l(e))return e;var a=Zv(s,e);if(!a.startsWith("[object "))return a;if(e.__sentry_skip_normalization__)return e;if(t===0)return a.replace("object ","");if(n(e))return"[Circular ~]";var c=e;if(c&&typeof c.toJSON=="function")try{var l=c.toJSON();return ln("",l,t-1,i,r)}catch{}var d=Array.isArray(e)?[]:{};let u=0;var h=zl(e);for(var m in h)if(!!Object.prototype.hasOwnProperty.call(h,m)){if(u>=i){d[m]="[MaxProperties ~]";break}var _=h[m];d[m]=ln(m,_,t-1,i,r),u+=1}return o(e),d}function Zv(s,e){try{return s==="domain"&&e&&typeof e=="object"&&e._events?"[Domain]":s==="domainEmitter"?"[DomainEmitter]":typeof global<"u"&&e===global?"[Global]":typeof window<"u"&&e===window?"[Window]":typeof document<"u"&&e===document?"[Document]":Sv(e)?"[SyntheticEvent]":typeof e=="number"&&e!==e?"[NaN]":e===void 0?"[undefined]":typeof e=="function"?`[Function: ${ft(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${Object.getPrototypeOf(e).constructor.name}]`}catch(t){return`**non-serializable** (${t})`}}function ew(s){return~-encodeURI(s).split(/%..|./).length}function tw(s){return ew(JSON.stringify(s))}var Le;(function(s){var e=0;s[s.PENDING=e]="PENDING";var t=1;s[s.RESOLVED=t]="RESOLVED";var i=2;s[s.REJECTED=i]="REJECTED"})(Le||(Le={}));function Lt(s){return new oe(e=>{e(s)})}function dn(s){return new oe((e,t)=>{t(s)})}class oe{__init(){this._state=Le.PENDING}__init2(){this._handlers=[]}constructor(e){oe.prototype.__init.call(this),oe.prototype.__init2.call(this),oe.prototype.__init3.call(this),oe.prototype.__init4.call(this),oe.prototype.__init5.call(this),oe.prototype.__init6.call(this);try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}then(e,t){return new oe((i,r)=>{this._handlers.push([!1,n=>{if(!e)i(n);else try{i(e(n))}catch(o){r(o)}},n=>{if(!t)r(n);else try{i(t(n))}catch(o){r(o)}}]),this._executeHandlers()})}catch(e){return this.then(t=>t,e)}finally(e){return new oe((t,i)=>{let r,n;return this.then(o=>{n=!1,r=o,e&&e()},o=>{n=!0,r=o,e&&e()}).then(()=>{if(n){i(r);return}t(r)})})}__init3(){this._resolve=e=>{this._setResult(Le.RESOLVED,e)}}__init4(){this._reject=e=>{this._setResult(Le.REJECTED,e)}}__init5(){this._setResult=(e,t)=>{if(this._state===Le.PENDING){if($n(t)){t.then(this._resolve,this._reject);return}this._state=e,this._value=t,this._executeHandlers()}}}__init6(){this._executeHandlers=()=>{if(this._state!==Le.PENDING){var e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===Le.RESOLVED&&t[1](this._value),this._state===Le.REJECTED&&t[2](this._value),t[0]=!0)})}}}}function iw(s){var e=[];function t(){return s===void 0||e.length<s}function i(o){return e.splice(e.indexOf(o),1)[0]}function r(o){if(!t())return dn(new re("Not adding Promise due to buffer limit reached."));var a=o();return e.indexOf(a)===-1&&e.push(a),a.then(()=>i(a)).then(null,()=>i(a).then(null,()=>{})),a}function n(o){return new oe((a,c)=>{let l=e.length;if(!l)return a(!0);var d=setTimeout(()=>{o&&o>0&&a(!1)},o);e.forEach(u=>{Lt(u).then(()=>{--l||(clearTimeout(d),a(!0))},c)})})}return{$:e,add:r,drain:n}}var rw=["fatal","error","warning","log","info","debug"];function sw(s){return s==="warn"?"warning":rw.includes(s)?s:"log"}var un={nowSeconds:()=>Date.now()/1e3};function nw(){const{performance:s}=M();if(!(!s||!s.now)){var e=Date.now()-s.now();return{now:()=>s.now(),timeOrigin:e}}}function ow(){try{var s=ot(Ke,"perf_hooks");return s.performance}catch{return}}var Ls=es()?ow():nw(),La=Ls===void 0?un:{nowSeconds:()=>(Ls.timeOrigin+Ls.now())/1e3},ts=un.nowSeconds.bind(un),Hn=La.nowSeconds.bind(La),Gi=Hn,qi=(()=>{const{performance:s}=M();if(!(!s||!s.now)){var e=3600*1e3,t=s.now(),i=Date.now(),r=s.timeOrigin?Math.abs(s.timeOrigin+t-i):e,n=r<e,o=s.timing&&s.timing.navigationStart,a=typeof o=="number",c=a?Math.abs(o+t-i):e,l=c<e;return n||l?r<=c?s.timeOrigin:o:i}})(),aw=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function cw(s){var e=s.match(aw);if(e){let t;return e[3]==="1"?t=!0:e[3]==="0"&&(t=!1),{traceId:e[1],parentSampled:t,parentSpanId:e[2]}}}function is(s,e=[]){return[s,e]}function lw(s,e){const[t,i]=s;return[t,[...i,e]]}function Fa(s,e){var t=s[1];t.forEach(i=>{var r=i[0].type;e(i,r)})}function hn(s,e){var t=e||new TextEncoder;return t.encode(s)}function Jl(s,e){const[t,i]=s;let r=JSON.stringify(t);function n(a){typeof r=="string"?r=typeof a=="string"?r+a:[hn(r,e),a]:r.push(typeof a=="string"?hn(a,e):a)}for(var o of i){const[a,c]=o;n(`
${JSON.stringify(a)}
`),n(typeof c=="string"||c instanceof Uint8Array?c:JSON.stringify(c))}return typeof r=="string"?r:dw(r)}function dw(s){var e=s.reduce((n,o)=>n+o.length,0),t=new Uint8Array(e);let i=0;for(var r of s)t.set(r,i),i+=r.length;return t}function uw(s,e){var t=typeof s.data=="string"?hn(s.data,e):s.data;return[lt({type:"attachment",length:t.length,filename:s.filename,content_type:s.contentType,attachment_type:s.attachmentType}),t]}var hw={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default"};function Va(s){return hw[s]}function pw(s,e,t){var i=[{type:"client_report"},{timestamp:t||ts(),discarded_events:s}];return is(e?{dsn:e}:{},[i])}var mw=60*1e3;function _w(s,e=Date.now()){var t=parseInt(`${s}`,10);if(!isNaN(t))return t*1e3;var i=Date.parse(`${s}`);return isNaN(i)?mw:i-e}function fw(s,e){return s[e]||s.all||0}function gw(s,e,t=Date.now()){return fw(s,e)>t}function yw(s,{statusCode:e,headers:t},i=Date.now()){var r={...s},n=t&&t["x-sentry-rate-limits"],o=t&&t["retry-after"];if(n)for(var a of n.trim().split(",")){const[u,h]=a.split(":",2);var c=parseInt(u,10),l=(isNaN(c)?60:c)*1e3;if(!h)r.all=i+l;else for(var d of h.split(";"))r[d]=i+l}else o?r.all=i+_w(o,i):e===429&&(r.all=i+60*1e3);return r}var Wt="baggage",vw="sentry-",Ka=/^sentry-/,ww=8192;function zr(s,e="",t=!0){return[{...s},e,t]}function bw(s){return Object.keys(s[0]).length===0}function Xl(s){return s[0]}function Sw(s){return s[1]}function Ew(s){return s[2]}function Iw(s){s[2]=!1}function Tw(s){return Object.keys(s[0]).reduce((e,t)=>{var i=s[0][t],r=`${vw}${encodeURIComponent(t)}=${encodeURIComponent(i)}`,n=e===""?r:`${e},${r}`;return n.length>ww?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Not adding key: ${t} with val: ${i} to baggage due to exceeding baggage size limits.`),e):n},s[1])}function Ql(s,e=!1){if(!Array.isArray(s)&&!_t(s)||typeof s=="number")return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("[parseBaggageHeader] Received input value of incompatible type: ",typeof s,s),zr({},"");var t=(_t(s)?s:s.join(",")).split(",").map(i=>i.trim()).filter(i=>i!==""&&(e||Ka.test(i)));return t.reduce(([i,r],n)=>{const[o,a]=n.split("=");if(Ka.test(o)){var c=decodeURIComponent(o.split("-")[1]);return[{...i,[c]:decodeURIComponent(a)},r,!0]}else return[i,r===""?n:`${r},${n}`,!0]},[{},"",!0])}function ki(s,e){if(!s&&!e)return"";var t=e&&Ql(e,!0)||void 0,i=t&&Sw(t),r=zr(s&&s[0]||{},i||"");return Tw(r)}function xw(s,e){var t=Ql(s||"");return(e||!bw(t))&&Iw(t),t}function kw(s){var e=Hn(),t={sid:dt(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>Aw(t)};return s&&ai(t,s),t}function ai(s,e={}){if(e.user&&(!s.ipAddress&&e.user.ip_address&&(s.ipAddress=e.user.ip_address),!s.did&&!e.did&&(s.did=e.user.id||e.user.email||e.user.username)),s.timestamp=e.timestamp||Hn(),e.ignoreDuration&&(s.ignoreDuration=e.ignoreDuration),e.sid&&(s.sid=e.sid.length===32?e.sid:dt()),e.init!==void 0&&(s.init=e.init),!s.did&&e.did&&(s.did=`${e.did}`),typeof e.started=="number"&&(s.started=e.started),s.ignoreDuration)s.duration=void 0;else if(typeof e.duration=="number")s.duration=e.duration;else{var t=s.timestamp-s.started;s.duration=t>=0?t:0}e.release&&(s.release=e.release),e.environment&&(s.environment=e.environment),!s.ipAddress&&e.ipAddress&&(s.ipAddress=e.ipAddress),!s.userAgent&&e.userAgent&&(s.userAgent=e.userAgent),typeof e.errors=="number"&&(s.errors=e.errors),e.status&&(s.status=e.status)}function Rw(s,e){let t={};e?t={status:e}:s.status==="ok"&&(t={status:"exited"}),ai(s,t)}function Aw(s){return lt({sid:`${s.sid}`,init:s.init,started:new Date(s.started*1e3).toISOString(),timestamp:new Date(s.timestamp*1e3).toISOString(),status:s.status,errors:s.errors,did:typeof s.did=="number"||typeof s.did=="string"?`${s.did}`:void 0,duration:s.duration,attrs:{release:s.release,environment:s.environment,ip_address:s.ipAddress,user_agent:s.userAgent}})}var $a=100;class ut{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}static clone(e){var t=new ut;return e&&(t._breadcrumbs=[...e._breadcrumbs],t._tags={...e._tags},t._extra={...e._extra},t._contexts={...e._contexts},t._user=e._user,t._level=e._level,t._span=e._span,t._session=e._session,t._transactionName=e._transactionName,t._fingerprint=e._fingerprint,t._eventProcessors=[...e._eventProcessors],t._requestSession=e._requestSession,t._attachments=[...e._attachments]),t}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{},this._session&&ai(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(e){return this._requestSession=e,this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this._tags={...this._tags,[e]:t},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts={...this._contexts,[e]:t},this._notifyScopeListeners(),this}setSpan(e){return this._span=e,this._notifyScopeListeners(),this}getSpan(){return this._span}getTransaction(){var e=this.getSpan();return e&&e.transaction}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;if(typeof e=="function"){var t=e(this);return t instanceof ut?t:this}return e instanceof ut?(this._tags={...this._tags,...e._tags},this._extra={...this._extra,...e._extra},this._contexts={...this._contexts,...e._contexts},e._user&&Object.keys(e._user).length&&(this._user=e._user),e._level&&(this._level=e._level),e._fingerprint&&(this._fingerprint=e._fingerprint),e._requestSession&&(this._requestSession=e._requestSession)):oi(e)&&(e=e,this._tags={...this._tags,...e.tags},this._extra={...this._extra,...e.extra},this._contexts={...this._contexts,...e.contexts},e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession)),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this}addBreadcrumb(e,t){var i=typeof t=="number"?Math.min(t,$a):$a;if(i<=0)return this;var r={timestamp:ts(),...e};return this._breadcrumbs=[...this._breadcrumbs,r].slice(-i),this._notifyScopeListeners(),this}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}getAttachments(){return this._attachments}clearAttachments(){return this._attachments=[],this}applyToEvent(e,t={}){if(this._extra&&Object.keys(this._extra).length&&(e.extra={...this._extra,...e.extra}),this._tags&&Object.keys(this._tags).length&&(e.tags={...this._tags,...e.tags}),this._user&&Object.keys(this._user).length&&(e.user={...this._user,...e.user}),this._contexts&&Object.keys(this._contexts).length&&(e.contexts={...this._contexts,...e.contexts}),this._level&&(e.level=this._level),this._transactionName&&(e.transaction=this._transactionName),this._span){e.contexts={trace:this._span.getTraceContext(),...e.contexts};var i=this._span.transaction&&this._span.transaction.name;i&&(e.tags={transaction:i,...e.tags})}return this._applyFingerprint(e),e.breadcrumbs=[...e.breadcrumbs||[],...this._breadcrumbs],e.breadcrumbs=e.breadcrumbs.length>0?e.breadcrumbs:void 0,e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...this._sdkProcessingMetadata},this._notifyEventProcessors([...Zl(),...this._eventProcessors],e,t)}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata={...this._sdkProcessingMetadata,...e},this}_notifyEventProcessors(e,t,i,r=0){return new oe((n,o)=>{var a=e[r];if(t===null||typeof a!="function")n(t);else{var c=a({...t},i);(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&a.id&&c===null&&y.log(`Event processor "${a.id}" dropped event`),$n(c)?c.then(l=>this._notifyEventProcessors(e,l,i,r+1).then(n)).then(null,o):this._notifyEventProcessors(e,c,i,r+1).then(n).then(null,o)}})}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}_applyFingerprint(e){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],this._fingerprint&&(e.fingerprint=e.fingerprint.concat(this._fingerprint)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}}function Zl(){return Vn("globalEventProcessors",()=>[])}function Wn(s){Zl().push(s)}var Yn=4,Cw=100;class er{__init(){this._stack=[{}]}constructor(e,t=new ut,i=Yn){this._version=i,er.prototype.__init.call(this),this.getStackTop().scope=t,e&&this.bindClient(e)}isOlderThan(e){return this._version<e}bindClient(e){var t=this.getStackTop();t.client=e,e&&e.setupIntegrations&&e.setupIntegrations()}pushScope(){var e=ut.clone(this.getScope());return this.getStack().push({client:this.getClient(),scope:e}),e}popScope(){return this.getStack().length<=1?!1:!!this.getStack().pop()}withScope(e){var t=this.pushScope();try{e(t)}finally{this.popScope()}}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getStack(){return this._stack}getStackTop(){return this._stack[this._stack.length-1]}captureException(e,t){var i=this._lastEventId=t&&t.event_id?t.event_id:dt(),r=new Error("Sentry syntheticException");return this._withClient((n,o)=>{n.captureException(e,{originalException:e,syntheticException:r,...t,event_id:i},o)}),i}captureMessage(e,t,i){var r=this._lastEventId=i&&i.event_id?i.event_id:dt(),n=new Error(e);return this._withClient((o,a)=>{o.captureMessage(e,t,{originalException:e,syntheticException:n,...i,event_id:r},a)}),r}captureEvent(e,t){var i=t&&t.event_id?t.event_id:dt();return e.type!=="transaction"&&(this._lastEventId=i),this._withClient((r,n)=>{r.captureEvent(e,{...t,event_id:i},n)}),i}lastEventId(){return this._lastEventId}addBreadcrumb(e,t){const{scope:i,client:r}=this.getStackTop();if(!i||!r)return;const{beforeBreadcrumb:n=null,maxBreadcrumbs:o=Cw}=r.getOptions&&r.getOptions()||{};if(!(o<=0)){var a=ts(),c={timestamp:a,...e},l=n?Gl(()=>n(c,t)):c;l!==null&&i.addBreadcrumb(l,o)}}setUser(e){var t=this.getScope();t&&t.setUser(e)}setTags(e){var t=this.getScope();t&&t.setTags(e)}setExtras(e){var t=this.getScope();t&&t.setExtras(e)}setTag(e,t){var i=this.getScope();i&&i.setTag(e,t)}setExtra(e,t){var i=this.getScope();i&&i.setExtra(e,t)}setContext(e,t){var i=this.getScope();i&&i.setContext(e,t)}configureScope(e){const{scope:t,client:i}=this.getStackTop();t&&i&&e(t)}run(e){var t=ja(this);try{e(this)}finally{ja(t)}}getIntegration(e){var t=this.getClient();if(!t)return null;try{return t.getIntegration(e)}catch{return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Cannot retrieve integration ${e.id} from the current Hub`),null}}startTransaction(e,t){return this._callExtensionMethod("startTransaction",e,t)}traceHeaders(){return this._callExtensionMethod("traceHeaders")}captureSession(e=!1){if(e)return this.endSession();this._sendSessionUpdate()}endSession(){var e=this.getStackTop(),t=e&&e.scope,i=t&&t.getSession();i&&Rw(i),this._sendSessionUpdate(),t&&t.setSession()}startSession(e){const{scope:t,client:i}=this.getStackTop(),{release:r,environment:n}=i&&i.getOptions()||{};var o=M();const{userAgent:a}=o.navigator||{};var c=kw({release:r,environment:n,...t&&{user:t.getUser()},...a&&{userAgent:a},...e});if(t){var l=t.getSession&&t.getSession();l&&l.status==="ok"&&ai(l,{status:"exited"}),this.endSession(),t.setSession(c)}return c}shouldSendDefaultPii(){var e=this.getClient(),t=e&&e.getOptions();return Boolean(t&&t.sendDefaultPii)}_sendSessionUpdate(){const{scope:e,client:t}=this.getStackTop();if(!!e){var i=e.getSession();i&&t&&t.captureSession&&t.captureSession(i)}}_withClient(e){const{scope:t,client:i}=this.getStackTop();i&&e(i,t)}_callExtensionMethod(e,...t){var i=mi(),r=i.__SENTRY__;if(r&&r.extensions&&typeof r.extensions[e]=="function")return r.extensions[e].apply(this,t);(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Extension method ${e} couldn't be found, doing nothing.`)}}function mi(){var s=M();return s.__SENTRY__=s.__SENTRY__||{extensions:{},hub:void 0},s}function ja(s){var e=mi(),t=nt(e);return Jn(e,s),t}function V(){var s=mi();return(!ed(s)||nt(s).isOlderThan(Yn))&&Jn(s,new er),es()?Nw(s):nt(s)}function Nw(s){try{var e=mi().__SENTRY__,t=e&&e.extensions&&e.extensions.domain&&e.extensions.domain.active;if(!t)return nt(s);if(!ed(t)||nt(t).isOlderThan(Yn)){var i=nt(s).getStackTop();Jn(t,new er(i.client,ut.clone(i.scope)))}return nt(t)}catch{return nt(s)}}function ed(s){return!!(s&&s.__SENTRY__&&s.__SENTRY__.hub)}function nt(s){return Vn("hub",()=>new er,s)}function Jn(s,e){if(!s)return!1;var t=s.__SENTRY__=s.__SENTRY__||{};return t.hub=e,!0}function td(s,e){return V().captureException(s,{captureContext:e})}function Si(s,e){V().setTag(s,e)}function Mw(s){V().withScope(s)}var Dw="7";function Pw(s){var e=s.protocol?`${s.protocol}:`:"",t=s.port?`:${s.port}`:"";return`${e}//${s.host}${t}${s.path?`/${s.path}`:""}/api/`}function Ow(s){return`${Pw(s)}${s.projectId}/envelope/`}function Uw(s){return Mv({sentry_key:s.publicKey,sentry_version:Dw})}function id(s,e){return e||`${Ow(s)}?${Uw(s)}`}function rd(s){if(!s||!s.sdk)return;const{name:e,version:t}=s.sdk;return{name:e,version:t}}function Bw(s,e){return e&&(s.sdk=s.sdk||{},s.sdk.name=s.sdk.name||e.name,s.sdk.version=s.sdk.version||e.version,s.sdk.integrations=[...s.sdk.integrations||[],...e.integrations||[]],s.sdk.packages=[...s.sdk.packages||[],...e.packages||[]]),s}function Lw(s,e,t,i){var r=rd(t),n={sent_at:new Date().toISOString(),...r&&{sdk:r},...!!i&&{dsn:jn(e)}},o="aggregates"in s?[{type:"sessions"},s]:[{type:"session"},s];return is(n,[o])}function Fw(s,e,t,i){var r=rd(t),n=s.type||"event";const{transactionSampling:o}=s.sdkProcessingMetadata||{},{method:a,rate:c}=o||{};Bw(s,t&&t.sdk);var l=Vw(s,r,i,e);delete s.sdkProcessingMetadata;var d=[{type:n,sample_rates:[{id:a,rate:c}]},s];return is(l,[d])}function Vw(s,e,t,i){var r=s.sdkProcessingMetadata&&s.sdkProcessingMetadata.baggage,n=r&&Xl(r);return{event_id:s.event_id,sent_at:new Date().toISOString(),...e&&{sdk:e},...!!t&&{dsn:jn(i)},...s.type==="transaction"&&n&&{trace:lt({...n})}}}var Ga=[];function qa(s){return s.reduce((e,t)=>(e.every(i=>t.name!==i.name)&&e.push(t),e),[])}function Kw(s){var e=s.defaultIntegrations&&[...s.defaultIntegrations]||[],t=s.integrations;let i=[...qa(e)];Array.isArray(t)?i=[...i.filter(o=>t.every(a=>a.name!==o.name)),...qa(t)]:typeof t=="function"&&(i=t(i),i=Array.isArray(i)?i:[i]);var r=i.map(o=>o.name),n="Debug";return r.indexOf(n)!==-1&&i.push(...i.splice(r.indexOf(n),1)),i}function $w(s){var e={};return s.forEach(t=>{e[t.name]=t,Ga.indexOf(t.name)===-1&&(t.setupOnce(Wn,V),Ga.push(t.name),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`Integration installed: ${t.name}`))}),e}var za="Not capturing exception because it's already been captured.";class Yt{__init(){this._integrations={}}__init2(){this._integrationsInitialized=!1}__init3(){this._numProcessing=0}__init4(){this._outcomes={}}constructor(e){if(Yt.prototype.__init.call(this),Yt.prototype.__init2.call(this),Yt.prototype.__init3.call(this),Yt.prototype.__init4.call(this),this._options=e,e.dsn){this._dsn=Av(e.dsn);var t=id(this._dsn,e.tunnel);this._transport=e.transport({recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:t})}else(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("No DSN provided, client will not do anything.")}captureException(e,t,i){if(Ba(e)){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(za);return}let r=t&&t.event_id;return this._process(this.eventFromException(e,t).then(n=>this._captureEvent(n,t,i)).then(n=>{r=n})),r}captureMessage(e,t,i,r){let n=i&&i.event_id;var o=Kl(e)?this.eventFromMessage(String(e),t,i):this.eventFromException(e,i);return this._process(o.then(a=>this._captureEvent(a,i,r)).then(a=>{n=a})),n}captureEvent(e,t,i){if(t&&t.originalException&&Ba(t.originalException)){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(za);return}let r=t&&t.event_id;return this._process(this._captureEvent(e,t,i).then(n=>{r=n})),r}captureSession(e){if(!this._isEnabled()){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("SDK not enabled, will not capture session.");return}typeof e.release!="string"?(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Discarded session because of missing or non-string release"):(this.sendSession(e),ai(e,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getTransport(){return this._transport}flush(e){var t=this._transport;return t?this._isClientDoneProcessing(e).then(i=>t.flush(e).then(r=>i&&r)):Lt(!0)}close(e){return this.flush(e).then(t=>(this.getOptions().enabled=!1,t))}setupIntegrations(){this._isEnabled()&&!this._integrationsInitialized&&(this._integrations=$w(this._options.integrations),this._integrationsInitialized=!0)}getIntegrationById(e){return this._integrations[e]}getIntegration(e){try{return this._integrations[e.id]||null}catch{return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Cannot retrieve integration ${e.id} from the current Client`),null}}sendEvent(e,t={}){if(this._dsn){let r=Fw(e,this._dsn,this._options._metadata,this._options.tunnel);for(var i of t.attachments||[])r=lw(r,uw(i,this._options.transportOptions&&this._options.transportOptions.textEncoder));this._sendEnvelope(r)}}sendSession(e){if(this._dsn){var t=Lw(e,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(t)}}recordDroppedEvent(e,t){if(this._options.sendClientReports){var i=`${e}:${t}`;(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`Adding outcome: "${i}"`),this._outcomes[i]=this._outcomes[i]+1||1}}_updateSessionFromEvent(e,t){let i=!1,r=!1;var n=t.exception&&t.exception.values;if(n){r=!0;for(var o of n){var a=o.mechanism;if(a&&a.handled===!1){i=!0;break}}}var c=e.status==="ok",l=c&&e.errors===0||c&&i;l&&(ai(e,{...i&&{status:"crashed"},errors:e.errors||Number(r||i)}),this.captureSession(e))}_isClientDoneProcessing(e){return new oe(t=>{let i=0;var r=1,n=setInterval(()=>{this._numProcessing==0?(clearInterval(n),t(!0)):(i+=r,e&&i>=e&&(clearInterval(n),t(!1)))},r)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._dsn!==void 0}_prepareEvent(e,t,i){const{normalizeDepth:r=3,normalizeMaxBreadth:n=1e3}=this.getOptions();var o={...e,event_id:e.event_id||t.event_id||dt(),timestamp:e.timestamp||ts()};this._applyClientOptions(o),this._applyIntegrationsMetadata(o);let a=i;t.captureContext&&(a=ut.clone(a).update(t.captureContext));let c=Lt(o);if(a){var l=[...t.attachments||[],...a.getAttachments()];l.length&&(t.attachments=l),c=a.applyToEvent(o,t)}return c.then(d=>typeof r=="number"&&r>0?this._normalizeEvent(d,r,n):d)}_normalizeEvent(e,t,i){if(!e)return null;var r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(n=>({...n,...n.data&&{data:xt(n.data,t,i)}}))},...e.user&&{user:xt(e.user,t,i)},...e.contexts&&{contexts:xt(e.contexts,t,i)},...e.extra&&{extra:xt(e.extra,t,i)}};return e.contexts&&e.contexts.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=xt(e.contexts.trace.data,t,i))),e.spans&&(r.spans=e.spans.map(n=>(n.data&&(n.data=xt(n.data,t,i)),n))),r}_applyClientOptions(e){var t=this.getOptions();const{environment:i,release:r,dist:n,maxValueLength:o=250}=t;"environment"in e||(e.environment="environment"in t?i:"production"),e.release===void 0&&r!==void 0&&(e.release=r),e.dist===void 0&&n!==void 0&&(e.dist=n),e.message&&(e.message=Mi(e.message,o));var a=e.exception&&e.exception.values&&e.exception.values[0];a&&a.value&&(a.value=Mi(a.value,o));var c=e.request;c&&c.url&&(c.url=Mi(c.url,o))}_applyIntegrationsMetadata(e){var t=Object.keys(this._integrations);t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}_captureEvent(e,t={},i){return this._processEvent(e,t,i).then(r=>r.event_id,r=>{(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(r)})}_processEvent(e,t,i){const{beforeSend:r,sampleRate:n}=this.getOptions();if(!this._isEnabled())return dn(new re("SDK not enabled, will not capture event."));var o=e.type==="transaction";return!o&&typeof n=="number"&&Math.random()>n?(this.recordDroppedEvent("sample_rate","error"),dn(new re(`Discarding event because it's not included in the random sample (sampling rate = ${n})`))):this._prepareEvent(e,t,i).then(a=>{if(a===null)throw this.recordDroppedEvent("event_processor",e.type||"error"),new re("An event processor returned null, will not send event.");var c=t.data&&t.data.__sentry__===!0;if(c||o||!r)return a;var l=r(a,t);return jw(l)}).then(a=>{if(a===null)throw this.recordDroppedEvent("before_send",e.type||"error"),new re("`beforeSend` returned `null`, will not send event.");var c=i&&i.getSession();return!o&&c&&this._updateSessionFromEvent(c,a),this.sendEvent(a,t),a}).then(null,a=>{throw a instanceof re?a:(this.captureException(a,{data:{__sentry__:!0},originalException:a}),new re(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
Reason: ${a}`))})}_process(e){this._numProcessing+=1,e.then(t=>(this._numProcessing-=1,t),t=>(this._numProcessing-=1,t))}_sendEnvelope(e){this._transport&&this._dsn?this._transport.send(e).then(null,t=>{(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error("Error while sending event:",t)}):(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error("Transport disabled")}_clearOutcomes(){var e=this._outcomes;return this._outcomes={},Object.keys(e).map(t=>{const[i,r]=t.split(":");return{reason:i,category:r,quantity:e[t]}})}}function jw(s){var e="`beforeSend` method has to return `null` or a valid event.";if($n(s))return s.then(t=>{if(!(oi(t)||t===null))throw new re(e);return t},t=>{throw new re(`beforeSend rejected with ${t}`)});if(!(oi(s)||s===null))throw new re(e);return s}function Gw(s,e){e.debug===!0&&(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__?y.enable():console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."));var t=V(),i=t.getScope();i&&i.update(e.initialScope);var r=new s(e);t.bindClient(r)}var qw=30;function sd(s,e,t=iw(s.bufferSize||qw)){let i={};var r=o=>t.drain(o);function n(o){var a=[];if(Fa(o,(u,h)=>{var m=Va(h);gw(i,m)?s.recordDroppedEvent("ratelimit_backoff",m):a.push(u)}),a.length===0)return Lt();var c=is(o[0],a),l=u=>{Fa(c,(h,m)=>{s.recordDroppedEvent(u,Va(m))})},d=()=>e({body:Jl(c,s.textEncoder)}).then(u=>{u.statusCode!==void 0&&(u.statusCode<200||u.statusCode>=300)&&(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Sentry responded with status code ${u.statusCode} to sent event.`),i=yw(i,u)},u=>{(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error("Failed while sending event:",u),l("network_error")});return t.add(d).then(u=>u,u=>{if(u instanceof re)return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error("Skipped sending event due to full buffer"),l("queue_overflow"),Lt();throw u})}return{send:n,flush:r}}var Ha="7.5.0";let Wa;class zi{constructor(){zi.prototype.__init.call(this)}static __initStatic(){this.id="FunctionToString"}__init(){this.name=zi.id}setupOnce(){Wa=Function.prototype.toString,Function.prototype.toString=function(...e){var t=qn(this)||this;return Wa.apply(t,e)}}}zi.__initStatic();var zw=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/];class Qt{static __initStatic(){this.id="InboundFilters"}__init(){this.name=Qt.id}constructor(e={}){this._options=e,Qt.prototype.__init.call(this)}setupOnce(e,t){var i=r=>{var n=t();if(n){var o=n.getIntegration(Qt);if(o){var a=n.getClient(),c=a?a.getOptions():{},l=Hw(o._options,c);return Ww(r,l)?null:r}}return r};i.id=this.name,e(i)}}Qt.__initStatic();function Hw(s={},e={}){return{allowUrls:[...s.allowUrls||[],...e.allowUrls||[]],denyUrls:[...s.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...s.ignoreErrors||[],...e.ignoreErrors||[],...zw],ignoreInternal:s.ignoreInternal!==void 0?s.ignoreInternal:!0}}function Ww(s,e){return e.ignoreInternal&&Zw(s)?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Event dropped due to being internal Sentry Error.
Event: ${Ct(s)}`),!0):Yw(s,e.ignoreErrors)?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
Event: ${Ct(s)}`),!0):Jw(s,e.denyUrls)?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Event dropped due to being matched by \`denyUrls\` option.
Event: ${Ct(s)}.
Url: ${Hr(s)}`),!0):Xw(s,e.allowUrls)?!1:((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`Event dropped due to not being matched by \`allowUrls\` option.
Event: ${Ct(s)}.
Url: ${Hr(s)}`),!0)}function Yw(s,e){return!e||!e.length?!1:Qw(s).some(t=>e.some(i=>$i(t,i)))}function Jw(s,e){if(!e||!e.length)return!1;var t=Hr(s);return t?e.some(i=>$i(t,i)):!1}function Xw(s,e){if(!e||!e.length)return!0;var t=Hr(s);return t?e.some(i=>$i(t,i)):!0}function Qw(s){if(s.message)return[s.message];if(s.exception)try{const{type:e="",value:t=""}=s.exception.values&&s.exception.values[0]||{};return[`${t}`,`${e}: ${t}`]}catch{return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error(`Cannot extract message for event ${Ct(s)}`),[]}return[]}function Zw(s){try{return s.exception.values[0].type==="SentryError"}catch{}return!1}function eb(s=[]){for(let t=s.length-1;t>=0;t--){var e=s[t];if(e&&e.filename!=="<anonymous>"&&e.filename!=="[native code]")return e.filename||null}return null}function Hr(s){try{let e;try{e=s.exception.values[0].stacktrace.frames}catch{}return e?eb(e):null}catch{return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error(`Cannot extract url for event ${Ct(s)}`),null}}function nd(s,e){var t=Xn(s,e),i={type:e&&e.name,value:sb(e)};return t.length&&(i.stacktrace={frames:t}),i.type===void 0&&i.value===""&&(i.value="Unrecoverable error caught"),i}function tb(s,e,t,i){var r={exception:{values:[{type:Kn(e)?e.constructor.name:i?"UnhandledRejection":"Error",value:`Non-Error ${i?"promise rejection":"exception"} captured with keys: ${Dv(e)}`}]},extra:{__serialized__:Yl(e)}};if(t){var n=Xn(s,t);n.length&&(r.exception.values[0].stacktrace={frames:n})}return r}function Fs(s,e){return{exception:{values:[nd(s,e)]}}}function Xn(s,e){var t=e.stacktrace||e.stack||"",i=rb(e);try{return s(t,i)}catch{}return[]}var ib=/Minified React error #\d+;/i;function rb(s){if(s){if(typeof s.framesToPop=="number")return s.framesToPop;if(ib.test(s.message))return 1}return 0}function sb(s){var e=s&&s.message;return e?e.error&&typeof e.error.message=="string"?e.error.message:e:"No error message"}function nb(s,e,t,i){var r=t&&t.syntheticException||void 0,n=Qn(s,e,r,i);return ji(n),n.level="error",t&&t.event_id&&(n.event_id=t.event_id),Lt(n)}function ob(s,e,t="info",i,r){var n=i&&i.syntheticException||void 0,o=pn(s,e,n,r);return o.level=t,i&&i.event_id&&(o.event_id=i.event_id),Lt(o)}function Qn(s,e,t,i,r){let n;if(Vl(e)&&e.error){var o=e;return Fs(s,o.error)}if(Ca(e)||vv(e)){var a=e;if("stack"in e)n=Fs(s,e);else{var c=a.name||(Ca(a)?"DOMError":"DOMException"),l=a.message?`${c}: ${a.message}`:c;n=pn(s,l,t,i),cn(n,l)}return"code"in a&&(n.tags={...n.tags,"DOMException.code":`${a.code}`}),n}if(Fl(e))return Fs(s,e);if(oi(e)||Kn(e)){var d=e;return n=tb(s,d,t,r),ji(n,{synthetic:!0}),n}return n=pn(s,e,t,i),cn(n,`${e}`,void 0),ji(n,{synthetic:!0}),n}function pn(s,e,t,i){var r={message:e};if(i&&t){var n=Xn(s,t);n.length&&(r.exception={values:[{value:e,stacktrace:{frames:n}}]})}return r}var od="Breadcrumbs";class Hi{static __initStatic(){this.id=od}__init(){this.name=Hi.id}constructor(e){Hi.prototype.__init.call(this),this.options={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...e}}setupOnce(){this.options.console&&he("console",cb),this.options.dom&&he("dom",ab(this.options.dom)),this.options.xhr&&he("xhr",lb),this.options.fetch&&he("fetch",db),this.options.history&&he("history",ub)}}Hi.__initStatic();function ab(s){function e(t){let i,r=typeof s=="object"?s.serializeAttribute:void 0;typeof r=="string"&&(r=[r]);try{i=t.event.target?Ki(t.event.target,r):Ki(t.event,r)}catch{i="<unknown>"}i.length!==0&&V().addBreadcrumb({category:`ui.${t.name}`,message:i},{event:t.event,name:t.name,global:t.global})}return e}function cb(s){var e={category:"console",data:{arguments:s.args,logger:"console"},level:sw(s.level),message:Ma(s.args," ")};if(s.level==="assert")if(s.args[0]===!1)e.message=`Assertion failed: ${Ma(s.args.slice(1)," ")||"console.assert"}`,e.data.arguments=s.args.slice(1);else return;V().addBreadcrumb(e,{input:s.args,level:s.level})}function lb(s){if(s.endTimestamp){if(s.xhr.__sentry_own_request__)return;const{method:e,url:t,status_code:i,body:r}=s.xhr.__sentry_xhr__||{};V().addBreadcrumb({category:"xhr",data:{method:e,url:t,status_code:i},type:"http"},{xhr:s.xhr,input:r});return}}function db(s){!s.endTimestamp||s.fetchData.url.match(/sentry_key/)&&s.fetchData.method==="POST"||(s.error?V().addBreadcrumb({category:"fetch",data:s.fetchData,level:"error",type:"http"},{data:s.error,input:s.args}):V().addBreadcrumb({category:"fetch",data:{...s.fetchData,status_code:s.response.status},type:"http"},{input:s.args,response:s.response}))}function ub(s){var e=M();let t=s.from,i=s.to;var r=Bs(e.location.href);let n=Bs(t);var o=Bs(i);n.path||(n=r),r.protocol===o.protocol&&r.host===o.host&&(i=o.relative),r.protocol===n.protocol&&r.host===n.host&&(t=n.relative),V().addBreadcrumb({category:"navigation",data:{from:t,to:i}})}var ve=M();let Tr;function ad(){if(Tr)return Tr;if(an(ve.fetch))return Tr=ve.fetch.bind(ve);var s=ve.document;let e=ve.fetch;if(s&&typeof s.createElement=="function")try{var t=s.createElement("iframe");t.hidden=!0,s.head.appendChild(t);var i=t.contentWindow;i&&i.fetch&&(e=i.fetch),s.head.removeChild(t)}catch(r){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",r)}return Tr=e.bind(ve)}function hb(s,e){var t=Object.prototype.toString.call(ve&&ve.navigator)==="[object Navigator]",i=t&&typeof ve.navigator.sendBeacon=="function";if(i){var r=ve.navigator.sendBeacon.bind(ve.navigator);r(s,e)}else if(zn()){var n=ad();n(s,{body:e,method:"POST",credentials:"omit",keepalive:!0}).then(null,o=>{(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error(o)})}}var Vs=M();class pb extends Yt{constructor(e){e._metadata=e._metadata||{},e._metadata.sdk=e._metadata.sdk||{name:"sentry.javascript.browser",packages:[{name:"npm:@sentry/browser",version:Ha}],version:Ha},super(e),e.sendClientReports&&Vs.document&&Vs.document.addEventListener("visibilitychange",()=>{Vs.document.visibilityState==="hidden"&&this._flushOutcomes()})}eventFromException(e,t){return nb(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t="info",i){return ob(this._options.stackParser,e,t,i,this._options.attachStacktrace)}sendEvent(e,t){var i=this.getIntegrationById(od);i&&i.options&&i.options.sentry&&V().addBreadcrumb({category:`sentry.${e.type==="transaction"?"transaction":"event"}`,event_id:e.event_id,level:e.level,message:Ct(e)},{event:e}),super.sendEvent(e,t)}_prepareEvent(e,t,i){return e.platform=e.platform||"javascript",super._prepareEvent(e,t,i)}_flushOutcomes(){var e=this._clearOutcomes();if(e.length===0){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("No outcomes to send");return}if(!this._dsn){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("No dsn provided, will not send outcomes");return}(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("Sending outcomes:",e);var t=id(this._dsn,this._options.tunnel),i=pw(e,this._options.tunnel&&jn(this._dsn));try{hb(t,Jl(i))}catch(r){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.error(r)}}}function mb(s,e=ad()){function t(i){var r={body:i.body,method:"POST",referrerPolicy:"origin",headers:s.headers,...s.fetchOptions};return e(s.url,r).then(n=>({statusCode:n.status,headers:{"x-sentry-rate-limits":n.headers.get("X-Sentry-Rate-Limits"),"retry-after":n.headers.get("Retry-After")}}))}return sd(s,t)}var _b=4;function fb(s){function e(t){return new oe((i,r)=>{var n=new XMLHttpRequest;n.onerror=r,n.onreadystatechange=()=>{n.readyState===_b&&i({statusCode:n.status,headers:{"x-sentry-rate-limits":n.getResponseHeader("X-Sentry-Rate-Limits"),"retry-after":n.getResponseHeader("Retry-After")}})},n.open("POST",s.url);for(var o in s.headers)Object.prototype.hasOwnProperty.call(s.headers,o)&&n.setRequestHeader(o,s.headers[o]);n.send(t.body)})}return sd(s,e)}var rs="?",gb=30,yb=40,vb=50;function Zn(s,e,t,i){var r={filename:s,function:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}var wb=/^\s*at (?:(.*?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,bb=/\((\S*)(?::(\d+))(?::(\d+))\)/,Sb=s=>{var e=wb.exec(s);if(e){var t=e[2]&&e[2].indexOf("eval")===0;if(t){var i=bb.exec(e[2]);i&&(e[2]=i[1],e[3]=i[2],e[4]=i[3])}const[r,n]=cd(e[1]||rs,e[2]);return Zn(n,r,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}},Eb=[gb,Sb],Ib=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Tb=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xb=s=>{var e=Ib.exec(s);if(e){var t=e[3]&&e[3].indexOf(" > eval")>-1;if(t){var i=Tb.exec(e[3]);i&&(e[1]=e[1]||"eval",e[3]=i[1],e[4]=i[2],e[5]="")}let r=e[3],n=e[1]||rs;return[n,r]=cd(n,r),Zn(r,n,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},kb=[vb,xb],Rb=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Ab=s=>{var e=Rb.exec(s);return e?Zn(e[2],e[1]||rs,+e[3],e[4]?+e[4]:void 0):void 0},Cb=[yb,Ab],Nb=[Eb,kb,Cb],Mb=Hl(...Nb),cd=(s,e)=>{var t=s.indexOf("safari-extension")!==-1,i=s.indexOf("safari-web-extension")!==-1;return t||i?[s.indexOf("@")!==-1?s.split("@")[0]:rs,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[s,e]};let mn=0;function ld(){return mn>0}function Db(){mn+=1,setTimeout(()=>{mn-=1})}function ci(s,e={},t){if(typeof s!="function")return s;try{var i=s.__sentry_wrapped__;if(i)return i;if(qn(s))return s}catch{return s}var r=function(){var a=Array.prototype.slice.call(arguments);try{t&&typeof t=="function"&&t.apply(this,arguments);var c=a.map(l=>ci(l,e));return s.apply(this,c)}catch(l){throw Db(),Mw(d=>{d.addEventProcessor(u=>(e.mechanism&&(cn(u,void 0,void 0),ji(u,e.mechanism)),u.extra={...u.extra,arguments:a},u)),td(l)}),l}};try{for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(r[n]=s[n])}catch{}ql(r,s),Gn(s,"__sentry_wrapped__",r);try{var o=Object.getOwnPropertyDescriptor(r,"name");o.configurable&&Object.defineProperty(r,"name",{get(){return s.name}})}catch{}return r}class ht{static __initStatic(){this.id="GlobalHandlers"}__init(){this.name=ht.id}__init2(){this._installFunc={onerror:Pb,onunhandledrejection:Ob}}constructor(e){ht.prototype.__init.call(this),ht.prototype.__init2.call(this),this._options={onerror:!0,onunhandledrejection:!0,...e}}setupOnce(){Error.stackTraceLimit=50;var e=this._options;for(var t in e){var i=this._installFunc[t];i&&e[t]&&(Lb(t),i(),this._installFunc[t]=void 0)}}}ht.__initStatic();function Pb(){he("error",s=>{const[e,t,i]=hd();if(!e.getIntegration(ht))return;const{msg:r,url:n,line:o,column:a,error:c}=s;if(!(ld()||c&&c.__sentry_own_request__)){var l=c===void 0&&_t(r)?Bb(r,n,o,a):dd(Qn(t,c||r,void 0,i,!1),n,o,a);l.level="error",ud(e,c,l,"onerror")}})}function Ob(){he("unhandledrejection",s=>{const[e,t,i]=hd();if(!e.getIntegration(ht))return;let r=s;try{"reason"in s?r=s.reason:"detail"in s&&"reason"in s.detail&&(r=s.detail.reason)}catch{}if(ld()||r&&r.__sentry_own_request__)return!0;var n=Kl(r)?Ub(r):Qn(t,r,void 0,i,!0);n.level="error",ud(e,r,n,"onunhandledrejection")})}function Ub(s){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(s)}`}]}}}function Bb(s,e,t,i){var r=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;let n=Vl(s)?s.message:s,o="Error";var a=n.match(r);a&&(o=a[1],n=a[2]);var c={exception:{values:[{type:o,value:n}]}};return dd(c,e,t,i)}function dd(s,e,t,i){var r=s.exception=s.exception||{},n=r.values=r.values||[],o=n[0]=n[0]||{},a=o.stacktrace=o.stacktrace||{},c=a.frames=a.frames||[],l=isNaN(parseInt(i,10))?void 0:i,d=isNaN(parseInt(t,10))?void 0:t,u=_t(e)&&e.length>0?e:Iv();return c.length===0&&c.push({colno:l,filename:u,function:"?",in_app:!0,lineno:d}),s}function Lb(s){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`Global Handler attached: ${s}`)}function ud(s,e,t,i){ji(t,{handled:!1,type:i}),s.captureEvent(t,{originalException:e})}function hd(){var s=V(),e=s.getClient(),t=e&&e.getOptions()||{stackParser:()=>[],attachStacktrace:!1};return[s,t.stackParser,t.attachStacktrace]}var Fb=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];class Wi{static __initStatic(){this.id="TryCatch"}__init(){this.name=Wi.id}constructor(e){Wi.prototype.__init.call(this),this._options={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...e}}setupOnce(){var e=M();this._options.setTimeout&&se(e,"setTimeout",Ya),this._options.setInterval&&se(e,"setInterval",Ya),this._options.requestAnimationFrame&&se(e,"requestAnimationFrame",Vb),this._options.XMLHttpRequest&&"XMLHttpRequest"in e&&se(XMLHttpRequest.prototype,"send",Kb);var t=this._options.eventTarget;if(t){var i=Array.isArray(t)?t:Fb;i.forEach($b)}}}Wi.__initStatic();function Ya(s){return function(...e){var t=e[0];return e[0]=ci(t,{mechanism:{data:{function:ft(s)},handled:!0,type:"instrument"}}),s.apply(this,e)}}function Vb(s){return function(e){return s.apply(this,[ci(e,{mechanism:{data:{function:"requestAnimationFrame",handler:ft(s)},handled:!0,type:"instrument"}})])}}function Kb(s){return function(...e){var t=this,i=["onload","onerror","onprogress","onreadystatechange"];return i.forEach(r=>{r in t&&typeof t[r]=="function"&&se(t,r,function(n){var o={mechanism:{data:{function:r,handler:ft(n)},handled:!0,type:"instrument"}},a=qn(n);return a&&(o.mechanism.data.handler=ft(a)),ci(n,o)})}),s.apply(this,e)}}function $b(s){var e=M(),t=e[s]&&e[s].prototype;!t||!t.hasOwnProperty||!t.hasOwnProperty("addEventListener")||(se(t,"addEventListener",function(i){return function(r,n,o){try{typeof n.handleEvent=="function"&&(n.handleEvent=ci(n.handleEvent,{mechanism:{data:{function:"handleEvent",handler:ft(n),target:s},handled:!0,type:"instrument"}}))}catch{}return i.apply(this,[r,ci(n,{mechanism:{data:{function:"addEventListener",handler:ft(n),target:s},handled:!0,type:"instrument"}}),o])}}),se(t,"removeEventListener",function(i){return function(r,n,o){var a=n;try{var c=a&&a.__sentry_wrapped__;c&&i.call(this,r,c,o)}catch{}return i.call(this,r,a,o)}}))}var jb="cause",Gb=5;class Zt{static __initStatic(){this.id="LinkedErrors"}__init(){this.name=Zt.id}constructor(e={}){Zt.prototype.__init.call(this),this._key=e.key||jb,this._limit=e.limit||Gb}setupOnce(){var e=V().getClient();!e||Wn((t,i)=>{var r=V().getIntegration(Zt);return r?qb(e.getOptions().stackParser,r._key,r._limit,t,i):t})}}Zt.__initStatic();function qb(s,e,t,i,r){if(!i.exception||!i.exception.values||!r||!Ye(r.originalException,Error))return i;var n=pd(s,t,r.originalException,e);return i.exception.values=[...n,...i.exception.values],i}function pd(s,e,t,i,r=[]){if(!Ye(t[i],Error)||r.length+1>=e)return r;var n=nd(s,t[i]);return pd(s,e,t[i],i,[n,...r])}var It=M();class ei{constructor(){ei.prototype.__init.call(this)}static __initStatic(){this.id="HttpContext"}__init(){this.name=ei.id}setupOnce(){Wn(e=>{if(V().getIntegration(ei)){if(!It.navigator&&!It.location&&!It.document)return e;var t=e.request&&e.request.url||It.location&&It.location.href;const{referrer:n}=It.document||{},{userAgent:o}=It.navigator||{};var i={...e.request&&e.request.headers,...n&&{Referer:n},...o&&{"User-Agent":o}},r={...t&&{url:t},headers:i};return{...e,request:r}}return e})}}ei.__initStatic();class ti{constructor(){ti.prototype.__init.call(this)}static __initStatic(){this.id="Dedupe"}__init(){this.name=ti.id}setupOnce(e,t){var i=r=>{var n=t().getIntegration(ti);if(n){try{if(zb(r,n._previousEvent))return(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{return n._previousEvent=r}return n._previousEvent=r}return r};i.id=this.name,e(i)}}ti.__initStatic();function zb(s,e){return e?!!(Hb(s,e)||Wb(s,e)):!1}function Hb(s,e){var t=s.message,i=e.message;return!(!t&&!i||t&&!i||!t&&i||t!==i||!_d(s,e)||!md(s,e))}function Wb(s,e){var t=Ja(e),i=Ja(s);return!(!t||!i||t.type!==i.type||t.value!==i.value||!_d(s,e)||!md(s,e))}function md(s,e){let t=Xa(s),i=Xa(e);if(!t&&!i)return!0;if(t&&!i||!t&&i||(t=t,i=i,i.length!==t.length))return!1;for(let o=0;o<i.length;o++){var r=i[o],n=t[o];if(r.filename!==n.filename||r.lineno!==n.lineno||r.colno!==n.colno||r.function!==n.function)return!1}return!0}function _d(s,e){let t=s.fingerprint,i=e.fingerprint;if(!t&&!i)return!0;if(t&&!i||!t&&i)return!1;t=t,i=i;try{return t.join("")===i.join("")}catch{return!1}}function Ja(s){return s.exception&&s.exception.values&&s.exception.values[0]}function Xa(s){var e=s.exception;if(e)try{return e.values[0].stacktrace.frames}catch{return}}var Yb=[new Qt,new zi,new Wi,new Hi,new ht,new Zt,new ti,new ei];function Jb(s={}){if(s.defaultIntegrations===void 0&&(s.defaultIntegrations=Yb),s.release===void 0){var e=M();e.SENTRY_RELEASE&&e.SENTRY_RELEASE.id&&(s.release=e.SENTRY_RELEASE.id)}s.autoSessionTracking===void 0&&(s.autoSessionTracking=!0),s.sendClientReports===void 0&&(s.sendClientReports=!0);var t={...s,stackParser:Ov(s.stackParser||Mb),integrations:Kw(s),transport:s.transport||(zn()?mb:fb)};Gw(pb,t),s.autoSessionTracking&&Xb()}function Qa(s){s.startSession({ignoreDuration:!0}),s.captureSession()}function Xb(){var s=M(),e=s.document;if(typeof e>"u"){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Session tracking in non-browser environment with @sentry/browser is not supported.");return}var t=V();!t.captureSession||(Qa(t),he("history",({from:i,to:r})=>{i===void 0||i===r||Qa(V())}))}function eo(s){var e=V().getClient(),t=s||e&&e.getOptions();return!!t&&("tracesSampleRate"in t||"tracesSampler"in t)}function ss(s){var e=s||V(),t=e.getScope();return t&&t.getTransaction()}function Q(s){return s/1e3}function Qb(){he("error",Za),he("unhandledrejection",Za)}function Za(){var s=ss();if(s){var e="internal_error";(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Transaction: ${e} -> Global error occured`),s.setStatus(e)}}class ns{__init(){this.spans=[]}constructor(e=1e3){ns.prototype.__init.call(this),this._maxlen=e}add(e){this.spans.length>this._maxlen?e.spanRecorder=void 0:this.spans.push(e)}}class tt{__init2(){this.traceId=dt()}__init3(){this.spanId=dt().substring(16)}__init4(){this.startTimestamp=Gi()}__init5(){this.tags={}}__init6(){this.data={}}constructor(e){if(tt.prototype.__init2.call(this),tt.prototype.__init3.call(this),tt.prototype.__init4.call(this),tt.prototype.__init5.call(this),tt.prototype.__init6.call(this),!e)return this;e.traceId&&(this.traceId=e.traceId),e.spanId&&(this.spanId=e.spanId),e.parentSpanId&&(this.parentSpanId=e.parentSpanId),"sampled"in e&&(this.sampled=e.sampled),e.op&&(this.op=e.op),e.description&&(this.description=e.description),e.data&&(this.data=e.data),e.tags&&(this.tags=e.tags),e.status&&(this.status=e.status),e.startTimestamp&&(this.startTimestamp=e.startTimestamp),e.endTimestamp&&(this.endTimestamp=e.endTimestamp)}startChild(e){var t=new tt({...e,parentSpanId:this.spanId,sampled:this.sampled,traceId:this.traceId});return t.spanRecorder=this.spanRecorder,t.spanRecorder&&t.spanRecorder.add(t),t.transaction=this.transaction,t}setTag(e,t){return this.tags={...this.tags,[e]:t},this}setData(e,t){return this.data={...this.data,[e]:t},this}setStatus(e){return this.status=e,this}setHttpStatus(e){this.setTag("http.status_code",String(e));var t=Zb(e);return t!=="unknown_error"&&this.setStatus(t),this}isSuccess(){return this.status==="ok"}finish(e){this.endTimestamp=typeof e=="number"?e:Gi()}toTraceparent(){let e="";return this.sampled!==void 0&&(e=this.sampled?"-1":"-0"),`${this.traceId}-${this.spanId}${e}`}toContext(){return lt({data:this.data,description:this.description,endTimestamp:this.endTimestamp,op:this.op,parentSpanId:this.parentSpanId,sampled:this.sampled,spanId:this.spanId,startTimestamp:this.startTimestamp,status:this.status,tags:this.tags,traceId:this.traceId})}updateWithContext(e){return this.data=st(e.data,()=>({})),this.description=e.description,this.endTimestamp=e.endTimestamp,this.op=e.op,this.parentSpanId=e.parentSpanId,this.sampled=e.sampled,this.spanId=st(e.spanId,()=>this.spanId),this.startTimestamp=st(e.startTimestamp,()=>this.startTimestamp),this.status=e.status,this.tags=st(e.tags,()=>({})),this.traceId=st(e.traceId,()=>this.traceId),this}getTraceContext(){return lt({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,trace_id:this.traceId})}toJSON(){return lt({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,start_timestamp:this.startTimestamp,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this.endTimestamp,trace_id:this.traceId})}}function Zb(s){if(s<400&&s>=100)return"ok";if(s>=400&&s<500)switch(s){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(s>=500&&s<600)switch(s){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}class os extends tt{__init(){this._measurements={}}constructor(e,t){super(e),os.prototype.__init.call(this),this._hub=t||V(),this.name=e.name||"",this.metadata=e.metadata||{},this._trimEnd=e.trimEnd,this.transaction=this}setName(e){this.name=e}initSpanRecorder(e=1e3){this.spanRecorder||(this.spanRecorder=new ns(e)),this.spanRecorder.add(this)}setMeasurement(e,t,i=""){this._measurements[e]={value:t,unit:i}}setMetadata(e){this.metadata={...this.metadata,...e}}finish(e){if(this.endTimestamp===void 0){if(this.name||((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this.name="<unlabeled transaction>"),super.finish(e),this.sampled!==!0){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");var t=this._hub.getClient();t&&t.recordDroppedEvent("sample_rate","transaction");return}var i=this.spanRecorder?this.spanRecorder.spans.filter(o=>o!==this&&o.endTimestamp):[];this._trimEnd&&i.length>0&&(this.endTimestamp=i.reduce((o,a)=>o.endTimestamp&&a.endTimestamp?o.endTimestamp>a.endTimestamp?o:a:o).endTimestamp);var r={contexts:{trace:this.getTraceContext()},spans:i,start_timestamp:this.startTimestamp,tags:this.tags,timestamp:this.endTimestamp,transaction:this.name,type:"transaction",sdkProcessingMetadata:{...this.metadata,baggage:this.getBaggage()}},n=Object.keys(this._measurements).length>0;return n&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding measurements to transaction",JSON.stringify(this._measurements,void 0,2)),r.measurements=this._measurements),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`),this._hub.captureEvent(r)}}toContext(){var e=super.toContext();return lt({...e,name:this.name,trimEnd:this._trimEnd})}updateWithContext(e){return super.updateWithContext(e),this.name=st(e.name,()=>""),this._trimEnd=e.trimEnd,this}getBaggage(){var e=this.metadata.baggage,t=!e||Ew(e)?this._populateBaggageWithSentryValues(e):e;return this.metadata.baggage=t,t}_populateBaggageWithSentryValues(e=zr({})){var t=this._hub||V(),i=t&&t.getClient();if(!i)return e;const{environment:r,release:n}=i.getOptions()||{},{publicKey:o}=i.getDsn()||{};var a=this.metadata&&this.metadata.transactionSampling&&this.metadata.transactionSampling.rate,c=a!==void 0?a.toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:16}):void 0,l=t.getScope();const{id:d,segment:u}=l&&l.getUser()||{};return zr(lt({environment:r,release:n,transaction:this.name,...t.shouldSendDefaultPii()&&{user_id:d},user_segment:u,public_key:o,trace_id:this.traceId,sample_rate:c,...Xl(e)}),"",!1)}}var fd=1e3,gd=3e4,eS=5e3;class tS extends ns{constructor(e,t,i,r){super(r),this._pushActivity=e,this._popActivity=t,this.transactionSpanId=i}add(e){e.spanId!==this.transactionSpanId&&(e.finish=t=>{e.endTimestamp=typeof t=="number"?t:Gi(),this._popActivity(e.spanId)},e.endTimestamp===void 0&&this._pushActivity(e.spanId)),super.add(e)}}class Jt extends os{__init(){this.activities={}}__init2(){this._heartbeatCounter=0}__init3(){this._finished=!1}__init4(){this._beforeFinishCallbacks=[]}constructor(e,t,i=fd,r=gd,n=!1){super(e,t),this._idleHub=t,this._idleTimeout=i,this._finalTimeout=r,this._onScope=n,Jt.prototype.__init.call(this),Jt.prototype.__init2.call(this),Jt.prototype.__init3.call(this),Jt.prototype.__init4.call(this),n&&(ec(t),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`),t.configureScope(o=>o.setSpan(this))),this._startIdleTimeout(),setTimeout(()=>{this._finished||(this.setStatus("deadline_exceeded"),this.finish())},this._finalTimeout)}finish(e=Gi()){if(this._finished=!0,this.activities={},this.spanRecorder){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] finishing IdleTransaction",new Date(e*1e3).toISOString(),this.op);for(var t of this._beforeFinishCallbacks)t(this,e);this.spanRecorder.spans=this.spanRecorder.spans.filter(i=>{if(i.spanId===this.spanId)return!0;i.endTimestamp||(i.endTimestamp=e,i.setStatus("cancelled"),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] cancelling span since transaction ended early",JSON.stringify(i,void 0,2)));var r=i.startTimestamp<e;return r||(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] discarding Span since it happened after Transaction was finished",JSON.stringify(i,void 0,2)),r}),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] flushing IdleTransaction")}else(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] No active IdleTransaction");return this._onScope&&ec(this._idleHub),super.finish(e)}registerBeforeFinishCallback(e){this._beforeFinishCallbacks.push(e)}initSpanRecorder(e){if(!this.spanRecorder){var t=r=>{this._finished||this._pushActivity(r)},i=r=>{this._finished||this._popActivity(r)};this.spanRecorder=new tS(t,i,this.spanId,e),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("Starting heartbeat"),this._pingHeartbeat()}this.spanRecorder.add(this)}_cancelIdleTimeout(){this._idleTimeoutID&&(clearTimeout(this._idleTimeoutID),this._idleTimeoutID=void 0)}_startIdleTimeout(e){this._cancelIdleTimeout(),this._idleTimeoutID=setTimeout(()=>{!this._finished&&Object.keys(this.activities).length===0&&this.finish(e)},this._idleTimeout)}_pushActivity(e){this._cancelIdleTimeout(),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] pushActivity: ${e}`),this.activities[e]=!0,(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] new activities count",Object.keys(this.activities).length)}_popActivity(e){if(this.activities[e]&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] popActivity ${e}`),delete this.activities[e],(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] new activities count",Object.keys(this.activities).length)),Object.keys(this.activities).length===0){var t=Gi()+this._idleTimeout/1e3;this._startIdleTimeout(t)}}_beat(){if(!this._finished){var e=Object.keys(this.activities).join("");e===this._prevHeartbeatString?this._heartbeatCounter+=1:this._heartbeatCounter=1,this._prevHeartbeatString=e,this._heartbeatCounter>=3?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] Transaction finished because of no change for 3 heart beats"),this.setStatus("deadline_exceeded"),this.finish()):this._pingHeartbeat()}}_pingHeartbeat(){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`),setTimeout(()=>{this._beat()},eS)}}function ec(s){var e=s.getScope();if(e){var t=e.getTransaction();t&&e.setSpan(void 0)}}function iS(){var s=this.getScope();if(s){var e=s.getSpan();if(e)return{"sentry-trace":e.toTraceparent()}}return{}}function yd(s,e,t){if(!eo(e))return s.sampled=!1,s;if(s.sampled!==void 0)return s.setMetadata({transactionSampling:{method:"explicitly_set"}}),s;let i;return typeof e.tracesSampler=="function"?(i=e.tracesSampler(t),s.setMetadata({transactionSampling:{method:"client_sampler",rate:Number(i)}})):t.parentSampled!==void 0?(i=t.parentSampled,s.setMetadata({transactionSampling:{method:"inheritance"}})):(i=e.tracesSampleRate,s.setMetadata({transactionSampling:{method:"client_rate",rate:Number(i)}})),rS(i)?i?(s.sampled=Math.random()<i,s.sampled?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] starting ${s.op} transaction - ${s.name}`),s):((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(i)})`),s)):((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Discarding transaction because ${typeof e.tracesSampler=="function"?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0"}`),s.sampled=!1,s):((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("[Tracing] Discarding transaction because of invalid sample rate."),s.sampled=!1,s)}function rS(s){return $l(s)||!(typeof s=="number"||typeof s=="boolean")?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(s)} of type ${JSON.stringify(typeof s)}.`),!1):s<0||s>1?((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${s}.`),!1):!0}function sS(s,e){var t=this.getClient(),i=t&&t.getOptions()||{};let r=new os(s,this);return r=yd(r,i,{parentSampled:s.parentSampled,transactionContext:s,...e}),r.sampled&&r.initSpanRecorder(i._experiments&&i._experiments.maxSpans),r}function nS(s,e,t,i,r,n){var o=s.getClient(),a=o&&o.getOptions()||{};let c=new Jt(e,s,t,i,r);return c=yd(c,a,{parentSampled:e.parentSampled,transactionContext:e,...n}),c.sampled&&c.initSpanRecorder(a._experiments&&a._experiments.maxSpans),c}function oS(){var s=mi();!s.__SENTRY__||(s.__SENTRY__.extensions=s.__SENTRY__.extensions||{},s.__SENTRY__.extensions.startTransaction||(s.__SENTRY__.extensions.startTransaction=sS),s.__SENTRY__.extensions.traceHeaders||(s.__SENTRY__.extensions.traceHeaders=iS))}function aS(){var s=mi();if(!!s.__SENTRY__){var e={mongodb(){var i=ot(Ke,"./integrations/node/mongo");return new i.Mongo},mongoose(){var i=ot(Ke,"./integrations/node/mongo");return new i.Mongo({mongoose:!0})},mysql(){var i=ot(Ke,"./integrations/node/mysql");return new i.Mysql},pg(){var i=ot(Ke,"./integrations/node/postgres");return new i.Postgres}},t=Object.keys(e).filter(i=>!!gv(i)).map(i=>{try{return e[i]()}catch{return}}).filter(i=>i);t.length>0&&(s.__SENTRY__.integrations=[...s.__SENTRY__.integrations||[],...t])}}function cS(){oS(),es()&&aS(),Qb()}var xr=M();function lS(){xr&&xr.document?xr.document.addEventListener("visibilitychange",()=>{var s=ss();if(xr.document.hidden&&s){var e="cancelled";(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Transaction: ${e} -> since tab moved to the background, op: ${s.op}`),s.status||s.setStatus(e),s.setTag("visibilitychange","document.hidden"),s.finish()}}):(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("[Tracing] Could not set up background tab detection due to lack of global document")}var to=(s,e,t)=>{let i;return r=>{e.value>=0&&(r||t)&&(e.delta=e.value-(i||0),(e.delta||i===void 0)&&(i=e.value,s(e)))}},dS=()=>`v2-${Date.now()}-${Math.floor(Math.random()*(9e12-1))+1e12}`,io=(s,e)=>({name:s,value:st(e,()=>-1),delta:0,entries:[],id:dS()}),ro=(s,e)=>{try{if(PerformanceObserver.supportedEntryTypes.includes(s)){if(s==="first-input"&&!("PerformanceEventTiming"in self))return;var t=new PerformanceObserver(i=>i.getEntries().map(e));return t.observe({type:s,buffered:!0}),t}}catch{}},as=(s,e)=>{var t=i=>{(i.type==="pagehide"||M().document.visibilityState==="hidden")&&(s(i),e&&(removeEventListener("visibilitychange",t,!0),removeEventListener("pagehide",t,!0)))};addEventListener("visibilitychange",t,!0),addEventListener("pagehide",t,!0)},uS=(s,e)=>{var t=io("CLS",0);let i,r=0,n=[];var o=c=>{if(c&&!c.hadRecentInput){var l=n[0],d=n[n.length-1];r&&n.length!==0&&c.startTime-d.startTime<1e3&&c.startTime-l.startTime<5e3?(r+=c.value,n.push(c)):(r=c.value,n=[c]),r>t.value&&(t.value=r,t.entries=n,i&&i())}},a=ro("layout-shift",o);a&&(i=to(s,t,e),as(()=>{a.takeRecords().map(o),i(!0)}))};let Pr=-1;var hS=()=>M().document.visibilityState==="hidden"?0:1/0,pS=()=>{as(({timeStamp:s})=>{Pr=s},!0)},so=()=>(Pr<0&&(Pr=hS(),pS()),{get firstHiddenTime(){return Pr}}),mS=(s,e)=>{var t=so(),i=io("FID");let r;var n=a=>{r&&a.startTime<t.firstHiddenTime&&(i.value=a.processingStart-a.startTime,i.entries.push(a),r(!0))},o=ro("first-input",n);o&&(r=to(s,i,e),as(()=>{o.takeRecords().map(n),o.disconnect()},!0))},tc={},_S=(s,e)=>{var t=so(),i=io("LCP");let r;var n=c=>{var l=c.startTime;l<t.firstHiddenTime&&(i.value=l,i.entries.push(c)),r&&r()},o=ro("largest-contentful-paint",n);if(o){r=to(s,i,e);var a=()=>{tc[i.id]||(o.takeRecords().map(n),o.disconnect(),tc[i.id]=!0,r(!0))};["keydown","click"].forEach(c=>{addEventListener(c,a,{once:!0,capture:!0})}),as(a,!0)}};function kr(s){return typeof s=="number"&&isFinite(s)}function li(s,{startTimestamp:e,...t}){return e&&s.startTimestamp>e&&(s.startTimestamp=e),s.startChild({startTimestamp:e,...t})}var Ut=M();function vd(){return Ut&&Ut.addEventListener&&Ut.performance}let ic=0,D={},Re,Pi;function fS(s=!1){var e=vd();e&&qi&&(e.mark&&Ut.performance.mark("sentry-tracing-init"),gS(),yS(s),vS())}function gS(){uS(s=>{var e=s.entries.pop();!e||((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding CLS"),D.cls={value:s.value,unit:""},Pi=e)})}function yS(s){_S(e=>{var t=e.entries.pop();if(!!t){var i=Q(qi),r=Q(t.startTime);(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding LCP"),D.lcp={value:e.value,unit:"millisecond"},D["mark.lcp"]={value:i+r,unit:"second"},Re=t}},s)}function vS(){mS(s=>{var e=s.entries.pop();if(!!e){var t=Q(qi),i=Q(e.startTime);(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding FID"),D.fid={value:s.value,unit:"millisecond"},D["mark.fid"]={value:t+i,unit:"second"}}})}function wS(s){var e=vd();if(!e||!Ut.performance.getEntries||!qi)return;(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Tracing] Adding & adjusting spans using Performance API");var t=Q(qi),i=e.getEntries();let r,n;i.slice(ic).forEach(o=>{var a=Q(o.startTime),c=Q(o.duration);if(!(s.op==="navigation"&&t+a<s.startTimestamp))switch(o.entryType){case"navigation":{SS(s,o,t),r=t+Q(o.responseStart),n=t+Q(o.requestStart);break}case"mark":case"paint":case"measure":{var l=bS(s,o,a,c,t),d=so(),u=o.startTime<d.firstHiddenTime;o.name==="first-paint"&&u&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding FP"),D.fp={value:o.startTime,unit:"millisecond"},D["mark.fp"]={value:l,unit:"second"}),o.name==="first-contentful-paint"&&u&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding FCP"),D.fcp={value:o.startTime,unit:"millisecond"},D["mark.fcp"]={value:l,unit:"second"});break}case"resource":{var h=o.name.replace(Ut.location.origin,"");IS(s,o,h,a,c,t);break}}}),ic=Math.max(i.length-1,0),TS(s),s.op==="pageload"&&(typeof r=="number"&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding TTFB"),D.ttfb={value:(r-s.startTimestamp)*1e3,unit:"millisecond"},typeof n=="number"&&n<=r&&(D["ttfb.requestTime"]={value:(r-n)*1e3,unit:"millisecond"})),["fcp","fp","lcp"].forEach(o=>{if(!(!D[o]||t>=s.startTimestamp)){var a=D[o].value,c=t+Q(a),l=Math.abs((c-s.startTimestamp)*1e3),d=l-a;(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Measurements] Normalized ${o} from ${a} to ${l} (${d})`),D[o].value=l}}),D["mark.fid"]&&D.fid&&li(s,{description:"first input delay",endTimestamp:D["mark.fid"].value+Q(D.fid.value),op:"web.vitals",startTimestamp:D["mark.fid"].value}),"fcp"in D||delete D.cls,Object.keys(D).forEach(o=>{s.setMeasurement(o,D[o].value,D[o].unit)}),xS(s)),Re=void 0,Pi=void 0,D={}}function bS(s,e,t,i,r){var n=r+t,o=n+i;return li(s,{description:e.name,endTimestamp:o,op:e.entryType,startTimestamp:n}),n}function SS(s,e,t){["unloadEvent","redirect","domContentLoadedEvent","loadEvent","connect"].forEach(i=>{Rr(s,e,i,t)}),Rr(s,e,"secureConnection",t,"TLS/SSL","connectEnd"),Rr(s,e,"fetch",t,"cache","domainLookupStart"),Rr(s,e,"domainLookup",t,"DNS"),ES(s,e,t)}function Rr(s,e,t,i,r,n){var o=n?e[n]:e[`${t}End`],a=e[`${t}Start`];!a||!o||li(s,{op:"browser",description:st(r,()=>t),startTimestamp:i+Q(a),endTimestamp:i+Q(o)})}function ES(s,e,t){li(s,{op:"browser",description:"request",startTimestamp:t+Q(e.requestStart),endTimestamp:t+Q(e.responseEnd)}),li(s,{op:"browser",description:"response",startTimestamp:t+Q(e.responseStart),endTimestamp:t+Q(e.responseEnd)})}function IS(s,e,t,i,r,n){if(!(e.initiatorType==="xmlhttprequest"||e.initiatorType==="fetch")){var o={};"transferSize"in e&&(o["Transfer Size"]=e.transferSize),"encodedBodySize"in e&&(o["Encoded Body Size"]=e.encodedBodySize),"decodedBodySize"in e&&(o["Decoded Body Size"]=e.decodedBodySize);var a=n+i,c=a+r;li(s,{description:t,endTimestamp:c,op:e.initiatorType?`resource.${e.initiatorType}`:"resource",startTimestamp:a,data:o})}}function TS(s){var e=Ut.navigator;if(!!e){var t=e.connection;t&&(t.effectiveType&&s.setTag("effectiveConnectionType",t.effectiveType),t.type&&s.setTag("connectionType",t.type),kr(t.rtt)&&(D["connection.rtt"]={value:t.rtt,unit:"millisecond"}),kr(t.downlink)&&(D["connection.downlink"]={value:t.downlink,unit:""})),kr(e.deviceMemory)&&s.setTag("deviceMemory",`${e.deviceMemory} GB`),kr(e.hardwareConcurrency)&&s.setTag("hardwareConcurrency",String(e.hardwareConcurrency))}}function xS(s){Re&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding LCP Data"),Re.element&&s.setTag("lcp.element",Ki(Re.element)),Re.id&&s.setTag("lcp.id",Re.id),Re.url&&s.setTag("lcp.url",Re.url.trim().slice(0,200)),s.setTag("lcp.size",Re.size)),Pi&&Pi.sources&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log("[Measurements] Adding CLS Data"),Pi.sources.forEach((e,t)=>s.setTag(`cls.source.${t+1}`,Ki(e.node))))}var kS=["localhost",/^\//],Wr={traceFetch:!0,traceXHR:!0,tracingOrigins:kS};function RS(s){const{traceFetch:e,traceXHR:t,tracingOrigins:i,shouldCreateSpanForRequest:r}={...Wr,...s};var n={},o=l=>{if(n[l])return n[l];var d=i;return n[l]=d.some(u=>$i(l,u))&&!$i(l,"sentry_key"),n[l]};let a=o;typeof r=="function"&&(a=l=>o(l)&&r(l));var c={};e&&he("fetch",l=>{AS(l,a,c)}),t&&he("xhr",l=>{NS(l,a,c)})}function AS(s,e,t){if(!(!eo()||!(s.fetchData&&e(s.fetchData.url)))){if(s.endTimestamp){var i=s.fetchData.__span;if(!i)return;var r=t[i];r&&(s.response?r.setHttpStatus(s.response.status):s.error&&r.setStatus("internal_error"),r.finish(),delete t[i]);return}var n=ss();if(n){var r=n.startChild({data:{...s.fetchData,type:"fetch"},description:`${s.fetchData.method} ${s.fetchData.url}`,op:"http.client"});s.fetchData.__span=r.spanId,t[r.spanId]=r;var o=s.args[0]=s.args[0],a=s.args[1]=s.args[1]||{};a.headers=CS(o,n.getBaggage(),r,a)}}}function CS(s,e,t,i){let r=i.headers;if(Ye(s,Request)&&(r=s.headers),r)if(typeof r.append=="function")r.append("sentry-trace",t.toTraceparent()),r.append(Wt,ki(e,r.get(Wt)));else if(Array.isArray(r)){const[,n]=r.find(([o,a])=>o===Wt);r=[...r,["sentry-trace",t.toTraceparent()],[Wt,ki(e,n)]]}else r={...r,"sentry-trace":t.toTraceparent(),baggage:ki(e,r.baggage)};else r={"sentry-trace":t.toTraceparent(),baggage:ki(e)};return r}function NS(s,e,t){if(!(!eo()||s.xhr&&s.xhr.__sentry_own_request__||!(s.xhr&&s.xhr.__sentry_xhr__&&e(s.xhr.__sentry_xhr__.url)))){var i=s.xhr.__sentry_xhr__;if(s.endTimestamp){var r=s.xhr.__sentry_xhr_span_id__;if(!r)return;var n=t[r];n&&(n.setHttpStatus(i.status_code),n.finish(),delete t[r]);return}var o=ss();if(o){var n=o.startChild({data:{...i.data,type:"xhr",method:i.method,url:i.url},description:`${i.method} ${i.url}`,op:"http.client"});if(s.xhr.__sentry_xhr_span_id__=n.spanId,t[s.xhr.__sentry_xhr_span_id__]=n,s.xhr.setRequestHeader)try{s.xhr.setRequestHeader("sentry-trace",n.toTraceparent());var a=s.xhr.getRequestHeader&&s.xhr.getRequestHeader(Wt);s.xhr.setRequestHeader(Wt,ki(o.getBaggage(),a))}catch{}}}}var Ei=M();function MS(s,e=!0,t=!0){if(!Ei||!Ei.location){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("Could not initialize routing instrumentation due to invalid location");return}let i=Ei.location.href,r;e&&(r=s({name:Ei.location.pathname,op:"pageload"})),t&&he("history",({to:n,from:o})=>{if(o===void 0&&i&&i.indexOf(n)!==-1){i=void 0;return}o!==n&&(i=void 0,r&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Finishing current transaction with op: ${r.op}`),r.finish()),r=s({name:Ei.location.pathname,op:"navigation"}))})}var DS="BrowserTracing",PS={idleTimeout:fd,finalTimeout:gd,markBackgroundTransactions:!0,routingInstrumentation:MS,startTransactionOnLocationChange:!0,startTransactionOnPageLoad:!0,...Wr};class no{__init(){this.name=DS}constructor(e){no.prototype.__init.call(this);let t=Wr.tracingOrigins;e&&(e.tracingOrigins&&Array.isArray(e.tracingOrigins)&&e.tracingOrigins.length!==0?t=e.tracingOrigins:(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&(this._emitOptionsWarning=!0)),this.options={...PS,...e,tracingOrigins:t};const{_metricOptions:i}=this.options;fS(i&&i._reportAllChanges)}setupOnce(e,t){this._getCurrentHub=t,this._emitOptionsWarning&&((typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn("[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace."),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`[Tracing] We added a reasonable default for you: ${Wr.tracingOrigins}`));const{routingInstrumentation:i,startTransactionOnLocationChange:r,startTransactionOnPageLoad:n,markBackgroundTransactions:o,traceFetch:a,traceXHR:c,tracingOrigins:l,shouldCreateSpanForRequest:d}=this.options;i(u=>this._createRouteTransaction(u),n,r),o&&lS(),RS({traceFetch:a,traceXHR:c,tracingOrigins:l,shouldCreateSpanForRequest:d})}_createRouteTransaction(e){if(!this._getCurrentHub){(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.warn(`[Tracing] Did not create ${e.op} transaction because _getCurrentHub is invalid.`);return}const{beforeNavigate:t,idleTimeout:i,finalTimeout:r}=this.options;var n=e.op==="pageload"?OS():void 0,o={...e,...n,trimEnd:!0},a=typeof t=="function"?t(o):o,c=a===void 0?{...o,sampled:!1}:a;c.sampled===!1&&(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Will not send ${c.op} transaction because of beforeNavigate.`),(typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__)&&y.log(`[Tracing] Starting ${c.op} transaction on scope`);var l=this._getCurrentHub();const{location:d}=M();var u=nS(l,c,i,r,!0,{location:d});return u.registerBeforeFinishCallback(h=>{wS(h),h.setTag("sentry_reportAllChanges",Boolean(this.options._metricOptions&&this.options._metricOptions._reportAllChanges))}),u}}function OS(){var s=rc("sentry-trace"),e=rc("baggage"),t=s?cw(s):void 0,i=xw(e,s);if(t||i)return{...t&&t,...i&&{metadata:{baggage:i}}}}function rc(s){var e=M();if(e.document&&e.document.querySelector){var t=e.document.querySelector(`meta[name=${s}]`);return t?t.getAttribute("content"):null}else return null}(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&cS();const US={downloadSandbox:uv,worker:hv,olm:{wasm:pv,legacyBundle:_v,wasmBundle:mv}},BS="#chatterbox";async function LS(){const e=new URLSearchParams(window.location.search).get("config");if(!e)throw new Error("Root element does not have config specified");return await(await fetch(e)).json()}function FS(){return!!new URLSearchParams(window.location.search).get("minimized")}async function VS(){jS();const s=document.querySelector(BS);if(!s)throw new Error("No element with id as 'chatterbox' found!");s.className="hydrogen";const e=await LS();e.sentry&&(Jb({dsn:e.sentry.dsn,environment:e.sentry.environment,integrations:[new no]}),Si("homeserver",e.homeserver),Si("encrypt_room",e.encrypt_room),e.invite_user?Si("mode","invite_user"):e.auto_join_room?Si("mode","auto_join_room"):Si("mode","unknown"));const t=new Jm({container:s,assetPaths:US,config:{themeManifests:[]},options:{development:!1}});$S(t);const i=new Xg(KS);t.setNavigation(i);const r=ty({navigation:i,history:t.history}),n=FS(),o=new rv(e,{platform:t,navigation:i,urlCreator:r,startMinimized:n});o.start();const a=new dv(o);s.appendChild(a.mount())}function KS(s,e){const{type:t}=e;switch(s?.type){case void 0:return t==="start"||t==="account-setup"||t==="timeline"||t==="minimize";default:return!1}}function $S(s){window.downloadLogs=async()=>{const e=await s.logger.export();confirm(`Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited, the usernames of other users and the names of files you send. They do not contain messages. For more information, review our privacy policy at https://element.io/privacy.
Continue to export logs?`)&&s.saveFileAs(e.asBlob(),"chatterbox-logs.json")}}function jS(){const s=e=>(td(e,{tags:{fatalError:!0}}),e.message==="ResizeObserver loop completed with undelivered notifications."||e.message==="ResizeObserver loop limit exceeded"||e.target.tagName==="IMG"?(e.stopImmediatePropagation(),!1):(console.error(e.error??e.reason),window.sendError(),!1));window.addEventListener("error",s,!0),window.addEventListener("unhandledrejection",s,!0)}window.sendViewChangeToParent=function(s){window.parent?.postMessage({action:"resize-iframe",view:s},"*")};window.sendMinimizeToParent=function(){window.parent?.postMessage({action:"minimize"},"*")};window.sendNotificationCount=function(s){window.parent?.postMessage({action:"unread-message",count:s},"*")};window.sendError=function(){window.parent?.postMessage({action:"error"},"*")};VS()});export default GS();