var Gc=Object.defineProperty,Yc=Object.defineProperties;var Jc=Object.getOwnPropertyDescriptors;var Yi=Object.getOwnPropertySymbols;var jn=Object.prototype.hasOwnProperty,qn=Object.prototype.propertyIsEnumerable;var $n=(n,e,t)=>e in n?Gc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,It=(n,e)=>{for(var t in e||(e={}))jn.call(e,t)&&$n(n,t,e[t]);if(Yi)for(var t of Yi(e))qn.call(e,t)&&$n(n,t,e[t]);return n},Fr=(n,e)=>Yc(n,Jc(e));var Hn=(n,e)=>{var t={};for(var s in n)jn.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&Yi)for(var s of Yi(n))e.indexOf(s)<0&&qn.call(n,s)&&(t[s]=n[s]);return t};function oi(...n){const e={};for(const t of n)e[t]=t;return Object.freeze(e)}function Wn(n){try{return new URL(n).origin}catch{return new URL(`https://${n}`).origin}}async function Qc(n,e){const t={format:"json",timeout:3e4,method:"GET"};try{const s=`${n}/.well-known/matrix/client`;return await e(s,t).response()}catch(s){if(s.name==="ConnectionError")return null;throw s}}async function Xc(n,e){var s;n=Wn(n);const t=await Qc(n,e);if(t&&t.status===200){const{body:i}=t,r=(s=i["m.homeserver"])==null?void 0:s.base_url;typeof r=="string"&&(n=Wn(r))}return n}class $t{constructor(){this._handlersByName={}}emit(e,t){const s=this._handlersByName[e];s&&s.forEach(i=>i(t))}disposableOn(e,t){return this.on(e,t),()=>{this.off(e,t)}}on(e,t){let s=this._handlersByName[e];s||(this.onFirstSubscriptionAdded(e),this._handlersByName[e]=s=new Set),s.add(t)}off(e,t){const s=this._handlersByName[e];s&&(s.delete(t),s.size===0&&(delete this._handlersByName[e],this.onLastSubscriptionRemoved(e)))}onFirstSubscriptionAdded(e){}onLastSubscriptionRemoved(e){}}class oa extends $t{constructor(e){super(),this._abortable=void 0;const t=i=>(this._abortable=i,i);this._progress=void 0;const s=i=>{this._progress=i,this.emit("change","progress")};this.result=e(t,s)}get progress(){return this._progress}abort(){var e;(e=this._abortable)==null||e.abort(),this._abortable=void 0}}class rt extends Error{get name(){return"AbortError"}}class xr{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 yt extends xr{emit(e){for(const t of this._handlers)t(e)}waitFor(e){return e(this.get())?new el(Promise.resolve(this.get())):new Zc(this,e)}flatMap(e){return new sl(this,e)}}class Zc{constructor(e,t){this._promise=new Promise((s,i)=>{this._reject=i,this._subscription=e.subscribe(r=>{t(r)&&(this._reject=null,s(r),this.dispose())})})}get promise(){return this._promise}dispose(){this._subscription&&(this._subscription(),this._subscription=null),this._reject&&(this._reject(new rt),this._reject=null)}}class el{constructor(e){this.promise=e}dispose(){}}class tl extends yt{constructor(e,t){super(),this.value=e,this.eventName=t}onSubscribeFirst(){this.eventSubscription=this.value.disposableOn(this.eventName,()=>{this.emit(this.value)}),super.onSubscribeFirst()}onUnsubscribeLast(){this.eventSubscription(),super.onUnsubscribeLast()}get(){return this.value}}class Vt extends yt{constructor(e){super(),this._value=e}get(){return this._value}set(e){e!==this._value&&(this._value=e,this.emit(this._value))}}class sl extends yt{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==null?void 0:t.get()}}function il(n,e){return e{}){super(e),this.freeCallback=t,this.startCallback=s}onSubscribeFirst(){this.startCallback()}onUnsubscribeLast(){super.onUnsubscribeLast(),this.freeCallback()}}class ai extends xr{emitReset(){for(let e of this._handlers)e.onReset(this)}emitAdd(e,t){for(let s of this._handlers)s.onAdd(e,t,this)}emitUpdate(e,t,s){for(let i of this._handlers)i.onUpdate(e,t,s,this)}emitRemove(e,t){for(let s of this._handlers)s.onRemove(e,t,this)}emitMove(e,t,s){for(let i of this._handlers)i.onMove(e,t,s,this)}}/** * @license * Based off baseSortedIndex function in Lodash * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */function Nt(n,e,t){let s=0,i=n.length;for(;s>>1,o=t(e,n[r]);o>0?s=r+1:o<0?i=r:s=i=r}return i}class gn extends ai{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 s of t)this.insert(e,s),e+=1}insert(e,t){this._items.splice(e,0,t),this.emitAdd(e,t)}move(e,t){if(e=0&&e=this._items.length||this._comparator(this._items[s],e)!==0?(this._items.splice(s,0,e),this.emitAdd(s,e)):(this._items[s]=e,this.emitUpdate(s,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 nl(this)}}class nl{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 ol extends ai{constructor(e,t,s,i){super(),this._sourceUnsubscribe=null,this._mappedValues=null,this._sourceList=e,this._mapper=t,this._updater=s,this._removeCallback=i}findAndUpdate(e,t){return aa(e,this._mappedValues,this,t)}get length(){return this._mappedValues.length}[Symbol.iterator](){return this._mappedValues.values()}}function al(n,e,t){n._mappedValues.splice(e,0,t),n.emitAdd(e,t)}function cl(n,e,t,s){const i=n._mappedValues[e];n._updater&&n._updater(i,s,t),n.emitUpdate(e,i,s)}function ll(n,e){const t=n._mappedValues[e];n._mappedValues.splice(e,1),n._removeCallback&&n._removeCallback(t),n.emitRemove(e,t)}function hl(n,e,t){const s=n._mappedValues[e];n._mappedValues.splice(e,1),n._mappedValues.splice(t,0,s),n.emitMove(e,t,s)}function dl(n){n._mappedValues=[],n.emitReset()}class ul extends ol{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 zn(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 gl),this._flush())}onAdd(e,t){this._eventQueue&&(this._eventQueue.push(new zn(e,t)),this._flush())}onUpdate(e,t,s){this._eventQueue&&(this._eventQueue.push(new ml(e,t,s)),this._flush())}onRemove(e){this._eventQueue&&(this._eventQueue.push(new _l(e)),this._flush())}onMove(e,t){this._eventQueue&&(this._eventQueue.push(new pl(e,t)),this._flush())}onUnsubscribeLast(){this._sourceUnsubscribe(),this._eventQueue=null,this._mappedValues=null}}class zn{constructor(e,t){this.index=e,this.value=t}async run(e){const t=await e._mapper(this.value);al(e,this.index,t)}}class ml{constructor(e,t,s){this.index=e,this.value=t,this.params=s}async run(e){cl(e,this.index,this.value,this.params)}}class _l{constructor(e){this.index=e}async run(e){ll(e,this.index)}}class pl{constructor(e,t){this.fromIdx=e,this.toIdx=t}async run(e){hl(e,this.fromIdx,this.toIdx)}}class gl{async run(e){dl(e)}}class ca extends ai{constructor(...e){super(),this._sourceUnsubscribes=null,this._sourceLists=e}_offsetForSource(e){const t=this._sourceLists.indexOf(e);let s=0;for(let i=0;ie.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,s){this.emitAdd(this._offsetForSource(s)+e,t)}onUpdate(e,t,s,i){!this._sourceUnsubscribes||this.emitUpdate(this._offsetForSource(i)+e,t,s)}onRemove(e,t,s){this.emitRemove(this._offsetForSource(s)+e,t)}onMove(e,t,s,i){const r=this._offsetForSource(i);this.emitMove(r+e,r+t,s)}get length(){let e=0;for(let t=0;t{let s=t.next();for(;s.done;){if(e+=1,e>=this._sourceLists.length)return s;t=this._sourceLists[e][Symbol.iterator](),s=t.next()}return s}}}}class fl extends ai{constructor(e,t){super(),this._sourceMap=e,this._comparator=(s,i)=>t(s.value,i.value),this._sortedPairs=null,this._mapSubscription=null}onAdd(e,t){const s={key:e,value:t},i=Nt(this._sortedPairs,s,this._comparator);this._sortedPairs.splice(i,0,s),this.emitAdd(i,t)}onRemove(e,t){const s={key:e,value:t},i=Nt(this._sortedPairs,s,this._comparator);this._sortedPairs.splice(i,1),this.emitRemove(i,t)}onUpdate(e,t,s){if(!this._sortedPairs)return;const i=this._sortedPairs.findIndex(c=>c.key===e);this._sortedPairs.splice(i,1);const r={key:e,value:t},o=Nt(this._sortedPairs,r,this._comparator);this._sortedPairs.splice(o,0,r),i!==o&&this.emitMove(i,o,t),this.emitUpdate(o,t,s)}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,s]of this._sourceMap)this._sortedPairs[e]={key:t,value:s},++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 ci extends xr{constructor(){super()}emitReset(){for(let e of this._handlers)e.onReset()}emitAdd(e,t){for(let s of this._handlers)s.onAdd(e,t)}emitUpdate(e,t,s){for(let i of this._handlers)i.onUpdate(e,t,s)}emitRemove(e,t){for(let s of this._handlers)s.onRemove(e,t)}join(...e){return new bl([this].concat(e))}mapValues(e,t){return new Il(this,e,t)}sortValues(e){return new fl(this,e)}filterValues(e){return new wl(this,e)}observeSize(){return new Cl(this)}}class yl extends ci{constructor(e,t){super(),this._source=e,this._apply=t}hasApply(){return!!this._apply}setApply(e){this._apply=e,this._apply&&this.applyOnce(this._apply)}applyOnce(e){for(const[t,s]of this._source)e(t,s)}onAdd(e,t){this._apply&&this._apply(e,t),this.emitAdd(e,t)}onRemove(e,t){this.emitRemove(e,t)}onUpdate(e,t,s){this._apply&&this._apply(e,t,s),this.emitUpdate(e,t,s)}onSubscribeFirst(){this._subscription=this._source.subscribe(this),this._apply&&this.applyOnce(this._apply),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._subscription&&(this._subscription=this._subscription())}onReset(){this._apply&&this.applyOnce(this._apply),this.emitReset()}[Symbol.iterator](){return this._source[Symbol.iterator]()}get size(){return this._source.size}get(e){return this._source.get(e)}}class wl extends ci{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){this._included=this._included||new Map;for(const[t,s]of this._source){const i=this._filter(s,t),r=this._included.get(t);if(this._included.set(t,i),!e){const o=r||!0;this._emitForUpdate(o,i,t,s)}}}else{if(this._included&&!e)for(const[t,s]of this._source)this._included.get(t)||this.emitAdd(t,s);this._included=void 0}}onAdd(e,t){if(this._filter)if(this._included){const s=this._filter(t,e);if(this._included.set(e,s),!s)return}else throw new Error("Internal logic error: FilteredMap._included used before initialized");this.emitAdd(e,t)}onRemove(e,t){var i;const s=!this._filter||((i=this._included)==null?void 0:i.get(e));if(this._included)this._included.delete(e),s&&this.emitRemove(e,t);else throw new Error("Internal logic error: FilteredMap._included used before initialized")}onUpdate(e,t,s){if(!!this._included)if(this._filter){const i=this._included.get(e),r=this._filter(t,e);this._included.set(e,r),this._emitForUpdate(i,r,e,t,s)}else this.emitUpdate(e,t,s)}_emitForUpdate(e,t,s,i,r=null){e&&!t?this.emitRemove(s,i):!e&&t?this.emitAdd(s,i):e&&t&&this.emitUpdate(s,i,r)}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 vl(this._source,this._included)}get size(){var t;let e=0;return(t=this._included)==null||t.forEach(s=>{s&&(e+=1)}),e}get(e){const t=this._source.get(e);if(t&&this._filter(t,e))return t}}class vl{constructor(e,t){this._included=t,this._sourceIterator=e[Symbol.iterator]()}next(){var e;for(;;){const t=this._sourceIterator.next();if(t.done)return t;const s=t.value[0];if((e=this._included)!=null&&e.get(s))return t}}}class bl extends ci{constructor(e){super(),this._sources=e}onAdd(e,t,s){if(!this._isKeyAtSourceOccluded(e,t)){const i=this._getValueFromOccludedSources(e,t);i!==void 0&&this.emitRemove(t,i),this.emitAdd(t,s)}}onRemove(e,t,s){if(!this._isKeyAtSourceOccluded(e,t)){this.emitRemove(t,s);const i=this._getValueFromOccludedSources(e,t);i!==void 0&&this.emitAdd(t,i)}}onUpdate(e,t,s,i){!this._subscriptions||this._isKeyAtSourceOccluded(e,t)||this.emitUpdate(t,s,i)}onReset(){this.emitReset()}onSubscribeFirst(){this._subscriptions=this._sources.map(e=>new kl(e,this).subscribe()),super.onSubscribeFirst()}_isKeyAtSourceOccluded(e,t){const s=this._sources.indexOf(e);for(let i=0;ie+t.size,0)}get(e){for(const t of this._sources){const s=t.get(e);if(s)return s}}}class Sl{constructor(e){this._sourceIndex=-1,this._encounteredKeys=new Set,this._sources=e}next(){var t;let e;for(;!e;){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 s=(t=this._currentIterator)==null?void 0:t.next();if(!s||s.done){this._currentIterator=void 0;continue}else{const i=s.value[0];this._encounteredKeys.has(i)||(this._encounteredKeys.add(i),e=s)}}return e}}class kl{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,s){this._joinedMap.onUpdate(this._source,e,t,s)}onReset(){this._joinedMap.onReset()}}class Il extends ci{constructor(e,t,s){super(),this._source=e,this._mapper=t,this._updater=s,this._mappedValues=new Map}_emitSpontaneousUpdate(e,t){const s=this._mappedValues.get(e);s&&this.emitUpdate(e,s,t)}onAdd(e,t){const s=this._emitSpontaneousUpdate.bind(this,e),i=this._mapper(t,s);this._mappedValues.set(e,i),this.emitAdd(e,i)}onRemove(e){const t=this._mappedValues.get(e);this._mappedValues.delete(e)&&t&&this.emitRemove(e,t)}onUpdate(e,t,s){var r;if(!this._mappedValues)return;const i=this._mappedValues.get(e);i!==void 0&&((r=this._updater)==null||r.call(this,s,i,t),this.emitUpdate(e,i,s))}onSubscribeFirst(){this._subscription=this._source.subscribe(this);for(let[e,t]of this._source){const s=this._emitSpontaneousUpdate.bind(this,e),i=this._mapper(t,s);this._mappedValues.set(e,i)}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 Dt extends ci{constructor(e){super(),this._values=new Map(e)}update(e,t){const s=this._values.get(e);return s!==void 0?(this._values.set(e,s),this.emitUpdate(e,s,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()}}class Ml extends ci{constructor(e,t){super(),this.key=e,this.observableValue=t}onSubscribeFirst(){this.subscription=this.observableValue.subscribe(e=>{this.emitUpdate(this.key,e,void 0)}),super.onSubscribeFirst()}onUnsubscribeLast(){this.subscription(),super.onUnsubscribeLast()}*[Symbol.iterator](){yield[this.key,this.observableValue.get()]}get size(){return 1}get(e){if(e==this.key)return this.observableValue.get()}}class Cl extends yt{constructor(e){super(),this.map=e}onSubscribeFirst(){this.subscription=this.map.subscribe({onAdd:(e,t)=>{this.emit(this.get())},onRemove:(e,t)=>{this.emit(this.get())},onUpdate:(e,t)=>{},onReset:()=>{this.emit(this.get())}})}onUnsubscribeLast(){var e;this.subscription=(e=this.subscription)==null?void 0:e.call(this)}get(){return this.map.size}}const El={"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},Gn="application/octet-stream";class Ts{constructor(e,t=null){this._blob=e,this._buffer=t,this._url=null}static fromBuffer(e,t){return t=t?t.split(";")[0].trim():"",El[t]||(t=Gn),new Ts(new Blob([e],{type:t}),e)}static fromBlobUnsafe(e){return new Ts(e)}get nativeBlob(){return this._blob}async readAsBuffer(){if(this._buffer)return this._buffer;{const e=new FileReader,t=new Promise((s,i)=>{e.addEventListener("load",r=>s(r.target.result)),e.addEventListener("error",r=>i(r.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||Gn}dispose(){this._url&&(URL.revokeObjectURL(this._url),this._url=null)}}function la(n){return Object.entries(n||{}).filter(([,e])=>e!==void 0).map(([e,t])=>(typeof t=="object"&&(t=JSON.stringify(t)),`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join("&")}function Rl(n){if(n instanceof Ts){const e=n;return{mimeType:e.mimeType,body:e}}else{if(n instanceof Map)return{mimeType:"multipart/form-data",body:n};if(typeof n=="object"){const e=JSON.stringify(n);return{mimeType:"application/json",body:e}}else throw new Error("Unknown body type: "+n)}}class ha extends Error{constructor(e,t){super(`${e}: ${t.message}`),this.cause=t}get name(){return"WrappedError"}}class da extends Error{constructor(e,t,s,i){super(`${s?s.error:i} on ${e} ${t}`),this.errcode=s?s.errcode:null,this.retry_after_ms=s?s.retry_after_ms:0,this.statusCode=i}get name(){return"HomeServerError"}}class Ut extends Error{constructor(e,t){super(e||"ConnectionError"),this.isTimeout=t}get name(){return"ConnectionError"}}class Tl{constructor(e,t,s,i){let r;if(i!=null&&i.log){const o=i==null?void 0:i.log;r=o.child({t:"network",url:t,method:e},o.level.Info)}this._log=r,this._sourceRequest=s,this._promise=s.response().then(o=>{var c,l;if(r==null||r.set("status",o.status),o.status>=200&&o.status<300||((c=i==null?void 0:i.allowedStatusCodes)==null?void 0:c.includes(o.status)))return r==null||r.finish(),o.body;if(o.status>=500){const h=new Ut("Internal Server Error");throw r==null||r.catch(h),h}else if(o.status>=400&&!((l=o.body)!=null&&l.errcode)){const h=new Ut(`HTTP error status ${o.status} without errcode in body, assume this is a load balancer complaining the server is offline.`);throw r==null||r.catch(h),h}else{const h=new da(e,t,o.body,o.status);throw r==null||r.set("errcode",h.errcode),r==null||r.catch(h),h}},o=>{if(o.name==="AbortError"&&this._sourceRequest){const c=new Ut("Service worker aborted, either updating or hit #187.");throw r==null||r.catch(c),c}else throw o.name==="ConnectionError"&&(r==null||r.set("timeout",o.isTimeout)),r==null||r.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 Ji="/_matrix/client/r0",Yn="/_matrix/client/v3",Lr="/_matrix/client/unstable/org.matrix.msc2697.v2";class ws{constructor({homeserver:e,accessToken:t,request:s,reconnector:i}){this._homeserver=e,this._accessToken=t,this._requestFn=s,this._reconnector=i}_url(e,t=Ji){return this._homeserver+t+e}_baseRequest(e,t,s,i,r,o){const c=la(s);t=`${t}?${c}`;let l;const h=new Map;if(o&&h.set("Authorization",`Bearer ${o}`),h.set("Accept","application/json"),i){const p=Rl(i);h.set("Content-Type",p.mimeType),l=p.body}const a=this._requestFn(t,{method:e,headers:h,body:l,timeout:r==null?void 0:r.timeout,uploadProgress:r==null?void 0:r.uploadProgress,format:"json",cache:e!=="GET"}),u=new Tl(e,t,a,r);return this._reconnector&&u.response().catch(p=>{p.name==="ConnectionError"&&this._reconnector.onRequestFailed(this)}),u}_unauthedRequest(e,t,s,i,r){return this._baseRequest(e,t,s,i,r)}_authedRequest(e,t,s,i,r){return this._baseRequest(e,t,s,i,r,this._accessToken)}_post(e,t,s,i){return this._authedRequest("POST",this._url(e,(i==null?void 0:i.prefix)||Ji),t,s,i)}_put(e,t,s,i){return this._authedRequest("PUT",this._url(e,(i==null?void 0:i.prefix)||Ji),t,s,i)}_get(e,t,s,i){return this._authedRequest("GET",this._url(e,(i==null?void 0:i.prefix)||Ji),t,s,i)}updateAccessToken(e){this._accessToken=e}sync(e,t,s,i){return this._get("/sync",{since:e,timeout:s,filter:t},void 0,i)}context(e,t,s,i){return this._get(`/rooms/${encodeURIComponent(e)}/context/${encodeURIComponent(t)}`,{filter:i,limit:s})}messages(e,t,s){return this._get(`/rooms/${encodeURIComponent(e)}/messages`,t,void 0,s)}members(e,t,s){return this._get(`/rooms/${encodeURIComponent(e)}/members`,t,void 0,s)}send(e,t,s,i,r){return this._put(`/rooms/${encodeURIComponent(e)}/send/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},i,r)}redact(e,t,s,i,r){return this._put(`/rooms/${encodeURIComponent(e)}/redact/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},i,r)}receipt(e,t,s,i){return this._post(`/rooms/${encodeURIComponent(e)}/receipt/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},{},i)}state(e,t,s,i){return this._get(`/rooms/${encodeURIComponent(e)}/state/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},void 0,i)}sendState(e,t,s,i,r){return this._put(`/rooms/${encodeURIComponent(e)}/state/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},i,r)}getLoginFlows(){return this._unauthedRequest("GET",this._url("/login"))}register(e,t,s,i,r=!1,o={}){o.allowedStatusCodes=[401];const c={auth:i,password:t,initial_device_displayname:s,inhibit_login:r};return e&&(c.username=e),this._unauthedRequest("POST",this._url("/register",Yn),void 0,c,o)}passwordLogin(e,t,s,i){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:s},i)}tokenLogin(e,t,s,i){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:s},i)}createFilter(e,t,s){return this._post(`/user/${encodeURIComponent(e)}/filter`,{},t,s)}versions(e){return this._unauthedRequest("GET",`${this._homeserver}/_matrix/client/versions`,void 0,void 0,e)}uploadKeys(e,t,s){let i="/keys/upload";return e&&(i=i+`/${encodeURIComponent(e)}`),this._post(i,{},t,s)}uploadSignatures(e,t){return this._post("/keys/signatures/upload",{},e,t)}queryKeys(e,t){return this._post("/keys/query",{},e,t)}claimKeys(e,t){return this._post("/keys/claim",{},e,t)}sendToDevice(e,t,s,i){return this._put(`/sendToDevice/${encodeURIComponent(e)}/${encodeURIComponent(s)}`,{},t,i)}roomKeysVersion(e,t){let s="";return e&&(s=`/${encodeURIComponent(e)}`),this._get(`/room_keys/version${s}`,void 0,void 0,t)}roomKeyForRoomAndSession(e,t,s,i){return this._get(`/room_keys/keys/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{version:e},void 0,i)}uploadRoomKeysToBackup(e,t,s={}){return s.prefix=Yn,this._put("/room_keys/keys",{version:e},t,s)}uploadAttachment(e,t,s){return this._authedRequest("POST",`${this._homeserver}/_matrix/media/r0/upload`,{filename:t},e,s)}setPusher(e,t){return this._post("/pushers/set",{},e,t)}getPushers(e){return this._get("/pushers",void 0,void 0,e)}invite(e,t,s,i){return this._post(`/rooms/${encodeURIComponent(e)}/invite`,{},{user_id:t,reason:s},i)}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=Lr,this._get("/dehydrated_device",void 0,void 0,e)}createDehydratedDevice(e,t={}){return t.prefix=Lr,this._put("/dehydrated_device",{},e,t)}claimDehydratedDevice(e,t={}){return t.prefix=Lr,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,s,i){return this._put(`/user/${encodeURIComponent(e)}/account_data/${encodeURIComponent(t)}`,{},s,i)}getTurnServer(e){return this._get("/voip/turnServer",void 0,void 0,e)}}class ua{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 rt))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 Ys=(n=>(n[n.Waiting=0]="Waiting",n[n.Reconnecting=1]="Reconnecting",n[n.Online=2]="Online",n))(Ys||{});class Al{constructor({retryDelay:e,createMeasure:t,onlineStatus:s}){this._onlineStatus=s,this._retryDelay=e,this._createTimeMeasure=t,this._state=new Vt(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(s=>{s&&this.tryNow()});try{await this._reconnectLoop(e)}catch(s){console.error(s)}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 xl(n,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:s}=n,{base64:i}=n.encoding;var r=i.decode(t.iv),o=i.encode(i.decode(t.hashes.sha256));const c=await s.digest("SHA-256",e);if(i.encode(new Uint8Array(c))!=o)throw new Error("Mismatched SHA-256 digest");var l;return t.v=="v1"||t.v=="v2"?l=64:l=128,await s.aes.decryptCTR({jwkKey:t.key,iv:r,data:e,counterLength:l})}async function Vl(n,e){const{crypto:t}=n,{base64:s}=n.encoding,i=await t.aes.generateIV(),r=await t.aes.generateKey("jwk",256),o=await e.readAsBuffer(),c=await t.aes.encryptCTR({jwkKey:r,iv:i,data:o}),l=await t.digest("SHA-256",c);return{blob:n.createBlob(c,"application/octet-stream"),info:{v:"v2",key:r,iv:s.encodeUnpadded(i),hashes:{sha256:s.encodeUnpadded(l)}}}}class Nl{constructor(e){this.homeserver=e.homeserver,this.platform=e.platform,this.generateMediaUrl(e.serverVersions)}generateMediaUrl(e){const t="v1.11";e.includes(t)?this.mediaUrlPart="_matrix/client/v1/media":this.mediaUrlPart="_matrix/media/v3"}mxcUrlThumbnail(e,t,s,i){const r=this.parseMxcUrl(e);if(r){const[o,c]=r;return`${this.homeserver}/${this.mediaUrlPart}/thumbnail/${encodeURIComponent(o)}/${encodeURIComponent(c)}`+"?"+la({width:Math.round(t),height:Math.round(s),method:i})}}mxcUrl(e){const t=this.parseMxcUrl(e);if(t){const[s,i]=t;return`${this.homeserver}/${this.mediaUrlPart}/download/${encodeURIComponent(s)}/${encodeURIComponent(i)}`}}parseMxcUrl(e){const t="mxc://";if(e.startsWith(t))return e.slice(t.length).split("/",2)}async downloadEncryptedFile(e,t=!1){const s=this.mxcUrl(e.url),{body:i}=await this.platform.request(s,{method:"GET",format:"buffer",cache:t}).response(),r=await xl(this.platform,i,e);return this.platform.createBlob(r,e.mimetype)}async downloadPlaintextFile(e,t,s=!1){const i=this.mxcUrl(e),{body:r}=await this.platform.request(i,{method:"GET",format:"buffer",cache:s}).response();return this.platform.createBlob(r,t)}async downloadAttachment(e,t=!1){var s;return e.file?this.downloadEncryptedFile(e.file,t):this.downloadPlaintextFile(e.url,(s=e.info)==null?void 0:s.mimetype,t)}}class Dl{constructor(e,t){this.methodName=e,this.args=t,this._responsePromise=new Promise((s,i)=>{this.responseResolve=s,this.responseReject=i})}abort(){var e;this._requestResult?this._requestResult.abort():(this.responseReject(new rt),(e=this.responseCodeReject)==null||e.call(this,new rt))}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 i,r,o;this._requestResult=e;const t=await((i=this._requestResult)==null?void 0:i.response());this.responseResolve(t);const s=await((r=this._requestResult)==null?void 0:r.responseCode());(o=this.responseCodeResolve)==null||o.call(this,s)}get requestResult(){return this._requestResult}}class ma{constructor(e){this._scheduler=e}}for(const n of Object.getOwnPropertyNames(ws.prototype))n!=="constructor"&&!n.startsWith("_")&&(ma.prototype[n]=function(...e){return this._scheduler._hsApiRequest(n,e)});class Ul{constructor({hsApi:e,clock:t}){this._requests=new Set,this._stopped=!1,this._wrapper=new ma(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 s=new Dl(e,t);return this._doSend(s),s}async _doSend(e){this._requests.add(e);try{let t;for(;!this._stopped;)try{const s=this._hsApi[e.methodName].apply(this._hsApi,e.args);await e.setRequestResult(s);return}catch(s){if(s instanceof da&&s.errcode==="M_LIMIT_EXCEEDED")Number.isSafeInteger(s.retry_after_ms)?await this._clock.createTimeout(s.retry_after_ms).elapsed():(t||(t=new ua(this._clock.createTimeout)),await t.waitForRetry());else{e.responseReject(s);return}}this._stopped&&e.abort()}finally{this._requests.delete(e)}}}const Ol=3e4,te=oi("InitialSync","CatchupSync","Syncing","Stopped");function Pl(n){var e;try{const t=(e=n==null?void 0:n.timeline)==null?void 0:e.events;return Array.isArray(t)&&t.length===0}catch{return!0}}class Fl{constructor({hsApi:e,session:t,storage:s,logger:i}){this._hsApi=e,this._logger=i,this._session=t,this._storage=s,this._currentRequest=null,this._status=new Vt(te.Stopped),this._error=null}get status(){return this._status}get error(){return this._error}start(){if(this._status.get()!==te.Stopped)return;this._error=null;let e=this._session.syncToken;e?this._status.set(te.CatchupSync):this._status.set(te.InitialSync),this._syncLoop(e)}async _syncLoop(e){for(;this._status.get()!==te.Stopped;){let t,s,i=this._status.get()===te.CatchupSync||this._status.get()===te.InitialSync;await this._logger.run("sync",async r=>{r.set("token",e),r.set("status",this._status.get());try{const o=this._status.get()===te.Syncing?Ol:0,c=await this._syncRequest(e,o,r);e=c.syncToken,t=c.roomStates,s=c.sessionChanges,this._status.get()!==te.Syncing&&c.hadToDeviceMessages?this._status.set(te.CatchupSync):this._status.set(te.Syncing)}catch(o){if(o.name==="ConnectionError"&&o.isTimeout)return;this._error=o,o.name!=="AbortError"&&(r.error=o,r.logLevel=r.level.Fatal),r.set("stopping",!0),this._status.set(te.Stopped)}this._status.get()!==te.Stopped&&await r.wrap("afterSyncCompleted",o=>this._runAfterSyncCompleted(s,t,o))},this._logger.level.Info,(r,o)=>o.durationWithoutType("network")>=2e3||o.error||i?r.minLevel(o.level.Detail):r.minLevel(o.level.Info))}}async _runAfterSyncCompleted(e,t,s){const i=this._status.get()===te.CatchupSync,r=(async()=>{try{await s.wrap("session",c=>this._session.afterSyncCompleted(e,i,c))}catch{}})(),o=t.map(async c=>{try{await c.room.afterSyncCompleted(c.changes,s)}catch{}});await Promise.all(o.concat(r))}async _syncRequest(e,t,s){var g;let{syncFilterId:i}=this._session;typeof i!="string"&&(this._currentRequest=this._hsApi.createFilter(this._session.user.id,{room:{state:{lazy_load_members:!0}}},{log:s}),i=(await this._currentRequest.response()).filter_id);const r=t+80*1e3;this._currentRequest=this._hsApi.sync(e,i,t,{timeout:r,log:s});const o=await this._currentRequest.response(),c=!e,l=new Ll,h=this._parseInvites(o.rooms),{roomStates:a,archivedRoomStates:u}=await this._parseRoomsResponse(o.rooms,h,c,s);try{l.lock=await s.wrap("obtainSyncLock",()=>this._session.obtainSyncLock(o)),await s.wrap("prepare",f=>this._prepareSync(l,a,o,f)),await s.wrap("afterPrepareSync",f=>Promise.all(a.map(v=>v.room.afterPrepareSync(v.preparation,f)))),await s.wrap("write",async f=>this._writeSync(l,h,a,u,o,i,c,f))}finally{l.dispose()}s.wrap("after",f=>this._afterSync(l,h,a,u,f));const p=(g=o.to_device)==null?void 0:g.events;return{syncToken:o.next_batch,roomStates:a,sessionChanges:l.changes,hadToDeviceMessages:Array.isArray(p)&&p.length>0}}_openPrepareSyncTxn(){const e=this._storage.storeNames;return this._storage.readTxn([e.deviceKeys,e.olmSessions,e.inboundGroupSessions,e.timelineFragments,e.timelineEvents])}async _prepareSync(e,t,s,i){var c,l;const r=await this._openPrepareSyncTxn();e.preparation=await i.wrap("session",h=>this._session.prepareSync(s,e.lock,r,h));const o=(c=e.preparation)==null?void 0:c.newKeysByRoom;if(o){const{hasOwnProperty:h}=Object.prototype;for(const a of o.keys())if(!(((l=s.rooms)==null?void 0:l.join)&&h.call(s.rooms.join,a))){let p=this._session.rooms.get(a);p&&t.push(new Jn(p,!1,{},p.membership))}}await Promise.all(t.map(async h=>{const a=o==null?void 0:o.get(h.room.id);h.preparation=await i.wrap("room",async u=>(h.isNewRoom&&await h.room.load(null,r,u),h.room.prepareSync(h.roomResponse,h.membership,a,r,u)),i.level.Detail)})),await r.complete()}async _writeSync(e,t,s,i,r,o,c,l){const h=await this._openSyncTxn();try{e.changes=await l.wrap("session",a=>this._session.writeSync(r,o,e.preparation,h,a)),await Promise.all(t.map(async a=>{a.changes=await l.wrap("invite",u=>a.invite.writeSync(a.membership,a.roomResponse,h,u))})),await Promise.all(s.map(async a=>{a.changes=await l.wrap("room",u=>a.room.writeSync(a.roomResponse,c,a.preparation,h,u))})),await Promise.all(i.map(async a=>{var p;const u=(p=a.roomState)==null?void 0:p.summaryChanges;a.changes=await l.wrap("archivedRoom",g=>a.archivedRoom.writeSync(u,a.roomResponse,a.membership,h,g))}))}catch(a){throw h.abort(l),h.getCause(a)}await h.complete(l)}_afterSync(e,t,s,i,r){r.wrap("session",o=>this._session.afterSync(e.changes,o),r.level.Detail);for(let o of i)r.wrap("archivedRoom",c=>{o.archivedRoom.afterSync(o.changes,c),o.archivedRoom.release()},r.level.Detail);for(let o of s)r.wrap("room",c=>o.room.afterSync(o.changes,c),r.level.Detail);for(let o of t)r.wrap("invite",c=>o.invite.afterSync(o.changes,c),r.level.Detail);this._session.applyRoomCollectionChangesAfterSync(t,s,i,r)}_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.deviceKeys,e.outboundGroupSessions,e.operations,e.accountData,e.olmSessions,e.inboundGroupSessions,e.calls])}async _parseRoomsResponse(e,t,s,i){const r=[],o=[];if(e){const c=["join","leave"];for(const l of c){const h=e[l];if(h)for(const[a,u]of Object.entries(h)){if(s&&Pl(u))continue;const p=this._session.invites.get(a);p&&t.push(new Qn(p,!1,null,l));const g=this._createRoomSyncState(a,u,l,s);g&&r.push(g);const f=await this._createArchivedRoomSyncState(a,g,u,l,s,i);f&&o.push(f)}}}return{roomStates:r,archivedRoomStates:o}}_createRoomSyncState(e,t,s,i){let r=!1,o=this._session.rooms.get(e);if(!o&&(s==="join"||i&&s==="leave")&&(o=this._session.createJoinedRoom(e),r=!0),o)return new Jn(o,r,t,s)}async _createArchivedRoomSyncState(e,t,s,i,r,o){let c;if((t==null?void 0:t.shouldAdd)&&!r?c=this._session.createOrGetArchivedRoomForSync(e):i==="leave"&&(t?c=this._session.createOrGetArchivedRoomForSync(e):c=await this._session.loadArchivedRoom(e,o)),c)return new Kl(c,t,s,i)}_parseInvites(e){const t=[];if(e!=null&&e.invite)for(const[s,i]of Object.entries(e.invite)){let r=this._session.invites.get(s),o=!1;r||(r=this._session.createInvite(s),o=!0),t.push(new Qn(r,o,i,"invite"))}return t}stop(){this._status.get()!==te.Stopped&&(this._status.set(te.Stopped),this._currentRequest&&(this._currentRequest.abort(),this._currentRequest=null))}}class Ll{constructor(){this.lock=null,this.preparation=null,this.changes=null}dispose(){var e;(e=this.lock)==null||e.release()}}class Jn{constructor(e,t,s,i){this.room=e,this.isNewRoom=t,this.roomResponse=s,this.membership=i,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 Kl{constructor(e,t,s,i,r){this.archivedRoom=e,this.roomState=t,this.roomResponse=s,this.membership=i,this.isInitialSync=r,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 Qn{constructor(e,t,s,i){this.invite=e,this.isNewInvite=t,this.membership=i,this.roomResponse=s,this.changes=null}get id(){return this.invite.id}get shouldAdd(){return this.isNewInvite}get shouldRemove(){return this.membership!=="invite"}}function _a(n){if(n.__esModule)return n;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(n).forEach(function(t){var s=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return n[t]}})}),e}var Xn=/[\\\"\x00-\x1F]/g,jt={};for(var Qi=0;Qi<32;++Qi)jt[String.fromCharCode(Qi)]="\\U"+("0000"+Qi.toString(16)).slice(-4).toUpperCase();jt["\b"]="\\b";jt[" "]="\\t";jt[` `]="\\n";jt["\f"]="\\f";jt["\r"]="\\r";jt['"']='\\"';jt["\\"]="\\\\";function pa(n){return Xn.lastIndex=0,n.replace(Xn,function(e){return jt[e]})}function yn(n){switch(typeof n){case"string":return'"'+pa(n)+'"';case"number":return isFinite(n)?n:"null";case"boolean":return n;case"object":return n===null?"null":Array.isArray(n)?Bl(n):$l(n);default:throw new Error("Cannot stringify: "+typeof n)}}function Bl(n){for(var e="[",t="",s=0;s(n[n.Sync=0]="Sync",n[n.Timeline=1]="Timeline",n[n.Retry=2]="Retry",n))(ts||{});const Oe="e2ee:",wn="m.olm.v1.curve25519-aes-sha2",ft="m.megolm.v1.aes-sha2";class fe extends Error{constructor(e,t,s){super(`Decryption error ${e}${s?": "+JSON.stringify(s):""}`),this.code=e,this.event=t,this.detailsObj=s}}const jl="ed25519";function ks(n){return n.keys[`ed25519:${n.device_id}`]}function _t(n){return n.keys[`curve25519:${n.device_id}`]}function ql(n,e,t){var s,i;return(i=(s=n==null?void 0:n.signatures)==null?void 0:s[e])==null?void 0:i[`${jl}:${t}`]}var ne=(n=>(n[n.Valid=0]="Valid",n[n.Invalid=1]="Invalid",n[n.NotSigned=2]="NotSigned",n))(ne||{});function vn(n,e,t,s,i,r){const o=ql(i,e,t);if(!o)return r==null||r.set("no_signature",!0),2;const c=Object.assign({},i);delete c.unsigned,delete c.signatures;const l=qi.stringify(c);try{return n.ed25519_verify(s,l,o),0}catch(h){if(r){const a=r.log({l:"Invalid signature, ignoring.",ed25519Key:s,canonicalJson:l,signature:o});a.error=h,a.logLevel=r.level.Warn}return 1}}function Hl(){return{type:"m.room.encryption",state_key:"",content:{algorithm:ft,rotation_period_ms:6048e5,rotation_period_msgs:100}}}function Xi(n,e){switch(e){case"world_readable":return!0;case"shared":return n!==void 0;case"joined":return n==="join";case"invited":return n==="invite"||n==="join";default:return!1}}function Qr(n){var e;return((e=n.unsigned)==null?void 0:e.prev_content)||n.prev_content}const gt="m.room.redaction";function Xr(n){var e;return!!((e=n==null?void 0:n.unsigned)!=null&&e.redacted_because)}var se=(n=>(n[n.None=1]="None",n[n.BeingCreated=2]="BeingCreated",n[n.Invited=4]="Invited",n[n.Joined=8]="Joined",n[n.Replaced=16]="Replaced",n[n.Archived=32]="Archived",n))(se||{}),Le=(n=>(n[n.DirectMessage=0]="DirectMessage",n[n.Private=1]="Private",n[n.Public=2]="Public",n))(Le||{});function Js(n,e){var o,c;let t;const s=l=>{const h=e(l);h instanceof Promise&&(t=t!=null?t:[],t.push(h))},i=(o=n.state)==null?void 0:o.events;if(i)for(let l=0;l{})}function Wl(n,e,t,s,i){return e.length&&(n=e.reduce((r,o)=>Jl(r,o,t,s,i),n)),n}function zl(n,e,t,s){e.summary&&(n=Ql(n,e.summary)),t!==n.membership&&(n=n.cloneIfNeeded(),n.membership=t),e.account_data&&(n=e.account_data.events.reduce(Yl,n)),Js(e,r=>{n=ga(n,r,s)});const i=e.unread_notifications;return i&&(n=Gl(n,i)),n}function Gl(n,e){const t=e.highlight_count||0;t!==n.highlightCount&&(n=n.cloneIfNeeded(),n.highlightCount=t);const s=e.notification_count;return s!==n.notificationCount&&(n=n.cloneIfNeeded(),n.notificationCount=s),n}function Yl(n,e){var t;if((e==null?void 0:e.type)==="m.tag"){let s=(t=e==null?void 0:e.content)==null?void 0:t.tags;(!s||Array.isArray(s)||typeof s!="object")&&(s=null),n=n.cloneIfNeeded(),n.tags=s}return n}function ga(n,e,t){var s,i,r;if(e.type==="m.room.create")n=n.cloneIfNeeded(),n.lastMessageTimestamp=e.origin_server_ts;else if(e.type==="m.room.encryption"){const o=(s=e.content)==null?void 0:s.algorithm;!n.encryption&&o===ft&&(n=n.cloneIfNeeded(),n.encryption=e.content)}else if(e.type==="m.room.name"){const o=(i=e.content)==null?void 0:i.name;o!==n.name&&(n=n.cloneIfNeeded(),n.name=o)}else if(e.type==="m.room.avatar"){const o=(r=e.content)==null?void 0:r.url;o!==n.avatarUrl&&(n=n.cloneIfNeeded(),n.avatarUrl=o)}else if(e.type==="m.room.canonical_alias"){const o=e.content;n=n.cloneIfNeeded(),n.canonicalAlias=o.alias}else if(e.type==="m.room.member"){const o=e.content;if(o.is_direct===!0&&o.membership==="invite"&&!n.isDirectMessage){let c;e.sender===t?c=e.state_key:e.state_key===t&&(c=e.sender),c&&(n=n.cloneIfNeeded(),n.isDirectMessage=!0,n.dmUserId=c)}else o.membership==="leave"&&n.isDirectMessage&&n.dmUserId===e.state_key&&(n=n.cloneIfNeeded(),n.isDirectMessage=!1,n.dmUserId=null)}return n}function Jl(n,e,t,s,i){return e.eventType==="m.room.message"&&((!n.lastMessageTimestamp||e.timestamp>n.lastMessageTimestamp)&&(n=n.cloneIfNeeded(),n.lastMessageTimestamp=e.timestamp),!t&&e.sender!==i&&s&&(n=n.cloneIfNeeded(),n.isUnread=!0)),n}function Ql(n,e){const t=e["m.heroes"],s=e["m.joined_member_count"],i=e["m.invited_member_count"];return t&&Array.isArray(t)&&(n=n.cloneIfNeeded(),n.heroes=t),Number.isInteger(i)&&(n=n.cloneIfNeeded(),n.inviteCount=i),Number.isInteger(s)&&(n=n.cloneIfNeeded(),n.joinCount=s),n}class Rt{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(s=>s!=="cloned"&&this[s]!==e[s])}cloneIfNeeded(){return this.cloned?this:new Rt(this)}serialize(){return Object.entries(this).reduce((e,[t,s])=>(t!=="cloned"&&s!==null&&(e[t]=s),e),{})}applyTimelineEntries(e,t,s,i){return Wl(this,e,t,s,i)}applySyncResponse(e,t,s){return zl(this,e,t,s)}get needsHeroes(){return!this.name&&!this.canonicalAlias&&this.heroes&&this.heroes.length>0}isNewJoin(e){return this.membership==="join"&&e.membership!=="join"}}class Xl{constructor(e){this._data=null,this.applyChanges(new Rt(null,e))}get data(){return this._data}writeClearUnread(e){const t=new Rt(this._data);return t.isUnread=!1,t.notificationCount=0,t.highlightCount=0,e.roomSummary.set(t.serialize()),t}writeHasFetchedMembers(e,t){const s=new Rt(this._data);return s.hasFetchedMembers=e,t.roomSummary.set(s.serialize()),s}writeIsTrackingMembers(e,t){const s=new Rt(this._data);return s.isTrackingMembers=e,t.roomSummary.set(s.serialize()),s}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 s=await t.readWriteTxn([t.storeNames.roomSummary]);try{s.roomSummary.set(e.serialize())}catch(i){throw s.abort(),i}return await s.complete(),this.applyChanges(e),!0}applyChanges(e){this._data=e,this._data.cloned=!1}async load(e){this.applyChanges(new Rt(e))}}var J=(n=>(n.session="session",n.roomState="roomState",n.roomSummary="roomSummary",n.archivedRoomSummary="archivedRoomSummary",n.invites="invites",n.roomMembers="roomMembers",n.timelineEvents="timelineEvents",n.timelineRelations="timelineRelations",n.timelineFragments="timelineFragments",n.pendingEvents="pendingEvents",n.userIdentities="userIdentities",n.deviceKeys="deviceKeys",n.olmSessions="olmSessions",n.inboundGroupSessions="inboundGroupSessions",n.outboundGroupSessions="outboundGroupSessions",n.groupSessionDecryptions="groupSessionDecryptions",n.operations="operations",n.accountData="accountData",n.calls="calls",n.crossSigningKeys="crossSigningKeys",n.sharedSecrets="sharedSecrets",n))(J||{});const Oi=Object.values(J);class Ot extends Error{constructor(e,t=null){super(e),t&&(this.errcode=t.name),this.cause=t}get name(){return"StorageError"}}const ce={get minStorageKey(){return 0},get middleStorageKey(){return 2147483647},get maxStorageKey(){return 4294967295}};class pe{constructor(e,t){this.fragmentId=e,this.eventIndex=t}nextFragmentKey(){return new pe(this.fragmentId+1,ce.middleStorageKey)}nextKeyForDirection(e){return e.isForward?this.nextKey():this.previousKey()}previousKey(){return new pe(this.fragmentId,this.eventIndex-1)}nextKey(){return new pe(this.fragmentId,this.eventIndex+1)}static get maxKey(){return new pe(ce.maxStorageKey,ce.maxStorageKey)}static get minKey(){return new pe(ce.minStorageKey,ce.minStorageKey)}static get defaultLiveKey(){return pe.defaultFragmentKey(ce.minStorageKey)}static defaultFragmentKey(e){return new pe(e,ce.middleStorageKey)}toString(){return`[${this.fragmentId}/${this.eventIndex}]`}equals(e){return this.fragmentId===(e==null?void 0:e.fragmentId)&&this.eventIndex===(e==null?void 0:e.eventIndex)}}const Zr=Number.MAX_SAFE_INTEGER;class fa{constructor(e){this._fragmentIdComparer=e}compare(e){return this.fragmentId===e.fragmentId?this.entryIndex-e.entryIndex:this.fragmentId===Zr?1:e.fragmentId===Zr?-1:this._fragmentIdComparer.compare(this.fragmentId,e.fragmentId)}asEventKey(){return new pe(this.fragmentId,this.entryIndex)}}const Zl="m.reaction",ss="m.annotation",ya="m.reference";function eh(n,e){return{"m.relates_to":{event_id:n,key:e,rel_type:ss}}}function th(n){return{"m.relates_to":{event_id:n,rel_type:ya}}}function bn(n){var e;return n.event_id||((e=n["m.in_reply_to"])==null?void 0:e.event_id)}function wa(n,e){n.event_id!==void 0?n.event_id=e:n["m.in_reply_to"]&&(n["m.in_reply_to"].event_id=e)}function va(n){if(n.type===gt)return n.redacts;{const e=Xt(n);if(e)return bn(e)}return null}function rs(n){return n==null?void 0:n["m.relates_to"]}function Xt(n){return rs(n.content)}class sh{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,s)=>!t||s.pendingEvent.queueIndex>t.pendingEvent.queueIndex?s:t,null);return e?!e.isRedaction:!1}get isEmpty(){return this._entries.length===0}}function Zn(n){return n.replace(/&/g,"&").replace(//g,">")}function ih(n){switch(n){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 rh(n){return n==="m.emote"?"* ":""}function nh(n,e,t,s){return{msgtype:e,body:t,format:"org.matrix.custom.html",formatted_body:s,"m.relates_to":{"m.in_reply_to":{event_id:n}}}}function oh(n,e,t){const s=ih(n.content.msgtype),i=rh(n.content.msgtype),r=n.sender,o=n.displayName||r,c=s||n.content.formatted_body||n.content.body&&Zn(n.content.body)||"",l=`
In reply to ${i}${o}
${c}
`,a=(s||n.content.body||"").split(` `);a[0]=`> ${i}<${r}> ${a[0]}`;const p=a.join(` > `)+` `+t,g=l+Zn(t);return nh(n.id,e,p,g)}class ba extends fa{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 isReference(){var e;return((e=this.relation)==null?void 0:e.rel_type)===ya}get isRedacting(){return!!this._pendingRedactions}get isRedacted(){return this.isRedacting}get isRedaction(){return this.eventType===gt}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===gt&&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===ss&&this._addPendingAnnotation(e))return"pendingAnnotations"}}removeLocalRelation(e){var t;if(e.eventType===gt&&e.isRelatedToId(this.id)&&this._pendingRedactions){const s=this._pendingRedactions.length;if(this._pendingRedactions=this._pendingRedactions.filter(i=>i!==e),this._pendingRedactions.length===0&&(this._pendingRedactions=null,s!==0))return"isRedacted"}else{const s=e.redactingEntry||e;if(s.isRelatedToId(this.id)&&((t=s.relation)==null?void 0:t.rel_type)===ss&&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 s=this._pendingAnnotations.get(t);return s||(s=new sh,this._pendingAnnotations.set(t,s)),s.add(e),!0}return!1}_removePendingAnnotation(e){const{key:t}=(e.redactingEntry||e).relation;if(t){let s=this._pendingAnnotations.get(t);return s.remove(e)&&s.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 eh(this.id,e)}createReplyContent(e,t){return oh(this,e,t)}isRelatedToId(e){return e&&this.relatedEventId===e}haveAnnotation(e){var r,o,c;const t=((o=(r=this.annotations)==null?void 0:r[e])==null?void 0:o.me)||!1,s=(c=this.pendingAnnotations)==null?void 0:c.get(e),i=(s==null?void 0:s.willAnnotate)||!1;return t&&(!s||i)||!t&&i}get relation(){return rs(this.content)}get pendingAnnotations(){return this._pendingAnnotations}get annotations(){return null}}class ah extends ba{constructor({pendingEvent:e,member:t,clock:s,redactingEntry:i}){super(null),this._pendingEvent=e,this._member=t,this._timestamp=s.now()-(100-e.queueIndex),this._redactingEntry=i}get fragmentId(){return Zr}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}}class As{constructor(){let e,t;this.promise=new Promise((s,i)=>{e=s,t=i}),this.resolve=s=>{this._value=s,e(s)},this.reject=t}get value(){return this._value}}const X=oi("Waiting","EncryptingAttachments","UploadingAttachments","Encrypting","Sending","Sent","Error"),eo=["m.relates_to"];class ch{constructor({data:e,remove:t,emitUpdate:s,attachments:i}){this._data=e,this._attachments=i,this._emitUpdate=s,this._removeFromQueueCallback=t,this._aborted=!1,this._status=X.Waiting,this._sendRequest=null,this._attachmentsTotalBytes=0,this._deferred=new As,this._attachments&&(this._attachmentsTotalBytes=Object.values(this._attachments).reduce((r,o)=>r+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=rs(this.content);return e?bn(e):this._data.relatedEventId}setRelatedEventId(e){const t=rs(this.content);t?wa(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=X.Encrypting,this._emitUpdate("status")}get contentForEncryption(){const e=Object.assign({},this._data.content);for(const t of eo)delete e[t];return e}_preserveContentFields(e){const t=this._data.content;for(const s of eo)t[s]!==void 0&&(e[s]=t[s])}setEncrypted(e,t){this._preserveContentFields(t),this._data.encryptedEventType=e,this._data.encryptedContent=t,this._data.needsEncryption=!1}setError(e){this._status=X.Error,this._error=e,this._emitUpdate("status")}setWaiting(){this._status=X.Waiting,this._emitUpdate("status")}get status(){return this._status}get error(){return this._error}get hasStartedSending(){return this._status===X.Sending||this._status===X.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=X.EncryptingAttachments,this._emitUpdate("status");for(const i of Object.values(this._attachments))if(await t.wrap("encrypt",()=>(t.set("size",i.size),i.encrypt())),this.aborted)throw new rt}this._status=X.UploadingAttachments,this._emitUpdate("status");const s=Object.entries(this._attachments);s.sort(([,i],[,r])=>i.size-r.size);for(const[i,r]of s)await t.wrap("upload",o=>(o.set("size",r.size),r.upload(e,()=>{this._emitUpdate("attachmentsSentBytes")},o))),r.applyToContent(i,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=X.Sending,this._emitUpdate("status");const s=this._data.encryptedEventType||this._data.eventType,i=this._data.encryptedContent||this._data.content;s===gt?this._sendRequest=e.redact(this.roomId,this._data.relatedEventId,this.txnId,i,{log:t}):this._sendRequest=e.send(this.roomId,s,this.txnId,i,{log:t});const r=await this._sendRequest.response();this._sendRequest=null,this._data.remoteId=r.event_id,this._deferred.resolve(r.event_id),t.set("id",this._data.remoteId),this._status=X.Sent,this._emitUpdate("status")}getRemoteId(){return this._deferred.promise}dispose(){if(this._attachments)for(const e of Object.values(this._attachments))e.dispose()}}class Ye extends ba{constructor(e,t){super(t),this._eventEntry=e,this._decryptionError=null,this._decryptionResult=null}clone(){const e=new Ye(this._eventEntry,this._fragmentIdComparer);return e.updateFrom(this),e}updateFrom(e){e._decryptionResult&&(this._decryptionResult=e._decryptionResult),e._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 Qr(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 va(this.event)}get isRedacted(){return super.isRedacted||Xr(this._eventEntry.event)}get redactionReason(){var t,s;const e=(t=this._eventEntry.event.unsigned)==null?void 0:t.redacted_because;return e?(s=e.content)==null?void 0:s.reason:super.redactionReason}get annotations(){return this._eventEntry.annotations}get relation(){const e=this._eventEntry.event.content;return e&&rs(e)||rs(this.content)}get contextEventId(){return this.isReply||this.isReference?this.relatedEventId:null}}function Sa(n,e,t){return{fragmentId:n.fragmentId,eventIndex:n.eventIndex,roomId:e,event:t}}function Vi(n,e,t){t.isForward?n.push(e):n.unshift(e)}function lh(n,e,t){return t.isForward?n.concat(e):e.concat(n)}const Ke="m.room.member";class Q{constructor(e){this._data=e}static fromUserId(e,t,s){return new Q({roomId:e,userId:t,membership:s})}static fromMemberEvent(e,t){const s=t==null?void 0:t.state_key;if(typeof s!="string")return;const i=t.content,r=Qr(t),o=i==null?void 0:i.membership,c=(i==null?void 0:i.displayname)||(r==null?void 0:r.displayname),l=(i==null?void 0:i.avatar_url)||(r==null?void 0:r.avatar_url);return this._validateAndCreateMember(e,s,o,c,l)}static fromReplacingMemberEvent(e,t){const s=t&&t.state_key;if(typeof s!="string")return;const i=Qr(t);return this._validateAndCreateMember(e,s,i==null?void 0:i.membership,i==null?void 0:i.displayname,i==null?void 0:i.avatar_url)}static _validateAndCreateMember(e,t,s,i,r){if(typeof s=="string")return new Q({roomId:e,userId:t,membership:s,avatarUrl:r,displayName:i})}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,s=e._data;return t.roomId===s.roomId&&t.userId===s.userId&&t.membership===s.membership&&t.displayName===s.displayName&&t.avatarUrl===s.avatarUrl}}class ka{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"}}function Sn(n){return typeof n=="number"}const hh=["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"].reduce(function(n,e){return n[e]=1,n},{}),dh={"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 uh(n,e){for(const i of Object.keys(e))hh[i]||delete e[i];const{content:t}=e,s=dh[e.type];for(const i of Object.keys(t))s!=null&&s[i]||delete t[i];e.unsigned=e.unsigned||{},e.unsigned.redacted_because=n}function mh(n,e){const t=[];for(;Sn(n.previousId);){const s=e.get(n.previousId);if(!s)break;if(s.nextId!==n.id)throw new Error(`Previous fragment ${s.id} doesn't point back to ${n.id}`);e.delete(n.previousId),t.unshift(s),n=s}return t}function _h(n,e){const t=[];for(;Sn(n.nextId);){const s=e.get(n.nextId);if(!s)break;if(s.previousId!==n.id)throw new Error(`Next fragment ${s.id} doesn't point back to ${n.id}`);e.delete(n.nextId),t.push(s),n=s}return t}function ph(n){const e=new Map;for(let s of n)e.set(s.id,s);const t=[];for(;e.size;){const s=e.values().next().value;e.delete(s.id);const i=mh(s,e),r=_h(s,e),o=i.concat(s,r);t.push(o)}return t.map(s=>new gh(s))}class Kr{constructor(e,t,s){this.id=e,this.previousId=t,this.nextId=s}}class gh{constructor(e){this._idToSortIndex=new Map,e.forEach((t,s)=>{this._idToSortIndex.set(t.id,s)})}compare(e,t){const s=this._idToSortIndex.get(e);if(s===void 0)throw new Error(`first id ${e} isn't part of this island`);const i=this._idToSortIndex.get(t);if(i===void 0)throw new Error(`second id ${t} isn't part of this island`);return s-i}get fragmentIds(){return this._idToSortIndex.keys()}}class to extends Error{get name(){return"CompareError"}}class fh{constructor(e){this._fragmentsById=e.reduce((t,s)=>(t.set(s.id,s),t),new Map),this.rebuild(e)}_getIsland(e){const t=this._idToIsland.get(e);if(t===void 0)throw new to(`Unknown fragment id ${e}`);return t}compare(e,t){if(e===t)return 0;const s=this._getIsland(e),i=this._getIsland(t);if(s!==i)throw new to(`${e} and ${t} are on different islands, can't tell order`);return s.compare(e,t)}rebuild(e){const t=ph(e);this._idToIsland=new Map;for(let s of t)for(let i of s.fragmentIds)this._idToIsland.set(i,s)}add(e){const t=new Kr(e.id,e.previousId,e.nextId);this._fragmentsById.set(e.id,t),this.rebuild(this._fragmentsById.values())}append(e,t){const s=new Kr(e,t,null),i=this._fragmentsById.get(t);i&&(i.nextId=e),this._fragmentsById.set(e,s),this.rebuild(this._fragmentsById.values())}prepend(e,t){const s=new Kr(e,null,t),i=this._fragmentsById.get(t);i&&(i.previousId=e),this._fragmentsById.set(e,s),this.rebuild(this._fragmentsById.values())}}(function(){const e=document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"})();function yh(n){return"objectStore"in n?`${n.objectStore.name}.${n.name}`:n.name}function wh(n){var e,t,s,i,r;return"objectStore"in n?(s=(t=(e=n.objectStore)==null?void 0:e.transaction)==null?void 0:t.db)==null?void 0:s.name:(r=(i=n.transaction)==null?void 0:i.db)==null?void 0:r.name}class Ia extends Ot{constructor(e,t,s=null){const i=t&&"source"in t?t.source:t,r=i?yh(i):"",o=i?wh(i):"";let c=`${e} on ${o}.${r}`;s&&(c+=": ",typeof s.name=="string"&&(c+=`(name: ${s.name}) `),typeof s.code=="number"&&(c+=`(code: ${s.code}) `)),s&&(c+=s.message),super(c,s),this.storeName=r,this.databaseName=o}}class kn extends Ia{constructor(e){const t=e.target,s=t.source,i=t.error;super("IDBRequest failed",s,i),this.errorEvent=e}preventTransactionAbort(){this.errorEvent.preventDefault()}}class lt extends Ia{constructor(e,t,s,i){super(`${e}(${i.map(r=>JSON.stringify(r)).join(", ")}) failed`,t,s)}}const so={done:!0},Lt={done:!1};function vr(n){const e=n.toString(16);return"0".repeat(8-e.length)+e}function en(n){return parseInt(n,16)}function In(n,e,t,s=window.indexedDB){const i=s.open(n,t);return i.onupgradeneeded=async r=>{const o=r.target,c=o.result,l=o.transaction,h=r.oldVersion;try{await e(c,l,h,t)}catch{try{l.abort()}catch{}}},Me(i)}function Me(n){return new Promise((e,t)=>{n.addEventListener("success",s=>{e(s.target.result)}),n.addEventListener("error",s=>{const i=new kn(s);t(i)})})}function Pi(n){return new Promise((e,t)=>{n.addEventListener("complete",()=>{e()}),n.addEventListener("abort",s=>{t(new rt)})})}function _e(n,e){return new Promise((t,s)=>{n.onerror=i=>{s(new kn(i))},n.onsuccess=i=>{const r=i.target.result;if(!r){t(!1);return}const o=e(r.value,r.key,r),c=o==null?void 0:o.done,l=o==null?void 0:o.jumpTo;c?t(!0):l?r.continue(l):r.continue()}}).catch(t=>{throw new Ot("iterateCursor failed",t)})}async function vh(n,e){const t=[];return await _e(n,s=>(t.push(s),{done:e(t)})),t}class io{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 Me(this._target.count(e))}get(e){return Me(this._target.get(e))}getKey(e){return this._target.supports("getKey")?Me(this._target.getKey(e)):Me(this._target.get(e)).then(t=>{if(t){let s=this._target.keyPath;return typeof s=="string"&&(s=[s]),s.reduce((i,r)=>i[r],t)}})}reduce(e,t,s){return this._reduce(e,t,s,"next")}reduceReverse(e,t,s){return this._reduce(e,t,s,"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 s=this._openCursor(e,t),i=[];return await _e(s,r=>(i.push(r),Lt)),i}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 s;return await _e(t,(i,r)=>(s=r,so)),s}async iterateValues(e,t){const s=this._target.openCursor(e,"next");await _e(s,(i,r,o)=>({done:t(i,r,o)}))}async iterateKeys(e,t){const s=this._target.openKeyCursor(e,"next");await _e(s,(i,r,o)=>({done:t(r,o)}))}async findExistingKeys(e,t,s){const i=(u,p)=>t?-this.idbFactory.cmp(u,p):this.idbFactory.cmp(u,p),r=e.slice().sort(i),o=r[0],c=r[r.length-1],l=t?"prev":"next",h=this._target.openKeyCursor(this.IDBKeyRange.bound(o,c),l);let a=0;await _e(h,(u,p,g)=>{for(;a=r.length?so:{done:!1,jumpTo:r[a]}})}_reduce(e,t,s,i){let r=s;const o=this._openCursor(e,i);return _e(o,c=>(r=t(r,c),Lt))}_selectLimit(e,t,s){return this._selectUntil(e,i=>i.length===t,s)}async _selectUntil(e,t,s){const i=this._openCursor(e,s),r=[];return await _e(i,o=>(r.push(o),{done:t(r,o)})),r}async _selectWhile(e,t,s){const i=this._openCursor(e,s),r=[];return await _e(i,o=>{const c=t(o);return c&&r.push(o),{done:!c}}),r}async iterateWhile(e,t){const s=this._openCursor(e,"next");await _e(s,i=>({done:!t(i)}))}async _find(e,t,s){const i=this._openCursor(e,s);let r;if(await _e(i,c=>{const l=t(c);return l&&(r=c),{done:l}}))return r}}const Mt=!1;function Ct(n,e,t){var r,o;const s=t==null?void 0:t.name,i=(o=(r=t==null?void 0:t.transaction)==null?void 0:r.db)==null?void 0:o.name;console.info(`${i}.${s}.${n}(${e.map(c=>JSON.stringify(c)).join(", ")})`)}class ro{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?(Mt&&Ct("openKeyCursor",[e,t],this._qt),this._qt.openKeyCursor(e,t)):(Mt&&Ct("openCursor",[e,t],this._qt),this.openCursor(e,t))}catch(s){throw new lt("openKeyCursor",this._qt,s,[e,t])}}openCursor(e,t){try{return Mt&&Ct("openCursor",[],this._qt),this._qt.openCursor(e,t)}catch(s){throw new lt("openCursor",this._qt,s,[e,t])}}put(e,t){try{return Mt&&Ct("put",[e,t],this._qt),this._qtStore.put(e,t)}catch(s){throw new lt("put",this._qt,s,[e,t])}}add(e,t){try{return Mt&&Ct("add",[e,t],this._qt),this._qtStore.add(e,t)}catch(s){throw new lt("add",this._qt,s,[e,t])}}get(e){try{return Mt&&Ct("get",[e],this._qt),this._qt.get(e)}catch(t){throw new lt("get",this._qt,t,[e])}}getKey(e){try{return Mt&&Ct("getKey",[e],this._qt),this._qt.getKey(e)}catch(t){throw new lt("getKey",this._qt,t,[e])}}delete(e){try{return Mt&&Ct("delete",[e],this._qt),this._qtStore.delete(e)}catch(t){throw new lt("delete",this._qt,t,[e])}}clear(){try{return Mt&&Ct("clear",[],this._qt),this._qtStore.clear()}catch(e){throw new lt("delete",this._qt,e,[])}}count(e){try{return this._qt.count(e)}catch(t){throw new lt("count",this._qt,t,[e])}}index(e){try{return this._qtStore.index(e)}catch(t){throw new lt("index",this._qt,t,[e])}}get indexNames(){return Array.from(this._qtStore.indexNames)}}class Ma extends io{constructor(e,t){super(new ro(e),t)}get _idbStore(){return this._target}index(e){return new io(new ro(this._idbStore.index(e)),this._transaction)}put(e,t){const s=this._idbStore.put(e);this._prepareErrorLog(s,t,"put",void 0,e)}add(e,t){const s=this._idbStore.add(e);this._prepareErrorLog(s,t,"add",void 0,e)}async tryAdd(e,t){try{return await Me(this._idbStore.add(e)),!0}catch(s){if(s instanceof kn)return t.log({l:"could not write",id:this._getKeys(e),e:s},t.level.Warn),s.preventTransactionAbort(),!1;throw s}}delete(e,t){const s=this._idbStore.delete(e);this._prepareErrorLog(s,t,"delete",e,void 0)}clear(e){const t=this._idbStore.clear();this._prepareErrorLog(t,e,"delete",void 0,void 0)}_prepareErrorLog(e,t,s,i,r){t&&t.ensureRefId(),Me(e).catch(o=>{let c;r?c=this._getKeys(r):i&&(c=[i]),this._transaction.addWriteError(o,t,s,c)})}_getKeys(e){const t=[],{keyPath:s}=this._idbStore;try{t.push(this._readKeyPath(e,s))}catch{console.warn("could not read keyPath",s)}for(const i of this._idbStore.indexNames)try{const r=this._idbStore.index(i);t.push(this._readKeyPath(e,r.keyPath))}catch{console.warn("could not read index",i)}return t}_readKeyPath(e,t){if(Array.isArray(t)){let s=e;for(const i of t)if(typeof s=="object")s=s[i];else break;return s}else return e[t]}}function bh(n){return JSON.stringify(Ca(n))}function Sh(n){return Ea(JSON.parse(n))}function Ca(n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if(n.byteLength)return{_type:n.constructor.name,value:Array.from(n)};let e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=Ca(n[t]));return e}else return n}function Ea(n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if(typeof n._type=="string")switch(n._type){case"Int8Array":return Int8Array.from(n.value);case"Uint8Array":return Uint8Array.from(n.value);case"Uint8ClampedArray":return Uint8ClampedArray.from(n.value);case"Int16Array":return Int16Array.from(n.value);case"Uint16Array":return Uint16Array.from(n.value);case"Int32Array":return Int32Array.from(n.value);case"Uint32Array":return Uint32Array.from(n.value);case"Float32Array":return Float32Array.from(n.value);case"Float64Array":return Float64Array.from(n.value);case"BigInt64Array":return BigInt64Array.from(n.value);case"BigUint64Array":return BigUint64Array.from(n.value);default:return n.value}let e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=Ea(n[t]));return e}else return n}function Ra(n){return`${n}.session.`}function kh(n,e){const t=[];for(let s=0;s(t.startsWith(Oe)&&this._writeKeyToLocalStorage(t,e.value),!1))}async tryRestoreE2EEIdentityFromLocalStorage(e){let t=!1;const s=this._localStorageKeyPrefix,i=s+Oe;for(let r=0;r(n[n.All=1]="All",n[n.Debug=2]="Debug",n[n.Detail=3]="Detail",n[n.Info=4]="Info",n[n.Warn=5]="Warn",n[n.Error=6]="Error",n[n.Fatal=7]="Fatal",n[n.Off=8]="Off",n))(Ge||{});class br{constructor(e){this._parentFilter=e}filter(e,t){return!(this._parentFilter&&!this._parentFilter.filter(e,t)||this._min!==void 0&&!Array.isArray(t)&&e.logLevels(t(this.item))).then(Sr,Sr),this.item}get level(){return Ge}}class Ch{constructor(e){this.logger=e}discard(){}wrap(e,t){return this.run(t)}run(e){return e(this)}log(e){return this}set(e){return this}runDetached(e,t){return new Promise(s=>s(t(this))).then(Sr,Sr),this}wrapDetached(e,t){return this.refDetached()}refDetached(){}ensureRefId(){}get level(){return Ge}get duration(){return 0}catch(e){return e}child(){return this}finish(){}forceFinish(){}serialize(){}}const Eh=new Mh;function tt(n,e,t){return`${n}|${vr(e)}|${vr(t)}`}function Rh(n){const[e,t,s]=n.split("|");return{roomId:e,eventKey:new pe(en(t),en(s))}}function Zi(n,e){return`${n}|${e}`}function oo(n){const[e,t]=n.split("|");return{roomId:e,eventId:t}}class er{constructor(e,t,s,i,r=!1,o=!1){this._IDBKeyRange=e,this._only=t,this._lower=s,this._upper=i,this._lowerOpen=r,this._upperOpen=o}asIDBKeyRange(e){try{if(this._only)return this._IDBKeyRange.only(tt(e,this._only.fragmentId,this._only.eventIndex));if(this._lower&&!this._upper)return this._IDBKeyRange.bound(tt(e,this._lower.fragmentId,this._lower.eventIndex),tt(e,this._lower.fragmentId,ce.maxStorageKey),this._lowerOpen,!1);if(!this._lower&&this._upper)return this._IDBKeyRange.bound(tt(e,this._upper.fragmentId,ce.minStorageKey),tt(e,this._upper.fragmentId,this._upper.eventIndex),!1,this._upperOpen);if(this._lower&&this._upper)return this._IDBKeyRange.bound(tt(e,this._lower.fragmentId,this._lower.eventIndex),tt(e,this._upper.fragmentId,this._upper.eventIndex),this._lowerOpen,this._upperOpen)}catch(t){throw new Ot("IDBKeyRange failed with data: "+JSON.stringify(this),t)}}}class Th{constructor(e){this._timelineStore=e}onlyRange(e){return new er(this._timelineStore.IDBKeyRange,e)}upperBoundRange(e,t=!1){return new er(this._timelineStore.IDBKeyRange,void 0,void 0,e,void 0,t)}lowerBoundRange(e,t=!1){return new er(this._timelineStore.IDBKeyRange,void 0,e,void 0,t)}boundRange(e,t,s=!1,i=!1){return new er(this._timelineStore.IDBKeyRange,void 0,e,t,s,i)}async lastEvents(e,t,s){const i=pe.maxKey;return i.fragmentId=t,this.eventsBefore(e,i,s)}async firstEvents(e,t,s){const i=pe.minKey;return i.fragmentId=t,this.eventsAfter(e,i,s)}eventsAfter(e,t,s){const i=this.lowerBoundRange(t,!0).asIDBKeyRange(e);return this._timelineStore.selectLimit(i,s)}async eventsBefore(e,t,s){const i=this.upperBoundRange(t,!0).asIDBKeyRange(e),r=await this._timelineStore.selectLimitReverse(i,s);return r.reverse(),r}async getEventKeysForIds(e,t){const s=this._timelineStore.index("byEventId"),i=t.map(o=>Zi(e,o)),r=new Map;return await s.findExistingKeys(i,!1,(o,c)=>{const{eventId:l}=oo(o),{eventKey:h}=Rh(c);return r.set(l,h),!1}),r}async findFirstOccurringEventId(e,t){const s=this._timelineStore.index("byEventId"),i=t.map(l=>Zi(e,l)),r=new Array(i.length);let o;function c(){for(let l=0;l{const a=i.indexOf(l);return r[a]=h,o=c(),!!o}),o&&oo(o).eventId}tryInsert(e,t){return e.key=tt(e.roomId,e.fragmentId,e.eventIndex),e.eventIdKey=Zi(e.roomId,e.event.event_id),this._timelineStore.tryAdd(e,t)}update(e){this._timelineStore.put(e)}get(e,t){return this._timelineStore.get(tt(e,t.fragmentId,t.eventIndex))}getByEventId(e,t){return this._timelineStore.index("byEventId").get(Zi(e,t))}removeAllForRoom(e){const t=tt(e,ce.minStorageKey,ce.minStorageKey),s=tt(e,ce.maxStorageKey,ce.maxStorageKey),i=this._timelineStore.IDBKeyRange.bound(t,s);this._timelineStore.delete(i)}}const de="\0",ae="\u{10FFFF}";function ht(n,e,t,s){return`${n}|${e}|${t}|${s}`}function ao(n){const[e,t,s,i]=n.split("|");return{roomId:e,targetEventId:t,relType:s,sourceEventId:i}}class Ah{constructor(e){this._store=e}add(e,t,s,i){this._store.add({key:ht(e,t,s,i)})}remove(e,t,s,i){this._store.delete(ht(e,t,s,i))}removeAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(ht(e,t,de,de),ht(e,t,ae,ae),!0,!0);this._store.delete(s)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(ht(e,de,de,de),ht(e,ae,ae,ae),!0,!0);this._store.delete(t)}async getForTargetAndType(e,t,s){const i=this._store.IDBKeyRange.bound(ht(e,t,s,de),ht(e,t,s,ae),!0,!0);return(await this._store.selectAll(i)).map(o=>ao(o.key))}async getAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(ht(e,t,de,de),ht(e,t,ae,ae),!0,!0);return(await this._store.selectAll(s)).map(r=>ao(r.key))}}function tr(n,e,t){return`${n}|${e}|${t}`}class xh{constructor(e){this._roomStateStore=e}get(e,t,s){const i=tr(e,t,s);return this._roomStateStore.get(i)}getAllForType(e,t){const s=this._roomStateStore.IDBKeyRange.bound(tr(e,t,""),tr(e,t,ae),!1,!0);return this._roomStateStore.selectAll(s)}set(e,t){const s=tr(e,t.type,t.state_key),i={roomId:e,event:t,key:s};this._roomStateStore.put(i)}removeAllForRoom(e){const t=this._roomStateStore.IDBKeyRange.bound(e,`${e}|${ae}`,!0,!0);this._roomStateStore.delete(t)}}function sr(n,e){return`${n}|${e}`}function Vh(n){const[e,t]=n.split("|");return{roomId:e,userId:t}}class Ta{constructor(e){this._roomMembersStore=e}get(e,t){return this._roomMembersStore.get(sr(e,t))}set(e){e.key=sr(e.roomId,e.userId),this._roomMembersStore.put(e)}getAll(e){const t=this._roomMembersStore.IDBKeyRange.lowerBound(sr(e,""));return this._roomMembersStore.selectWhile(t,s=>s.roomId===e)}async getAllUserIds(e){const t=[],s=this._roomMembersStore.IDBKeyRange.lowerBound(sr(e,""));return await this._roomMembersStore.iterateKeys(s,i=>{const r=Vh(i);return r.roomId===e?(t.push(r.userId),!1):!0}),t}removeAllForRoom(e){const t=this._roomMembersStore.IDBKeyRange.bound(e,`${e}|${ae}`,!0,!0);this._roomMembersStore.delete(t)}}function ir(n,e){return`${n}|${vr(e)}`}class Nh{constructor(e){this._store=e}_allRange(e){try{return this._store.IDBKeyRange.bound(ir(e,ce.minStorageKey),ir(e,ce.maxStorageKey))}catch(t){throw new Ot(`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=ir(e.roomId,e.id),this._store.add(e)}update(e){this._store.put(e)}get(e,t){return this._store.get(ir(e,t))}removeAllForRoom(e){this._store.delete(this._allRange(e))}}function ps(n,e){return`${n}|${vr(e)}`}function Dh(n){const[e,t]=n.split("|"),s=en(t);return{roomId:e,queueIndex:s}}class Uh{constructor(e){this._eventStore=e}async getMaxQueueIndex(e){const t=this._eventStore.IDBKeyRange.bound(ps(e,ce.minStorageKey),ps(e,ce.maxStorageKey),!1,!1),s=await this._eventStore.findMaxKey(t);if(s)return Dh(s).queueIndex}remove(e,t){const s=this._eventStore.IDBKeyRange.only(ps(e,t));this._eventStore.delete(s)}async exists(e,t){const s=this._eventStore.IDBKeyRange.only(ps(e,t));return!!await this._eventStore.getKey(s)}add(e){e.key=ps(e.roomId,e.queueIndex),this._eventStore.add(e)}update(e){this._eventStore.put(e)}getAll(){return this._eventStore.selectAll()}removeAllForRoom(e){const t=ps(e,ce.minStorageKey),s=ps(e,ce.maxStorageKey),i=this._eventStore.IDBKeyRange.bound(t,s);this._eventStore.delete(i)}}class Oh{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 gs(n,e){return`${n}|${e}`}function Ph(n){const[e,t]=n.split("|");return{userId:e,deviceId:t}}class Fh{constructor(e){this._store=e}async getAllForUserId(e){const t=this._store.IDBKeyRange.lowerBound(gs(e,de));return(await this._store.selectWhile(t,i=>i.deviceKey.user_id===e)).map(i=>i.deviceKey)}async getAllDeviceIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(gs(e,de));return await this._store.iterateKeys(s,i=>{const r=Ph(i);return r.userId===e?(t.push(r.deviceId),!1):!0}),t}async get(e,t){var s;return(s=await this._store.get(gs(e,t)))==null?void 0:s.deviceKey}set(e){this._store.put({key:gs(e.user_id,e.device_id),curve25519Key:_t(e),deviceKey:e})}async getByCurve25519Key(e){const t=await this._store.index("byCurve25519Key").get(e);return t==null?void 0:t.deviceKey}remove(e,t){this._store.delete(gs(e,t))}removeAllForUser(e){const t=this._store.IDBKeyRange.bound(gs(e,de),gs(e,ae),!0,!0);this._store.delete(t)}}function yi(n,e){return`${n}|${e}`}class Lh{constructor(e){this._store=e}async get(e,t){var s;return(s=await this._store.get(yi(e,t)))==null?void 0:s.crossSigningKey}set(e){this._store.put({key:yi(e.user_id,e.usage[0]),crossSigningKey:e})}remove(e,t){this._store.delete(yi(e,t))}removeAllForUser(e){const t=this._store.IDBKeyRange.bound(yi(e,de),yi(e,ae),!0,!0);this._store.delete(t)}}function wi(n,e){return`${n}|${e}`}function Kh(n){const[e,t]=n.split("|");return{senderKey:e,sessionId:t}}class Bh{constructor(e){this._store=e}async getSessionIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(wi(e,""));return await this._store.iterateKeys(s,i=>{const r=Kh(i);return r.senderKey===e?(t.push(r.sessionId),!1):!0}),t}getAll(e){const t=this._store.IDBKeyRange.lowerBound(wi(e,""));return this._store.selectWhile(t,s=>s.senderKey===e)}get(e,t){return this._store.get(wi(e,t))}set(e){e.key=wi(e.senderKey,e.sessionId),this._store.put(e)}remove(e,t){this._store.delete(wi(e,t))}}var Vr=(n=>(n[n.NotBackedUp=0]="NotBackedUp",n[n.BackedUp=1]="BackedUp",n))(Vr||{}),Hi=(n=>(n[n.DeviceMessage=1]="DeviceMessage",n[n.Backup=2]="Backup",n[n.Outbound=3]="Outbound",n))(Hi||{});function qs(n,e,t){return`${n}|${e}|${t}`}class $h{constructor(e){this._store=e}async has(e,t,s){const i=qs(e,t,s),r=await this._store.getKey(i);return i===r}get(e,t,s){return this._store.get(qs(e,t,s))}set(e){const t=e;t.key=qs(e.roomId,e.senderKey,e.sessionId),this._store.put(t)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(qs(e,de,de),qs(e,ae,ae));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,s){const i=await this._store.get(qs(e,t,s));i&&(i.backup=1,this._store.put(i))}async markAllAsNotBackedUp(){const e=this._store.IDBKeyRange.only(1);let t=0;return await this._store.index("byBackup").iterateValues(e,(s,i,r)=>(s.backup=0,r.update(s),t+=1,!1)),t}}class jh{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 rr(n,e,t){return`${n}|${e}|${t}`}class qh{constructor(e){this._store=e}get(e,t,s){return this._store.get(rr(e,t,s))}set(e,t,s,i){i.key=rr(e,t,s),this._store.put(i)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(rr(e,de,de),rr(e,ae,ae));this._store.delete(t)}}function Ci(n,e){return`${n}|${e}`}class Hh{constructor(e){this._store=e}getAll(){return this._store.selectAll()}async getAllByTypeAndScope(e,t){const s=Ci(t,e),i=[];return await this._store.index("byScopeAndType").iterateWhile(s,r=>r.scopeTypeKey!==s?!1:(i.push(r),!0)),i}add(e){e.scopeTypeKey=Ci(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(Ci(e,de),Ci(e,ae));await this._store.index("byScopeAndType").iterateValues(t,(i,r,o)=>(o.delete(),!0))}}class Wh{constructor(e){this._store=e}async get(e){return await this._store.get(e)}set(e){this._store.put(e)}async getAll(){return await this._store.selectAll()}}function Hs(n,e,t){return`${n}|${e}|${t}`}function co(n){const[e,t,s]=n.key.split("|");return{intent:e,roomId:t,callId:s,timestamp:n.timestamp}}class zh{constructor(e){this._callStore=e}async getByIntent(e){const t=this._callStore.IDBKeyRange.bound(Hs(e,de,de),Hs(e,ae,ae),!0,!0);return(await this._callStore.selectAll(t)).map(i=>co(i))}async getByIntentAndRoom(e,t){const s=this._callStore.IDBKeyRange.bound(Hs(e,t,de),Hs(e,t,ae),!0,!0);return(await this._callStore.selectAll(s)).map(r=>co(r))}add(e){const t={key:Hs(e.intent,e.roomId,e.callId),timestamp:e.timestamp};this._callStore.add(t)}remove(e,t,s){this._callStore.delete(Hs(e,t,s))}}class Gh{constructor(e){this._store=e}get(e){return this._store.get(e)}set(e,t){t.key=e,this._store.put(t)}remove(e){this._store.delete(e)}deleteAllSecrets(){this._store.clear()}}class Yh{constructor(e,t,s,i){this.error=e,this.refItem=t,this.operationName=s,this.keys=i}}class lo{constructor(e,t,s){this._txn=e,this._allowedStoreNames=t,this._stores={},this._storage=s,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 Ot(`Invalid store for transaction: ${e}, only ${this._allowedStoreNames.join(", ")} are allowed.`);return new Ma(this._txn.objectStore(e),this)}_store(e,t){if(!this._stores[e]){const s=this._idbStore(e);this._stores[e]=t(s)}return this._stores[e]}get session(){return this._store(J.session,e=>new Mn(e,this._storage.localStorage))}get roomSummary(){return this._store(J.roomSummary,e=>new no(e))}get archivedRoomSummary(){return this._store(J.archivedRoomSummary,e=>new no(e))}get invites(){return this._store(J.invites,e=>new Ih(e))}get timelineFragments(){return this._store(J.timelineFragments,e=>new Nh(e))}get timelineEvents(){return this._store(J.timelineEvents,e=>new Th(e))}get timelineRelations(){return this._store(J.timelineRelations,e=>new Ah(e))}get roomState(){return this._store(J.roomState,e=>new xh(e))}get roomMembers(){return this._store(J.roomMembers,e=>new Ta(e))}get pendingEvents(){return this._store(J.pendingEvents,e=>new Uh(e))}get userIdentities(){return this._store(J.userIdentities,e=>new Oh(e))}get deviceKeys(){return this._store(J.deviceKeys,e=>new Fh(e))}get crossSigningKeys(){return this._store(J.crossSigningKeys,e=>new Lh(e))}get olmSessions(){return this._store(J.olmSessions,e=>new Bh(e))}get inboundGroupSessions(){return this._store(J.inboundGroupSessions,e=>new $h(e))}get outboundGroupSessions(){return this._store(J.outboundGroupSessions,e=>new jh(e))}get groupSessionDecryptions(){return this._store(J.groupSessionDecryptions,e=>new qh(e))}get operations(){return this._store(J.operations,e=>new Hh(e))}get accountData(){return this._store(J.accountData,e=>new Wh(e))}get calls(){return this._store(J.calls,e=>new zh(e))}get sharedSecrets(){return this._store(J.sharedSecrets,e=>new Gh(e))}async complete(e){try{await Pi(this._txn)}catch(t){throw this._writeErrors.length?(this._logWriteErrors(e),this._writeErrors[0].error):t}}getCause(e){return e instanceof Ot&&e.errcode==="AbortError"&&this._writeErrors.length?this._writeErrors[0].error:e}abort(e){try{this._txn.abort()}catch{e==null||e.set("couldNotAbortTxn",!0)}this._writeErrors.length&&this._logWriteErrors(e)}addWriteError(e,t,s,i){(e.errcode!=="AbortError"||this._writeErrors.length===0)&&this._writeErrors.push(new Yh(e,t,s,i))}_logWriteErrors(e){const t=i=>{e||i.set("allowedStoreNames",this._allowedStoreNames);for(const r of this._writeErrors)i.wrap({l:r.operationName,id:r.keys},o=>{r.refItem&&o.refDetached(r.refItem),o.catch(r.error)})},s=`${this._writeErrors.length} storage write operation(s) failed`;e?e.wrap(s,t):this.logger.run(s,t)}}const ho="782rh281re38-boguskey";class Jh{constructor(e,t,s,i,r,o){this._db=e,this.idbFactory=t,this.IDBKeyRange=s,this._hasWebkitEarlyCloseTxnBug=i,this.storeNames=J,this.localStorage=r,this.logger=o}_validateStoreNames(e){const t=e.findIndex(s=>!Oi.includes(s));if(t!==-1)throw new Ot(`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 Me(t.objectStore(e[0]).get(ho)),new lo(t,e,this)}catch(t){throw new Ot("readTxn failed",t)}}async readWriteTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readwrite");return this._hasWebkitEarlyCloseTxnBug&&await Me(t.objectStore(e[0]).get(ho)),new lo(t,e,this)}catch(t){throw new Ot("readWriteTxn failed",t)}}close(){this._db.close()}get databaseName(){return this._db.name}}async function Qh(n){const e=n.transaction(Oi,"readonly"),t={};return await Promise.all(Oi.map(async s=>{const i=t[s]=[],r=e.objectStore(s);await _e(r.openCursor(),o=>(i.push(o),Lt))})),t}async function Xh(n,e){const t=n.transaction(Oi,"readwrite");for(const s of Oi){const i=t.objectStore(s);for(const r of e[s])i.add(r)}await Pi(t)}function Zh(n,e,t,s,i){let r=!1;if(t instanceof Uint8Array){const l=new n.PkSigning;i=l.init_with_seed(t),t=l,r=!0}const o=e.signatures||{};delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{const l=o[s]||{};return o[s]=l,l["ed25519:"+i]=t.sign(qi.stringify(e))}finally{e.signatures=o,c&&(e.unsigned=c),r&&t.free()}}class qt{constructor(e){this.options=e,this.ourUserId=e.ourUserId,this.ourUserDeviceId=e.ourUserDeviceId,this.otherUserId=e.otherUserId,this.log=e.log,this.olmSAS=e.olmSas,this.olmUtil=e.olmUtil,this.channel=e.channel,this.e2eeAccount=e.e2eeAccount,this.deviceTracker=e.deviceTracker,this.hsApi=e.hsApi,this.eventEmitter=e.eventEmitter}setNextStage(e){this._nextStage=e}get nextStage(){return this._nextStage}get otherUserDeviceId(){const e=this.channel.otherUserDeviceId;if(!e)throw new Error("Accessed otherUserDeviceId before it was set in channel!");return e}}var P=(n=>(n.Request="m.key.verification.request",n.Ready="m.key.verification.ready",n.Start="m.key.verification.start",n.Accept="m.key.verification.accept",n.Key="m.key.verification.key",n.Cancel="m.key.verification.cancel",n.Mac="m.key.verification.mac",n.Done="m.key.verification.done",n))(P||{}),A=(n=>(n.UserCancelled="m.user",n.TimedOut="m.timeout",n.UnknownTransaction="m.unknown_transaction",n.UnknownMethod="m.unknown_method",n.UnexpectedMessage="m.unexpected_message",n.KeyMismatch="m.key_mismatch",n.UserMismatch="m.user_mismatch",n.InvalidMessage="m.invalid_message",n.OtherDeviceAccepted="m.accepted",n.MismatchedCommitment="m.mismatched_commitment",n.MismatchedSAS="m.mismatched_sas",n))(A||{});const Aa=["curve25519-hkdf-sha256","curve25519"],xa=["sha256"],Va=["hkdf-hmac-sha256.v2","org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],Na=["decimal","emoji"],ed=new Set(Na),td=[["\u{1F436}","dog"],["\u{1F431}","cat"],["\u{1F981}","lion"],["\u{1F40E}","horse"],["\u{1F984}","unicorn"],["\u{1F437}","pig"],["\u{1F418}","elephant"],["\u{1F430}","rabbit"],["\u{1F43C}","panda"],["\u{1F413}","rooster"],["\u{1F427}","penguin"],["\u{1F422}","turtle"],["\u{1F41F}","fish"],["\u{1F419}","octopus"],["\u{1F98B}","butterfly"],["\u{1F337}","flower"],["\u{1F333}","tree"],["\u{1F335}","cactus"],["\u{1F344}","mushroom"],["\u{1F30F}","globe"],["\u{1F319}","moon"],["\u2601\uFE0F","cloud"],["\u{1F525}","fire"],["\u{1F34C}","banana"],["\u{1F34E}","apple"],["\u{1F353}","strawberry"],["\u{1F33D}","corn"],["\u{1F355}","pizza"],["\u{1F382}","cake"],["\u2764\uFE0F","heart"],["\u{1F642}","smiley"],["\u{1F916}","robot"],["\u{1F3A9}","hat"],["\u{1F453}","glasses"],["\u{1F527}","spanner"],["\u{1F385}","santa"],["\u{1F44D}","thumbs up"],["\u2602\uFE0F","umbrella"],["\u231B","hourglass"],["\u23F0","clock"],["\u{1F381}","gift"],["\u{1F4A1}","light bulb"],["\u{1F4D5}","book"],["\u270F\uFE0F","pencil"],["\u{1F4CE}","paperclip"],["\u2702\uFE0F","scissors"],["\u{1F512}","lock"],["\u{1F511}","key"],["\u{1F528}","hammer"],["\u260E\uFE0F","telephone"],["\u{1F3C1}","flag"],["\u{1F682}","train"],["\u{1F6B2}","bicycle"],["\u2708\uFE0F","aeroplane"],["\u{1F680}","rocket"],["\u{1F3C6}","trophy"],["\u26BD","ball"],["\u{1F3B8}","guitar"],["\u{1F3BA}","trumpet"],["\u{1F514}","bell"],["\u2693\uFE0F","anchor"],["\u{1F3A7}","headphones"],["\u{1F4C1}","folder"],["\u{1F4CC}","pin"]];function sd(n){return[n[0]>>2,(n[0]&3)<<4|n[1]>>4,(n[1]&15)<<2|n[2]>>6,n[2]&63,n[3]>>2,(n[3]&3)<<4|n[4]>>4,(n[4]&15)<<2|n[5]>>6].map(t=>td[t])}const id={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hkdf-hmac-sha256.v2":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function Da(n,e){return function(t,s,i){return i.wrap({l:"calculate MAC",method:e},()=>n[id[e]](t,s))}}class rd extends qt{async completeStage(){await this.log.wrap("SendDoneStage.completeStage",async e=>{await this.channel.send(P.Done,{},e),await this.channel.waitForEvent(P.Done),this.eventEmitter.emit("VerificationCompleted",this.otherUserDeviceId)})}}class nd extends qt{async completeStage(){await this.log.wrap("VerifyMacStage.completeStage",async e=>{const s=this.channel.acceptMessage.content.message_authentication_code,i=Da(this.olmSAS,s);await this.checkMAC(i,e),this.setNextStage(new rd(this.options))})}async checkMAC(e,t){const{content:s}=this.channel.getReceivedMessage(P.Mac),i="MATRIX_KEY_VERIFICATION_MAC"+this.otherUserId+this.otherUserDeviceId+this.ourUserId+this.ourUserDeviceId+this.channel.id,r=e(Object.keys(s.mac).sort().join(","),i+"KEY_IDS",t);if(s.keys!==r){t.log({l:"MAC verification failed for keys field",keys:s.keys,calculated:r}),this.channel.cancelVerification(A.KeyMismatch);return}await this.verifyKeys(s.mac,(o,c,l)=>{const h=e(c,i+o,t),a=l===h;return a||(t.log({l:"Mac verification failed for key",keyMac:l,calculatedMAC:h,keyId:o,key:c}),this.channel.cancelVerification(A.KeyMismatch)),a},t)}async verifyKeys(e,t,s){const i=this.otherUserId;for(const[r,o]of Object.entries(e)){const c=r.split(":",2)[1],l=await this.deviceTracker.deviceForId(i,c,this.hsApi,s);if(l){if(!t(r,ks(l),o))throw new Error(`MAC verification failed for key ${o}`)}else{const h=await this.deviceTracker.getCrossSigningKeyForUser(i,Et.Master,this.hsApi,s);if(!h)throw s.log({l:"Fetching msk failed",userId:i}),new Error("Fetching MSK for user failed!");const a=Qs(h);if(!(a&&t(r,a,o)))throw new Error(`MAC verification failed for key ${o}`)}}}}class od extends qt{async completeStage(){await this.log.wrap("SendMacStage.completeStage",async e=>{const s=this.channel.acceptMessage.content.message_authentication_code,i=Da(this.olmSAS,s);await this.sendMAC(i,e),await this.channel.waitForEvent(P.Mac),this.setNextStage(new nd(this.options))})}async sendMAC(e,t){const s={},i=[],r="MATRIX_KEY_VERIFICATION_MAC"+this.ourUserId+this.ourUserDeviceId+this.otherUserId+this.otherUserDeviceId+this.channel.id,o=`ed25519:${this.ourUserDeviceId}`,c=this.e2eeAccount.getUnsignedDeviceKey();s[o]=e(c.keys[o],r+o,t),i.push(o);const l=await this.deviceTracker.getCrossSigningKeyForUser(this.ourUserId,Et.Master,this.hsApi,t);if(!l)throw t.log({l:"Fetching msk failed",userId:this.ourUserId}),new Error("Fetching MSK for user failed!");const h=Qs(l);if(h){const u=`ed25519:${h}`;s[u]=e(h,r+u,t),i.push(u)}const a=e(i.sort().join(","),r+"KEY_IDS",t);await this.channel.send(P.Mac,{mac:s,keys:a},t)}}class pt extends Error{get name(){return"VerificationCancelledError"}get message(){return"Verification is cancelled!"}}const ad={"curve25519-hkdf-sha256":function(n,e,t){const s=`${n.our.userId}|${n.our.deviceId}|${n.our.publicKey}|`,i=`${n.their.userId}|${n.their.deviceId}|${n.their.publicKey}|`,r="MATRIX_KEY_VERIFICATION_SAS|"+(n.initiatedByMe?s+i:i+s)+n.id;return e.generate_bytes(r,t)},curve25519:function(n,e,t){const s=`${n.our.userId}${n.our.deviceId}`,i=`${n.their.userId}${n.their.deviceId}`,r="MATRIX_KEY_VERIFICATION_SAS"+(n.initiatedByMe?s+i:i+s)+n.id;return e.generate_bytes(r,t)}};class cd extends qt{async completeStage(){await this.log.wrap("CalculateSASStage.completeStage",async e=>{if(this.channel.initiatedByUs&&!await this.verifyHashCommitment(e))return;const t=new Promise((r,o)=>{this.resolve=r,this.reject=o});this.olmSAS.set_their_key(this.theirKey);const s=this.generateSASBytes();this.emoji=sd(Array.from(s)),this.eventEmitter.emit("EmojiGenerated",this);const i=this.channel.waitForEvent(P.Cancel);await Promise.race([t,i]),this.setNextStage(new od(this.options))})}async verifyHashCommitment(e){return await e.wrap("CalculateSASStage.verifyHashCommitment",async()=>{const t=this.channel.getReceivedMessage(P.Accept).content,i=this.channel.getReceivedMessage(P.Key).content.key+qi.stringify(this.channel.startMessage.content),r=t.commitment,o=this.olmUtil.sha256(i);return o!==r?(e.log({l:"Commitment mismatched!",received:r,calculated:o}),await this.channel.cancelVerification(A.MismatchedCommitment),!1):!0})}generateSASBytes(){const e=this.channel.acceptMessage.content.key_agreement_protocol,t=this.otherUserDeviceId;return ad[e]({our:{userId:this.ourUserId,deviceId:this.ourUserDeviceId,publicKey:this.olmSAS.get_pubkey()},their:{userId:this.otherUserId,deviceId:t,publicKey:this.theirKey},id:this.channel.id,initiatedByMe:this.channel.initiatedByUs},this.olmSAS,6)}async setEmojiMatch(e){e?this.resolve():(await this.channel.cancelVerification(A.MismatchedSAS),this.reject(new pt))}get theirKey(){const{content:e}=this.channel.getReceivedMessage(P.Key);return e.key}}class Ua extends qt{async completeStage(){await this.log.wrap("SendKeyStage.completeStage",async e=>{const t=this.olmSAS.get_pubkey();await this.channel.send(P.Key,{key:t},e),await this.channel.waitForEvent(P.Key),this.setNextStage(new cd(this.options))})}}function nr(n,e){return Array.isArray(n)?n.filter(t=>e.has(t)):[]}class ld extends qt{async completeStage(){await this.log.wrap("SendAcceptVerificationStage.completeStage",async e=>{const{content:t}=this.channel.startMessage,s=nr(Aa,new Set(t.key_agreement_protocols))[0],i=nr(xa,new Set(t.hashes))[0],r=nr(Va,new Set(t.message_authentication_codes))[0],o=nr(t.short_authentication_string,ed);if(!s||!i||!r||!o.length){await this.channel.cancelVerification(A.UnknownMethod);return}const l=this.olmSAS.get_pubkey()+qi.stringify(t),h={key_agreement_protocol:s,hash:i,message_authentication_code:r,short_authentication_string:o,commitment:this.olmUtil.sha256(l)};await this.channel.send(P.Accept,h,e),await this.channel.waitForEvent(P.Key),this.setNextStage(new Ua(this.options))})}}class Cn extends qt{constructor(){super(...arguments),this.allowSelection=!0}async completeStage(){await this.log.wrap("SelectVerificationMethodStage.completeStage",async e=>{await this.findDeviceName(e),this.eventEmitter.emit("SelectVerificationStage",this);const t=this.channel.waitForEvent(P.Start),s=this.channel.waitForEvent(P.Accept),{content:i}=await Promise.race([t,s]);i.method?(this.allowSelection=!1,this.hasSentStartMessage?(await this.hasSentStartMessage,await this.resolveStartConflict(e)):this.channel.setStartMessage(this.channel.getReceivedMessage(P.Start))):this.channel.setStartMessage(this.channel.getSentMessage(P.Start)),this.channel.initiatedByUs?(await s,this.setNextStage(new Ua(this.options))):this.setNextStage(new ld(this.options))})}async resolveStartConflict(e){await e.wrap("resolveStartConflict",async()=>{const t=this.channel.getReceivedMessage(P.Start),s=this.channel.getSentMessage(P.Start);if(t.content.method!==s.content.method){e.log({l:"Methods don't match for the start messages",received:t.content.method,sent:s.content.method}),await this.channel.cancelVerification(A.UnexpectedMessage);return}const i=this.ourUserId===this.otherUserId?this.ourUserDeviceId:this.ourUserId,r=this.ourUserId===this.otherUserId?this.otherUserDeviceId:this.otherUserId,o=i{var s;const t=await this.options.deviceTracker.deviceForId(this.otherUserId,this.otherUserDeviceId,this.options.hsApi,e);if(!t)throw e.log({l:"Cannot find device",userId:this.otherUserId,deviceId:this.otherUserDeviceId}),new Error("Cannot find device");this.otherDeviceName=(s=t.unsigned.device_display_name)!=null?s:t.device_id})}async selectEmojiMethod(e){if(!this.allowSelection)return;const t=new As;this.hasSentStartMessage=t.promise;const s={method:"m.sas.v1",from_device:this.ourUserDeviceId,key_agreement_protocols:Aa,hashes:xa,message_authentication_codes:Va,short_authentication_string:Na};await this.channel.send(P.Start,s,e),t.resolve()}}class hd extends qt{async completeStage(){await this.log.wrap("SendRequestVerificationStage.completeStage",async e=>{const t={from_device:this.ourUserDeviceId,methods:["m.sas.v1"]};await this.channel.send(P.Request,t,e),this.setNextStage(new Cn(this.options)),await this.channel.waitForEvent(P.Ready)})}}class dd extends qt{async completeStage(){await this.log.wrap("SendReadyStage.completeStage",async e=>{const t={from_device:this.ourUserDeviceId,methods:["m.sas.v1"]};await this.channel.send(P.Ready,t,e),this.setNextStage(new Cn(this.options))})}}var ud={exports:{}},md={},_d=Object.freeze(Object.defineProperty({__proto__:null,default:md},Symbol.toStringTag,{value:"Module"})),or=_a(_d);(function(n,e){// @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt Apache-2.0 var t=function(){var s={},i,r,o=(()=>{var l=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(l=l||__filename),function(h){h=h||{};var a;a||(a=typeof h!="undefined"?h:{});var u,p;a.ready=new Promise(function(d,m){u=d,p=m});var g;if(typeof window!="undefined")g=function(d){window.crypto.getRandomValues(d)};else if(n.exports){var f=or;g=function(d){var m=f.randomBytes(d.length);d.set(m)}}else throw Error("Cannot find global to attach library to");if(typeof OLM_OPTIONS!="undefined")for(var v in OLM_OPTIONS)OLM_OPTIONS.hasOwnProperty(v)&&(a[v]=OLM_OPTIONS[v]);a.onRuntimeInitialized=function(){le=a._olm_error(),s.PRIVATE_KEY_LENGTH=a._olm_pk_private_key_length(),i&&i()},a.onAbort=function(d){r&&r(d)};var M=Object.assign({},a),R=typeof window=="object",N=typeof importScripts=="function",F=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T="",D,B,G,$e,Ns,di;F?(T=N?or.dirname(T)+"/":__dirname+"/",di=()=>{Ns||($e=or,Ns=or)},D=function(d,m){return di(),d=Ns.normalize(d),$e.readFileSync(d,m?void 0:"utf8")},G=d=>(d=D(d,!0),d.buffer||(d=new Uint8Array(d)),d),B=(d,m,_)=>{di(),d=Ns.normalize(d),$e.readFile(d,function(w,k){w?_(w):m(k.buffer)})},1{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.send(null),m.responseText},N&&(G=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),B=(d,m,_)=>{var w=new XMLHttpRequest;w.open("GET",d,!0),w.responseType="arraybuffer",w.onload=()=>{w.status==200||w.status==0&&w.response?m(w.response):_()},w.onerror=_,w.send(null)}),a.print||console.log.bind(console);var as=a.printErr||console.warn.bind(console);Object.assign(a,M),M=null;var cs;a.wasmBinary&&(cs=a.wasmBinary),a.noExitRuntime,typeof WebAssembly!="object"&&je("no native wasm support detected");var Ds,Ue=!1,Us=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function U(d,m){if(d){var _=re,w=d+m;for(m=d;_[m]&&!(m>=w);)++m;if(16k?w+=String.fromCharCode(k):(k-=65536,w+=String.fromCharCode(55296|k>>10,56320|k&1023))}}else w+=String.fromCharCode(k)}d=w}}else d="";return d}function zi(d,m,_,w){if(!(0=z){var Se=d.charCodeAt(++V);z=65536+((z&1023)<<10)|Se&1023}if(127>=z){if(_>=w)break;m[_++]=z}else{if(2047>=z){if(_+1>=w)break;m[_++]=192|z>>6}else{if(65535>=z){if(_+2>=w)break;m[_++]=224|z>>12}else{if(_+3>=w)break;m[_++]=240|z>>18,m[_++]=128|z>>12&63}m[_++]=128|z>>6&63}m[_++]=128|z&63}}return m[_]=0,_-k}function Ht(d,m,_){return zi(d,re,m,_)}function Wt(d){for(var m=0,_=0;_=w?m++:2047>=w?m+=2:55296<=w&&57343>=w?(m+=4,++_):m+=3}return m}var ui,Je,re,Os,ie,Ps,ls,hs;function mi(){var d=Ds.buffer;ui=d,a.HEAP8=Je=new Int8Array(d),a.HEAP16=Os=new Int16Array(d),a.HEAP32=ie=new Int32Array(d),a.HEAPU8=re=new Uint8Array(d),a.HEAPU16=new Uint16Array(d),a.HEAPU32=Ps=new Uint32Array(d),a.HEAPF32=ls=new Float32Array(d),a.HEAPF64=hs=new Float64Array(d)}var Fs=[],_i=[],vt=[];function zt(){var d=a.preRun.shift();Fs.unshift(d)}var Qe=0,bt=null;function je(d){throw a.onAbort&&a.onAbort(d),d="Aborted("+d+")",as(d),Ue=!0,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),p(d),d}function ds(){return we.startsWith("data:application/octet-stream;base64,")}var we;if(we="olm.wasm",!ds()){var us=we;we=a.locateFile?a.locateFile(us,T):T+us}function pi(){var d=we;try{if(d==we&&cs)return new Uint8Array(cs);if(G)return G(d);throw"both async and sync fetching of the wasm failed"}catch(m){je(m)}}function gi(){if(!cs&&(R||N)){if(typeof fetch=="function"&&!we.startsWith("file://"))return fetch(we,{credentials:"same-origin"}).then(function(d){if(!d.ok)throw"failed to load wasm binary file at '"+we+"'";return d.arrayBuffer()}).catch(function(){return pi()});if(B)return new Promise(function(d,m){B(we,function(_){d(new Uint8Array(_))},m)})}return Promise.resolve().then(function(){return pi()})}var St;function at(d){for(;0>0];case"i8":return Je[d>>0];case"i16":return Os[d>>1];case"i32":return ie[d>>2];case"i64":return ie[d>>2];case"float":return ls[d>>2];case"double":return hs[d>>3];case"*":return Ps[d>>2];default:je("invalid type for getValue: "+m)}return null}function Xe(d){var m="i8";switch(m.endsWith("*")&&(m="*"),m){case"i1":Je[d>>0]=0;break;case"i8":Je[d>>0]=0;break;case"i16":Os[d>>1]=0;break;case"i32":ie[d>>2]=0;break;case"i64":St=[0,0],ie[d>>2]=St[0],ie[d+4>>2]=St[1];break;case"float":ls[d>>2]=0;break;case"double":hs[d>>3]=0;break;case"*":Ps[d>>2]=0;break;default:je("invalid type for setValue: "+m)}}function Gt(d,m,_){for(var w=0;w>0]=d.charCodeAt(w);_||(Je[m>>0]=0)}function Ks(d,m,_){return _=Array(0<_?_:Wt(d)+1),d=zi(d,_,0,_.length),m&&(_.length=d),_}var Gi={b:function(d,m,_){re.copyWithin(d,m,m+_)},a:function(d){var m=re.length;if(d>>>=0,2147483648=_;_*=2){var w=m*(1+.2/_);w=Math.min(w,d+100663296);var k=Math;w=Math.max(d,w),k=k.min.call(k,2147483648,w+(65536-w%65536)%65536);e:{try{Ds.grow(k-ui.byteLength+65535>>>16),mi();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}};(function(){function d(k){a.asm=k.exports,Ds=a.asm.c,mi(),_i.unshift(a.asm.d),Qe--,a.monitorRunDependencies&&a.monitorRunDependencies(Qe),Qe==0&&bt&&(k=bt,bt=null,k())}function m(k){d(k.instance)}function _(k){return gi().then(function(V){return WebAssembly.instantiate(V,w)}).then(function(V){return V}).then(k,function(V){as("failed to asynchronously prepare wasm: "+V),je(V)})}var w={a:Gi};if(Qe++,a.monitorRunDependencies&&a.monitorRunDependencies(Qe),a.instantiateWasm)try{return a.instantiateWasm(w,d)}catch(k){return as("Module.instantiateWasm callback failed with error: "+k),!1}return function(){return cs||typeof WebAssembly.instantiateStreaming!="function"||ds()||we.startsWith("file://")||F||typeof fetch!="function"?_(m):fetch(we,{credentials:"same-origin"}).then(function(k){return WebAssembly.instantiateStreaming(k,w).then(m,function(V){return as("wasm streaming compile failed: "+V),as("falling back to ArrayBuffer instantiation"),_(m)})})}().catch(p),{}})(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.d).apply(null,arguments)},a._olm_get_library_version=function(){return(a._olm_get_library_version=a.asm.f).apply(null,arguments)},a._olm_error=function(){return(a._olm_error=a.asm.g).apply(null,arguments)},a._olm_account_last_error=function(){return(a._olm_account_last_error=a.asm.h).apply(null,arguments)},a.__olm_error_to_string=function(){return(a.__olm_error_to_string=a.asm.i).apply(null,arguments)},a._olm_account_last_error_code=function(){return(a._olm_account_last_error_code=a.asm.j).apply(null,arguments)},a._olm_session_last_error=function(){return(a._olm_session_last_error=a.asm.k).apply(null,arguments)},a._olm_session_last_error_code=function(){return(a._olm_session_last_error_code=a.asm.l).apply(null,arguments)},a._olm_utility_last_error=function(){return(a._olm_utility_last_error=a.asm.m).apply(null,arguments)},a._olm_utility_last_error_code=function(){return(a._olm_utility_last_error_code=a.asm.n).apply(null,arguments)},a._olm_account_size=function(){return(a._olm_account_size=a.asm.o).apply(null,arguments)},a._olm_session_size=function(){return(a._olm_session_size=a.asm.p).apply(null,arguments)},a._olm_utility_size=function(){return(a._olm_utility_size=a.asm.q).apply(null,arguments)},a._olm_account=function(){return(a._olm_account=a.asm.r).apply(null,arguments)},a._olm_session=function(){return(a._olm_session=a.asm.s).apply(null,arguments)},a._olm_utility=function(){return(a._olm_utility=a.asm.t).apply(null,arguments)},a._olm_clear_account=function(){return(a._olm_clear_account=a.asm.u).apply(null,arguments)},a._olm_clear_session=function(){return(a._olm_clear_session=a.asm.v).apply(null,arguments)},a._olm_clear_utility=function(){return(a._olm_clear_utility=a.asm.w).apply(null,arguments)},a._olm_pickle_account_length=function(){return(a._olm_pickle_account_length=a.asm.x).apply(null,arguments)},a._olm_pickle_session_length=function(){return(a._olm_pickle_session_length=a.asm.y).apply(null,arguments)},a._olm_pickle_account=function(){return(a._olm_pickle_account=a.asm.z).apply(null,arguments)},a._olm_pickle_session=function(){return(a._olm_pickle_session=a.asm.A).apply(null,arguments)},a._olm_unpickle_account=function(){return(a._olm_unpickle_account=a.asm.B).apply(null,arguments)},a._olm_unpickle_session=function(){return(a._olm_unpickle_session=a.asm.C).apply(null,arguments)},a._olm_create_account_random_length=function(){return(a._olm_create_account_random_length=a.asm.D).apply(null,arguments)},a._olm_create_account=function(){return(a._olm_create_account=a.asm.E).apply(null,arguments)},a._olm_account_identity_keys_length=function(){return(a._olm_account_identity_keys_length=a.asm.F).apply(null,arguments)},a._olm_account_identity_keys=function(){return(a._olm_account_identity_keys=a.asm.G).apply(null,arguments)},a._olm_account_signature_length=function(){return(a._olm_account_signature_length=a.asm.H).apply(null,arguments)},a._olm_account_sign=function(){return(a._olm_account_sign=a.asm.I).apply(null,arguments)},a._olm_account_one_time_keys_length=function(){return(a._olm_account_one_time_keys_length=a.asm.J).apply(null,arguments)},a._olm_account_one_time_keys=function(){return(a._olm_account_one_time_keys=a.asm.K).apply(null,arguments)},a._olm_account_mark_keys_as_published=function(){return(a._olm_account_mark_keys_as_published=a.asm.L).apply(null,arguments)},a._olm_account_max_number_of_one_time_keys=function(){return(a._olm_account_max_number_of_one_time_keys=a.asm.M).apply(null,arguments)},a._olm_account_generate_one_time_keys_random_length=function(){return(a._olm_account_generate_one_time_keys_random_length=a.asm.N).apply(null,arguments)},a._olm_account_generate_one_time_keys=function(){return(a._olm_account_generate_one_time_keys=a.asm.O).apply(null,arguments)},a._olm_account_generate_fallback_key_random_length=function(){return(a._olm_account_generate_fallback_key_random_length=a.asm.P).apply(null,arguments)},a._olm_account_generate_fallback_key=function(){return(a._olm_account_generate_fallback_key=a.asm.Q).apply(null,arguments)},a._olm_account_fallback_key_length=function(){return(a._olm_account_fallback_key_length=a.asm.R).apply(null,arguments)},a._olm_account_fallback_key=function(){return(a._olm_account_fallback_key=a.asm.S).apply(null,arguments)},a._olm_account_unpublished_fallback_key_length=function(){return(a._olm_account_unpublished_fallback_key_length=a.asm.T).apply(null,arguments)},a._olm_account_unpublished_fallback_key=function(){return(a._olm_account_unpublished_fallback_key=a.asm.U).apply(null,arguments)},a._olm_account_forget_old_fallback_key=function(){return(a._olm_account_forget_old_fallback_key=a.asm.V).apply(null,arguments)},a._olm_create_outbound_session_random_length=function(){return(a._olm_create_outbound_session_random_length=a.asm.W).apply(null,arguments)},a._olm_create_outbound_session=function(){return(a._olm_create_outbound_session=a.asm.X).apply(null,arguments)},a._olm_create_inbound_session=function(){return(a._olm_create_inbound_session=a.asm.Y).apply(null,arguments)},a._olm_create_inbound_session_from=function(){return(a._olm_create_inbound_session_from=a.asm.Z).apply(null,arguments)},a._olm_session_id_length=function(){return(a._olm_session_id_length=a.asm._).apply(null,arguments)},a._olm_session_id=function(){return(a._olm_session_id=a.asm.$).apply(null,arguments)},a._olm_session_has_received_message=function(){return(a._olm_session_has_received_message=a.asm.aa).apply(null,arguments)},a._olm_session_describe=function(){return(a._olm_session_describe=a.asm.ba).apply(null,arguments)},a._olm_matches_inbound_session=function(){return(a._olm_matches_inbound_session=a.asm.ca).apply(null,arguments)},a._olm_matches_inbound_session_from=function(){return(a._olm_matches_inbound_session_from=a.asm.da).apply(null,arguments)},a._olm_remove_one_time_keys=function(){return(a._olm_remove_one_time_keys=a.asm.ea).apply(null,arguments)},a._olm_encrypt_message_type=function(){return(a._olm_encrypt_message_type=a.asm.fa).apply(null,arguments)},a._olm_encrypt_random_length=function(){return(a._olm_encrypt_random_length=a.asm.ga).apply(null,arguments)},a._olm_encrypt_message_length=function(){return(a._olm_encrypt_message_length=a.asm.ha).apply(null,arguments)},a._olm_encrypt=function(){return(a._olm_encrypt=a.asm.ia).apply(null,arguments)},a._olm_decrypt_max_plaintext_length=function(){return(a._olm_decrypt_max_plaintext_length=a.asm.ja).apply(null,arguments)},a._olm_decrypt=function(){return(a._olm_decrypt=a.asm.ka).apply(null,arguments)},a._olm_sha256_length=function(){return(a._olm_sha256_length=a.asm.la).apply(null,arguments)},a._olm_sha256=function(){return(a._olm_sha256=a.asm.ma).apply(null,arguments)},a._olm_ed25519_verify=function(){return(a._olm_ed25519_verify=a.asm.na).apply(null,arguments)},a._olm_pk_encryption_last_error=function(){return(a._olm_pk_encryption_last_error=a.asm.oa).apply(null,arguments)},a._olm_pk_encryption_last_error_code=function(){return(a._olm_pk_encryption_last_error_code=a.asm.pa).apply(null,arguments)},a._olm_pk_encryption_size=function(){return(a._olm_pk_encryption_size=a.asm.qa).apply(null,arguments)},a._olm_pk_encryption=function(){return(a._olm_pk_encryption=a.asm.ra).apply(null,arguments)},a._olm_clear_pk_encryption=function(){return(a._olm_clear_pk_encryption=a.asm.sa).apply(null,arguments)},a._olm_pk_encryption_set_recipient_key=function(){return(a._olm_pk_encryption_set_recipient_key=a.asm.ta).apply(null,arguments)},a._olm_pk_key_length=function(){return(a._olm_pk_key_length=a.asm.ua).apply(null,arguments)},a._olm_pk_ciphertext_length=function(){return(a._olm_pk_ciphertext_length=a.asm.va).apply(null,arguments)},a._olm_pk_mac_length=function(){return(a._olm_pk_mac_length=a.asm.wa).apply(null,arguments)},a._olm_pk_encrypt_random_length=function(){return(a._olm_pk_encrypt_random_length=a.asm.xa).apply(null,arguments)},a._olm_pk_encrypt=function(){return(a._olm_pk_encrypt=a.asm.ya).apply(null,arguments)},a._olm_pk_decryption_last_error=function(){return(a._olm_pk_decryption_last_error=a.asm.za).apply(null,arguments)},a._olm_pk_decryption_last_error_code=function(){return(a._olm_pk_decryption_last_error_code=a.asm.Aa).apply(null,arguments)},a._olm_pk_decryption_size=function(){return(a._olm_pk_decryption_size=a.asm.Ba).apply(null,arguments)},a._olm_pk_decryption=function(){return(a._olm_pk_decryption=a.asm.Ca).apply(null,arguments)},a._olm_clear_pk_decryption=function(){return(a._olm_clear_pk_decryption=a.asm.Da).apply(null,arguments)},a._olm_pk_private_key_length=function(){return(a._olm_pk_private_key_length=a.asm.Ea).apply(null,arguments)},a._olm_pk_generate_key_random_length=function(){return(a._olm_pk_generate_key_random_length=a.asm.Fa).apply(null,arguments)},a._olm_pk_key_from_private=function(){return(a._olm_pk_key_from_private=a.asm.Ga).apply(null,arguments)},a._olm_pk_generate_key=function(){return(a._olm_pk_generate_key=a.asm.Ha).apply(null,arguments)},a._olm_pickle_pk_decryption_length=function(){return(a._olm_pickle_pk_decryption_length=a.asm.Ia).apply(null,arguments)},a._olm_pickle_pk_decryption=function(){return(a._olm_pickle_pk_decryption=a.asm.Ja).apply(null,arguments)},a._olm_unpickle_pk_decryption=function(){return(a._olm_unpickle_pk_decryption=a.asm.Ka).apply(null,arguments)},a._olm_pk_max_plaintext_length=function(){return(a._olm_pk_max_plaintext_length=a.asm.La).apply(null,arguments)},a._olm_pk_decrypt=function(){return(a._olm_pk_decrypt=a.asm.Ma).apply(null,arguments)},a._olm_pk_get_private_key=function(){return(a._olm_pk_get_private_key=a.asm.Na).apply(null,arguments)},a._olm_pk_signing_size=function(){return(a._olm_pk_signing_size=a.asm.Oa).apply(null,arguments)},a._olm_pk_signing=function(){return(a._olm_pk_signing=a.asm.Pa).apply(null,arguments)},a._olm_pk_signing_last_error=function(){return(a._olm_pk_signing_last_error=a.asm.Qa).apply(null,arguments)},a._olm_pk_signing_last_error_code=function(){return(a._olm_pk_signing_last_error_code=a.asm.Ra).apply(null,arguments)},a._olm_clear_pk_signing=function(){return(a._olm_clear_pk_signing=a.asm.Sa).apply(null,arguments)},a._olm_pk_signing_seed_length=function(){return(a._olm_pk_signing_seed_length=a.asm.Ta).apply(null,arguments)},a._olm_pk_signing_public_key_length=function(){return(a._olm_pk_signing_public_key_length=a.asm.Ua).apply(null,arguments)},a._olm_pk_signing_key_from_seed=function(){return(a._olm_pk_signing_key_from_seed=a.asm.Va).apply(null,arguments)},a._olm_pk_signature_length=function(){return(a._olm_pk_signature_length=a.asm.Wa).apply(null,arguments)},a._olm_pk_sign=function(){return(a._olm_pk_sign=a.asm.Xa).apply(null,arguments)},a._olm_inbound_group_session_size=function(){return(a._olm_inbound_group_session_size=a.asm.Ya).apply(null,arguments)},a._olm_inbound_group_session=function(){return(a._olm_inbound_group_session=a.asm.Za).apply(null,arguments)},a._olm_clear_inbound_group_session=function(){return(a._olm_clear_inbound_group_session=a.asm._a).apply(null,arguments)},a._olm_inbound_group_session_last_error=function(){return(a._olm_inbound_group_session_last_error=a.asm.$a).apply(null,arguments)},a._olm_inbound_group_session_last_error_code=function(){return(a._olm_inbound_group_session_last_error_code=a.asm.ab).apply(null,arguments)},a._olm_init_inbound_group_session=function(){return(a._olm_init_inbound_group_session=a.asm.bb).apply(null,arguments)},a._olm_import_inbound_group_session=function(){return(a._olm_import_inbound_group_session=a.asm.cb).apply(null,arguments)},a._olm_pickle_inbound_group_session_length=function(){return(a._olm_pickle_inbound_group_session_length=a.asm.db).apply(null,arguments)},a._olm_pickle_inbound_group_session=function(){return(a._olm_pickle_inbound_group_session=a.asm.eb).apply(null,arguments)},a._olm_unpickle_inbound_group_session=function(){return(a._olm_unpickle_inbound_group_session=a.asm.fb).apply(null,arguments)},a._olm_group_decrypt_max_plaintext_length=function(){return(a._olm_group_decrypt_max_plaintext_length=a.asm.gb).apply(null,arguments)},a._olm_group_decrypt=function(){return(a._olm_group_decrypt=a.asm.hb).apply(null,arguments)},a._olm_inbound_group_session_id_length=function(){return(a._olm_inbound_group_session_id_length=a.asm.ib).apply(null,arguments)},a._olm_inbound_group_session_id=function(){return(a._olm_inbound_group_session_id=a.asm.jb).apply(null,arguments)},a._olm_inbound_group_session_first_known_index=function(){return(a._olm_inbound_group_session_first_known_index=a.asm.kb).apply(null,arguments)},a._olm_inbound_group_session_is_verified=function(){return(a._olm_inbound_group_session_is_verified=a.asm.lb).apply(null,arguments)},a._olm_export_inbound_group_session_length=function(){return(a._olm_export_inbound_group_session_length=a.asm.mb).apply(null,arguments)},a._olm_export_inbound_group_session=function(){return(a._olm_export_inbound_group_session=a.asm.nb).apply(null,arguments)},a._olm_outbound_group_session_size=function(){return(a._olm_outbound_group_session_size=a.asm.ob).apply(null,arguments)},a._olm_outbound_group_session=function(){return(a._olm_outbound_group_session=a.asm.pb).apply(null,arguments)},a._olm_clear_outbound_group_session=function(){return(a._olm_clear_outbound_group_session=a.asm.qb).apply(null,arguments)},a._olm_outbound_group_session_last_error=function(){return(a._olm_outbound_group_session_last_error=a.asm.rb).apply(null,arguments)},a._olm_outbound_group_session_last_error_code=function(){return(a._olm_outbound_group_session_last_error_code=a.asm.sb).apply(null,arguments)},a._olm_pickle_outbound_group_session_length=function(){return(a._olm_pickle_outbound_group_session_length=a.asm.tb).apply(null,arguments)},a._olm_pickle_outbound_group_session=function(){return(a._olm_pickle_outbound_group_session=a.asm.ub).apply(null,arguments)},a._olm_unpickle_outbound_group_session=function(){return(a._olm_unpickle_outbound_group_session=a.asm.vb).apply(null,arguments)},a._olm_init_outbound_group_session_random_length=function(){return(a._olm_init_outbound_group_session_random_length=a.asm.wb).apply(null,arguments)},a._olm_init_outbound_group_session=function(){return(a._olm_init_outbound_group_session=a.asm.xb).apply(null,arguments)},a._olm_group_encrypt_message_length=function(){return(a._olm_group_encrypt_message_length=a.asm.yb).apply(null,arguments)},a._olm_group_encrypt=function(){return(a._olm_group_encrypt=a.asm.zb).apply(null,arguments)},a._olm_outbound_group_session_id_length=function(){return(a._olm_outbound_group_session_id_length=a.asm.Ab).apply(null,arguments)},a._olm_outbound_group_session_id=function(){return(a._olm_outbound_group_session_id=a.asm.Bb).apply(null,arguments)},a._olm_outbound_group_session_message_index=function(){return(a._olm_outbound_group_session_message_index=a.asm.Cb).apply(null,arguments)},a._olm_outbound_group_session_key_length=function(){return(a._olm_outbound_group_session_key_length=a.asm.Db).apply(null,arguments)},a._olm_outbound_group_session_key=function(){return(a._olm_outbound_group_session_key=a.asm.Eb).apply(null,arguments)},a._olm_sas_last_error=function(){return(a._olm_sas_last_error=a.asm.Fb).apply(null,arguments)},a._olm_sas_last_error_code=function(){return(a._olm_sas_last_error_code=a.asm.Gb).apply(null,arguments)},a._olm_sas_size=function(){return(a._olm_sas_size=a.asm.Hb).apply(null,arguments)},a._olm_sas=function(){return(a._olm_sas=a.asm.Ib).apply(null,arguments)},a._olm_clear_sas=function(){return(a._olm_clear_sas=a.asm.Jb).apply(null,arguments)},a._olm_create_sas_random_length=function(){return(a._olm_create_sas_random_length=a.asm.Kb).apply(null,arguments)},a._olm_create_sas=function(){return(a._olm_create_sas=a.asm.Lb).apply(null,arguments)},a._olm_sas_pubkey_length=function(){return(a._olm_sas_pubkey_length=a.asm.Mb).apply(null,arguments)},a._olm_sas_get_pubkey=function(){return(a._olm_sas_get_pubkey=a.asm.Nb).apply(null,arguments)},a._olm_sas_set_their_key=function(){return(a._olm_sas_set_their_key=a.asm.Ob).apply(null,arguments)},a._olm_sas_is_their_key_set=function(){return(a._olm_sas_is_their_key_set=a.asm.Pb).apply(null,arguments)},a._olm_sas_generate_bytes=function(){return(a._olm_sas_generate_bytes=a.asm.Qb).apply(null,arguments)},a._olm_sas_mac_length=function(){return(a._olm_sas_mac_length=a.asm.Rb).apply(null,arguments)},a._olm_sas_calculate_mac_fixed_base64=function(){return(a._olm_sas_calculate_mac_fixed_base64=a.asm.Sb).apply(null,arguments)},a._olm_sas_calculate_mac=function(){return(a._olm_sas_calculate_mac=a.asm.Tb).apply(null,arguments)},a._olm_sas_calculate_mac_long_kdf=function(){return(a._olm_sas_calculate_mac_long_kdf=a.asm.Ub).apply(null,arguments)},a._malloc=function(){return(a._malloc=a.asm.Vb).apply(null,arguments)},a._free=function(){return(a._free=a.asm.Wb).apply(null,arguments)};var Bs=a.stackSave=function(){return(Bs=a.stackSave=a.asm.Xb).apply(null,arguments)},$s=a.stackRestore=function(){return($s=a.stackRestore=a.asm.Yb).apply(null,arguments)},Ze=a.stackAlloc=function(){return(Ze=a.stackAlloc=a.asm.Zb).apply(null,arguments)};a.UTF8ToString=U,a.stringToUTF8=Ht,a.intArrayFromString=Ks,a.writeAsciiToMemory=Gt,a.ALLOC_STACK=1;var kt;bt=function d(){kt||js(),kt||(bt=d)};function js(){function d(){if(!kt&&(kt=!0,a.calledRun=!0,!Ue)){if(at(_i),u(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;){var m=a.postRun.shift();vt.unshift(m)}at(vt)}}if(!(0[],(t,s)=>t.push(s))}function En(n,e,t,s){return n.reduce((i,r)=>{const o=e(r);let c=i.get(o);return c||(c=t(),i.set(o,c)),s(c,r),i},new Map)}function uo(n,e){return n.reduce((t,s)=>{const i=e(s);return t[i]?t[i]+=1:t[i]=1,t},{})}function Pe(){return Ir("t")}function Ir(n){const t=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16);return n+"0".repeat(14-t.length)+t}function mo(n){return n.startsWith("t")&&n.length===15}function Fi(n){const e=ti(n,s=>s.device.user_id);return{messages:Array.from(e.entries()).reduce((s,[i,r])=>(s[i]=r.reduce((o,c)=>(o[c.device.device_id]=c.content,o),{}),s),{})}}function Br(n){typeof n=="function"?n():n.dispose()}function gd(n){return n&&(typeof n=="function"||typeof n.dispose=="function")}class li{constructor(){this._disposables=[]}track(e){if(!gd(e))throw new Error("Not a disposable");return this.isDisposed?(console.warn("Disposables already disposed, disposing new value"),Br(e),e):(this._disposables.push(e),e)}untrack(e){if(!this._disposables)return;const t=this._disposables.indexOf(e);t>=0&&this._disposables.splice(t,1)}dispose(){if(this._disposables){for(const e of this._disposables)Br(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[s]=this._disposables.splice(t,1);Br(s)}else console.warn("disposable not found, did it leak?",e)}}class fd extends li{constructor(e,t){super(),this.sentMessages=new Map,this.receivedMessages=new Map,this.waitMap=new Map,this.hsApi=e.hsApi,this.deviceTracker=e.deviceTracker,this.otherUserId=e.otherUserId,this.ourDeviceId=e.ourUserDeviceId,this.clock=e.clock,this.log=e.log,this.deviceMessageHandler=e.deviceMessageHandler,this.track(this.deviceMessageHandler.disposableOn("message",async({unencrypted:s})=>{!s||await this.handleDeviceMessage(s)})),this.track(()=>{this.waitMap.forEach(s=>{s.reject(new pt)})}),t&&(this.id=t.content.transaction_id,this.receivedMessages.set(t.type,t),this.otherUserDeviceId=t.content.from_device)}get cancellation(){return this._cancellation}get isCancelled(){return!!this._cancellation}async send(e,t,s){await s.wrap("ToDeviceChannel.send",async()=>{if(this.isCancelled)throw new pt;if(e===P.Request){await this.handleRequestEventSpecially(e,t,s);return}Object.assign(t,{transaction_id:this.id});const i={messages:{[this.otherUserId]:{[this.otherUserDeviceId]:t}}};await this.hsApi.sendToDevice(e,i,Pe(),{log:s}).response(),this.sentMessages.set(e,{content:t})})}async handleRequestEventSpecially(e,t,s){await s.wrap("ToDeviceChannel.handleRequestEventSpecially",async()=>{const i=this.clock.now(),r=Pe();this.id=r,Object.assign(t,{timestamp:i,transaction_id:r});const o={messages:{[this.otherUserId]:{"*":t}}};await this.hsApi.sendToDevice(e,o,Pe(),{log:s}).response(),this.sentMessages.set(e,{content:t})})}getReceivedMessage(e){return this.receivedMessages.get(e)}getSentMessage(e){return this.sentMessages.get(e)}get acceptMessage(){var e;return(e=this.receivedMessages.get(P.Accept))!=null?e:this.sentMessages.get(P.Accept)}async handleDeviceMessage(e){await this.log.wrap("ToDeviceChannel.handleDeviceMessage",async t=>{if(!!e.type.startsWith("m.key.verification.")){if(e.content.transaction_id!==this.id){await this.cancelVerification(A.UnknownTransaction);return}if(this.resolveAnyWaits(e),this.receivedMessages.set(e.type,e),e.type===P.Ready){this.handleReadyMessage(e,t);return}if(e.type===P.Cancel){this._cancellation={code:e.content.code,cancelledByUs:!1},this.dispose();return}}})}async handleReadyMessage(e,t){const s=e.content.from_device;this.otherUserDeviceId=s;const r=(await this.deviceTracker.devicesForUsers([this.otherUserId],this.hsApi,t)).filter(h=>h.device_id!==s&&h.device_id!==this.ourDeviceId),o={code:A.OtherDeviceAccepted,reason:kr[A.OtherDeviceAccepted],transaction_id:this.id},c=r.reduce((h,a)=>(h[a.device_id]=o,h),{}),l={messages:{[this.otherUserId]:c}};await this.hsApi.sendToDevice(P.Cancel,l,Pe(),{log:t}).response()}async cancelVerification(e){await this.log.wrap("Channel.cancelVerification",async t=>{var i;if(this.isCancelled)throw new pt;const s={messages:{[this.otherUserId]:{[(i=this.otherUserDeviceId)!=null?i:"*"]:{code:e,reason:kr[e],transaction_id:this.id}}}};await this.hsApi.sendToDevice(P.Cancel,s,Pe(),{log:t}).response(),this._cancellation={code:e,cancelledByUs:!0},this.dispose()})}resolveAnyWaits(e){const{type:t}=e,s=this.waitMap.get(t);s&&(s.resolve(e),this.waitMap.delete(t))}waitForEvent(e){if(this.isCancelled)throw new pt;const t=this.receivedMessages.get(e);if(t)return Promise.resolve(t);const s=this.waitMap.get(e);if(s)return s.promise;const i=new As;return this.waitMap.set(e,i),i.promise}setStartMessage(e){this.startMessage=e,this._initiatedByUs=e.content.from_device===this.ourDeviceId}get initiatedByUs(){return this._initiatedByUs}}class yd extends li{constructor(e,t){var s,i;if(super(),this.sentMessages=new Map,this.receivedMessages=new Map,this.waitMap=new Map,this.otherUserId=e.otherUserId,this.ourUserId=e.ourUserId,this.ourDeviceId=e.ourUserDeviceId,this.log=e.log,this.room=e.room,this.subscribeToTimeline(),this.track(()=>{this.waitMap.forEach(r=>{r.reject(new pt)})}),t){this.id=t.id;const r=(i=(s=t.content)==null?void 0:s.msgtype)!=null?i:t.eventType;this.receivedMessages.set(r,t),this.otherUserDeviceId=t.content.from_device}}async subscribeToTimeline(){const e=await this.room.openTimeline();this.track(()=>e.release()),this.track(e.entries.subscribe({onAdd:async(t,s)=>{this.handleRoomMessage(s)},onRemove:()=>{},onUpdate:()=>{}}))}get cancellation(){return this._cancellation}get isCancelled(){return!!this._cancellation}async send(e,t,s){await s.wrap("RoomChannel.send",async i=>{if(this.isCancelled)throw new pt;if(e===P.Request){await this.handleRequestEventSpecially(e,t,s);return}!this.id||(await this.room.ensureMessageKeyIsShared(i),Object.assign(t,th(this.id)),await this.room.sendEvent(e,t,void 0,s),this.sentMessages.set(e,{content:t}))})}async handleRequestEventSpecially(e,t,s){await s.wrap("RoomChannel.handleRequestEventSpecially",async()=>{Object.assign(t,{body:`${this.otherUserId} is requesting to verify your key, but your client does not support in-chat key verification. You will need to use legacy key verification to verify keys.`,msgtype:P.Request,to:this.otherUserId});const i=await this.room.sendEvent("m.room.message",t,void 0,s);this.id=await i.getRemoteId(),this.sentMessages.set(e,{content:t})})}getReceivedMessage(e){return this.receivedMessages.get(e)}getSentMessage(e){return this.sentMessages.get(e)}get acceptMessage(){var e;return(e=this.receivedMessages.get(P.Accept))!=null?e:this.sentMessages.get(P.Accept)}async handleRoomMessage(e){var s,i;const t=(i=(s=e.content)==null?void 0:s.msgtype)!=null?i:e.eventType;!(t!=null&&t.startsWith("m.key.verification"))||e.sender===this.ourUserId||e.isLoadedFromStorage||await this.log.wrap("RoomChannel.handleRoomMessage",async r=>{if(!this.id)throw new Error("Couldn't find event-id of request message!");if(va(e.event)!==this.id){await this.cancelVerification(A.UnknownTransaction);return}if(this.resolveAnyWaits(e),this.receivedMessages.set(e.eventType,e),e.eventType===P.Ready){const o=e.content.from_device;this.otherUserDeviceId=o;return}if(e.eventType===P.Cancel){this._cancellation={code:e.content.code,cancelledByUs:!1},this.dispose();return}})}async cancelVerification(e){await this.log.wrap("RoomChannel.cancelVerification",async t=>{if(t.log({reason:kr[e]}),this.isCancelled)throw new pt;const s={code:e,reason:kr[e]};await this.send(P.Cancel,s,t),this._cancellation={code:e,cancelledByUs:!0},this.dispose()})}resolveAnyWaits(e){const{eventType:t}=e,s=this.waitMap.get(t);s&&(s.resolve(e),this.waitMap.delete(t))}waitForEvent(e){if(this.isCancelled)throw new pt;const t=this.receivedMessages.get(e);if(t)return Promise.resolve(t);const s=this.waitMap.get(e);if(s)return s.promise;const i=new As;return this.waitMap.set(e,i),i.promise}setStartMessage(e){if(e.content["m.relates_to"])this.startMessage=e;else{const t=e.clone();t.content["m.relates_to"]=t.event.content["m.relates_to"],this.startMessage=t}this._initiatedByUs=e.content.from_device===this.ourDeviceId}get initiatedByUs(){return this._initiatedByUs}}class pr{constructor(e){this.startingMessage=e}get deviceId(){return this.startingMessage.content.from_device}get sender(){return this.startingMessage.sender}get id(){var e;return(e=this.startingMessage.content.transaction_id)!=null?e:this.startingMessage.eventId}async reject(e,t,s){const i=e.startVerification(this,t,s);await(i==null?void 0:i.abort())}}var Et=(n=>(n.Master="master",n.SelfSigning="self_signing",n.UserSigning="user_signing",n))(Et||{}),et=(n=>(n[n.Trusted=1]="Trusted",n[n.UserNotSigned=2]="UserNotSigned",n[n.UserSignatureMismatch=3]="UserSignatureMismatch",n[n.UserDeviceNotSigned=4]="UserDeviceNotSigned",n[n.UserDeviceSignatureMismatch=5]="UserDeviceSignatureMismatch",n[n.UserSetupError=6]="UserSetupError",n[n.OwnSetupError=7]="OwnSetupError",n))(et||{});class wd{constructor(e){this._isMasterKeyTrusted=!1,this.observedUsers=new Map,this.receivedSASVerifications=new Dt,this.storage=e.storage,this.secretFetcher=e.secretFetcher,this.platform=e.platform,this.deviceTracker=e.deviceTracker,this.olm=e.olm,this.olmUtil=e.olmUtil,this.hsApi=e.hsApi,this.ownUserId=e.ownUserId,this.deviceId=e.deviceId,this.e2eeAccount=e.e2eeAccount,this.deviceMessageHandler=e.deviceMessageHandler,this.handleSASDeviceMessage=this.handleSASDeviceMessage.bind(this),this.deviceMessageHandler.on("message",this.handleSASDeviceMessage)}async load(e){return await this.verifyMSKFrom4S(!1,e)!==0}async start(e){this.isMasterKeyTrusted||await this.verifyMSKFrom4S(!0,e)}async verifyMSKFrom4S(e,t){return await t.wrap("CrossSigning.verifyMSKFrom4S",async s=>{const i=await this.getSigningKey("master");if(!i)return s.set("failure","no_priv_msk"),0;const r=new this.olm.PkSigning;let o;try{o=r.init_with_seed(i)}finally{r.free()}const c=await this.deviceTracker.getCrossSigningKeyForUser(this.ownUserId,"master",e?this.hsApi:void 0,s);if(!c)return s.set("failure","no_pub_msk"),1;const l=c&&Qs(c);return s.set({publishedMasterKey:l,derivedPublicKey:o}),this._isMasterKeyTrusted=!!l&&l===o,this._isMasterKeyTrusted?3:(s.set("failure","mismatch"),2)})}get isMasterKeyTrusted(){return this._isMasterKeyTrusted}startVerification(e,t,s){const i=s!=null?s:t;if(this.sasVerificationInProgress&&!this.sasVerificationInProgress.finished){i.log({sasVerificationAlreadyInProgress:!0});return}const r=e instanceof pr?e.sender:e,o=e instanceof pr?e.startingMessage:void 0;let c;return r===this.ownUserId?c=new fd({deviceTracker:this.deviceTracker,hsApi:this.hsApi,otherUserId:r,clock:this.platform.clock,deviceMessageHandler:this.deviceMessageHandler,ourUserDeviceId:this.deviceId,log:i},o):c=new yd({room:t,otherUserId:r,ourUserId:this.ownUserId,ourUserDeviceId:this.deviceId,log:i},o),this.sasVerificationInProgress=new pd({olm:this.olm,olmUtil:this.olmUtil,ourUserId:this.ownUserId,ourUserDeviceId:this.deviceId,otherUserId:r,log:i,channel:c,e2eeAccount:this.e2eeAccount,deviceTracker:this.deviceTracker,hsApi:this.hsApi,clock:this.platform.clock}),this.sasVerificationInProgress}async handleSASDeviceMessage({unencrypted:e}){!e||e.type!==P.Request&&e.type!==P.Start||await this.platform.logger.run("CrossSigning.handleSASDeviceMessage",async t=>{var c;const s=e.content.transaction_id,i=e.content.from_device,r=e.sender;if(!i||r!==this.ownUserId)return;if(!await this.areWeVerified(t)){const l=await this.deviceTracker.deviceForId(this.ownUserId,i,this.hsApi,t);if(!l||!await this.isOurUserDeviceTrusted(l,t))return}if(((c=this.sasVerificationInProgress)==null?void 0:c.channel.id)!==s)switch(e.type){case P.Cancel:this.receivedSASVerifications.remove(s);return;case P.Request:case P.Start:this.platform.logger.run("Create SASRequest",()=>{this.receivedSASVerifications.set(s,new pr(e))});return;default:return}})}async signOwnDevice(e){return e.wrap("CrossSigning.signOwnDevice",async t=>{if(!this._isMasterKeyTrusted){t.set("mskNotTrusted",!0);return}const s=this.e2eeAccount.getUnsignedDeviceKey();return this.signDeviceKey(s,t)})}async signDevice(e,t){return t.wrap("CrossSigning.signDevice",async s=>{this._isMasterKeyTrusted||s.set("mskNotTrusted",!0);const i=await e.verify()&&this._isMasterKeyTrusted;if(s.set("shouldSign",i),!i)return;const r=e.otherDeviceId;s.set("id",r);const o=await this.deviceTracker.deviceForId(this.ownUserId,r,this.hsApi,s);if(!!o)return delete o.signatures,this.signDeviceKey(o,s)})}async signUser(e,t){return t.wrap("CrossSigning.signUser",async s=>{const i=e.otherUserId;if(s.set("id",i),!this._isMasterKeyTrusted){s.set("mskNotTrusted",!0);return}if(i===this.ownUserId)return;const r=await e.verify();if(s.set("shouldSign",r),!r)return;const o=await this.deviceTracker.getCrossSigningKeyForUser(i,"master",this.hsApi,s);if(!o)return;const c=await this.getSigningKey("user_signing");if(!c)return;delete o.signatures,this.signKey(o,c);const l={[o.user_id]:{[Qs(o)]:o}};return await this.hsApi.uploadSignatures(l,{log:s}).response(),await this.deviceTracker.invalidateUserKeys(i),this.emitUserTrustUpdate(i,s),o})}async isOurUserDeviceTrusted(e,t){return await this.platform.logger.wrapOrRun(t,"CrossSigning.isOurUserDeviceTrusted",async s=>{const i=await this.deviceTracker.getCrossSigningKeyForUser(this.ownUserId,"self_signing",this.hsApi,s);return i?this.hasValidSignatureFrom(e,i,s)===ne.Valid:!1})}areWeVerified(e){return this.platform.logger.wrapOrRun(e,"CrossSigning.areWeVerified",async t=>{const s=await this.deviceTracker.deviceForId(this.ownUserId,this.deviceId,this.hsApi,t);return this.isOurUserDeviceTrusted(s,e)})}getUserTrust(e,t){return t.wrap("CrossSigning.getUserTrust",async s=>{s.set("id",e);const i=f=>(s.set("result",f),f);if(!this.isMasterKeyTrusted)return i(7);const r=await s.wrap("get our msk",f=>this.deviceTracker.getCrossSigningKeyForUser(this.ownUserId,"master",this.hsApi,f));if(!r)return i(7);const o=await s.wrap("get our usk",f=>this.deviceTracker.getCrossSigningKeyForUser(this.ownUserId,"user_signing",this.hsApi,f));if(!o||s.wrap("verify our usk",f=>this.hasValidSignatureFrom(o,r,f))!==ne.Valid)return i(7);const l=await s.wrap("get their msk",f=>this.deviceTracker.getCrossSigningKeyForUser(e,"master",this.hsApi,f));if(!l)return i(2);const h=s.wrap("verify their msk",f=>this.hasValidSignatureFrom(l,o,f));if(h!==ne.Valid)return h===ne.NotSigned?i(2):i(3);const a=await s.wrap("get their ssk",f=>this.deviceTracker.getCrossSigningKeyForUser(e,"self_signing",this.hsApi,f));if(!a||s.wrap("verify their ssk",f=>this.hasValidSignatureFrom(a,l,f))!==ne.Valid)return i(6);const g=(await s.wrap("get their devices",f=>this.deviceTracker.devicesForUsers([e],this.hsApi,f))).reduce((f,v)=>s.wrap({l:"verify device",id:v.device_id},M=>{const R=this.hasValidSignatureFrom(v,a,M);return f===ne.Invalid||R===ne.Invalid?ne.Invalid:f===ne.NotSigned||R===ne.NotSigned?ne.NotSigned:f===ne.Valid||R===ne.Valid?ne.Valid:ne.Invalid}),ne.Valid);return g!==ne.Valid?g===ne.NotSigned?i(4):i(5):i(1)})}dispose(){this.deviceMessageHandler.off("message",this.handleSASDeviceMessage)}observeUserTrust(e,t){const s=this.observedUsers.get(e);if(s)return s;const i=new Ui(void 0,()=>{this.observedUsers.delete(e)});return this.observedUsers.set(e,i),t.wrapDetached("get user trust",async r=>{i.get()===void 0&&i.set(await this.getUserTrust(e,r))}),i}async signDeviceKey(e,t){const s=await this.getSigningKey("self_signing");if(!s)return;this.signKey(e,s);const i={[e.user_id]:{[e.device_id]:e}};return await this.hsApi.uploadSignatures(i,{log:t}).response(),await this.deviceTracker.invalidateUserKeys(this.ownUserId),this.emitUserTrustUpdate(this.ownUserId,t),e}async getSigningKey(e){const t=await this.secretFetcher.getSecret(`m.cross_signing.${e}`);if(t)return new Uint8Array(this.platform.encoding.base64.decode(t))}signKey(e,t){Zh(this.olm,e,t,this.ownUserId,"")}hasValidSignatureFrom(e,t,s){const i=Qs(t);return i?vn(this.olmUtil,t.user_id,i,i,e,s):ne.NotSigned}emitUserTrustUpdate(e,t){const s=this.observedUsers.get(e);s&&s.get()!==void 0&&(s.set(void 0),t.wrapDetached("update user trust",async i=>{s.set(await this.getUserTrust(e,i))}))}}function vd(n){if(!Array.isArray(n.usage)||n.usage.length!==1)return;const e=n.usage[0];if(!(e!=="master"&&e!=="self_signing"&&e!=="user_signing"))return e}const bd="ed25519",Sd=`${bd}:`;function Qs(n){const e=Object.keys(n.keys).filter(i=>i.startsWith(Sd));if(e.length!==1)return;const t=e[0];return n.keys[t]}function _o(n){return n.user_id}var Oa=(n=>(n[n.Outdated=0]="Outdated",n[n.UpToDate=1]="UpToDate",n))(Oa||{});function Pa(n,e){return{userId:n,roomIds:e?[e]:[],keysTrackingStatus:0}}function kd(n,e,t){if(n){if(!n.roomIds.includes(t))return n.roomIds.push(t),n}else return n=Pa(e,t),n}class Id{constructor(e){this._storage=e.storage,this._getSyncToken=e.getSyncToken,this._olmUtil=e.olmUtil,this._ownUserId=e.ownUserId,this._ownDeviceId=e.ownDeviceId}async writeDeviceChanges(e,t,s){const{userIdentities:i}=t;s.set("changed",e.length),await Promise.all(e.map(async r=>{const o=await i.get(r);o&&(s.log({l:"outdated",id:r}),o.keysTrackingStatus=0,i.set(o))}))}async writeMemberChanges(e,t,s,i){const r=[],o=[];return await Promise.all(Array.from(t.values()).map(async c=>{if(Xi(c.membership,s))await this._addRoomToUserIdentity(c.roomId,c.userId,i)&&r.push(c.userId);else if(Xi(c.previousMembership,s)){const{roomId:l}=c;if(c.userId===this._ownUserId){const h=await i.roomMembers.getAllUserIds(l);await Promise.all(h.map(a=>this._removeRoomFromUserIdentity(l,a,i)))}else await this._removeRoomFromUserIdentity(l,c.userId,i);o.push(c.userId)}})),{added:r,removed:o}}async trackRoom(e,t,s){if(e.isTrackingMembers||!e.isEncrypted)return;const i=await e.loadMemberList(void 0,s),r=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary,this._storage.storeNames.userIdentities,this._storage.storeNames.deviceKeys]);try{let o;try{o=e.writeIsTrackingMembers(!0,r);const c=Array.from(i.members.values());s.set("members",c.length),await Promise.all(c.map(async l=>{Xi(l.membership,t)?await this._addRoomToUserIdentity(l.roomId,l.userId,r):await this._removeRoomFromUserIdentity(l.roomId,l.userId,r)}))}catch(c){throw r.abort(),c}await r.complete(),e.applyIsTrackingMembersChanges(o)}finally{i.release()}}async invalidateUserKeys(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.userIdentities]),s=await t.userIdentities.get(e);s&&(s.keysTrackingStatus=0,t.userIdentities.set(s)),await t.complete()}async getCrossSigningKeyForUser(e,t,s,i){return await i.wrap({l:"DeviceTracker.getCrossSigningKeyForUser",id:e,usage:t},async r=>{const o=await this._storage.readTxn([this._storage.storeNames.userIdentities,this._storage.storeNames.crossSigningKeys]),c=await o.userIdentities.get(e);if(c&&c.keysTrackingStatus!==0)return await o.crossSigningKeys.get(e,t);if(!s)return;const l=await this._queryKeys([e],s,r);switch(t){case Et.Master:return l.masterKeys.get(e);case Et.SelfSigning:return l.selfSigningKeys.get(e);case Et.UserSigning:return l.userSigningKeys.get(e)}})}async writeHistoryVisibility(e,t,s,i){const r=[],o=[];return e.isTrackingMembers&&e.isEncrypted&&await i.wrap("rewriting userIdentities",async c=>{const l=await e.loadMemberList(s,c);try{const h=Array.from(l.members.values());c.set("members",h.length),await Promise.all(h.map(async a=>{Xi(a.membership,t)?await this._addRoomToUserIdentity(a.roomId,a.userId,s)&&r.push(a.userId):await this._removeRoomFromUserIdentity(a.roomId,a.userId,s)&&o.push(a.userId)}))}finally{l.release()}}),{added:r,removed:o}}async _addRoomToUserIdentity(e,t,s){const{userIdentities:i}=s,r=await i.get(t),o=kd(r,t,e);return o?(i.set(o),!0):!1}async _removeRoomFromUserIdentity(e,t,s){const{userIdentities:i,deviceKeys:r}=s,o=await i.get(t);return o?(o.roomIds=o.roomIds.filter(c=>c!==e),o.roomIds.length===0?(i.remove(t),r.removeAllForUser(t)):i.set(o),!0):!1}async _queryKeys(e,t,s){const i=await t.queryKeys({timeout:1e4,device_keys:e.reduce((a,u)=>(a[u]=[],a),{}),token:this._getSyncToken()},{log:s}).response(),r=s.wrap("master keys",a=>this._filterVerifiedCrossSigningKeys(i.master_keys,Et.Master,a)),o=s.wrap("self-signing keys",a=>this._filterVerifiedCrossSigningKeys(i.self_signing_keys,Et.SelfSigning,a)),c=s.wrap("user-signing keys",a=>this._filterVerifiedCrossSigningKeys(i.user_signing_keys,Et.UserSigning,a)),l=s.wrap("device keys",a=>this._filterVerifiedDeviceKeys(i.device_keys,a)),h=await this._storage.readWriteTxn([this._storage.storeNames.userIdentities,this._storage.storeNames.deviceKeys,this._storage.storeNames.crossSigningKeys]);try{for(const u of r.values())h.crossSigningKeys.set(u);for(const u of o.values())h.crossSigningKeys.set(u);for(const u of c.values())h.crossSigningKeys.set(u);let a=0;await Promise.all(Array.from(l.keys()).map(async u=>{let p=l.get(u);a+=p.length,p=await this._storeQueriedDevicesForUserId(u,p,h),l.set(u,p)})),s.set("devices",a)}catch(a){throw h.abort(),a}return await h.complete(),{deviceKeys:l,masterKeys:r,selfSigningKeys:o,userSigningKeys:c}}async _storeQueriedDevicesForUserId(e,t,s){const i=await s.deviceKeys.getAllDeviceIds(e);for(const l of i)t.every(h=>h.device_id!==l)&&s.deviceKeys.remove(e,l);const r=[],o=[];await Promise.all(t.map(async l=>{if(i.includes(l.device_id)){const h=await s.deviceKeys.get(l.user_id,l.device_id);if(h&&ks(h)!==ks(l)){r.push(h);return}}r.push(l),o.push(l)}));for(const l of o)s.deviceKeys.set(l);let c=await s.userIdentities.get(e);return c||(c=Pa(e)),c.keysTrackingStatus=1,s.userIdentities.set(c),r}_filterVerifiedCrossSigningKeys(e,t,s){const i=new Map;if(!e)return i;for(const[r,o]of Object.entries(e))s.wrap({l:r},c=>{this._validateCrossSigningKey(r,o,t,c)&&i.set(_o(o),o)});return i}_validateCrossSigningKey(e,t,s,i){return _o(t)!==e?(i.log({l:"user_id mismatch",userId:t.user_id}),!1):vd(t)!==s?(i.log({l:"usage mismatch",usage:t.usage}),!1):Qs(t)?!0:(i.log({l:"no ed25519 key",keys:t.keys}),!1)}_filterVerifiedDeviceKeys(e,t){const s=new Set,i=new Map;if(!e)return i;for(const[r,o]of Object.entries(e))t.wrap(r,c=>{const h=Object.entries(o).filter(([a,u])=>c.wrap(a,p=>{if(this._validateDeviceKey(r,a,u,p)){const g=_t(u);return s.has(g)?(t.log({l:"ignore device with duplicate curve25519 key",keys:u},t.level.Warn),!1):(s.add(g),!0)}else return!1})).map(([,a])=>a);i.set(r,h)});return i}_validateDeviceKey(e,t,s,i){const r=s.device_id,o=s.user_id;if(o!==e)return i.log("user_id mismatch"),!1;if(r!==t)return i.log("device_id mismatch"),!1;const c=ks(s),l=_t(s);if(typeof c!="string"||typeof l!="string")return i.log("ed25519 and/or curve25519 key invalid").set({deviceKey:s}),!1;const h=vn(this._olmUtil,o,r,c,s,i)===ne.Valid;return h||i.log({l:"ignore device with invalid signature",keys:s},i.level.Warn),h}async devicesForTrackedRoom(e,t,s){const i=await this._storage.readTxn([this._storage.storeNames.roomMembers,this._storage.storeNames.userIdentities]),r=await i.roomMembers.getAllUserIds(e);return await this._devicesForUserIdsInTrackedRoom(e,r,i,t,s)}async devicesForRoomMembers(e,t,s,i){const r=await this._storage.readTxn([this._storage.storeNames.userIdentities]);return await this._devicesForUserIdsInTrackedRoom(e,t,r,s,i)}async devicesForUsers(e,t,s){const i=await this._storage.readTxn([this._storage.storeNames.userIdentities]),r=[],o=[];return await Promise.all(e.map(async c=>{const l=await i.userIdentities.get(c);l&&l.keysTrackingStatus===1?r.push(l):(!l||l.keysTrackingStatus===0)&&o.push(c)})),this._devicesForUserIdentities(r,o,t,s)}async deviceForId(e,t,s,i){var h;const o=await(await this._storage.readTxn([this._storage.storeNames.userIdentities])).userIdentities.get(e);if((o==null?void 0:o.keysTrackingStatus)!==1){const{deviceKeys:a}=await this._queryKeys([e],s,i);return a.get(e).find(g=>g.device_id===t)}let l=await(await this._storage.readTxn([this._storage.storeNames.deviceKeys])).deviceKeys.get(e,t);if(l)i.set("existingDevice",!0);else{const a=await s.queryKeys({timeout:1e4,device_keys:{[e]:[t]},token:this._getSyncToken()},{log:i}).response(),p=(h=i.wrap("verify",v=>this._filterVerifiedDeviceKeys(a.device_keys,v)).get(e))==null?void 0:h.find(v=>v.device_id===t);if(!p)return;const g=await this._storage.readWriteTxn([this._storage.storeNames.deviceKeys]),f=await g.deviceKeys.get(e,t);if(f)l=f,i.set("existingDeviceAfterFetch",!0);else{try{g.deviceKeys.set(p),l=p,i.set("newDevice",!0)}catch(v){throw g.abort(),v}await g.complete()}}return l}async deviceForCurveKey(e,t,s,i){const r=await this._storage.readTxn([this._storage.storeNames.deviceKeys,this._storage.storeNames.userIdentities]),o=await r.userIdentities.get(e);if((o==null?void 0:o.keysTrackingStatus)!==1){const{deviceKeys:l}=await this._queryKeys([e],s,i);return l.get(e).find(u=>_t(u)===t)}return await r.deviceKeys.getByCurve25519Key(t)}async _devicesForUserIdsInTrackedRoom(e,t,s,i,r){const c=(await Promise.all(t.map(u=>s.userIdentities.get(u)))).filter(u=>u&&u.roomIds.includes(e)),l=c.filter(u=>u.keysTrackingStatus===1),h=c.filter(u=>u.keysTrackingStatus===0).map(u=>u.userId);let a=await this._devicesForUserIdentities(l,h,i,r);return a=a.filter(u=>!(u.user_id===this._ownUserId&&u.device_id===this._ownDeviceId)),a}async _devicesForUserIdentities(e,t,s,i){i.set("uptodate",e.length),i.set("outdated",t.length);let r;if(t.length){const{deviceKeys:h}=await this._queryKeys(t,s,i);r=h}const o=await this._storage.readTxn([this._storage.storeNames.deviceKeys]);let l=(await Promise.all(e.map(h=>o.deviceKeys.getAllForUserId(h.userId)))).reduce((h,a)=>h.concat(a),[]);if(r&&r.size)for(const h of r.values())l=l.concat(h);return l}async getDeviceByCurve25519Key(e,t){return await t.deviceKeys.getByCurve25519Key(e)}get ownDeviceId(){return this._ownDeviceId}}const Fa=[Cd,Ed,Rd,Td,Ad,xd,Vd,Nd,Dd,Ud,Od,Pd,Fd,Ld,Kd,Bd,$d,jd,qd];function Md(n){return{databaseName:n.name,get idbFactory(){throw new Error("unused")},get IDBKeyRange(){throw new Error("unused")},addWriteError(){}}}function Cd(n){n.createObjectStore("session",{keyPath:"key"}),n.createObjectStore("roomSummary",{keyPath:"roomId"}),n.createObjectStore("timelineFragments",{keyPath:"key"}),n.createObjectStore("timelineEvents",{keyPath:"key"}).createIndex("byEventId","eventIdKey",{unique:!0}),n.createObjectStore("roomState",{keyPath:"key"}),n.createObjectStore("pendingEvents",{keyPath:"key"})}async function Ed(n,e){const t=new Ta(n.createObjectStore("roomMembers",{keyPath:"key"})),s=e.objectStore("roomState");await _e(s.openCursor(),i=>{if(i.event.type===Ke){s.delete(i.key);const r=Q.fromMemberEvent(i.roomId,i.event);r&&t.set(r.serialize())}return Lt})}async function Rd(n,e,t){const s=e.objectStore("session");try{const r=await Me(s.get(1));if(r){s.delete(1);const{syncToken:o,syncFilterId:c,serverVersions:l}=r.value,h=new Mn(s,t);h.set("sync",{token:o,filterId:c}),h.set("serverVersions",l)}}catch(i){e.abort(),console.error("could not migrate session",i.stack)}}function Td(n){n.createObjectStore("userIdentities",{keyPath:"userId"}),n.createObjectStore("deviceIdentities",{keyPath:"key"}).createIndex("byCurve25519Key","curve25519Key",{unique:!0}),n.createObjectStore("olmSessions",{keyPath:"key"}),n.createObjectStore("inboundGroupSessions",{keyPath:"key"}),n.createObjectStore("outboundGroupSessions",{keyPath:"roomId"}),n.createObjectStore("groupSessionDecryptions",{keyPath:"key"}),n.createObjectStore("operations",{keyPath:"id"}).createIndex("byTypeAndScope","typeScopeKey",{unique:!1})}async function Ad(n,e){var r;const t=e.objectStore("roomSummary"),s=e.objectStore("roomState"),i=[];await _e(t.openCursor(),o=>(i.push(o),Lt));for(const o of i){const c=await Me(s.get(`${o.roomId}|m.room.encryption|`));c&&(o.encryption=(r=c==null?void 0:c.event)==null?void 0:r.content,delete o.isEncrypted,t.put(o))}}function xd(n){n.createObjectStore("accountData",{keyPath:"type"})}function Vd(n){n.createObjectStore("invites",{keyPath:"roomId"})}function Nd(n){n.createObjectStore("archivedRoomSummary",{keyPath:"summary.roomId"})}async function Dd(n,e){try{const t=e.objectStore("operations");t.deleteIndex("byTypeAndScope"),await _e(t.openCursor(),(s,i,r)=>{const{typeScopeKey:o}=s;delete s.typeScopeKey;const[c,l]=o.split("|");return s.scopeTypeKey=Ci(l,c),r.update(s),Lt}),t.createIndex("byScopeAndType","scopeTypeKey",{unique:!1})}catch(t){e.abort(),console.error("could not migrate operations",t.stack)}}function Ud(n){n.createObjectStore("timelineRelations",{keyPath:"key"})}function Od(){}async function Pd(n,e){const t=e.objectStore("session"),s=await Me(t.get("ssssKey"));s&&t.put({key:`${Oe}ssssKey`,value:s.value})}async function Fd(n,e,t,s){const i=e.objectStore("session"),r=new Mn(new Ma(i,Md(n)),t);r.writeE2EEIdentityToLocalStorage();const o=await r.tryRestoreE2EEIdentityFromLocalStorage(s);s.set("restored",o)}async function Ld(n,e){for(const t of n.objectStoreNames){const s=e.objectStore(t);switch(t){case"inboundGroupSessions":case"outboundGroupSessions":case"olmSessions":case"operations":continue;case"session":{await _e(s.openCursor(),(i,r,o)=>(r.startsWith(Oe)||o.delete(),Lt));break}default:{s.clear();break}}}}async function Kd(n,e,t,s){e.objectStore("inboundGroupSessions").createIndex("byBackup","backup",{unique:!1})}async function Bd(n,e,t,s){const i=e.objectStore("inboundGroupSessions");let r=0,o=0;await _e(i.openCursor(),(c,l,h)=>(c.session?(c.backup=Vr.NotBackedUp,c.source=Hi.DeviceMessage,h.update(c),r+=1):o+=1,Lt)),s.set("countWithoutSession",o),s.set("countWithSession",r)}function $d(n){n.createObjectStore("calls",{keyPath:"key"})}async function jd(n,e,t,s){n.createObjectStore("crossSigningKeys",{keyPath:"key"}),n.deleteObjectStore("deviceIdentities"),n.createObjectStore("deviceKeys",{keyPath:"key"}).createIndex("byCurve25519Key","curve25519Key",{unique:!0});const r=e.objectStore("userIdentities");let o=0;await _e(r.openCursor(),(c,l,h)=>(delete c.deviceTrackingStatus,delete c.crossSigningKeys,c.keysTrackingStatus=Oa.Outdated,h.update(c),o+=1,Lt)),s.set("marked_outdated",o)}function qd(n){n.createObjectStore("sharedSecrets",{keyPath:"key"})}async function Hd(n){const e="hydrogen_webkit_test_inactive_txn_bug";try{const t=await In(e,r=>{r.createObjectStore("test",{keyPath:"key"})},1,n),s=t.transaction(["test"],"readonly");await Me(s.objectStore("test").get("somekey")),await new Promise(r=>setTimeout(r,0));const i=t.transaction(["test"],"readwrite");await Promise.resolve(),i.objectStore("test").add({key:"somekey",value:"foo"}),await Pi(i),t.close()}catch(t){if(t.name==="TransactionInactiveError")return!0}return!1}const La=n=>`hydrogen_session_${n}`,$r=function(n,e,t,s){const i=(r,o,c,l)=>Gd(r,o,c,l,t,s);return In(La(n),i,Fa.length,e)};async function Wd(){var e,t;const n=this;if((t=(e=n==null?void 0:n.navigator)==null?void 0:e.storage)!=null&&t.persist)return await n.navigator.storage.persist();if(n!=null&&n.document.requestStorageAccess)try{return await n.document.requestStorageAccess(),!0}catch(s){return console.warn("requestStorageAccess threw an error:",s),!1}else return!1}class zd{constructor(e,t=window.indexedDB,s=window.IDBKeyRange,i=window.localStorage){this._serviceWorkerHandler=e,this._idbFactory=t,this._IDBKeyRange=s,this._localStorage=i}async create(e,t){var r;await((r=this._serviceWorkerHandler)==null?void 0:r.preventConcurrentSessionAccess(e)),Wd().then(o=>{o||t.log("no persisted storage, database can be evicted by browser",t.level.Warn)});const s=await Hd(this._idbFactory),i=await $r(e,this._idbFactory,this._localStorage,t);return new Jh(i,this._idbFactory,this._IDBKeyRange,s,this._localStorage,t.logger)}async delete(e){const t=La(e);try{kh(this._localStorage,t)}catch{}try{const s=this._idbFactory.deleteDatabase(t);await Me(s)}catch{}}async export(e,t){const s=await $r(e,this._idbFactory,this._localStorage,t);return await Qh(s)}async import(e,t,s){const i=await $r(e,this._idbFactory,this._localStorage,s);return await Xh(i,t)}}async function Gd(n,e,t,s,i,r){const o=t||0;return r.wrap({l:"storage migration",oldVersion:t,version:s},async c=>{for(let l=o;lh(n,e,i,a))}})}class Ka{constructor({roomId:e,ownUserId:t,fragmentIdComparer:s}){this._roomId=e,this._ownUserId=t,this._fragmentIdComparer=s}async writeRelation(e,t,s){const{relatedEventId:i}=e;if(i){const r=Xt(e.event);r&&r.rel_type&&t.timelineRelations.add(this._roomId,r.event_id,r.rel_type,e.id);const o=await t.timelineEvents.getByEventId(this._roomId,i);if(o){const c=await this._applyRelation(e,o,t,s);if(c)return c.map(l=>(t.timelineEvents.update(l),new Ye(l,this._fragmentIdComparer)))}}return null}async writeGapRelation(e,t,s,i){const r=new Ye(e,this._fragmentIdComparer),o=await this.writeRelation(r,s,i);if(t.isBackward&&!Xr(e.event)){const c=await s.timelineRelations.getAllForTarget(this._roomId,r.id);if(c.length)for(const l of c){const h=await s.timelineEvents.getByEventId(this._roomId,l.sourceEventId);if(h){const a=new Ye(h,this._fragmentIdComparer);await this._applyRelation(a,e,s,i)}}}return o}async _applyRelation(e,t,s,i){if(e.eventType===gt)return i.wrap("redact",async r=>{const o=t.event,c=Xt(o);if(this._applyRedaction(e.event,t,s,r)){const h=[t];if(c){const a=await this._reaggregateRelation(o,c,s,r);a&&h.push(a)}return h}return null});{const r=Xt(e.event);if(r&&!Xr(t.event)&&r.rel_type===ss&&i.wrap("react",l=>this._aggregateAnnotation(e.event,t,l)))return[t]}return null}_applyRedaction(e,t,s,i){const r=t.event;i.set("redactionId",e.event_id),i.set("id",r.event_id);const o=Xt(r);return o&&o.rel_type&&s.timelineRelations.remove(this._roomId,o.event_id,o.rel_type,r.event_id),s.timelineRelations.removeAllForTarget(this._roomId,r.event_id),uh(e,r),delete t.annotations,!0}_aggregateAnnotation(e,t){const s=Xt(e);if(!s)return!1;let{annotations:i}=t;i||(t.annotations=i={});let r=i[s.key];r||(i[s.key]=r={count:0,me:!1,firstTimestamp:Number.MAX_SAFE_INTEGER});const o=e.sender===this._ownUserId;return r.me=r.me||o,r.count+=1,r.firstTimestamp=Math.min(r.firstTimestamp,e.origin_server_ts),!0}async _reaggregateRelation(e,t,s,i){return t.rel_type===ss?i.wrap("reaggregate annotations",r=>this._reaggregateAnnotation(t.event_id,t.key,s,r)):null}async _reaggregateAnnotation(e,t,s,i){const r=await s.timelineEvents.getByEventId(this._roomId,e);if(!r||!r.annotations)return null;i.set("id",e);const o=await s.timelineRelations.getForTargetAndType(this._roomId,e,ss);return i.set("relations",o.length),delete r.annotations[t],Yd(r.annotations)&&delete r.annotations,await Promise.all(o.map(async c=>{const l=await s.timelineEvents.getByEventId(this._roomId,c.sourceEventId);l||i.log({l:"missing annotation",id:c.sourceEventId}),Xt(l.event).key===t&&this._aggregateAnnotation(l.event,r,i)})),r}}function Yd(n){for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}class Kt{constructor(e){this.isForward=e}get isBackward(){return!this.isForward}asApiString(){return this.isForward?"f":"b"}reverse(){return this.isForward?Kt.Backward:Kt.Forward}static get Forward(){return Jd}static get Backward(){return Qd}}const Jd=new Kt(!0),Qd=new Kt(!1);class it extends fa{constructor(e,t,s){super(s),this._fragment=e,this._isFragmentStart=t}static start(e,t){return new it(e,!0,t)}static end(e,t){return new it(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?ce.minStorageKey:ce.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 Sn(this.linkedFragmentId)}get direction(){return this.started?Kt.Backward:Kt.Forward}withUpdatedFragment(e){return new it(e,this._isFragmentStart,this._fragmentIdComparer)}createNeighbourEntry(e){return new it(e,!this._isFragmentStart,this._fragmentIdComparer)}addLocalRelation(){}removeLocalRelation(){}}function Xd(n){const e=new Set;return n.filter(t=>e.has(t.event_id)?!1:(e.add(t.event_id),!0))}class Zd{constructor({roomId:e,fragmentIdComparer:t,memberWriter:s,relationWriter:i}){this._roomId=e,this._memberWriter=s,this._relationWriter=i,this._fragmentIdComparer=t,this._lastLiveKey=null}async load(e,t){const s=await e.timelineFragments.liveFragment(this._roomId);if(s){const[i]=await e.timelineEvents.lastEvents(this._roomId,s.id,1),r=i?i.eventIndex:pe.defaultLiveKey.eventIndex;this._lastLiveKey=new pe(s.id,r)}this._lastLiveKey&&t.set("live key",this._lastLiveKey.toString())}async _createLiveFragment(e,t){const s=await e.timelineFragments.liveFragment(this._roomId);if(s)return s;{t||(t=null);const i={roomId:this._roomId,id:pe.defaultLiveKey.fragmentId,previousId:null,nextId:null,previousToken:t,nextToken:null};return e.timelineFragments.add(i),this._fragmentIdComparer.add(i),i}}async _replaceLiveFragment(e,t,s,i){const r=await i.timelineFragments.get(this._roomId,e);if(!r)throw new Error(`old live fragment doesn't exist: ${e}`);r.nextId=t,i.timelineFragments.update(r);const o={roomId:this._roomId,id:t,previousId:e,nextId:null,previousToken:s,nextToken:null};return i.timelineFragments.add(o),this._fragmentIdComparer.append(t,e),{oldFragment:r,newFragment:o}}async _ensureLiveFragment(e,t,s,i,r){if(e){if(s.limited){const o=e.fragmentId;e=e.nextFragmentKey();const{oldFragment:c,newFragment:l}=await this._replaceLiveFragment(o,e.fragmentId,s.prev_batch,i);t.push(it.end(c,this._fragmentIdComparer)),t.push(it.start(l,this._fragmentIdComparer)),r.log({l:"live fragment",limited:!0,id:e.fragmentId})}}else{let o=await this._createLiveFragment(i,s.prev_batch);e=new pe(o.id,pe.defaultLiveKey.eventIndex),t.push(it.start(o,this._fragmentIdComparer)),r.log({l:"live fragment",first:!0,id:e.fragmentId})}return e}async _writeStateEvents(e,t,s){let i=0;for(const r of e)r.type!==Ke&&(t.roomState.set(this._roomId,r),i+=1);s.set("stateEvents",i)}async _writeTimeline(e,t,s,i,r,o){const c=[],l=[];if(e!=null&&e.length){i=await this._ensureLiveFragment(i,c,t,r,o),o.set("timelineEvents",e.length);let h=0;for(const a of e){i=i.nextKey();const u=Sa(i,this._roomId,a);let p=await s.lookupMemberAtEvent(a.sender,a,r);if(p&&(u.displayName=p.displayName,u.avatarUrl=p.avatarUrl),!await r.timelineEvents.tryInsert(u,o))continue;const f=new Ye(u,this._fragmentIdComparer);c.push(f);const v=await this._relationWriter.writeRelation(f,r,o);v&&l.push(...v),typeof a.state_key=="string"&&a.type!==Ke&&(h+=1,r.roomState.set(this._roomId,a))}o.set("timelineStateEventCount",h)}return{currentKey:i,entries:c,updatedEntries:l}}async _handleRejoinOverlap(e,t,s){if(this._lastLiveKey){const{fragmentId:i}=this._lastLiveKey,[r]=await t.timelineEvents.lastEvents(this._roomId,i,1);if(r){const o=r.event.event_id,{events:c}=e,l=c.findIndex(h=>h.event_id===o);if(l!==-1)return s.set("overlap_event_id",o),Object.assign({},e,{limited:!1,events:c.slice(l+1)})}}return e.limited?e:(s.set("force_limited_without_overlap",!0),Object.assign({},e,{limited:!0}))}async writeSync(e,t,s,i,r){let{timeline:o}=e;r.set("isRejoin",t),t&&(o=await this._handleRejoinOverlap(o,i,r));let c;Array.isArray(o==null?void 0:o.events)&&(c=Xd(o.events));const{state:l}=e;let h;Array.isArray(l==null?void 0:l.events)&&(h=l.events);const a=this._memberWriter.prepareMemberSync(h,c,s);h&&await this._writeStateEvents(h,i,r);const{currentKey:u,entries:p,updatedEntries:g}=await this._writeTimeline(c,o,a,this._lastLiveKey,i,r),f=await a.write(i);return{entries:p,updatedEntries:g,newLiveKey:u,memberChanges:f,memberSync:a}}afterSync(e){this._lastLiveKey=e}get lastMessageKey(){return this._lastLiveKey}}class Ba{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 s=t?this._entries.findIndex(t):-1;this._entries.unshift(e),s===-1?this._entries.length>this.limit&&(s=this._entries.length-1):s+=1,s!==-1&&(this.onEvictEntry(this._entries[s]),this._entries.splice(s,1))}onEvictEntry(e){}}class $a extends Ba{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,s=>this._keyFn(s)===t)}}class eu{constructor(e){this._roomId=e,this._cache=new $a(5,t=>t.userId)}prepareMemberSync(e,t,s){return new tu(this,e,t,s)}async _writeMember(e,t){let s=this._cache.get(e.userId);if(!s){const i=await t.roomMembers.get(this._roomId,e.userId);i&&(s=new Q(i))}if(!s||!s.equals(e))return t.roomMembers.set(e.serialize()),this._cache.set(e),new ka(e,s==null?void 0:s.membership)}async lookupMember(e,t){let s=this._cache.get(e);if(!s){const i=await t.roomMembers.get(this._roomId,e);i&&(s=new Q(i),this._cache.set(s))}return s}}class tu{constructor(e,t,s,i){this._memberWriter=e,this._timelineEvents=s,this._hasFetchedMembers=i,this._newStateMembers=null,t&&(this._newStateMembers=this._stateEventsToMembers(t))}get _roomId(){return this._memberWriter._roomId}_stateEventsToMembers(e){let t;for(const s of e)if(s.type===Ke){const i=Q.fromMemberEvent(this._roomId,s);i&&(t||(t=new Map),t.set(i.userId,i))}return t}_timelineEventsToMembers(e){let t;for(let s=e.length-1;s>=0;s--){const i=e[s],r=i.state_key;if(i.type===Ke&&!(t!=null&&t.has(r))){const o=Q.fromMemberEvent(this._roomId,i);o&&(t||(t=new Map),t.set(o.userId,o))}}return t}async lookupMemberAtEvent(e,t,s){var r;let i;return this._timelineEvents&&(i=this._findPrecedingMemberEventInTimeline(e,t),i)||(i=(r=this._newStateMembers)==null?void 0:r.get(e),i)?i:await this._memberWriter.lookupMember(e,s)}async write(e){const t=new Map;let s;if(this._timelineEvents&&(s=this._timelineEventsToMembers(this._timelineEvents)),this._newStateMembers){for(const i of this._newStateMembers.values())if(!(s!=null&&s.has(i.userId))){const r=await this._memberWriter._writeMember(i,e);r&&(!this._hasFetchedMembers&&!r.previousMembership&&(r.previousMembership=i.membership),t.set(r.userId,r))}}if(s)for(const i of s.values()){const r=await this._memberWriter._writeMember(i,e);r&&t.set(r.userId,r)}return t}_findPrecedingMemberEventInTimeline(e,t){let s=-1;for(let i=this._timelineEvents.length-1;i>=0;i--)if(this._timelineEvents[i].event_id===t.event_id){s=i;break}for(let i=s-1;i>=0;i--){const r=this._timelineEvents[i];if(r.type===Ke&&r.state_key===e){const o=Q.fromMemberEvent(this._roomId,r);if(o)return o}}}}class su{constructor({roomId:e,storage:t,fragmentIdComparer:s,relationWriter:i}){this._roomId=e,this._storage=t,this._fragmentIdComparer=s,this._relationWriter=i}async _findOverlappingEvents(e,t,s,i){const r=t.map(h=>h.event_id),o=await s.timelineEvents.getEventKeysForIds(this._roomId,r);i.set("existingEvents",o.size);const c=t.filter(h=>!o.has(h.event_id));i.set("nonOverlappingEvents",c.length);let l;if(e.hasLinkedFragment){i.set("linkedFragmentId",e.linkedFragmentId);for(const h of o.values())if(h.fragmentId===e.linkedFragmentId){i.set("foundLinkedFragment",!0);const a=await s.timelineFragments.get(this._roomId,e.linkedFragmentId);l=e.createNeighbourEntry(a);break}}return{nonOverlappingEvents:c,neighbourFragmentEntry:l}}async _findFragmentEdgeEventKey(e,t){const{fragmentId:s,direction:i}=e,r=await this._findFragmentEdgeEvent(s,i,t);return r?new pe(r.fragmentId,r.eventIndex):pe.defaultFragmentKey(e.fragmentId)}async _findFragmentEdgeEvent(e,t,s){if(t.isBackward){const[i]=await s.timelineEvents.firstEvents(this._roomId,e,1);return i}else{const[i]=await s.timelineEvents.lastEvents(this._roomId,e,1);return i}}async _storeEvents(e,t,s,i,r,o){const c=[],l=[];let h=t;for(let a=0;a=0&&h=0&&hnew Ye(u,i));if(o=lh(o,a,t),o.length{const c=await this._storage.readTxn(this.readTxnStores);return await this._readFrom(e,t,s,r,c,o)},i)}readFromEnd(e,t=null,s){return new po(async(i,r)=>{const o=t||await this._storage.readTxn(this.readTxnStores),c=await o.timelineFragments.liveFragment(this._roomId);let l;if(!c)l=[];else{this._fragmentIdComparer.add(c);const h=it.end(c,this._fragmentIdComparer),a=h.asEventKey();l=await this._readFrom(a,Kt.Backward,e,i,o,r),l.unshift(h)}return l},s)}async readById(e,t){let s=[this._storage.storeNames.timelineEvents];this._decryptEntries&&s.push(this._storage.storeNames.inboundGroupSessions);const i=await this._storage.readTxn(s),r=await i.timelineEvents.getByEventId(this._roomId,e);if(r){const o=new Ye(r,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o],i,t).complete(),o}}async _readFrom(e,t,s,i,r,o){const c=await iu(this._roomId,e,t,s,this._fragmentIdComparer,r);if(this._decryptEntries){i.decryptRequest=this._decryptEntries(c,r,o);try{await i.decryptRequest.complete()}finally{i.decryptRequest=null}}return c}}class ru extends Ye{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 qa{constructor(e){this._retentionCount=1,this._freeCallback=e}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._freeCallback()}}class nu{constructor(e){this._userId=e}get id(){return this._userId}}class Mr extends qa{constructor({roomId:e,storage:t,closeCallback:s,fragmentIdComparer:i,pendingEvents:r,clock:o,powerLevelsObservable:c,hsApi:l}){super(()=>{this.dispose()}),this._roomId=e,this._storage=t,this._closeCallback=s,this._fragmentIdComparer=i,this._disposables=new li,this._pendingEvents=r,this._clock=o,this._remoteEntries=new fn((h,a)=>h.compare(a)),this._ownMember=null,this._timelineReader=new ja({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}),this._readerRequest=null,this._allEntries=null,this._contextEntriesNotInTimeline=new Map,this._decryptEntries=null,this._hsApi=l,this.initializePowerLevels(c)}initializePowerLevels(e){e&&(this._powerLevels=e.get(),this._disposables.track(e.subscribe(t=>this._powerLevels=t)))}async load(e,t,s){const i=await this._storage.readTxn(this._timelineReader.readTxnStores.concat(this._storage.storeNames.roomMembers,this._storage.storeNames.roomState)),r=await i.roomMembers.get(this._roomId,e.id);r?this._ownMember=new Q(r):this._ownMember=Q.fromUserId(this._roomId,e.id,t);const o=this._disposables.track(this._timelineReader.readFromEnd(20,i,s));try{const c=await o.complete();this._loadContextEntriesWhereNeeded(c),this._setupEntries(c)}finally{this._disposables.disposeTracked(o)}}_setupEntries(e){this._remoteEntries.setManySorted(e),this._pendingEvents?this._localEntries=new ul(this._pendingEvents,t=>this._mapPendingEventToEntry(t),(t,s)=>{t.notifyUpdate(s)},t=>this._applyAndEmitLocalRelationChange(t,s=>s.removeLocalRelation(t))):this._localEntries=new gn,this._allEntries=new ca(this._remoteEntries,this._localEntries)}async _mapPendingEventToEntry(e){let t;e.eventType===gt&&(t=await this._getOrLoadEntry(e.relatedTxnId,e.relatedEventId));const s=new ah({pendingEvent:e,member:this._ownMember,clock:this._clock,redactingEntry:t});return this._loadContextEntriesWhereNeeded([s]),this._applyAndEmitLocalRelationChange(s,i=>i.addLocalRelation(s)),s}_applyAndEmitLocalRelationChange(e,t){var i,r;const s=o=>{const c=t(o);return c||!1};if(this._findAndUpdateEntryById(e.pendingEvent.relatedTxnId,e.relatedEventId,s),e.redactingEntry){const o=(i=e.redactingEntry.pendingEvent)==null?void 0:i.relatedTxnId;this._findAndUpdateEntryById(o,e.redactingEntry.relatedEventId,s),(r=e.redactingEntry.contextForEntries)==null||r.forEach(c=>this._emitUpdateForEntry(c,"contextEntry"))}}_findAndUpdateEntryById(e,t,s){let i=!1;e&&(i=this._localEntries.findAndUpdate(r=>r.id===e,s)),!i&&t&&this._remoteEntries.findAndUpdate(r=>r.id===t,s)}async getOwnAnnotationEntry(e,t){const s=await this._storage.readWriteTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations]),i=await s.timelineRelations.getForTargetAndType(this._roomId,e,ss);for(const r of i){const o=await s.timelineEvents.getByEventId(this._roomId,r.sourceEventId);if(o&&o.event.sender===this._ownMember.userId&&Xt(o.event).key===t){const c=new Ye(o,this._fragmentIdComparer);return this._addLocalRelationsToNewRemoteEntries([c]),c}}return null}updateOwnMember(e){this._ownMember=e}_addLocalRelationsToNewRemoteEntries(e){var t;if(!!((t=this._localEntries)!=null&&t.hasSubscriptions))for(const s of this._localEntries){if(s.relatedEventId){const i=e.find(r=>r.id===s.relatedEventId);i==null||i.addLocalRelation(s)}if(s.redactingEntry){const i=s.redactingEntry.relatedEventId,r=e.find(o=>o.id===i);r==null||r.addLocalRelation(s)}}}static _entryUpdater(e,t){var s;return(s=e.contextForEntries)==null||s.forEach(i=>i.setContextEntry(t)),t.updateFrom(e),t}replaceEntries(e){var t;this._addLocalRelationsToNewRemoteEntries(e);for(const s of e)try{this._remoteEntries.getAndUpdate(s,Mr._entryUpdater);const i=this._contextEntriesNotInTimeline.get(s.id);i&&(Mr._entryUpdater(i,s),this._contextEntriesNotInTimeline.set(s.id,s)),(t=s.contextForEntries)==null||t.forEach(r=>this._emitUpdateForEntry(r,"contextEntry"))}catch(i){if(i.name==="CompareError")continue;throw i}}addEntries(e){this._addLocalRelationsToNewRemoteEntries(e),this._updateEntriesFetchedFromHomeserver(e),this._moveEntryToRemoteEntries(e),this._loadContextEntriesWhereNeeded(e),this._remoteEntries.setManySorted(e)}_updateEntriesFetchedFromHomeserver(e){var t;for(const s of e){const i=this._contextEntriesNotInTimeline.get(s.relatedEventId);(i==null?void 0:i.isNonPersisted)&&(i==null?void 0:i.addLocalRelation(s))&&((t=i.contextForEntries)==null||t.forEach(r=>this._emitUpdateForEntry(r,"contextEntry")))}}_moveEntryToRemoteEntries(e){for(const t of e){const s=this._contextEntriesNotInTimeline.get(t.id);s&&(s.contextForEntries.forEach(i=>{i.setContextEntry(t),this._emitUpdateForEntry(i,"contextEntry")}),this._contextEntriesNotInTimeline.delete(t.id))}}_emitUpdateForEntry(e,t){const s=e.isPending?e.id:null,i=e.isPending?null:e.id;this._findAndUpdateEntryById(s,i,()=>t)}async _loadContextEntriesWhereNeeded(e){for(const t of e){if(!t.contextEventId)continue;const s=t.contextEventId;let i=e.find(r=>r.id===s);i||(i=this._findLoadedEventById(s)),i?(t.setContextEntry(i),this._emitUpdateForEntry(i,"context-added")):this._loadContextEntryNotInTimeline(t)}}async _loadContextEntryNotInTimeline(e){const t=e.contextEventId;let s=await this._getEventFromStorage(t);s||(s=await this._getEventFromHomeserver(t)),s&&(this._contextEntriesNotInTimeline.set(t,s),e.setContextEntry(s),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(),s=t.event.sender,i=t.state.find(c=>c.type===Ke&&c.user_id===s),r={event:t.event,displayName:i.content.displayname,avatarUrl:i.content.avatar_url},o=new ru(r,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(i=>!!i.eventType);if(!t)return!0;const s=this._disposables.track(this._timelineReader.readFrom(t.asEventKey(),Kt.Backward,e));try{const i=await s.complete();return this.addEntries(i),i.lengthnew Q(i))}async function au({summary:n,syncToken:e,roomId:t,hsApi:s,storage:i,setChangedMembersMap:r},o){const c=new Map;r(c);const l=await s.members(t,{at:e},{log:o}).response(),h=await i.readWriteTxn([i.storeNames.roomSummary,i.storeNames.roomMembers]);let a,u;try{a=n.writeHasFetchedMembers(!0,h);const{roomMembers:p}=h,g=l.chunk;if(!Array.isArray(g))throw new Error("malformed");o.set("members",g.length),u=await Promise.all(g.map(async f=>{const v=f==null?void 0:f.state_key;if(!v)throw new Error("malformed");const M=c.get(v);if(M)return M;{const R=Q.fromMemberEvent(t,f);return R&&p.set(R.serialize()),R}}))}catch(p){throw h.abort(),p}finally{r(null)}return await h.complete(),n.applyChanges(a),u}async function cu(n,e){const{summary:t}=n;return t.data.hasFetchedMembers?ou(n):e.wrapOrRun(n.log,"fetchMembers",s=>au(n,s))}async function lu(n,e){const t=await hu(n),{summary:s}=n;return!s.data.hasFetchedMembers&&!t?e.wrapOrRun(n.log,"fetchMember",i=>du(n,i)):t}async function hu({roomId:n,userId:e,storage:t}){const i=await(await t.readTxn([t.storeNames.roomMembers])).roomMembers.get(n,e);return i?new Q(i):null}async function du({roomId:n,userId:e,hsApi:t,storage:s},i){let r;try{r=await t.state(n,"m.room.member",e,{log:i}).response()}catch(l){if(l.name==="HomeServerError"&&l.errcode==="M_NOT_FOUND")return null;throw l}const o=new Q({roomId:n,userId:e,membership:r.membership,avatarUrl:r.avatar_url,displayName:r.displayname}),c=await s.readWriteTxn([s.storeNames.roomMembers]);try{c.roomMembers.set(o.serialize())}catch(l){throw c.abort(),l}return await c.complete(),o}class uu extends qa{constructor({members:e,closeCallback:t}){super(t),this._members=new Dt;for(const s of e)this._members.add(s.userId,s)}afterSync(e){for(const[t,s]of e.entries())this._members.set(t,s.member)}get members(){return this._members}}function tn(n,e,t){const s=e.joinCount+e.inviteCount-1;if(n.length>=s)if(n.length>1){const i=n[n.length-1];return n.slice(0,n.length-1).map(o=>o.name).join(", ")+" and "+i.name}else{const i=n[0];return i?i.name:(t.log({l:"could get get other member name",length:n.length,otherMember:!!i,otherMemberMembership:i==null?void 0:i.membership}),"Unknown DM Name")}else return n.lengthi.name).join(", ")+` and ${s} others`:null}class Rn{constructor(e){this._roomId=e,this._members=new Map}async calculateChanges(e,t,s){const i=new Map,r=[];for(const o of this._members.keys())e.indexOf(o)===-1&&r.push(o);for(const[o,c]of t.entries())(this._members.has(o)||e.indexOf(o)!==-1)&&i.set(o,c.member);for(const o of e)if(!this._members.has(o)&&!i.has(o)){const c=await s.roomMembers.get(this._roomId,o);if(c){const l=new Q(c);i.set(l.userId,l)}}return{updatedHeroMembers:i.values(),removedUserIds:r}}applyChanges({updatedHeroMembers:e,removedUserIds:t},s,i){for(const o of t)this._members.delete(o);for(const o of e)t.includes(o.userId)||this._members.set(o.userId,o);const r=Array.from(this._members.values()).sort((o,c)=>o.name.localeCompare(c.name));this._roomName=tn(r,s,i)}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 mu{constructor(e){this._map=new Map,this._notifyEmpty=e}observe(e,t=null){let s=this._map.get(e);return s||(s=new _u(this,t,e),this._map.set(e,s)),s}updateEvents(e){for(let t=0;t{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 pu(n){return n||Eh.item}const gu="m.room.power_levels",fu=50;class gr{constructor({powerLevelEvent:e,createEvent:t,ownUserId:s,membership:i}){this._plEvent=e,this._createEvent=t,this._ownUserId=s,this._membership=i}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,s,i,r;if(this._plEvent){let o=(s=(t=this._plEvent.content)==null?void 0:t.users)==null?void 0:s[e];if(typeof o!="number"&&(o=(i=this._plEvent.content)==null?void 0:i.users_default),typeof o=="number")return o}else if(this._createEvent&&e===((r=this._createEvent.content)==null?void 0:r.creator))return 100;return 0}_getActionLevel(e){var s,i;const t=(i=(s=this._plEvent)==null?void 0:s.content)==null?void 0:i[e];return typeof t=="number"?t:fu}_getEventTypeLevel(e){var s,i,r,o,c;const t=(r=(i=(s=this._plEvent)==null?void 0:s.content)==null?void 0:i.events)==null?void 0:r[e];if(typeof t=="number")return t;{const l=(c=(o=this._plEvent)==null?void 0:o.content)==null?void 0:c.events_default;return typeof l=="number"?l:0}}}class yu extends Dt{constructor(e){super(),this.type=e}async load(e,t){const s=await t.roomState.getAllForType(e,this.type);for(let i=0;i{this._roomStateObservers.delete(e)})}async _eventIdsToEntries(e,t){const s=[];return await Promise.all(e.map(async i=>{const r=await t.timelineEvents.getByEventId(this._roomId,i);r&&s.push(new Ye(r,this._fragmentIdComparer))})),s}_getAdditionalTimelineRetryEntries(e,t){let s=this._roomEncryption.filterUndecryptedEventEntriesForKeys(this._timeline.remoteEntries,t);const i=e.reduce((r,o)=>(r.add(o.id),r),new Set);return s=s.filter(r=>!i.has(r.id)),s}async notifyRoomKey(e,t,s){var o;if(!this._roomEncryption)return;const i=await this._storage.readTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.inboundGroupSessions]);let r=await this._eventIdsToEntries(t,i);if(this._timeline){const c=this._getAdditionalTimelineRetryEntries(r,[e]);r=r.concat(c)}if(r.length){await this._decryptEntries(ts.Retry,r,i,s).complete(),(o=this._timeline)==null||o.replaceEntries(r);const l=this._summary.data.applyTimelineEntries(r,!1,!1);await this._summary.writeAndApplyData(l,this._storage)&&this._emitUpdate()}}_setEncryption(e){return e&&!this._roomEncryption?(this._roomEncryption=e,this._timeline&&this._timeline.enableEncryption(this._decryptEntries.bind(this,ts.Timeline)),!0):!1}_decryptEntries(e,t,s,i=null){return new bu(async(o,c)=>{if(s||(s=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions])),o.cancelled)return;const l=t.filter(f=>f.eventType===vu).map(f=>f.event);if(o.preparation=await this._roomEncryption.prepareDecryptAll(l,null,e,s),o.cancelled)return;const h=await o.preparation.decrypt();if(o.preparation=null,o.cancelled)return;const a=[this._storage.storeNames.groupSessionDecryptions],u=this._isTimelineOpen;u&&a.push(this._storage.storeNames.deviceKeys);const p=await this._storage.readWriteTxn(a);let g;try{g=await h.write(p,c),u&&await g.verifyKnownSenders(p)}catch(f){throw p.abort(),f}await p.complete(),g.applyToEntries(t),this._observedEvents&&this._observedEvents.updateEvents(t),u&&g.hasUnverifiedSenders&&c.wrapDetached("fetch unknown senders keys",async f=>{var R,N;const v=await g.fetchAndVerifyRemainingSenders(this._hsApi,f),M=[];v.applyToEntries(t,F=>M.push(F)),(R=this._timeline)==null||R.replaceEntries(M),(N=this._observedEvents)==null||N.updateEvents(M)})},pu(i))}async _getSyncRetryDecryptEntries(e,t,s){let r=(await Promise.all(e.map(async o=>{const c=await t.getEventIdsForMissingKey(o,s);if(c)return this._eventIdsToEntries(c,s)}))).reduce((o,c)=>c?o.concat(c):o,[]);if(this._timeline){const c=this._getAdditionalTimelineRetryEntries(r,e).map(l=>l.clone());r=r.concat(c)}return r}async load(e,t,s){s.set("id",this.id);try{if(e&&this._summary.load(e),this._summary.data.encryption){const i=this._createRoomEncryption(this,this._summary.data.encryption);this._setEncryption(i)}if(this._summary.data.needsHeroes){this._heroes=new Rn(this._roomId);const i=await this._heroes.calculateChanges(this._summary.data.heroes,[],t);this._heroes.applyChanges(i,this._summary.data,s)}}catch(i){throw new ha(`Could not load room ${this._roomId}`,i)}}async observeMember(e){this._observedMembers||(this._observedMembers=new Map);const t=this._observedMembers.get(e);if(t)return t;const s=await lu({summary:this._summary,roomId:this._roomId,userId:e,storage:this._storage,hsApi:this._hsApi},this._platform.logger);if(!s)return null;const i=new Ui(s,()=>this._observedMembers.delete(e));return this._observedMembers.set(e,i),i}async loadMemberList(e=void 0,t=null){if(this._memberList)return this._memberList.retain(),this._memberList;{const s=await cu({summary:this._summary,roomId:this._roomId,hsApi:this._hsApi,storage:this._storage,txn:e,syncToken:this._getSyncToken(),setChangedMembersMap:i=>this._changedMembersDuringSync=i,log:t},this._platform.logger);return this._memberList=new uu({members:s,closeCallback:()=>{this._memberList=null}}),this._memberList}}fillGap(e,t,s=null){return this._platform.logger.wrapOrRun(s,"fillGap",async i=>{if(i.set("id",this.id),i.set("fragment",e.fragmentId),i.set("dir",e.direction.asApiString()),e.edgeReached){i.set("edgeReached",!0);return}const r=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:i}).response(),o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents,this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations,this._storage.storeNames.timelineFragments]);let c,l;try{c=await this._writeGapFill(r.chunk,o,i);const h=new Ka({roomId:this._roomId,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});l=await new su({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,relationWriter:h}).writeFragmentFill(e,r,e.token,o,i)}catch(h){throw o.abort(),h}await o.complete(),this._roomEncryption&&await this._decryptEntries(ts.Timeline,l.entries,null,i).complete();for(const h of l.fragments)this._fragmentIdComparer.add(h);c&&this._applyGapFill(c),this._timeline&&(this._timeline.replaceEntries(l.updatedEntries),this._timeline.addEntries(l.entries))})}async _writeGapFill(e,t,s){}_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}get user(){return this._user}isDirectMessageForUserId(e){if(this._summary.data.dmUserId===e)return!0;{const{heroes:t,joinCount:s,inviteCount:i}=this._summary.data;if(t&&t.includes(e)&&s+i===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 gr({powerLevelEvent:t.event,ownUserId:this._user.id,membership:this.membership});const s=await e.roomState.get(this._roomId,"m.room.create","");if(s)return new gr({createEvent:s.event,ownUserId:this._user.id,membership:this.membership});{const i=this.membership;return new gr({ownUserId:this._user.id,membership:i})}}async observePowerLevels(){this._powerLevelLoading&&await this._powerLevelLoading;let e=this._powerLevels;if(!e){this._powerLevelLoading=this._loadPowerLevels();const t=await this._powerLevelLoading;e=new Ui(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",s=>this._roomEncryption.restoreMissingSessionsFromBackup(this._timeline.remoteEntries,s))}get _isTimelineOpen(){return!!this._timeline}_emitUpdate(){this.emit("change"),this._emitCollectionChange(this)}async openTimeline(e=null){return await this._platform.logger.wrapOrRun(e,"open timeline",async t=>{this._timelineLoadPromise&&await this._timelineLoadPromise;let s;if(this._timelineLoadPromise=new Promise(i=>{s=()=>{this._timelineLoadPromise=null,i()}}),t.set("id",this.id),this._timeline)return t.log({l:"Returning existing timeline"}),s(),this._timeline.retain(),this._timeline;this._timeline=new Mr({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,ts.Timeline)),await this._timeline.load(this._user,this.membership,t)}catch(i){throw this._timeline.dispose(),i}finally{s()}return this._timeline.retain(),this._timeline})}_getPendingEvents(){return null}observeEvent(e){this._observedEvents||(this._observedEvents=new mu(()=>{this._observedEvents=null}));let t=null;this._timeline&&(t=this._timeline.getByEventId(e));const s=this._observedEvents.observe(e,t);return t||this._readEventById(e).then(i=>{s.update(i)}).catch(i=>{console.warn(`could not load event ${e} from storage`,i)}),s}async _readEventById(e){return await new ja({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}).readById(e)}dispose(){var e;(e=this._roomEncryption)==null||e.dispose()}}class bu{constructor(e,t){this._cancelled=!1,this.preparation=null,this._promise=t.wrap("decryptEntries",s=>e(this,s))}complete(){return this._promise}get cancelled(){return this._cancelled}dispose(){this._cancelled=!0,this.preparation&&this.preparation.dispose()}}class Su{constructor({roomId:e,storage:t,hsApi:s,pendingEvents:i}){i=i||[],this._roomId=e,this._storage=t,this._hsApi=s,this._pendingEvents=new fn((r,o)=>r.queueIndex-o.queueIndex),this._pendingEvents.setManyUnsorted(i.map(r=>this._createPendingEvent(r))),this._isSending=!1,this._offline=!1,this._roomEncryption=null,this._currentQueueIndex=0}_createPendingEvent(e,t=null){const s=new ch({data:e,remove:()=>this._removeEvent(s),emitUpdate:i=>this._pendingEvents.update(s,i),attachments:t});return s}enableEncryption(e){this._roomEncryption=e}_sendLoop(e){this._isSending=!0,this._sendLoopLogItem=e.runDetached("send queue flush",async t=>{try{for(const s of this._pendingEvents)await t.wrap("send event",async i=>{i.set("queueIndex",s.queueIndex);try{this._currentQueueIndex=s.queueIndex,await this._sendEvent(s,i)}catch(r){r instanceof Ut?(this._offline=!0,i.set("offline",!0),s.setWaiting()):(i.catch(r),r.name==="HomeServerError"&&(r.statusCode===400||r.statusCode===403||r.statusCode===404)?(i.set("remove",!0),await s.abort()):s.setError(r))}finally{this._currentQueueIndex=0}})}finally{this._isSending=!1,this._sendLoopLogItem=null}})}async _sendEvent(e,t){if(e.needsUpload&&(await t.wrap("upload attachments",s=>e.uploadAttachments(this._hsApi,s)),await this._tryUpdateEvent(e)),e.needsEncryption){e.setEncrypting();const s=e.contentForEncryption,{type:i,content:r}=await t.wrap("encrypt",o=>this._roomEncryption.encrypt(e.eventType,s,this._hsApi,o));e.setEncrypted(i,r),await this._tryUpdateEvent(e)}if(e.needsSending){await e.send(this._hsApi,t);const s=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{await this._tryUpdateEventWithTxn(e,s),await this._resolveRemoteIdInPendingRelations(e.txnId,e.remoteId,s)}catch(i){throw s.abort(),i}await s.complete()}}async _resolveRemoteIdInPendingRelations(e,t,s){const i=this._pendingEvents.array.filter(r=>r.relatedTxnId===e&&r.relatedEventId!==t);for(const r of i)r.setRelatedEventId(t),await this._tryUpdateEventWithTxn(r,s);return i}async removeRemoteEchos(e,t,s){const i=[];for(const r of e){const o=r.unsigned&&r.unsigned.transaction_id;let c;if(o?c=this._pendingEvents.array.findIndex(l=>l.txnId===o):c=this._pendingEvents.array.findIndex(l=>l.remoteId===r.event_id),c!==-1){const l=this._pendingEvents.get(c),h=r.event_id;s.log({l:"removeRemoteEcho",queueIndex:l.queueIndex,remoteId:h,txnId:o}),t.pendingEvents.remove(l.roomId,l.queueIndex),i.push(l),await this._resolveRemoteIdInPendingRelations(o,h,t)}}return i}async _removeEvent(e){if(this._pendingEvents.array.indexOf(e)!==-1){const s=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{s.pendingEvents.remove(e.roomId,e.queueIndex)}catch{s.abort()}await s.complete();const i=this._pendingEvents.array.indexOf(e);i!==-1&&this._pendingEvents.remove(i)}e.dispose()}emitRemovals(e){for(const t of e){const s=this._pendingEvents.array.indexOf(t);s!==-1&&this._pendingEvents.remove(s),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,s,i){const r=rs(t);let o=null;if(r){const c=bn(r);if(mo(c)&&(o=c,wa(r,null)),r.rel_type===ss&&this._pendingEvents.array.some(h=>{const a=rs(h.content);return h.eventType===e&&a&&a.key===r.key&&(h.relatedTxnId===o||a.event_id===r.event_id)})){i.set("already_annotating",!0);return}}return await this._enqueueEvent(e,t,s,o,null,i)}async _enqueueEvent(e,t,s,i,r,o){const c=await this._createAndStoreEvent(e,t,i,r,s);return this._pendingEvents.set(c),o.set("queueIndex",c.queueIndex),o.set("pendingEvents",this._pendingEvents.length),!this._isSending&&!this._offline&&this._sendLoop(o),this._sendLoopLogItem&&o.refDetached(this._sendLoopLogItem),c}async enqueueRedaction(e,t,s){if(this._pendingEvents.array.some(c=>c.eventType===gt&&(c.relatedTxnId===e||c.relatedEventId===e))){s.set("already_redacting",!0);return}let r,o;if(mo(e)){r=e;const c=e,l=this._pendingEvents.array.find(h=>h.txnId===c);if(l&&!l.remoteId&&l.status!==X.Sending){s.set("remove",r),await l.abort();return}else if(l)o=l.remoteId;else return}else{o=e;const c=this._pendingEvents.array.find(l=>l.remoteId===o);c&&(r=c.txnId)}s.set("relatedTxnId",r),s.set("relatedEventId",o),await this._enqueueEvent(gt,{reason:t},null,r,o,s)}get pendingEvents(){return this._pendingEvents}async _tryUpdateEvent(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{this._tryUpdateEventWithTxn(e,t)}catch(s){throw t.abort(),s}await t.complete()}async _tryUpdateEventWithTxn(e,t){await t.pendingEvents.exists(e.roomId,e.queueIndex)&&t.pendingEvents.update(e.data)}async _createAndStoreEvent(e,t,s,i,r){const o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);let c;try{const l=o.pendingEvents,h=await l.getMaxQueueIndex(this._roomId)||0,u=Math.max(h,this._currentQueueIndex)+1,p=e!==gt&&e!==Zl&&!!this._roomEncryption;c=this._createPendingEvent({roomId:this._roomId,queueIndex:u,eventType:e,content:t,relatedTxnId:s,relatedEventId:i,txnId:Pe(),needsEncryption:p,needsUpload:!!r},r),l.add(c.data)}catch(l){throw o.abort(),l}return await o.complete(),c}dispose(){for(const e of this._pendingEvents)e.dispose()}}class Wa{constructor({filename:e,blob:t,platform:s}){this._filename=e,this._unencryptedBlob=t,this._transferredBlob=this._unencryptedBlob,this._platform=s,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 Vl(this._platform,this._transferredBlob);this._transferredBlob=t,this._encryptionInfo=e}async upload(e,t,s){this._uploadRequest=e.uploadAttachment(this._transferredBlob,this._filename,{uploadProgress:r=>{this._sentBytes=r,t()},log:s});const{content_uri:i}=await this._uploadRequest.response();this._mxcUrl=i}applyToContent(e,t){if(!this._mxcUrl)throw new Error("upload has not finished");let s=e.substr(0,e.lastIndexOf("url"));ar(`${s}info.size`,t,this._transferredBlob.size),ar(`${s}info.mimetype`,t,this._unencryptedBlob.mimeType),this._encryptionInfo?ar(`${s}file`,t,Object.assign(this._encryptionInfo,{mimetype:this._unencryptedBlob.mimeType,url:this._mxcUrl})):ar(`${s}url`,t,this._mxcUrl)}dispose(){this._unencryptedBlob.dispose(),this._transferredBlob.dispose()}}function ar(n,e,t){const s=n.split(".");let i=e;for(let o=0;op.event)))),u=u.filter(p=>(p==null?void 0:p.type)===ku),u.length&&(h=await c.prepareDecryptAll(u,s,ts.Sync,i))}return{roomEncryption:c,summaryChanges:o,decryptPreparation:h,decryptChanges:null,retryEntries:l}}async afterPrepareSync(e,t){e.decryptPreparation&&await t.wrap("decrypt",async s=>{s.set("id",this.id),e.decryptChanges=await e.decryptPreparation.decrypt(),e.decryptPreparation=null},t.level.Detail)}async writeSync(e,t,{summaryChanges:s,decryptChanges:i,roomEncryption:r,retryEntries:o},c,l){var D;l.set("id",this.id);const h=s.isNewJoin(this._summary.data);h&&(c.roomState.removeAllForRoom(this.id),c.roomMembers.removeAllForRoom(this.id));const{entries:a,updatedEntries:u,newLiveKey:p,memberChanges:g,memberSync:f}=await l.wrap("syncWriter",B=>this._syncWriter.writeSync(e,h,s.hasFetchedMembers,c,B),l.level.Detail);let v;i&&(v=await l.wrap("decryptChanges",B=>i.write(c,B)),l.set("decryptionResults",v.results.size),l.set("decryptionErrors",v.errors.size),this._isTimelineOpen&&await v.verifyKnownSenders(c),v.applyToEntries(a),o!=null&&o.length&&(v.applyToEntries(o),u.push(...o))),l.set("newEntries",a.length),l.set("updatedEntries",u.length);let M;r&&(M=await r.writeSync(e,g,c,l),l.set("shouldFlushKeyShares",M.shouldFlush));const R=a.concat(u);s=s.applyTimelineEntries(R,t,!this._isTimelineOpen,this._user.id),s.membership!=="join"?c.roomSummary.remove(this.id):s=this._summary.writeData(s,c),s&&l.set("summaryChanges",s.changedKeys(this._summary.data));let N;s!=null&&s.needsHeroes&&(this._heroes||(this._heroes=new Rn(this._roomId)),N=await this._heroes.calculateChanges(s.heroes,g,c));let F;Array.isArray((D=e.timeline)==null?void 0:D.events)&&(F=await this._sendQueue.removeRemoteEchos(e.timeline.events,c,l));const T=this._getPowerLevelsEvent(e);return await this._runRoomStateHandlers(e,f,c,l),{roomResponse:e,summaryChanges:s,roomEncryption:r,newEntries:a,updatedEntries:u,newLiveKey:p,removedPendingEvents:F,memberChanges:g,heroChanges:N,powerLevelsEvent:T,encryptionChanges:M,decryption:v}}afterSync(e,t){const{summaryChanges:s,newEntries:i,updatedEntries:r,newLiveKey:o,removedPendingEvents:c,memberChanges:l,powerLevelsEvent:h,heroChanges:a,roomEncryption:u,roomResponse:p,encryptionChanges:g}=e;if(t.set("id",this.id),this._syncWriter.afterSync(o),this._setEncryption(u),this._roomEncryption&&this._roomEncryption.afterSync(g),l.size){if(this._changedMembersDuringSync)for(const[v,M]of l.entries())this._changedMembersDuringSync.set(v,M.member);if(this._memberList&&this._memberList.afterSync(l),this._roomStateHandler.updateRoomMembers(this,l),this._observedMembers&&this._updateObservedMembers(l),this._timeline){for(const[v,M]of l.entries())if(v===this._user.id){this._timeline.updateOwnMember(M.member);break}}}let f=!1;if(s&&(this._summary.applyChanges(s),this._summary.data.needsHeroes||(this._heroes=null),f=!0),this._heroes&&a){const v=this.name;this._heroes.applyChanges(a,this._summary.data,t),v!==this.name&&(f=!0)}h&&this._updatePowerLevels(h),f&&this._emitUpdate(),this._timeline&&(this._timeline.replaceEntries(r),this._timeline.addEntries(i)),this._observedEvents&&(this._observedEvents.updateEvents(r),this._observedEvents.updateEvents(i)),c&&this._sendQueue.emitRemovals(c),this._emitSyncRoomState(p)}_updateObservedMembers(e){for(const[t,s]of e){const i=this._observedMembers.get(t);i&&i.set(s.member)}}_getPowerLevelsEvent(e){let t;return Js(e,s=>{s.state_key===""&&s.type===gu&&(t=s)}),t}_updatePowerLevels(e){if(this._powerLevels){const t=new gr({powerLevelEvent:e,ownUserId:this._user.id,membership:this.membership});this._powerLevels.set(t)}}async afterSyncCompleted({encryptionChanges:e,decryption:t,newEntries:s,updatedEntries:i},r){const o=e==null?void 0:e.shouldFlush,c=this._isTimelineOpen&&(t==null?void 0:t.hasUnverifiedSenders);(o||c)&&await r.wrap({l:"room",id:this.id},async l=>{const h=[];if(o&&h.push(this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,null,l)),c){const a=l.wrap("verify senders",async u=>{var v,M;const p=await t.fetchAndVerifyRemainingSenders(this._hsApi,u),g=[],f=R=>g.push(R);p.applyToEntries(s,f),p.applyToEntries(i,f),u.set("verifiedEntries",g.length),(v=this._timeline)==null||v.replaceEntries(g),(M=this._observedEvents)==null||M.updateEvents(g)});h.push(a)}await Promise.all(h)})}start(e,t){if(this._roomEncryption){const s=e==null?void 0:e.get("share_room_key");s&&t.wrapDetached("flush room keys",i=>(i.set("id",this.id),this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,s,i)))}this._sendQueue.resumeSending(t)}async load(e,t,s){try{await super.load(e,t,s),await this._syncWriter.load(t,s)}catch(i){throw new ha(`Could not load room ${this._roomId}`,i)}}async _writeGapFill(e,t,s){return await this._sendQueue.removeRemoteEchos(e,t,s)}_applyGapFill(e){this._sendQueue.emitRemovals(e)}sendEvent(e,t,s,i=null){return this._platform.logger.wrapOrRun(i,"send",r=>(r.set("id",this.id),this._sendQueue.enqueueEvent(e,t,s,r)))}sendRedaction(e,t,s=null){return this._platform.logger.wrapOrRun(s,"redact",i=>(i.set("id",this.id),this._sendQueue.enqueueRedaction(e,t,i)))}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 t;const e=this._syncWriter.lastMessageKey;if(e){const i=await(await this._storage.readTxn([this._storage.storeNames.timelineEvents])).timelineEvents.get(this._roomId,e);return(t=i==null?void 0:i.event)==null?void 0:t.event_id}}async clearUnread(e=null,t=!0){if(this.isUnread||this.notificationCount)return await this._platform.logger.wrapOrRun(e,"clearUnread",async s=>{s.set("id",this.id);const i=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary]);let r;try{r=this._summary.writeClearUnread(i)}catch(o){throw i.abort(),o}await i.complete(),this._summary.applyChanges(r),this._emitUpdate();try{const o=t&&await this._getLastEventId();o&&await this._hsApi.receipt(this._roomId,"m.read",o)}catch(o){if(o.name!=="ConnectionError")throw o}})}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()})}async inviteUser(e,t){if(!e)throw new Error("userId is null/undefined");await this._hsApi.invite(this.id,e,t).response()}_getPendingEvents(){return this._sendQueue.pendingEvents}_runRoomStateHandlers(e,t,s,i){const r=[];return Js(e,o=>{r.push(this._roomStateHandler.handleRoomState(this,o,t,s,i))}),Promise.all(r)}_emitSyncRoomState(e){Js(e,t=>{for(const s of this._roomStateObservers)s.handleStateEvent(t)})}writeIsTrackingMembers(e,t){return this._summary.writeIsTrackingMembers(e,t)}applyIsTrackingMembersChanges(e){this._summary.applyChanges(e)}createAttachment(e,t){return new Wa({blob:e,filename:t,platform:this._platform})}dispose(){super.dispose(),this._sendQueue.dispose()}}class Mu extends Ha{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 s=await t.roomMembers.get(this.id,e);return s?new Q(s):Q.fromUserId(this.id,e,"join")}async load(e,t,s){const{summary:i,kickDetails:r}=e;return this._kickDetails=r,this._kickDetails&&(this._kickedBy=await this._getKickAuthor(this._kickDetails.sender,t)),super.load(i,t,s)}async writeSync(e,t,s,i,r){if(r.set("id",this.id),s==="leave"){const o=Cu(t,this._user.id);if(o||e){const c=o||this._kickDetails;let l;o&&(l=await this._getKickAuthor(o.sender,i));const h=e||this._summary.data;return i.archivedRoomSummary.set({summary:h.serialize(),kickDetails:c}),{kickDetails:c,kickedBy:l,summaryData:h}}}else s==="join"&&i.archivedRoomSummary.remove(this.id);return{}}afterSync({summaryData:e,kickDetails:t,kickedBy:s},i){i.set("id",this.id),e&&this._summary.applyChanges(e),t&&(this._kickDetails=t),s&&(this._kickedBy=s),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 s=this._storage.storeNames,i=await this._storage.readWriteTxn([s.roomState,s.archivedRoomSummary,s.roomMembers,s.timelineEvents,s.timelineFragments,s.timelineRelations,s.pendingEvents,s.inboundGroupSessions,s.groupSessionDecryptions,s.operations]);i.roomState.removeAllForRoom(this.id),i.archivedRoomSummary.remove(this.id),i.roomMembers.removeAllForRoom(this.id),i.timelineEvents.removeAllForRoom(this.id),i.timelineFragments.removeAllForRoom(this.id),i.timelineRelations.removeAllForRoom(this.id),i.pendingEvents.removeAllForRoom(this.id),i.inboundGroupSessions.removeAllForRoom(this.id),i.groupSessionDecryptions.removeAllForRoom(this.id),await i.operations.removeAllForScope(this.id),await i.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 Cu(n,e){var s,i;let t;if(Js(n,r=>{r.type===Ke&&r.state_key===e&&r.sender!==r.state_key&&(t=r)}),t)return{membership:(s=t.content)==null?void 0:s.membership,reason:(i=t.content)==null?void 0:i.reason,sender:t.sender}}async function Eu(n,e,t){const s=await Promise.all(n.map(async i=>{const r=await e.profile(i,{log:t}).response();return new Ru(i,r.displayname,r.avatar_url)}));return s.sort((i,r)=>i.name.localeCompare(r.name)),s}class Ru{constructor(e,t,s){this.userId=e,this.displayName=t,this.avatarUrl=s}get name(){return this.displayName||this.userId}}class Tu{constructor(e){this.userId=e}get displayName(){}get name(){return this.userId}get avatarUrl(){}}function Au(n){switch(n){case Le.DirectMessage:case Le.Private:return!0;case Le.Public:return!1}}function xu(n){switch(n){case Le.DirectMessage:return"trusted_private_chat";case Le.Private:return"private_chat";case Le.Public:return"public_chat"}}class Vu extends $t{constructor(e,t,s,i,r,o){var c;if(super(),this.id=e,this.options=t,this.updateCallback=s,this.mediaRepository=i,this.platform=r,this.profiles=[],this._isCancelled=!1,this.isEncrypted=t.isEncrypted===void 0?Au(t.type):t.isEncrypted,t.name)this._calculatedName=t.name;else{const l={joinCount:1,inviteCount:((c=t.invites)==null?void 0:c.length)||0},h=(t.invites||[]).map(a=>new Tu(a));this._calculatedName=tn(h,l,o)}}async create(e,t){try{let s;if(this.options.avatar){const{avatar:o}=this.options,c=new Wa({filename:o.name,blob:o.blob,platform:this.platform});await c.upload(e,()=>{},t),s={info:o.info},c.applyToContent("url",s)}const i={is_direct:this.options.type===Le.DirectMessage,preset:xu(this.options.type),initial_state:[]};this.options.name&&(i.name=this.options.name),this.options.topic&&(i.topic=this.options.topic),this.options.invites&&(i.invite=this.options.invites),this.options.alias&&(i.room_alias_name=this.options.alias),this.options.isFederationDisabled===!0&&(i.creation_content={"m.federate":!1}),this.options.powerLevelContentOverride&&(i.power_level_content_override=this.options.powerLevelContentOverride),this.isEncrypted&&i.initial_state.push(Hl()),s&&i.initial_state.push({type:"m.room.avatar",state_key:"",content:s});const r=await e.createRoom(i,{log:t}).response();this._roomId=r.room_id}catch(s){this._error=s}this.emitChange()}async loadProfiles(e,t){try{if(!this.options.name&&this.options.invites){this.profiles=await Eu(this.options.invites,e,t);const s={joinCount:1,inviteCount:this.options.invites.length};this._calculatedName=tn(this.profiles,s,t),this.emitChange()}}catch{}}emitChange(e){this.updateCallback(this,e),this.emit("change")}get avatarColorId(){var e,t,s;return(s=(t=(e=this.options.invites)==null?void 0:e[0])!=null?t:this._roomId)!=null?s: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,s,i){if(!this.options.invites||this.options.type!==Le.DirectMessage)return;const r=this.options.invites[0],o="m.direct";await i.wrap("set "+o,async c=>{try{const l=await t.readWriteTxn([t.storeNames.accountData]);let h;try{h=await l.accountData.get(o),h||(h={type:o,content:{}});const a=h.content;let u=a[r];u||(a[r]=u=[]),u.push(this._roomId),l.accountData.set(h),await l.complete()}catch(a){throw l.abort(),a}await s.setAccountData(e.id,o,h.content,{log:c}).response()}catch(l){c.catch(l)}})}}class Nu extends $t{constructor({roomId:e,user:t,hsApi:s,mediaRepository:i,emitCollectionRemove:r,emitCollectionUpdate:o,platform:c}){super(),this._roomId=e,this._user=t,this._hsApi=s,this._emitCollectionRemove=r,this._emitCollectionUpdate=o,this._mediaRepository=i,this._platform=c,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 Q(e.inviter):null}async writeSync(e,t,s,i){var r;if(e==="invite"){i.set("id",this.id),i.set("add",!0);const o=(r=t.invite_state)==null?void 0:r.events;if(!Array.isArray(o))return null;const c=this._createSummaryData(o);let l;!c.name&&!c.canonicalAlias&&(l=await this._createHeroes(o,i));const h=this._getMyInvite(o);if(!h)return null;const a=this._getInviter(h,o),u=this._createData(o,h,a,c,l);return s.invites.set(u),{inviteData:u,inviter:a}}else return i.set("id",this.id),i.set("membership",e),s.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,s,i,r){const o=r?r.roomName:i.name,c=r?r.roomAvatarUrl:i.avatarUrl,l=(r==null?void 0:r.roomAvatarColorId)||this.id;return{roomId:this.id,isEncrypted:!!i.encryption,isDirectMessage:i.isDirectMessage,name:o,avatarUrl:c,avatarColorId:l,canonicalAlias:i.canonicalAlias,timestamp:this._platform.clock.now(),joinRule:this._getJoinRule(e),inviter:s==null?void 0:s.serialize()}}_createSummaryData(e){return e.reduce((t,s)=>ga(t,s,this._user.id),new Rt(null,this.id))}async _createHeroes(e,t){const s=e.filter(a=>a.type===Ke),i=s.filter(a=>a.state_key!==this._user.id),r=i.reduce((a,u)=>{const p=Q.fromMemberEvent(this.id,u);return a.set(p.userId,new ka(p,null)),a},new Map),o=i.map(a=>a.state_key),c=new Rn(this.id),l=await c.calculateChanges(o,r,null),h=new Rt(null,this.id);return h.joinCount=s.reduce((a,u)=>{var p;return a+(((p=u.content)==null?void 0:p.membership)==="join"?1:0)},0),h.inviteCount=s.reduce((a,u)=>{var p;return a+(((p=u.content)==null?void 0:p.membership)==="invite"?1:0)},0),c.applyChanges(l,h,t),c}_getMyInvite(e){return e.find(t=>t.type===Ke&&t.state_key===this._user.id)}_getInviter(e,t){const s=t.find(i=>i.type===Ke&&i.state_key===e.sender);if(s)return Q.fromMemberEvent(this.id,s)}_getJoinRule(e){var s;const t=e.find(i=>i.type==="m.room.join_rules");return t?(s=t.content)==null?void 0:s.join_rule:null}}class bs{constructor(e){this._description=e}static httpPusher(e,t,s,i){return new bs({kind:"http",append:!0,data:Object.assign({},i,{url:e+"/_matrix/push/v1/notify"}),pushkey:s,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 s=Object.assign({},this._description,{kind:null});await e.setPusher(s,{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)}}class Du extends $t{constructor({storage:e,callHandler:t}){super(),this._storage=e,this._olmDecryption=null,this._megolmDecryption=null,this._callHandler=t,this._senderDeviceCache=new $a(10,s=>s.curve25519Key)}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,s,i){i.set("messageTypes",uo(e,c=>c.type));const r=e.filter(c=>c.type==="m.room.encrypted");if(this._emitUnencryptedEvents(e),!this._olmDecryption){i.log("can't decrypt, encryption not enabled",i.level.Warn);return}const o=r.filter(c=>{var l;return((l=c.content)==null?void 0:l.algorithm)===wn});if(o.length){const c=await this._olmDecryption.decryptAll(o,t,s);i.set("decryptedTypes",uo(c.results,h=>{var a;return(a=h.event)==null?void 0:a.type}));for(const h of c.errors)i.child("decrypt_error").catch(h);const l=this._megolmDecryption.roomKeysFromDeviceMessages(c.results,i);return new Uu(c,l)}}async writeSync(e,t){return e.olmDecryptChanges.write(t),{hasNewRoomKeys:(await Promise.all(e.newRoomKeys.map(r=>this._megolmDecryption.writeRoomKey(r,t)))).some(r=>!!r),decryptionResults:e.olmDecryptChanges.results}}async afterSyncCompleted(e,t,s,i){if(await i.wrap("Verifying fingerprint of encrypted toDevice messages",async r=>{for(const o of e){const c=o.event.sender,l=await t.deviceForCurveKey(c,o.senderCurve25519Key,s,r);o.setDevice(l),o.isVerified?this.emit("message",{encrypted:o}):r.log({l:"could not verify olm fingerprint key matches, ignoring",ed25519Key:o.device.ed25519Key,claimedEd25519Key:o.claimedEd25519Key,deviceId:l.deviceId,userId:l.userId})}}),this._callHandler){const r=e.filter(o=>{var c;return this._callHandler.handlesDeviceMessageEventType((c=o.event)==null?void 0:c.type)});r.length&&await i.wrap("process call signalling messages",async o=>{for(const c of r){const l=await t.deviceForId(c.event.sender,c.event.content.device_id,s,o);c.setDevice(l),c.isVerified?this._callHandler.handleDeviceMessage(c.event,c.userId,c.deviceId,o):o.log({l:"could not verify olm fingerprint key matches, ignoring",ed25519Key:c.device.ed25519Key,claimedEd25519Key:c.claimedEd25519Key,deviceId:l.deviceId,userId:l.userId})}})}}_emitUnencryptedEvents(e){const t=e.filter(s=>s.type!=="m.room.encrypted");for(const s of t)this.emit("message",{unencrypted:s})}}class Uu{constructor(e,t){this.olmDecryptChanges=e,this.newRoomKeys=t,this.newKeysByRoom=ti(t,s=>s.roomId)}}const Ei=Oe+"olmAccount",sn=Oe+"areDeviceKeysUploaded",fr=Oe+"serverOTKCount";async function go(n,e,t,s,i){const r=n.pickle(e),o=await i.readWriteTxn([i.storeNames.session]);try{o.session.add(Ei,r),o.session.add(sn,t),o.session.add(fr,s)}catch(c){throw o.abort(),c}await o.complete()}class Is{static async load({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,txn:c}){const l=await c.session.get(Ei);if(l){const h=new e.Account,a=await c.session.get(sn);h.unpickle(t,l);const u=await c.session.get(fr);return new Is({pickleKey:t,hsApi:s,account:h,userId:i,deviceId:r,areDeviceKeysUploaded:a,serverOTKCount:u,olm:e,olmWorker:o})}}static async adoptDehydratedDevice({olm:e,dehydratedDevice:t,pickleKey:s,hsApi:i,userId:r,olmWorker:o,storage:c}){const l=t.adoptUnpickledOlmAccount(),h=JSON.parse(l.one_time_keys()),u=Object.entries(h.curve25519).length,p=!0;return await go(l,s,p,u,c),new Is({pickleKey:s,hsApi:i,account:l,userId:r,deviceId:t.deviceId,areDeviceKeysUploaded:p,serverOTKCount:u,olm:e,olmWorker:o})}static async create({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,storage:c}){const l=new e.Account;o?await o.createAccountAndOTKs(l,l.max_number_of_one_time_keys()):(l.create(),l.generate_one_time_keys(l.max_number_of_one_time_keys()));const h=!1,a=0;return c&&await go(l,t,h,a,c),new Is({pickleKey:t,hsApi:s,account:l,userId:i,deviceId:r,areDeviceKeysUploaded:h,serverOTKCount:a,olm:e,olmWorker:o})}constructor({pickleKey:e,hsApi:t,account:s,userId:i,deviceId:r,areDeviceKeysUploaded:o,serverOTKCount:c,olm:l,olmWorker:h}){this._olm=l,this._pickleKey=e,this._hsApi=t,this._account=s,this._userId=i,this._deviceId=r,this._areDeviceKeysUploaded=o,this._serverOTKCount=c,this._olmWorker=h,this._identityKeys=JSON.parse(this._account.identity_keys())}get identityKeys(){return this._identityKeys}setDeviceId(e){this._deviceId=e}async uploadKeys(e,t,s){var o;const i=JSON.parse(this._account.one_time_keys()),r=Object.entries(i.curve25519);if(r.length||!this._areDeviceKeysUploaded){const c={};if(!this._areDeviceKeysUploaded){s.set("identity",!0);const a=JSON.parse(this._account.identity_keys());c.device_keys=this._deviceKeysPayload(a)}r.length&&(s.set("otks",!0),c.one_time_keys=this._oneTimeKeysPayload(r));const l=t?this._deviceId:void 0,h=await this._hsApi.uploadKeys(l,c,{log:s}).response();this._serverOTKCount=(o=h==null?void 0:h.one_time_key_counts)==null?void 0:o.signed_curve25519,s.set("serverOTKCount",this._serverOTKCount),await this._updateSessionStorage(e,a=>{r.length&&(this._account.mark_keys_as_published(),a==null||a.set(Ei,this._account.pickle(this._pickleKey)),a==null||a.set(fr,this._serverOTKCount)),this._areDeviceKeysUploaded||(this._areDeviceKeysUploaded=!0,a==null||a.set(sn,this._areDeviceKeysUploaded))})}}async generateOTKsIfNeeded(e,t){const s=this._account.max_number_of_one_time_keys(),i=Math.floor(s/2);if(this._serverOTKCount0&&await t.wrap("generate otks",h=>{h.set("max",s),h.set("server",this._serverOTKCount),h.set("unpublished",c),h.set("new",l),h.set("limit",i),this._account.generate_one_time_keys(l),this._updateSessionStorage(e,a=>{a.set(Ei,this._account.pickle(this._pickleKey))})}),!0}return!1}createInboundOlmSession(e,t){const s=new this._olm.Session;try{return s.create_inbound_from(this._account,e,t),s}catch(i){throw s.free(),i}}async createOutboundOlmSession(e,t){const s=new this._olm.Session;try{return this._olmWorker?await this._olmWorker.createOutboundOlmSession(this._account,s,e,t):s.create_outbound(this._account,e,t),s}catch(i){throw s.free(),i}}writeRemoveOneTimeKey(e,t){this._account.remove_one_time_keys(e),t.session.set(Ei,this._account.pickle(this._pickleKey))}writeSync(e,t,s){const i=e.signed_curve25519;if(Number.isSafeInteger(i)&&i!==this._serverOTKCount)return t.session.set(fr,i),s.set("otkCount",i),i}afterSync(e){Number.isSafeInteger(e)&&(this._serverOTKCount=e)}_keysAsSignableObject(e){const t={user_id:this._userId,device_id:this._deviceId,algorithms:[wn,ft],keys:{}};for(const[s,i]of Object.entries(e))t.keys[`${s}:${this._deviceId}`]=i;return t}getUnsignedDeviceKey(){const e=JSON.parse(this._account.identity_keys());return this._keysAsSignableObject(e)}_deviceKeysPayload(e){const t=this._keysAsSignableObject(e);return this.signObject(t),t}_oneTimeKeysPayload(e){const t={};for(const[s,i]of e){const r={key:i};this.signObject(r),t[`signed_curve25519:${s}`]=r}return t}async _updateSessionStorage(e,t){if(e){const s=await e.readWriteTxn([e.storeNames.session]);try{await t(s.session)}catch(i){throw s.abort(),i}await s.complete()}else await t(void 0)}signObject(e){const t=e.signatures||{},s=e.unsigned;delete e.signatures,delete e.unsigned,t[this._userId]=t[this._userId]||{},t[this._userId]["ed25519:"+this._deviceId]=this._account.sign(qi.stringify(e)),e.signatures=t,s!==void 0&&(e.unsigned=s)}pickleWithKey(e){return this._account.pickle(e)}dispose(){this._account.free(),this._account=void 0}}class Tn{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 s=this._keyDescription;if(s.mac){const i=await Ou(e.binaryKey,s.iv,t);return s.mac===i}else if(s.passphrase){const i=e.description._keyDescription;return i.passphrase?s.passphrase.algorithm===i.passphrase.algorithm&&s.passphrase.iterations===i.passphrase.iterations&&s.passphrase.salt===i.passphrase.salt:!1}}return!1}}class Wi{constructor(e,t){this._keyDescription=e,this._binaryKey=t}withDescription(e){return new Wi(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 Ou(n,e,t){const{crypto:s,encoding:i}=t,{utf8:r,base64:o}=i,{derive:c,aes:l,hmac:h}=s,a=o.decode(e),u=new Uint8Array(8),p="\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",g=r.encode(""),f=await c.hkdf(n,u,g,"SHA-256",512),v=f.slice(0,32),M=f.slice(32),R=await l.encryptCTR({key:v,iv:a,data:r.encode(p)}),N=await h.compute(M,R,"SHA-256");return o.encode(N)}const Pu=5e5,Fu=256;async function Lu(n,e,t){const{passphraseParams:s}=n;if(!s)throw new Error("not a passphrase key");if(s.algorithm!=="m.pbkdf2")throw new Error(`Unsupported passphrase algorithm: ${s.algorithm}`);const{utf8:i}=t.encoding,r=await t.crypto.derive.pbkdf2(i.encode(e),s.iterations||Pu,i.encode(s.salt),"SHA-512",s.bits||Fu);return new Wi(n,r)}const vi=[139,1];function Ku(n,e,t,s){const i=s.encoding.base58.decode(e.replace(/ /g,""));let r=0;for(const c of i)r^=c;if(r!==0)throw new Error("Incorrect parity");for(let c=0;c{switch(e==null?void 0:e.event.type){case"m.secret.request":{await this._respondToRequest(e);break}case"m.secret.send":{const{secret:s}=e.event.content,i=await this.shouldAcceptSecret(e);i&&this.writeSecretToStorage(i,s);break}}}),await this.aesEncryption.load()}async _respondToRequest(e){await this.logger.run("SharedSecret.respondToRequest",async t=>{if(!await this.shouldRespondToRequest(e,t))return;const s=e.event.content,i=s.request_id,r=s.requesting_device_id,o=s.name,c=await this.secretFetcher.getSecret(o);if(!c){t.log({l:"Secret not available to share"});return}const l={secret:c,request_id:i},h=await this.deviceTracker.deviceForId(this.ourUserId,r,this.hsApi,t);if(!h){t.log({l:"Cannot find device",deviceId:r});return}const a=await t.wrap("olm encrypt",p=>this.olmEncryption.encrypt("m.secret.send",l,[h],this.hsApi,p)),u=Fi(a);await this.hsApi.sendToDevice("m.room.encrypted",u,Pe(),{log:t}).response()})}async shouldRespondToRequest(e,t){return t.wrap("SecretSharing.shouldRespondToRequest",async()=>{if(e.event.content.requesting_device_id===this.deviceTracker.ownDeviceId)return!1;const s=this.crossSigning.get();if(!s)return t.log({crossSigningNotAvailable:!0}),!1;const i=e.event.content;if(e.event.sender!==this.ourUserId||!(i.name&&i.action&&i.requesting_device_id&&i.request_id)||i.action==="request_cancellation")return!1;const r=i.requesting_device_id,o=await this.deviceTracker.deviceForId(this.ourUserId,r,this.hsApi,t);return o?await s.isOurUserDeviceTrusted(o,t)?!0:(t.log({l:"Device not trusted, returning"}),!1):(t.log({l:"Device could not be acquired",deviceId:r}),!1)})}async shouldAcceptSecret(e){const t=this.crossSigning.get();if(!t)return;const s=e.device;if(!s||!await t.isOurUserDeviceTrusted(s))return;const r=e.event.content.request_id,o=this.waitMap.get(r);if(o){const{name:a,deferred:u}=o;return u.resolve(e),this.waitMap.delete(r),await this.removeStoredRequestId(r),a}const l=await(await this.storage.readTxn([this.storage.storeNames.session])).session.get(bi),h=l==null?void 0:l[r];if(h)return await this.removeStoredRequestId(r),h}async removeStoredRequestId(e){const t=await this.storage.readWriteTxn([this.storage.storeNames.session]),s=await t.session.get(bi);s&&(delete s[e],t.session.set(bi,s))}async checkSecretValidity(e){const t=this.crossSigning.get();!await(t==null?void 0:t.areWeVerified(e))&&(await this.storage.readWriteTxn([this.storage.storeNames.sharedSecrets])).sharedSecrets.deleteAllSecrets()}async getLocallyStoredSecret(e){const s=await(await this.storage.readTxn([this.storage.storeNames.sharedSecrets])).sharedSecrets.get(e);if(s)return await this.aesEncryption.decrypt(s.encrypted)}requestSecret(e,t){return t.wrap("SharedSecret.requestSecret",async s=>{const i=Pe(),r=this.trackSecretRequest(i,e);return await this.sendRequestForSecret(e,i,s),await this.writeRequestIdToStorage(i,e),new ju(r)})}async writeRequestIdToStorage(e,t){var r;const s=await this.storage.readWriteTxn([this.storage.storeNames.session]),i=(r=await s.session.get(bi))!=null?r:{};i[e]=t,s.session.set(bi,i)}async writeSecretToStorage(e,t){const s=await this.aesEncryption.encrypt(t);(await this.storage.readWriteTxn([J.sharedSecrets])).sharedSecrets.set(e,{encrypted:s})}trackSecretRequest(e,t){const s=new As;return this.waitMap.set(e,{deferred:s,name:t}),s.promise}async sendRequestForSecret(e,t,s){const i={action:"request",name:e,request_id:t,requesting_device_id:this.deviceTracker.ownDeviceId};let r=await this.deviceTracker.devicesForUsers([this.ourUserId],this.hsApi,s);r=r.filter(l=>l.device_id!==this.deviceTracker.ownDeviceId);const o=await s.wrap("olm encrypt",l=>this.olmEncryption.encrypt("m.secret.request",i,r,this.hsApi,l)),c=Fi(o);await this.hsApi.sendToDevice("m.room.encrypted",c,Pe(),{log:s}).response()}setSecretFetcher(e){this.secretFetcher=e}}class ju{constructor(e){this.receivedSecretPromise=e}async waitForResponse(e=30){const t=new Promise((i,r)=>{setTimeout(r,e*1e3)});return(await Promise.race([this.receivedSecretPromise,t])).event.content.secret}}class qu{constructor(e,t,s){this.storage=e,this.crypto=t,this.encoding=s}async load(){var r;const e=`${Oe}localAESKey`,t=await this.storage.readTxn([J.session]);let{key:s,iv:i}=(r=await t.session.get(e))!=null?r:{};s||(s=await this.crypto.aes.generateKey("jwk"),i=await this.crypto.aes.generateIV(),(await this.storage.readWriteTxn([J.session])).session.set(e,{key:s,iv:i})),this.key=s,this.iv=i}async encrypt(e){const t=this.encoding.utf8.encode(e);return await this.crypto.aes.encryptCTR({jwkKey:this.key,iv:this.iv,data:t})}async decrypt(e){const t=await this.crypto.aes.decryptCTR({jwkKey:this.key,iv:this.iv,data:e});return this.encoding.utf8.decode(t)}}class cr extends Error{constructor(e,t){super(e),this.reason=t}}class Hu{constructor({key:e,platform:t,storage:s}){this._key=e,this._platform=t,this._storage=s}async hasValidKeyForAnyAccountData(){const t=await(await this._storage.readTxn([this._storage.storeNames.accountData])).accountData.getAll();for(const s of t)try{const i=await this._decryptAccountData(s);return!0}catch(i){if(i instanceof cr&&i.reason!==0)throw i;continue}return!1}async readSecret(e){const s=await(await this._storage.readTxn([this._storage.storeNames.accountData])).accountData.get(e);if(!!s)return await this._decryptAccountData(s)}async _decryptAccountData(e){var s,i;const t=(i=(s=e==null?void 0:e.content)==null?void 0:s.encrypted)==null?void 0:i[this._key.id];if(!t)throw new cr(`Secret ${e.type} is not encrypted for key ${this._key.id}`,0);if(this._key.algorithm==="m.secret_storage.v1.aes-hmac-sha2")return await this._decryptAESSecret(e.type,t);throw new cr(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`,2)}async _decryptAESSecret(e,t){const{base64:s,utf8:i}=this._platform.encoding,r=await this._platform.crypto.derive.hkdf(this._key.binaryKey,new Uint8Array(8).buffer,i.encode(e),"SHA-256",512),o=r.slice(0,32),c=r.slice(32),l=s.decode(t.ciphertext);if(!await this._platform.crypto.hmac.verify(c,s.decode(t.mac),l,"SHA-256"))throw new cr("Bad MAC",1);const a=await this._platform.crypto.aes.decryptCTR({key:o,iv:s.decode(t.iv),data:l});return i.decode(a)}}const An=`${Oe}ssssKey`,fo=`${Oe}keyBackupVersion`;var mt=(n=>(n[n.RecoveryKey=0]="RecoveryKey",n[n.Passphrase=1]="Passphrase",n))(mt||{});async function za(n){var r;const e=await n.readTxn([n.storeNames.accountData]),t=await e.accountData.get("m.secret_storage.default_key"),s=(r=t==null?void 0:t.content)==null?void 0:r.key;if(!s)return;const i=await e.accountData.get(`m.secret_storage.key.${s}`);if(!!i)return new Tn(s,i.content)}async function Wu(n,e,t){const s=await t.session.get(fo);return t.session.set(fo,e),t.session.set(An,{id:n.id,binaryKey:n.binaryKey}),s}async function zu(n){const e=await n.session.get(An);if(!e)return;const t=await n.accountData.get(`m.secret_storage.key.${e.id}`);if(t)return new Wi(new Tn(e.id,t.content),e.binaryKey)}async function Gu(n){n.session.remove(An)}async function Yu(n,e,t,s,i){const r=await za(t);if(!r)throw new Error("Could not find a default secret storage key in account data");return await Ga(n,e,r,s,i)}async function Ga(n,e,t,s,i){let r;if(n===1)r=await Lu(t,e,s);else if(n===0)r=Ku(t,e,i,s);else throw new Error(`Invalid type: ${n}`);return r}async function Ju(n,e,t){const s=await za(e);if(await(s==null?void 0:s.isCompatible(n,t)))return n.withDescription(s)}const Ya="org.matrix.msc2697.v1.olm.libolm_pickle";async function Qu(n,e,t,s){try{const i=await n.getDehydratedDevice({log:s}).response();if(i.device_data.algorithm===Ya)return new Zu(i,e,t)}catch(i){i.name!=="HomeServerError"&&(s.error=i);return}}async function Xu(n,e,t,s,i){var c;const o=(await e.createDehydratedDevice({device_data:{algorithm:Ya,account:n.pickleWithKey(t.binaryKey.slice()),passphrase:((c=t.description)==null?void 0:c.passphraseParams)||{}},initial_device_display_name:s}).response()).device_id;return n.setDeviceId(o),await n.uploadKeys(void 0,!0,i),o}class Zu{constructor(e,t,s){this._dehydratedDevice=e,this._olm=t,this._platform=s}async decrypt(e,t){const s=new Tn("dehydrated_device",this._dehydratedDevice.device_data.passphrase),i=await Ga(e,t,s,this._platform,this._olm),r=new this._olm.Account;try{const o=this._dehydratedDevice.device_data.account;return r.unpickle(i.binaryKey.slice(),o),new em(this._dehydratedDevice,r,i)}catch(o){if(r.free(),o.message==="OLM.BAD_ACCOUNT_KEY")return;throw o}}get deviceId(){return this._dehydratedDevice.device_id}}class em{constructor(e,t,s){this._dehydratedDevice=e,this._account=t,this._key=s}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 Ja{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 Qa{constructor(e){this.locks=e}release(){for(const e of this.locks)e.release()}}function Xa(n,e,t,s){return{session:n.pickle(s),sessionId:n.session_id(),senderKey:e,lastUsed:t}}class Cr{constructor(e,t,s,i=!1){this.data=e,this.pickleKey=t,this.olm=s,this.isNew=i,this.isModified=i}static create(e,t,s,i,r){const o=Xa(t,e,r,i);return new Cr(o,i,s,!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 Za{constructor(e,t,s,i){this.event=e,this.senderCurve25519Key=t,this.claimedEd25519Key=s,this.encryptedEvent=i}setDevice(e){this.device=e}get isVerified(){return this.device?ks(this.device)===this.claimedEd25519Key:!1}get isUnverified(){return this.device?!this.isVerified:!0}get userId(){var e;return(e=this.device)==null?void 0:e.user_id}get deviceId(){var e;return(e=this.device)==null?void 0:e.device_id}get isVerificationUnknown(){return!this.device}}var Er=(n=>(n[n.PreKey=0]="PreKey",n[n.Normal=1]="Normal",n))(Er||{});const yo=4;function ec(n){n.sort((e,t)=>t.data.lastUsed-e.data.lastUsed)}class tm{constructor(e,t,s,i,r,o){this.account=e,this.pickleKey=t,this.now=s,this.ownUserId=i,this.olm=r,this.senderKeyLock=o}async obtainDecryptionLock(e){var i;const t=new Set;for(const r of e){const o=(i=r.content)==null?void 0:i.sender_key;o&&t.add(o)}const s=await Promise.all(Array.from(t).map(r=>this.senderKeyLock.takeLock(r)));return new Qa(s)}async decryptAll(e,t,s){try{const i=ti(e,a=>{var u;return(u=a.content)==null?void 0:u.sender_key}),r=this.now(),o=await Promise.all(Array.from(i.entries()).map(([a,u])=>this._decryptAllForSenderKey(a,u,r,s))),c=o.reduce((a,u)=>a.concat(u.results),[]),l=o.reduce((a,u)=>a.concat(u.errors),[]),h=o.map(a=>a.senderKeyDecryption);return new im(h,c,l,this.account,t)}catch(i){throw t.release(),i}}async _decryptAllForSenderKey(e,t,s,i){const r=await this._getSessions(e,i),o=new sm(e,r,s),c=[],l=[];for(const h of t)try{const a=this._decryptForSenderKey(o,h,s);c.push(a)}catch(a){l.push(a)}return{results:c,errors:l,senderKeyDecryption:o}}_decryptForSenderKey(e,t,s){const i=e.senderKey,r=this._getMessageAndValidateEvent(t);let o;try{o=e.decrypt(r)}catch(c){throw new fe("OLM_BAD_ENCRYPTED_MESSAGE",t,{senderKey:i,error:c.message})}if(typeof o!="string"&&r.type===Er.PreKey){let c;try{c=this._createSessionAndDecrypt(i,r,s)}catch(l){throw new fe(`Could not create inbound olm session: ${l.message}`,t,{senderKey:i,error:l})}e.addNewSession(c.session),o=c.plaintext}if(typeof o=="string"){let c;try{c=JSON.parse(o)}catch(l){throw new fe("PLAINTEXT_NOT_JSON",t,{plaintext:o,error:l})}return this._validatePayload(c,t),new Za(c,i,c.keys.ed25519)}else throw new fe("OLM_NO_MATCHING_SESSION",t,{knownSessionIds:e.sessions.map(c=>c.id)})}_createSessionAndDecrypt(e,t,s){let i;const r=this.account.createInboundOlmSession(e,t.body);try{i=r.decrypt(t.type,t.body);const o=Cr.create(e,r,this.olm,this.pickleKey,s);return o.unload(r),{session:o,plaintext:i}}catch(o){throw r.free(),o}}_getMessageAndValidateEvent(e){var i;const t=(i=e.content)==null?void 0:i.ciphertext;if(!t)throw new fe("OLM_MISSING_CIPHERTEXT",e);const s=t==null?void 0:t[this.account.identityKeys.curve25519];if(!s)throw new fe("OLM_NOT_INCLUDED_IN_RECIPIENTS",e);return s}async _getSessions(e,t){const i=(await t.olmSessions.getAll(e)).map(r=>new Cr(r,this.pickleKey,this.olm));return ec(i),i}_validatePayload(e,t){var s,i,r;if(e.sender!==t.sender)throw new fe("OLM_FORWARDED_MESSAGE",t,{sentBy:t.sender,encryptedBy:e.sender});if(e.recipient!==this.ownUserId)throw new fe("OLM_BAD_RECIPIENT",t,{recipient:e.recipient});if(((s=e.recipient_keys)==null?void 0:s.ed25519)!==this.account.identityKeys.ed25519)throw new fe("OLM_BAD_RECIPIENT_KEY",t,{key:(i=e.recipient_keys)==null?void 0:i.ed25519});if(!e.type)throw new fe("missing type on payload",t,{payload:e});if(typeof((r=e.keys)==null?void 0:r.ed25519)!="string")throw new fe("Missing or invalid claimed ed25519 key on payload",t,{payload:e})}}class sm{constructor(e,t,s){this.senderKey=e,this.sessions=t,this.timestamp=s}addNewSession(e){this.sessions.unshift(e)}decrypt(e){for(const t of this.sessions){const s=this.decryptWithSession(t,e);if(typeof s=="string")return ec(this.sessions),s}}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 s=e.load();try{if(t.type===Er.PreKey&&!s.matches_inbound(t.body))return;try{const i=s.decrypt(t.type,t.body);return e.save(s),e.data.lastUsed=this.timestamp,i}catch(i){if(t.type===Er.PreKey)throw new Error(`Error decrypting prekey message with existing session id ${e.id}: ${i.message}`);return}}finally{e.unload(s)}}}class im{constructor(e,t,s,i,r){this.senderKeyDecryptions=e,this.results=t,this.errors=s,this.account=i,this.lock=r}get hasNewSessions(){return this.senderKeyDecryptions.some(e=>e.hasNewSessions)}write(e){try{for(const t of this.senderKeyDecryptions){for(const s of t.getModifiedSessions())if(e.olmSessions.set(s.data),s.isNew){const i=s.load();try{this.account.writeRemoveOneTimeKey(i,e)}finally{s.unload(i)}}if(t.sessions.length>yo){const{senderKey:s,sessions:i}=t;for(let r=i.length-1;r>=yo;r-=1){const o=i[r];e.olmSessions.remove(s,o.id)}}}}finally{this.lock.release()}}}function rm(n){return n.reduce((e,t)=>!e||t!s.isTaken).slice(0,e);if(t.lengthi.isTaken).slice(0,e-t.length);t.push(...s)}return await Promise.all(t.map(s=>s.take())),new Qa(t)}async encrypt(e,t,s,i,r){let o=[];for(let c=0;cthis.senderKeyLock.takeLock(_t(c))));try{const{devicesWithoutSession:c,existingEncryptionTargets:l}=await this._findExistingSessions(s),h=this.now();let a=[];try{if(c.length){const g=await r.wrap("create sessions",f=>this._createNewSessions(c,i,h,f));a=a.concat(g)}await this._loadSessions(l),a=a.concat(l);const u={l:"encrypt",targets:a.length},p=r.wrap(u,()=>a.map(g=>{const f=this._encryptForDevice(e,t,g);return new om(f,g.device)}));return await this._storeSessions(a,h),p}finally{for(const u of a)u.dispose()}}finally{for(const c of o)c.release()}}async _findExistingSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]),s=await Promise.all(e.map(async o=>await t.olmSessions.getSessionIds(_t(o)))),i=e.filter((o,c)=>{const l=s[c];return!(l!=null&&l.length)}),r=e.map((o,c)=>{const l=s[c];if((l==null?void 0:l.length)>0){const h=rm(l);return Li.fromSessionId(o,h)}}).filter(o=>!!o);return{devicesWithoutSession:i,existingEncryptionTargets:r}}_encryptForDevice(e,t,s){const{session:i,device:r}=s,o=JSON.stringify(this._buildPlainTextMessageForDevice(e,t,r)),c=i.encrypt(o);return{algorithm:wn,sender_key:this.account.identityKeys.curve25519,ciphertext:{[_t(r)]:c}}}_buildPlainTextMessageForDevice(e,t,s){return{keys:{ed25519:this.account.identityKeys.ed25519},recipient_keys:{ed25519:ks(s)},recipient:s.user_id,sender:this.ownUserId,content:t,type:e}}async _createNewSessions(e,t,s,i){const r=await i.wrap("claim",o=>this._claimOneTimeKeys(t,e,o));try{for(const o of r){const{device:c,oneTimeKey:l}=o;o.session=await this.account.createOutboundOlmSession(_t(c),l)}await this._storeSessions(r,s)}catch(o){for(const c of r)c.dispose();throw o}return r}async _claimOneTimeKeys(e,t,s){const i=En(t,l=>l.user_id,()=>new Map,(l,h)=>l.set(h.device_id,h)),r=Array.from(i.entries()).reduce((l,[h,a])=>(l[h]=Array.from(a.values()).reduce((u,p)=>(u[p.device_id]=wo,u),{}),l),{}),o=await e.claimKeys({timeout:1e4,one_time_keys:r},{log:s}).response();Object.keys(o.failures).length&&s.log({l:"failures",servers:Object.keys(o.failures)},s.level.Warn);const c=o==null?void 0:o.one_time_keys;return this._verifyAndCreateOTKTargets(c,i,s)}_verifyAndCreateOTKTargets(e,t,s){var r;const i=[];for(const[o,c]of Object.entries(e))for(const[l,h]of Object.entries(c)){const[a,u]=Object.entries(h)[0],[p]=a.split(":");if(p===wo){const g=(r=t.get(o))==null?void 0:r.get(l);if(g&&vn(this.olmUtil,o,l,ks(g),u,s)===ne.Valid){const v=Li.fromOTK(g,u.key);i.push(v)}}}return i}async _loadSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]);let s=!1;try{await Promise.all(e.map(async i=>{const r=await t.olmSessions.get(_t(i.device),i.sessionId);if(r&&!s){const o=new this.olm.Session;o.unpickle(this.pickleKey,r.session),i.session=o}}))}catch(i){s=!0;for(const r of e)r.dispose();throw i}}async _storeSessions(e,t){const s=await this.storage.readWriteTxn([this.storage.storeNames.olmSessions]);try{for(const i of e){const r=Xa(i.session,_t(i.device),t,this.pickleKey);s.olmSessions.set(r)}}catch(i){throw s.abort(),i}await s.complete()}}class Li{constructor(e,t,s){this.device=e,this.oneTimeKey=t,this.sessionId=s,this.session=null}static fromOTK(e,t){return new Li(e,t,null)}static fromSessionId(e,t){return new Li(e,null,t)}dispose(){this.session&&this.session.free()}}class om{constructor(e,t){this.content=e,this.device=t}}class am{constructor(e,t,s,i){this._roomId=e,this._results=t,this._errors=s,this._replayEntries=i}async write(e){return await Promise.all(this._replayEntries.map(async t=>{try{this._handleReplayAttack(this._roomId,t,e)}catch(s){this._errors.set(t.eventId,s)}})),{results:this._results,errors:this._errors}}async _handleReplayAttack(e,t,s){const{messageIndex:i,sessionId:r,eventId:o,timestamp:c}=t,l=await s.groupSessionDecryptions.get(e,r,i);if(l&&l.eventId!==o){const a=l.timestamp{const r=await i.decryptAll();rn(r.errors,e),rn(r.results,t),s.push(...r.replayEntries)})),new am(this._roomId,t,e,s)}finally{this.dispose()}}dispose(){for(const e of this._sessionDecryptions)e.dispose()}}class lm{constructor(e,t,s){this.sessionId=e,this.messageIndex=t,this.event=s}get eventId(){return this.event.event_id}get timestamp(){return this.event.origin_server_ts}}class hm{constructor(e,t,s,i){this.key=e,this.events=t,this.olmWorker=s,this.keyLoader=i,this.decryptionRequests=s?[]:void 0}async decryptAll(){const e=[],t=new Map;let s;return await this.keyLoader.useKey(this.key,async i=>{for(const r of this.events)try{const o=r.content.ciphertext;let c;if(this.olmWorker){const u=this.olmWorker.megolmDecrypt(i,o);this.decryptionRequests.push(u),c=await u.response()}else c=i.decrypt(o);const{plaintext:l}=c;let h;try{h=JSON.parse(l)}catch(u){throw new fe("PLAINTEXT_NOT_JSON",r,{plaintext:l,err:u})}if(h.room_id!==this.key.roomId)throw new fe("MEGOLM_WRONG_ROOM",r,{encryptedRoomId:h.room_id,eventRoomId:this.key.roomId});e.push(new lm(this.key.sessionId,c.message_index,r));const a=new Za(h,this.key.senderKey,this.key.claimedEd25519Key,r);t.set(r.event_id,a)}catch(o){if(o.name==="AbortError")return;s||(s=new Map),s.set(r.event_id,o)}}),{results:t,errors:s,replayEntries:e}}dispose(){if(this.decryptionRequests)for(const e of this.decryptionRequests)e.abort()}}function xn(n){var e;return(e=n.content)==null?void 0:e.sender_key}function Vn(n){var e;return(e=n.content)==null?void 0:e.session_id}function dm(n){var e;return(e=n.content)==null?void 0:e.ciphertext}function um(n){return typeof xn(n)=="string"&&typeof Vn(n)=="string"&&typeof dm(n)=="string"}class mm{constructor(){this.events=[]}get senderKey(){return xn(this.events[0])}get sessionId(){return Vn(this.events[0])}}function nn(n){return En(n,e=>`${xn(e)}|${Vn(e)}`,()=>new mm,(e,t)=>e.events.push(t))}class tc{isForSession(e,t,s){return this.roomId===e&&this.senderKey===t&&this.sessionId===s}get isBetter(){return this._isBetter}set isBetter(e){this._isBetter=e}}function sc(n,e){return n.first_known_index(){s=r.pickle(o)},t),this.isBetter===!1)return!1;s||(s=await e.useKey(this,(r,o)=>r.pickle(o)));const i={roomId:this.roomId,senderKey:this.senderKey,sessionId:this.sessionId,session:s,backup:this.backupStatus,source:this.keySource,claimedKeys:{ed25519:this.claimedEd25519Key}};return t.inboundGroupSessions.set(i),!0}get eventIds(){return this._eventIds}async _checkBetterThanKeyInStorage(e,t,s){if(this.isBetter!==void 0)return this.isBetter;let i=e.getCachedKey(this.roomId,this.senderKey,this.sessionId);if(!i){const r=await nc(this.roomId,this.senderKey,this.sessionId,s);r&&(r.hasSession?i=r:r.eventIds&&(this._eventIds=r.eventIds))}if(i){const r=i;await e.useKey(this,async o=>{await e.useKey(r,(c,l)=>{this.isBetter=sc(o,c),r.isBetter=!this.isBetter,this.isBetter&&t&&t(o,l)})})}else this.isBetter=!0;return this.isBetter}get backupStatus(){return Vr.NotBackedUp}}class _m extends Nn{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 Hi.DeviceMessage}loadInto(e){e.create(this.serializationKey)}}class pm extends Nn{constructor(e,t,s){super(),this._roomId=e,this.outboundSession=t,this.identityKeys=s,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 Hi.Outbound}loadInto(e){e.create(this.serializationKey)}}class gm extends Nn{constructor(e,t,s){super(),this._roomId=e,this._sessionId=t,this._backupInfo=s}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 Hi.Backup}loadInto(e){e.import_session(this.serializationKey)}get backupStatus(){return Vr.BackedUp}}class ic extends tc{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 fm(n){var s;const e=(s=n.event.content)==null?void 0:s.session_key,t=new _m(n);if(typeof t.roomId=="string"&&typeof t.sessionId=="string"&&typeof t.senderKey=="string"&&typeof e=="string")return t}function rc(n,e,t){var o;const s=t.session_key,i=t.sender_key,r=(o=t.sender_claimed_keys)==null?void 0:o.ed25519;if(typeof n=="string"&&typeof e=="string"&&typeof i=="string"&&typeof s=="string"&&typeof r=="string")return new gm(n,e,t)}async function nc(n,e,t,s){const i=await s.inboundGroupSessions.get(n,e,t);if(i)return new ic(i)}class ym{constructor(e,t){this.keyLoader=e,this.olmWorker=t}async addMissingKeyEventIds(e,t,s,i,r){let o=await r.inboundGroupSessions.get(e,t,s);if(!(o!=null&&o.session)){if(o){const c=new Set(o.eventIds);for(const l of i)c.add(l);o.eventIds=Array.from(c)}else o={roomId:e,senderKey:t,sessionId:s,eventIds:i};r.inboundGroupSessions.set(o)}}async getEventIdsForMissingKey(e,t,s,i){const r=await i.inboundGroupSessions.get(e,t,s);if(r&&!r.session)return r.eventIds}async hasSession(e,t,s,i){const r=await i.inboundGroupSessions.get(e,t,s);return typeof(r==null?void 0:r.session)=="string"}async prepareDecryptAll(e,t,s,i){const r=new Map,o=[];for(const h of t)um(h)?o.push(h):r.set(h.event_id,new fe("MEGOLM_INVALID_EVENT",h));const c=nn(o),l=[];return await Promise.all(Array.from(c.values()).map(async h=>{const a=await this.getRoomKey(e,h.senderKey,h.sessionId,s,i);if(a)l.push(new hm(a,h.events,this.olmWorker,this.keyLoader));else for(const u of h.events)r.set(u.event_id,new fe("MEGOLM_NO_SESSION",u))})),new cm(e,l,r)}async getRoomKey(e,t,s,i,r){if(i){const l=i.find(h=>h.isForSession(e,t,s));if(l&&await l.checkBetterThanKeyInStorage(this.keyLoader,r))return l}const o=this.keyLoader.getCachedKey(e,t,s);if(o)return o;const c=await nc(e,t,s,r);if(c&&c.serializationKey)return c}writeRoomKey(e,t){return e.write(this.keyLoader,t)}roomKeysFromDeviceMessages(e,t){var i,r;const s=[];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)!==ft||t.wrap("room_key",c=>{const l=fm(o);l?(c.set("roomId",l.roomId),c.set("id",l.sessionId),s.push(l)):(c.logLevel=c.level.Warn,c.set("invalid",!0))},t.level.Detail);return s}roomKeyFromBackup(e,t,s){return rc(e,t,s)}dispose(){this.keyLoader.dispose()}}class wm extends Ba{constructor(e,t,s){super(s),this.pickleKey=t,this.olm=e}getCachedKey(e,t,s){const i=this.findCachedKeyIndex(e,t,s);if(i!==-1)return this._getByIndexAndMoveUp(i).key}async useKey(e,t){const s=await this.allocateOperation(e);try{return await t(s.session,this.pickleKey)}finally{this.releaseOperation(s)}}get running(){return this._entries.some(e=>e.refCount!==0)}dispose(){for(let e=0;e{this.resolveUnusedOperation=e})),this.operationBecomesUnusedPromise}findIndexForAllocation(e){let t=this.findIndexSameKey(e);return t===-1&&(this.size{const l=i===-1?void 0:c[i];return r.isBest===!0&&r.isForSameSession(e,t,s)&&(!l||r.isBetter(l))?o:i},-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,s,i,r)=>{const o=t===-1?void 0:r[t];return s.refCount===0&&s.isForSameSession(e.roomId,e.senderKey,e.sessionId)&&(!o||!s.isBetter(o))?i: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 vm{constructor(e,t){this.key=e,this.session=t,this.refCount=1}isForSameSession(e,t,s){return this.key.roomId===e&&this.key.senderKey===t&&this.key.sessionId===s}isBetter(e){return sc(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 bm="m.megolm_backup.v1.curve25519-aes-sha2";class Dn{constructor(e,t){this.encryption=e,this.decryption=t}static fromAuthData(e,t,s){const i=e.public_key,r=new s.PkDecryption,o=new s.PkEncryption;try{const c=r.init_with_private_key(t);if(c!==i)throw new Error(`Bad backup key, public key does not match. Calculated ${c} but expected ${i}`);o.set_recipient_key(c)}catch(c){throw r.free(),o.free(),c}return new Dn(o,r)}decryptRoomKey(e){const t=this.decryption.decrypt(e.ephemeral,e.mac,e.ciphertext);return JSON.parse(t)}encryptRoomKey(e,t){const s={algorithm:ft,sender_key:e.senderKey,sender_claimed_keys:{ed25519:e.claimedEd25519Key},forwarding_curve25519_key_chain:[],session_key:t};return this.encryption.encrypt(JSON.stringify(s))}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 Sm=200;class km{constructor(e,t){this.info=e,this.crypto=t}}class Im extends $t{constructor(e,t,s,i,r,o=1e4){super(),this.hsApi=e,this.olm=t,this.keyLoader=s,this.storage=i,this.platform=r,this.maxDelay=o,this._stopped=!1,this._needsNewKey=!1,this._hasBackedUpAllKeys=!1,this.backupConfigDeferred=new As,this.backupConfigDeferred=new As}get hasStopped(){return this._stopped}get error(){return this._error}get version(){var e,t;return(t=(e=this.backupConfigDeferred.value)==null?void 0:e.info)==null?void 0:t.version}get needsNewKey(){return this._needsNewKey}get hasBackedUpAllKeys(){return this._hasBackedUpAllKeys}get operationInProgress(){return this._operationInProgress}async getRoomKey(e,t,s){if(this.needsNewKey)return;const i=await this.backupConfigDeferred.promise;if(!i)return;const r=await this.hsApi.roomKeyForRoomAndSession(i.info.version,e,t,{log:s}).response();if(!r.session_data)return;const o=i.crypto.decryptRoomKey(r.session_data);if((o==null?void 0:o.algorithm)===ft)return rc(e,t,o);o!=null&&o.algorithm&&s.set("unknown algorithm",o.algorithm)}markAllForBackup(e){return e.inboundGroupSessions.markAllAsNotBackedUp()}async load(e,t){const s=await e.readSecret("m.megolm_backup.v1");return s?(this.privateKey=new Uint8Array(this.platform.encoding.base64.decode(s)),!0):(this.backupConfigDeferred.resolve(void 0),!1)}async start(e){await e.wrap("KeyBackup.start",async t=>{if(this.privateKey&&!this.backupInfoRequest){let s;try{this.backupInfoRequest=this.hsApi.roomKeysVersion(void 0,{log:t}),s=await this.backupInfoRequest.response()}catch(i){if(i.name==="AbortError"){t.set("aborted",!0);return}else throw i}finally{this.backupInfoRequest=void 0}if(s.algorithm===bm){const i=Dn.fromAuthData(s.auth_data,this.privateKey,this.olm);this.backupConfigDeferred.resolve(new km(s,i)),this.emit("change")}else this.backupConfigDeferred.resolve(void 0),t.log({l:"Unknown backup algorithm",algorithm:s.algorithm});this.privateKey=void 0}this.flush(t)})}flush(e){this._operationInProgress||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 s=this._runFlushOperation(t);this._operationInProgress=s,this.emit("change");try{await s.result,this._hasBackedUpAllKeys=!0}catch(i){this._stopped=!0,i.name==="HomeServerError"&&(i.errcode==="M_WRONG_ROOM_KEYS_VERSION"||i.errcode==="M_NOT_FOUND")?(t.set("wrong_version",!0),this._needsNewKey=!0):(i.name!=="AbortError"||i.name==="StorageError"&&i.errcode==="AbortError")&&(this._error=i),t.catch(i)}this._operationInProgress=void 0,this.emit("change")})}_runFlushOperation(e){return new oa(async(t,s)=>{const i=await this.backupConfigDeferred.promise;if(!i)return;let r=0,o=0;for(;;){const c=this.platform.random()*this.maxDelay,l=this.platform.clock.createTimeout(c);t(l),await l.elapsed();const h=await this.storage.readTxn([J.inboundGroupSessions]);t(h),r=o+await h.inboundGroupSessions.countNonBackedUpSessions(),s(new vo(r,o));const a=(await h.inboundGroupSessions.getFirstNonBackedUpSessions(Sm)).map(g=>new ic(g));if(a.length===0){e.set("total",r);return}const u=await this.encodeKeysForBackup(a,i.crypto),p=this.hsApi.uploadRoomKeysToBackup(i.info.version,u,{log:e});t(p),await p.response(),await this.markKeysAsBackedUp(a,t),o+=a.length,s(new vo(r,o))}})}async encodeKeysForBackup(e,t){const s={rooms:{}},i=s.rooms;for(const r of e){let o=i[r.roomId];o||(o=i[r.roomId]={sessions:{}}),o.sessions[r.sessionId]=await this.encodeRoomKey(r,t)}return s}async markKeysAsBackedUp(e,t){const s=await this.storage.readWriteTxn([J.inboundGroupSessions]);t(s);try{await Promise.all(e.map(i=>s.inboundGroupSessions.markAsBackedUp(i.roomId,i.senderKey,i.sessionId)))}catch(i){throw s.abort(),i}await s.complete()}async encodeRoomKey(e,t){return await this.keyLoader.useKey(e,s=>{const i=s.first_known_index(),r=s.export_session(i);return{first_message_index:i,forwarded_count:0,is_verified:!1,session_data:t.encryptRoomKey(e,r)}})}dispose(){var e,t,s;(e=this.backupInfoRequest)==null||e.abort(),(s=(t=this.backupConfigDeferred.value)==null?void 0:t.crypto)==null||s.dispose()}}class vo{constructor(e,t){this.total=e,this.finished=t}}class Mm{constructor({pickleKey:e,olm:t,account:s,keyLoader:i,storage:r,now:o,ownDeviceId:c}){this._pickleKey=e,this._olm=t,this._account=s,this._keyLoader=i,this._storage=r,this._now=o,this._ownDeviceId=c}discardOutboundSession(e,t){t.outboundGroupSessions.remove(e)}async createRoomKeyMessage(e,t){let s=await t.outboundGroupSessions.get(e);if(s){const i=new this._olm.OutboundGroupSession;try{return i.unpickle(this._pickleKey,s.session),this._createRoomKeyMessage(i,e)}finally{i.free()}}}createWithheldMessage(e,t,s){return{algorithm:e.algorithm,code:t,reason:s,room_id:e.room_id,sender_key:this._account.identityKeys.curve25519,session_id:e.session_id}}async ensureOutboundSession(e,t){let s=new this._olm.OutboundGroupSession;try{const i=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let r;try{let o=await i.outboundGroupSessions.get(e);r=await this._readOrCreateSession(s,o,e,t,i),r&&this._writeSession(this._now(),s,e,i)}catch(o){throw i.abort(),o}return await i.complete(),r}finally{s.free()}}async _readOrCreateSession(e,t,s,i,r){if(t&&e.unpickle(this._pickleKey,t.session),!t||this._needsToRotate(e,t.createdAt,i)){t&&(e.free(),e=new this._olm.OutboundGroupSession),e.create();const o=this._createRoomKeyMessage(e,s);return await new pm(s,e,this._account.identityKeys).write(this._keyLoader,r),o}}_writeSession(e,t,s,i){i.outboundGroupSessions.set({roomId:s,session:t.pickle(this._pickleKey),createdAt:e})}async encrypt(e,t,s,i){let r=new this._olm.OutboundGroupSession;try{const o=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let c,l;try{let h=await o.outboundGroupSessions.get(e);c=await this._readOrCreateSession(r,h,e,i,o),l=this._encryptContent(e,r,t,s);const a=c?this._now():h.createdAt;this._writeSession(a,r,e,o)}catch(h){throw o.abort(),h}return await o.complete(),new Cm(l,c)}finally{r&&r.free()}}_needsToRotate(e,t,s){let i=6048e5;Number.isSafeInteger(s==null?void 0:s.rotation_period_ms)&&(i=s==null?void 0:s.rotation_period_ms);let r=100;if(Number.isSafeInteger(s==null?void 0:s.rotation_period_msgs)&&(r=s==null?void 0:s.rotation_period_msgs),this._now()>t+i||e.message_index()>=r)return!0}_encryptContent(e,t,s,i){const r=JSON.stringify({room_id:e,type:s,content:i}),o=t.encrypt(r);return{algorithm:ft,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:ft,chain_index:e.message_index()}}}class Cm{constructor(e,t){this.content=e,this.roomKeyMessage=t}}const bo="m.room.encrypted",So="m.room.history_visibility",Em=60*1e3;class Rm{constructor({room:e,deviceTracker:t,olmEncryption:s,megolmEncryption:i,megolmDecryption:r,encryptionParams:o,storage:c,keyBackup:l,notifyMissingMegolmSession:h,clock:a}){this._room=e,this._deviceTracker=t,this._olmEncryption=s,this._megolmEncryption=i,this._megolmDecryption=r,this._encryptionParams=o,this._senderDeviceCache=new Map,this._storage=c,this._keyBackup=l,this._notifyMissingMegolmSession=h,this._clock=a,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 s=e.filter(a=>a.isEncrypted&&!a.isDecrypted&&a.event).map(a=>a.event),i=nn(s),r=Array.from(i.values()),o=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]),c=await Promise.all(r.map(async a=>this._megolmDecryption.hasSession(this._room.id,a.senderKey,a.sessionId,o))),l=r.filter((a,u)=>!c[u]);if(l.length)for(var h=l.length-1;h>=0;h--){const a=l[h];await t.wrap("session",u=>this._requestMissingSessionFromBackup(a.senderKey,a.sessionId,u))}}notifyTimelineClosed(){this._senderDeviceCache=new Map}async writeSync(e,t,s,i){let r=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility,s);const o=[],c=[];if(await Js(e,h=>{var a;if(h.state_key===""&&h.type===So){const u=(a=h==null?void 0:h.content)==null?void 0:a.history_visibility;if(u!==r)return i.wrap({l:"history_visibility changed",from:r,to:u},async p=>{r=u;const g=await this._deviceTracker.writeHistoryVisibility(this._room,r,s,p);o.push(...g.added),c.push(...g.removed)})}}),t.size){const h=await this._deviceTracker.writeMemberChanges(this._room,t,r,s);o.push(...h.added),c.push(...h.removed)}c.length&&(i.log({l:"discardOutboundSession",leftUsers:c}),this._megolmEncryption.discardOutboundSession(this._room.id,s));let l=!1;return o.length&&(l=await this._addShareRoomKeyOperationForMembers(o,s,i)),{shouldFlush:l,historyVisibility:r}}afterSync({historyVisibility:e}){this._historyVisibility=e}async _loadHistoryVisibilityIfNeeded(e,t=void 0){var s,i;if(!e){t||(t=await this._storage.readTxn([this._storage.storeNames.roomState]));const r=await t.roomState.get(this._room.id,So,"");if(r)return(i=(s=r.event)==null?void 0:s.content)==null?void 0:i.history_visibility}return e}async prepareDecryptAll(e,t,s,i){var l,h,a;const r=new Map,o=[];for(const u of e)u.redacted_because||((l=u.unsigned)==null?void 0:l.redacted_because)||(((h=u.content)==null?void 0:h.algorithm)!==ft&&r.set(u.event_id,new Error("Unsupported algorithm: "+((a=u.content)==null?void 0:a.algorithm))),o.push(u));const c=await this._megolmDecryption.prepareDecryptAll(this._room.id,o,t,i);return new Tm(c,r,s,this,e)}async _processDecryptionResults(e,t,s,i,r,o){const c=e.filter(h=>{const a=s.get(h.event_id);return(a==null?void 0:a.code)==="MEGOLM_NO_SESSION"});if(!c.length)return;const l=nn(c);i===ts.Sync&&await Promise.all(Array.from(l.values()).map(async h=>{const a=h.events.map(u=>u.event_id);return this._megolmDecryption.addMissingKeyEventIds(this._room.id,h.senderKey,h.sessionId,a,r)})),this._keyBackup&&o.wrapDetached("check key backup",async h=>{if(h.set("source",i),h.set("events",c.length),h.set("sessions",l.size),i===ts.Sync){if(await this._clock.createTimeout(1e4).elapsed(),this._disposed)return;const a=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);await Promise.all(Array.from(l).map(async([u,p])=>{await this._megolmDecryption.hasSession(this._room.id,p.senderKey,p.sessionId,a)&&l.delete(u)}))}await Promise.all(Array.from(l.values()).map(a=>h.wrap("session",u=>this._requestMissingSessionFromBackup(a.senderKey,a.sessionId,u))))})}async _verifyDecryptionResults(e,t){await Promise.all(e.map(async s=>{let i=this._senderDeviceCache.get(s.senderCurve25519Key);i||(i=await this._deviceTracker.getDeviceByCurve25519Key(s.senderCurve25519Key,t),this._senderDeviceCache.set(s.senderCurve25519Key,i)),i&&s.setDevice(i)}))}async _fetchKeyAndVerifyDecryptionResults(e,t,s){const i=e.filter(r=>r.isVerificationUnknown);return i.length?s.wrap("fetch unverified senders",async r=>{const o=Array.from(i.reduce((a,u)=>a.add(u.encryptedEvent.sender),new Set));r.set("senders",o),await this._deviceTracker.devicesForUsers(o,t,r);const c=await this._storage.readTxn([this._storage.storeNames.deviceKeys]);await this._verifyDecryptionResults(i,c);const h=i.filter(a=>!a.isVerificationUnknown).reduce((a,u)=>(a.set(u.encryptedEvent.event_id,u),a),new Map);return new on(h,new Map,this)}):new on(new Map,new Map,this)}async _requestMissingSessionFromBackup(e,t,s){if(!this._keyBackup){s.set("enabled",!1),this._notifyMissingMegolmSession();return}s.set("id",t),s.set("senderKey",e);try{const i=await this._keyBackup.getRoomKey(this._room.id,t,s);if(i){if(i.senderKey!==e){s.set("wrong_sender_key",i.senderKey),s.logLevel=s.level.Warn;return}let r=!1,o;const c=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions]);try{r=await this._megolmDecryption.writeRoomKey(i,c),s.set("isBetter",r),r&&(o=i.eventIds)}catch(l){throw c.abort(),l}await c.complete(),r&&await s.wrap("retryDecryption",l=>this._room.notifyRoomKey(i,o||[],l))}}catch(i){i.name==="HomeServerError"&&i.errcode==="M_NOT_FOUND"?(s.error=i,s.logLevel=s.level.Error):s.set("not_found",!0)}}getEventIdsForMissingKey(e,t){return this._megolmDecryption.getEventIdsForMissingKey(this._room.id,e.senderKey,e.sessionId,t)}async ensureMessageKeyIsShared(e,t){var s;if(!(((s=this._lastKeyPreShareTime)==null?void 0:s.measure()){var r;const i=await this._megolmEncryption.ensureOutboundSession(this._room.id,this._encryptionParams);i&&((r=this._keyBackup)==null||r.flush(t),await t.wrap("share key",o=>this._shareNewRoomKey(i,e,o)))})(),await this._keySharePromise}finally{this._keySharePromise=null}}}async encrypt(e,t,s,i){var o;this._keySharePromise&&(i.set("waitForRunningKeyShare",!0),await this._keySharePromise);const r=await i.wrap("megolm encrypt",()=>this._megolmEncryption.encrypt(this._room.id,e,t,this._encryptionParams));return r.roomKeyMessage&&((o=this._keyBackup)==null||o.flush(i),await i.wrap("share key",c=>this._shareNewRoomKey(r.roomKeyMessage,s,c))),{type:bo,content:r.content}}needsToShareKeys(e){for(const t of e.values())if(t.hasJoined)return!0;return!1}async _shareNewRoomKey(e,t,s){this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,s);const i=await this._deviceTracker.devicesForTrackedRoom(this._room.id,t,s),r=Array.from(i.reduce((l,h)=>l.add(h.user_id),new Set));let o=await this._storage.readWriteTxn([this._storage.storeNames.operations]),c;try{c=this._writeRoomKeyShareOperation(e,r,o)}catch(l){throw o.abort(),l}await this._processShareRoomKeyOperation(c,t,s)}async _addShareRoomKeyOperationForMembers(e,t,s){const i=await this._megolmEncryption.createRoomKeyMessage(this._room.id,t);return i?(s.log({l:"share key for new members",userIds:e,id:i.session_id,chain_index:i.chain_index}),this._writeRoomKeyShareOperation(i,e,t),!0):!1}async flushPendingRoomKeyShares(e,t,s){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 i of t)i.type==="share_room_key"&&await s.wrap("operation",r=>this._processShareRoomKeyOperation(i,e,r))}finally{this._isFlushingRoomKeyShares=!1}}}_writeRoomKeyShareOperation(e,t,s){const r={id:Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(),type:"share_room_key",scope:this._room.id,userIds:t,roomKeyMessage:e};return s.operations.add(r),r}async _processShareRoomKeyOperation(e,t,s){s.set("id",e.id),this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,s);const i=await this._deviceTracker.devicesForRoomMembers(this._room.id,e.userIds,t,s),r=await s.wrap("olm encrypt",c=>this._olmEncryption.encrypt("m.room_key",e.roomKeyMessage,i,t,c)),o=i.filter(c=>!r.some(l=>l.device===c));await s.wrap("send",c=>this._sendMessagesToDevices(bo,r,t,c)),o.length&&await s.wrap("missingDevices",async c=>{c.set("devices",o.map(a=>a.device_id));const l=e.userIds.filter(a=>o.some(u=>u.user_id===a));c.set("unsentUserIds",l),e.userIds=l,await this._updateOperationsStore(a=>a.update(e));const h=this._megolmEncryption.createWithheldMessage(e.roomKeyMessage,"m.no_olm","OTKs exhausted");await this._sendSharedMessageToDevices("org.matrix.room_key.withheld",h,o,t,c)}),await this._updateOperationsStore(c=>c.remove(e.id))}async _updateOperationsStore(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.operations]);try{e(t.operations)}catch(s){throw t.abort(),s}await t.complete()}async _sendSharedMessageToDevices(e,t,s,i,r){const o=ti(s,h=>h.user_id),c={messages:Array.from(o.entries()).reduce((h,[a,u])=>(h[a]=u.reduce((p,g)=>(p[g.device_id]=t,p),{}),h),{})},l=Pe();await i.sendToDevice(e,c,l,{log:r}).response()}async _sendMessagesToDevices(e,t,s,i){i.set("messages",t.length);const r=Fi(t),o=Pe();await s.sendToDevice(e,r,o,{log:i}).response()}filterUndecryptedEventEntriesForKeys(e,t){return e.filter(s=>{var i,r;if(s.isEncrypted&&!s.isDecrypted){const{event:o}=s;if(o){const c=(i=o.content)==null?void 0:i.sender_key,l=(r=o.content)==null?void 0:r.session_id;return t.some(h=>c===h.senderKey&&l===h.sessionId)}}return!1})}dispose(){this._disposed=!0}}class Tm{constructor(e,t,s,i,r){this._megolmDecryptionPreparation=e,this._extraErrors=t,this._source=s,this._roomEncryption=i,this._events=r}async decrypt(){return new Am(await this._megolmDecryptionPreparation.decrypt(),this._extraErrors,this._source,this._roomEncryption,this._events)}dispose(){this._megolmDecryptionPreparation.dispose()}}class Am{constructor(e,t,s,i,r){this._megolmDecryptionChanges=e,this._extraErrors=t,this._source=s,this._roomEncryption=i,this._events=r}async write(e,t){const{results:s,errors:i}=await this._megolmDecryptionChanges.write(e);return rn(this._extraErrors,i),await this._roomEncryption._processDecryptionResults(this._events,s,i,this._source,e,t),new on(s,i,this._roomEncryption)}}class on{constructor(e,t,s){this.results=e,this.errors=t,this._roomEncryption=s}applyToEntries(e,t=void 0){for(const s of e){const i=this.results.get(s.id);if(i)s.setDecryptionResult(i),t==null||t(s);else{const r=this.errors.get(s.id);r&&(s.setDecryptionError(r),t==null||t(s))}}}verifyKnownSenders(e){return this._roomEncryption._verifyDecryptionResults(Array.from(this.results.values()),e)}get hasUnverifiedSenders(){for(const e of this.results.values())if(e.isVerificationUnknown)return!0;return!1}fetchAndVerifyRemainingSenders(e,t){return this._roomEncryption._fetchKeyAndVerifyDecryptionResults(Array.from(this.results.values()),e,t)}}class xm{constructor(){this._map=new Map}async takeLock(e){let t=this._map.get(e);return t?await t.take():(t=new Ja,t.tryTake(),this._map.set(e,t)),t.released().then(()=>{Promise.resolve().then(()=>{t.isTaken||this._map.delete(e)})}),t}}function oc(n,e,t=!1){for(const[s,i]of Object.entries(e)){if(n[s]instanceof Object&&i){oc(n[s],i);continue}if(i!=null||!t){n[s]=i;continue}}return n}/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */var an=(n=>(n.Video="video",n.Audio="audio",n))(an||{});function is(n){return n==null?void 0:n.getAudioTracks()[0]}function xt(n){return n==null?void 0:n.getVideoTracks()[0]}function cn(n,e,t){return t.wrap("mute",s=>{s.set("cameraMuted",e.camera),s.set("microphoneMuted",e.microphone);const i=is(n.userMedia);if(i){const o=!e.microphone;s.set("microphone enabled",o),i.enabled=o}const r=xt(n.userMedia);if(r){const o=!e.camera;s.set("camera enabled",o),r.enabled=o}})}class si{constructor(e=!1,t=!1,s=!1,i=!1){this.isMicrophoneMuted=e,this.isCameraMuted=t,this.hasMicrophoneTrack=s,this.hasCameraTrack=i}updateTrackInfo(e){this.hasMicrophoneTrack=!!is(e),this.hasCameraTrack=!!xt(e)}get microphone(){return!this.hasMicrophoneTrack||this.isMicrophoneMuted}get camera(){return!this.hasCameraTrack||this.isCameraMuted}toggleCamera(){return new si(this.microphone,!this.camera,this.hasMicrophoneTrack,this.hasCameraTrack)}toggleMicrophone(){return new si(!this.microphone,this.camera,this.hasMicrophoneTrack,this.hasCameraTrack)}equals(e){return this.microphone===e.microphone&&this.camera===e.camera}}const fs="call",jr=3600*1e3;var q=(n=>(n.GroupCall="org.matrix.msc3401.call",n.GroupCallMember="org.matrix.msc3401.call.member",n.Invite="m.call.invite",n.Candidates="m.call.candidates",n.Answer="m.call.answer",n.Hangup="m.call.hangup",n.Reject="m.call.reject",n.SelectAnswer="m.call.select_answer",n.Negotiate="m.call.negotiate",n.SDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",n.SDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",n.Replaces="m.call.replaces",n.AssertedIdentity="m.call.asserted_identity",n.AssertedIdentityPrefix="org.matrix.call.asserted_identity",n))(q||{});const dt="org.matrix.msc3077.sdp_stream_metadata";var Zt=(n=>(n.Usermedia="m.usermedia",n.Screenshare="m.screenshare",n))(Zt||{}),ee=(n=>(n.UserHangup="user_hangup",n.LocalOfferFailed="local_offer_failed",n.NoUserMedia="no_user_media",n.UnknownDevices="unknown_devices",n.SendInvite="send_invite",n.CreateAnswer="create_answer",n.SendAnswer="send_answer",n.SetRemoteDescription="set_remote_description",n.SetLocalDescription="set_local_description",n.AnsweredElsewhere="answered_elsewhere",n.IceFailed="ice_failed",n.InviteTimeout="invite_timeout",n.Replaced="replaced",n.SignallingFailed="signalling_timeout",n.UserBusy="user_busy",n.Transfered="transferred",n.NewSession="new_session",n))(ee||{}),Ki=(n=>(n.Ring="m.ring",n.Prompt="m.prompt",n.Room="m.room",n))(Ki||{}),yr=(n=>(n.Video="m.video",n.Voice="m.voice",n))(yr||{}),ln=(n=>(n[n.InviteGlare=0]="InviteGlare",n[n.Handle=1]="Handle",n[n.Ignore=2]="Ignore",n))(ln||{});class Vm{constructor(e,t){this.userMedia=e,this.screenShare=t}}class Nm{constructor(e,t,s){this.callId=e,this.options=t,this.logItem=s,this._state=$.Fledgling,this.candidateSendQueue=[],this.remoteCandidateBuffer=new Map,this.disposables=new li,this.statePromiseMap=new Map,this._remoteTrackToStreamId=new Map,this._remoteStreams=new Map,this.makingOffer=!1,this.ignoreOffer=!1,this.sentEndOfCandidates=!1,this._remoteMuteSettings=new si,this.onIceConnectionStateChange=async(r,o)=>{var l,h;if(this._state===$.Ended)return;let c=!1;if(r=="connected")(l=this.iceDisconnectedTimeout)==null||l.abort(),this.iceDisconnectedTimeout=void 0,this.setState($.Connected,o);else if(r=="failed")c=!0,(h=this.iceDisconnectedTimeout)==null||h.abort(),this.iceDisconnectedTimeout=void 0,await this._hangup(ee.IceFailed,o);else if(r=="disconnected"){c=!0,this.iceDisconnectedTimeout=this.options.createTimeout(30*1e3);try{await this.iceDisconnectedTimeout.elapsed(),await this._hangup(ee.IceFailed,o)}catch(a){if(!(a instanceof rt))throw a}}if(c){const a=await this.peerConnection.getStats(),u={};a.forEach((p,g)=>{u[g]=p}),o.set("peerConnectionStats",u)}},s.log({l:"create PeerCall",id:e}),this._remoteMedia=new Vm,this.peerConnection=t.webRTC.createPeerConnection(this.options.forceTURN,[this.options.turnServer.get()],0),this.disposables.track(this.options.turnServer.subscribe(r=>{this.logItem.log({l:"updating turn server",turnServer:r}),this.peerConnection.setConfiguration({iceServers:[r]})}));const i=(r,o,c)=>{const l=a=>{this.options.errorBoundary.try(()=>o(a))};this.peerConnection.addEventListener(r,l);const h=()=>{this.peerConnection.removeEventListener(r,l)};this.disposables.track(h)};i("iceconnectionstatechange",async()=>{const r=this.peerConnection.iceConnectionState;await s.wrap({l:"onIceConnectionStateChange",status:r},async o=>{await this.onIceConnectionStateChange(r,o)})}),i("icecandidate",async r=>{await s.wrap("onLocalIceCandidate",async o=>{r.candidate&&await this.handleLocalIceCandidate(r.candidate,o)})}),i("icegatheringstatechange",async()=>{const r=this.peerConnection.iceGatheringState;await s.wrap({l:"onIceGatheringStateChange",status:r},async o=>{await this.handleIceGatheringState(r,o)})}),i("track",r=>{s.wrap("onRemoteTrack",o=>{this.onRemoteTrack(r.track,r.streams,o)})}),i("datachannel",r=>{s.wrap("onRemoteDataChannel",o=>{this._dataChannel=r.channel,this.options.emitUpdate(this,void 0,o)})}),i("negotiationneeded",()=>{var c,l;const r=this.peerConnection.signalingState,o=()=>s.wrap({l:"onNegotiationNeeded",signalingState:r},h=>this.handleNegotiation(h));this.responsePromiseChain=(l=(c=this.responsePromiseChain)==null?void 0:c.then(o))!=null?l:o(),this.responsePromiseChain.catch(h=>this.options.errorBoundary.reportError(h))})}get dataChannel(){return this._dataChannel}get state(){return this._state}get hangupReason(){return this._hangupReason}get remoteMedia(){return this._remoteMedia}get remoteMuteSettings(){return this._remoteMuteSettings}call(e,t,s){return s.wrap("call",async i=>{var r;this._state===$.Fledgling&&(i.set("signalingState",this.peerConnection.signalingState),this.direction=Ri.Outbound,this.setState($.CreateOffer,i),this.localMuteSettings=t,await this.updateLocalMedia(e,i),(r=this.localMedia)!=null&&r.dataChannelOptions&&(this._dataChannel=this.peerConnection.createDataChannel("channel",this.localMedia.dataChannelOptions)),await this.waitForState([$.InviteSent,$.CreateAnswer]))})}answer(e,t,s){return s.wrap("answer",async i=>{if(this._state!==$.Ringing)return;this.setState($.CreateAnswer,i),this.localMuteSettings=t,await this.updateLocalMedia(e,i);let r;try{r=await this.peerConnection.createAnswer()}catch(o){await i.wrap("Failed to create answer",c=>{c.catch(o),this.terminate(De.Local,ee.CreateAnswer,c)});return}try{await this.peerConnection.setLocalDescription(r),this.setState($.Connecting,i)}catch(o){await i.wrap("Error setting local description!",c=>{c.catch(o),this.terminate(De.Local,ee.SetLocalDescription,c)});return}try{await this.delay(200)}catch{return}await this.sendAnswer(i)})}setMedia(e,t){return t.wrap("setMedia",async s=>{s.set("userMedia_audio",!!is(e.userMedia)),s.set("userMedia_video",!!xt(e.userMedia)),s.set("screenShare_video",!!xt(e.screenShare)),s.set("datachannel",!!e.dataChannelOptions),await this.updateLocalMedia(e,s);const i={call_id:this.callId,version:1,[dt]:this.getSDPMetadata()};await this.sendSignallingMessage({type:q.SDPStreamMetadataChangedPrefix,content:i},s)})}setMuted(e,t){return t.wrap("setMuted",async s=>{if(this.localMuteSettings=e,s.set("cameraMuted",e.camera),s.set("microphoneMuted",e.microphone),this.localMedia){cn(this.localMedia,e,s);const i={call_id:this.callId,version:1,[dt]:this.getSDPMetadata()};await this.sendSignallingMessage({type:q.SDPStreamMetadataChangedPrefix,content:i},s)}})}hangup(e,t){return t.wrap("hangup",s=>this._hangup(e,s))}async _hangup(e,t){this._state===$.Ended||this._state===$.Ending||(this.setState($.Ending,t),await this.sendHangupWithCallId(this.callId,e,t),this.terminate(De.Local,e,t))}getMessageAction(e){const t=this.callId===e.content.call_id;return e.type===q.Invite&&!t?0:t?1:2}handleIncomingSignallingMessage(e,t,s){let i;return s.wrap({l:"receive signalling message",type:e.type,callId:e.content.call_id,payload:e.content},async r=>{var o;if(i=r,this.getMessageAction(e)!==1){r.set("wrongCallId",!0);return}switch(e.type){case q.Invite:await this.handleFirstInvite(e.content,t,r);break;case q.Answer:await this.handleAnswer(e.content,t,r);break;case q.Negotiate:await this.onNegotiateReceived(e.content,r);break;case q.Candidates:await this.handleRemoteIceCandidates(e.content,t,r);break;case q.SDPStreamMetadataChanged:case q.SDPStreamMetadataChangedPrefix:this.updateRemoteSDPStreamMetadata(e.content[dt],r);break;case q.Hangup:r.set("reason",e.content.reason),this.terminate(De.Remote,(o=e.content.reason)!=null?o:ee.UserHangup,r);break;default:r.log(`Unknown event type for call: ${e.type}`);break}}),i}sendHangupWithCallId(e,t,s){const i={call_id:e,version:1};return t&&(i.reason=t),this.sendSignallingMessage({type:q.Hangup,content:i},s)}async handleNegotiation(e){this.makingOffer=!0;try{try{await this.peerConnection.setLocalDescription()}catch(s){e.log("Error setting local description!").catch(s),this.terminate(De.Local,ee.SetLocalDescription,e);return}if(this.peerConnection.iceGatheringState==="gathering")try{await this.delay(200)}catch{return}if(this._state===$.Ended)return;const t=this.peerConnection.localDescription;if(e.set("includedCandidates",this.candidateSendQueue.length),this.candidateSendQueue=[],this._state===$.CreateOffer){const s={call_id:this.callId,offer:t,[dt]:this.getSDPMetadata(),version:1,lifetime:Si};await this.sendSignallingMessage({type:q.Invite,content:s},e),this.setState($.InviteSent,e)}else if(this._state===$.Connected||this._state===$.Connecting){const s={call_id:this.callId,description:t,[dt]:this.getSDPMetadata(),version:1,lifetime:Si};await this.sendSignallingMessage({type:q.Negotiate,content:s},e)}}finally{this.makingOffer=!1}if(this.sendCandidateQueue(e),this._state===$.InviteSent){const t=this.logItem.child("invite timeout");e.refDetached(t),await t.run(async s=>{try{await this.delay(Si)}catch{return}this._state===$.InviteSent&&await this._hangup(ee.InviteTimeout,s)})}}handleInviteGlare(e,t,s){if(e.type!==q.Invite)return{shouldReplace:!1};const{content:i}=e,r=i.call_id,o=this.callId>r;let c;return s.wrap("handling call glare",async l=>{c=l,o?(l.log("Glare detected: answering incoming call "+r+" and canceling outgoing call "),this._state!==$.Fledgling&&this._state!==$.CreateOffer&&await this.sendHangupWithCallId(this.callId,ee.Replaced,l),this.close(ee.Replaced,l),this.dispose()):(l.log("Glare detected: rejecting incoming call "+r+" and keeping outgoing call "),await this.sendHangupWithCallId(r,ee.Replaced,l))}),{shouldReplace:o,log:c}}handleHangupReceived(e,t){this.terminate(De.Remote,e.reason||ee.UserHangup,t)}async handleFirstInvite(e,t,s){this._state!==$.Fledgling||this.opponentPartyId!==void 0||await this.handleInvite(e,t,s)}async handleInvite(e,t,s){var r;this.opponentPartyId=t,this.direction=Ri.Inbound;const i=e[dt];i?this.updateRemoteSDPStreamMetadata(i,s):s.log("Call did not get any SDPStreamMetadata! Can not send/receive multiple streams");try{await this.peerConnection.setRemoteDescription(e.offer),await this.addBufferedIceCandidates(s)}catch(o){await s.wrap("Call failed to set remote description",async c=>(c.catch(o),this.terminate(De.Local,ee.SetRemoteDescription,c)));return}if(this.peerConnection.getReceivers().length===0){await s.wrap("Call no remote stream or no tracks after setting remote description!",async o=>this.terminate(De.Local,ee.SetRemoteDescription,o));return}this.setState($.Ringing,s);try{await this.delay((r=e.lifetime)!=null?r:Si)}catch{return}this._state===$.Ringing&&(s.log("Invite has expired. Hanging up."),this.hangupParty=De.Remote,this.setState($.Ended,s),this.peerConnection.signalingState!="closed"&&this.peerConnection.close())}async handleAnswer(e,t,s){if(this._state===$.Ended){s.log("Ignoring answer because call has ended");return}if(this.opponentPartyId!==void 0){s.log(`Ignoring answer: we already have an answer/reject from ${this.opponentPartyId}`);return}this.opponentPartyId=t,await this.addBufferedIceCandidates(s),this.setState($.Connecting,s);const i=e[dt];i?this.updateRemoteSDPStreamMetadata(i,s):s.log("Did not get any SDPStreamMetadata! Can not send/receive multiple streams");try{await this.peerConnection.setRemoteDescription(e.answer)}catch(r){await s.wrap("Failed to set remote description",o=>{o.catch(r),this.terminate(De.Local,ee.SetRemoteDescription,o)});return}}async handleIceGatheringState(e,t){if(e==="complete"&&!this.sentEndOfCandidates){const s={candidate:""};await this.queueCandidate(s,t),this.sentEndOfCandidates=!0}}async handleLocalIceCandidate(e,t){t.set("sdpMid",e.sdpMid),t.set("candidate",e.candidate),this._state!==$.Ended&&(e.candidate!==""||!this.sentEndOfCandidates)&&(await this.queueCandidate(e,t),e.candidate===""&&(this.sentEndOfCandidates=!0))}async handleRemoteIceCandidates(e,t,s){if(this.state===$.Ended){s.log("Ignoring remote ICE candidate because call has ended");return}const i=e.candidates;if(!i){s.log("Ignoring candidates event with no candidates!");return}const r=e.version===0?null:t||null;if(this.opponentPartyId===void 0){s.log(`Buffering ${i.length} candidates until we pick an opponent`);const o=this.remoteCandidateBuffer.get(r)||[];o.push(...i),this.remoteCandidateBuffer.set(r,o);return}if(this.opponentPartyId!==t){s.log(`Ignoring candidates from party ID ${t}: we have chosen party ID ${this.opponentPartyId}`);return}await this.addIceCandidates(i,s)}async onNegotiateReceived(e,t){const s=e.description;if(!s||!s.sdp||!s.type){t.log("Ignoring invalid m.call.negotiate event");return}const i=this.direction===Ri.Inbound,r=s.type==="offer"&&(this.makingOffer||this.peerConnection.signalingState!=="stable");if(this.ignoreOffer=!i&&r,this.ignoreOffer){t.log("Ignoring colliding negotiate event because we're impolite");return}const o=e[dt];o?this.updateRemoteSDPStreamMetadata(o,t):t.log("Received negotiation event without SDPStreamMetadata!");try{if(await this.peerConnection.setRemoteDescription(s),s.type==="offer"){await this.peerConnection.setLocalDescription();const c={call_id:this.callId,description:this.peerConnection.localDescription,[dt]:this.getSDPMetadata(),version:1,lifetime:Si};await this.sendSignallingMessage({type:q.Negotiate,content:c},t)}}catch(c){t.log("Failed to complete negotiation").catch(c)}}async sendAnswer(e){const t=this.peerConnection.localDescription,s={call_id:this.callId,version:1,answer:{sdp:t.sdp,type:t.type},[dt]:this.getSDPMetadata()};e.log(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`),this.candidateSendQueue=[];try{await this.sendSignallingMessage({type:q.Answer,content:s},e)}catch(i){throw this.terminate(De.Local,ee.SendAnswer,e),i}this.sendCandidateQueue(e)}async queueCandidate(e,t){var i;if(this.candidateSendQueue.push(e),this._state===$.Ringing)return;this.flushCandidatesLog=(i=this.flushCandidatesLog)!=null?i:this.logItem.child("flush candidate queue"),t.refDetached(this.flushCandidatesLog);const{flushCandidatesLog:s}=this;try{await this.delay(this.direction===Ri.Inbound?500:2e3)}catch{return}this.sendCandidateQueue(s),this.flushCandidatesLog=void 0}async sendCandidateQueue(e){if(this.candidateSendQueue.length===0||this._state===$.Ended)return;const t=this.candidateSendQueue;return this.candidateSendQueue=[],e.wrap({l:"send candidates",size:t.length},async s=>{try{await this.sendSignallingMessage({type:q.Candidates,content:{call_id:this.callId,version:1,candidates:t}},s),await this.sendCandidateQueue(s)}catch(i){s.catch(i),this.terminate(De.Local,ee.SignallingFailed,s)}})}updateRemoteSDPStreamMetadata(e,t){this.remoteSDPStreamMetadata=oc(this.remoteSDPStreamMetadata||{},e,!0),this.updateRemoteMedia(t)}async addBufferedIceCandidates(e){if(this.remoteCandidateBuffer&&this.opponentPartyId){const t=this.remoteCandidateBuffer.get(this.opponentPartyId);t&&(e.log(`Adding ${t.length} buffered candidates for opponent ${this.opponentPartyId}`),await this.addIceCandidates(t,e)),this.remoteCandidateBuffer=void 0}}async addIceCandidates(e,t){for(const s of e){let i;(s.sdpMid===null||s.sdpMid===void 0)&&(s.sdpMLineIndex===null||s.sdpMLineIndex===void 0)?i=t.log("Got remote end-of-ICE candidates"):i=t.log(`Adding remote ICE ${s.sdpMid} candidate: ${s.candidate}`);try{await this.peerConnection.addIceCandidate(s)}catch(r){this.ignoreOffer||i.catch(r)}}}setState(e,t){if(e!==this._state){t.log({l:"change state",status:e,oldState:this._state}),this._state,this._state=e;let s=this.statePromiseMap.get(e);s&&(s.resolve(),this.statePromiseMap.delete(e)),this.options.emitUpdate(this,void 0,t)}}waitForState(e){return Promise.race(e.map(t=>{let s=this.statePromiseMap.get(t);if(!s){let i;const r=new Promise(o=>{i=o});s={resolve:i,promise:r},this.statePromiseMap.set(t,s)}return s.promise}))}terminate(e,t,s){this._state!==$.Ended&&(this.hangupParty=e,this._hangupReason=t,this.setState($.Ended,s),this.localMedia=void 0,this.peerConnection&&this.peerConnection.signalingState!=="closed"&&this.peerConnection.close())}getSDPMetadata(){var t,s,i,r,o,c;const e={};if((t=this.localMedia)!=null&&t.userMedia){const l=this.localMedia.userMedia.id;e[l]={purpose:Zt.Usermedia,audio_muted:(i=(s=this.localMuteSettings)==null?void 0:s.microphone)!=null?i:!1,video_muted:(o=(r=this.localMuteSettings)==null?void 0:r.camera)!=null?o:!1}}if((c=this.localMedia)!=null&&c.screenShare){const l=this.localMedia.screenShare.id;e[l]={purpose:Zt.Screenshare}}return e}findReceiverForStream(e,t){return this.peerConnection.getReceivers().find(s=>s.track.kind===e&&this._remoteTrackToStreamId.get(s.track.id)===t)}findTransceiverForTrack(e){return this.peerConnection.getTransceivers().find(t=>{var s;return((s=t.sender.track)==null?void 0:s.id)===e.id})}onRemoteTrack(e,t,s){if(s.set("kind",e.kind),s.set("id",e.id),s.set("streams",t.map(r=>r.id)),t.length===0){s.log({l:`ignoring ${e.kind} streamless track`,id:e.id});return}const i=t[0];if(this._remoteTrackToStreamId.set(e.id,i.id),!this._remoteStreams.has(i.id)){const r=c=>{this.logItem.wrap({l:"removetrack",id:c.track.id},l=>{const h=this._remoteTrackToStreamId.get(c.track.id);if(h){this._remoteTrackToStreamId.delete(c.track.id);const a=this._remoteStreams.get(h);a&&a.stream.getTracks().length===0&&(this.disposables.disposeTracked(o),this._remoteStreams.delete(i.id),this.updateRemoteMedia(l))}})};i.addEventListener("removetrack",r);const o=()=>{i.removeEventListener("removetrack",r)};this.disposables.track(o),this._remoteStreams.set(i.id,{disposeListener:o,stream:i})}this.updateRemoteMedia(s)}updateRemoteMedia(e){e.wrap("reevaluating remote media",t=>{var s,i;if(this._remoteMedia.userMedia=void 0,this._remoteMedia.screenShare=void 0,this.remoteSDPStreamMetadata)for(const r of this._remoteStreams.values()){const{stream:o}=r,c=this.remoteSDPStreamMetadata[o.id];if(c)if(c.purpose===Zt.Usermedia){this._remoteMedia.userMedia=o;const l=this.findReceiverForStream(an.Audio,o.id);l&&(l.track.enabled=!c.audio_muted);const h=this.findReceiverForStream(an.Video,o.id);h&&(h.track.enabled=!c.video_muted),this._remoteMuteSettings=new si((s=c.audio_muted)!=null?s:!1,(i=c.video_muted)!=null?i:!1,!!(l!=null&&l.track),!!(h!=null&&h.track)),t.log({l:"setting userMedia",micMuted:this._remoteMuteSettings.microphone,cameraMuted:this._remoteMuteSettings.camera})}else c.purpose===Zt.Screenshare&&(this._remoteMedia.screenShare=o,t.log("setting screenShare"));else t.log({l:"no metadata yet for stream, ignoring for now",id:o.id})}this.options.emitUpdate(this,void 0,t)})}updateLocalMedia(e,t){return t.wrap("updateLocalMedia",async s=>{var o,c;const i=this.peerConnection.getSenders(),r=async(l,h,a)=>{const u=async(p,g)=>{const f=i.find(M=>M.track===p),v=l!=null?l:h;if(v!==h&&(p&&(v.removeTrack(p),p.stop()),g&&v.addTrack(g)),g&&f)try{await s.wrap(`attempting to replace ${a} ${g.kind} track`,M=>f.replaceTrack(g));return}catch{}f&&s.wrap(`removing ${a} ${f.track.kind} track`,M=>{this.peerConnection.removeTrack(f)}),g&&s.wrap(`adding ${a} ${g.kind} track`,M=>{const R=this.peerConnection.addTrack(g,v);this.options.webRTC.prepareSenderForPurpose(this.peerConnection,R,a)})};!l&&!h||(await u(is(l),is(h)),await u(xt(l),xt(h)))};await r((o=this.localMedia)==null?void 0:o.userMedia,e==null?void 0:e.userMedia,Zt.Usermedia),await r((c=this.localMedia)==null?void 0:c.screenShare,e==null?void 0:e.screenShare,Zt.Screenshare),this.localMedia||(this.localMedia=e)})}async delay(e){const t=this.disposables.track(this.options.createTimeout(e));try{await t.elapsed()}finally{this.disposables.untrack(t)}}sendSignallingMessage(e,t){return t.wrap({l:"send",id:e.type},async s=>this.options.sendSignallingMessage(e,s))}dispose(){var e;this.disposables.dispose(),(e=this.iceDisconnectedTimeout)==null||e.abort(),this.peerConnection.close(),this.options.emitUpdate=(t,s,i)=>{i.log("emitting update from PeerCall after disposal",this.logItem.level.Error),console.trace("emitting update from PeerCall after disposal")}}close(e,t){e===void 0&&(e=ee.UserHangup),this.terminate(De.Local,e,t)}}var De=(n=>(n.Local="local",n.Remote="remote",n))(De||{}),$=(n=>(n.Fledgling="fledgling",n.CreateOffer="create_offer",n.InviteSent="invite_sent",n.CreateAnswer="create_answer",n.Connecting="connecting",n.Connected="connected",n.Ringing="ringing",n.Ending="ending",n.Ended="ended",n))($||{}),Ri=(n=>(n.Inbound="inbound",n.Outbound="outbound",n))(Ri||{});const Si=6e4;function Dm(n){return n===q.Invite||n===q.Candidates||n===q.Answer||n===q.Hangup||n===q.SDPStreamMetadataChanged||n===q.SDPStreamMetadataChangedPrefix||n===q.Negotiate}class ac{constructor(e){this.errorCallback=e}try(e,t){try{let s=e();return s instanceof Promise&&(s=s.catch(i=>(this._error=i,this.reportError(i),t))),s}catch(s){return this._error=s,this.reportError(s),t}}reportError(e){try{this.errorCallback(e)}catch(t){console.error("error in ErrorBoundary callback",t)}}get error(){return this._error}}const Um=[ee.UserHangup,ee.AnsweredElsewhere,ee.Replaced,ee.UserBusy,ee.Transfered,ee.NewSession];class Om{constructor(e,t,s,i){this.localMedia=e,this.localMuteSettings=t,this.turnServer=s,this.logItem=i,this.retryCount=0,this.queuedSignallingMessages=[],this.outboundSeqCounter=0}get canDequeueNextSignallingMessage(){if(this.queuedSignallingMessages.length===0)return!1;const t=this.queuedSignallingMessages[0].content.seq;return this.lastIgnoredSeqNr!==void 0&&t===this.lastIgnoredSeqNr+1?!0:this.lastProcessedSeqNr===void 0?t===0:t<=this.lastProcessedSeqNr+1}dispose(){var e;(e=this.peerCall)==null||e.dispose(),this.localMedia.dispose(),this.logItem.finish()}}class Pm{constructor(e,t,s,i){this.member=e,this.callDeviceMembership=t,this.options=s,this.errorBoundary=new ac(r=>{this.options.emitUpdate(this,"error"),this.connection&&this.connection.logItem.log("error at boundary").catch(r)}),this.emitUpdateFromPeerCall=async(r,o,c)=>{const l=this.connection;if(r.state===$.Ringing)l.logItem.wrap("ringing, answer peercall",h=>(c.refDetached(h),r.answer(l.localMedia,l.localMuteSettings,h)));else if(r.state===$.Ended){const h=r.hangupReason;if(r.dispose(),l.peerCall=void 0,h&&!Um.includes(h)){l.retryCount+=1;const{retryCount:a}=l;await l.logItem.wrap({l:"retry connection",retryCount:a},async u=>{if(c.refDetached(u),a<=3)await this.callIfNeeded(u);else{const p=await this.disconnect(!1);p&&u.refDetached(p)}})}}this.options.emitUpdate(this,o)},this.sendSignallingMessage=async(r,o)=>{const c=r;c.content.seq=this.connection.outboundSeqCounter++,c.content.conf_id=this.options.confId,c.content.device_id=this.options.ownDeviceId,c.content.party_id=this.options.ownDeviceId,c.content.sender_session_id=this.options.sessionId,c.content.dest_session_id=this.sessionId;let l,h=r.type;const a=await this.options.encryptDeviceMessage(this.member.userId,this.deviceId,c,o);a?(l=Fi(a),h="m.room.encrypted"):l=Fi([{content:c.content,device:this}]),o.set("payload",c.content),await this.options.hsApi.sendToDevice(h,l,Pe(),{log:o}).response()},this._renewExpireTimeout(i)}get error(){return this.errorBoundary.error}get usesFoci(){const e=this.callDeviceMembership["m.foci.active"];return Array.isArray(e)&&e.length>0}_renewExpireTimeout(e){var i;(i=this.expireTimeout)==null||i.dispose(),this.expireTimeout=void 0;const t=Rr(this.callDeviceMembership);if(typeof t!="number")return;const s=Math.max(0,t-this.options.clock.now());e==null||e.set("expiresIn",s),this.expireTimeout=this.options.clock.createTimeout(s+10),this.expireTimeout.elapsed().then(()=>{this.options.emitUpdate(this,"isExpired")},r=>{})}get logItem(){var e;return(e=this.connection)==null?void 0:e.logItem}get remoteMedia(){var e,t;return(t=(e=this.connection)==null?void 0:e.peerCall)==null?void 0:t.remoteMedia}get isExpired(){return!this.isConnected&&hn(this.callDeviceMembership,this.options.clock.now())}get remoteMuteSettings(){var e,t;return(t=(e=this.connection)==null?void 0:e.peerCall)==null?void 0:t.remoteMuteSettings}get isConnected(){var e,t;return((t=(e=this.connection)==null?void 0:e.peerCall)==null?void 0:t.state)===$.Connected}get userId(){return this.member.userId}get deviceId(){return this.callDeviceMembership.device_id}get user_id(){return this.userId}get device_id(){return this.deviceId}get sessionId(){return this.callDeviceMembership.session_id}get dataChannel(){var e,t;return(t=(e=this.connection)==null?void 0:e.peerCall)==null?void 0:t.dataChannel}connect(e,t,s,i){return this.errorBoundary.try(async()=>{if(this.connection)return;const r=new Om(e.clone(),t,s,i);this.connection=r;let o;return await r.logItem.wrap("connect",async c=>{o=c,await this.callIfNeeded(c)}),o})}callIfNeeded(e){return e.wrap("callIfNeeded",async t=>{let s;if(this.member.userId===this.options.ownUserId?s=this.deviceId>this.options.ownDeviceId:s=this.member.userId>this.options.ownUserId,s){const i=this.connection;i.peerCall=this._createPeerCall(Ir("c")),await i.peerCall.call(i.localMedia,i.localMuteSettings,t)}else t.set("wait_for_invite",!0)})}disconnect(e){return this.errorBoundary.try(async()=>{const{connection:t}=this;if(!t)return;let s;return await t.logItem.wrap("disconnect",async i=>{s=i,e&&t.peerCall&&await t.peerCall.hangup(ee.UserHangup,i)}),t.dispose(),this.connection=void 0,s})}updateCallInfo(e,t){this.errorBoundary.try(()=>{this.callDeviceMembership=e,this._renewExpireTimeout(t),this.connection&&this.connection.logItem.refDetached(t)})}updateRoomMember(e){this.member=e,this.options.emitUpdate(this)}handleDeviceMessage(e,t){this.errorBoundary.try(()=>{var s;t.wrap({l:"Member.handleDeviceMessage",type:e.type,seq:(s=e.content)==null?void 0:s.seq},i=>{const{connection:r}=this;if(r){const o=e.content.dest_session_id;if(o!==this.options.sessionId){const h=r.logItem.log({l:"ignoring to_device event with wrong session_id",destSessionId:o,type:e.type});i.refDetached(h);return}if(r.peerCall&&r.peerCall.getMessageAction(e)===ln.InviteGlare){const{shouldReplace:a,log:u}=r.peerCall.handleInviteGlare(e,this.deviceId,r.logItem);u&&u.refDetached(u),a&&(r.peerCall.dispose(),r.peerCall=void 0)}e.type===q.Invite&&!r.peerCall&&(r.peerCall=this._createPeerCall(e.content.call_id));const c=Nt(r.queuedSignallingMessages,e,(h,a)=>h.content.seq-a.content.seq);r.queuedSignallingMessages.splice(c,0,e);let l=!1;r.peerCall&&(l=this.dequeueSignallingMessages(r,r.peerCall,e,i)),l||i.refDetached(r.logItem.log({l:"queued message",type:e.type,seq:e.content.seq,idx:c}))}else t.log({l:"member not connected",userId:this.userId,deviceId:this.deviceId})})})}dequeueSignallingMessages(e,t,s,i){let r=!1;for(;e.canDequeueNextSignallingMessage;){const o=e.queuedSignallingMessages.shift(),c=o===s;r=r||c,i.wrap(c?"process message":"dequeue message",l=>{var u;const h=(u=o.content)==null?void 0:u.seq;if(l.set("seq",h),l.set("type",o.type),t.getMessageAction(o)===ln.Handle){const p=t.handleIncomingSignallingMessage(o,this.deviceId,e.logItem);l.refDetached(p),e.lastProcessedSeqNr=h}else l.set("ignored",!0),e.lastIgnoredSeqNr=h})}return r}async setMedia(e,t){return this.errorBoundary.try(async()=>{var i;const{connection:s}=this;s&&(s.localMedia=e.replaceClone(s.localMedia,t),await((i=s.peerCall)==null?void 0:i.setMedia(s.localMedia,s.logItem)))})}async setMuted(e){return this.errorBoundary.try(async()=>{var s;const{connection:t}=this;t&&(t.localMuteSettings=e,await((s=t.peerCall)==null?void 0:s.setMuted(e,t.logItem)))})}_createPeerCall(e){const t=this.connection;return new Nm(e,Object.assign({},this.options,{errorBoundary:this.errorBoundary,emitUpdate:this.emitUpdateFromPeerCall,sendSignallingMessage:this.sendSignallingMessage,turnServer:t.turnServer}),t.logItem)}dispose(){var e,t;(e=this.connection)==null||e.dispose(),this.connection=void 0,(t=this.expireTimeout)==null||t.dispose(),this.expireTimeout=void 0,this.options.emitUpdate=()=>{}}}function Rr(n){const e=n.expires_ts;if(Number.isSafeInteger(e))return e}function hn(n,e,t=0){const s=Rr(n);return typeof s=="number"?s+t<=e:!0}function Ws(n,e){return JSON.stringify(n)+","+JSON.stringify(e)}function ko(n,e){return n.startsWith(JSON.stringify(e)+",")}function Fm(n){return JSON.parse(`[${n}]`)[1]}class Lm{constructor(e,t,s,i,r,o){this.logItem=e,this.membersLogItem=t,this.localMedia=s,this.localPreviewMedia=i,this.localMuteSettings=r,this.turnServer=o}dispose(){var e;this.localMedia.dispose(),this.localPreviewMedia.dispose(),this.logItem.finish(),(e=this.renewMembershipTimeout)==null||e.dispose()}}class qr extends $t{constructor(e,t,s,i,r,o,c){super(),this.id=e,this.isLoadedFromStorage=t,this.startTime=i,this.callContent=r,this.roomId=o,this.options=c,this._members=new Dt,this.bufferedDeviceMessages=new Map,this.errorBoundary=new ac(l=>{this.emitChange(),this.joinedData&&(this.joinedData.logItem.log("error at boundary").catch(l),console.error(l))}),this._state=s?"fledgling":"created",this._memberOptions=Object.assign({},c,{confId:this.id,emitUpdate:l=>{var a;const h=Ws(l.userId,l.deviceId);if(l.isExpired&&!l.isConnected){const u=this.options.logger.log({l:"removing expired member from call",memberKey:h,callId:this.id});(a=l.logItem)==null||a.refDetached(u),l.dispose(),this._members.remove(h)}else this._members.update(h)},encryptDeviceMessage:(l,h,a,u)=>this.options.encryptDeviceMessage(this.roomId,l,h,a,u)})}get localMedia(){var e;return(e=this.joinedData)==null?void 0:e.localMedia}get localPreviewMedia(){var e;return(e=this.joinedData)==null?void 0:e.localPreviewMedia}get members(){return this._members}get isTerminated(){var e;return!!((e=this.callContent)!=null&&e["m.terminated"])}get usesFoci(){for(const e of this._members.values())if(e.usesFoci)return!0;return!1}get duration(){if(typeof this.startTime=="number")return this.options.clock.now()-this.startTime}get isRinging(){return this._state==="created"&&this.intent==="m.ring"&&!this.isMember(this.options.ownUserId)}get name(){var e;return(e=this.callContent)==null?void 0:e["m.name"]}get intent(){var e;return(e=this.callContent)==null?void 0:e["m.intent"]}get type(){var e;return(e=this.callContent)==null?void 0:e["m.type"]}get logItem(){var e;return(e=this.joinedData)==null?void 0:e.logItem}get error(){return this.errorBoundary.error}join(e,t){return this.options.logger.wrapOrRun(t,"Call.join",async s=>{if(this._state!=="created"||this.joinedData||this.usesFoci){e.dispose();return}const i=this.options.logger.child({l:"Call.connection",t:fs,id:this.id,ownSessionId:this.options.sessionId}),r=await this.options.turnServerSource.getSettings(i),o=i.child("member connections"),c=new si;c.updateTrackInfo(e.userMedia);const l=e.asPreview(),h=new Lm(i,o,e,l,c,r);this.joinedData=h,await h.logItem.wrap("join",async a=>{s.refDetached(a),this._state="joining",this.emitChange(),await a.wrap("update member state",async u=>{const p=await this._createMemberPayload(!0);u.set("payload",p),await this.options.hsApi.sendState(this.roomId,q.GroupCallMember,this.options.ownUserId,p,{log:u}).response(),this.emitChange()});for(const u of this._members.values())this.connectToMember(u,h,a)})})}async setMedia(e){var t;if((this._state==="joining"||this._state==="joined")&&this.joinedData){const s=this.joinedData.localMedia;this.joinedData.localMedia=e,(t=this.joinedData.localPreviewMedia)==null||t.dispose(),this.joinedData.localPreviewMedia=e.asPreview(),this.joinedData.localMuteSettings.updateTrackInfo(e.userMedia),this.emitChange(),await Promise.all(Array.from(this._members.values()).map(i=>i.setMedia(e,s))),s==null||s.dispose()}}async setMuted(e){const{joinedData:t}=this;if(!t)return;const s=t.localMuteSettings;e.updateTrackInfo(t.localMedia.userMedia),t.localMuteSettings=e,s.equals(e)||(this.localPreviewMedia&&cn(this.localPreviewMedia,e,this.joinedData.logItem),this.localMedia&&cn(this.localMedia,e,this.joinedData.logItem),await Promise.all(Array.from(this._members.values()).map(i=>i.setMuted(t.localMuteSettings))),this.emitChange())}get muteSettings(){var e;return(e=this.joinedData)==null?void 0:e.localMuteSettings}get hasJoined(){return this._state==="joining"||this._state==="joined"}async leave(e){await this.options.logger.wrapOrRun(e,"Call.leave",async t=>{var i;const{joinedData:s}=this;if(!!s)try{(i=s.renewMembershipTimeout)==null||i.dispose(),s.renewMembershipTimeout=void 0;const r=await this._createMemberPayload(!1);r?(await this.options.hsApi.sendState(this.roomId,q.GroupCallMember,this.options.ownUserId,r,{log:t}).response(),(this.intent===Ki.Ring||this.intent===Ki.Prompt)&&this._members.size===0&&await this.terminate(t)):t.set("already_left",!0)}finally{if(!this.disconnect(t))throw this.errorBoundary.error}})}terminate(e){return this.options.logger.wrapOrRun(e,{l:"terminate call",t:fs},async t=>{if(this._state==="fledgling")return;await this.options.hsApi.sendState(this.roomId,q.GroupCall,this.id,Object.assign({},this.callContent,{"m.terminated":!0}),{log:t}).response()})}create(e,t){return t.wrap({l:"create call",t:fs},async s=>{if(this._state!=="fledgling")return;this._state="creating",this.emitChange(),this.callContent=Object.assign({"m.type":e},this.callContent),await this.options.hsApi.sendState(this.roomId,q.GroupCall,this.id,this.callContent,{log:s}).response(),this._state="created",this.emitChange()})}updateCallEvent(e,t){this.errorBoundary.try(()=>{t.wrap({l:"update call",t:fs,id:this.id},s=>{typeof this.startTime!="number"&&(this.startTime=e.origin_server_ts),this.callContent=e.content,this._state==="creating"&&(this._state="created"),s.set("status",this._state),this.emitChange()})})}updateRoomMembers(e){this.errorBoundary.try(()=>{for(const t of e.values()){const{member:s}=t;for(const i of this._members.values())i.userId===s.userId&&i.updateRoomMember(s)}})}updateMembership(e,t,s,i){this.errorBoundary.try(async()=>{await i.wrap({l:"update call membership",t:fs,id:this.id,userId:e},async r=>{const o=this.options.clock.now(),c=s["m.devices"],l=this.getDeviceIdsForUserId(e);for(const a of c){const u=a.device_id,p=Ws(e,u);e===this.options.ownUserId&&u===this.options.ownDeviceId?r.wrap("update own membership",g=>{this.hasJoined&&(this.joinedData&&this.joinedData.logItem.refDetached(g),this._setupRenewMembershipTimeout(a,g)),this._state==="joining"&&(g.set("joined",!0),this._state="joined",this.emitChange())}):await r.wrap({l:"update device membership",id:p,sessionId:a.session_id},async g=>{if(hn(a,o)){g.set("expired",!0);const M=this._members.get(p);M?(M.dispose(),this._members.remove(p),g.set("removed",!0)):g.discard();return}let f=this._members.get(p);const v=f&&f.sessionId!==a.session_id;if(f&&!v)g.set("update",!0),f.updateCallInfo(a,g);else{if(f&&v){g.set("removedSessionId",f.sessionId);const M=await f.disconnect(!1);M&&g.refDetached(M),f.dispose(),this._members.remove(p),f=void 0}g.set("add",!0),f=new Pm(t,a,this._memberOptions,g),this._members.add(p,f),this.joinedData&&this.connectToMember(f,this.joinedData,g)}this.flushPendingIncomingDeviceMessages(f,g)})}const h=new Set(c.map(a=>a.device_id));for(const a of l)h.has(a)||this.removeMemberDevice(e,a,r);e===this.options.ownUserId&&!h.has(this.options.ownDeviceId)&&this.removeOwnDevice(r)})})}removeMembership(e,t){this.errorBoundary.try(()=>{const s=this.getDeviceIdsForUserId(e);t.wrap({l:"remove call member",t:fs,id:this.id,userId:e},i=>{for(const r of s)this.removeMemberDevice(e,r,i);e===this.options.ownUserId&&this.removeOwnDevice(i)})})}flushPendingIncomingDeviceMessages(e,t){const s=Ws(e.userId,e.deviceId),i=this.bufferedDeviceMessages.get(s);if(i){for(const r of i)r.content.sender_session_id===e.sessionId&&(e.handleDeviceMessage(r,t),i.delete(r));i.size===0&&this.bufferedDeviceMessages.delete(s)}}getDeviceIdsForUserId(e){return Array.from(this._members.keys()).filter(t=>ko(t,e)).map(t=>Fm(t))}isMember(e){return Array.from(this._members.keys()).some(t=>ko(t,e))}removeOwnDevice(e){e.wrap("remove own membership",t=>{this.disconnect(t)})}disconnect(e){return this.errorBoundary.try(async()=>{var t;if(this.hasJoined){for(const s of this._members.values()){const i=await s.disconnect(!0);i&&e.refDetached(i)}this._state="created"}(t=this.joinedData)==null||t.dispose(),this.joinedData=void 0,this.emitChange()},!1)||!0}async removeMemberDevice(e,t,s){const i=Ws(e,t);await s.wrap({l:"remove device member",id:i},async r=>{const o=this._members.get(i);if(o){r.set("leave",!0);const c=await o.disconnect(!1);c&&r.refDetached(c),o.dispose(),this._members.remove(i)}})}handleDeviceMessage(e,t,s,i){this.errorBoundary.try(()=>{const r=Ws(t,s);let o=this._members.get(r);if(o&&e.content.sender_session_id===o.sessionId)o.handleDeviceMessage(e,i);else{i.log({l:"call: buffering to_device message, member not found",t:fs,id:this.id,userId:t,deviceId:s,sessionId:e.content.sender_session_id,type:e.type});let c=this.bufferedDeviceMessages.get(r);c||(c=new Set,this.bufferedDeviceMessages.set(r,c)),c.add(e)}})}async _createMemberPayload(e){var h,a;const{storage:t}=this.options,i=await(await t.readTxn([t.storeNames.roomState])).roomState.get(this.roomId,q.GroupCallMember,this.options.ownUserId),r=(a=(h=i==null?void 0:i.event)==null?void 0:h.content)!=null?a:{["m.calls"]:[]};let o=r["m.calls"],c=o.find(u=>u["m.call_id"]===this.id);c||(c={["m.call_id"]:this.id,["m.devices"]:[]},o.push(c));const l=this.options.clock.now();return c["m.devices"]=c["m.devices"].filter(u=>!(u.device_id===this.options.ownDeviceId||Rr(u)===void 0||hn(u,l,jr))),e&&c["m.devices"].push({device_id:this.options.ownDeviceId,session_id:this.options.sessionId,expires_ts:l+jr,feeds:[{purpose:"m.usermedia"}]}),r["m.calls"]=o.filter(u=>u["m.devices"].length!==0),r}async connectToMember(e,t,s){const i=Ws(e.userId,e.deviceId),r=t.membersLogItem.child({l:"member",id:i,sessionId:e.sessionId});await s.wrap({l:"connect",id:i},async o=>{const c=await e.connect(t.localMedia,t.localMuteSettings,t.turnServer,r);c&&o.refDetached(c)})}emitChange(){this.emit("change"),this.options.emitUpdate(this)}_setupRenewMembershipTimeout(e,t){var l;const{joinedData:s}=this;if(!s)return;(l=s.renewMembershipTimeout)==null||l.dispose(),s.renewMembershipTimeout=void 0;const i=Rr(e);if(typeof i!="number")return;const r=i-this.options.clock.now(),o=Math.max(1e4,Math.ceil((.2+this.options.random()*.8)*(.08333*jr))),c=Math.max(0,r-o);t.set("expiresIn",r),t.set("renewIn",c),s.renewMembershipTimeout=this.options.clock.createTimeout(c),s.renewMembershipTimeout.elapsed().then(()=>{s.logItem.wrap("renew membership",async h=>{const a=await this._createMemberPayload(!0);h.set("payload",a),await this.options.hsApi.sendState(this.roomId,q.GroupCallMember,this.options.ownUserId,a,{log:h}).response()})},()=>{})}dispose(){var e;(e=this.joinedData)==null||e.dispose();for(const t of this._members.values())t.dispose()}}const Io=5*60,Km={urls:["stun:turn.matrix.org"],username:"",credential:""};class Bm{constructor(e,t,s=Km){this.hsApi=e,this.clock=t,this.defaultSettings=s,this.isPolling=!1}getSettings(e){return e.wrap("get turn server",async t=>{if(!this.isPolling){const s=await this.doRequest(t),i=s?Mo(s):this.defaultSettings;t.set("iceServer",i),this.currentObservable?this.currentObservable.set(i):this.currentObservable=new Ui(i,()=>{this.stopPollLoop()},()=>{var r;this.runLoop((r=s==null?void 0:s.ttl)!=null?r:Io)})}return this.currentObservable})}async runLoop(e){let t=e;for(this.isPolling=!0;this.isPolling;)try{this.pollTimeout=this.clock.createTimeout(t*1e3),await this.pollTimeout.elapsed(),this.pollTimeout=void 0;const s=await this.doRequest(void 0);if(s){const i=Mo(s);$m(this.currentObservable,i)&&this.currentObservable.set(i),s.ttl>0?t=s.ttl:this.stopPollLoop()}else t=Io}catch(s){s.name}}async doRequest(e){try{return this.pollRequest=this.hsApi.getTurnServer({log:e}),await this.pollRequest.response()}catch(t){if(t.name==="HomeServerError")return;throw t}finally{this.pollRequest=void 0}}stopPollLoop(){var e,t;this.isPolling=!1,this.currentObservable=void 0,(e=this.pollTimeout)==null||e.dispose(),this.pollTimeout=void 0,(t=this.pollRequest)==null||t.abort(),this.pollRequest=void 0}dispose(){this.stopPollLoop()}}function $m(n,e){const t=n.get();if(!t)return!0;const s=Array.isArray(t.urls)?t.urls:[t.urls],i=Array.isArray(e.urls)?e.urls:[e.urls];return!(s.length===i.length&&!i.some(o=>!s.includes(o)))||e.username!==t.username||e.credential!==t.credential}function Mo(n){return{urls:n.uris,username:n.username,credential:n.password,credentialType:"password"}}function jm(n,e){return JSON.stringify(n)+","+JSON.stringify(e)}class qm{constructor(e){this.options=e,this._calls=new Dt,this.roomMemberToCallIds=new Map,this.sessionId=Ir("s"),this.groupCallOptions=Object.assign({},this.options,{turnServerSource:new Bm(this.options.hsApi,this.options.clock),emitUpdate:(t,s)=>this._calls.update(t.id,s),createTimeout:this.options.clock.createTimeout,sessionId:this.sessionId})}loadCalls(e,t){return this.options.logger.wrapOrRun(t,"CallHandler.loadCalls",async s=>{e||(e=Ki.Ring),s.set("intent",e);const i=await this._getLoadTxn(),r=await i.calls.getByIntent(e);await this._loadCallEntries(r,i,s)})}loadCallsForRoom(e,t,s){return this.options.logger.wrapOrRun(s,"CallHandler.loadCallsForRoom",async i=>{i.set("intent",e),i.set("roomId",t);const r=await this._getLoadTxn(),o=await r.calls.getByIntentAndRoom(e,t);await this._loadCallEntries(o,r,i)})}async _getLoadTxn(){const e=this.options.storage.storeNames;return await this.options.storage.readTxn([e.calls,e.roomState])}async _loadCallEntries(e,t,s){s.set("entries",e.length),await Promise.all(e.map(async r=>{if(this._calls.get(r.callId))return;const o=await t.roomState.get(r.roomId,q.GroupCall,r.callId);if(o){const c=new qr(o.event.state_key,!0,!1,r.timestamp,o.event.content,o.roomId,this.groupCallOptions);this._calls.set(c.id,c)}}));const i=Array.from(new Set(e.map(r=>r.roomId)));await Promise.all(i.map(async r=>{const o=await t.roomState.getAllForType(r,q.GroupCallMember);await Promise.all(o.map(async c=>{const l=c.event.sender,h=await t.roomState.get(r,Ke,l);let a;h&&(a=Q.fromMemberEvent(h.event)),a||(a=Q.fromUserId(r,l,"join")),this.handleCallMemberEvent(c.event,a,r,s)}))})),s.set("newSize",this._calls.size)}createCall(e,t,s,i,r){return this.options.logger.wrapOrRun(r,"CallHandler.createCall",async o=>{i||(i=Ki.Ring);const c=new qr(Ir("conf-"),!1,!0,void 0,{"m.name":s,"m.intent":i},e,this.groupCallOptions);this._calls.set(c.id,c);try{await c.create(t,o);const l=await this.options.storage.readWriteTxn([this.options.storage.storeNames.calls]);l.calls.add({intent:c.intent,callId:c.id,timestamp:this.options.clock.now(),roomId:e}),await l.complete()}catch(l){throw this._calls.remove(c.id),l}return c})}get calls(){return this._calls}async handleRoomState(e,t,s,i,r){if(t.type===q.GroupCall&&this.handleCallEvent(t,e.id,i,r),t.type===q.GroupCallMember){let o=await s.lookupMemberAtEvent(t.sender,t,i);o||(o=Q.fromUserId(e.id,t.sender,"join")),this.handleCallMemberEvent(t,o,e.id,r)}}updateRoomMembers(e,t){for(const s of this._calls.values())s.roomId===e.id&&s.updateRoomMembers(t)}handlesDeviceMessageEventType(e){return Dm(e)}handleDeviceMessage(e,t,s,i){const r=this._calls.get(e.content.conf_id);r==null||r.handleDeviceMessage(e,t,s,i)}handleCallEvent(e,t,s,i){const r=e.state_key;let o=this._calls.get(r);o?(o.updateCallEvent(e,i),o.isTerminated&&(o.disconnect(i),this._calls.remove(o.id),s.calls.remove(o.intent,t,o.id))):e.content["m.terminated"]||(o=new qr(e.state_key,!1,!1,e.origin_server_ts,e.content,t,this.groupCallOptions),this._calls.set(o.id,o),s.calls.add({intent:o.intent,callId:o.id,timestamp:e.origin_server_ts,roomId:t}))}handleCallMemberEvent(e,t,s,i){var a;const r=e.state_key,o=jm(s,r),c=(a=e.content["m.calls"])!=null?a:[];for(const u of c){const p=u["m.call_id"],g=this._calls.get(p);g==null||g.updateMembership(r,t,u,i)}const l=new Set(c.map(u=>u["m.call_id"]));let h=this.roomMemberToCallIds.get(o);if(h){for(const u of h)if(!l.has(u)){const p=this._calls.get(u);p==null||p.removeMembership(r,i)}}l.size===0?this.roomMemberToCallIds.delete(o):this.roomMemberToCallIds.set(o,l)}dispose(){this.groupCallOptions.turnServerSource.dispose();for(const e of this._calls.values())e.dispose()}}class Hm extends xr{async handleRoomState(e,t,s,i,r){const o=[];for(let c of this._handlers)o.push(c.handleRoomState(e,t,s,i,r));await Promise.all(o)}updateRoomMembers(e,t){for(let s of this._handlers)s.updateRoomMembers(e,t)}}var dn=(n=>(n[n.Calls=1]="Calls",n[n.CrossSigning=2]="CrossSigning",n))(dn||{});class Xs{constructor(e=0){this.flags=e}withFeature(e){return new Xs(this.flags|e)}withoutFeature(e){return new Xs(this.flags^e)}isFeatureEnabled(e){return(this.flags&e)!==0}get calls(){return this.isFeatureEnabled(1)}get crossSigning(){return this.isFeatureEnabled(2)}static async load(e){const t=await e.getInt("enabled_features")||0;return new Xs(t)}async store(e){await e.setInt("enabled_features",this.flags)}}const ys="DEFAULT_KEY",ki="pusher";class Wm{constructor({storage:e,hsApi:t,sessionInfo:s,olm:i,olmWorker:r,platform:o,mediaRepository:c,features:l}){this._platform=o,this._storage=e,this._hsApi=t,this._mediaRepository=c,this._features=l,this._syncInfo=null,this._sessionInfo=s,this._rooms=new Dt,this._roomUpdateCallback=(h,a)=>this._rooms.update(h.id,a),this._activeArchivedRooms=new Map,this._invites=new Dt,this._inviteUpdateCallback=(h,a)=>this._invites.update(h.id,a),this._roomsBeingCreatedUpdateCallback=(h,a)=>{h.isCancelled?this._roomsBeingCreated.remove(h.id):this._roomsBeingCreated.update(h.id,a)},this._roomsBeingCreated=new Dt,this._user=new nu(s.userId),this._roomStateHandler=new Hm,l.calls&&this._setupCallHandler(),this._deviceMessageHandler=new Du({storage:e,callHandler:this._callHandler}),this._olm=i,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=r,this._keyBackup=new Vt(void 0),this._crossSigning=new Vt(void 0),this._observedRoomStatus=new Map,i&&(this._olmUtil=new i.Utility,this._deviceTracker=new Id({storage:e,getSyncToken:this._getSyncToken,olmUtil:this._olmUtil,ownUserId:s.userId,ownDeviceId:s.deviceId})),this._createRoomEncryption=this._createRoomEncryption.bind(this),this._forgetArchivedRoom=this._forgetArchivedRoom.bind(this),this.needsKeyBackup=new Vt(!1),this._secretFetcher=new Bu,this._secretSharing=null,this._secretStorage=null}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}get callHandler(){return this._callHandler}get features(){return this._features}_setupCallHandler(){this._callHandler=new qm({clock:this._platform.clock,random:this._platform.random,hsApi:this._hsApi,encryptDeviceMessage:async(e,t,s,i,r)=>{if(!this._deviceTracker||!this._olmEncryption){r.set("encryption_disabled",!0);return}const o=await r.wrap("get device key",async c=>{const l=this._deviceTracker.deviceForId(t,s,this._hsApi,c);return l||c.set("not_found",!0),l});if(o)return await this._olmEncryption.encrypt(i.type,i.content,[o],this._hsApi,r)},storage:this._storage,webRTC:this._platform.webRTC,ownDeviceId:this._sessionInfo.deviceId,ownUserId:this._sessionInfo.userId,logger:this._platform.logger,forceTURN:!1}),this.observeRoomState(this._callHandler)}async _setupEncryption(){const e=new xm,t=new tm(this._e2eeAccount,ys,this._platform.clock.now,this._user.id,this._olm,e);this._olmEncryption=new nm(this._e2eeAccount,ys,this._olm,this._storage,this._platform.clock.now,this._user.id,this._olmUtil,e),this._keyLoader=new wm(this._olm,ys,20),this._megolmEncryption=new Mm({account:this._e2eeAccount,pickleKey:ys,olm:this._olm,storage:this._storage,keyLoader:this._keyLoader,now:this._platform.clock.now,ownDeviceId:this._sessionInfo.deviceId}),this._megolmDecryption=new ym(this._keyLoader,this._olmWorker),this._deviceMessageHandler.enableEncryption({olmDecryption:t,megolmDecryption:this._megolmDecryption}),this._secretSharing=new $u({hsApi:this._hsApi,storage:this._storage,deviceMessageHandler:this._deviceMessageHandler,deviceTracker:this._deviceTracker,ourUserId:this.userId,olmEncryption:this._olmEncryption,crypto:this._platform.crypto,encoding:this._platform.encoding,crossSigning:this._crossSigning,logger:this._platform.logger}),await this._secretSharing.load(),this._secretFetcher.setSecretSharing(this._secretSharing)}_createRoomEncryption(e,t){var s;if(!this._olmEncryption)throw new Error("creating room encryption before encryption got globally enabled");return t.algorithm!==ft?null:new Rm({room:e,deviceTracker:this._deviceTracker,olmEncryption:this._olmEncryption,megolmEncryption:this._megolmEncryption,megolmDecryption:this._megolmDecryption,storage:this._storage,keyBackup:(s=this._keyBackup)==null?void 0:s.get(),encryptionParams:t,notifyMissingMegolmSession:()=>{this._keyBackup.get()||this.needsKeyBackup.set(!0)},clock:this._platform.clock})}enableSecretStorage(e,t,s=void 0){return this._platform.logger.wrapOrRun(s,"enable secret storage",async i=>{var o,c;if(!this._olm)throw new Error("olm required");this._keyBackup.get()&&(this._keyBackup.get().dispose(),this._keyBackup.set(void 0));const r=await Yu(e,t,this._storage,this._platform,this._olm);if(await this._tryLoadSecretStorage(r,i))return await this._writeSSSSKey(r,i),await((o=this._keyBackup.get())==null?void 0:o.start(i)),await((c=this._crossSigning.get())==null?void 0:c.start(i)),r;throw new Error("Could not read key backup with the given key")})}async _writeSSSSKey(e,t){const s=this._keyBackup.get();if(!s)return;const i=s.version,r=await this._storage.readWriteTxn([this._storage.storeNames.session,this._storage.storeNames.inboundGroupSessions]);try{const o=await Wu(e,i,r);if(t.set("previousBackupVersion",o),t.set("backupVersion",i),!!o&&o!==i){const c=await s.markAllForBackup(r);t.set("amountMarkedForBackup",c)}}catch(o){throw r.abort(),o}await r.complete()}async disableSecretStorage(){const e=await this._storage.readWriteTxn([this._storage.storeNames.session]);try{Gu(e)}catch(s){throw e.abort(),s}if(await e.complete(),this._keyBackup.get()){for(const s of this._rooms.values())s.isEncrypted&&s.enableKeyBackup(void 0);this._keyBackup.get().dispose(),this._keyBackup.set(void 0)}const t=this._crossSigning.get();t&&(t.dispose(),this._crossSigning.set(void 0))}_tryLoadSecretStorage(e,t){return t.wrap("enable secret storage",async s=>{const i=new Hu({key:e,platform:this._platform,storage:this._storage}),r=await i.hasValidKeyForAnyAccountData();return s.set("isValid",r),r&&(this._secretStorage=i,await this._loadSecretStorageServices(i,s),this._secretFetcher.setSecretStorage(i)),r})}async _loadSecretStorageServices(e,t){try{await t.wrap("enable key backup",async s=>{const i=new Im(this._hsApi,this._olm,this._keyLoader,this._storage,this._platform);if(await i.load(e,s)){for(const r of this._rooms.values())r.isEncrypted&&r.enableKeyBackup(i);return this._keyBackup.set(i),!0}else s.set("no_backup",!0)})}catch(s){t.catch(s)}}get keyBackup(){return this._keyBackup}get crossSigning(){return this._crossSigning}get secretSharing(){return this._secretSharing}get secretFetcher(){return this._secretFetcher}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),await this._setupEncryption()),this._sessionInfo.isReadOnly||(await this._e2eeAccount.generateOTKsIfNeeded(this._storage,e),await e.wrap("uploadKeys",t=>this._e2eeAccount.uploadKeys(this._storage,!1,t))),await this._createCrossSigning())}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 Is.adoptDehydratedDevice({dehydratedDevice:e,hsApi:this._hsApi,olm:this._olm,pickleKey:ys,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 Is.create({hsApi:this._hsApi,olm:this._olm,pickleKey:ys,userId:this._sessionInfo.userId,olmWorker:this._olmWorker,deviceId:e,storage:t})}setupDehydratedDevice(e,t=null){return this._platform.logger.wrapOrRun(t,"setupDehydratedDevice",async s=>{const i=await this._createNewAccount("temp-device-id");try{const r=await Xu(i,this._hsApi,e,"Dehydrated device",s);return s.set("deviceId",r),r}finally{i.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._storage.storeNames.accountData,this._storage.storeNames.crossSigningKeys]);this._syncInfo=await t.session.get("sync"),this._olm&&(this._e2eeAccount=await Is.load({hsApi:this._hsApi,olm:this._olm,pickleKey:ys,userId:this._sessionInfo.userId,deviceId:this._sessionInfo.deviceId,olmWorker:this._olmWorker,txn:t}),this._e2eeAccount&&e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption());const s=await this._getPendingEventsByRoom(t),i=await t.invites.getAll(),r=Promise.all(i.map(async l=>{const h=this.createInvite(l.roomId);e.wrap("invite",a=>h.load(l,a)),this._invites.add(h.id,h)})),o=await t.roomSummary.getAll(),c=Promise.all(o.map(async l=>{const h=this.createJoinedRoom(l.roomId,s.get(l.roomId));await e.wrap("room",a=>h.load(l,t,a)),this._rooms.add(h.id,h)}));await Promise.all([r,c]);for(const[l,h]of this.invites){const a=this.rooms.get(l);a&&a.setInvite(h)}if(this._olm&&this._e2eeAccount){const l=await zu(t);l&&await this._tryLoadSecretStorage(l,e)}this._e2eeAccount&&await this._createCrossSigning()}async _createCrossSigning(){this._features.crossSigning&&this._platform.logger.run("enable cross-signing",async e=>{const t=new wd({storage:this._storage,secretFetcher:this._secretFetcher,platform:this._platform,olm:this._olm,olmUtil:this._olmUtil,deviceTracker:this._deviceTracker,deviceMessageHandler:this._deviceMessageHandler,hsApi:this._hsApi,ownUserId:this.userId,e2eeAccount:this._e2eeAccount,deviceId:this.deviceId});await t.load(e),this._crossSigning.set(t)})}dispose(){var e,t,s,i,r,o;(e=this._olmWorker)==null||e.dispose(),this._olmWorker=void 0,(t=this._keyBackup.get())==null||t.dispose(),this._keyBackup.set(void 0),(s=this._megolmDecryption)==null||s.dispose(),this._megolmDecryption=void 0,(i=this._e2eeAccount)==null||i.dispose(),this._e2eeAccount=void 0,(r=this._callHandler)==null||r.dispose(),this._callHandler=void 0,(o=this._crossSigning.get())==null||o.dispose();for(const c of this._rooms.values())c.dispose();this._rooms=void 0}async start(e,t,s){var c,l;if(e){const h=await this._storage.readWriteTxn([this._storage.storeNames.session]);h.session.set("serverVersions",e),await h.complete()}t&&await s.wrap("SSSSKeyFromDehydratedDeviceKey",async h=>{const a=await Ju(t.key,this._storage,this._platform);a&&await this._tryLoadSecretStorage(a,h)&&(h.set("success",!0),await this._writeSSSSKey(a))}),await((c=this._keyBackup.get())==null?void 0:c.start(s)),await((l=this._crossSigning.get())==null?void 0:l.start(s));const r=await(await this._storage.readWriteTxn([this._storage.storeNames.operations])).operations.getAll(),o=ti(r,h=>h.scope);for(const h of this._rooms.values()){let a;const u=o.get(h.id);u&&(a=ti(u,p=>p.type)),h.start(a,s)}}async _getPendingEventsByRoom(e){return(await e.pendingEvents.getAll()).reduce((s,i)=>{const r=s.get(i.roomId);return r?r.push(i):s.set(i.roomId,[i]),s},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 Iu({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,roomStateHandler:this._roomStateHandler})}_createArchivedRoom(e){const t=new Mu({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 Nu({roomId:e,hsApi:this._hsApi,emitCollectionUpdate:this._inviteUpdateCallback,mediaRepository:this._mediaRepository,user:this._user,platform:this._platform})}get roomsBeingCreated(){return this._roomsBeingCreated}async createRoom(e){let t;return await this._platform.logger.run("create room",async s=>{const i=`local-${Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER)}`;t=new Vu(i,e,this._roomsBeingCreatedUpdateCallback,this._mediaRepository,this._platform,s),this._roomsBeingCreated.set(i,t);const r=[t.create(this._hsApi,s)];e.loadProfiles!==!1&&r.push(t.loadProfiles(this._hsApi,s)),await Promise.all(r),t.roomId&&(this.rooms.get(t.roomId)&&this._tryReplaceRoomBeingCreated(t.roomId,s),await t.adjustDirectMessageMapIfNeeded(this._user,this._storage,this._hsApi,s))}),t}async obtainSyncLock(e){var s;const t=(s=e.to_device)==null?void 0:s.events;if(Array.isArray(t)&&t.length)return await this._deviceMessageHandler.obtainSyncLock(t)}async prepareSync(e,t,s,i){var o;const r=(o=e.to_device)==null?void 0:o.events;if(Array.isArray(r)&&r.length)return await i.wrap("deviceMsgs",c=>this._deviceMessageHandler.prepareSync(r,t,s,c))}async writeSync(e,t,s,i,r){const o={syncInfo:null,e2eeAccountChanges:null,hasNewRoomKeys:!1,deviceMessageDecryptionResults:null,changedDevices:null},c=e.next_batch;if(c!==this.syncToken){const u={token:c,filterId:t};i.session.set("sync",u),o.syncInfo=u}const l=e.device_one_time_keys_count;this._e2eeAccount&&l&&(o.e2eeAccountChanges=this._e2eeAccount.writeSync(l,i,r));const h=e.device_lists;if(this._deviceTracker&&Array.isArray(h==null?void 0:h.changed)&&h.changed.length&&(await r.wrap("deviceLists",u=>this._deviceTracker.writeDeviceChanges(h.changed,i,u)),o.changedDevices=h.changed),s){const{hasNewRoomKeys:u,decryptionResults:p}=await r.wrap("deviceMsgs",g=>this._deviceMessageHandler.writeSync(s,i,g));o.hasNewRoomKeys=u,o.deviceMessageDecryptionResults=p}const a=e.account_data;if(Array.isArray(a==null?void 0:a.events))for(const u of a.events)typeof u.type=="string"&&i.accountData.set(u);return o}afterSync({syncInfo:e,e2eeAccountChanges:t}){e&&(this._syncInfo=e),this._e2eeAccount&&this._e2eeAccount.afterSync(t)}async afterSyncCompleted(e,t,s){var i,r,o;this._e2eeAccount&&!t&&!this._sessionInfo.isReadOnly&&await this._e2eeAccount.generateOTKsIfNeeded(this._storage,s)&&await s.wrap("uploadKeys",l=>this._e2eeAccount.uploadKeys(this._storage,!1,l)),e.hasNewRoomKeys&&((i=this._keyBackup.get())==null||i.flush(s)),e.deviceMessageDecryptionResults&&await this._deviceMessageHandler.afterSyncCompleted(e.deviceMessageDecryptionResults,this._deviceTracker,this._hsApi,s),(r=e.changedDevices)!=null&&r.includes(this.userId)&&((o=this._secretSharing)==null||o.checkSecretValidity())}_tryReplaceRoomBeingCreated(e,t){for(const[,s]of this._roomsBeingCreated)if(s.roomId===e){const i=this._observedRoomStatus.get(s.id);i&&(t.log("replacing room being created").set("localId",s.id).set("roomId",s.roomId),i.set(i.get()|se.Replaced)),s.dispose(),this._roomsBeingCreated.remove(s.id);return}}async applyRoomCollectionChangesAfterSync(e,t,s,i){var r,o;for(const c of t)c.shouldAdd?(this._rooms.add(c.id,c.room),this._tryReplaceRoomBeingCreated(c.id,i)):c.shouldRemove&&this._rooms.remove(c.id);for(const c of e)c.shouldAdd?this._invites.add(c.id,c.invite):c.shouldRemove&&this._invites.remove(c.id);if(this._observedRoomStatus.size!==0){for(const c of s)c.shouldAdd&&((r=this._observedRoomStatus.get(c.id))==null||r.set(se.Archived));for(const c of t)c.shouldAdd&&((o=this._observedRoomStatus.get(c.id))==null||o.set(se.Joined));for(const c of e){const l=this._observedRoomStatus.get(c.id);if(l){const h=l.get()|se.Invited;if(c.shouldAdd)l.set(h);else if(c.shouldRemove){const a=h^se.Invited;l.set(a)}}}}}_forgetArchivedRoom(e){const t=this._observedRoomStatus.get(e);t&&t.set((t.get()|se.Archived)^se.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=bs.createDefaultPayload(this._sessionInfo.id),s=await this._platform.notificationService.enablePush(bs,t);if(!s)return e.set("no_pusher",!0),!1;await s.enable(this._hsApi,e);const i=await this._storage.readWriteTxn([this._storage.storeNames.session]);return i.session.set(ki,s.serialize()),await i.complete(),!0})}async _disablePush(){return this._platform.logger.run("disablePush",async e=>{await this._platform.notificationService.disablePush();const s=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(ki);if(!s)return!0;await new bs(s).disable(this._hsApi,e);const r=await this._storage.readWriteTxn([this._storage.storeNames.session]);return r.session.remove(ki),await r.complete(),!0})}async arePushNotificationsEnabled(){return await this._platform.notificationService.isPushEnabled()?!!await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(ki):!1}async checkPusherEnabledOnHomeserver(){const t=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(ki);if(!t)return!1;const s=new bs(t),i=await this._hsApi.getPushers().response();return((i==null?void 0:i.pushers)||[]).map(o=>new bs(o)).some(o=>o.equals(s))}async getRoomStatus(e){if(!!this._roomsBeingCreated.get(e))return se.BeingCreated;if(!!this._rooms.get(e))return se.Joined;{const i=!!this._invites.get(e),o=await(await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary])).archivedRoomSummary.has(e);return i&&o?se.Invited|se.Archived:i?se.Invited:o?se.Archived:se.None}}async observeRoomStatus(e){let t=this._observedRoomStatus.get(e);if(!t){let s;t=new Ui(s,()=>{this._observedRoomStatus.delete(e)}),this._observedRoomStatus.set(e,t),s=await this.getRoomStatus(e),t.get()===void 0&&t.set(s)}return t}observeRoomState(e){return this._roomStateHandler.subscribe(e)}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 s=>{s.set("id",e);const i=this._activeArchivedRooms.get(e);if(i)return i.retain(),i;const r=await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary,this._storage.storeNames.roomMembers]),o=await r.archivedRoomSummary.get(e);if(o){const c=this._createArchivedRoom(e);return await c.load(o,r,s),c}})}joinRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"joinRoom",async s=>(await this._hsApi.joinIdOrAlias(e,{log:s}).response()).room_id)}updateAccessToken(e){this._hsApi.updateAccessToken(e)}}class zm{constructor({username:e,password:t,homeserver:s}){this._username=e,this._password=t,this.homeserver=s}async login(e,t,s){return await e.passwordLogin(this._username,this._password,t,{log:s}).response()}}class Gm{constructor({homeserver:e,loginToken:t}){this.homeserver=e,this._loginToken=t}async login(e,t,s){return await e.tokenLogin(this._loginToken,Pe(),t,{log:s}).response()}}class Ym{constructor(e){this._homeserver=e}get homeserver(){return this._homeserver}createSSORedirectURL(e){return`${this._homeserver}/_matrix/client/r0/login/sso/redirect?redirectUrl=${encodeURIComponent(e)}`}}class Un{constructor(e,t){this._session=e,this._params=t}setNextStage(e){this._nextStage=e}get nextStage(){return this._nextStage}}class Jm extends Un{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.dummy"}}class Qm 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 Xm extends Un{constructor(e,t,s){super(e,t),this._type=s}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 Zm{constructor(e,t,s,i){this.homeserver=e,this._hsApi=t,this._accountDetails=s,this._flowSelector=i!=null?i:r=>r[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:s,password:i,initialDeviceDisplayName:r,inhibitLogin:o}=this._accountDetails,c=this._hsApi.register(s,i,r,t,o),l=await c.response(),h=await c.responseCode(),a=Fr(It({},l),{status:h});return this.parseRegistrationResponse(a,e)}parseStagesFromResponse(e){const{session:t,params:s}=e,i=this._flowSelector(e.flows);if(!i)throw new Error("flowSelector did not return any flow!");let r,o;for(const c of i.stages){const l=this._createRegistrationStage(c,t,s);r?(o.setNextStage(l),o=l):(r=l,o=l)}return r}async parseRegistrationResponse(e,t){var s;switch(e.status){case 200:this._registerResponse=e;return;case 401:if((s=e.completed)!=null&&s.includes(t.type))return t.nextStage;throw new Error("This stage could not be completed!")}}_createRegistrationStage(e,t,s){switch(e){case"m.login.dummy":return new Jm(t,s==null?void 0:s[e]);case"m.login.terms":return new Qm(t,s==null?void 0:s[e]);case"org.matrix.msc3231.login.registration_token":case"m.login.registration_token":return new Xm(t,s==null?void 0:s[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 W=oi("NotLoading","Login","LoginFailed","QueryAccount","AccountSetup","Loading","SessionSetup","Migrating","FirstSync","Error","Ready"),Pt=oi("Connection","Credentials","Unknown");class Nr{constructor(e,t=new Xs(0)){this._platform=e,this._sessionStartedByReconnector=!1,this._status=new Vt(W.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,this._features=t}createNewSessionId(){return Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER).toString()}get sessionId(){return this._sessionId}async startWithExistingSession(e){this._status.get()===W.NotLoading&&(this._status.set(W.Loading),await this._platform.logger.run("load session",async t=>{t.set("id",e);try{const s=await this._platform.sessionInfoStorage.get(e);if(!s)throw new Error("Invalid session id: "+e);await this._loadSessionInfo(s,null,t),t.set("status",this._status.get())}catch(s){t.catch(s),this._error=s,this._status.set(W.Error)}}))}_parseLoginOptions(e,t){const s=e.flows,i={homeserver:t};for(const r of s)r.type==="m.login.password"?i.password=(o,c)=>new zm({homeserver:t,username:o,password:c}):r.type==="m.login.sso"&&s.find(o=>o.type==="m.login.token")?i.sso=new Ym(t):r.type==="m.login.token"&&(i.token=o=>new Gm({homeserver:t,loginToken:o}));return i}queryLogin(e){return new oa(async t=>{e=await Xc(e,(r,o)=>t(this._platform.request(r,o)));const s=new ws({homeserver:e,request:this._platform.request}),i=await t(s.getLoginFlows()).response();return this._parseLoginOptions(i,e)})}async startRegistration(e,t,s,i,r){const o=this._platform.request,c=new ws({homeserver:e,request:o});return new Zm(e,c,{username:t,password:s,initialDeviceDisplayName:i},r)}async startWithAuthData({accessToken:e,deviceId:t,userId:s,homeserver:i,isReadOnly:r=!1}){await this._platform.logger.run("startWithAuthData",async o=>{r&&o.set("isReadonly (Disabled OTK Upload)",!0),await this._createSessionAfterAuth({accessToken:e,deviceId:t,userId:s,homeserver:i},!0,r,o)})}async startWithLogin(e,{inspectAccountSetup:t}={}){const s=this._status.get();s!==W.LoginFailed&&s!==W.NotLoading&&s!==W.Error||(this._resetStatus(),await this._platform.logger.run("login",async i=>{this._status.set(W.Login);let r;try{const o=this._platform.request,c=new ws({homeserver:e.homeserver,request:o}),l=await e.login(c,"Hydrogen",i);r={deviceId:l.device_id,userId:l.user_id,homeserver:e.homeserver,accessToken:l.access_token}}catch(o){this._error=o,o.name==="HomeServerError"?(o.errcode==="M_FORBIDDEN"?this._loginFailure=Pt.Credentials:this._loginFailure=Pt.Unknown,i.set("loginFailure",this._loginFailure),this._status.set(W.LoginFailed)):o.name==="ConnectionError"?(this._loginFailure=Pt.Connection,this._status.set(W.LoginFailed)):this._status.set(W.Error);return}await this._createSessionAfterAuth(r,t,!1,i)}))}async _createSessionAfterAuth({deviceId:e,userId:t,accessToken:s,homeserver:i},r,o,c){const l=this.createNewSessionId(),h=this._platform.clock.now(),a={id:l,deviceId:e,userId:t,homeServer:i,homeserver:i,accessToken:s,lastUsed:h,isReadOnly:o};let u;r&&(u=await this._inspectAccountAfterLogin(a,c),u&&(a.deviceId=u.deviceId)),await this._platform.sessionInfoStorage.add(a);try{await this._loadSessionInfo(a,u,c),c.set("status",this._status.get())}catch(p){c.catch(p),u==null||u.dispose(),this._error=p,this._status.set(W.Error)}}async _loadSessionInfo(e,t,s){s.set("appVersion",this._platform.version);const i=this._platform.clock;this._sessionStartedByReconnector=!1,this._status.set(W.Loading),this._reconnector=new Al({onlineStatus:this._platform.onlineStatus,retryDelay:new ua(i.createTimeout),createMeasure:i.createMeasure});const r=new ws({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,s);const o={id:e.id,deviceId:e.deviceId,userId:e.userId,homeserver:e.homeServer,isReadOnly:e.isReadOnly},c=await this._olmPromise;let l=null;this._workerPromise&&(l=await this._workerPromise),this._requestScheduler=new Ul({hsApi:r,clock:i}),this._requestScheduler.start();const h=await r.versions({timeout:1e4,log:s}).response(),a=new Nl({homeserver:e.homeServer,platform:this._platform,serverVersions:h.versions});if(this._platform.updateService.updateAuthData({accessToken:e.accessToken,homeserver:e.homeServer}),this._session=new Wm({storage:this._storage,sessionInfo:o,hsApi:this._requestScheduler.hsApi,olm:c,olmWorker:l,mediaRepository:a,platform:this._platform,features:this._features}),await this._session.load(s),t?(await s.wrap("dehydrateIdentity",u=>this._session.dehydrateIdentity(t,u)),await this._session.setupDehydratedDevice(t.key,s)):this._session.hasIdentity||(this._status.set(W.SessionSetup),await s.wrap("createIdentity",u=>this._session.createIdentity(u))),this._sync=new Fl({hsApi:this._requestScheduler.hsApi,storage:this._storage,session:this._session,logger:this._platform.logger}),this._reconnectSubscription=this._reconnector.connectionStatus.subscribe(u=>{u===Ys.Online&&this._platform.logger.runDetached("reconnect",async p=>{this._requestScheduler.start(),this._sync.start(),this._sessionStartedByReconnector=!0;const g=t;t=void 0,await p.wrap("session start",f=>this._session.start(this._reconnector.lastVersionsResponse,g,f))})}),await s.wrap("wait first sync",()=>this._waitForFirstSync()),!this._isDisposed&&(this._status.set(W.Ready),!this._sessionStartedByReconnector)){if(this._isDisposed)return;const u=t;t=void 0,await s.wrap("session start",p=>this._session.start(h,u,p))}}async updateAccessToken(e){if(!this._session)throw Error("No session loaded, cannot update access token");this._session.updateAccessToken(e),this._platform.updateService.updateAuthData({accessToken:e}),await this._platform.sessionInfoStorage.updateAccessToken(this._sessionId,e)}async _waitForFirstSync(){this._sync.start(),this._status.set(W.FirstSync),this._waitForFirstSyncHandle=this._sync.status.waitFor(e=>{var t;return e===te.Stopped?((t=this._sync.error)==null?void 0:t.name)!=="ConnectionError":e===te.Syncing});try{if(await this._waitForFirstSyncHandle.promise,this._sync.status.get()===te.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 s=>{var c;this._status.set(W.QueryAccount);const i=new ws({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request}),r=await this._olmPromise;let o;try{o=await Qu(i,r,this._platform,s)}catch(l){if(l.name==="HomeServerError")s.set("not_supported",!0);else throw l}if(o){let l;const h=new Promise(u=>l=u);this._accountSetup=new e_(o,l),this._status.set(W.AccountSetup),await h;const a=(c=this._accountSetup)==null?void 0:c._dehydratedDevice;return this._accountSetup=null,a}})}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 s=await this._platform.sessionInfoStorage.get(this._sessionId);if(!s)throw new Error(`Could not find session for id ${this._sessionId}`);try{await new ws({homeserver:s.homeServer,accessToken:s.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(W.NotLoading),this._error=null,this._loginFailure=null}}class e_{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 L extends $t{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 i=this.navigation.observe(e).subscribe(r=>{t(r,e)});this.track(i)}track(e){return this.disposables||(this.disposables=new li),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 s="";for(let i=0;it.toLowerCase().trim())}matches(e){const t=e.name.toLowerCase();return this._parts.every(s=>t.includes(s))}}class o_{constructor(e){this._observables=new Map,this._allowsChild=e,this._path=new Tt([],e),this._pathObservable=new Vt(this._path)}get pathObservable(){return this._pathObservable}get path(){return this._path}push(e,...t){const s=this.path.with(new ze(e,...t));s&&this.applyPath(s)}applyPath(e){const t=this._path;this._path=e;for(let s=t.segments.length-1;s>=0;s-=1){const i=t.segments[s];if(!this._path.get(i.type)){const r=this._observables.get(i.type);r==null||r.emitIfChanged()}}for(const s of this._path.segments){const i=this._observables.get(s.type);i==null||i.emitIfChanged()}this._pathObservable.set(this._path)}observe(e){let t=this._observables.get(e);return t||(t=new c_(this,e),this._observables.set(e,t)),t}pathFrom(e){let t,s;for(s=0;s=-1)}until(e){const t=this._segments.findIndex(s=>s.type===e);return t!==-1?new Tt(this._segments.slice(0,t+1),this._allowsChild):new Tt([],this._allowsChild)}get(e){return this._segments.find(t=>t.type===e)}replace(e){const t=this._segments.findIndex(s=>s.type===e.type);if(t!==-1){const s=this._segments[t-1];if(this._allowsChild(s,e)){const i=this._segments[t+1];if(!i||this._allowsChild(e,i)){const r=this._segments.slice();return r[t]=e,new Tt(r,this._allowsChild)}}}}get segments(){return this._segments}}class c_ extends yt{constructor(e,t){var s;super(),this._navigation=e,this._type=t,this._lastSetValue=(s=e.path.get(t))==null?void 0:s.value}get(){const t=this._navigation.path.get(this._type);return t==null?void 0:t.value}emitIfChanged(){const e=this.get();a_(e,this._lastSetValue)||(this._lastSetValue=e,this.emit(e))}}class l_{constructor(e,t,s,i){this._isApplyingUrl=!1,this._history=e,this._navigation=t,this._parseUrlPath=s,this._stringifyPath=i,this._defaultSessionId=this._getLastSessionId()}_getLastSessionId(){var s;const t=(s=this._urlAsNavPath(this._history.getLastSessionUrl()||"").get("session"))==null?void 0:s.value;if(typeof t=="string")return t}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 s of e)if(t=t.with(s),!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/${encodeURIComponent(e)}`;return this._history.pathAsUrl(t)}createSSOCallbackURL(){return window.location.href}normalizeUrl(){const e=new URL(window.location.href);e.searchParams.delete("loginToken"),this._history.replaceUrlSilently(e.toString())}}function h_(){return new o_(u_)}function d_({history:n,navigation:e}){return new l_(n,e,__,p_)}function u_(n,e){const{type:t}=e;switch(n==null?void 0:n.type){case void 0:return t==="login"||t==="session"||t==="sso"||t==="logout";case"session":return t==="room"||t==="rooms"||t==="settings"||t==="create-room"||t==="join-room"||t==="device-verification";case"rooms":return t==="room"||t==="empty-grid-tile";case"room":return t==="lightbox"||t==="right-panel";case"right-panel":return t==="details"||t==="members"||t==="member"||t==="verification"||t==="invite";case"logout":return t==="forced";default:return!1}}function m_(n,e,t){if(n.value.includes(e))return n;{const s=t.get("empty-grid-tile"),i=t.get("room");let r=0;s?r=s.value:i&&(r=n.value.indexOf(i.value));const o=n.value.slice();return o[r]=e,new ze("rooms",o)}}function Eo(n,e,...t){n.push(new ze("right-panel")),n.push(new ze(e,...t))}function mn(n,e){const t=n.path.segments,s=t.findIndex(r=>r.type==="right-panel");let i=e;return s!==-1&&(i=e.until("room"),i=i.with(t[s]),i=i.with(t[s+1])),i}function __(n,e,t){const s=n.substring(1).split("/"),i=s[Symbol.iterator](),r=[];let o;for(;!(o=i.next()).done;){const c=o.value;if(c==="rooms"){const l=i.next().value;if(l===void 0)break;const h=l.split(",").map(p=>decodeURIComponent(p));r.push(new ze(c,h));const a=parseInt(i.next().value||"0",10),u=h[a];u?r.push(new ze("room",u)):r.push(new ze("empty-grid-tile",a))}else if(c==="open-room"){let l=i.next().value;if(!l)break;l=decodeURIComponent(l);const h=e.get("rooms");if(h&&r.push(m_(h,l,e)),r.push(new ze("room",l)),s.findIndex(p=>p==="open-room")>=s.length-2){const p=e.segments,g=p.findIndex(f=>f.type==="right-panel");g!==-1&&r.push(...p.slice(g))}}else if(c==="last-session"){let l=e.get("session");typeof(l==null?void 0:l.value)!="string"&&t&&(l=new ze("session",t)),l&&r.push(l)}else if(c==="details"||c==="members"||c==="verification"||c==="invite")Eo(r,c);else if(c==="member"){let l=i.next().value;if(!l)break;l=decodeURIComponent(l),Eo(r,c,l)}else if(c.includes("loginToken")){const l=c.split("=").pop();r.push(new ze("sso",l))}else{let l=i.next().value;l&&(l=decodeURIComponent(l)),r.push(new ze(c,l))}}return r}function p_(n){let e="",t;for(const s of n.segments){const i=g_(s.value);switch(s.type){case"rooms":e+=`/rooms/${i}`;break;case"empty-grid-tile":e+=`/${i}`;break;case"room":(t==null?void 0:t.type)==="rooms"?e+=`/${t.value.indexOf(s.value)}`:e+=`/${s.type}/${i}`;break;case"right-panel":case"sso":continue;default:e+=`/${s.type}`,i&&(e+=`/${i}`)}t=s}return e}function g_(n){return n===!0?"":Array.isArray(n)?n.map(e=>encodeURIComponent(e)).join(","):encodeURIComponent(n)}class f_ extends L{constructor(e){super(e);const{session:t}=e;this._tileViewModelsMap=this._mapTileViewModels(t.roomsBeingCreated,t.invites,t.rooms),this._tileViewModelsFilterMap=new yl(this._tileViewModelsMap),this._tileViewModels=this._tileViewModelsFilterMap.sortValues((s,i)=>s.compare(i)),this._currentTileVM=null,this._setupNavigation(),this._closeUrl=this.urlRouter.urlForSegment("session"),this._settingsUrl=this.urlRouter.urlForSegment("settings")}_mapTileViewModels(e,t,s){return t.join(e,s).mapValues((r,o)=>{var h;let c;return r.isBeingCreated?c=new r_(this.childOptions({roomBeingCreated:r,emitChange:o})):r.isInvite?c=new i_(this.childOptions({invite:r,emitChange:o})):c=new s_(this.childOptions({room:r,emitChange:o})),((h=this.navigation.path.get("room"))==null?void 0:h.value)===r.id&&(c.open(),this._updateCurrentVM(c)),c})}_updateCurrentVM(e){var t;(t=this._currentTileVM)==null||t.close(),this._currentTileVM=e}get closeUrl(){return this._closeUrl}get settingsUrl(){return this._settingsUrl}showCreateRoomView(){this.navigation.push("create-room")}showJoinRoomView(){this.navigation.push("join-room")}_setupNavigation(){const e=this.navigation.observe("room");this.track(e.subscribe(s=>this._open(s)));const t=this.navigation.observe("rooms");this.gridEnabled=!!t.get(),this.track(t.subscribe(s=>{const i=this.gridEnabled^!!s;this.gridEnabled=!!s,i&&this.emitChange("gridEnabled")}))}_open(e){var t,s;(t=this._currentTileVM)==null||t.close(),this._currentTileVM=null,e&&(this._currentTileVM=this._tileViewModelsMap.get(e),(s=this._currentTileVM)==null||s.open())}toggleGrid(){const e=this.navigation.path.get("room");let t=this.navigation.path.until("session");this.gridEnabled?e&&(t=t.with(e),t=mn(this.navigation,t)):e?(t=t.with(this.navigation.segment("rooms",[e.value])),t=t.with(e),t=mn(this.navigation,t)):(t=t.with(this.navigation.segment("rooms",[])),t=t.with(this.navigation.segment("empty-grid-tile",0))),this.navigation.applyPath(t)}get tileViewModels(){return this._tileViewModels}clearFilter(){this._tileViewModelsFilterMap.setApply(null),this._tileViewModelsFilterMap.applyOnce((e,t)=>t.hidden=!1)}setFilter(e){if(e=e.trim(),e.length===0)return this.clearFilter(),!1;{const t=!this._tileViewModelsFilterMap.hasApply(),s=new n_(e);return this._tileViewModelsFilterMap.setApply((i,r)=>{r.hidden=!s.matches(r)}),t}}}var me=(n=>(n.Message="message",n.MessageStatus="message-status",n.Announcement="announcement",n.File="file",n.Gap="gap",n.Image="image",n.Location="location",n.MissingAttachment="missing-attachment",n.Redacted="redacted",n.Video="video",n.DateHeader="date-header",n.Call="call",n.Verification="verification",n))(me||{});class Fe{constructor(e,t,s,i){this._remove=e,this._update=t,this._replace=s,this._updateParams=i}get shouldReplace(){return this._replace}get shouldRemove(){return this._remove}get shouldUpdate(){return this._update}get updateParams(){return this._updateParams}static Remove(){return new Fe(!0,!1,!1,null)}static Update(e){return new Fe(!1,!0,!1,e)}static Nothing(){return new Fe(!1,!1,!1,null)}static Replace(e){return new Fe(!1,!1,!0,e)}}class y_ extends ai{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,this._tileOptions);if(t)return new t(e,this._tileOptions)}_emitSpontanousUpdate(e,t){const s=e.lowerEntry,i=this._findTileIdx(s);this.emitUpdate(i,e,t)}onSubscribeFirst(){this._entrySubscription=this._entries.subscribe(this),this._populateTiles()}_populateTiles(){this._silent=!0,this._tiles=[];let e=null;for(let s of this._entries)(!e||!e.tryIncludeEntry(s))&&(e=this._createTile(s),e&&this._tiles.push(e));let t=null;for(let s of this._tiles)t&&t.updateNextSibling(s),s.updatePreviousSibling(t),t=s;t&&t.updateNextSibling(null);for(let s=0;s-s.compareEntry(t))}_findTileAtIdx(e,t){const s=this._getTileAtIdx(t);if(s&&s.compareEntry(e)===0)return s}_getTileAtIdx(e){return e>=0&&e=this._tiles.length)break;const i=this._tiles[s],r=s>0?this._tiles[s-1]:void 0,o=(r==null?void 0:r.shape)===me.DateHeader;i.needsDateSeparator&&!o?(e+=1,this._addTileAt(s,i.createDateSeparator())):!i.needsDateSeparator&&o&&this._removeTile(s-1,r)}}_addTileAt(e,t,s=!1){const i=e>0?this._tiles[e-1]:void 0,r=this._tiles[e];i==null||i.updateNextSibling(t),t.updatePreviousSibling(i),t.updateNextSibling(r),r==null||r.updatePreviousSibling(t),this._tiles.splice(e,0,t),s||this.emitAdd(e,t),t.setUpdateEmit(this._emitSpontanousUpdate)}onUpdate(e,t,s){if(!this._tiles)return;const i=this._findTileIdx(t),r=this._findTileAtIdx(t,i);if(r){const o=r.updateEntry(t,s);if(o.shouldReplace){const c=this._createTile(t);c?(this._replaceTile(i,r,c,o.updateParams),c.setUpdateEmit(this._emitSpontanousUpdate)):this._removeTile(i,r)}o.shouldRemove&&this._removeTile(i,r),o.shouldUpdate&&this.emitUpdate(i,r,o.updateParams)}}_replaceTile(e,t,s,i){t.dispose();const r=this._getTileAtIdx(e-1),o=this._getTileAtIdx(e+1);this._tiles[e]=s,r==null||r.updateNextSibling(s),s.updatePreviousSibling(r),s.updateNextSibling(o),o==null||o.updatePreviousSibling(s),this.emitUpdate(e,s,i)}_removeTile(e,t){const s=this._getTileAtIdx(e-1),i=this._getTileAtIdx(e+1);this._tiles.splice(e,1),t.dispose(),this.emitRemove(e,t),s==null||s.updateNextSibling(i),i==null||i.updatePreviousSibling(s),s&&s.shape===me.DateHeader&&(!i||!i.needsDateSeparator)&&this._removeTile(e-1,s)}onRemove(e,t){const s=this._findTileIdx(t),i=this._findTileAtIdx(t,s);i&&(i.removeEntry(t)?this._removeTile(s,i):this.emitUpdate(s,i))}onMove(){}[Symbol.iterator](){return this._tiles.values()}get length(){return this._tiles.length}getFirst(){return this._tiles[0]}getTileIndex(e){const t=Nt(this._tiles,e,(i,r)=>i.compare(r)),s=this._tiles[t];return(s==null?void 0:s.compare(e))===0?t:-1}sliceIterator(e,t){return this._tiles.slice(e,t)[Symbol.iterator]()}}class w_ extends L{constructor(e){super(e);const{timeline:t,tileOptions:s}=e;this._timeline=this.track(t),this._tiles=new y_(t.entries,s),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 s;if(e&&t){this._startTile=e,this._endTile=t;const i=this._tiles.getTileIndex(this._startTile),r=this._tiles.getTileIndex(this._endTile);for(const o of this._tiles.sliceIterator(i,r+1))o.notifyVisible();s=i<10,this._setShowJumpDown(r{this._topLoadingPromise=null,i||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 v_ extends L{constructor(e){super(e.options),this._roomVM=e,this._isEmpty=!0,this._replyVM=null}setReplyingTo(e){var s;(new Boolean(e)!==new Boolean(this._replyVM)||!((s=this._replyVM)!=null&&s.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"}}async function b_(n,e,t,s){const i=new Map;n.text&&i.set("text",n.text),i.set("user_agent",n.userAgent),i.set("app",n.app),i.set("version",n.version),n.label&&i.set("label",n.label),i.set("file",{name:"logs.json",blob:e});const r=new Map;r.set("Accept","application/json");const o=s(t,{method:"POST",body:i,headers:r});let c;try{c=await o.response()}catch(a){throw new Error(`Could not submit logs to ${t}, got error ${a.message}`)}const{status:l,body:h}=c;if(l<200||l>=300)throw new Error(`Could not submit logs to ${t}, got status code ${l} with body ${h}`)}async function cc(n,e){const{bugReportEndpointUrl:t}=e.config;if(!t)throw new Error("no server configured to submit logs");const i=e.logger.reporters.find(o=>!!o.export);if(!i)throw new Error("No logger that can export configured");const r=await i.export();await b_({app:"hydrogen",userAgent:e.description,version:e.version,text:`Submit logs from settings for user ${n.userId} on device ${n.deviceId}`},r.asBlob(),t,e.request)}class S_ extends L{get message(){return this.error.message}get error(){return this.getOption("error")}close(){this.getOption("onClose")()}async submitLogs(){try{return await cc(this.getOption("session"),this.platform),!0}catch{return!1}}}class ot extends L{get errorViewModel(){return this._errorViewModel}reportError(e){var t;((t=this._errorViewModel)==null?void 0:t.error)!==e&&(this.disposeTracked(this._errorViewModel),this._errorViewModel=this.track(new S_(this.childOptions({error:e,onClose:()=>{this._errorViewModel=this.disposeTracked(this._errorViewModel),this.emitChange("errorViewModel")}}))),this.emitChange("errorViewModel"))}logAndCatch(e,t,s=void 0){try{let i=this.logger.run(e,t);return i instanceof Promise&&(i=i.catch(r=>(this.reportError(r),s))),i}catch(i){return this.reportError(i),s}}}class Ro extends ot{constructor(e){super(e);const t=new tl(this.call,"change");this.track(t.subscribe(()=>this.onUpdate()));const s=new Ml("self",t).mapValues((r,o)=>new k_(this.childOptions({call:r,emitChange:o})),()=>{}),i=this.call.members.filterValues(r=>r.isConnected).mapValues((r,o)=>new Pn(this.childOptions({member:r,emitChange:o,mediaRepository:this.getOption("room").mediaRepository})),(r,o)=>o==null?void 0:o.onUpdate());this.memberViewModels=i.join(s).sortValues((r,o)=>r.compare(o)),this.track(this.memberViewModels.subscribe({onRemove:()=>{this.emitChange()},onAdd:()=>{this.emitChange()},onUpdate:()=>{},onReset:()=>{},onMove:()=>{}}))}get isCameraMuted(){var e,t;return(t=(e=this.call.muteSettings)==null?void 0:e.camera)!=null?t:!0}get isMicrophoneMuted(){var e,t;return(t=(e=this.call.muteSettings)==null?void 0:e.microphone)!=null?t:!0}get memberCount(){return this.memberViewModels.length}get name(){return this.call.name}get id(){return this.call.id}get call(){return this.getOption("call")}onUpdate(){this.call.error&&this.reportError(this.call.error)}async hangup(){this.logAndCatch("CallViewModel.hangup",async e=>{this.call.hasJoined&&await this.call.leave(e)})}async toggleCamera(){this.logAndCatch("Call.toggleCamera",async e=>{const{localMedia:t,muteSettings:s}=this.call;if(s&&t){if(s.camera&&!xt(t.userMedia)){const i=await this.platform.mediaDevices.getMediaTracks(!s.microphone,!0);await this.call.setMedia(t.withUserMedia(i))}else await this.call.setMuted(s.toggleCamera());this.emitChange()}})}async toggleMicrophone(){this.logAndCatch("Call.toggleMicrophone",async e=>{const{localMedia:t,muteSettings:s}=this.call;if(s&&t){if(s.microphone&&!is(t.userMedia)){const i=await this.platform.mediaDevices.getMediaTracks(!0,!s.camera);await this.call.setMedia(t.withUserMedia(i))}else await this.call.setMuted(s.toggleMicrophone());this.emitChange()}})}}class k_ extends ot{constructor(e){super(e),this.init()}async init(){const e=this.getOption("room");this.memberObservable=await e.observeMember(e.user.id),this.track(this.memberObservable.subscribe(()=>{this.emitChange(void 0)}))}get errorViewModel(){}get stream(){var e;return(e=this.call.localPreviewMedia)==null?void 0:e.userMedia}get call(){return this.getOption("call")}get isCameraMuted(){var e,t;return(t=(e=this.call.muteSettings)==null?void 0:e.camera)!=null?t:!0}get isMicrophoneMuted(){var e,t;return(t=(e=this.call.muteSettings)==null?void 0:e.microphone)!=null?t:!0}get avatarLetter(){var t;const e=(t=this.memberObservable)==null?void 0:t.get();return e?Ee(e.name):this.getOption("room").user.id}get avatarColorNumber(){return Re(this.getOption("room").user.id)}avatarUrl(e){var s;const t=(s=this.memberObservable)==null?void 0:s.get();if(t)return Be(t.avatarUrl,e,this.platform,this.getOption("room").mediaRepository)}get avatarTitle(){var t;const e=(t=this.memberObservable)==null?void 0:t.get();return e?e.name:this.getOption("room").user.id}compare(e){return-1}}class Pn extends ot{get stream(){var e;return(e=this.member.remoteMedia)==null?void 0:e.userMedia}get member(){return this.getOption("member")}get isCameraMuted(){var e,t;return(t=(e=this.member.remoteMuteSettings)==null?void 0:e.camera)!=null?t:!0}get isMicrophoneMuted(){var e,t;return(t=(e=this.member.remoteMuteSettings)==null?void 0:e.microphone)!=null?t:!0}get avatarLetter(){return Ee(this.member.member.name)}get avatarColorNumber(){return Re(this.member.userId)}avatarUrl(e){const{avatarUrl:t}=this.member.member,s=this.getOption("mediaRepository");return Be(t,e,this.platform,s)}get avatarTitle(){return this.member.member.name}onUpdate(){this.mapMemberSyncErrorIfNeeded()}mapMemberSyncErrorIfNeeded(){this.member.error&&this.reportError(this.member.error)}compare(e){if(e instanceof Pn){const t=this.member.member.userId,s=e.member.member.userId;return t===s?0:t0){const s=is(t);s&&(s.stop(),t.removeTrack(s))}return e}replaceClone(e,t){const s=(i,r,o)=>(i==null?void 0:i.id)===(o==null?void 0:o.id)?r:o==null?void 0:o.clone();return new At(s(t==null?void 0:t.userMedia,e==null?void 0:e.userMedia,this.userMedia),s(t==null?void 0:t.screenShare,e==null?void 0:e.screenShare,this.screenShare),this.dataChannelOptions)}clone(){var e,t;return new At((e=this.userMedia)==null?void 0:e.clone(),(t=this.screenShare)==null?void 0:t.clone(),this.dataChannelOptions)}dispose(){var e,t,s;(e=is(this.userMedia))==null||e.stop(),(t=xt(this.userMedia))==null||t.stop(),(s=xt(this.screenShare))==null||s.stop()}}class I_ extends L{constructor(e,t){super(t),this._firstTileInDay=e}setUpdateEmit(e){this._emitUpdate=e}get upperEntry(){return this.refEntry}get lowerEntry(){return this.refEntry}get refEntry(){return this._firstTileInDay.lowerEntry}compare(e){return this.compareEntry(e.upperEntry)}get relativeDate(){return this._dateString||(this._dateString=this.timeFormatter.formatRelativeDate(new Date(this.refEntry.timestamp))),this._dateString}get machineReadableDate(){return this._machineReadableString||(this._machineReadableString=this.timeFormatter.formatMachineReadableDate(new Date(this.refEntry.timestamp))),this._machineReadableString}get shape(){return me.DateHeader}get needsDateSeparator(){return!1}createDateSeparator(){}compareEntry(e){const t=this.refEntry.compare(e);return t===0?-1:t}updateEntry(e,t){return Fe.Nothing()}removeEntry(e){return!1}tryIncludeEntry(){return!1}get comparisonIsNotCommutative(){return!0}updatePreviousSibling(e){this._firstTileInDay.updatePreviousSibling(e)}updateNextSibling(e){var s;if(!e)return;this._firstTileInDay=e;const t=this._dateString;this._dateString=void 0,this._machineReadableString=void 0,t&&t!==this.relativeDate&&((s=this._emitUpdate)==null||s.call(this,this,"relativeDate"))}notifyVisible(){}dispose(){}}class xs extends ot{constructor(e,t){super(t),this._needsDateSeparator=!1,this._entry=e,this._date=this._entry.timestamp?new Date(this._entry.timestamp):void 0}get isContinuation(){return!1}get needsDateSeparator(){return this._needsDateSeparator}createDateSeparator(){return new I_(this,this.childOptions({}))}_updateDateSeparator(e){e&&e._date&&this._date?this._needsDateSeparator=e._date.getFullYear()!==this._date.getFullYear()||e._date.getMonth()!==this._date.getMonth()||e._date.getDate()!==this._date.getDate():this._needsDateSeparator=!!this._date}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!==X.Sent}get canAbortSending(){return this._entry.isPending&&!this._entry.pendingEvent.hasStartedSending}async abortSending(){var e;await((e=this._entry.pendingEvent)==null?void 0: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}get comparisonIsNotCommutative(){return!1}compare(e){return e.comparisonIsNotCommutative?-e.compare(this):this.upperEntry.compare(e.upperEntry)}compareEntry(e){return this._entry.compare(e)}updateEntry(e,t){const s=this.shape==="redacted";return!e.isGap&&e.isRedacted!==s?Fe.Replace("shape"):(this._entry=e,Fe.Update(t))}removeEntry(){return!0}tryIncludeEntry(){return!1}updatePreviousSibling(e){(e==null?void 0:e.shape)!==me.DateHeader&&this._updateDateSeparator(e)}updateNextSibling(){}notifyVisible(){}dispose(){this.setUpdateEmit(void 0),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}get displayName(){return this._entry.displayName||this.sender}get sender(){return this._entry.sender}}class M_ extends xs{constructor(e,t){super(e,t),this._loading=!1,this._waitingForConnection=!1,this._isAtTop=!0,this._siblingChanged=!1}get needsDateSeparator(){return!1}async fill(e=!1){if(!this._loading&&!this._entry.edgeReached){this._loading=!0,this.emitChange("isLoading");try{await this._room.fillGap(this._entry,10)}catch(t){return t instanceof Ut?(await this._waitForReconnection(),e?!1:await this.fill(!0)):(this.reportError(t),!1)}finally{this._loading=!1,this.emitChange("isLoading")}return!0}return!1}async notifyVisible(){if(this.errorViewModel)return;let e=0,t;this._siblingChanged=!1;do t=await this.fill(),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?Fe.Nothing():Fe.Remove()}async _waitForReconnection(){this._waitingForConnection=!0,this.emitUpdate("status"),await this.options.client.reconnector.connectionStatus.waitFor(e=>e===Ys.Online).promise,this._waitingForConnection=!1,this.emitUpdate("status")}get shape(){return"gap"}get isLoading(){return this._loading}get showSpinner(){return this.isLoading||this._waitingForConnection}get status(){const e=this._entry.prev_batch?"previous":"next";return this._waitingForConnection?"Waiting for connection\u2026":this.errorViewModel?`Could not load ${e} messages`:this.isLoading?"Loading more messages\u2026":"Gave up loading more messages"}}class C_{constructor(e){this._parentTile=e,this._map=new Dt,this._reactions=this._map.sortValues((t,s)=>t._compare(s))}update(e,t){if(e){for(const s in e)if(e.hasOwnProperty(s)){const i=e[s],r=this._map.get(s);r?r._tryUpdate(i)&&this._map.update(s):this._map.add(s,new To(s,i,null,this._parentTile))}}if(t)for(const[s,i]of t.entries()){const r=this._map.get(s);r?(r._tryUpdatePending(i),this._map.update(s)):this._map.add(s,new To(s,null,i,this._parentTile))}for(const s of this._map.keys()){const i=t==null?void 0:t.has(s),r=e==null?void 0:e.hasOwnProperty(s);!r&&!i?this._map.remove(s):r?i||this._map.get(s)._tryUpdatePending(null)&&this._map.update(s):this._map.get(s)._tryUpdate(null)&&this._map.update(s)}}get reactions(){return this._reactions}getReaction(e){return this._map.get(e)}}class To{constructor(e,t,s,i){this._key=e,this._annotation=t,this._pending=s,this._parentTile=i,this._isToggling=!1}_tryUpdate(e){const t=!!this._annotation!=!!e,i=this._annotation&&e&&(e.me!==this._annotation.me||e.count!==this._annotation.count||e.firstTimestamp!==this._annotation.firstTimestamp);return t||i?(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{var r,o;if(!this.canReact){s.set("powerlevel_lacking",!0);return}if(this._entry.haveAnnotation(e)){s.set("already_reacted",!0);return}const i=(o=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:o.redactionEntry;i&&!i.pendingEvent.hasStartedSending?(s.set("abort_redaction",!0),await i.pendingEvent.abort()):await this._room.sendEvent("m.reaction",this._entry.annotate(e),null,s)})}redactReaction(e,t=null){return this.logger.wrapOrRun(t,"redactReaction",async s=>{var r,o;if(!this._powerLevels.canRedactFromSender(this._ownMember.userId)){s.set("powerlevel_lacking",!0);return}if(!this._entry.haveAnnotation(e)){s.set("not_yet_reacted",!0);return}let i=(o=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:o.annotationEntry;i||(i=await this._timeline.getOwnAnnotationEntry(this._entry.id,e)),i?await this._room.sendRedaction(i.id,null,s):s.set("no_reaction",!0)})}toggleReaction(e,t=null){return this.logger.wrapOrRun(t,"toggleReaction",async s=>{this._entry.haveAnnotation(e)?await this.redactReaction(e,s):await this.react(e,s)})}_updateReactions(){const{annotations:e,pendingAnnotations:t}=this._entry;!e&&!t?this._reactions&&(this._reactions=null):(this._reactions||(this._reactions=new C_(this)),this._reactions.update(e,t))}get replyTile(){return this._entry.contextEventId?this._replyTile:null}}const E_="(?:https|http|ftp):\\/\\/",lc="[^\\s.,?!)]",Ao="[a-zA-Z0-9:.\\[\\]-]",R_=`${Ao}*(?=${Ao})${lc}`,T_=`(?:[\\/#](?:[^\\s]*${lc})?)`,A_=`${E_}${R_}${T_}?`,x_=new RegExp(A_,"gi");function hc(n,e){const t=n.matchAll(x_);let s=0;for(let r of t){const o=n.slice(s,r.index);e(o,!1),e(r[0],!0);const c=r[0].length;s=r.index+c}const i=n.slice(s);e(i,!1)}function V_(n){const e=[],t=n.split(` `),s=(i,r)=>{r?e.push(new _n(i,[new ii(i)])):e.push(new ii(i))};for(let i=0;i=t.length-1||e.push(new dc)}return new Fn(n,e)}function N_(n){return new Fn(n,[new ii(n)])}class D_{constructor(e,t){this.level=e,this.inlines=t}get type(){return"header"}}class xo{constructor(e,t){this.language=e,this.text=t}get type(){return"codeblock"}}class U_{constructor(e,t){this.items=t,this.startOffset=e}get type(){return"list"}}class O_{constructor(e,t){this.head=e,this.body=t}get type(){return"table"}}class P_{get type(){return"rule"}}class dc{get type(){return"newline"}}class hr{constructor(e,t){this.format=e.toLowerCase(),this.children=t}get type(){return"format"}}class F_{constructor(e,t,s,i,r){this.src=e,this.width=t,this.height=s,this.alt=i,this.title=r}get type(){return"image"}}class L_{constructor(e,t,s){this.id=e,this.href=t,this.children=s}get type(){return"pill"}get avatarColorNumber(){return Re(this.id)}get avatarInitials(){return Ee(this.id)}}class _n{constructor(e,t){this.url=e,this.inlines=t}get type(){return"link"}}class ii{constructor(e){this.text=e}get type(){return"text"}}function K_(n){return n.type==="format"&&n.format==="blockquote"}class Fn{constructor(e,t){this.sourceString=e,this.parts=t}insertEmote(e){let t=0;for(;t`${n}://`),q_="https://matrix.to",Vo=`${q_}/#/`;class H_{constructor(e,t){this.result=e,this.mediaRepository=t}parsePillLink(e){if(!e.startsWith(Vo))return null;const t=e.substring(Vo.length);return t[0]==="@"?t:null}parseLink(e,t){const s=this.result.getAttributeValue(e,"href"),i=s==null?void 0:s.toLowerCase();if(!i||!j_.some(o=>i.startsWith(o)))return new hr("span",t);const r=this.parsePillLink(s);return r?new L_(r,s,t):new _n(s,t)}parseList(e){const t=this.result;let s=null;t.getNodeElementName(e)==="OL"&&(s=parseInt(t.getAttributeValue(e,"start"))||1);const i=[];for(const r of t.getChildNodes(e)){if(t.getNodeElementName(r)!=="LI")continue;const o=this.parseAnyNodes(t.getChildNodes(r));i.push(o)}return new U_(s,i)}_ensureElement(e,t){return e&&this.result.isElementNode(e)&&this.result.getNodeElementName(e)===t}parseCodeBlock(e){const t=this.result;let s;for(const o of t.getChildNodes(e)){s=o;break}let i=null;if(!this._ensureElement(s,"CODE"))return new xo(i,this.result.getNodeText(e));const r=t.getAttributeValue(s,"class")||"";for(const o of r.split(" "))if(o.startsWith("language-")&&!o.startsWith("language-_")){i=o.substring(9);break}return new xo(i,this.result.getNodeText(s))}parseImage(e){const t=this.result,s=t.getAttributeValue(e,"src")||"",i=this.mediaRepository.mxcUrl(s);if(!i)return null;const r=parseInt(t.getAttributeValue(e,"width"))||null,o=parseInt(t.getAttributeValue(e,"height"))||null,c=t.getAttributeValue(e,"alt"),l=t.getAttributeValue(e,"title");return new F_(i,r,o,c,l)}parseTableRow(e,t){const s=[];for(const i of this.result.getChildNodes(e)){if(!this._ensureElement(i,t))continue;const r=this.result.getChildNodes(i),o=this.parseInlineNodes(r);s.push(o)}return s}parseTableHead(e){let t=null;for(const s of this.result.getChildNodes(e)){t=s;break}return this._ensureElement(t,"TR")?this.parseTableRow(t,"TH"):null}parseTableBody(e){const t=[];for(const s of this.result.getChildNodes(e))!this._ensureElement(s,"TR")||t.push(this.parseTableRow(s,"TD"));return t}parseTable(e){const t=Array.from(this.result.getChildNodes(e));let s,i;return this._ensureElement(t[0],"THEAD")&&this._ensureElement(t[1],"TBODY")?(s=this.parseTableHead(t[0]),i=this.parseTableBody(t[1])):this._ensureElement(t[0],"TBODY")&&(s=null,i=this.parseTableBody(t[0])),new O_(s,i)}parseInlineElement(e){const t=this.result,s=t.getNodeElementName(e),i=t.getChildNodes(e);switch(s){case"A":{const r=this.parseInlineNodes(i);return this.parseLink(e,r)}case"BR":return new dc;default:{if(!B_.includes(s))return null;const r=this.parseInlineNodes(i);return new hr(s,r)}}}parseInlineNode(e){return this.result.isElementNode(e)?this.parseInlineElement(e):null}parseBlockElement(e){const t=this.result,s=t.getNodeElementName(e),i=t.getChildNodes(e);switch(s){case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":{const r=this.parseInlineNodes(i);return new D_(parseInt(s[1]),r)}case"UL":case"OL":return this.parseList(e);case"PRE":return this.parseCodeBlock(e);case"HR":return new P_;case"IMG":return this.parseImage(e);case"P":{const r=this.parseInlineNodes(i);return new hr(s,r)}case"TABLE":return this.parseTable(e);default:{if(!$_.includes(s))return null;const r=this.parseAnyNodes(i);return new hr(s,r)}}}parseBlockNode(e){return this.result.isElementNode(e)?this.parseBlockElement(e):null}_parseTextParts(e,t){if(!this.result.isTextNode(e))return!1;const s=(i,r)=>{r?t.push(new _n(i,[new ii(i)])):t.push(new ii(i))};return hc(this.result.getNodeText(e),s),!0}_isAllowedNode(e){return!this._ensureElement(e,"MX-REPLY")}_parseInlineNodes(e,t){for(const s of e){if(this._parseTextParts(s,t))continue;const i=this.parseInlineNode(s);if(i){t.push(i);continue}this._isAllowedNode(s)&&this._parseInlineNodes(this.result.getChildNodes(s),t)}}parseInlineNodes(e){const t=[];return this._parseInlineNodes(e,t),t}_parseAnyNodes(e,t){for(const s of e){if(this._parseTextParts(s,t))continue;const i=this.parseInlineNode(s)||this.parseBlockNode(s);if(i){t.push(i);continue}this._isAllowedNode(s)&&this._parseAnyNodes(this.result.getChildNodes(s),t)}}parseAnyNodes(e){const t=[];return this._parseAnyNodes(e,t),t}}function W_(n,e,t){const s=n.parseHTML(t),r=new H_(s,e).parseAnyNodes(s.rootNodes);return new Fn(t,r)}class z_ extends uc{_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()===Ti.Html?this._getFormattedBody():this._getPlainBody()}_getBodyFormat(){var e;return((e=this._getContent())==null?void 0:e.format)==="org.matrix.custom.html"?Ti.Html:Ti.Plain}_parseBody(e,t){var i;let s;return t===Ti.Html?s=W_(this.platform,this._mediaRepository,e):s=V_(e),((i=this._getContent())==null?void 0:i.msgtype)==="m.emote"&&s.insertEmote(`* ${this.displayName} `),s}}class No extends ns{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 G_=300,Y_=400;class mc extends ns{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 s;try{s=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(s,t)}catch(i){this._downloadError=i}finally{s==null||s.dispose(),this._downloading=!1}this.emitChange("status")}get isUploading(){return this.isPending&&this._entry.pendingEvent.status===X.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==null?void 0:e.status){case X.Waiting:return this.i18n`Waiting…`;case X.EncryptingAttachments:case X.Encrypting:return this.i18n`Encrypting…`;case X.UploadingAttachments:return this.i18n`Uploading…`;case X.Sending:return this.i18n`Sending…`;case X.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 s=(e=this._getContent().info)==null?void 0:e.thumbnail_url;if(s)return this._mediaRepository.mxcUrlThumbnail(s,this.width,this.height,"scale")}if(this._entry.isPending){const s=this._entry.pendingEvent.getAttachment("info.thumbnail_url");return s&&s.localPreview.url}if(this._isMainResourceImage()){if(this._decryptedFile)return this._decryptedFile.url;{const s=(t=this._getContent())==null?void 0:t.url;if(typeof s=="string")return this._mediaRepository.mxcUrlThumbnail(s,this.width,this.height,"scale")}}return""}notifyVisible(){super.notifyVisible(),this._isVisible=!0,this.emitChange("thumbnailUrl"),this.isPending||this._tryLoadEncryptedThumbnail()}get width(){var t;const e=(t=this._getContent())==null?void 0:t.info;return Math.round((e==null?void 0:e.w)*this._scaleFactor())}get height(){var t;const e=(t=this._getContent())==null?void 0:t.info;return Math.round((e==null?void 0:e.h)*this._scaleFactor())}get mimeType(){var t;const e=(t=this._getContent())==null?void 0:t.info;return e==null?void 0:e.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,s=this._getContent().file;t?(this._decryptedThumbnail=await this._loadEncryptedFile(t),this.emitChange("thumbnailUrl")):s&&this._isMainResourceImage()&&(this._decryptedFile=await this._loadEncryptedFile(s),this.emitChange("thumbnailUrl"))}catch(t){this._error=t,this.emitChange("error")}}_scaleFactor(){var i;const e=(i=this._getContent())==null?void 0:i.info,t=G_/(e==null?void 0:e.h),s=Y_/(e==null?void 0:e.w);return Math.min(s,t,1)}_isMainResourceImage(){return!0}}class J_ extends mc{constructor(e,t){super(e,t),this._lightboxUrl=this.urlRouter.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 Q_ extends mc{async loadVideo(){const e=this._getContent().file;e&&!this._decryptedFile&&(this._decryptedFile=await this._loadEncryptedFile(e),this.emitChange("videoUrl"))}get videoUrl(){var t;if(this._decryptedFile)return this._decryptedFile.url;const e=(t=this._getContent())==null?void 0:t.url;return typeof e=="string"?this._mediaRepository.mxcUrl(e):""}get shape(){return"video"}_isMainResourceImage(){return!1}}function X_(n,e=2){if(Number.isSafeInteger(n)){const t=Math.min(3,Math.floor(Math.log(n)/Math.log(1024))),s=Math.round(n/Math.pow(1024,t)).toFixed(e);switch(t){case 0:return`${s} bytes`;case 1:return`${s} KB`;case 2:return`${s} MB`;case 3:return`${s} GB`}}return""}class Z_ extends ns{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 s;try{s=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(s,t)}catch(i){this._downloadError=i}finally{s==null||s.dispose(),this._downloading=!1}this.emitChange("label")}get label(){var s;if(this._downloadError)return`Could not download file: ${this._downloadError.message}`;const t=this._getContent().body;if(this._entry.isPending){const{pendingEvent:i}=this._entry;switch(i==null?void 0:i.status){case X.Waiting:return this.i18n`Waiting to send ${t}…`;case X.EncryptingAttachments:case X.Encrypting:return this.i18n`Encrypting ${t}…`;case X.UploadingAttachments:{const r=Math.round(i.attachmentsSentBytes/i.attachmentsTotalBytes*100);return this.i18n`Uploading ${t}: ${r}%`}case X.Sending:case X.Sent:return this.i18n`Sending ${t}…`;case X.Error:return this.i18n`Error: could not send ${t}: ${i.error.message}`;default:return`Unknown send status for ${t}`}}else{const i=X_((s=this._getContent().info)==null?void 0:s.size);return this._downloading?this.i18n`Downloading ${t} (${i})…`:this.i18n`Download ${t} (${i})`}}get shape(){return"file"}}class ep extends ns{get shape(){return"location"}get mapsLink(){try{const e=new URL(this._getContent().geo_uri);if(e.protocol!=="geo:")return"";const[t,...s]=e.pathname.split(";"),[i,r]=t.split(","),o=parseFloat(i),c=parseFloat(r);let l;for(const h of s){const[a,u]=h.split("=");a==="u"&&(l=parseFloat(u))}if(this.platform.isIOS)return`http://maps.apple.com/?ll=${o},${c}`;{let h=`geo:${o},${c}`;return l&&(h=h+`;u=${l}`),h}}catch{return""}}get label(){return this.i18n`${this.displayName} sent their location`}}class tp extends xs{get shape(){return"announcement"}get announcement(){const e=this._entry.content;return`${this._entry.displayName||this._entry.sender} named the room "${e==null?void 0:e.name}"`}}class sp extends xs{get shape(){return"announcement"}get announcement(){var h,a;const{sender:e,content:t,prevContent:s,stateKey:i}=this._entry,r=this._entry.displayName||e,o=e===i?r:((h=this._entry.content)==null?void 0:h.displayname)||i,c=t&&t.membership,l=s&&s.membership;if(l==="join"&&c==="join"){if(t.avatar_url!==s.avatar_url)return`${r} changed their avatar`;if(t.displayname!==s.displayname)return t.displayname?`${(a=s.displayname)!=null?a:i} changed their name to ${t.displayname}`:`${i} removed their name (${s.displayname})`}else{if(c==="join")return`${o} joined the room`;if(c==="invite")return`${o} was invited to the room by ${r}`;if(l==="invite"){if(c==="join")return`${o} accepted the invitation to join the room`;if(c==="leave")return`${o} declined the invitation to join the room`}else if(c==="leave"){if(i===e)return`${o} left the room`;{const u=t.reason;return`${o} was kicked from the room by ${r}${u?`: ${u}`:""}`}}else if(c==="ban")return`${o} was banned from the room by ${r}`}return`${e} membership changed to ${t.membership}`}}class ip extends uc{updateEntry(e,t){const s=super.updateEntry(e,t);return e.eventType!=="m.room.encrypted"?Fe.Replace("shape"):s}get shape(){return"message-status"}_getBody(){const e=this._entry.decryptionError,t=e==null?void 0:e.code;let s;return t==="MEGOLM_NO_SESSION"?s=this.i18n`The sender hasn't sent us the key for this message yet.`:s=(e==null?void 0:e.message)||this.i18n`Could not decrypt message because of unknown reason.`,s}}class rp extends xs{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 np extends ns{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.`}}class op extends xs{constructor(e,t){super(e,t);const s=this.getOption("session").callHandler.calls;this._callSubscription=void 0,this._memberSizeSubscription=void 0;const i=s.get(this._entry.stateKey);i&&!i.isTerminated&&(this._call=i,this.memberViewModels=this._setupMembersList(this._call),this._callSubscription=this.track(this._call.disposableOn("change",()=>{this._onCallUpdate()})),this._memberSizeSubscription=this.track(this._call.members.observeSize().subscribe(()=>{this.emitChange("memberCount")})),this._onCallUpdate())}_onCallUpdate(){this._call.isTerminated?(this._durationInterval=this.disposeTracked(this._durationInterval),this._callSubscription=this.disposeTracked(this._callSubscription),this._call=void 0):this._durationInterval||(this._durationInterval=this.track(this.platform.clock.createInterval(()=>{this.emitChange("duration")},1e3))),this.emitChange()}_setupMembersList(e){return e.members.mapValues((t,s)=>new ap(this.childOptions({member:t,emitChange:s,mediaRepository:this.getOption("room").mediaRepository}))).sortValues((t,s)=>t.userId.localeCompare(s.userId))}get memberCount(){return this._call?this._call.members.size:0}get confId(){return this._entry.stateKey}get duration(){return this._call&&this._call.duration?this.timeFormatter.formatDuration(this._call.duration):""}get shape(){return"call"}get canJoin(){return this._call&&!this._call.hasJoined&&!this._call.usesFoci}get canLeave(){return this._call&&this._call.hasJoined}get title(){return this._call?this.type===yr.Video?`${this.displayName} started a video call`:`${this.displayName} started a voice call`:this.type===yr.Video?"Video call ended":"Voice call ended"}get typeLabel(){return this._call&&this._call.usesFoci?"This call uses a stream-forwarding unit, which isn't supported yet, so you can't join this call.":this.type===yr.Video?"Video call":"Voice call"}get type(){return this._entry.event.content["m.type"]}async join(){await this.logAndCatch("CallTile.join",async e=>{if(this.canJoin){const t=await this.platform.mediaDevices.getMediaTracks(!1,!0),s=new At().withUserMedia(t);await this._call.join(s,e)}})}async leave(){await this.logAndCatch("CallTile.leave",async e=>{this.canLeave&&await this._call.leave(e)})}}class ap extends L{get _member(){return this.getOption("member")}get userId(){return this._member.userId}get avatarLetter(){return Ee(this._member.member.name)}get avatarColorNumber(){return Re(this._member.userId)}avatarUrl(e){const{avatarUrl:t}=this._member.member,s=this.getOption("mediaRepository");return Be(t,e,this.platform,s)}get avatarTitle(){return this._member.member.name}}var Ai=(n=>(n[n.Ready=0]="Ready",n[n.InProgress=1]="InProgress",n[n.Completed=2]="Completed",n[n.Cancelled=3]="Cancelled",n))(Ai||{});class cp extends xs{constructor(e,t){super(e,t),this.status=0,this.request=new pr(this.lowerEntry),this.updateStatusFromAvailableContextForEntries()}get shape(){return me.Verification}get description(){return this.i18n`${this.sender} wants to verify`}accept(){this.getOption("session").crossSigning.get().receivedSASVerifications.set(this.eventId,this.request),this.openVerificationPanel(this.eventId)}async reject(){await this.logAndCatch("VerificationTile.reject",async e=>{const t=this.getOption("session").crossSigning.get();await this.request.reject(t,this._room,e)})}openVerificationPanel(e){let t=this.navigation.path.until("room");t=t.with(this.navigation.segment("right-panel",!0)),t=t.with(this.navigation.segment("verification",e)),this.navigation.applyPath(t)}updateEntry(e,t){return t==="context-added"?this.updateStatusFromAvailableContextForEntries()?Fe.Update(t):Fe.Nothing():super.updateEntry(e,t)}updateStatusFromAvailableContextForEntries(){var t;let e=!1;for(const s of(t=this.lowerEntry.contextForEntries)!=null?t:[])switch(s.eventType){case P.Cancel:return this.status=3,this.isCancelledByUs=s.sender===this.getOption("session").userId,!0;case P.Done:return this.status=2,!0;default:this.status=1,e=!0}return e}}function lp(n,e){if(n.isGap)return M_;if(n.isPending&&n.pendingEvent.isMissingAttachments)return np;if(n.eventType)switch(n.eventType){case"m.room.message":{if(n.isRedacted)return No;const t=n.content;switch(t&&t.msgtype){case"m.text":case"m.notice":case"m.emote":return z_;case"m.image":return J_;case"m.video":return Q_;case"m.file":return Z_;case"m.location":return ep;case"m.key.verification.request":const i=!e.session.features.crossSigning,r=e.session.userId;return i||n.sender===r?void 0:cp;default:return}}case"m.room.name":return tp;case"m.room.member":return sp;case"m.room.encrypted":return n.isRedacted?No:ip;case"m.room.encryption":return rp;case"org.matrix.msc3401.call":return e.features.calls&&n.stateKey&&!n.prevContent?op:void 0;default:return}}async function _c(n,e){var t,s,i,r;try{const o=await e.joinRoom(n);return await(await e.observeRoomStatus(o)).waitFor(l=>l===se.Joined),o}catch(o){throw((t=o.statusCode)!=null?t:o.status)===400?new Error(`'${n}' is not a legal room ID or alias`):((s=o.statusCode)!=null?s:o.status)===404||((i=o.statusCode)!=null?i:o.status)===502||o.message=="Internal Server eor"?new Error(`Room '${n}' could not be found`):((r=o.statusCode)!=null?r:o.status)===403?new Error(`You are not invited to join '${n}'`):o}}class Do extends ot{constructor(e){var i;super(e);const{room:t,tileClassForEntry:s}=e;this._sendReadReceipt=(i=e.sendReadReceipt)!=null?i:!0,this._room=t,this._timelineVM=null,this._tileClassForEntry=s!=null?s:lp,this._tileOptions=void 0,this._onRoomChange=this._onRoomChange.bind(this),this._composerVM=null,t.isArchived?this._composerVM=this.track(new dp(this.childOptions({archivedRoom:t}))):this._recreateComposerOnPowerLevelChange(),this._clearUnreadTimout=null,this._closeUrl=this.urlRouter.urlUntilSegment("session"),this._setupCallViewModel()}_setupCallViewModel(){if(!this.features.calls)return;const e=this.getOption("session").callHandler.calls;this._callObservable=new rl(e.filterValues(s=>s.roomId===this._room.id&&s.hasJoined)),this._callViewModel=void 0,this.track(this._callObservable.subscribe(s=>{s&&this._callViewModel&&s.id===this._callViewModel.id||(this._callViewModel=this.disposeTracked(this._callViewModel),s&&(this._callViewModel=this.track(new Ro(this.childOptions({call:s,room:this._room})))),this.emitChange("callViewModel"))}));const t=this._callObservable.get();t&&(this._callViewModel=this.track(new Ro(this.childOptions({call:t,room:this._room}))))}async load(){await this.logAndCatch("RoomViewModel.load",async e=>{this._room.on("change",this._onRoomChange);const t=await this._room.openTimeline(e);this.track(()=>t.release()),this._tileOptions=this.childOptions({session:this.getOption("session"),roomVM:this,timeline:t,tileClassForEntry:this._tileClassForEntry}),this._timelineVM=this.track(new w_(this.childOptions({tileOptions:this._tileOptions,timeline:t}))),this.emitChange("timelineViewModel"),await this._clearUnreadAfterDelay(e)})}async _recreateComposerOnPowerLevelChange(){const e=await this._room.observePowerLevels(),t=()=>e.get().canSendType("m.room.message");let s=t();const i=r=>{this._composerVM=this.disposeTracked(this._composerVM),r?this._composerVM=this.track(new v_(this)):this._composerVM=this.track(new up(this.childOptions())),this.emitChange("powerLevelObservable")};this.track(e.subscribe(()=>{const r=t();s!==r&&(i(r),s=r)})),i(s)}async _clearUnreadAfterDelay(e){if(!(this._room.isArchived||this._clearUnreadTimout)){this._clearUnreadTimout=this.clock.createTimeout(2e3);try{await this._clearUnreadTimout.elapsed(),await this._room.clearUnread(e,this._sendReadReceipt),this._clearUnreadTimout=null}catch(t){if(t.name==="AbortError")e.set("clearUnreadCancelled",!0);else throw t}}}focus(){this.logAndCatch("RoomViewModel.focus",async e=>{this._clearUnreadAfterDelay(e)})}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 avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this._room.avatarColorId)}avatarUrl(e){return Be(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,this._tileOptions);if(t)return new t(e,this._tileOptions)}}_sendMessage(e,t){return this.logAndCatch("RoomViewModel.sendMessage",async s=>{let i=!1;if(!this._room.isArchived&&e){let r="m.text";if(e.startsWith("//"))e=e.substring(1).trim();else if(e.startsWith("/")){const c=await this._processCommand(e);r=c.msgtype,e=c.message}let o;t?(s.set("replyingTo",t.eventId),o=await t.createReplyContent(r,e)):o={msgtype:r,body:e},await this._room.sendEvent("m.room.message",o,void 0,s),i=!0}return s.set("success",i),i},!1)}async _processCommandJoin(e){try{const t=this._options.client.session,s=await _c(e,t);this.navigation.push("room",s)}catch(t){this.reportError(t)}}async _processCommand(e){let t;const[s,...i]=e.substring(1).split(" ");switch(s){case"me":e=i.join(" "),t="m.emote";break;case"join":if(i.length===1){const r=i[0];await this._processCommandJoin(r)}else this.reportError(new Error("join syntax: /join "));break;case"invite":if(i.length===1){const r=i[0];await this._room.inviteUser(r)}else this.reportError(new Error("invite syntax: /invite "));break;case"shrug":e="\xAF\\_(\u30C4)_/\xAF "+i.join(" "),t="m.text";break;case"tableflip":e="(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B "+i.join(" "),t="m.text";break;case"unflip":e="\u252C\u2500\u2500\u252C \u30CE( \u309C-\u309C\u30CE) "+i.join(" "),t="m.text";break;case"lenny":e="( \u0361\xB0 \u035C\u0296 \u0361\xB0) "+i.join(" "),t="m.text";break;default:this.reportError(new Error(`no command name "${s}". To send the message instead of executing, please type "/${e}"`)),e=void 0}return{msgtype:t,message:e}}_pickAndSendFile(){return this.logAndCatch("RoomViewModel.sendFile",async e=>{const t=await this.platform.openFile();if(!t){e.set("cancelled",!0);return}return this._sendFile(t,e)})}async _sendFile(e,t){const s={body:e.name,msgtype:"m.file"};await this._room.sendEvent("m.room.message",s,{url:this._room.createAttachment(e.blob,e.name)},t)}_pickAndSendVideo(){return this.logAndCatch("RoomViewModel.sendVideo",async e=>{if(!this.platform.hasReadPixelPermission())throw new Error("Please allow canvas image data access, so we can scale your images down.");const t=await this.platform.openFile("video/*");if(!t)return;if(!t.blob.mimeType.startsWith("video/"))return this._sendFile(t,e);let s;try{s=await this.platform.loadVideo(t.blob)}catch(h){throw h instanceof window.MediaError&&h.code===4?new Error(`this browser does not support videos of type ${t==null?void 0:t.blob.mimeType}.`):h}const i={body:t.name,msgtype:"m.video",info:hp(s)},r={url:this._room.createAttachment(s.blob,t.name)},c=await this.platform.settingsStorage.getInt("sentImageSizeLimit")||Math.min(s.maxDimension,800),l=await s.scale(c);i.info.thumbnail_info=Ni(l),r["info.thumbnail_url"]=this._room.createAttachment(l.blob,t.name),await this._room.sendEvent("m.room.message",i,r,e)})}async _pickAndSendPicture(){this.logAndCatch("RoomViewModel.sendPicture",async e=>{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const t=await this.platform.openFile("image/*");if(!t){e.set("cancelled",!0);return}if(!t.blob.mimeType.startsWith("image/"))return this._sendFile(t,e);let s=await this.platform.loadImage(t.blob);const i=await this.platform.settingsStorage.getInt("sentImageSizeLimit");if(i&&s.maxDimension>i){const c=await s.scale(i);s.dispose(),s=c}const r={body:t.name,msgtype:"m.image",info:Ni(s)},o={url:this._room.createAttachment(s.blob,t.name)};if(s.maxDimension>600){const c=await s.scale(400);r.info.thumbnail_info=Ni(c),o["info.thumbnail_url"]=this._room.createAttachment(c.blob,t.name)}await this._room.sendEvent("m.room.message",r,o,e)})}get room(){return this._room}get composerViewModel(){return this._composerVM}get callViewModel(){return this._callViewModel}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)}startCall(){return this.logAndCatch("RoomViewModel.startCall",async e=>{if(!this.features.calls){e.set("feature_disbled",!0);return}e.set("roomId",this._room.id);let t;try{const r=await this.platform.mediaDevices.getMediaTracks(!1,!0);t=new At().withUserMedia(r)}catch(r){throw new Error(`Could not get local audio and/or video stream: ${r.message}`)}const s=this.getOption("session");let i;try{i=await s.callHandler.createCall(this._room.id,"m.video","A call "+Math.round(this.platform.random()*100),void 0,e)}catch(r){throw new Error(`Could not create call: ${r.message}`)}try{await i.join(t,e)}catch(r){throw new Error(`Could not join call: ${r.message}`)}})}}function hp(n){const e=Ni(n);return e.duration=n.duration,e}class dp extends L{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 up extends L{get description(){return this.i18n`You do not have the powerlevel necessary to send messages`}get kind(){return"disabled"}}class mp extends L{constructor(e){super(e);const{roomIdOrAlias:t,session:s}=e;this._session=s,this.roomIdOrAlias=t,this._error=null,this._busy=!1,this._closeUrl=this.urlRouter.urlUntilSegment("session")}get closeUrl(){return this._closeUrl}get error(){var e;return(e=this._error)==null?void 0:e.message}async join(){this._busy=!0,this.emitChange("busy");try{const e=await this._session.joinRoom(this.roomIdOrAlias);this.navigation.push("room",e)}catch(e){this._error=e,this._busy=!1,this.emitChange("error")}}get busy(){return this._busy}get kind(){return"unknown"}}class _p extends L{constructor(e){super(e);const{invite:t,mediaRepository:s}=e;this._invite=t,this._mediaRepository=s,this._onInviteChange=this._onInviteChange.bind(this),this._error=null,this._closeUrl=this.urlRouter.urlUntilSegment("session"),this._invite.on("change",this._onInviteChange),this._inviter=null,this._invite.inviter&&(this._inviter=new pp(this._invite.inviter,s,this.platform)),this._roomDescription=this._createRoomDescription()}get kind(){return"invite"}get closeUrl(){return this._closeUrl}get name(){return this._invite.name}get id(){return this._invite.id}get isEncrypted(){return this._invite.isEncrypted}get isDirectMessage(){return this._invite.isDirectMessage}get inviter(){return this._inviter}get busy(){return this._invite.accepting||this._invite.rejecting}get error(){return this._error?`Something went wrong: ${this._error.message}`:""}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this._invite.avatarColorId)}avatarUrl(e){return Be(this._invite.avatarUrl,e,this.platform,this._mediaRepository)}_createRoomDescription(){const e=[];return this._invite.isPublic?e.push("Public room"):e.push("Private room"),this._invite.canonicalAlias&&e.push(this._invite.canonicalAlias),e.join(" \u2022 ")}get roomDescription(){return this._roomDescription}get avatarTitle(){return this.name}focus(){}async accept(){try{await this._invite.accept()}catch(e){this._error=e,this.emitChange("error")}}async reject(){try{await this._invite.reject()}catch(e){this._error=e,this.emitChange("error")}}_onInviteChange(){this.emitChange()}dispose(){super.dispose(),this._invite.off("change",this._onInviteChange)}}class pp{constructor(e,t,s){this._member=e,this._mediaRepository=t,this._platform=s}get id(){return this._member.userId}get name(){return this._member.name}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this._member.userId)}avatarUrl(e){return Be(this._member.avatarUrl,e,this._platform,this._mediaRepository)}get avatarTitle(){return this.name}}class gp extends L{constructor(e){super(e);const{roomBeingCreated:t,mediaRepository:s}=e;this._roomBeingCreated=t,this._mediaRepository=s,this._onRoomChange=this._onRoomChange.bind(this),this._closeUrl=this.urlRouter.urlUntilSegment("session"),this._roomBeingCreated.on("change",this._onRoomChange)}get kind(){return"roomBeingCreated"}get closeUrl(){return this._closeUrl}get name(){return this._roomBeingCreated.name}get id(){return this._roomBeingCreated.id}get isEncrypted(){return this._roomBeingCreated.isEncrypted}get error(){const{error:e}=this._roomBeingCreated;return e?e.name==="ConnectionError"?this.i18n`You seem to be offline`:e.message:""}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this._roomBeingCreated.avatarColorId)}get avatarTitle(){return this.name}avatarUrl(e){var t;return(t=this._roomBeingCreated.avatarBlobUrl)!=null?t:Be(this._roomBeingCreated.avatarUrl,e,this.platform,this._mediaRepository)}focus(){}_onRoomChange(){this.emitChange()}cancel(){this._roomBeingCreated.cancel(),this.navigation.applyPath(this.navigation.path.until("session"))}dispose(){super.dispose(),this._roomBeingCreated.off("change",this._onRoomChange)}}class fp extends L{constructor(e){super(e),this._eventId=e.eventId,this._unencryptedImageUrl=null,this._decryptedImage=null,this._closeUrl=this.urlRouter.urlUntilSegment("room"),this._date=null,this._subscribeToEvent(e.room,e.eventId)}_subscribeToEvent(e,t){const s=e.observeEvent(t);this.track(s.subscribe(i=>{this._loadEvent(e,i)})),this._loadEvent(e,s.get())}async _loadEvent(e,t){if(!t)return;const{mediaRepository:s}=e;this._eventEntry=t;const{content:i}=this._eventEntry;this._date=this._eventEntry.timestamp?new Date(this._eventEntry.timestamp):null,i.url?(this._unencryptedImageUrl=s.mxcUrl(i.url),this.emitChange("imageUrl")):i.file&&(this._decryptedImage=this.track(await s.downloadEncryptedFile(i.file)),this.emitChange("imageUrl"))}get imageWidth(){var e,t,s;return(s=(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.info)==null?void 0:s.w}get imageHeight(){var e,t,s;return(s=(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.info)==null?void 0:s.h}get name(){var e,t;return(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.body}get sender(){var e;return(e=this._eventEntry)==null?void 0:e.displayName}get imageUrl(){return this._decryptedImage?this._decryptedImage.url:this._unencryptedImageUrl?this._unencryptedImageUrl:""}get date(){return this._date&&this._date.toLocaleDateString({},{weekday:"long",year:"numeric",month:"long",day:"numeric"})}get time(){return this._date&&this._date.toLocaleTimeString({},{hour:"numeric",minute:"2-digit"})}get closeUrl(){return this._closeUrl}close(){this.platform.history.pushUrl(this.closeUrl)}}const ke=oi("Disconnected","Connecting","FirstSync","Sending","Syncing","SyncError");class yp extends L{constructor(e){super(e);const{sync:t,reconnector:s,session:i}=e;this._sync=t,this._reconnector=s,this._status=this._calculateState(s.connectionStatus.get(),t.status.get()),this._session=i,this._setupKeyBackupUrl=this.urlRouter.urlForSegment("settings"),this._dismissSecretStorage=!1}start(){const e=()=>this._updateStatus();this.track(this._sync.status.subscribe(e)),this.track(this._reconnector.connectionStatus.subscribe(e)),this.track(this._session.needsKeyBackup.subscribe(()=>{this.emitChange()}))}get setupKeyBackupUrl(){return this._setupKeyBackupUrl}get isShown(){return this._session.needsKeyBackup.get()&&!this._dismissSecretStorage||this._status!==ke.Syncing}get statusLabel(){switch(this._status){case ke.Disconnected:{const e=Math.round(this._reconnector.retryIn/1e3);return this.i18n`Disconnected, trying to reconnect in ${e}s…`}case ke.Connecting:return this.i18n`Trying to reconnect now…`;case ke.FirstSync:return this.i18n`Catching up with your conversations…`;case ke.SyncError:return this.i18n`Sync failed because of ${this._sync.error}`}return this._session.needsKeyBackup.get()?this.i18n`Set up session backup to decrypt older messages.`:""}get isWaiting(){switch(this._status){case ke.Connecting:case ke.FirstSync:return!0;default:return!1}}_updateStatus(){const e=this._calculateState(this._reconnector.connectionStatus.get(),this._sync.status.get());e!==this._status&&(e===ke.Disconnected?this._retryTimer=this.track(this.clock.createInterval(()=>{this.emitChange("statusLabel")},1e3)):this._retryTimer=this.disposeTracked(this._retryTimer),this._status=e,this.emitChange())}_calculateState(e,t){if(e!==Ys.Online)switch(e){case Ys.Reconnecting:return ke.Connecting;case Ys.Waiting:return ke.Disconnected}else if(t!==te.Syncing)switch(t){case te.InitialSync:case te.CatchupSync:return ke.FirstSync;case te.Stopped:return ke.SyncError}else return ke.Syncing}get isConnectNowShown(){return this._status===ke.Disconnected}get isSecretStorageShown(){return this._status===ke.Syncing&&this._session.needsKeyBackup.get()&&!this._dismissSecretStorage}get canDismiss(){return this.isSecretStorageShown}dismiss(){this.isSecretStorageShown&&(this._dismissSecretStorage=!0,this.emitChange())}connectNow(){this.isConnectNowShown&&this._reconnector.tryNow()}}function Uo(n){return n.map((e,t)=>{if(!n.slice(0,t).includes(e))return e})}class wp extends L{constructor(e){super(e),this._width=e.width,this._height=e.height,this._createRoomViewModelObservable=e.createRoomViewModelObservable,this._selectedIndex=0,this._viewModelsObservables=[],this._setupNavigation()}_setupNavigation(){const e=this.navigation.observe("empty-grid-tile");this.track(e.subscribe(s=>{typeof s=="number"&&this._setFocusIndex(s)})),typeof e.get()=="number"&&(this._selectedIndex=e.get());const t=this.navigation.observe("room");this.track(t.subscribe(s=>{s&&this._setFocusRoom(s)}))}roomViewModelAt(e){var t;return(t=this._viewModelsObservables[e])==null?void 0:t.get()}get focusIndex(){return this._selectedIndex}get width(){return this._width}get height(){return this._height}_switchToRoom(e){let t=this.navigation.path.until("rooms");t=t.with(this.navigation.segment("room",e)),t=mn(this.navigation,t),this.navigation.applyPath(t)}focusTile(e){if(e===this._selectedIndex)return;const t=this._viewModelsObservables[e];t?this._switchToRoom(t.id):this.navigation.push("empty-grid-tile",e)}initializeRoomIdsAndTransferVM(e,t){e=Uo(e);let s=!1;if(t){const r=e.indexOf(t.id);r!==-1&&(this._viewModelsObservables[r]=this.track(t),t.subscribe(o=>this._refreshRoomViewModel(o)),s=!0)}this.setRoomIds(e);const i=this.navigation.path.get("room");if(i){const r=this._viewModelsObservables.findIndex(o=>o&&o.id===i.value);r!==-1&&(this._selectedIndex=r)}return s}setRoomIds(e){e=Uo(e);let t=!1;const s=this._height*this._width;for(let i=0;ithis._refreshRoomViewModel(l)),c.initialize()}t=!0}}return t&&this.emitChange(),t}_refreshRoomViewModel(e){this.emitChange(),e==null||e.focus()}releaseRoomViewModel(e){const t=this._viewModelsObservables.findIndex(s=>s&&s.id===e);if(t!==-1){const s=this._viewModelsObservables[t];return this.untrack(s),s.unsubscribeAll(),this._viewModelsObservables[t]=null,s}}_setFocusIndex(e){var s;if(e===this._selectedIndex||e>=this._width*this._height)return;this._selectedIndex=e;const t=this._viewModelsObservables[this._selectedIndex];(s=t==null?void 0:t.get())==null||s.focus(),this.emitChange("focusIndex")}_setFocusRoom(e){const t=this._viewModelsObservables.findIndex(s=>(s==null?void 0:s.id)===e);t>=0&&this._setFocusIndex(t)}}var st=(n=>(n[n.Enabled=0]="Enabled",n[n.SetupWithPassphrase=1]="SetupWithPassphrase",n[n.SetupWithRecoveryKey=2]="SetupWithRecoveryKey",n[n.Pending=3]="Pending",n[n.NewVersionAvailable=4]="NewVersionAvailable",n))(st||{}),wr=(n=>(n[n.Writing=0]="Writing",n[n.Stopped=1]="Stopped",n[n.Done=2]="Done",n[n.Pending=3]="Pending",n))(wr||{});class vp extends L{constructor(e){super(e),this._error=void 0,this._isBusy=!1,this._dehydratedDeviceId=void 0,this._status=3,this._backupOperationSubscription=void 0,this._keyBackupSubscription=void 0,this._progress=void 0,this._setupKeyType=mt.RecoveryKey;const t=s=>{s&&!this._keyBackupSubscription?this._keyBackupSubscription=this.track(this._session.keyBackup.get().disposableOn("change",()=>{this._onKeyBackupChange()})):!s&&this._keyBackupSubscription&&(this._keyBackupSubscription=this.disposeTracked(this._keyBackupSubscription)),this._onKeyBackupChange()};this.track(this._session.keyBackup.subscribe(t)),this.track(this._session.crossSigning.subscribe(()=>{this.emitChange("crossSigning")})),t(this._keyBackup)}get _session(){return this.getOption("session")}get _keyBackup(){return this._session.keyBackup.get()}get _crossSigning(){return this._session.crossSigning.get()}_onKeyBackupChange(){const e=this._keyBackup;if(e){const{operationInProgress:t}=e;t&&!this._backupOperationSubscription?this._backupOperationSubscription=this.track(t.disposableOn("change",()=>{this._progress=t.progress,this.emitChange("backupPercentage")})):this._backupOperationSubscription&&!t&&(this._backupOperationSubscription=this.disposeTracked(this._backupOperationSubscription),this._progress=void 0)}this.emitChange("status")}get status(){const e=this._keyBackup;if(e)return e.needsNewKey?4:e.version===void 0?3:e.needsNewKey?4:0;switch(this._setupKeyType){case mt.RecoveryKey:return 2;case mt.Passphrase:return 1}}get decryptAction(){return this.i18n`Set up`}get purpose(){return this.i18n`set up key backup`}offerDehydratedDeviceSetup(){return!0}get dehydratedDeviceId(){return this._dehydratedDeviceId}get isBusy(){return this._isBusy}get backupVersion(){var e,t;return(t=(e=this._keyBackup)==null?void 0:e.version)!=null?t:""}get isMasterKeyTrusted(){var e,t;return(t=(e=this._crossSigning)==null?void 0:e.isMasterKeyTrusted)!=null?t:!1}get canSignOwnDevice(){return!!this._crossSigning}async _signOwnDevice(){const e=this._crossSigning;e&&await this.logger.run("KeyBackupViewModel.signOwnDevice",async t=>{await e.signOwnDevice(t)})}navigateToVerification(){this.navigation.push("device-verification",!0)}get backupWriteStatus(){const e=this._keyBackup;return!e||e.version===void 0?3:e.hasStopped?1:e.operationInProgress?0:e.hasBackedUpAllKeys?2:3}get backupError(){var e,t;return(t=(e=this._keyBackup)==null?void 0:e.error)==null?void 0:t.message}get error(){var e;return(e=this._error)==null?void 0:e.message}showPhraseSetup(){this._setupKeyType=mt.Passphrase,this.emitChange("status")}showKeySetup(){this._setupKeyType=mt.RecoveryKey,this.emitChange("status")}async _enterCredentials(e,t,s){if(t)try{this._isBusy=!0,this.emitChange("isBusy");const i=await this._session.enableSecretStorage(e,t);s&&(this._dehydratedDeviceId=await this._session.setupDehydratedDevice(i)),await this._signOwnDevice()}catch(i){console.error(i),this._error=i,this.emitChange("error")}finally{this._isBusy=!1,this.emitChange()}}enterSecurityPhrase(e,t){return this._enterCredentials(mt.Passphrase,e,t)}enterSecurityKey(e,t){return this._enterCredentials(mt.RecoveryKey,e,t)}async disable(){try{this._isBusy=!0,this.emitChange("isBusy"),await this._session.disableSecretStorage()}catch(e){console.error(e),this._error=e,this.emitChange("error")}finally{this._isBusy=!1,this.emitChange()}}get isBackingUp(){var e;return((e=this._keyBackup)==null?void 0:e.operationInProgress)!==void 0}get backupPercentage(){return this._progress?Math.round(this._progress.finished/this._progress.total*100):0}get backupInProgressLabel(){return this._progress?this.i18n`${this._progress.finished} of ${this._progress.total}`:this.i18n`…`}cancelBackup(){var e,t;(t=(e=this._keyBackup)==null?void 0:e.operationInProgress)==null||t.abort()}startBackup(){this.logger.run("KeyBackupViewModel.startBackup",e=>{var t;(t=this._keyBackup)==null||t.flush(e)})}}class bp extends L{constructor(e){super(e),this.featureViewModels=[new Oo(this.childOptions({name:this.i18n`Audio/video calls`,description:this.i18n`Allows starting and participating in A/V calls compatible with Element Call (MSC3401). Look for the start call option in the room menu ((...) in the right corner) to start a call.`,feature:dn.Calls})),new Oo(this.childOptions({name:this.i18n`Cross-Signing`,description:this.i18n`Allows verifying the identity of people you chat with. This feature is still evolving constantly, expect things to break.`,feature:dn.CrossSigning}))]}}class Oo extends L{get enabled(){return this.features.isFeatureEnabled(this.getOption("feature"))}async enableFeature(e){let t;e?t=this.features.withFeature(this.getOption("feature")):t=this.features.withoutFeature(this.getOption("feature")),await t.store(this.platform.settingsStorage),this.platform.restart()}get id(){return`${this.getOption("feature")}`}get name(){return this.getOption("name")}get description(){return this.getOption("description")}}class Sp{constructor(){this.supported=null,this.enabled=!1,this.updating=!1,this.enabledOnServer=null,this.serverError=null}}function kp(n){const t=Math.ceil(n.length/4);let s="";for(let i=0;ithis.maxSentImageSizeLimit||etypeof s.export=="function").export()).asBlob()}get canSendLogsToServer(){return!!this.platform.config.bugReportEndpointUrl}get logsServer(){const{bugReportEndpointUrl:e}=this.platform.config;try{if(e)return new URL(e).hostname}catch{}return""}async sendLogsToServer(){this._logsFeedbackMessage=this.i18n`Sending logs…`;try{await cc(this._session,this.platform),this._logsFeedbackMessage=this.i18n`Logs sent succesfully!`}catch(e){this._logsFeedbackMessage=e.message,this.emitChange()}}get logsFeedbackMessage(){return this._logsFeedbackMessage}async togglePushNotifications(){this.pushNotifications.updating=!0,this.pushNotifications.enabledOnServer=null,this.pushNotifications.serverError=null,this.emitChange("pushNotifications.updating");try{await this._session.enablePushNotifications(!this.pushNotifications.enabled)&&(this.pushNotifications.enabled=!this.pushNotifications.enabled,this.pushNotifications.enabled&&this.platform.notificationService.showNotification(this.i18n`Push notifications are now enabled`))}finally{this.pushNotifications.updating=!1,this.emitChange("pushNotifications.updating")}}async checkPushEnabledOnServer(){this.pushNotifications.enabledOnServer=null,this.pushNotifications.serverError=null;try{this.pushNotifications.enabledOnServer=await this._session.checkPusherEnabledOnHomeserver(),this.emitChange("pushNotifications.enabledOnServer")}catch(e){this.pushNotifications.serverError=e,this.emitChange("pushNotifications.serverError")}}changeThemeOption(e,t){this.platform.themeLoader.setTheme(e,t),this.emitChange("themeOption")}}class Mp extends L{constructor(e){super(e);const{session:t}=e;this._session=t,this._name=void 0,this._topic=void 0,this._roomAlias=void 0,this._isPublic=!1,this._isEncrypted=!0,this._isAdvancedShown=!1,this._isFederationDisabled=!1,this._avatarScaledBlob=void 0,this._avatarFileName=void 0,this._avatarInfo=void 0,this._closeUrl=this.urlRouter.urlUntilSegment("session")}get isPublic(){return this._isPublic}get isEncrypted(){return this._isEncrypted}get canCreate(){return!!this._name}avatarUrl(){return this._avatarScaledBlob.url}get avatarTitle(){return this._name}get avatarLetter(){return""}get avatarColorNumber(){return 0}get hasAvatar(){return!!this._avatarScaledBlob}get isFederationDisabled(){return this._isFederationDisabled}get isAdvancedShown(){return this._isAdvancedShown}get closeUrl(){return this._closeUrl}setName(e){this._name=e,this.emitChange("canCreate")}setRoomAlias(e){this._roomAlias=e}setTopic(e){this._topic=e}setPublic(e){this._isPublic=e,this.emitChange("isPublic")}setEncrypted(e){this._isEncrypted=e,this.emitChange("isEncrypted")}setFederationDisabled(e){this._isFederationDisabled=e,this.emitChange("isFederationDisabled")}toggleAdvancedShown(){this._isAdvancedShown=!this._isAdvancedShown,this.emitChange("isAdvancedShown")}create(){var s,i;let e;this._avatarScaledBlob&&(e={info:this._avatarInfo,name:this._avatarFileName,blob:this._avatarScaledBlob});const t=this._session.createRoom({type:this.isPublic?Le.Public:Le.Private,name:(s=this._name)!=null?s:void 0,topic:(i=this._topic)!=null?i:void 0,isEncrypted:!this.isPublic&&this._isEncrypted,isFederationDisabled:this._isFederationDisabled,alias:this.isPublic?Cp(this._roomAlias):void 0,avatar:e});this.navigation.push("room",t.id)}async selectAvatar(){if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}this._avatarScaledBlob&&this._avatarScaledBlob.dispose(),this._avatarScaledBlob=void 0,this._avatarFileName=void 0,this._avatarInfo=void 0;const e=await this.platform.openFile("image/*");if(!e||!e.blob.mimeType.startsWith("image/")){this.emitChange("hasAvatar");return}let t=await this.platform.loadImage(e.blob);const s=800;if(t.maxDimension>s){const i=await t.scale(s);t.dispose(),t=i}this._avatarScaledBlob=t.blob,this._avatarInfo=Ni(t),this._avatarFileName=e.name,this.emitChange("hasAvatar")}}function Cp(n){n.startsWith("#")&&(n=n.substr(1));const e=n.indexOf(":");return e!==-1&&(n=n.substr(0,e)),n}class Ep extends L{constructor(e){super(e),this._joinInProgress=!1,this._session=e.session,this._closeUrl=this.urlRouter.urlUntilSegment("session")}get closeUrl(){return this._closeUrl}async join(e){this._error=void 0,this._joinInProgress=!0,this.emitChange("joinInProgress");try{const t=await _c(e,this._session);this.navigation.push("room",t)}catch(t){this._error=t,this._joinInProgress=!1,this.emitChange("error")}}get joinInProgress(){return this._joinInProgress}get status(){if(this._error)return this._error.message;if(this._joinInProgress)return"Joining room"}}class Rp extends L{async cancel(){await this.options.sas.abort()}get title(){const e=this.getOption("sas").isCrossSigningAnotherUser?"Waiting for the other user to accept the verification request":"Waiting for any of your device to accept the verification request";return this.i18n`${e}`}get description(){const e=this.getOption("sas").isCrossSigningAnotherUser?"Ask the other user to accept the request from their client!":"Accept the request from the device you wish to verify!";return this.i18n`${e}`}get kind(){return"waiting-for-user"}}class pc extends ot{dismiss(){if(this.getOption("sas").isCrossSigningAnotherUser){const e=this.navigation.path.until("room");this.navigation.applyPath(e)}else this.navigation.push("settings",!0)}}class Tp extends pc{get cancelCode(){return this.options.cancellation.code}get isCancelledByUs(){return this.options.cancellation.cancelledByUs}get kind(){return"verification-cancelled"}get title(){return this.isCancelledByUs?this.i18n`You cancelled the verification!`:this.getOption("sas").isCrossSigningAnotherUser?this.i18n`The other user cancelled the verification!`:this.i18n`The other device cancelled the verification!`}get description(){var c;const e={[A.InvalidMessage]:"Your other device sent an invalid message.",[A.KeyMismatch]:"The key could not be verified.",[A.TimedOut]:"The verification process timed out.",[A.UnexpectedMessage]:"Your other device sent an unexpected message.",[A.UnknownMethod]:"Your other device is using an unknown method for verification.",[A.UnknownTransaction]:"Your other device sent a message with an unknown transaction id.",[A.UserMismatch]:"The expected user did not match the user verified.",[A.MismatchedCommitment]:"The hash commitment does not match.",[A.MismatchedSAS]:"The emoji/decimal did not match."},t={[A.UserCancelled]:"Your other device cancelled the verification!",[A.InvalidMessage]:"Invalid message sent to the other device.",[A.KeyMismatch]:"The other device could not verify our keys",[A.TimedOut]:"The verification process timed out.",[A.UnexpectedMessage]:"Unexpected message sent to the other device.",[A.UnknownMethod]:"Your other device does not understand the method you chose",[A.UnknownTransaction]:"Your other device rejected our message.",[A.UserMismatch]:"The expected user did not match the user verified.",[A.MismatchedCommitment]:"Your other device was not able to verify the hash commitment",[A.MismatchedSAS]:"The emoji/decimal did not match."},s={[A.InvalidMessage]:"The other user sent an invalid message.",[A.KeyMismatch]:"The key could not be verified.",[A.TimedOut]:"The verification process timed out.",[A.UnexpectedMessage]:"The other user sent an unexpected message.",[A.UnknownMethod]:"The other user is using an unknown method for verification.",[A.UnknownTransaction]:"The other user sent a message with an unknown transaction id.",[A.UserMismatch]:"The expected user did not match the user verified.",[A.MismatchedCommitment]:"The hash commitment does not match.",[A.MismatchedSAS]:"The emoji/decimal did not match."},i={[A.UserCancelled]:"The other user cancelled the verification!",[A.InvalidMessage]:"Invalid message sent to the other user.",[A.KeyMismatch]:"The other user could not verify our keys",[A.TimedOut]:"The verification process timed out.",[A.UnexpectedMessage]:"Unexpected message sent to the other user.",[A.UnknownMethod]:"The other user does not understand the method you chose",[A.UnknownTransaction]:"The other user rejected our message.",[A.UserMismatch]:"The expected user did not match the user verified.",[A.MismatchedCommitment]:"The other user was not able to verify the hash commitment",[A.MismatchedSAS]:"The emoji/decimal did not match."};let r;this.getOption("sas").isCrossSigningAnotherUser?r=this.isCancelledByUs?s:i:r=this.isCancelledByUs?e:t;const o=(c=r[this.cancelCode])!=null?c:"";return this.i18n`${o}`}}class Ap extends ot{constructor(){super(...arguments),this.hasProceeded=!1}async proceed(){await this.logAndCatch("SelectMethodViewModel.proceed",async e=>{await this.options.stage.selectEmojiMethod(e),this.hasProceeded=!0,this.emitChange("hasProceeded")})}async cancel(){await this.logAndCatch("SelectMethodViewModel.cancel",async()=>{await this.options.sas.abort()})}get deviceName(){return this.options.stage.otherDeviceName}get otherUserId(){return this.getOption("sas").otherUserId}get kind(){return"select-method"}get isCrossSigningAnotherUser(){return this.getOption("sas").isCrossSigningAnotherUser}}class xp extends ot{constructor(){super(...arguments),this._isWaiting=!1}async setEmojiMatch(e){await this.logAndCatch("VerifyEmojisViewModel.setEmojiMatch",async()=>{await this.options.stage.setEmojiMatch(e),this._isWaiting=!0,this.emitChange("isWaiting")})}get emojis(){return this.options.stage.emoji}get kind(){return"verify-emojis"}get isWaiting(){return this._isWaiting}}class Vp extends pc{get otherDeviceId(){return this.options.deviceId}get otherUsername(){return this.getOption("sas").otherUserId}get kind(){return"verification-completed"}get verificationSuccessfulMessage(){return this.getOption("sas").isCrossSigningAnotherUser?this.i18n`You successfully verified user ${this.otherUsername}`:this.i18n`You successfully verified device ${this.otherDeviceId}`}}class Np extends L{gotoSettings(){this.navigation.push("settings",!0)}get kind(){return"keys-missing"}}const Po=["m.cross_signing.master","m.cross_signing.self_signing","m.cross_signing.user_signing"];class gc extends ot{constructor(e){super(e),this.start(e)}async start(e){var i,r;const t=e.room;let s;s=(r=(i=e.request)!=null?i:e.userId)!=null?r:this.getOption("session").userId,await this.startVerification(s,t)}async startVerification(e,t){await this.logAndCatch("DeviceVerificationViewModel.startVerification",async s=>{const r=await this.getOption("session").crossSigning.waitFor(o=>!!o).promise;if(this.sas=r.startVerification(e,t,s),!this.sas)throw new Error("CrossSigning.startVerification did not return a sas object!");if(!!await this.performPreVerificationChecks(r,e,s))return this.addEventListeners(),typeof e=="string"&&this.updateCurrentStageViewModel(new Rp(this.childOptions({sas:this.sas}))),this.sas.isCrossSigningAnotherUser?r.signUser(this.sas,s):r.signDevice(this.sas,s)})}async performPreVerificationChecks(e,t,s){return await s.wrap("DeviceVerificationViewModel.performPreVerificationChecks",async i=>{const r=await e.areWeVerified(s),c=(typeof t=="string"?t:t.sender)===this.getOption("session").userId;if(this._needsToRequestSecret=c&&!r,this._needsToRequestSecret)return!0;const l=this.getOption("session"),h=Po.map(u=>l.secretFetcher.getSecret(u)),a=await Promise.all(h);for(const u of a)if(!u)return this.updateCurrentStageViewModel(new Np(this.childOptions({}))),!1;return!0})}addEventListeners(){this.track(this.sas.disposableOn("SelectVerificationStage",e=>{this.updateCurrentStageViewModel(new Ap(this.childOptions({sas:this.sas,stage:e})))})),this.track(this.sas.disposableOn("EmojiGenerated",e=>{this.updateCurrentStageViewModel(new xp(this.childOptions({stage:e})))})),this.track(this.sas.disposableOn("VerificationCancelled",e=>{this.updateCurrentStageViewModel(new Tp(this.childOptions({cancellation:e,sas:this.sas})))})),this.track(this.sas.disposableOn("VerificationCompleted",e=>{this.updateCurrentStageViewModel(new Vp(this.childOptions({deviceId:e,sas:this.sas}))),this.requestSecrets()}))}async requestSecrets(){await this.platform.logger.run("DeviceVerificationViewModel.requestSecrets",async e=>{if(this._needsToRequestSecret){const t=this.getOption("session").secretSharing,s=Po.map(c=>t.requestSecret(c,e)),r=(await Promise.all(s)).map(c=>c.waitForResponse());await Promise.all(r),this.getOption("session").crossSigning.get().start(e)}})}updateCurrentStageViewModel(e){this._currentStageViewModel=this.disposeTracked(this._currentStageViewModel),this._currentStageViewModel=this.track(e),this.emitChange("currentStageViewModel")}dispose(){this.sas&&!this.sas.finished&&this.sas.abort().catch(e=>{console.error(e)}),super.dispose()}get currentStageViewModel(){return this._currentStageViewModel}get type(){return"verification"}get isHappeningInRoom(){return!!this.navigation.path.get("room")}}class Fo extends Vt{constructor(e,t){super(null),this._statusSubscription=null,this._sessionViewModel=e,this.id=t}async initialize(){const{session:e}=this._sessionViewModel._client,t=await e.observeRoomStatus(this.id);this.set(await this._statusToViewModel(t.get())),this._statusSubscription=t.subscribe(async s=>{var i;(i=this.get())==null||i.dispose(),this.set(await this._statusToViewModel(s))})}async _statusToViewModel(e){if(e&se.Replaced)if(e&se.BeingCreated){const{session:t}=this._sessionViewModel._client,s=t.roomsBeingCreated.get(this.id);this._sessionViewModel.notifyRoomReplaced(s.id,s.roomId)}else throw new Error("Don't know how to replace a room with this status: "+(e^se.Replaced));else return e&se.BeingCreated?this._sessionViewModel._createRoomBeingCreatedViewModel(this.id):e&se.Invited?this._sessionViewModel._createInviteViewModel(this.id):e&se.Joined?this._sessionViewModel._createRoomViewModelInstance(this.id):e&se.Archived?await this._sessionViewModel._createArchivedRoomViewModel(this.id):this._sessionViewModel._createUnknownRoomViewModel(this.id)}dispose(){var e;this._statusSubscription&&(this._statusSubscription=this._statusSubscription()),this.unsubscribeAll(),(e=this.get())==null||e.dispose()}}class Dp extends L{constructor(e){super(e),this._room=e.room,this._onRoomChange=this._onRoomChange.bind(this),this._room.on("change",this._onRoomChange)}get type(){return"room-details"}get shouldShowBackButton(){return!1}get previousSegmentName(){return!1}get roomId(){return this._room.id}get canonicalAlias(){return this._room.canonicalAlias}get name(){return this._room.name}get isEncrypted(){return!!this._room.isEncrypted}get memberCount(){return this._room.joinedMemberCount}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this._room.avatarColorId)}avatarUrl(e){return Be(this._room.avatarUrl,e,this.platform,this._room.mediaRepository)}get avatarTitle(){return this.name}_onRoomChange(){this.emitChange()}dispose(){super.dispose(),this._room.off("change",this._onRoomChange)}openPanel(e){let t=this.navigation.path.until("room");t=t.with(this.navigation.segment("right-panel",!0)),t=t.with(this.navigation.segment(e,!0)),this.navigation.applyPath(t)}}class Up extends L{constructor(e){super(e),this._member=this._options.member,this._mediaRepository=e.mediaRepository,this._previousName=null,this._nameChanged=!0}get name(){return`${this._member.name}${this._disambiguationPart}`}get _disambiguationPart(){return this._disambiguate?` (${this.userId})`:""}get userId(){return this._member.userId}get previousName(){return this._previousName}get nameChanged(){return this._nameChanged}get detailsUrl(){const e=this.navigation.path.get("room").value;return`${this.urlRouter.openRoomActionUrl(e)}/member/${encodeURIComponent(this._member.userId)}`}_updatePreviousName(e){const t=this._member.name;t!==e?(this._previousName=t,this._nameChanged=!0):this._nameChanged=!1}setDisambiguation(e){this._disambiguate=e,this.emitChange()}updateFrom(e){this._updatePreviousName(e.name),this._member=e}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this.userId)}avatarUrl(e){return Be(this._member.avatarUrl,e,this.platform,this._mediaRepository)}get avatarTitle(){return this.name}}function Op(n){const e=new Intl.Collator,t=s=>s.charAt(0)==="@"?s.slice(1):s;return function(i,r){const o=n.getUserLevel(i.userId),c=n.getUserLevel(r.userId);if(o!==c)return c-o;const l=t(i.name),h=t(r.name);return e.compare(l,h)}}class Pp{constructor(){this._map=new Map}_unDisambiguate(e,t){const s=t.indexOf(e);if(s!==-1){const[i]=t.splice(s,1);i.setDisambiguation(!1)}}_handlePreviousName(e){const t=e.previousName;if(typeof t!="string")return;const s=this._map.get(t);if(Array.isArray(s)){if(this._unDisambiguate(e,s),s.length===1){const i=s[0];i.setDisambiguation(!1),this._map.set(t,i)}}else this._map.delete(t)}_updateMap(e){const t=e.name,s=this._map.get(t);if(s){if(Array.isArray(s))return s.findIndex(i=>i.userId===e.userId)!==-1?void 0:(s.push(e),s);if(e.userId!==s.userId){const i=[s,e];return this._map.set(t,i),i}}else this._map.set(t,e)}disambiguate(e){if(!e.nameChanged)return;this._handlePreviousName(e);const t=this._updateMap(e);t==null||t.forEach(s=>s.setDisambiguation(!0))}}class Fp extends L{constructor(e){super(e);const t=e.members,s=e.powerLevelsObservable;this.track(s.subscribe(()=>{}));const i=s.get();this.memberTileViewModels=this._mapTileViewModels(t.members.filterValues(r=>r.membership==="join")).sortValues(Op(i)),this.nameDisambiguator=new Pp,this.mediaRepository=e.mediaRepository}get type(){return"member-list"}get shouldShowBackButton(){return!0}get previousSegmentName(){return"details"}_mapTileViewModels(e){const t=(i,r)=>{const o=this.mediaRepository,c=new Up(this.childOptions({member:i,emitChange:r,mediaRepository:o}));return this.nameDisambiguator.disambiguate(c),c},s=(i,r,o)=>{r.updateFrom(o),this.nameDisambiguator.disambiguate(r)};return e.mapValues(t,s)}openInvitePanel(){let e=this.navigation.path.until("room");e=e.with(this.navigation.segment("right-panel",!0)),e=e.with(this.navigation.segment("invite",!0)),this.navigation.applyPath(e)}}class Lp extends L{constructor(e){super(e),this._observableMember=e.observableMember,this._mediaRepository=e.mediaRepository,this._member=this._observableMember.get(),this._isEncrypted=e.isEncrypted,this._powerLevelsObservable=e.powerLevelsObservable,this._session=e.session,this.track(this._powerLevelsObservable.subscribe(()=>this._onPowerLevelsChange())),this.track(this._observableMember.subscribe(()=>this._onMemberChange())),this._userTrust=void 0,this._userTrustSubscription=void 0,this.features.crossSigning&&this.track(this._session.crossSigning.subscribe(()=>{this._onCrossSigningChange()})),this._onCrossSigningChange()}get name(){return this._member.name}get userId(){return this._member.userId}get canVerifyUser(){return this._member.userId!==this._session.userId}get trustDescription(){var e;switch((e=this._userTrust)==null?void 0:e.get()){case et.Trusted:return this.i18n`You have verified this user. This user has verified all of their sessions.`;case et.UserNotSigned:return this.i18n`You have not verified this user.`;case et.UserSignatureMismatch:return this.i18n`You appear to have signed this user, but the signature is invalid.`;case et.UserDeviceNotSigned:return this.i18n`You have verified this user, but they have one or more unverified sessions.`;case et.UserDeviceSignatureMismatch:return this.i18n`This user has a session signature that is invalid.`;case et.UserSetupError:return this.i18n`This user hasn't set up cross-signing correctly`;case et.OwnSetupError:return this.i18n`Cross-signing wasn't set up correctly on your side.`;case void 0:default:return this.i18n`Please wait…`}}get trustShieldColor(){var e;if(!this._isEncrypted)return"";switch((e=this._userTrust)==null?void 0:e.get()){case void 0:case et.OwnSetupError:return"";case et.Trusted:return"green";case et.UserNotSigned:return"black";default:return"red"}}get type(){return"member-details"}get shouldShowBackButton(){return!0}get previousSegmentName(){return"members"}get role(){return this.powerLevel>=100?this.i18n`Admin`:this.powerLevel>=50?this.i18n`Moderator`:this.powerLevel===0?this.i18n`Default`:this.i18n`Custom (${this.powerLevel})`}_onMemberChange(){this._member=this._observableMember.get(),this.emitChange("member")}_onPowerLevelsChange(){this.emitChange("role")}async signUser(){const e=this._session.crossSigning.get();e&&await this.logger.run("MemberDetailsViewModel.signUser",async t=>{await e.signUser(this.userId,t)})}async verifyUser(){await this.logger.run("MemberDetailsViewModel.verifyUser",async()=>{const e=this._session.findDirectMessageForUserId(this.userId);let t=e==null?void 0:e.id;t||(t=(await this._session.createRoom({type:Le.DirectMessage,invites:[this.userId]})).roomId),await(await this._session.observeRoomStatus(t)).waitFor(r=>r===se.Joined).promise;let i=this.navigation.path.until("session");i=i.with(this.navigation.segment("room",t)),i=i.with(this.navigation.segment("right-panel",!0)),i=i.with(this.navigation.segment("verification",this.userId)),this.navigation.applyPath(i)})}get avatarLetter(){return Ee(this.name)}get avatarColorNumber(){return Re(this.userId)}avatarUrl(e){return Be(this._member.avatarUrl,e,this.platform,this._mediaRepository)}get avatarTitle(){return this.name}get isEncrypted(){return this._isEncrypted}get powerLevel(){var e;return(e=this._powerLevelsObservable.get())==null?void 0:e.getUserLevel(this._member.userId)}get linkToUser(){return`https://matrix.to/#/${encodeURIComponent(this._member.userId)}`}async openDirectMessage(){const e=this._session.findDirectMessageForUserId(this.userId);let t=e==null?void 0:e.id;t||(t=(await this._session.createRoom({type:Le.DirectMessage,invites:[this.userId]})).id),this.navigation.push("room",t)}_onCrossSigningChange(){const e=this._session.crossSigning.get();this._userTrustSubscription=this.disposeTracked(this._userTrustSubscription),this._userTrust=void 0,e&&this.logger.run("MemberDetailsViewModel.observeUserTrust",t=>{this._userTrust=e.observeUserTrust(this.userId,t),this._userTrustSubscription=this.track(this._userTrust.subscribe(()=>{this.emitChange("trustShieldColor")}))}),this.emitChange("trustShieldColor")}}class Kp extends ot{constructor(e){super(e)}get type(){return"invite"}get shouldShowBackButton(){return!0}get previousSegmentName(){return"members"}get roomName(){return this.getOption("room").name}async invite(e){await this.logAndCatch("InvitePanelViewModel.invite",async()=>{await this.getOption("room").inviteUser(e);const s=this.navigation.path.until("room");this.navigation.applyPath(s)})}}class Bp extends L{constructor(e){super(e),this._room=e.room,this._session=e.session,this._members=null,this._setupNavigation()}get activeViewModel(){return this._activeViewModel}async _getMemberListArguments(){this._members||(this._members=await this._room.loadMemberList(),this.track(()=>this._members.release()));const e=this._room,t=await this._room.observePowerLevels();return{members:this._members,powerLevelsObservable:t,mediaRepository:e.mediaRepository}}async _getMemberDetailsArguments(){const t=this.navigation.path.get("member").value,s=await this._room.observeMember(t);if(!s)return!1;const i=this._room.isEncrypted,r=await this._room.observePowerLevels();return{observableMember:s,isEncrypted:i,powerLevelsObservable:r,mediaRepository:this._room.mediaRepository,session:this._session}}_setupNavigation(){this._hookUpdaterToSegment("details",Dp,()=>({room:this._room})),this._hookUpdaterToSegment("invite",Kp,()=>({room:this._room})),this._hookUpdaterToSegment("members",Fp,()=>this._getMemberListArguments()),this._hookUpdaterToSegment("member",Lp,()=>this._getMemberDetailsArguments(),()=>{const e=`${this.urlRouter.urlUntilSegment("room")}/members`;this.urlRouter.pushUrl(e)}),this._hookUpdaterToSegment("verification",gc,()=>{var s,i;const e={session:this._session,room:this._room},t=this.navigation.path.get("verification").value;if(typeof t=="string"){const r=(i=(s=this._session)==null?void 0:s.crossSigning.get())==null?void 0:i.receivedSASVerifications.get(t);Object.assign(e,r?{request:r}:{userId:t})}return e})}async _hookUpdaterToSegment(e,t,s,i){const r=this.navigation.observe(e),o=await this._setupUpdater(e,t,s,i);this.track(r.subscribe(o))}async _setupUpdater(e,t,s,i){const r=async(o=!1)=>{var l;if(this._activeViewModel instanceof t)return;if(o||(this._activeViewModel=this.disposeTracked(this._activeViewModel)),!!((l=this.navigation.path.get(e))!=null&&l.value)){const h=await s();if(!h&&i){i();return}this._activeViewModel=this.track(new t(this.childOptions(h)))}this.emitChange("activeViewModel")};return await r(!0),r}closePanel(){const e=this.navigation.path.until("room");this.navigation.applyPath(e)}showPreviousPanel(){const e=this.activeViewModel.previousSegmentName;if(e){let t=this.navigation.path.until("room");t=t.with(this.navigation.segment("right-panel",!0)),t=t.with(this.navigation.segment(e,!0)),this.navigation.applyPath(t)}}}class fc extends ot{constructor(e){super(e)}dismiss(){this.getOption("dismiss")()}}class $p extends fc{constructor(e){super(e),this.track(this.call.members.observeSize().subscribe(()=>{this.emitChange("memberCount")})),this.track(this.navigation.observe("room").subscribe(t=>{t===this.call.roomId&&this.dismiss()}))}get kind(){return"calls"}async join(){await this.logAndCatch("CallToastNotificationViewModel.join",async e=>{const t=await this.platform.mediaDevices.getMediaTracks(!1,!0),s=new At().withUserMedia(t);await this.call.join(s,e);const i=this.urlRouter.openRoomActionUrl(this.call.roomId);this.urlRouter.pushUrl(i)})}get call(){return this.getOption("call")}get room(){return this.getOption("room")}get roomName(){return this.room.name}get memberCount(){return this.call.members.size}get avatarLetter(){return Ee(this.roomName)}get avatarColorNumber(){return Re(this.room.avatarColorId)}avatarUrl(e){return Be(this.room.avatarUrl,e,this.platform,this.room.mediaRepository)}get avatarTitle(){return this.roomName}}class jp extends L{constructor(e){super(e),this.toastViewModels=new gn;const t=this.getOption("session");if(this.features.calls){const s=t.callHandler.calls;this.track(s.subscribe(this))}}async onAdd(e,t){if(this._shouldShowNotification(t)){const s=await this._findRoomForCall(t),i=()=>{const r=this.toastViewModels.array.findIndex(o=>o.call===t);r!==-1&&this.toastViewModels.remove(r)};this.toastViewModels.append(new $p(this.childOptions({call:t,room:s,dismiss:i})))}}onRemove(e,t){const s=this.toastViewModels.array.findIndex(i=>i.call===t);s!==-1&&this.toastViewModels.remove(s)}onUpdate(e,t){const s=this.toastViewModels.array.findIndex(i=>i.call===t);s!==-1&&this.toastViewModels.update(s,this.toastViewModels.at(s))}onReset(){for(let e=0;ec===se.Joined).promise,i.get(t)}_shouldShowNotification(e){var s;const t=(s=this.navigation.path.get("room"))==null?void 0:s.value;return!e.isLoadedFromStorage&&e.roomId!==t&&!e.usesFoci}}class qp extends fc{constructor(e){super(e)}get kind(){return"verification"}get request(){return this.getOption("request")}get otherDeviceId(){return this.request.deviceId}accept(){this.navigation.push("device-verification",this.request.id),this.dismiss()}}class Hp extends L{constructor(e){super(e),this.toastViewModels=new gn,this.subscribeToSASRequests()}async subscribeToSASRequests(){await this.getOption("session").crossSigning.waitFor(t=>!!t).promise;const e=this.getOption("session").crossSigning.get();this.track(e.receivedSASVerifications.subscribe(this))}async onAdd(e,t){if(t.sender!==this.getOption("session").userId)return;const s=()=>{const i=this.toastViewModels.array.findIndex(r=>r.request.id===t.id);i!==-1&&this.toastViewModels.remove(i)};this.toastViewModels.append(this.track(new qp(this.childOptions({request:t,dismiss:s}))))}onRemove(e,t){const s=this.toastViewModels.array.findIndex(i=>i.request.id===t.id);s!==-1&&this.toastViewModels.remove(s)}onUpdate(e,t){const s=this.toastViewModels.array.findIndex(i=>i.request.id===t.id);s!==-1&&this.toastViewModels.update(s,this.toastViewModels.at(s))}onReset(){for(let e=0;er.toastViewModels);i.length!==0&&(this.toastViewModels=new ca(...i))}}class zp extends L{constructor(e){super(e);const{client:t}=e;this._client=this.track(t),this._sessionStatusViewModel=this.track(new yp(this.childOptions({sync:t.sync,reconnector:t.reconnector,session:t.session}))),this._leftPanelViewModel=this.track(new f_(this.childOptions({session:this._client.session}))),this._settingsViewModel=null,this._roomViewModelObservable=null,this._gridViewModel=null,this._createRoomViewModel=null,this._joinRoomViewModel=null,this._verificationViewModel=null,this._toastCollectionViewModel=this.track(new Wp(this.childOptions({session:this._client.session}))),this._setupNavigation(),this._setupForcedLogoutOnAccessTokenInvalidation()}_setupNavigation(){const e=this.navigation.observe("rooms");this.track(e.subscribe(l=>{this._updateGrid(l)})),e.get()&&this._updateGrid(e.get());const t=this.navigation.observe("room");this.track(t.subscribe(l=>{this._gridViewModel||this._updateRoom(l),this._updateRightPanel()})),this._gridViewModel||this._updateRoom(t.get());const s=this.navigation.observe("settings");this.track(s.subscribe(l=>{this._updateSettings(l)})),this._updateSettings(s.get());const i=this.navigation.observe("create-room");this.track(i.subscribe(l=>{this._updateCreateRoom(l)})),this._updateCreateRoom(i.get());const r=this.navigation.observe("join-room");if(this.track(r.subscribe(l=>{this._updateJoinRoom(l)})),this._updateJoinRoom(r.get()),this.features.crossSigning){const l=this.navigation.observe("device-verification");this.track(l.subscribe(h=>{this._updateVerification(h)})),this._updateVerification(l.get())}const o=this.navigation.observe("lightbox");this.track(o.subscribe(l=>{this._updateLightbox(l)})),this._updateLightbox(o.get());const c=this.navigation.observe("right-panel");this.track(c.subscribe(()=>this._updateRightPanel())),this._updateRightPanel()}_setupForcedLogoutOnAccessTokenInvalidation(){this.track(this._client.sync.status.subscribe(e=>{if(e===te.Stopped){const t=this._client.sync.error;if((t==null?void 0:t.errcode)==="M_UNKNOWN_TOKEN"){const s=[this.navigation.segment("logout",this.id),this.navigation.segment("forced",!0)],i=this.navigation.pathFrom(s);this.navigation.applyPath(i)}}}))}get id(){return this._client.sessionId}start(){this._sessionStatusViewModel.start(),this.features.calls&&(this._client.session.callHandler.loadCalls("m.ring"),this._client.session.callHandler.loadCalls("m.prompt"))}get activeMiddleViewModel(){var e;return((e=this._roomViewModelObservable)==null?void 0:e.get())||this._gridViewModel||this._settingsViewModel||this._createRoomViewModel||this._joinRoomViewModel||this._verificationViewModel}get roomGridViewModel(){return this._gridViewModel}get leftPanelViewModel(){return this._leftPanelViewModel}get sessionStatusViewModel(){return this._sessionStatusViewModel}get settingsViewModel(){return this._settingsViewModel}get currentRoomViewModel(){var e;return(e=this._roomViewModelObservable)==null?void 0:e.get()}get rightPanelViewModel(){return this._rightPanelViewModel}get createRoomViewModel(){return this._createRoomViewModel}get joinRoomViewModel(){return this._joinRoomViewModel}get verificationViewModel(){return this._verificationViewModel}get toastCollectionViewModel(){return this._toastCollectionViewModel}_updateGrid(e){var i;const t=!(this._gridViewModel&&e),s=this.navigation.path.get("room");if(e)this._gridViewModel?this._gridViewModel.setRoomIds(e):(this._gridViewModel=this.track(new wp(this.childOptions({width:3,height:2,createRoomViewModelObservable:r=>new Fo(this,r)}))),(i=this._roomViewModelObservable)==null||i.unsubscribeAll(),this._gridViewModel.initializeRoomIdsAndTransferVM(e,this._roomViewModelObservable)?this._roomViewModelObservable=this.untrack(this._roomViewModelObservable):this._roomViewModelObservable&&(this._roomViewModelObservable=this.disposeTracked(this._roomViewModelObservable)));else if(this._gridViewModel&&!e){if(s){const r=this._gridViewModel.releaseRoomViewModel(s.value);r&&(this._roomViewModelObservable=this.track(r),this._roomViewModelObservable.subscribe(()=>{this.emitChange("activeMiddleViewModel")}))}this._gridViewModel=this.disposeTracked(this._gridViewModel)}t&&this.emitChange("activeMiddleViewModel")}_createRoomViewModelInstance(e){const t=this._client.session.rooms.get(e);if(t){const s=new Do(this.childOptions({room:t,session:this._client.session}));return s.load(),s}return null}_createUnknownRoomViewModel(e){return new mp(this.childOptions({roomIdOrAlias:e,session:this._client.session}))}async _createArchivedRoomViewModel(e){const t=await this._client.session.loadArchivedRoom(e);if(t){const s=new Do(this.childOptions({room:t,session:this._client.session}));return s.load(),s}return null}_createInviteViewModel(e){const t=this._client.session.invites.get(e);return t?new _p(this.childOptions({invite:t,mediaRepository:this._client.session.mediaRepository})):null}_createRoomBeingCreatedViewModel(e){const t=this._client.session.roomsBeingCreated.get(e);return t?new gp(this.childOptions({roomBeingCreated:t,mediaRepository:this._client.session.mediaRepository})):null}_updateRoom(e){var s;if(((s=this._roomViewModelObservable)==null?void 0:s.id)===e)return;if(this._roomViewModelObservable&&(this._roomViewModelObservable=this.disposeTracked(this._roomViewModelObservable)),!e){this.emitChange("activeMiddleViewModel");return}const t=new Fo(this,e);this._roomViewModelObservable=this.track(t),this._roomViewModelObservable.subscribe(()=>{this.emitChange("activeMiddleViewModel")}),t.initialize()}_updateSettings(e){this._settingsViewModel&&(this._settingsViewModel=this.disposeTracked(this._settingsViewModel)),e&&(this._settingsViewModel=this.track(new Ip(this.childOptions({client:this._client}))),this._settingsViewModel.load()),this.emitChange("activeMiddleViewModel")}_updateCreateRoom(e){this._createRoomViewModel&&(this._createRoomViewModel=this.disposeTracked(this._createRoomViewModel)),e&&(this._createRoomViewModel=this.track(new Mp(this.childOptions({session:this._client.session})))),this.emitChange("activeMiddleViewModel")}_updateJoinRoom(e){this._joinRoomViewModel&&(this._joinRoomViewModel=this.disposeTracked(this._joinRoomViewModel)),e&&(this._joinRoomViewModel=this.track(new Ep(this.childOptions({session:this._client.session})))),this.emitChange("activeMiddleViewModel")}_updateVerification(e){var t;if(this._verificationViewModel&&(this._verificationViewModel=this.disposeTracked(this._verificationViewModel)),e){const s=(t=this._client.session.crossSigning.get())==null?void 0:t.receivedSASVerifications.get(e);this._verificationViewModel=this.track(new gc(this.childOptions({session:this._client.session,request:s})))}this.emitChange("activeMiddleViewModel")}_updateLightbox(e){if(this._lightboxViewModel&&(this._lightboxViewModel=this.disposeTracked(this._lightboxViewModel)),e){const t=this._roomFromNavigation();this._lightboxViewModel=this.track(new fp(this.childOptions({eventId:e,room:t})))}this.emitChange("lightboxViewModel")}get lightboxViewModel(){return this._lightboxViewModel}_roomFromNavigation(){var s;const e=(s=this.navigation.path.get("room"))==null?void 0:s.value;return this._client.session.rooms.get(e)}_updateRightPanel(){var t;if(this._rightPanelViewModel=this.disposeTracked(this._rightPanelViewModel),!!((t=this.navigation.path.get("right-panel"))!=null&&t.value)){const s=this._roomFromNavigation();this._rightPanelViewModel=this.track(new Bp(this.childOptions({room:s,session:this._client.session})))}this.emitChange("rightPanelViewModel")}notifyRoomReplaced(e,t){this.navigation.push("room",t)}}class Gp extends L{constructor(e){super(e),this._accountSetup=e.accountSetup,this._dehydratedDevice=void 0,this._decryptDehydratedDeviceViewModel=void 0,this._accountSetup.encryptedDehydratedDevice&&(this._decryptDehydratedDeviceViewModel=new Yp(this,t=>{this._dehydratedDevice=t,this._decryptDehydratedDeviceViewModel=void 0,this.emitChange("deviceDecrypted")}))}get decryptDehydratedDeviceViewModel(){return this._decryptDehydratedDeviceViewModel}get deviceDecrypted(){return!!this._dehydratedDevice}get dehydratedDeviceId(){return this._accountSetup.encryptedDehydratedDevice.deviceId}finish(){this._accountSetup.finish(this._dehydratedDevice)}}class Yp extends L{constructor(e,t){super(e.options),this._accountSetupViewModel=e,this._isBusy=!1,this._status=st.SetupWithRecoveryKey,this._error=void 0,this._decryptedCallback=t}get decryptAction(){return this.i18n`Restore`}get purpose(){return this.i18n`claim your dehydrated device`}get offerDehydratedDeviceSetup(){return!1}get dehydratedDeviceId(){var e;return(e=this._accountSetupViewModel._dehydratedDevice)==null?void 0:e.deviceId}get isBusy(){return this._isBusy}get backupVersion(){return 0}get status(){return this._status}get error(){var e;return(e=this._error)==null?void 0:e.message}showPhraseSetup(){this._status===st.SetupWithRecoveryKey&&(this._status=st.SetupWithPassphrase,this.emitChange("status"))}showKeySetup(){this._status===st.SetupWithPassphrase&&(this._status=st.SetupWithRecoveryKey,this.emitChange("status"))}async _enterCredentials(e,t){if(t)try{this._isBusy=!0,this.emitChange("isBusy");const{encryptedDehydratedDevice:s}=this._accountSetupViewModel._accountSetup,i=await s.decrypt(e,t);this._decryptedCallback(i)}catch(s){console.error(s),this._error=s,this.emitChange("error")}finally{this._isBusy=!1,this.emitChange("")}}enterSecurityPhrase(e){this._enterCredentials(mt.Passphrase,e)}enterSecurityKey(e){this._enterCredentials(mt.RecoveryKey,e)}disable(){}}class yc extends L{constructor(e){super(e);const{client:t,ready:s,homeserver:i,deleteSessionOnCancel:r}=e;this._client=t,this._ready=s,this._homeserver=i,this._deleteSessionOnCancel=r,this._loading=!1,this._error=null,this.backUrl=this.urlRouter.urlForSegment("session",!0),this._accountSetupViewModel=void 0}async start(){if(!this._loading)try{this._loading=!0,this.emitChange("loading"),this._waitHandle=this._client.loadStatus.waitFor(s=>(s===W.AccountSetup?this._accountSetupViewModel=new Gp(this.childOptions({accountSetup:this._client.accountSetup})):this._accountSetupViewModel=void 0,this.emitChange("loadLabel"),s===W.FirstSync&&this._client.sync.status.get()===te.CatchupSync||s===W.LoginFailed||s===W.Error||s===W.Ready));try{await this._waitHandle.promise}catch{return}const e=this._client.loadStatus.get(),t=this._client.loadError;if(e===W.FirstSync||e===W.Ready){const s=this._client;this._client=null,this._ready(s)}t&&console.error("session load error",t.stack)}catch(e){this._error=e,console.error("error thrown during session load",e.stack)}finally{this._loading=!1,this.emitChange("loading")}}dispose(){this._client&&(this._client.dispose(),this._client=null),this._waitHandle&&(this._waitHandle.dispose(),this._waitHandle=null)}get loading(){const e=this._client;return e&&e.loadStatus.get()===W.AccountSetup?!1:this._loading}get loadLabel(){const e=this._client,t=this._getError();if(t||e&&e.loadStatus.get()===W.Error)return`Something went wrong: ${t&&t.message}.`;if(e)switch(e.loadStatus.get()){case W.QueryAccount:return"Querying account encryption setup\u2026";case W.AccountSetup:return"";case W.SessionSetup:return"Setting up your encryption keys\u2026";case W.Loading:return"Loading your conversations\u2026";case W.FirstSync:return"Getting your conversations from the server\u2026";default:return this._client.loadStatus.get()}return"Preparing\u2026"}_getError(){var e;return this._error||((e=this._client)==null?void 0:e.loadError)}get hasError(){return!!this._getError()}async exportLogs(){const e=await this.logger.export();this.platform.saveFileAs(e.asBlob(),`hydrogen-logs-${this.platform.clock.now()}.json`)}async logout(){await this._client.startLogout(this.navigation.path.get("session").value),this.navigation.push("session",!0)}get accountSetupViewModel(){return this._accountSetupViewModel}}class Jp extends L{constructor(e){super(e),this._isBusy=!1,this._errorMessage="";const{loginOptions:t,attemptLogin:s}=e;this._loginOptions=t,this._attemptLogin=s}get isBusy(){return this._isBusy}get errorMessage(){return this._errorMessage}setBusy(e){this._isBusy=e,this.emitChange("isBusy")}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}async login(e,t){this._errorMessage="",this.emitChange("errorMessage");const s=await this._attemptLogin(this._loginOptions.password(e,t));let i="";switch(s){case Pt.Credentials:i=this.i18n`Your username and/or password don't seem to be correct.`;break;case Pt.Connection:i=this.i18n`Can't connect to ${this._loginOptions.homeserver}.`;break;case Pt.Unknown:i=this.i18n`Something went wrong while checking your login and password.`;break}i&&this._showError(i)}}class Qp extends L{constructor(e){super(e),this._isBusy=!1,this._sso=e.loginOptions.sso,this._isBusy=!1}get isBusy(){return this._isBusy}setBusy(e){this._isBusy=e,this.emitChange("isBusy")}async startSSOLogin(){await this.platform.settingsStorage.setString("sso_ongoing_login_homeserver",this._sso.homeserver);const e=this._sso.createSSORedirectURL(this.urlRouter.createSSOCallbackURL());this.platform.openUrl(e)}}class Xp extends L{constructor(e){super(e),this._errorMessage="";const{loginToken:t,client:s,attemptLogin:i}=e;this._loginToken=t,this._client=s,this._attemptLogin=i,this._errorMessage="",this.performSSOLoginCompletion()}get errorMessage(){return this._errorMessage}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}async performSSOLoginCompletion(){if(!this._loginToken)return;const e=await this.platform.settingsStorage.getString("sso_ongoing_login_homeserver");let t;try{t=await this._client.queryLogin(e).result}catch(r){this._showError(r.message);return}if(!t.token){this.navigation.push("session");return}const s=await this._attemptLogin(t.token(this._loginToken));let i="";switch(s){case Pt.Credentials:i=this.i18n`Your login token is invalid.`;break;case Pt.Connection:i=this.i18n`Can't connect to ${e}.`;break;case Pt.Unknown:i=this.i18n`Something went wrong while checking your login token.`;break}i&&this._showError(i)}}class Zp extends L{constructor(e){super(e),this._hideHomeserver=!1,this._isBusy=!1,this._errorMessage="";const{ready:t,defaultHomeserver:s,loginToken:i}=e;this._ready=t,this._loginToken=i,this._client=new Nr(this.platform,this.features),this._homeserver=s,this._initViewModels()}get passwordLoginViewModel(){return this._passwordLoginViewModel}get startSSOLoginViewModel(){return this._startSSOLoginViewModel}get completeSSOLoginViewModel(){return this._completeSSOLoginViewModel}get homeserver(){return this._homeserver}get resolvedHomeserver(){var e;return(e=this._loginOptions)==null?void 0:e.homeserver}get errorMessage(){return this._errorMessage}get showHomeserver(){return!this._hideHomeserver}get loadViewModel(){return this._loadViewModel}get isBusy(){return this._isBusy}get isFetchingLoginOptions(){return!!this._abortQueryOperation}goBack(){this.navigation.push("session")}_initViewModels(){this._loginToken?(this._hideHomeserver=!0,this._completeSSOLoginViewModel=this.track(new Xp(this.childOptions({client:this._client,attemptLogin:e=>this.attemptLogin(e),loginToken:this._loginToken}))),this.emitChange("completeSSOLoginViewModel")):this.queryHomeserver()}_showPasswordLogin(){this._passwordLoginViewModel=this.track(new Jp(this.childOptions({loginOptions:this._loginOptions,attemptLogin:e=>this.attemptLogin(e)}))),this.emitChange("passwordLoginViewModel")}_showSSOLogin(){this._startSSOLoginViewModel=this.track(new Qp(this.childOptions({loginOptions:this._loginOptions}))),this.emitChange("startSSOLoginViewModel")}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}_setBusy(e){var t,s;this._isBusy=e,(t=this._passwordLoginViewModel)==null||t.setBusy(e),(s=this._startSSOLoginViewModel)==null||s.setBusy(e),this.emitChange("isBusy")}async attemptLogin(e){this._setBusy(!0),this._client.startWithLogin(e,{inspectAccountSetup:!0});const t=this._client.loadStatus;return await t.waitFor(r=>r!==W.Login).promise,this._setBusy(!1),t.get()===W.LoginFailed?this._client.loginFailure:(this._hideHomeserver=!0,this.emitChange("hideHomeserver"),this._disposeViewModels(),this._createLoadViewModel(),null)}_createLoadViewModel(){this._loadViewModelSubscription=this.disposeTracked(this._loadViewModelSubscription),this._loadViewModel=this.disposeTracked(this._loadViewModel),this._loadViewModel=this.track(new yc(this.childOptions({ready:e=>{this._client=null,this._ready(e)},client:this._client,homeserver:this._homeserver}))),this._loadViewModel.start(),this.emitChange("loadViewModel"),this._loadViewModelSubscription=this.track(this._loadViewModel.disposableOn("change",()=>{this._loadViewModel.loading||(this._loadViewModelSubscription=this.disposeTracked(this._loadViewModelSubscription)),this._setBusy(!1)}))}_disposeViewModels(){this._startSSOLoginViewModel=this.disposeTracked(this._startSSOLoginViewModel),this._passwordLoginViewModel=this.disposeTracked(this._passwordLoginViewModel),this._completeSSOLoginViewModel=this.disposeTracked(this._completeSSOLoginViewModel),this.emitChange("disposeViewModels")}async setHomeserver(e){this._homeserver=e,this._loginOptions=void 0,this._queriedHomeserver=void 0,this._showError(""),this._disposeViewModels(),this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation),this.emitChange("loginViewModels"),this.disposeTracked(this._abortHomeserverQueryTimeout);const t=this.clock.createTimeout(1e3);this._abortHomeserverQueryTimeout=this.track(()=>t.abort());try{await t.elapsed()}catch(s){if(s.name==="AbortError")return;throw s}this._abortHomeserverQueryTimeout=this.disposeTracked(this._abortHomeserverQueryTimeout),this.queryHomeserver()}async queryHomeserver(){if(!(this._homeserver===this._queriedHomeserver||this._homeserver==="")){this._queriedHomeserver=this._homeserver,this._abortHomeserverQueryTimeout=this.disposeTracked(this._abortHomeserverQueryTimeout),this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation);try{const e=this._client.queryLogin(this._homeserver);this._abortQueryOperation=this.track(()=>e.abort()),this.emitChange("isFetchingLoginOptions"),this._loginOptions=await e.result,this.emitChange("resolvedHomeserver")}catch(e){if(e.name==="AbortError")return;this._loginOptions=void 0}finally{this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation),this.emitChange("isFetchingLoginOptions")}this._loginOptions?(this._loginOptions.sso&&this._showSSOLogin(),this._loginOptions.password&&this._showPasswordLogin(),!this._loginOptions.sso&&!this._loginOptions.password&&this._showError("This homeserver supports neither SSO nor password based login flows")):this._showError(`Could not query login methods supported by ${this.homeserver}`)}}dispose(){super.dispose(),this._client&&this._client.deleteSession()}}class eg extends L{constructor(e){super(e),this._sessionId=e.sessionId,this._busy=!1,this._showConfirm=!0,this._error=void 0}get showConfirm(){return this._showConfirm}get busy(){return this._busy}get cancelUrl(){return this.urlRouter.urlForSegment("session",!0)}async logout(){this._busy=!0,this._showConfirm=!1,this.emitChange("busy");try{await new Nr(this.platform).startLogout(this._sessionId),this.navigation.push("session",!0)}catch(e){this._error=e,this._busy=!1,this.emitChange("busy")}}get status(){return this._error?this.i18n`Could not log out of device: ${this._error.message}`:this.i18n`Logging out… Please don't close the app.`}}class tg extends L{constructor(e){super(e),this._showStatus=!1,this._showSpinner=!1,this._sessionId=e.sessionId,this._logoutPromise=this.forceLogout()}async forceLogout(){try{await new Nr(this.platform).startForcedLogout(this._sessionId)}catch(e){this._error=e,this._showSpinner=!1,this._showStatus=!0,this.emitChange("error")}}async proceed(){this._showSpinner=!0,this._showStatus=!0,this.emitChange("showStatus"),await this._logoutPromise,this._error||this.navigation.push("login",!0)}get status(){return this._error?this.i18n`Could not log out of device: ${this._error.message}`:this.i18n`Logging out… Please don't close the app.`}get showStatus(){return this._showStatus}get showSpinner(){return this._showSpinner}}class sg extends L{constructor(e,t){super(e),this._pickerVM=t,this._sessionInfo=e.sessionInfo,this._isDeleting=!1,this._isClearing=!1,this._error=null,this._exportDataUrl=null}get error(){return this._error&&this._error.message}get id(){return this._sessionInfo.id}get openUrl(){return this.urlRouter.urlForSegment("session",this.id)}get label(){const{userId:e,comment:t}=this._sessionInfo;return t?`${e} (${t})`:e}get sessionInfo(){return this._sessionInfo}get exportDataUrl(){return this._exportDataUrl}get avatarColorNumber(){return Re(this._sessionInfo.userId)}get avatarInitials(){return Ee(this._sessionInfo.userId)}}class ig extends L{constructor(e){super(e),this._sessions=new fn((t,s)=>t.id.localeCompare(s.id)),this._loadViewModel=null,this._error=null}async load(){const e=await this.platform.sessionInfoStorage.getAll();this._sessions.setManyUnsorted(e.map(t=>new sg(this.childOptions({sessionInfo:t}),this)))}get loadViewModel(){return this._loadViewModel}get sessions(){return this._sessions}get cancelUrl(){return this.urlRouter.urlForSegment("login")}}class rg extends L{constructor(e){super(e),this._error=null,this._sessionPickerViewModel=null,this._sessionLoadViewModel=null,this._loginViewModel=null,this._logoutViewModel=null,this._forcedLogoutViewModel=null,this._sessionViewModel=null,this._pendingClient=null}async load(){this.track(this.navigation.observe("login").subscribe(()=>this._applyNavigation())),this.track(this.navigation.observe("session").subscribe(()=>this._applyNavigation())),this.track(this.navigation.observe("sso").subscribe(()=>this._applyNavigation())),this.track(this.navigation.observe("logout").subscribe(()=>this._applyNavigation())),this._applyNavigation(!0)}async _applyNavigation(e){var c,l,h,a;const t=this.navigation.path.get("login"),s=(c=this.navigation.path.get("logout"))==null?void 0:c.value,i=(l=this.navigation.path.get("forced"))==null?void 0:l.value,r=(h=this.navigation.path.get("session"))==null?void 0:h.value,o=(a=this.navigation.path.get("sso"))==null?void 0:a.value;if(t)this.activeSection!=="login"&&this._showLogin();else if(s&&i)this.activeSection!=="forced-logout"&&this._showForcedLogout(s);else if(s)this.activeSection!=="logout"&&this._showLogout(s);else if(r===!0)this.activeSection!=="picker"&&this._showPicker();else if(r){if(!this._sessionViewModel||this._sessionViewModel.id!==r)if(this._pendingClient&&this._pendingClient.sessionId===r){const u=this._pendingClient;this._pendingClient=null,this._showSession(u)}else this._pendingClient&&(this._pendingClient.dispose(),this._pendingClient=null),this._showSessionLoader(r)}else if(o)this.urlRouter.normalizeUrl(),this.activeSection!=="login"&&this._showLogin(o);else try{if(!(e&&this.urlRouter.tryRestoreLastUrl())){const u=await this.platform.sessionInfoStorage.getAll();u.length===0?this.navigation.push("login"):u.length===1?this.navigation.push("session",u[0].id):this.navigation.push("session")}}catch(u){this._setSection(()=>this._error=u)}}async _showPicker(){this._setSection(()=>{this._sessionPickerViewModel=new ig(this.childOptions())});try{await this._sessionPickerViewModel.load()}catch(e){this._setSection(()=>this._error=e)}}_showLogin(e){this._setSection(()=>{this._loginViewModel=new Zp(this.childOptions({defaultHomeserver:this.platform.config.defaultHomeServer,ready:t=>{this._pendingClient=t,this.navigation.push("session",t.sessionId)},loginToken:e}))})}_showLogout(e){this._setSection(()=>{this._logoutViewModel=new eg(this.childOptions({sessionId:e}))})}_showForcedLogout(e){this._setSection(()=>{this._forcedLogoutViewModel=new tg(this.childOptions({sessionId:e}))})}_showSession(e){this._setSection(()=>{this._sessionViewModel=new zp(this.childOptions({client:e})),this._sessionViewModel.start()})}_showSessionLoader(e){const t=new Nr(this.platform,this.features);t.startWithExistingSession(e),this._setSection(()=>{this._sessionLoadViewModel=new yc(this.childOptions({client:t,ready:s=>this._showSession(s)})),this._sessionLoadViewModel.start()})}get activeSection(){return this._error?"error":this._sessionViewModel?"session":this._loginViewModel?"login":this._logoutViewModel?"logout":this._forcedLogoutViewModel?"forced-logout":this._sessionPickerViewModel?"picker":this._sessionLoadViewModel?"loading":"redirecting"}_setSection(e){this._error=null,this._sessionPickerViewModel=this.disposeTracked(this._sessionPickerViewModel),this._sessionLoadViewModel=this.disposeTracked(this._sessionLoadViewModel),this._loginViewModel=this.disposeTracked(this._loginViewModel),this._logoutViewModel=this.disposeTracked(this._logoutViewModel),this._forcedLogoutViewModel=this.disposeTracked(this._forcedLogoutViewModel),this._sessionViewModel=this.disposeTracked(this._sessionViewModel),e(),this._sessionPickerViewModel&&this.track(this._sessionPickerViewModel),this._sessionLoadViewModel&&this.track(this._sessionLoadViewModel),this._loginViewModel&&this.track(this._loginViewModel),this._logoutViewModel&&this.track(this._logoutViewModel),this._forcedLogoutViewModel&&this.track(this._forcedLogoutViewModel),this._sessionViewModel&&this.track(this._sessionViewModel),this.emitChange("activeSection")}get error(){return this._error}get sessionViewModel(){return this._sessionViewModel}get loginViewModel(){return this._loginViewModel}get logoutViewModel(){return this._logoutViewModel}get forcedLogoutViewModel(){return this._forcedLogoutViewModel}get sessionPickerViewModel(){return this._sessionPickerViewModel}get sessionLoadViewModel(){return this._sessionLoadViewModel}}async function ng(n){try{await n.init();const e=await Xs.load(n.settingsStorage),t=h_();n.setNavigation(t);const s=d_({navigation:t,history:n.history});s.attach();const i=new rg({platform:n,urlRouter:s,navigation:t,features:e});await i.load(),n.createAndMountRootView(i)}catch(e){console.error(`${e.message}: ${e.stack}`)}}function og(n,e,t,s){const i=n(e);let r=!1;return i.elapsed().then(()=>{r=!0,t.abort()},()=>{}),s.then(o=>(i.abort(),o),o=>{throw i.abort(),o.name==="AbortError"&&r?new Ut(`Request timed out after ${e}ms`,!0):o})}function wc(n,e=Math.random){return n.includes("?")?n=n+"&":n=n+"?",n+`_cacheBuster=${Math.ceil(e()*Number.MAX_SAFE_INTEGER)}`}function vc(n){var t;const e=new FormData;for(const[s,i]of n)((t=i.blob)==null?void 0:t.nativeBlob)&&i.name?e.set(s,i.blob.nativeBlob,i.name):e.set(s,i);return e}class ag{constructor(e,t){this._promise=e,this._xhr=t}abort(){this._xhr.abort()}response(){return this._promise}}function cg(n,{method:e,headers:t,timeout:s,format:i,uploadProgress:r}){const o=new XMLHttpRequest;if(r&&o.upload.addEventListener("progress",c=>r(c.loaded)),o.open(e,n),i==="buffer"&&(o.responseType="arraybuffer"),t)for(const[c,l]of t.entries())try{o.setRequestHeader(c,l)}catch(h){console.info(`Could not set ${c} header: ${h.message}`)}return s&&(o.timeout=s),o}function lg(n,e,t){return new Promise((s,i)=>{n.addEventListener("load",()=>s(n)),n.addEventListener("abort",()=>i(new rt)),n.addEventListener("error",()=>i(new Ut(`Error ${e} ${t}`))),n.addEventListener("timeout",()=>i(new Ut(`Timeout ${e} ${t}`,!0)))})}function bc(n,e){let{cache:t,format:s,body:i,method:r}=e;t||(n=wc(n));const o=cg(n,e),c=lg(o,r,n).then(l=>{const{status:h}=l;let a=null;return s==="buffer"?a=l.response:l.getResponseHeader("Content-Type")==="application/json"&&(a=JSON.parse(l.responseText)),{status:h,body:a}});return i!=null&&i.nativeBlob&&(i=i.nativeBlob),i instanceof Map&&(i=vc(i)),o.send(i||null),new ag(c,o)}class Lo{constructor(e,t){if(t)this.promise=e,this._controller=t;else{const s=new Promise((i,r)=>{this._controller={abort(){const o=new Error("fetch request aborted");o.name="AbortError",r(o)}}});this.promise=Promise.race([e,s])}}abort(){this._controller.abort()}response(){return this.promise}}function hg(n,e){return function(s,i){if(e!=null&&e.haltRequests)return new Lo(new Promise(()=>{}),{});if(i!=null&&i.uploadProgress)return bc(s,i);let{method:r,headers:o,body:c,timeout:l,format:h,cache:a=!1}=i;const u=typeof AbortController=="function"?new AbortController:null;c!=null&&c.nativeBlob&&(c=c.nativeBlob),c instanceof Map&&(c=vc(c));let p={method:r,body:c};if(u&&(p=Object.assign(p,{signal:u.signal})),a||(s=wc(s)),p=Object.assign(p,{mode:"cors",credentials:"omit",referrer:"no-referrer",cache:"default"}),o){const v=new Headers;for(const[M,R]of o.entries())v.append(M,R);p.headers=v}const g=fetch(s,p).then(async v=>{const{status:M}=v;let R;try{h==="json"?R=await v.json():h==="buffer"?R=await v.arrayBuffer():h==="text"&&(R=await v.text())}catch(N){if(!(N.name==="SyntaxError"&&M>=400))throw N}return{status:M,body:R}},v=>{throw v.name==="AbortError"?new rt:v instanceof TypeError?new Ut(`${r} ${s}: ${v.message}`):v}),f=new Lo(g,u);return l&&(f.promise=og(n,l,f,f.promise)),f}}class dg{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 updateAccessToken(e,t){const s=await this.getAll(),i=s.find(r=>r.id===e);if(!i)throw Error("No session found");i.accessToken=t,localStorage.setItem(this._name,JSON.stringify(s))}async updateLastUsed(e,t){const s=await this.getAll(),i=s.find(r=>r.id===e);i&&(i.lastUsed=t,localStorage.setItem(this._name,JSON.stringify(s)))}async get(e){const t=await this.getAll();if(t)return t.find(s=>s.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(s=>s.id!==e),localStorage.setItem(this._name,JSON.stringify(t))}}class ug{constructor(e){this._prefix=e}async setInt(e,t){this._set(e,t)}async getInt(e,t=0){const s=window.localStorage.getItem(`${this._prefix}${e}`);return typeof s=="string"?parseInt(s,10):t}async setBool(e,t){this._set(e,t)}async getBool(e,t=!1){const s=window.localStorage.getItem(`${this._prefix}${e}`);return typeof s=="string"?s==="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 mg{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)}}var Ms={};(function(){for(var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Uint8Array(256),t=0;t>2],c+=n[(i[r]&3)<<4|i[r+1]>>4],c+=n[(i[r+1]&15)<<2|i[r+2]>>6],c+=n[i[r+2]&63];return o%3===2?c=c.substring(0,c.length-1)+"=":o%3===1&&(c=c.substring(0,c.length-2)+"=="),c},Ms.decode=function(s){var i=s.length*.75,r=s.length,o,c=0,l,h,a,u;s[s.length-1]==="="&&(i--,s[s.length-2]==="="&&i--);var p=new ArrayBuffer(i),g=new Uint8Array(p);for(o=0;o>4,g[c++]=(h&15)<<4|a>>2,g[c++]=(a&3)<<6|u&63;return p}})();class _g{encodeUnpadded(e){const t=Ms.encode(e),s=t.indexOf("=");return s!==-1?t.substr(0,s):t}encode(e){return Ms.encode(e)}decode(e){return Ms.decode(e)}}var Sc={isBuffer:function(n){return n instanceof Uint8Array},from:function(n){return n},allocUnsafe:function(n){return Sc.alloc(n)},alloc:function(n){return new Uint8Array(n)}},pg=Object.freeze(Object.defineProperty({__proto__:null,Buffer:Sc},Symbol.toStringTag,{value:"Module"})),gg=_a(pg),dr=gg.Buffer;function fg(n){if(n.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t>>0,F=new Uint8Array(N);M!==R;){for(var T=g[M],D=0,B=N-1;(T!==0||D>>0,F[B]=T%o>>>0,T=T/o>>>0;if(T!==0)throw new Error("Non-zero carry");v=D,M++}for(var G=N-v;G!==N&&F[G]===0;)G++;for(var $e=c.repeat(f);G>>0,N=new Uint8Array(R);g[f];){var F=e[g.charCodeAt(f)];if(F===255)return;for(var T=0,D=R-1;(F!==0||T>>0,N[D]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");M=T,f++}if(g[f]!==" "){for(var B=R-M;B!==R&&N[B]===0;)B++;var G=dr.allocUnsafe(v+(R-B));G.fill(0,0,v);for(var $e=v;B!==R;)G[$e++]=N[B++];return G}}}function p(g){var f=u(g);if(f)return f;throw new Error("Non-base"+o+" character")}return{encode:a,decodeUnsafe:u,decode:p}}var yg=fg,wg=yg,vg="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ko=wg(vg);class bg{encode(e){return Ko.encode(e)}decode(e){return Ko.decode(e)}}class Sg{constructor(){this.utf8=new mg,this.base64=new _g,this.base58=new bg}}class kg{constructor(e){this._workerPool=e}megolmDecrypt(e,t){const s=e.export_session(e.first_known_index());return this._workerPool.send({type:"megolm_decrypt",ciphertext:t,sessionKey:s})}async createAccountAndOTKs(e,t){let s;window.msCrypto&&(s=[window.msCrypto.getRandomValues(new Uint8Array(64)),window.msCrypto.getRandomValues(new Uint8Array(t*32))]);const i=await this._workerPool.send({type:"olm_create_account_otks",randomValues:s,otkAmount:t}).response();e.unpickle("",i)}async createOutboundOlmSession(e,t,s,i){const r=e.pickle("");let o;window.msCrypto&&(o=[window.msCrypto.getRandomValues(new Uint8Array(64))]);const c=await this._workerPool.send({type:"olm_create_outbound",accountPickle:r,theirIdentityKey:s,theirOneTimeKey:i,randomValues:o}).response();t.unpickle("",c)}dispose(){this._workerPool.dispose()}}class Ig{constructor(e){var t;this.options=e,this._queuedItems=this._loadQueuedItems(),window.addEventListener("pagehide",this,!1),this._flushInterval=this.options.platform.clock.createInterval(()=>this._tryFlush(),(t=this.options.flushInterval)!=null?t:60*1e3)}setLogger(e){this.logger=e}reportItem(e,t,s){const i=this.prepareItemForQueue(e,t,s);i&&this._queuedItems.push(i)}async export(){const e=await this._openDB();try{const s=e.transaction(["logs"],"readonly").objectStore("logs"),i=await vh(s.openCursor(),()=>!1),r=this.getSerializedOpenItems(),o=i.concat(this._queuedItems).concat(r);return new Mg(o,this,this.options.platform)}finally{try{e.close()}catch{}}}dispose(){window.removeEventListener("pagehide",this,!1),this._flushInterval.dispose()}handleEvent(e){e.type==="pagehide"&&this._finishAllAndFlush()}async _tryFlush(){var t;const e=await this._openDB();try{const s=e.transaction(["logs"],"readwrite"),i=s.objectStore("logs"),r=this._queuedItems.length;for(const l of this._queuedItems)i.add(l);const o=await Me(i.count()),c=(t=this.options.limit)!=null?t:3e3;if(o>c){let l=o-c+Math.round(.1*c);await _e(i.openCursor(),(h,a,u)=>(u.delete(),l-=1,{done:l===0}))}await Pi(s),this._queuedItems.splice(0,r)}catch(s){console.error("Could not flush logs",s)}finally{try{e.close()}catch{}}}_finishAllAndFlush(){this.logger&&(this.logger.log({l:"pagehide, closing logs",t:"navigation"}),this.logger.forceFinish()),this._persistQueuedItems(this._queuedItems)}_loadQueuedItems(){const e=`${this.options.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 In(this.options.name,e=>e.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),1)}prepareItemForQueue(e,t,s){let i=e.serialize(t,void 0,s);if(i)return this.options.serializedTransformer&&(i=this.options.serializedTransformer(i)),{json:JSON.stringify(i)}}_persistQueuedItems(e){try{window.localStorage.setItem(`${this.options.name}_queuedItems`,JSON.stringify(e))}catch(t){console.error("Could not persist queued log items in localStorage, they will likely be lost",t)}}async removeItems(e){const t=await this._openDB();try{const s=t.transaction(["logs"],"readwrite"),i=s.objectStore("logs");for(const r of e)if(typeof r.id=="number")i.delete(r.id);else{const o=this._queuedItems.indexOf(r);o===-1&&this._queuedItems.splice(o,1)}await Pi(s)}finally{try{t.close()}catch{}}}getSerializedOpenItems(){const e=[];if(!this.logger)return e;const t=new br;for(const s of this.logger.getOpenRootItems()){const i=this.prepareItemForQueue(s,t,!1);i&&e.push(i)}return e}}class Mg{constructor(e,t,s){this._items=e,this._logger=t,this._platform=s}get count(){return this._items.length}removeFromStore(){return this._logger.removeItems(this._items)}asBlob(){const e=this.toJSON(),t=this._platform.encoding.utf8.encode(e);return this._platform.createBlob(t,"application/json")}toJSON(){var s;const e={formatVersion:1,appVersion:(s=this._platform.updateService)==null?void 0:s.version,platform:this._platform.description,items:this._items.map(i=>JSON.parse(i.json))};return JSON.stringify(e)}}class Cg{reportItem(e){Ic(e)}setLogger(e){this.logger=e}printOpenItems(){if(!!this.logger)for(const e of this.logger.getOpenRootItems())this.reportItem(e)}}const Eg=["l","id"];function Rg(n){return Object.entries(n).filter(([e])=>!Eg.includes(e)).reduce((e,[t,s])=>(e=e||{},e[t]=s,e),null)}function kc(n){if(n.error)return!0;if(n.children){for(const e of n.children)if(kc(e))return!0}return!1}function Ic(n){const e=`${Tg(n)} (@${n.start}ms, duration: ${n.duration}ms)`,t=Rg(n.values),s=n.children||t;if(s?(kc(n)?console.group(e):console.groupCollapsed(e),n.error&&console.error(n.error)):n.error?console.error(n.error):console.log(e),t&&console.table(t),n.children)for(const i of n.children)Ic(i);s&&console.groupEnd()}function Tg(n){return n.values.t==="network"?`${n.values.method} ${n.values.url}`:n.values.l&&typeof n.values.id!="undefined"?`${n.values.l} ${n.values.id}`:n.values.l&&typeof n.values.status!="undefined"?`${n.values.l} (${n.values.status})`:n.values.l&&typeof n.values.type!="undefined"?`${n.values.l} (${n.values.type})`:n.values.l&&n.error?`${n.values.l} failed`:typeof n.values.ref!="undefined"?`ref ${n.values.ref}`:n.values.l||n.values.type}class Zs{constructor(e,t,s,i){this._discard=!1,this._logger=s,this.start=s._now(),this._values=typeof e=="string"?{l:e}:e,this.logLevel=t,this._filterCreator=i}discard(){this._discard=!0}runDetached(e,t,s,i){return this._logger.runDetached(e,t,s,i)}wrapDetached(e,t,s,i){this.refDetached(this.runDetached(e,t,s,i))}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,s,i){return this.child(e,s,i).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,s)=>{const i=s.durationOfType(e);return t+(i!=null?i:0)},0):0}log(e,t){const s=this.child(e,t);return s.end=s.start,s}set(e,t){if(typeof e=="object"){const s=e;Object.assign(this._values,s)}else this._values[e]=t;return this}serialize(e,t,s){if(this._discard)return;if(this._filterCreator)try{e=this._filterCreator(new br(e),this)}catch(o){console.error("Error creating log filter",o)}let i=null;if(this._children&&(i=this._children.reduce((o,c)=>{const l=c.serialize(e,this.start,!1);return l&&(o===null&&(o=[]),o.push(l)),o},null)),e&&!e.filter(this,i))return;const r={s:typeof t=="number"?this.start-t:this.start,d:this.duration,v:this._values,l:this.logLevel};return this.error&&(r.e={stack:this.error.stack,name:this.error.name,message:this.error.message.split(` `)[0]}),s&&(r.f=!0),i&&(r.c=i),r}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(s=>(this.finish(),s),s=>{throw this.catch(s)}):(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()}}forceFinish(){this.finish()}get level(){return Ge}catch(e){return this.error=e,this.logLevel=Ge.Error,this.finish(),e}child(e,t,s){this.end&&console.trace(`log item ${this.values.l} finished, additional log ${JSON.stringify(e)} will likely not be recorded`),t||(t=this.logLevel||Ge.Info);const i=new Zs(e,t,this._logger,s);return this._children||(this._children=[]),this._children.push(i),i}get logger(){return this._logger}get values(){return this._values}get children(){return this._children}}class Ag{constructor({platform:e}){this._openItems=new Set,this.reporters=[],this._platform=e}log(e,t=Ge.Info){const s=new Zs(e,t,this);return s.end=s.start,this._persistItem(s,void 0,!1),s}child(e,t=Ge.Info,s){const i=new xg(e,t,this,s);return this._openItems.add(i),i}wrapOrRun(e,t,s,i,r){return e?e.wrap(t,s,i,r):this.run(t,s,i,r)}runDetached(e,t,s,i){s||(s=Ge.Info);const r=new Zs(e,s,this);return this._run(r,t,s,!1,i),r}run(e,t,s,i){s===void 0&&(s=Ge.Info);const r=new Zs(e,s,this);return this._run(r,t,s,!0,i)}_run(e,t,s,i,r){this._openItems.add(e);const o=()=>{let c=new br;if(r)try{c=r(c,e)}catch(l){console.error("Error while creating log filter",l)}else c=c.minLevel(s);try{this._persistItem(e,c,!1)}catch(l){console.error("Could not persist log item",l)}this._openItems.delete(e)};try{let c=e.run(t);if(c instanceof Promise){if(c=c.then(l=>(o(),l),l=>{if(o(),i)throw l}),i)return c}else if(o(),i)return c}catch(c){if(o(),i)throw c}}addReporter(e){e.setLogger(this),this.reporters.push(e)}getOpenRootItems(){return this._openItems}forceFinish(){for(const e of this._openItems){e.forceFinish();try{this._persistItem(e,new br,!0)}catch(t){console.error("Could not serialize log item",t)}}this._openItems.clear()}_removeItemFromOpenList(e){this._openItems.delete(e)}_persistItem(e,t,s){for(var i=0;i(typeof i=="function"&&(i=i(e)),i?t+(t.length?" ":"")+s:t),"")}function ei(n,e,t){e==="className"&&(e="class"),t===!1?n.removeAttribute(e):(t===!0&&(t=e),n.setAttribute(e,t))}function Vg(n,e,t){return Cc(Ln,n,e,t)}function Cc(n,e,t,s){t&&Mc(t)&&(s=t,t=void 0);const i=document.createElementNS(n,e);if(t)for(let[r,o]of Object.entries(t))typeof o=="object"&&(o=o!==null&&r==="className"?ri(o,void 0):!1),ei(i,r,o);if(s){Array.isArray(s)||(s=[s]);for(let r of s)typeof r=="string"&&(r=Ft(r)),i.appendChild(r)}return i}function Ft(n){return document.createTextNode(n)}const Ln="http://www.w3.org/1999/xhtml",Ng="http://www.w3.org/2000/svg",Ec={[Ln]:["br","a","ol","ul","li","div","h1","h2","h3","h4","h5","h6","p","strong","em","span","img","section","header","main","footer","dialog","article","aside","del","blockquote","details","summary","table","thead","tbody","tr","th","td","hr","pre","code","button","time","input","textarea","select","option","optgroup","label","form","progress","output","video","style"],[Ng]:["svg","g","path","circle","ellipse","rect","use"]},H={};for(const[n,e]of Object.entries(Ec))for(const t of e)H[t]=function(s,i){return Cc(n,t,s,i)};function Bi(n,e){let t;try{t=n.mount(e)}catch(s){console.error(s),t=Dg(s)}return t}function Dg(n){const e=new Error().stack;let t=null;return e&&(t=e.split(` `)[1]),H.div([H.h2("Something went wrong\u2026"),H.h3(n.message),H.p(`This occurred while running ${t}.`),H.pre(n.stack)])}function Bo(n,e,t){if(e===n.childElementCount)n.appendChild(t);else{const i=n.children[e];n.insertBefore(t,i)}}function Ug(n){n.innerHTML=""}function Kn(n){return async e=>{var t,s;(t=e.target)==null||t.setAttribute("disabled","disabled"),await n(e),(s=e.target)==null||s.removeAttribute("disabled")}}class os{constructor({list:e,onItemClick:t,className:s,tagName:i="ul",parentProvidesUpdates:r=!0},o){this._onItemClick=t,this._list=e,this._className=s,this._tagName=i,this._root=void 0,this._subscription=void 0,this._childCreator=o,this._childInstances=void 0,this._mountArgs={parentProvidesUpdates:r}}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=Vg(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 s=Array.prototype.indexOf.call(this._root.childNodes,t),i=this._childInstances[s];i&&this._onItemClick(i,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 s=this._childCreator(t);this._childInstances.push(s),e.appendChild(Bi(s,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,s){this.moveChild(e,t)}onUpdate(e,t,s){this.updateChild(e,t,s)}addChild(e,t){const s=this._childCreator(t);this._childInstances.splice(e,0,s),Bo(this._root,e,Bi(s,this._mountArgs))}removeChild(e){const[t]=this._childInstances.splice(e,1);t.root().remove(),t.unmount()}moveChild(e,t){const[s]=this._childInstances.splice(e,1);this._childInstances.splice(t,0,s),s.root().remove(),Bo(this._root,t,s.root())}updateChild(e,t,s){if(this._childInstances){const i=this._childInstances[e];i&&i.update(t,s)}}recreateItem(e,t){if(this._childInstances){const s=this._childCreator(t);if(!s)this.onRemove(e,t);else{const[i]=this._childInstances.splice(e,1,s);this._root.replaceChild(s.mount(this._mountArgs),i.root()),i.unmount()}}}getChildInstanceByIndex(e){var t;return(t=this._childInstances)==null?void 0:t[e]}}class Rc{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 Og(n){for(const e of Object.values(n))if(typeof e=="function")return!0;return!1}class E extends Rc{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:s,useCapture:i}of this._eventListeners)e.addEventListener(t,s,i)}_detach(){if(this._eventListeners)for(let{node:e,name:t,fn:s,useCapture:i}of this._eventListeners)e.removeEventListener(t,s,i)}mount(e){const t=new Tc(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 s of this._bindings)s()}_addEventListener(e,t,s,i=!1){this._eventListeners||(this._eventListeners=[]),this._eventListeners.push({node:e,name:t,fn:s,useCapture:i})}_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 s of this._subViews)s.update(e,t)}}class Tc{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,s,i=!1){this._templateView._addEventListener(e,t,s,i)}_addAttributeBinding(e,t,s){let i;const r=()=>{const o=s(this._value);i!==o&&(i=o,ei(e,t,o))};this._addBinding(r),r()}_addClassNamesBinding(e,t){this._addAttributeBinding(e,"className",s=>ri(t,s))}_addTextBinding(e){const t=e(this._value)+"",s=Ft(t);let i=t;const r=()=>{const o=e(this._value)+"";i!==o&&(i=o,s.textContent=o)};return this._addBinding(r),s}_isEventHandler(e,t){return e.startsWith("on")&&e.length>2&&typeof t=="function"}_setNodeAttributes(e,t){for(let[s,i]of Object.entries(t))if(typeof i=="object"){if(s!=="className"||i===null)continue;Og(i)?this._addClassNamesBinding(e,i):ei(e,s,ri(i,this._value))}else if(this._isEventHandler(s,i)){const r=s.substr(2,1).toLowerCase()+s.substr(3),o=i;this._templateView._addEventListener(e,r,o)}else typeof i=="function"?this._addAttributeBinding(e,s,i):ei(e,s,i)}_setNodeChildren(e,t){Array.isArray(t)||(t=[t]);for(let s of t)typeof s=="function"?s=this._addTextBinding(s):typeof s=="string"&&(s=Ft(s)),e.appendChild(s)}_addReplaceNodeBinding(e,t){let s=e(this._value),i=t(null);const r=()=>{const o=e(this._value);if(s!==o){s=o;const c=t(i);i.parentNode&&i.parentNode.replaceChild(c,i),i=c}};return this._addBinding(r),i}el(e,t,s){return this.elNS(Ln,e,t,s)}elNS(e,t,s,i){let r;s&&(Mc(s)?i=s:r=s);const o=document.createElementNS(e,t);return r&&this._setNodeAttributes(o,r),i&&this._setNodeChildren(o,i),o}view(e,t){return this._templateView.addSubView(e),Bi(e,t)}mapView(e,t){return this._addReplaceNodeBinding(e,s=>{if(s&&s.nodeType!==Node.COMMENT_NODE){const r=this._templateView._subViews;if(r){const o=r.findIndex(c=>c.root()===s);if(o!==-1){const[c]=r.splice(o,1);c.unmount()}}}const i=t(e(this._value));return i?this.view(i):document.createComment("node binding placeholder")})}map(e,t){return this.mapView(e,s=>new $i(this._value,(i,r)=>{const o=t(s,i,r);return o||document.createComment("map placeholder")}))}ifView(e,t){return this.mapView(s=>!!e(s),s=>s?t(this._value):null)}if(e,t){return this.ifView(e,s=>new $i(s,t))}mapSideEffect(e,t){let s=e(this._value);const i=()=>{const r=e(this._value);s!==r&&(t(r,s,this._value),s=r)};this._addBinding(i),t(s,void 0,this._value)}}for(const[n,e]of Object.entries(Ec))for(const t of e)Tc.prototype[t]=function(s,i){return this.elNS(n,t,s,i)};class $i extends E{constructor(e,t){super(e),this._render=t}render(e,t){return this._render(e,t)}}function Ss(n,e,t=void 0){const s=!!n.avatarUrl(e);let i=ri({avatar:!0,[`size-${e}`]:!0,[`usercolor${n.avatarColorNumber}`]:!s});t&&(i+=` ${t}`);const r=s?Ac(n,e):Ft(n.avatarLetter),o=H.div({className:i,title:n.avatarTitle,"data-testid":"avatar"},[r]);return s&&(ei(o,"data-avatar-letter",n.avatarLetter),ei(o,"data-avatar-color",n.avatarColorNumber)),o}function Ac(n,e){const t=e.toString();return H.img({src:n.avatarUrl(e),width:t,height:t,title:n.avatarTitle})}function Pg(n){const e=n.target,t=e.parentElement;return e.tagName==="IMG"&&t.classList.contains("avatar")}function $o(n){if(!Pg(n))return;const e=n.target.parentElement,t=e.getAttribute("data-avatar-color");e.classList.add(`usercolor${t}`);const s=e.getAttribute("data-avatar-letter");e.textContent=s}class wt extends Rc{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=Ss(this.value,this._size),this.subscribeOnMount(e),this._root}root(){return this._root}update(e){if(this._avatarUrlChanged()){const s=`usercolor${e.avatarColorNumber}`;e.avatarUrl(this._size)?(this._root.replaceChild(Ac(e,this._size),this._root.firstChild),this._root.classList.remove(s)):(this._root.textContent=e.avatarLetter,this._root.classList.add(s))}const t=!!e.avatarUrl(this._size);if(this._avatarTitleChanged()&&t){const s=this._root.firstChild;s.tagName==="IMG"&&s.setAttribute("title",e.avatarTitle)}this._avatarLetterChanged()&&!t&&(this._root.textContent=e.avatarLetter)}}let Ii;function ye(n,e=void 0){Ii===void 0&&(Ii=document.querySelector(".hydrogen"));const t=Object.assign({spinner:!0},e);return Ii!=null&&Ii.classList.contains("legacy")?n.div({className:t},[n.div(),n.div(),n.div(),n.div()]):n.svg({className:t,viewBox:"0 0 100 100"},n.circle({cx:"50%",cy:"50%",r:"45%",pathLength:"100"}))}class Fg extends E{render(e,t){const s={active:i=>i.isOpen,hidden:i=>i.hidden};return e.li({className:s},[e.a({href:t.url},[e.view(new wt(t,32),{parentProvidesUpdates:!0}),e.div({className:"description"},[e.div({className:{name:!0,unread:i=>i.isUnread}},i=>i.name),e.map(i=>i.busy,i=>i?ye(e):e.div({className:{badge:!0,highlighted:r=>r.isHighlighted,hidden:r=>!r.badgeCount}},r=>r.badgeCount))])])])}update(e,t){super.update(e),this.updateSubViews(e,t)}}class ue extends E{static option(e,t){return new Lg(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 Lg{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 Dr{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=H.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=Kg(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,s=this._popup.clientHeight,i=(this._scroller?this._scroller:document.documentElement).getBoundingClientRect();if(e.top>i.bottom||e.left>i.right||e.bottom=e.bottom+s)this._popup.style.top=`${e.bottom+this._verticalPadding}px`;else if(i.top<=e.top-s)this._popup.style.top=`${e.top-s-this._verticalPadding}px`;else return!1;if(i.right>=e.right+t)this._popup.style.left=`${e.left}px`;else if(i.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 Kg(n){let e=n;do if(e=e.parentElement,e.scrollHeight>e.clientHeight){const s=window.getComputedStyle(e).getPropertyValue("overflow-y");if(s==="auto"||s==="scroll")return e}while(e!==document.body)}class Bg extends E{render(e,t){const s=()=>{i.value="",i.blur(),r.blur(),t.clear()},i=e.input({type:"text",placeholder:t==null?void 0:t.label,"aria-label":t==null?void 0:t.label,autocomplete:t==null?void 0:t.autocomplete,enterkeyhint:"search",name:t==null?void 0:t.name,onInput:o=>t.set(o.target.value),onKeydown:o=>{(o.key==="Escape"||o.key==="Esc")&&s()},onFocus:()=>i.select()}),r=e.button({onClick:s,title:t.i18n`Clear`,"aria-label":t.i18n`Clear`});return e.div({className:"FilterField"},[i,r])}}class $g extends E{constructor(e){super(e),this._createMenuPopup=null}render(e,t){const s=o=>o.gridEnabled?o.i18n`Show single room`:o.i18n`Enable grid layout`,i=e.view(new os({className:"RoomList",list:t.tileViewModels},o=>new Fg(o))),r=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 Bg({i18n:t.i18n,label:t.i18n`Filter rooms…`,name:"room-filter",autocomplete:!0,set:o=>{t.setFilter(o)&&(i.scrollTop=0)},clear:()=>t.clearFilter()})),e.button({onClick:()=>t.toggleGrid(),className:{"button-utility":!0,grid:!0,on:o=>o.gridEnabled},title:s,"aria-label":s}),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"},[r,i])}_toggleCreateMenu(e){if(this._createMenuPopup&&this._createMenuPopup.isOpen)this._createMenuPopup.close();else{const t=this.value,s=[];s.push(ue.option(t.i18n`Create Room`,()=>t.showCreateRoomView())),s.push(ue.option(t.i18n`Join Room`,()=>t.showJoinRoomView())),this._createMenuPopup=new Dr(new ue(s)),this._createMenuPopup.trackInTemplateView(this),this._createMenuPopup.showRelativeTo(e.target,10)}}}function jo(n){return n.offsetTop+n.clientHeight}function qo(n,e,t=n.children.length-1){for(var s=t;s>=0;s--)if(n.children[s].offsetTop{this.restoreScrollPosition()}),this.tilesView=new qg(t.tiles,()=>this.restoreScrollPosition(),this.viewClassForTile);const s=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:i=>!i.showJumpDown},title:"Jump down",onClick:()=>this.jumpDown()})]);return typeof ResizeObserver=="function"&&(this.resizeObserver=new ResizeObserver(()=>{this.restoreScrollPosition()}),this.resizeObserver.observe(s)),s}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,s=e.clientHeight-t.clientHeight;if(s>0){t.style.setProperty("margin-top",`${s}px`);const i=this.value.tiles.length;this.updateVisibleRange(0,i-1)}else if(t.style.removeProperty("margin-top"),this.stickToBottom)e.scrollTop=e.scrollHeight;else if(this.anchoredNode){const i=jo(this.anchoredNode);if(i!==this.anchoredBottom){const r=i-this.anchoredBottom;typeof e.scrollBy=="function"?e.scrollBy(0,r):e.scrollTop=e.scrollTop+r,this.anchoredBottom=i}}}onScroll(){const{scrollNode:e,tilesNode:t}=this,{scrollHeight:s,scrollTop:i,clientHeight:r}=e;let o;if(this.stickToBottom=Math.abs(s-(i+r))<1,this.stickToBottom)o=this.value.tiles.length-1;else{const l=i+r,h=qo(t,l);this.anchoredNode=t.childNodes[h],this.anchoredBottom=jo(this.anchoredNode),o=h}let c=qo(t,i,o);this.updateVisibleRange(c,o)}updateVisibleRange(e,t){const s=this.tilesView.getChildInstanceByIndex(e),i=this.tilesView.getChildInstanceByIndex(t);this.value.setVisibleTileRange(s==null?void 0:s.value,i==null?void 0:i.value)}}class qg extends os{constructor(e,t,s){super({list:e,onItemClick:(i,r)=>i.onClick(r)},i=>{const r=s(i);return new r(i,s)}),this.viewClassForTile=s,this.onChanged=t}onReset(){super.onReset(),this.onChanged()}onUpdate(e,t,s){if(s==="shape"){const i=this.viewClassForTile(t),r=this.getChildInstanceByIndex(e);if(!i||!(r instanceof i)){super.recreateItem(e,t);return}}super.onUpdate(e,t,s),this.onChanged()}onAdd(e,t){super.onAdd(e,t),this.onChanged()}onRemove(e,t){super.onRemove(e,t),this.onChanged()}onMove(e,t,s){super.onMove(e,t,s),this.onChanged()}}class Hg extends E{render(e,t){return e.div({className:"TimelineLoadingView"},[ye(e),e.div(t.isEncrypted?t.i18n`Loading encrypted messages…`:t.i18n`Loading messages…`)])}}class Wg extends E{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:r=>this._onKeyDown(r),onInput:()=>{t.setInput(this._input.value),this._input.value?this._adjustHeight():this._clearHeight()},placeholder:r=>r.isEncrypted?"Send an encrypted message\u2026":"Send a message\u2026",rows:"1"}),this._focusInput=()=>this._input.focus(),this.value.on("focus",this._focusInput);const s=e.map(r=>r.replyViewModel,(r,o)=>{const c=r&&this._viewClassForTile(r);return c?o.div({className:"MessageComposer_replyPreview"},[o.span({className:"replying"},"Replying"),o.button({className:"cancel",onClick:()=>this._clearReplyingTo()},"Close"),o.view(new c(r,this._viewClassForTile,{interactive:!1},"div"))]):null}),i=e.div({className:"MessageComposer_input"},[this._input,e.button({className:"sendFile",title:t.i18n`Pick attachment`,onClick:r=>this._toggleAttachmentMenu(r)},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:r=>r.canSend}},[s,i])}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(s){t(),console.error(s)}}_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 Dr(new ue([ue.option(t.i18n`Send video`,()=>t.sendVideo()).setIcon("video"),ue.option(t.i18n`Send picture`,()=>t.sendPicture()).setIcon("picture"),ue.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 zg extends E{render(e){return e.div({className:"DisabledComposerView"},e.h3(t=>t.description))}}class Vs extends E{constructor(e,t={inline:!1}){super(e),this.options=t}render(e,t){const s=e.button({className:"ErrorView_submit",onClick:Kn(async r=>{r.stopPropagation(),await t.submitLogs()?alert("Logs submitted!"):alert("Could not submit logs")})},"Submit logs"),i=e.button({className:"ErrorView_close",onClick:r=>{r.stopPropagation(),t.close()},title:"Dismiss error"});return e.div({className:{ErrorView:!0,ErrorView_inline:this.options.inline,ErrorView_block:!this.options.inline}},[e.p({className:"ErrorView_message"},t.message),s,i])}}class Gg extends E{render(e,t){const s=e.view(new os({className:"CallView_members",list:t.memberViewModels},i=>new Yg(i)));return this.bindMembersCssClasses(e,s),e.div({class:"CallView"},[s,e.div({class:"CallView_buttons"},[e.button({className:{CallView_mutedMicrophone:i=>i.isMicrophoneMuted,CallView_unmutedMicrophone:i=>!i.isMicrophoneMuted},onClick:Hr(()=>t.toggleMicrophone())}),e.button({className:{CallView_mutedCamera:i=>i.isCameraMuted,CallView_unmutedCamera:i=>!i.isCameraMuted},onClick:Hr(()=>t.toggleCamera())}),e.button({className:"CallView_hangup",onClick:Hr(()=>t.hangup())})]),e.if(i=>!!i.errorViewModel,i=>i.div({className:"CallView_error"},i.view(new Vs(t.errorViewModel))))])}bindMembersCssClasses(e,t){if(e.mapSideEffect(s=>s.memberCount,s=>{t.classList.forEach((i,r,o)=>{i.startsWith("size")&&o.remove(i)}),t.classList.add(`size${s}`)}),typeof ResizeObserver=="function"){const s=(i,r)=>{r?t.classList.add(i):t.classList.remove(i)};this.resizeObserver=new ResizeObserver(()=>{const i=t.clientWidth/t.clientHeight,r=i<.5,o=!r&&i<1.8,c=!r&&!o;s("tall",r),s("square",o),s("wide",c)}),this.resizeObserver.observe(t)}}unmount(){this.resizeObserver&&(this.resizeObserver.unobserve(this.root().querySelector(".CallView_members")),this.resizeObserver=void 0),super.unmount()}}class Yg extends E{render(e,t){const s=e.video({autoplay:!0,disablePictureInPicture:!0,className:{hidden:i=>i.isCameraMuted}});return e.mapSideEffect(i=>i.stream,i=>{s.srcObject=i}),e.div({className:"StreamView"},[s,e.div({className:{StreamView_avatar:!0,hidden:i=>!i.isCameraMuted}},e.view(new wt(t,96),{parentProvidesUpdates:!0})),e.div({className:{StreamView_muteStatus:!0,hidden:i=>!i.isCameraMuted&&!i.isMicrophoneMuted,microphoneMuted:i=>i.isMicrophoneMuted&&!i.isCameraMuted,cameraMuted:i=>i.isCameraMuted}}),e.if(i=>!!i.errorViewModel,i=>i.div({className:"StreamView_error"},i.view(new Vs(t.errorViewModel))))])}update(e,t){super.update(e),this.updateSubViews(e,t)}}function Hr(n){return async e=>{var t,s;(t=e.target)==null||t.setAttribute("disabled","disabled"),await n(e),(s=e.target)==null||s.removeAttribute("disabled")}}class xc extends E{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 wt(t,32)),e.div({className:"room-description"},[e.h2(s=>s.name)]),e.button({className:"button-utility room-options","aria-label":t.i18n`Room options`,onClick:s=>this._toggleOptionsMenu(s)})]),e.div({className:"RoomView_body"},[e.if(s=>s.errorViewModel,s=>s.div({className:"RoomView_error"},s.view(new Vs(t.errorViewModel)))),e.mapView(s=>s.callViewModel,s=>s?new Gg(s):null),e.mapView(s=>s.timelineViewModel,s=>s?new jg(s,this._viewClassForTile):new Hg(t)),e.mapView(s=>s.composerViewModel,s=>{switch(s==null?void 0:s.kind){case"composer":return new Wg(t.composerViewModel,this._viewClassForTile);case"disabled":return new zg(t.composerViewModel)}})])])}_toggleOptionsMenu(e){if(this._optionsPopup&&this._optionsPopup.isOpen)this._optionsPopup.close();else{const t=this.value,s=[];if(s.push(ue.option(t.i18n`Room details`,()=>t.openDetailsPanel())),t.features.calls&&s.push(ue.option(t.i18n`Start call`,()=>t.startCall())),t.canLeave&&s.push(ue.option(t.i18n`Leave room`,()=>this._confirmToLeaveRoom()).setDestructive()),t.canForget&&s.push(ue.option(t.i18n`Forget room`,()=>t.forgetRoom()).setDestructive()),t.canRejoin&&s.push(ue.option(t.i18n`Rejoin room`,()=>t.rejoinRoom())),!s.length)return;this._optionsPopup=new Dr(new ue(s)),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 Jg extends E{render(e,t){return e.main({className:"UnknownRoomView middle"},[e.div({className:"UnknownRoomView_header middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Cancel room join`}),e.h2("Join room")]),e.div({className:"UnknownRoomView_body centered-column"},[e.div({className:"UnknownRoomView_container"},[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:s=>s.busy},t.i18n`Join room`),e.if(s=>s.error,s=>s.p({className:"error"},t.error))])])])}}class ni{constructor(e,t=void 0){typeof e=="function"&&!t&&(t=e,e=null),this._root=t?t(H,e):this.render(H,e)}mount(){return this._root}root(){return this._root}unmount(){}update(){}}class Vc extends ni{constructor(e="Loading"){super(e,(t,s)=>t.div({className:"LoadingView"},[ye(t),s]))}}class Nc extends E{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 wt(t,32)),e.div({className:"room-description"},[e.h2(s=>s.name)])]),e.div({className:"RoomView_body"},[e.mapView(s=>s.error,s=>s?new Qg(t):new Vc(t.i18n`Setting up the room…`))])])}}class Qg extends E{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 Dc extends E{render(e,t){var r;let s=[];t.isDirectMessage&&s.push(Ss(t,128,"InviteView_dmAvatar"));let i;return t.isDirectMessage?i=[e.strong(t.name),` (${(r=t.inviter)==null?void 0:r.id}) wants to chat with you.`]:t.inviter?i=[Ss(t.inviter,24),e.strong(t.inviter.name),` (${t.inviter.id}) invited you.`]:i="You were invited to join.",s.push(e.p({className:"InviteView_inviter"},i)),t.isDirectMessage||s.push(e.div({className:"InviteView_roomProfile"},[Ss(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`}),Ss(t,32),e.div({className:"room-description"},[e.h2(o=>o.name)])]),e.if(o=>o.error,o=>o.div({className:"RoomView_error"},c=>c.error)),e.div({className:"InviteView_body"},[e.div({className:"InviteView_invite"},[...s,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 Xg extends E{render(e,t){const s=e.a({href:t.closeUrl,title:t.i18n`Close`,className:"close"}),i=e.div({role:"img","aria-label":l=>l.name,title:l=>l.name,className:{picture:!0,hidden:l=>!l.imageUrl},style:l=>`background-image: url('${l.imageUrl}'); max-width: ${l.imageWidth}px; max-height: ${l.imageHeight}px;`}),r=e.div({className:{loading:!0,hidden:l=>!!l.imageUrl}},[ye(e),e.div(t.i18n`Loading image…`)]),o=e.div({className:"details"},[e.strong(l=>l.name),e.br(),"uploaded by ",e.strong(l=>l.sender),l=>` at ${l.time} on ${l.date}.`]),c=e.div({role:"dialog",className:"lightbox",onClick:l=>this.clickToClose(l),onKeydown:l=>this.closeOnEscKey(l)},[i,r,o,s]);return Zg(e,c),c}clickToClose(e){e.target===this.root()&&this.value.close()}closeOnEscKey(e){(e.key==="Escape"||e.key==="Esc")&&this.value.close()}}function Zg(n,e){const t=ef(e),s=t[0],i=t[t.length-1];n.addEventListener(e,"keydown",r=>{r.key==="Tab"&&(r.shiftKey?document.activeElement===s&&(i.focus(),r.preventDefault()):document.activeElement===i&&(s.focus(),r.preventDefault()))},!0),Promise.resolve().then(()=>{s.focus()})}function ef(n){return n.querySelectorAll("a[href], button, textarea, input, select")}class tf extends E{render(e,t){return e.div({className:{SessionStatusView:!0,hidden:s=>!s.isShown}},[ye(e,{hidden:s=>!s.isWaiting}),e.p(s=>s.statusLabel),e.if(s=>s.isConnectNowShown,s=>s.button({className:"link",onClick:()=>t.connectNow()},"Retry now")),e.if(s=>s.isSecretStorageShown,s=>s.a({href:t.setupKeyBackupUrl},"Go to settings")),e.if(s=>s.canDismiss,s=>s.div({className:"end"},s.button({className:"dismiss",onClick:()=>t.dismiss()})))])}}class sf extends E{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const s=[];for(let i=0;it.focusTile(i),onFocusin:()=>t.focusTile(i),className:{container:!0,[`tile${i}`]:!0,focused:r=>r.focusIndex===i}},e.mapView(r=>r.roomViewModelAt(i),r=>r?r.kind==="roomBeingCreated"?new Nc(r):r.kind==="invite"?new Dc(r):new xc(r,this._viewClassForTile):new ni(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 s.push(e.div({className:i=>`focus-ring tile${i.focusIndex}`})),e.div({className:"RoomGridView middle layout3x2"},s)}}class Uc extends E{render(e,t){return e.div([e.map(s=>s.status,(s,i,r)=>{switch(s){case st.Enabled:return rf(i,r);case st.NewVersionAvailable:return nf(i,r);case st.SetupWithPassphrase:return af(i,r);case st.SetupWithRecoveryKey:return of(i,r);case st.Pending:return i.p(r.i18n`Waiting to go online…`)}}),e.map(s=>s.backupWriteStatus,(s,i,r)=>{switch(s){case wr.Writing:{const o=i.progress({min:0+"",max:100+"",value:c=>c.backupPercentage});return i.div(["Backup in progress ",o," ",c=>c.backupInProgressLabel])}case wr.Stopped:{let o;return r.backupError?o=`Backup has stopped because of an error: ${r.backupError}`:o="Backup has stopped",i.p([o," ",i.button({onClick:()=>r.startBackup()},"Backup now")])}case wr.Done:return i.p("All keys are backed up.");default:return}}),e.if(s=>s.isMasterKeyTrusted,s=>s.p("Cross-signing master key found and trusted.")),e.if(s=>s.canSignOwnDevice,s=>s.div([s.button({onClick:Kn(async()=>{t.navigateToVerification()})},"Verify by emoji")]))])}}function rf(n,e){const t=[n.p([e.i18n`Key backup is enabled, using backup version ${e.backupVersion}. `,n.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return e.dehydratedDeviceId&&t.push(n.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.`)),n.div(t)}function nf(n,e){const t=[n.p([e.i18n`A new backup version has been created from another device. Disable key backup and enable it again with the new key.`,n.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return n.div(t)}function of(n,e){const t=n.button({className:"link",onClick:()=>e.showPhraseSetup()},e.i18n`use a security phrase`);return n.div([n.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.`),Pc(n),Oc(n,e,e.i18n`Security key`,(s,i)=>e.enterSecurityKey(s,i)),n.p([e.i18n`Alternatively, you can `,t,e.i18n` if you have one.`])])}function af(n,e){const t=n.button({className:"link",onClick:()=>e.showKeySetup()},e.i18n`use your security key`);return n.div([n.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.`),Pc(n),Oc(n,e,e.i18n`Security phrase`,(s,i)=>e.enterSecurityPhrase(s,i)),n.p([e.i18n`You can also `,t,e.i18n`.`])])}function Oc(n,e,t,s){let i;const r=()=>s(o.value,(i==null?void 0:i.checked)||!1),o=n.input({type:"password",disabled:l=>l.isBusy,placeholder:t}),c=[n.p([o,n.button({disabled:l=>l.isBusy,onClick:r},e.decryptAction)])];if(e.offerDehydratedDeviceSetup){i=n.input({type:"checkbox",id:"enable-dehydrated-device"});const l=n.a({href:"https://github.com/uhoreg/matrix-doc/blob/dehydration/proposals/2697-device-dehydration.md",target:"_blank",rel:"noopener"},"more info");c.push(n.p([i,n.label({for:i.id},[e.i18n`Back up my device as well (`,l,")"])]))}return n.div({className:"row"},[n.div({className:"label"},t),n.div({className:"content"},c)])}function Pc(n){return n.if(e=>e.error!==void 0,(e,t)=>e.div([e.p({className:"error"},s=>s.i18n`Could not enable key backup: ${s.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 cf extends E{render(e,t){return e.div({className:"FeaturesView"},[e.p("Enable experimental features here that are still in development. These are not yet ready for primetime, so expect bugs."),e.ul(t.featureViewModels.map(s=>e.li(e.view(new lf(s)))))])}}class lf extends E{render(e,t){let s=`feature_${t.id}`;return e.div({className:"FeatureView"},[e.input({type:"checkbox",id:s,checked:i=>i.enabled,onChange:i=>t.enableFeature(i.target.checked)}),e.div({class:"FeatureView_container"},[e.h4(e.label({for:s},t.name)),e.p(t.description)])])}}class hf extends E{render(e,t){let s=t.version;t.showUpdateButton&&(s=e.span([t.version,e.button({onClick:()=>t.checkForUpdate()},t.i18n`Check for updates`)]));const i=(c,l,h,a="")=>c.div({className:`row ${a}`},[c.div({className:"label"},l),c.div({className:"content"},h)]),r=[];r.push(e.h3("Session"),i(e,t.i18n`User ID`,t.userId),i(e,t.i18n`Session ID`,t.deviceId,"code"),i(e,t.i18n`Session key`,t.fingerprintKey,"code"),i(e,"",e.button({onClick:()=>t.logout(),disabled:c=>c.isLoggingOut},t.i18n`Log out`))),r.push(e.h3("Key backup & security"),e.view(new Uc(t.keyBackupViewModel))),r.push(e.h3("Notifications"),e.map(c=>c.pushNotifications.supported,(c,l)=>{if(c===null)return l.p(t.i18n`Loading…`);if(c){const h=u=>u.pushNotifications.enabled?u.i18n`Push notifications are enabled`:u.i18n`Push notifications are disabled`,a=u=>u.pushNotifications.enabled?u.i18n`Disable`:u.i18n`Enable`;return i(l,h,l.button({onClick:()=>t.togglePushNotifications(),disabled:u=>u.pushNotifications.updating},a))}else return l.p(t.i18n`Push notifications are not supported on this browser`)}),e.if(c=>c.pushNotifications.supported&&c.pushNotifications.enabled,c=>c.div([c.p(["If you think push notifications are not being delivered, ",c.button({className:"link",onClick:()=>t.checkPushEnabledOnServer()},"check")," if they got disabled on the server"]),c.map(l=>l.pushNotifications.enabledOnServer,(l,h)=>{if(l===!0)return h.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(l===!1)return h.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.")}),c.map(l=>l.pushNotifications.serverError,(l,h)=>{if(l)return h.p("Couldn't not check on server: "+l.message)})]))),r.push(e.h3("Preferences"),i(e,t.i18n`Scale down images when sending`,this._imageCompressionRange(e,t)),e.if(c=>c.activeTheme,(c,l)=>i(c,l.i18n`Use the following theme`,this._themeOptions(c,l))));const o=[];return t.canSendLogsToServer&&o.push(e.button({onClick:Kn(()=>t.sendLogsToServer())},`Submit logs to ${t.logsServer}`)),o.push(e.button({onClick:()=>t.exportLogs()},"Download logs")),r.push(e.h3("Experimental features"),e.view(new cf(t.featuresViewModel))),r.push(e.h3("Application"),i(e,t.i18n`Version`,s),i(e,t.i18n`Storage usage`,c=>`${c.storageUsage} / ${c.storageQuota}`),i(e,t.i18n`Debug logs`,o),e.p({className:{hidden:c=>!c.logsFeedbackMessage}},c=>c.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.p([])),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"},r)])}_imageCompressionRange(e,t){const i=Math.ceil(t.minSentImageSizeLimit/32)*32,r=(Math.floor(t.maxSentImageSizeLimit/32)+1)*32,o=c=>t.setSentImageSizeLimit(parseInt(c.target.value,10));return[e.input({type:"range",step:32,min:i,max:r,value:c=>c.sentImageSizeLimit||r,onInput:o,onChange:o})," ",e.output(c=>c.sentImageSizeLimit?c.i18n`resize to ${c.sentImageSizeLimit}px`:c.i18n`no resizing`)]}_themeOptions(e,t){const{themeName:s,themeVariant:i}=t.activeTheme,r=[];for(const f of Object.keys(t.themeMapping))r.push(e.option({value:f,selected:f===s},f));const o=e.select({onChange:f=>{const v=f.target.value;if(!("id"in t.themeMapping[v])){const M=a.checked?"dark":p.checked?"light":"default";c(M);return}t.changeThemeOption(v)}},r),c=f=>{const v=o.options[o.selectedIndex].value;t.changeThemeOption(v,f)},l=i==="dark",h=i==="light",a=e.input({type:"radio",name:"radio-chooser",value:"dark",id:"dark",checked:l}),u=e.input({type:"radio",name:"radio-chooser",value:"default",id:"default",checked:!(l||h)}),p=e.input({type:"radio",name:"radio-chooser",value:"light",id:"light",checked:h}),g=e.form({className:{hidden:()=>{const f=o.options[o.selectedIndex].value;return"id"in t.themeMapping[f]}},onChange:f=>c(f.target.value)},[u,e.label({for:"default"},"Match system theme"),a,e.label({for:"dark"},"dark"),p,e.label({for:"light"},"light")]);return e.div({className:"theme-chooser"},[o,g])}}class df extends E{render(e,t){return e.main({className:"CreateRoomView middle"},[e.div({className:"CreateRoomView_header middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Cancel room creation`}),e.h2("Create room")]),e.div({className:"CreateRoomView_body centered-column"},[e.form({className:"CreateRoomView_detailsForm form",onChange:s=>this.onFormChange(s),onSubmit:s=>this.onSubmit(s)},[e.div({className:"vertical-layout"},[e.button({type:"button",className:"CreateRoomView_selectAvatar",onClick:()=>t.selectAvatar()},e.mapView(s=>s.hasAvatar,s=>s?new wt(t,64):new ni(void 0,i=>i.div({className:"CreateRoomView_selectAvatarPlaceholder"})))),e.div({className:"stretch form-row text"},[e.label({for:"name"},t.i18n`Room name`),e.input({onInput:s=>t.setName(s.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:s=>t.setTopic(s.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:s=>s.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:s=>!s.isPublic}},[e.label({for:"roomAlias"},t.i18n`Room alias`),e.input({onInput:s=>t.setRoomAlias(s.target.value),type:"text",name:"roomAlias",id:"roomAlias",placeholder:t.i18n`Room alias (, or # or #:hs.tld`})]),e.div({className:"form-group"},[e.div(e.button({className:"link",type:"button",onClick:()=>t.toggleAdvancedShown()},s=>s.isAdvancedShown?s.i18n`Hide advanced settings`:s.i18n`Show advanced settings`)),e.div({className:{"form-row check":!0,hidden:s=>!s.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:s=>!s.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 uf extends E{render(e,t){const s=()=>t.isEncrypted?t.i18n`On`:t.i18n`Off`;return e.div({className:"RoomDetailsView"},[e.div({className:"RoomDetailsView_avatar"},[e.view(new wt(t,52)),e.mapView(i=>i.isEncrypted,i=>new mf(i))]),e.div({className:"RoomDetailsView_name"},[e.h2(i=>i.name)]),this._createRoomAliasDisplay(t),e.div({className:"RoomDetailsView_rows"},[this._createRightPanelButtonRow(e,t.i18n`People`,{MemberCount:!0},i=>i.memberCount,()=>t.openPanel("members")),this._createRightPanelRow(e,t.i18n`Encryption`,{EncryptionStatus:!0},s)])])}_createRoomAliasDisplay(e){return e.canonicalAlias?H.div({className:"RoomDetailsView_id"},[e.canonicalAlias]):""}_createRightPanelRow(e,t,s,i){const r=ri(It({RoomDetailsView_label:!0},s));return e.div({className:"RoomDetailsView_row"},[e.div({className:r},[t]),e.div({className:"RoomDetailsView_value"},i)])}_createRightPanelButtonRow(e,t,s,i,r){const o=ri(It({RoomDetailsView_label:!0},s));return e.button({className:"RoomDetailsView_row",onClick:r},[e.div({className:o},[t]),e.div({className:"RoomDetailsView_value"},i)])}}class mf extends E{render(e,t){return e.div({className:"EncryptionIconView"},[e.div({className:t?"EncryptionIconView_encrypted":"EncryptionIconView_unencrypted"})])}}class _f{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(n[n.Before=1]="Before",n[n.Inside=2]="Inside",n[n.After=3]="After",n))(Cs||{});class pf{constructor(e){this.range=e,this.idx=e.start-1}next(){return this.idxthis.range.start?(this.idx-=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}function ff(n,e){let t=0;for(;t(n[n.Move=0]="Move",n[n.Add=1]="Add",n[n.Remove=2]="Remove",n[n.RemoveAndAdd=3]="RemoveAndAdd",n[n.UpdateRange=4]="UpdateRange",n))(Gs||{});class Di extends _f{constructor(e,t,s,i=t-e){super(e,t),this._totalLength=s,this._viewportItemCount=i}expand(e){if(this.length===0)return this;const t=Math.max(0,this.start-e),s=Math.min(this.totalLength,this.end+e);return new Di(t,s,this.totalLength,this._viewportItemCount)}get totalLength(){return this._totalLength}get viewportItemCount(){return this._viewportItemCount}static fromViewport(e,t,s,i){const r=Math.min(Math.max(0,Math.floor(i/t)),e),o=e-r,c=s!==0?Math.ceil(s/t):0,l=Math.min(c,o);return new Di(r,r+l,e,c)}queryAdd(e,t,s){const i=this.viewportItemCount>this.length?this.end:this.end-1;if(e<=i){const r=this.clampIndex(e,i),o=r===e?t:ur(s[Symbol.iterator](),r);return this.createAddResult(r,o)}else return{type:4,newRange:this.deriveRange(1,0)}}queryRemove(e,t){if(ethis.length)return{type:1,addIdx:e,value:t,newRange:this.deriveRange(1,1)};{const s=this.clampIndex(Number.MAX_SAFE_INTEGER);return{type:3,removeIdx:s,addIdx:e,value:t,newRange:this.deriveRange(1,0)}}}createRemoveResult(e,t){if(this.endrequestAnimationFrame(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 Di.fromViewport(this._list.length,this.itemHeight,e,t)}reRenderFullRange(e){Ug(this._listElement);const t=document.createDocumentFragment(),s=this._list[Symbol.iterator]();this._childInstances.length=0,e.forEachInIterator(s,i=>{const r=this._childCreator(i);this._childInstances.push(r),t.appendChild(Bi(r,this._mountArgs))}),this._listElement.appendChild(t),this.adjustPadding(e)}renderUpdate(e,t){if(t.intersects(e)){for(const s of e.reverseIterable())if(!t.containsIndex(s)){const i=s-e.start;this.removeChild(i)}t.forEachInIterator(this._list[Symbol.iterator](),(s,i)=>{if(!e.containsIndex(i)){const r=i-t.start;this.addChild(r,s)}}),this.adjustPadding(t)}else this.reRenderFullRange(t)}adjustPadding(e){const t=e.start*this.itemHeight,s=(e.totalLength-e.end)*this.itemHeight,i=this._listElement.style;i.paddingTop=`${t}px`,i.paddingBottom=`${s}px`}mount(){const e=super.mount();return this.scrollContainer=H.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 s=this.renderRange.queryAdd(e,t,this._list);this.applyRemoveAddResult(s)}onRemove(e,t){const s=this.renderRange.queryRemove(e,this._list);this.applyRemoveAddResult(s)}onMove(e,t,s){const i=this.renderRange.queryMove(e,t,s,this._list);i&&(i.type===Gs.Move?this.moveChild(this.renderRange.toLocalIndex(i.fromIdx),this.renderRange.toLocalIndex(i.toIdx)):this.applyRemoveAddResult(i))}onUpdate(e,t,s){this.renderRange.containsIndex(e)&&this.updateChild(this.renderRange.toLocalIndex(e),t,s)}applyRemoveAddResult(e){(e.type===Gs.Remove||e.type===Gs.RemoveAndAdd)&&this.removeChild(this.renderRange.toLocalIndex(e.removeIdx)),e.newRange&&(this.renderRange=e.newRange,this.adjustPadding(this.renderRange)),(e.type===Gs.Add||e.type===Gs.RemoveAndAdd)&&this.addChild(this.renderRange.toLocalIndex(e.addIdx),e.value)}}class wf extends E{render(e,t){return e.li({className:"MemberTileView"},e.a({href:t.detailsUrl},[e.view(new wt(t,32)),e.div({className:"MemberTileView_name"},s=>s.name)]))}}class vf extends E{render(e,t){const s=new yf({list:t.memberTileViewModels,className:"MemberListView__list",itemHeight:40},i=>new wf(i));return e.div({className:"MemberListView"},[e.div({className:"MemberListView__invite-container"},[e.button({className:"MemberListView__invite-btn button-action primary",onClick:()=>t.openInvitePanel()},t.i18n`Invite to this room`)]),e.view(s)])}}class bf extends E{render(e,t){const s=[e.p(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.`)];return t.features.crossSigning&&s.push(e.div({className:"MemberDetailsView_shield_container"},[e.span({className:i=>`MemberDetailsView_shield_${i.trustShieldColor}`}),e.p({className:"MemberDetailsView_shield_description"},i=>i.trustDescription)])),e.div({className:"MemberDetailsView"},[e.view(new wt(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`,s),this._createOptions(e,t)])}_createSection(e,t,s){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t),e.div({className:"MemberDetailsView_value"},s)])}_createOptions(e,t){const s=[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`)];if(t.features.crossSigning){t.canVerifyUser&&s.push(e.button({className:"text",onClick:()=>t.verifyUser()},t.i18n`Verify`));const i=()=>{confirm("You don't want to do this with any account but a test account. This will cross-sign this user without verifying their keys first. You won't be able to undo this apart from resetting your cross-signing keys.")&&t.signUser()};s.push(e.button({className:"text",onClick:i},t.i18n`Cross-sign user (DO NOT USE, TESTING ONLY)`))}return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t.i18n`Options`),e.div({className:"MemberDetailsView_options"},s)])}}class Sf extends E{render(e,t){return e.div({className:"WaitingForOtherUserView"},[e.div({className:"WaitingForOtherUserView__heading"},[ye(e),e.h2({className:"WaitingForOtherUserView__title"},t.title)]),e.p({className:"WaitingForOtherUserView__description"},t.description),e.div({className:"WaitingForOtherUserView__actions"},e.button({className:{"button-action":!0,primary:!0,destructive:!0},onclick:()=>t.cancel()},"Cancel"))])}}class kf extends E{render(e,t){return e.div({className:"VerificationCancelledView"},[e.h2({className:"VerificationCancelledView__title"},t.title),e.p({className:"VerificationCancelledView__description"},t.description),e.div({className:"VerificationCancelledView__actions"},[e.button({className:{"button-action":!0,primary:!0},onclick:()=>t.dismiss()},"Got it")])])}}class If extends E{render(e){return e.div({className:"SelectMethodView"},[e.map(t=>t.hasProceeded,(t,s,i)=>t?ye(s):s.div([s.div({className:"SelectMethodView__heading"},[s.h2({className:"SelectMethodView__title"},this.getHeading(s,i))]),s.p({className:"SelectMethodView__description"},this.getSubheading(i)),s.div({className:"SelectMethodView__actions"},[s.button({className:{"button-action":!0,primary:!0,destructive:!0},onclick:()=>i.cancel()},"Cancel"),s.button({className:{"button-action":!0,primary:!0},onclick:()=>i.proceed()},"Proceed")])]))])}getHeading(e,t){return t.isCrossSigningAnotherUser?[t.i18n`Verify user `,e.span({className:"SelectMethodView__name"},t.otherUserId),t.i18n` by comparing emojis?`]:[t.i18n`Verify device`,e.span({className:"SelectMethodView__name"},t.deviceName),t.i18n` by comparing emojis?`]}getSubheading(e){return e.isCrossSigningAnotherUser?e.i18n`You are about to verify user (${e.otherUserId}) by comparing emojis.`:e.i18n`You are about to verify your other device (${e.deviceName}) by comparing emojis.`}}class Mf extends E{render(e,t){const s=t.emojis.reduce((r,[o,c])=>{const l=e.div({className:"EmojiContainer"},[e.div({className:"EmojiContainer__emoji"},o),e.div({className:"EmojiContainer__name"},c)]);return r.push(l),r},[]),i=e.div({className:"EmojiCollection"},s);return e.div({className:"VerifyEmojisView"},[e.div({className:"VerifyEmojisView__heading"},[e.h2({className:"VerifyEmojisView__title"},t.i18n`Do the emojis match?`)]),e.p({className:"VerifyEmojisView__description"},t.i18n`Confirm the emoji below are displayed on both devices, in the same order:`),e.div({className:"VerifyEmojisView__emojis"},i),e.map(r=>r.isWaiting,(r,o,c)=>r?o.div({className:"VerifyEmojisView__waiting"},[ye(o),o.span(c.i18n`Waiting for you to verify on your other device`)]):o.div({className:"VerifyEmojisView__actions"},[o.button({className:{"button-action":!0,primary:!0,destructive:!0},onclick:()=>c.setEmojiMatch(!1)},c.i18n`They don't match`),o.button({className:{"button-action":!0,primary:!0},onclick:()=>c.setEmojiMatch(!0)},c.i18n`They match`)]))])}}class Cf extends E{render(e,t){return e.div({className:"VerificationCompleteView"},[e.div({className:"VerificationCompleteView__icon"}),e.div({className:"VerificationCompleteView__heading"},[e.h2({className:"VerificationCompleteView__title"},t.i18n`Verification completed successfully!`)]),e.p({className:"VerificationCompleteView__description"},t.verificationSuccessfulMessage),e.div({className:"VerificationCompleteView__actions"},[e.button({className:{"button-action":!0,primary:!0},onclick:()=>t.dismiss()},"Got it")])])}}class Ef extends E{render(e,t){return e.div({className:"MissingKeysView"},[e.h2({className:"MissingKeysView__heading"},t.i18n`Verification is currently not possible!`),e.p({className:"MissingKeysView__description"},t.i18n`Some keys needed for verification are missing. You can fix this by enabling key backup in settings.`),e.div({className:"MissingKeysView__actions"},[e.button({className:{"button-action":!0,primary:!0},onclick:()=>t.gotoSettings()},"Open Settings")])])}}class Fc extends E{render(e,t){return e.div({className:{middle:!t.isHappeningInRoom,DeviceVerificationView:!0}},[e.mapView(s=>s.currentStageViewModel,s=>{switch(s==null?void 0:s.kind){case"waiting-for-user":return new Sf(s);case"verification-cancelled":return new kf(s);case"select-method":return new If(s);case"verify-emojis":return new Mf(s);case"verification-completed":return new Cf(s);case"keys-missing":return new Ef(s);default:return new $i(s,()=>ye(e))}})])}}class Rf extends E{render(e,t){const s=e.input({className:"InvitePanelView__input",type:"text",placeholder:"Enter user-id of user",onkeydown:i=>{i.key==="Enter"&&t.invite(s.value)}});return e.div({className:"InvitePanelView"},[e.h3({className:"InvitePanelView__heading"},i=>i.i18n`Invite to ${i.roomName}`),e.div({className:"InvitePanelView__form"},[s,e.button({className:"InvitePanelView__btn button-action primary",onClick:()=>t.invite(s.value)},"Invite")]),e.div({className:"InvitePanelView__error"},[e.ifView(i=>!!i.errorViewModel,i=>new Vs(i.errorViewModel))])])}}class Tf extends E{render(e){return e.div({className:"RightPanelView"},[e.ifView(t=>t.activeViewModel,t=>new Af(t)),e.mapView(t=>t.activeViewModel,t=>this._viewFromType(t))])}_viewFromType(e){switch(e==null?void 0:e.type){case"room-details":return new uf(e);case"member-list":return new vf(e);case"member-details":return new bf(e);case"invite":return new Rf(e);case"verification":return new Fc(e);default:return new Vc}}}class Af extends E{render(e,t){return e.div({className:"RightPanelView_buttons"},[e.button({className:{back:!0,"button-utility":!0,hide:s=>!s.activeViewModel.shouldShowBackButton},onClick:()=>t.showPreviousPanel()}),e.button({className:"close button-utility",onClick:()=>t.closePanel()})])}}class xf extends os{constructor(e){const t={className:"Timeline_messageReactions",tagName:"div",list:e.reactions,onItemClick:s=>s.onClick()};super(t,s=>new Vf(s))}}class Vf extends E{render(e,t){return e.button({className:{active:s=>s.isActive,pending:s=>s.isPending}},[t.key," ",s=>`${s.count}`])}onClick(){this.value.toggle()}}class hi extends E{constructor(e,t,s,i="li"){super(e),this._menuPopup=null,this._tagName=i,this._viewClassForTile=t,this._renderFlags=s}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 s=[this.renderMessageBody(e,t)];this._interactive&&s.push(e.button({className:"Timeline_messageOptions"},"\u22EF"));const i=e.el(this._tagName,{className:{Timeline_message:!0,own:t.isOwn,unsent:t.isUnsent,unverified:o=>o.isUnverified,disabled:!this._interactive,continuation:o=>o.isContinuation},"data-event-id":t.eventId},s);e.mapSideEffect(o=>o.isContinuation,(o,c)=>{if(o&&c===!1)i.removeChild(i.querySelector(".Timeline_messageAvatar")),i.removeChild(i.querySelector(".Timeline_messageSender"));else if(!o&&!this._isReplyPreview){const l=H.a({href:t.memberPanelLink,className:"Timeline_messageAvatar"},[Ss(t,30)]),h=H.div({className:`Timeline_messageSender usercolor${t.avatarColorNumber}`,title:t.sender},t.displayName);i.insertBefore(l,i.firstChild),i.insertBefore(h,i.firstChild)}});let r=null;return e.mapSideEffect(o=>o.reactions,o=>{o&&this._interactive&&!r?(r=new xf(o),this.addSubView(r),i.appendChild(Bi(r))):!o&&r&&(i.removeChild(r.root()),r.unmount(),this.removeSubView(r),r=null)}),i}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 s=()=>this.root().classList.remove("menuOpen");this._menuPopup=new Dr(new ue(t),s),this._menuPopup.trackInTemplateView(this),this._menuPopup.showRelativeTo(e,2)}}createMenuOptions(e){const t=[];return e.canReact&&e.shape!=="redacted"&&!e.isPending&&(t.push(new Nf(e)),t.push(ue.option(e.i18n`Reply`,()=>e.startReply()))),e.canAbortSending?t.push(ue.option(e.i18n`Cancel`,()=>e.abortSending())):e.canRedact&&t.push(ue.option(e.i18n`Delete`,()=>e.redact()).setDestructive()),t.push(ue.option(e.i18n`Copy matrix.to permalink`,()=>e.copyPermalink())),t}renderMessageBody(){}}class Nf{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(i=>e.button({onClick:()=>this._vm.react(i)},i)),s=e.button({onClick:()=>{const i=prompt("Enter your reaction (emoji)");i&&this._vm.react(i)}},"\u2026");return e.li({className:"quick-reactions"},[...t,s])}}class Df extends E{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const s=this._viewClassForTile(t);if(!s)throw new Error(`Shape ${t.shape} is unrecognized.`);const i=new s(t,this._viewClassForTile,{reply:!0,interactive:!1});return e.div({className:"ReplyPreviewView"},e.blockquote([e.a({className:"link",target:"_blank",href:t.permaLink},"In reply to"),e.a({className:"pill",target:"_blank",href:t.senderProfileLink},[Ss(t,12,void 0),t.displayName]),e.br(),e.view(i)]))}}class Uf extends E{render(e){return e.blockquote({className:"ReplyPreviewView"},[e.div({className:"Timeline_messageBody statusMessage"},"This reply could not be found.")])}}class Of extends hi{renderMessageBody(e,t){const s=e.time({className:{hidden:!t.time}},t.time),i=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 Uf:o?new Df(o,this._viewClassForTile):null)),r=o=>(o==null?void 0:o.nodeType)!==Node.COMMENT_NODE&&o.className!=="ReplyPreviewView";return e.mapSideEffect(o=>o.body,o=>{for(;r(i.lastChild);)i.removeChild(i.lastChild);for(const c of o.parts)i.appendChild(Lc(c));i.appendChild(s)}),i}}function Pf(n){const e=n.items.map(s=>H.li(Es(s))),t=n.startOffset;return t?H.ol({start:t},e):H.ul(e)}function Ff(n){const e={src:n.src};return n.width&&(e.width=n.width),n.height&&(e.height=n.height),n.alt&&(e.alt=n.alt),n.title&&(e.title=n.title),H.img(e)}function Lf(n){const e=`avatar size-12 usercolor${n.avatarColorNumber}`,t=H.div({class:e},Ft(n.avatarInitials)),s=Es(n.children);return s.unshift(t),H.a({class:"pill",href:n.href,rel:"noopener",target:"_blank"},s)}function Kf(n){const e=[];if(n.head){const s=n.head.map(i=>H.th(Es(i)));e.push(H.thead(H.tr(s)))}const t=[];for(const s of n.body){const i=s.map(r=>H.td(Es(r)));t.push(H.tr(i))}return e.push(H.tbody(t)),H.table(e)}const Bf={header:n=>H["h"+Math.min(6,n.level)](Es(n.inlines)),codeblock:n=>H.pre(H.code(Ft(n.text))),table:n=>Kf(n),code:n=>H.code(Ft(n.text)),text:n=>Ft(n.text),link:n=>H.a({href:n.url,className:"link",target:"_blank",rel:"noopener"},Es(n.inlines)),pill:Lf,format:n=>H[n.format](Es(n.children)),rule:()=>H.hr(),list:Pf,image:Ff,newline:()=>H.br()};function Lc(n){const e=Bf[n.type];return e?e(n):Ft(`[unknown part type ${n.type}]`)}function Es(n){return Array.from(n,Lc)}class Kc extends hi{renderMessageBody(e,t){let i=`padding-top: ${t.height/t.width*100}%;`;t.platform.isIE11&&(i=`height: ${t.height}px`);const r=[e.div({className:"spacer",style:i}),this.renderMedia(e,t),e.time(t.time)],o=e.div({className:{status:!0,hidden:c=>!c.status}},c=>c.status);if(r.push(o),t.isPending){const c=e.progress({min:0,max:100,value:l=>l.uploadPercentage,className:{hidden:l=>!l.isUploading}});r.push(c)}return e.div({className:"Timeline_messageBody"},[e.div({className:"media",style:`max-width: ${t.width}px`,"data-testid":"media"},r),e.if(c=>c.error,c=>c.p({className:"error"},t.error))])}createMenuOptions(e){const t=super.createMenuOptions(e);if(!e.isPending){let s;switch(e.shape){case"image":s=e.i18n`Download image`;break;case"video":s=e.i18n`Download video`;break;default:s=e.i18n`Download media`;break}t.push(ue.option(s,()=>e.downloadMedia()))}return t}}class $f extends Kc{renderMedia(e,t){const s=e.img({src:i=>i.thumbnailUrl,alt:i=>i.label,title:i=>i.label,style:`max-width: ${t.width}px; max-height: ${t.height}px;`});return t.isPending||!t.lightboxUrl?s:e.a({href:t.lightboxUrl},s)}}function Tr(n,e){return new Promise((t,s)=>{let i;const r=c=>{i(),s(c.target.error)},o=()=>{i(),t()};i=()=>{n.removeEventListener(e,o),n.removeEventListener("error",r)},n.addEventListener(e,o),n.addEventListener("error",r)})}async function jf(n){var e;try{if((e=navigator==null?void 0:navigator.clipboard)!=null&&e.writeText)return await navigator.clipboard.writeText(n),!0;{const t=document.createElement("textarea");t.value=n,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t);const s=document.getSelection();if(!s)return console.error("copyPlaintext: Unable to copy text to clipboard in fallback mode because `selection` was null/undefined"),!1;const i=document.createRange();i.selectNode(t),s.removeAllRanges(),s.addRange(i);const r=document.execCommand("copy");return s.removeAllRanges(),document.body.removeChild(t),r||console.error("copyPlaintext: Unable to copy text to clipboard in fallback mode because the `copy` command is unsupported or disabled"),r}}catch(t){console.error("copyPlaintext: Ran into an error",t)}return!1}class qf extends Kc{renderMedia(e){const t=e.video({src:s=>s.videoUrl||`data:${s.mimeType},`,title:s=>s.label,controls:!0,preload:"none",poster:s=>s.thumbnailUrl,onPlay:this._onPlay.bind(this),style:s=>`max-width: ${s.width}px; max-height: ${s.height}px;${s.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 s=e.target;await t.loadVideo();const i=Tr(s,"loadeddata");s.load(),await i,s.play()}catch{}}_onError(e){const t=this.value,s=e.target,i=s.error;if(i instanceof window.MediaError&&i.code===4)if(!s.src.startsWith("data:"))t.setViewError(new Error(`this browser does not support videos of type ${t.mimeType}.`));else return;else t.setViewError(i)}}class Hf extends hi{renderMessageBody(e,t){const s=[];return t.isPending?s.push(i=>i.label):s.push(e.button({className:"link",onClick:()=>t.download()},i=>i.label),e.time(t.time)),e.p({className:"Timeline_messageBody statusMessage"},s)}}class Wf 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.time)])}}class zf extends hi{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},t.label)}}class Gf extends E{constructor(e){super(e)}render(e,t){return e.li({className:"AnnouncementView","data-event-id":t.eventId},e.div(s=>s.announcement))}onClick(){}}class Yf 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(ue.option(e.i18n`Cancel`,()=>e.abortPendingRedaction())),t}}class Jf extends E{constructor(e){super(e)}render(e,t){const s={GapView:!0,isLoading:i=>i.isLoading,isAtTop:i=>i.isAtTop};return e.li({className:s},[e.div({class:"GapView_container"},[e.if(i=>i.showSpinner,i=>ye(i)),e.span(i=>i.status)]),e.if(i=>!!i.errorViewModel,i=>i.view(new Vs(t.errorViewModel,{inline:!0})))])}onClick(){}}class Qf extends E{render(e,t){return e.li({className:"CallTileView AnnouncementView"},e.div([e.if(s=>s.errorViewModel,s=>s.div({className:"CallTileView_error"},s.view(new Vs(t.errorViewModel,{inline:!0})))),e.div([e.div({className:"CallTileView_title"},s=>s.title),e.div({className:"CallTileView_subtitle"},[t.typeLabel," \u2022 ",e.span({className:"CallTileView_memberCount"},s=>s.memberCount)]),e.view(new os({className:"CallTileView_members",tagName:"div",list:t.memberViewModels},s=>new wt(s,24))),e.div(s=>s.duration),e.div([e.button({className:"CallTileView_join button-action primary",hidden:s=>!s.canJoin},"Join"),e.button({className:"CallTileView_leave button-action primary destructive",hidden:s=>!s.canLeave},"Leave")])])]))}onClick(e){e.target.classList.contains("CallTileView_join")?this.value.join():e.target.classList.contains("CallTileView_leave")&&this.value.leave()}}class Xf extends E{render(e,t){return e.h2({className:"DateHeader"},e.time({dateTime:t.machineReadableDate},t.relativeDate))}onClick(){}}class Zf extends E{render(e,t){return e.div({className:"VerificationTileView"},e.mapView(s=>s.status,s=>{switch(s){case Ai.Ready:return new ey(t);case Ai.Cancelled:return new ty(t);case Ai.Completed:return new sy(t);case Ai.InProgress:return new iy(t)}}))}onClick(e){var t;(t=this._subViews)==null||t.forEach(s=>{var i;return(i=s.onClick)==null?void 0:i.call(s,e)})}}class ey extends E{render(e,t){return e.div({className:"VerificationReadyTileView"},[e.div({className:"VerificationTileView__shield"}),e.div({className:"VerificationTileView__description"},[e.div(t.description)]),e.div({className:"VerificationTileView__actions"},[e.button({className:"VerificationTileView__accept button-action primary"},"Accept"),e.button({className:"VerificationTileView__reject button-action secondary"},"Reject")])])}onClick(e){e.target.classList.contains("VerificationTileView__accept")?this.value.accept():e.target.classList.contains("VerificationTileView__reject")&&this.value.reject()}}class ty extends E{render(e,t){return e.div({className:"VerificationCancelledTileView"},[e.div({className:"VerificationTileView__description"},t.i18n`${t.isCancelledByUs?"You":t.sender} cancelled the verification!`)])}}class sy extends E{render(e,t){return e.div({className:"VerificationCompletedTileView"},[e.div({className:"VerificationTileView__description"},[e.div({className:"VerificationTileView__shield"}),e.div(t.i18n`You verified ${t.sender}`)])])}}class iy extends E{render(e,t){return e.div({className:"VerificationInProgressTileView"},[e.div({className:"VerificationTileView__description"},t.i18n`Verification in progress`),e.div({className:"VerificationTileView__actions"},[ye(e)])])}}function Ho(n){switch(n.shape){case me.Gap:return Jf;case me.Announcement:return Gf;case me.Message:case me.MessageStatus:return Of;case me.Image:return $f;case me.Video:return qf;case me.File:return Hf;case me.Location:return Wf;case me.MissingAttachment:return zf;case me.Redacted:return Yf;case me.Call:return Qf;case me.DateHeader:return Xf;case me.Verification:return Zf;default:throw new Error(`Tiles of shape "${n.shape}" are not supported, check the tileClassForEntry function in the view model`)}}class ry extends E{render(e,t){const s=e.input({type:"text",name:"id",id:"id",placeholder:t.i18n`Enter a room id or alias`,disabled:i=>i.joinInProgress});return e.main({className:"JoinRoomView middle"},[e.div({className:"JoinRoomView_header middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Cancel room join`}),e.h2("Join room")]),e.div({className:"JoinRoomView_body centered-column"},[e.form({className:"JoinRoomView_detailsForm form",onSubmit:i=>this.onSubmit(i,s.value)},[e.div({className:"vertical-layout"},[e.div({className:"stretch form-row text"},[e.label({for:"id"},t.i18n`Room id`),s])]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:i=>i.joinInProgress},t.i18n`Join`)]),e.map(i=>i.status,(i,r)=>r.div({className:"JoinRoomView_status"},[ye(r,{hidden:o=>!o.joinInProgress}),r.span(i)]))])])])}onSubmit(e,t){e.preventDefault(),this.value.join(t)}}class ny extends E{render(e,t){return e.div({className:"CallToastNotificationView"},[e.div({className:"CallToastNotificationView__top"},[e.view(new wt(t,24)),e.span({className:"CallToastNotificationView__name"},s=>s.roomName),e.button({className:"button-action CallToastNotificationView__dismiss-btn",onClick:()=>t.dismiss()})]),e.div({className:"CallToastNotificationView__description"},[e.span(t.i18n`Video call started`)]),e.div({className:"CallToastNotificationView__info"},[e.span({className:"CallToastNotificationView__call-type"},t.i18n`Video`),e.span({className:"CallToastNotificationView__member-count"},s=>s.memberCount)]),e.div({className:"CallToastNotificationView__action"},[e.button({className:"button-action primary",onClick:()=>t.join()},t.i18n`Join`)]),e.if(s=>!!s.errorViewModel,s=>s.div({className:"CallView_error"},s.view(new Vs(t.errorViewModel))))])}}class oy extends E{render(e,t){return e.div({className:"VerificationToastNotificationView"},[e.div({className:"VerificationToastNotificationView__top"},[e.span({className:"VerificationToastNotificationView__title"},t.i18n`Device Verification`),e.button({className:"button-action VerificationToastNotificationView__dismiss-btn",onClick:()=>t.dismiss()})]),e.div({className:"VerificationToastNotificationView__description"},[e.span(t.i18n`Do you want to verify device ${t.otherDeviceId}?`)]),e.div({className:"VerificationToastNotificationView__action"},[e.button({className:"button-action primary destructive",onClick:()=>t.dismiss()},t.i18n`Ignore`),e.button({className:"button-action primary",onClick:()=>t.accept()},t.i18n`Accept`)])])}}function ay(n){switch(n.kind){case"calls":return new ny(n);case"verification":return new oy(n);default:throw new Error(`Cannot find view class for notification kind ${n.kind}`)}}class cy extends E{render(e,t){return e.div({className:"ToastCollectionView"},[e.ifView(s=>!!s.toastViewModels,s=>new os({list:t.toastViewModels,parentProvidesUpdates:!1},i=>ay(i)))])}}class ly extends E{render(e,t){return e.div({className:{SessionView:!0,"middle-shown":s=>!!s.activeMiddleViewModel,"right-shown":s=>!!s.rightPanelViewModel}},[e.view(new cy(t.toastCollectionViewModel)),e.view(new tf(t.sessionStatusViewModel)),e.view(new $g(t.leftPanelViewModel)),e.mapView(s=>s.activeMiddleViewModel,()=>t.roomGridViewModel?new sf(t.roomGridViewModel,Ho):t.settingsViewModel?new hf(t.settingsViewModel):t.createRoomViewModel?new df(t.createRoomViewModel):t.joinRoomViewModel?new ry(t.joinRoomViewModel):t.verificationViewModel?new Fc(t.verificationViewModel):t.currentRoomViewModel?t.currentRoomViewModel.kind==="invite"?new Dc(t.currentRoomViewModel):t.currentRoomViewModel.kind==="room"?new xc(t.currentRoomViewModel,Ho):t.currentRoomViewModel.kind==="roomBeingCreated"?new Nc(t.currentRoomViewModel):new Jg(t.currentRoomViewModel):new ni(s=>s.div({className:"room-placeholder"},s.h2(t.i18n`Choose a room on the left side.`)))),e.mapView(s=>s.lightboxViewModel,s=>s?new Xg(s):null),e.mapView(s=>s.rightPanelViewModel,s=>s?new Tf(s):null)])}}function Bc(n){return "3895512102"?n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web/releases/tag/v0.5.1"},`Hydrogen v0.5.1 (${"3895512102"}) on Github`):n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web"},"Hydrogen on Github")}class hy extends E{render(e,t){const s=o=>!!o.isBusy,i=e.input({id:"username",type:"text",placeholder:t.i18n`Username`,disabled:s}),r=e.input({id:"password",type:"password",placeholder:t.i18n`Password`,disabled:s});return e.div({className:"PasswordLoginView form"},[e.if(o=>o.error,o=>o.div({className:"error"},c=>c.error)),e.form({onSubmit:o=>{o.preventDefault(),t.login(i.value,r.value)}},[e.if(o=>o.errorMessage,(o,c)=>o.p({className:"error"},c.i18n(c.errorMessage))),e.div({className:"form-row text"},[e.label({for:"username"},t.i18n`Username`),i]),e.div({className:"form-row text"},[e.label({for:"password"},t.i18n`Password`),r]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:s},t.i18n`Log In`)])])])}}class dy extends E{render(e,t){return e.div({className:"Settings"},[e.h3(t.i18n`Restore your encrypted history?`),e.ifView(s=>s.decryptDehydratedDeviceViewModel,s=>new Uc(s.decryptDehydratedDeviceViewModel)),e.map(s=>s.deviceDecrypted,(s,i)=>s?i.p(t.i18n`That worked out, you're good to go!`):i.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"},s=>s.deviceDecrypted?s.i18n`Continue`:s.i18n`Continue without restoring`)])])}}class Ur extends E{render(e){const t=e.if(i=>i.hasError,(i,r)=>i.button({onClick:()=>r.exportLogs()},r.i18n`Export logs`)),s=e.if(i=>i.hasError,(i,r)=>i.button({onClick:()=>r.logout()},r.i18n`Log out`));return e.div({className:"SessionLoadStatusView"},[e.p({className:"status"},[ye(e,{hidden:i=>!i.loading}),e.p(i=>i.loadLabel),t,s]),e.ifView(i=>i.accountSetupViewModel,i=>new dy(i.accountSetupViewModel))])}}class uy extends E{render(e){return e.div({className:"CompleteSSOView"},[e.p({className:"CompleteSSOView_title"},"Finishing up your SSO Login"),e.if(t=>t.errorMessage,(t,s)=>t.p({className:"error"},s.i18n(s.errorMessage))),e.mapView(t=>t.loadViewModel,t=>t?new Ur(t):null)])}}class my extends E{render(e,t){const s=i=>i.isBusy;return e.div({className:"PreSessionScreen"},[e.button({className:"button-utility LoginView_back",onClick:()=>t.goBack(),disabled:s}),e.div({className:"logo"}),e.h1([t.i18n`Sign In`]),e.mapView(i=>i.completeSSOLoginViewModel,i=>i?new uy(i):null),e.if(i=>i.showHomeserver,(i,r)=>i.div({className:"LoginView_sso form-row text"},[i.label({for:"homeserver"},r.i18n`Homeserver`),i.input({id:"homeserver",type:"text",placeholder:r.i18n`Your matrix homeserver`,value:r.homeserver,disabled:s,onInput:o=>r.setHomeserver(o.target.value),onChange:()=>r.queryHomeserver()}),i.p({className:{LoginView_forwardInfo:!0,hidden:o=>!o.resolvedHomeserver}},o=>o.i18n`You will connect to ${o.resolvedHomeserver}.`),i.if(o=>o.errorMessage,(o,c)=>o.p({className:"error"},c.i18n(c.errorMessage)))])),e.if(i=>i.isFetchingLoginOptions,i=>i.div({className:"LoginView_query-spinner"},[ye(i),i.p("Fetching available login options...")])),e.mapView(i=>i.passwordLoginViewModel,i=>i?new hy(i):null),e.if(i=>i.passwordLoginViewModel&&i.startSSOLoginViewModel,i=>i.p({className:"LoginView_separator"},t.i18n`or`)),e.mapView(i=>i.startSSOLoginViewModel,i=>i?new _y(i):null),e.mapView(i=>i.loadViewModel,i=>i?new Ur(i):null),e.p(Bc(e))])}}class _y extends E{render(e,t){return e.div({className:"StartSSOLoginView"},e.button({className:"StartSSOLoginView_button button-action secondary",type:"button",onClick:()=>t.startSSOLogin(),disabled:s=>s.isBusy},t.i18n`Log in with SSO`))}}class py extends E{render(e,t){const s=new $i(t,r=>r.div([r.p("Are you sure you want to log out?"),r.div({className:"button-row"},[r.a({className:"button-action",type:"submit",href:t.cancelUrl},["Cancel"]),r.button({className:"button-action primary destructive",type:"submit",onClick:()=>t.logout()},t.i18n`Log out`)])])),i=new $i(t,r=>r.p({className:"status",hidden:o=>!o.showStatus},[ye(r,{hidden:o=>!o.busy}),r.span(o=>o.status)]));return e.div({className:"LogoutScreen"},[e.div({className:"content"},[e.mapView(r=>r.showConfirm,r=>r?s:i)])])}}class gy extends E{render(e){return e.div({className:"LogoutScreen"},[e.div({className:"content"},e.map(t=>t.showStatus,(t,s,i)=>t?s.p({className:"status"},[ye(s,{hidden:r=>!r.showSpinner}),s.span(r=>r.status)]):s.div([s.p("Your access token is no longer valid! You can reauthenticate in the next screen."),s.div({className:"button-row"},[s.button({className:"button-action primary",type:"submit",onClick:()=>i.proceed()},i.i18n`Proceed`)])])))])}}class fy extends E{render(e,t){return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionLoadView"},[e.view(new Ur(t))]),e.div({className:{"button-row":!0,hidden:s=>s.loading}},e.a({className:"button-action primary",href:t.backUrl},t.i18n`Go back`))])}}class yy extends E{_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}`},s=>s.avatarInitials),e.div({className:"user-id"},s=>s.label)])])}}class wy extends E{render(e,t){const s=new os({list:t.sessions,parentProvidesUpdates:!1},i=>new yy(i));return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionPickerView"},[e.h1(["Continue as \u2026"]),e.view(s),e.div({className:"button-row"},[e.a({className:"button-action primary",href:t.cancelUrl},t.i18n`Sign In`)]),e.ifView(i=>i.loadViewModel,()=>new Ur(t.loadViewModel)),e.p(Bc(e))])])}}class vy extends E{render(e,t){return e.mapView(s=>s.activeSection,s=>{switch(s){case"error":return new ni(i=>i.div({className:"StatusView"},[i.h1("Something went wrong"),i.p(t.errorText)]));case"session":return new ly(t.sessionViewModel);case"login":return new my(t.loginViewModel);case"logout":return new py(t.logoutViewModel);case"forced-logout":return new gy(t.forcedLogoutViewModel);case"picker":return new wy(t.sessionPickerViewModel);case"redirecting":return new ni(i=>i.p("Redirecting..."));case"loading":return new fy(t.sessionLoadViewModel);default:throw new Error(`Unknown section: ${t.activeSection}`)}})}}class by{constructor(e){this._reject=null,this._handle=null,this._promise=new Promise((t,s)=>{this._reject=s,this._handle=setTimeout(()=>{this._reject=null,t()},e)})}elapsed(){return this._promise}abort(){this._reject&&(this._reject(new rt),clearTimeout(this._handle),this._handle=null,this._reject=null)}dispose(){this.abort()}}class Sy{constructor(e,t){this._handle=setInterval(t,e)}dispose(){this._handle&&(clearInterval(this._handle),this._handle=null)}}class ky{constructor(){this._start=window.performance.now()}measure(){return window.performance.now()-this._start}}class Iy{createMeasure(){return new ky}createTimeout(e){return new by(e)}createInterval(e,t){return new Sy(t,e)}now(){return Date.now()}}class My{constructor(e){this._waitingForReply=new Map,this._messageIdCounter=0,this._navigation=null,this._registration=null,this._registrationPromise=null,this._currentController=null,this._sessionInfoStorage=e,this.haltRequests=!1,this._authData={}}setNavigation(e){this._navigation=e}updateAuthData(e){if(!e.accessToken&&!e.homeserver)throw new Error("updateAuthData argument must contain accessToken, homeserver or both!");this._authData=It(It({},this._authData),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")})()}async _onMessage(e){const{data:t}=e,s=t.replyTo;if(s){const i=this._waitingForReply.get(s);i&&(this._waitingForReply.delete(s),i(t.payload))}if(t.type==="hasSessionOpen"){const i=this._navigation.observe("session").get()===t.payload.sessionId;e.source.postMessage({replyTo:t.id,payload:i})}else if(t.type==="hasRoomOpen"){const i=this._navigation.observe("session").get()===t.payload.sessionId,r=this._navigation.observe("room").get()===t.payload.roomId;e.source.postMessage({replyTo:t.id,payload:i&&r})}else if(t.type==="closeSession"){const{sessionId:i}=t.payload;this._closeSessionIfNeeded(i).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):t.type==="getAuthInfo"&&e.source.postMessage({replyTo:t.id,payload:this._authData})}_closeSessionIfNeeded(e){var s;const t=(s=this._navigation)==null?void 0:s.path.get("session");return e&&(t==null?void 0:t.value)===e?new Promise(i=>{const r=this._navigation.pathObservable.subscribe(o=>{const c=o.get("session");(!c||c.value!==e)&&(r(),i())});this._navigation.push("session")}):Promise.resolve()}async _proposeUpdate(){if(document.hidden)return;const e=await this._sendAndWaitForReply("version",null,this._registration.waiting);(this.version==="develop"||confirm(`Version ${e.version} (${e.buildHash}) is available. Reload to apply?`))&&(console.log("Service Worker has been updated!"),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,s=void 0){this._registrationPromise&&await this._registrationPromise,s||(s=this._registration.active),s.postMessage({type:e,payload:t})}async _sendAndWaitForReply(e,t,s=void 0){this._registrationPromise&&await this._registrationPromise,s||(s=this._registration.active),this._messageIdCounter+=1;const i=this._messageIdCounter,r=new Promise(o=>{this._waitingForReply.set(i,o)});return s.postMessage({type:e,id:i,payload:t}),await r}async checkForUpdate(){this._registrationPromise&&await this._registrationPromise,this._registration.update()}get version(){return"0.5.1"}get buildHash(){return "3895512102"}async preventConcurrentSessionAccess(e){return this._sendAndWaitForReply("closeSession",{sessionId:e})}async getRegistration(){return this._registrationPromise&&await this._registrationPromise,this._registration}}class Cy{constructor(e,t){this._serviceWorkerHandler=e,this._pushConfig=t}async enablePush(e,t){var i;const s=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());if(s!=null&&s.pushManager){const o=(await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this._pushConfig.applicationServerKey})).toJSON(),c=o.keys.p256dh,l={endpoint:o.endpoint,auth:o.keys.auth,events_only:!0,default_payload:t};return e.httpPusher(this._pushConfig.gatewayUrl,this._pushConfig.appId,c,l)}}async disablePush(){var t;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());if(e!=null&&e.pushManager){const s=await e.pushManager.getSubscription();s&&await s.unsubscribe()}}async isPushEnabled(){var t;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());return e!=null&&e.pushManager?!!await e.pushManager.getSubscription():!1}async supportsPush(){var t;if(!this._pushConfig)return!1;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());return e&&"pushManager"in e}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 s=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());s==null||s.showNotification(e,{body:t})}}class Ey extends yt{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 Ry extends yt{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 Ie(n,e){return n instanceof Promise?n:new Promise((t,s)=>{n.oncomplete=i=>t(i.target.result),n.onerror=()=>s(new Error("Crypto error on "+e))})}class Ty{constructor(e){this._subtleCrypto=e}async verify(e,t,s,i){const r={name:"HMAC",hash:{name:Rs(i)}},o=await Ie(this._subtleCrypto.importKey("raw",e,r,!1,["verify"]),"importKey");return await Ie(this._subtleCrypto.verify(r,o,t,s),"verify")}async compute(e,t,s){const i={name:"HMAC",hash:{name:Rs(s)}},r=await Ie(this._subtleCrypto.importKey("raw",e,i,!1,["sign"]),"importKey"),o=await Ie(this._subtleCrypto.sign(i,r,t),"sign");return new Uint8Array(o)}}class Ay{constructor(e,t,s){this._subtleCrypto=e,this._crypto=t,this._cryptoExtras=s}async pbkdf2(e,t,s,i,r){if(!this._subtleCrypto.deriveBits)throw new Error("PBKDF2 is not supported");const o=await Ie(this._subtleCrypto.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),"importKey"),c=await Ie(this._subtleCrypto.deriveBits({name:"PBKDF2",salt:s,iterations:t,hash:Rs(i)},o,r),"deriveBits");return new Uint8Array(c)}async hkdf(e,t,s,i,r){if(!this._subtleCrypto.deriveBits)return this._cryptoExtras.hkdf(this._crypto,e,t,s,i,r);const o=await Ie(this._subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),"importKey"),c=await Ie(this._subtleCrypto.deriveBits({name:"HKDF",salt:t,info:s,hash:Rs(i)},o,r),"deriveBits");return new Uint8Array(c)}}class xy{constructor(e,t){this._subtleCrypto=e,this._crypto=t}async decryptCTR({key:e,jwkKey:t,iv:s,data:i,counterLength:r=64}){const o={name:"AES-CTR",counter:s,length:r};let c;try{const l=e||t,h=t?"jwk":"raw";c=await Ie(this._subtleCrypto.importKey(h,l,o,!1,["decrypt"]),"importKey")}catch(l){throw new Error(`Could not import key for AES-CTR decryption: ${l.message}`)}try{const l=await Ie(this._subtleCrypto.decrypt(o,c,i),"decrypt");return new Uint8Array(l)}catch(l){throw new Error(`Could not decrypt with AES-CTR: ${l.message}`)}}async encryptCTR({key:e,jwkKey:t,iv:s,data:i}){const r={name:"AES-CTR",counter:s,length:64};let o;const c=e||t,l=t?"jwk":"raw";try{o=await Ie(this._subtleCrypto.importKey(l,c,r,!1,["encrypt"]),"importKey")}catch(h){throw new Error(`Could not import key for AES-CTR encryption: ${h.message}`)}try{const h=await Ie(this._subtleCrypto.encrypt(r,o,i),"encrypt");return new Uint8Array(h)}catch(h){throw new Error(`Could not encrypt with AES-CTR: ${h.message}`)}}async generateKey(e,t=256){const s=await Ie(this._subtleCrypto.generateKey({name:"AES-CTR",length:t},!0,["encrypt","decrypt"]));return Ie(this._subtleCrypto.exportKey(e,s))}async generateIV(){return $c(this._crypto)}}function $c(n){const e=n.getRandomValues(new Uint8Array(8)),t=new Uint8Array(16);for(let s=0;s{this._resolve=s,this._reject=i}),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 Ky{constructor(e,t){this._workers=[];for(let s=0;s{this._init={resolve:t,reject:s}});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,s=this._requests.get(t.replyToId);if(s){if(s._worker.busy=!1,s._isNotDisposed){if(t.type==="success")s._resolve(t.payload);else if(t.type==="error"){const i=new Error(t.message);i.stack=t.stack,s._reject(i)}s._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 s=this._getFreeWorker();s&&(this._sendWith(t,s),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 Ly(e,this);return this._requests.set(e.id,t),t}send(e){const t=this._enqueueRequest(e),s=this._getFreeWorker();return s&&this._sendWith(t,s),t}sendAll(e){const t=this._workers.map(s=>{const i=this._enqueueRequest(Object.assign({},e));return this._sendWith(i,s),i.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 rt),e._worker&&(e._worker.busy=!1),this._requests.delete(e._message.id),this._trySendPendingInNextTick()}}class ji{static async fromBlob(e){const t=await zo(e),{width:s,height:i}=t;return new ji(e,s,i,t)}constructor(e,t,s,i){this.blob=e,this.width=t,this.height=s,this._domElement=i}get maxDimension(){return Math.max(this.width,this.height)}async _getDomElement(){return this._domElement||(this._domElement=await zo(this.blob)),this._domElement}async scale(e){const t=this.width/this.height,s=Math.min(1,e/(t>=1?this.width:this.height)),i=Math.round(this.width*s),r=Math.round(this.height*s),o=document.createElement("canvas");o.width=i,o.height=r;const c=o.getContext("2d"),l=await this._getDomElement();c.drawImage(l,0,0,i,r);let h=this.blob.mimeType==="image/jpeg"?"image/jpeg":"image/png",a;if(o.toBlob)a=await new Promise(p=>o.toBlob(p,h));else if(o.msToBlob)h="image/png",a=o.msToBlob();else throw new Error("canvas can't be turned into blob");const u=Ts.fromBlobUnsafe(a);return new ji(u,i,r,null)}dispose(){this.blob.dispose()}}class Bn extends ji{get duration(){if(typeof this._domElement.duration=="number")return Math.round(this._domElement.duration*1e3)}static async fromBlob(e){const t=await $y(e),{videoWidth:s,videoHeight:i}=t;return new Bn(e,s,i,t)}}function By(){const n=document.createElement("canvas");n.width=1,n.height=1;const e=n.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 s=e.getImageData(0,0,1,1).data;return s[0]===t[0]&&s[1]===t[1]&&s[2]===t[2]}async function zo(n){const e=document.createElement("img"),t=Tr(e,"load");return e.src=n.url,await t,e}async function $y(n){const e=document.createElement("video");e.muted=!0;const t=Tr(e,"loadedmetadata");e.src=n.url,e.load(),await t;const s=Tr(e,"seeked");return await new Promise(i=>setTimeout(i,200)),e.currentTime=.1,await s,e}async function jy(n,e,t,s,i){let r=n.querySelector("iframe.downloadSandbox");if(!r){r=document.createElement("iframe"),r.setAttribute("sandbox","allow-scripts allow-downloads allow-downloads-without-user-activation"),r.setAttribute("src",e),r.className="hidden downloadSandbox",n.appendChild(r);let o;await new Promise((c,l)=>{o=()=>{r.removeEventListener("load",c),r.removeEventListener("error",l)},r.addEventListener("load",c),r.addEventListener("error",l)}),o()}if(i){const o=await t.readAsBuffer();r.contentWindow.postMessage({type:"downloadBuffer",buffer:o,mimeType:t.mimeType,filename:s},"*")}else r.contentWindow.postMessage({type:"downloadBlob",blob:t.nativeBlob,filename:s},"*")}/*! @license DOMPurify 2.3.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.3.0/LICENSE */function qy(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e1?t-1:0),i=1;i/gm),rw=Bt(/^data-[\-\w.\u00B7-\uFFFF]/),nw=Bt(/^aria-[\-\w]+$/),ow=Bt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),aw=Bt(/^(?:\w+script|data):/i),cw=Bt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n};function ut(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e0&&arguments[0]!==void 0?arguments[0]:lw(),e=function(y){return qc(y)};if(e.version="2.3.0",e.removed=[],!n||!n.document||n.document.nodeType!==9)return e.isSupported=!1,e;var t=n.document,s=n.document,i=n.DocumentFragment,r=n.HTMLTemplateElement,o=n.Node,c=n.Element,l=n.NodeFilter,h=n.NamedNodeMap,a=h===void 0?n.NamedNodeMap||n.MozNamedAttrMap:h,u=n.Text,p=n.Comment,g=n.DOMParser,f=n.trustedTypes,v=c.prototype,M=mr(v,"cloneNode"),R=mr(v,"nextSibling"),N=mr(v,"childNodes"),F=mr(v,"parentNode");if(typeof r=="function"){var T=s.createElement("template");T.content&&T.content.ownerDocument&&(s=T.content.ownerDocument)}var D=hw(f,t),B=D&&us?D.createHTML(""):"",G=s,$e=G.implementation,Ns=G.createNodeIterator,di=G.createDocumentFragment,as=G.getElementsByTagName,cs=t.importNode,Ds={};try{Ds=zs(s).documentMode?s.documentMode:{}}catch{}var Ue={};e.isSupported=typeof F=="function"&&$e&&typeof $e.createHTMLDocument!="undefined"&&Ds!==9;var Us=sw,U=iw,zi=rw,Ht=nw,Wt=aw,ui=cw,Je=ow,re=null,Os=j({},[].concat(ut(Xo),ut(Wr),ut(zr),ut(Gr),ut(Zo))),ie=null,Ps=j({},[].concat(ut(ea),ut(Yr),ut(ta),ut(_r))),ls=null,hs=null,mi=!0,Fs=!0,_i=!1,vt=!1,zt=!1,Qe=!1,bt=!1,je=!1,ds=!1,we=!0,us=!1,pi=!0,gi=!0,St=!1,at={},Ls=j({},["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"]),Xe=null,Gt=j({},["audio","video","img","source","image","track"]),Ks=null,Gi=j({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Bs="http://www.w3.org/1998/Math/MathML",$s="http://www.w3.org/2000/svg",Ze="http://www.w3.org/1999/xhtml",kt=Ze,js=!1,ge=null,ve=s.createElement("form"),Te=function(y){ge&&ge===y||((!y||(typeof y=="undefined"?"undefined":xi(y))!=="object")&&(y={}),y=zs(y),re="ALLOWED_TAGS"in y?j({},y.ALLOWED_TAGS):Os,ie="ALLOWED_ATTR"in y?j({},y.ALLOWED_ATTR):Ps,Ks="ADD_URI_SAFE_ATTR"in y?j(zs(Gi),y.ADD_URI_SAFE_ATTR):Gi,Xe="ADD_DATA_URI_TAGS"in y?j(zs(Gt),y.ADD_DATA_URI_TAGS):Gt,ls="FORBID_TAGS"in y?j({},y.FORBID_TAGS):{},hs="FORBID_ATTR"in y?j({},y.FORBID_ATTR):{},at="USE_PROFILES"in y?y.USE_PROFILES:!1,mi=y.ALLOW_ARIA_ATTR!==!1,Fs=y.ALLOW_DATA_ATTR!==!1,_i=y.ALLOW_UNKNOWN_PROTOCOLS||!1,vt=y.SAFE_FOR_TEMPLATES||!1,zt=y.WHOLE_DOCUMENT||!1,je=y.RETURN_DOM||!1,ds=y.RETURN_DOM_FRAGMENT||!1,we=y.RETURN_DOM_IMPORT!==!1,us=y.RETURN_TRUSTED_TYPE||!1,bt=y.FORCE_BODY||!1,pi=y.SANITIZE_DOM!==!1,gi=y.KEEP_CONTENT!==!1,St=y.IN_PLACE||!1,Je=y.ALLOWED_URI_REGEXP||Je,kt=y.NAMESPACE||Ze,vt&&(Fs=!1),ds&&(je=!0),at&&(re=j({},[].concat(ut(Zo))),ie=[],at.html===!0&&(j(re,Xo),j(ie,ea)),at.svg===!0&&(j(re,Wr),j(ie,Yr),j(ie,_r)),at.svgFilters===!0&&(j(re,zr),j(ie,Yr),j(ie,_r)),at.mathMl===!0&&(j(re,Gr),j(ie,ta),j(ie,_r))),y.ADD_TAGS&&(re===Os&&(re=zs(re)),j(re,y.ADD_TAGS)),y.ADD_ATTR&&(ie===Ps&&(ie=zs(ie)),j(ie,y.ADD_ATTR)),y.ADD_URI_SAFE_ATTR&&j(Ks,y.ADD_URI_SAFE_ATTR),gi&&(re["#text"]=!0),zt&&j(re,["html","head","body"]),re.table&&(j(re,["tbody"]),delete ls.tbody),Ce&&Ce(y),ge=y)},Ae=j({},["mi","mo","mn","ms","mtext"]),ms=j({},["foreignobject","desc","title","annotation-xml"]),qe=j({},Wr);j(qe,zr),j(qe,ew);var He=j({},Gr);j(He,tw);var xe=function(y){var b=F(y);(!b||!b.tagName)&&(b={namespaceURI:Ze,tagName:"template"});var C=vs(y.tagName),O=vs(b.tagName);if(y.namespaceURI===$s)return b.namespaceURI===Ze?C==="svg":b.namespaceURI===Bs?C==="svg"&&(O==="annotation-xml"||Ae[O]):Boolean(qe[C]);if(y.namespaceURI===Bs)return b.namespaceURI===Ze?C==="math":b.namespaceURI===$s?C==="math"&&ms[O]:Boolean(He[C]);if(y.namespaceURI===Ze){if(b.namespaceURI===$s&&!ms[O]||b.namespaceURI===Bs&&!Ae[O])return!1;var oe=j({},["title","style","font","a","script"]);return!He[C]&&(oe[C]||!qe[C])}return!1},Ve=function(y){Mi(e.removed,{element:y});try{y.parentNode.removeChild(y)}catch{try{y.outerHTML=B}catch{y.remove()}}},Yt=function(y,b){try{Mi(e.removed,{attribute:b.getAttributeNode(y),from:b})}catch{Mi(e.removed,{attribute:null,from:b})}if(b.removeAttribute(y),y==="is"&&!ie[y])if(je||ds)try{Ve(b)}catch{}else try{b.setAttribute(y,"")}catch{}},We=function(y){var b=void 0,C=void 0;if(bt)y=""+y;else{var O=Jo(y,/^[\r\n\t ]+/);C=O&&O[0]}var oe=D?D.createHTML(y):y;if(kt===Ze)try{b=new g().parseFromString(oe,"text/html")}catch{}if(!b||!b.documentElement){b=$e.createDocument(kt,"template",null);try{b.documentElement.innerHTML=js?"":oe}catch{}}var he=b.body||b.documentElement;return y&&C&&he.insertBefore(s.createTextNode(C),he.childNodes[0]||null),kt===Ze?as.call(b,zt?"html":"body")[0]:zt?b.documentElement:he},Ne=function(y){return Ns.call(y.ownerDocument||y,y,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT,null,!1)},Z=function(y){return y instanceof u||y instanceof p?!1:typeof y.nodeName!="string"||typeof y.textContent!="string"||typeof y.removeChild!="function"||!(y.attributes instanceof a)||typeof y.removeAttribute!="function"||typeof y.setAttribute!="function"||typeof y.namespaceURI!="string"||typeof y.insertBefore!="function"},Y=function(y){return(typeof o=="undefined"?"undefined":xi(o))==="object"?y instanceof o:y&&(typeof y=="undefined"?"undefined":xi(y))==="object"&&typeof y.nodeType=="number"&&typeof y.nodeName=="string"},le=function(y,b,C){!Ue[y]||Jy(Ue[y],function(O){O.call(e,b,C,ge)})},be=function(y){var b=void 0;if(le("beforeSanitizeElements",y,null),Z(y)||Jo(y.nodeName,/[\u0080-\uFFFF]/))return Ve(y),!0;var C=vs(y.nodeName);if(le("uponSanitizeElement",y,{tagName:C,allowedTags:re}),!Y(y.firstElementChild)&&(!Y(y.content)||!Y(y.content.firstElementChild))&&Qt(/<[/\w]/g,y.innerHTML)&&Qt(/<[/\w]/g,y.textContent))return Ve(y),!0;if(!re[C]||ls[C]){if(gi&&!Ls[C]){var O=F(y)||y.parentNode,oe=N(y)||y.childNodes;if(oe&&O)for(var he=oe.length,d=he-1;d>=0;--d)O.insertBefore(M(oe[d],!0),R(y))}return Ve(y),!0}return y instanceof c&&!xe(y)||(C==="noscript"||C==="noembed")&&Qt(/<\/no(script|embed)/i,y.innerHTML)?(Ve(y),!0):(vt&&y.nodeType===3&&(b=y.textContent,b=Jt(b,Us," "),b=Jt(b,U," "),y.textContent!==b&&(Mi(e.removed,{element:y.cloneNode()}),y.textContent=b)),le("afterSanitizeElements",y,null),!1)},I=function(y,b,C){if(pi&&(b==="id"||b==="name")&&(C in s||C in ve))return!1;if(!(Fs&&!hs[b]&&Qt(zi,b))){if(!(mi&&Qt(Ht,b))){if(!ie[b]||hs[b])return!1;if(!Ks[b]){if(!Qt(Je,Jt(C,ui,""))){if(!((b==="src"||b==="xlink:href"||b==="href")&&y!=="script"&&Qy(C,"data:")===0&&Xe[y])){if(!(_i&&!Qt(Wt,Jt(C,ui,"")))){if(C)return!1}}}}}}return!0},K=function(y){var b=void 0,C=void 0,O=void 0,oe=void 0;le("beforeSanitizeAttributes",y,null);var he=y.attributes;if(!!he){var d={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ie};for(oe=he.length;oe--;){b=he[oe];var m=b,_=m.name,w=m.namespaceURI;if(C=Xy(b.value),O=vs(_),d.attrName=O,d.attrValue=C,d.keepAttr=!0,d.forceKeepAttr=void 0,le("uponSanitizeAttribute",y,d),C=d.attrValue,!d.forceKeepAttr&&(Yt(_,y),!!d.keepAttr)){if(Qt(/\/>/i,C)){Yt(_,y);continue}vt&&(C=Jt(C,Us," "),C=Jt(C,U," "));var k=y.nodeName.toLowerCase();if(!!I(k,O,C))try{w?y.setAttributeNS(w,_,C):y.setAttribute(_,C),Yo(e.removed)}catch{}}}le("afterSanitizeAttributes",y,null)}},x=function S(y){var b=void 0,C=Ne(y);for(le("beforeSanitizeShadowDOM",y,null);b=C.nextNode();)le("uponSanitizeShadowNode",b,null),!be(b)&&(b.content instanceof i&&S(b.content),K(b));le("afterSanitizeShadowDOM",y,null)};return e.sanitize=function(S,y){var b=void 0,C=void 0,O=void 0,oe=void 0,he=void 0;if(js=!S,js&&(S=""),typeof S!="string"&&!Y(S)){if(typeof S.toString!="function")throw Qo("toString is not a function");if(S=S.toString(),typeof S!="string")throw Qo("dirty is not a string, aborting")}if(!e.isSupported){if(xi(n.toStaticHTML)==="object"||typeof n.toStaticHTML=="function"){if(typeof S=="string")return n.toStaticHTML(S);if(Y(S))return n.toStaticHTML(S.outerHTML)}return S}if(Qe||Te(y),e.removed=[],typeof S=="string"&&(St=!1),!St)if(S instanceof o)b=We(""),C=b.ownerDocument.importNode(S,!0),C.nodeType===1&&C.nodeName==="BODY"||C.nodeName==="HTML"?b=C:b.appendChild(C);else{if(!je&&!vt&&!zt&&S.indexOf("<")===-1)return D&&us?D.createHTML(S):S;if(b=We(S),!b)return je?null:B}b&&bt&&Ve(b.firstChild);for(var d=Ne(St?S:b);O=d.nextNode();)O.nodeType===3&&O===oe||be(O)||(O.content instanceof i&&x(O.content),K(O),oe=O);if(oe=null,St)return S;if(je){if(ds)for(he=di.call(b.ownerDocument);b.firstChild;)he.appendChild(b.firstChild);else he=b;return we&&(he=cs.call(t,he,!0)),he}var m=zt?b.outerHTML:b.innerHTML;return vt&&(m=Jt(m,Us," "),m=Jt(m,U," ")),D&&us?D.createHTML(m):m},e.setConfig=function(S){Te(S),Qe=!0},e.clearConfig=function(){ge=null,Qe=!1},e.isValidAttribute=function(S,y,b){ge||Te({});var C=vs(S),O=vs(y);return I(C,O,b)},e.addHook=function(S,y){typeof y=="function"&&(Ue[S]=Ue[S]||[],Mi(Ue[S],y))},e.removeHook=function(S){Ue[S]&&Yo(Ue[S])},e.removeHooks=function(S){Ue[S]&&(Ue[S]=[])},e.removeAllHooks=function(){Ue={}},e}var dw=qc();class uw{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 mw={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 _w(n){const e=dw.sanitize(n,mw),t=new DOMParser().parseFromString(`${e}`,"text/html").body;return new uw(t)}const pw=200,gw=-60,fw=8;class yw{constructor(e){this.mediaDevices=e}enumerate(){return this.mediaDevices.enumerateDevices()}async getMediaTracks(e,t){const s=await this.mediaDevices.getUserMedia(this.getUserMediaContraints(e,t));return s.addEventListener("removetrack",i=>{console.log(`removing track ${i.track.id} (${i.track.kind}) from stream ${s.id}`)}),s}async getScreenShareTrack(){return await this.mediaDevices.getDisplayMedia(this.getScreenshareContraints())}getUserMediaContraints(e,t){const s=!!navigator.webkitGetUserMedia;return{audio:e?{deviceId:typeof e!="boolean"?{ideal:e.deviceId}:void 0}:!1,video:t?{deviceId:typeof t!="boolean"?{ideal:t.deviceId}:void 0,width:s?{exact:640}:{ideal:640},height:s?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(){return{audio:!1,video:!0}}createVolumeMeasurer(e,t){return new ww(e,t)}}class ww{constructor(e,t){this.measuringVolumeActivity=!1,this.speakingThreshold=gw,this.speaking=!1,this.volumeLooper=()=>{if(!this.analyser||!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let s=-1/0;for(let r=0;rs&&(s=this.frequencyBinCount[r]);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(s),this.callback();let i=!1;for(let r=0;rthis.speakingThreshold){i=!0;break}this.speaking!==i&&(this.speaking=i,this.callback()),this.volumeLooperTimeout=setTimeout(this.volumeLooper,pw)},this.stream=e,this.callback=t,this.speakingVolumeSamples=new Array(fw).fill(-1/0),this.initVolumeMeasuring(),this.measureVolumeActivity(!0)}get isSpeaking(){return this.speaking}measureVolumeActivity(e){if(e){if(!this.audioContext||!this.analyser||!this.frequencyBinCount)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.callback()}initVolumeMeasuring(){const e=window.AudioContext||window.webkitAudioContext;if(!e)return;this.audioContext=new e,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}setSpeakingThreshold(e){this.speakingThreshold=e}stop(){var e;clearTimeout(this.volumeLooperTimeout),this.analyser.disconnect(),(e=this.audioContext)==null||e.close()}}class vw{createPeerConnection(e,t,s){const i=new RTCPeerConnection({iceTransportPolicy:e?"relay":void 0,iceServers:t,iceCandidatePoolSize:s});return new Proxy(i,{get(r,o,c){o==="close"&&console.trace("calling peerConnection.close");const l=r[o];return typeof l=="function"?l.bind(r):l}})}prepareSenderForPurpose(e,t,s){s===Zt.Screenshare&&this.getRidOfRTXCodecs(e,t)}getRidOfRTXCodecs(e,t){var c,l,h,a,u,p;if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const s=(l=(c=RTCRtpReceiver.getCapabilities("video"))==null?void 0:c.codecs)!=null?l:[],r=[...(a=(h=RTCRtpSender.getCapabilities("video"))==null?void 0:h.codecs)!=null?a:[],...s];for(const g of r)if(g.mimeType==="video/rtx"){const f=r.indexOf(g);r.splice(f,1)}const o=e.getTransceivers().find(g=>g.sender===t);o&&(((u=o.sender.track)==null?void 0:u.kind)==="video"||((p=o.receiver.track)==null?void 0:p.kind)==="video")&&o.setCodecPreferences(r)}}var es=(n=>(n[n.Dark=0]="Dark",n[n.Light=1]="Light",n))(es||{});function bw(n,e,t){let s=n.replaceAll("#ff00ff",e);if(s=s.replaceAll("#00ffff",t),n===s)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 s}class Sw{constructor(e,t,s,i){this._platform=e,this._iconVariables=t,this._resolvedVariables=s,this._manifestLocation=i}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[s,i]of Object.entries(this._iconVariables)){const r=new URL(`https://${i}`),o=r.hostname,c=new URL(o,new URL(this._manifestLocation,window.location.origin)),l=this._platform.request(c,{method:"GET",format:"text",cache:!0}).response();e.push(l);const h=r.searchParams;t[s]={svg:l,primary:h.get("primary"),secondary:h.get("secondary")}}return{parsedStructure:t,promises:e}}async _produceColoredIconVariables(e){let t={};for(const[s,{svg:i,primary:r,secondary:o}]of Object.entries(e)){const{body:c}=await i;if(!r)throw new Error(`Primary color variable ${r} not in list of variables!`);const l=this._resolvedVariables[r],h=this._resolvedVariables[o],a=bw(c,l,h),u=`url('data:image/svg+xml;utf8,${encodeURIComponent(a)}')`;t[s]=u}return t}}var Or={exports:{}},kw=function(n){var e={};function t(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return n[s].call(i.exports,i,i.exports,t),i.l=!0,i.exports}return t.m=n,t.c=e,t.d=function(s,i,r){t.o(s,i)||Object.defineProperty(s,i,{enumerable:!0,get:r})},t.r=function(s){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},t.t=function(s,i){if(1&i&&(s=t(s)),8&i||4&i&&typeof s=="object"&&s&&s.__esModule)return s;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:s}),2&i&&typeof s!="string")for(var o in s)t.d(r,o,function(c){return s[c]}.bind(null,o));return r},t.n=function(s){var i=s&&s.__esModule?function(){return s.default}:function(){return s};return t.d(i,"a",i),i},t.o=function(s,i){return Object.prototype.hasOwnProperty.call(s,i)},t.p="",t(t.s=0)}([function(n,e,t){function s(h){let a,u;const p={light:function(){return!f()},dark:f,lighten:R,darken:M,saturate:N,desaturate:function(T=0){return N(T*=-1)},increaseContrast:function(T=0){return F(T*=-1)},decreaseContrast:F,active:function(){return F(.123)},highlight:function(){return F(.1)},selected:function(){return F(.066)},text:function(){return u=v()?i("#333333"):i("#FFFFFF"),p},shadow:function(){return u=v()?i("#000000"):i("#FFFFFF"),p},hex:function(){const T=u;return u=a,"#"+T.map(D=>parseInt(D+"",10).toString(16).padStart(2,"0")).join("")},rgb:function(){const T=u;return u=a,`rgb(${T.join()})`},rgba:function(T=1){const D=u;return u=a,`rgba(${D.join()}, ${T})`},setHex:g,setRgb:function(T=[0,0,0]){let[D,B,G]=T;return D=l(D,0,255),B=l(B,0,255),G=l(G,0,255),a=[D,B,G],u=[D,B,G],p}};function g(T="#000000"){return a=i(T),u=a,p}function f(){const[T,D,B]=u;return u=a,(299*T+587*D+114*B)/1e3<128}function v(){const[T,D,B]=u;return(299*T+587*D+114*B)/1e3>=128}function M(T=0){return R(T*=-1)}function R(T=0){let[D,B,G]=c(u);return G=l(G+T,0,1),u=r([D,B,G]),p}function N(T=0){let[D,B,G]=c(u);return B=l(B+T,0,1),u=r([D,B,G]),p}function F(T=0){return v()?M(T):R(T)}return g(h),p}function i(h){if(typeof h!="string")throw new TypeError("Expected a string");(h=h.replace(/^#/,"")).length===3&&(h=h[0]+h[0]+h[1]+h[1]+h[2]+h[2]);var a=parseInt(h,16);return[a>>16,a>>8&255,255&a]}function r(h){const[a,u,p]=h;let g,f,v;if(u===0)g=f=v=p;else{const M=function(F,T,D){return D<0&&(D+=1),D>1&&(D-=1),D<.16666666666666666?F+6*(T-F)*D:D<.5?T:D<.6666666666666666?F+(T-F)*(.6666666666666666-D)*6:F},R=p<.5?p*(1+u):p+u-p*u,N=2*p-R;g=l(M(N,R,a+1/3),0,1),f=l(M(N,R,a),0,1),v=l(M(N,R,a-1/3),0,1)}return[Math.round(255*g),Math.round(255*f),Math.round(255*v)]}t.r(e),t.d(e,"offColor",function(){return s}),t.d(e,"hexRgb",function(){return i}),t.d(e,"hslToRgb",function(){return r}),t.d(e,"color",function(){return o}),t.d(e,"rgbToHsl",function(){return c});const o=s;function c(h){const a=h[0]/255,u=h[1]/255,p=h[2]/255,g=Math.max(a,u,p),f=Math.min(a,u,p);let v=(g+f)/2,M=(g+f)/2;const R=(g+f)/2;if(g===f)v=M=0;else{const N=g-f;switch(M=R>.5?N/(2-g-f):N/(g+f),g){case a:v=(u-p)/N+(u=a?h:a}}]);Or.exports=kw;var Hc=Or.exports,ra;const Jr=(ra=Or.exports.offColor)!=null?ra:Hc.offColor;function sa(n,e,t,s){const i=parseInt(t);switch(s&&(e==="darker"?e="lighter":e==="lighter"&&(e="darker")),e){case"darker":return Jr(n).darken(i/100).hex();case"lighter":return Jr(n).lighten(i/100).hex();case"alpha":return Jr(n).rgba(i/100)}}class Iw{constructor(e,t,s){this._aliases={},this._derivedAliases=[],this._baseVariables=e,this._variablesToDerive=t,this._isDark=s}toVariables(){var t;const e={};this._detectAliases();for(const s of this._variablesToDerive){const i=this._derive(s);i&&(e[s]=i)}for(const[s,i]of Object.entries(this._aliases))e[s]=(t=this._baseVariables[i])!=null?t:e[i];for(const s of this._derivedAliases){const i=this._deriveAlias(s,e);i&&(e[s]=i)}return e}_detectAliases(){const e=[];for(const t of this._variablesToDerive){const[s,i]=t.split("=");i?this._aliases[s]=i:e.push(t)}this._variablesToDerive=e}_derive(e){const t=/(.+)--(.+)-(.+)/,s=e.match(t);if(s){const[,i,r,o]=s,c=this._baseVariables[i];if(!c)if(this._aliases[i]){this._derivedAliases.push(e);return}else throw new Error(`Cannot find value for base variable "${i}"!`);return sa(c,r,o,this._isDark)}}_deriveAlias(e,t){const s=/(.+)--(.+)-(.+)/,i=e.match(s);if(i){const[,r,o,c]=i,l=t[r];if(!l)throw new Error(`Cannot find value for alias "${r}" when trying to derive ${e}!`);return sa(l,o,c,this._isDark)}}}var na;(na=Or.exports.offColor)!=null||Hc.offColor;class Mw{constructor(e,t){this._themeMapping={},this._preferredColorScheme=t,this._platform=e}async parse(e,t,s,i){await i.wrap("RuntimeThemeParser.parse",async()=>{var u;const{cssLocation:r,derivedVariables:o,icons:c}=this._getSourceData(t,s,i),l=e.name;if(!l)throw new Error("Theme name not found in manifest!");let h={},a={};for(const[p,g]of Object.entries((u=e.values)==null?void 0:u.variants))try{const f=`${e.id}-${p}`,{name:v,default:M,dark:R,variables:N}=g,F=new Iw(N,o,R).toVariables();Object.assign(N,F);const T=await new Sw(this._platform,c,N,s).toVariables();Object.assign(N,F,T);const D=`${l} ${v}`;if(M){Object.assign(R?h:a,{variantName:v,id:f,cssLocation:r,variables:N});continue}this._themeMapping[D]={cssLocation:r,id:f,variables:N}}catch(f){console.error(f);continue}if(h.id&&a.id){const p=this._preferredColorScheme===es.Dark?h:a;this._themeMapping[l]={dark:h,light:a,default:p}}else{const p=h.id?h:a;this._themeMapping[`${l} ${p.variantName}`]={id:p.id,cssLocation:p.cssLocation}}})}_getSourceData(e,t,s){return s.wrap("getSourceData",()=>{var l,h,a;const i=(l=e.source)==null?void 0:l["runtime-asset"];if(!i)throw new Error(`Run-time asset not found in source section for theme at ${t}`);const r=new URL(i,new URL(t,window.location.origin)).href,o=(h=e.source)==null?void 0:h["derived-variables"];if(!o)throw new Error(`Derived variables not found in source section for theme at ${t}`);const c=(a=e.source)==null?void 0:a.icon;if(!c)throw new Error(`Icon mapping not found in source section for theme at ${t}`);return{cssLocation:r,derivedVariables:o,icons:c}})}get themeMapping(){return this._themeMapping}}class Cw{constructor(e){this._themeMapping={},this._preferredColorScheme=e}parse(e,t,s){s.wrap("BuiltThemeParser.parse",()=>{var l,h,a;const i=(l=e.source)==null?void 0:l["built-assets"],r=e.name;if(!r)throw new Error(`Theme name not found in manifest at ${t}`);let o={},c={};for(let[u,p]of Object.entries(i)){try{p=new URL(p,new URL(t,window.location.origin)).href}catch{continue}const g=(h=u.match(/.+-(.+)/))==null?void 0:h[1],f=(a=e.values)==null?void 0:a.variants[g];if(!f)throw new Error(`Variant ${g} is missing in manifest at ${t}`);const{name:v,default:M,dark:R}=f,N=`${r} ${v}`;if(M){const F=R?o:c;F.variantName=v,F.id=u,F.cssLocation=p;continue}this._themeMapping[N]={cssLocation:p,id:u}}if(o.id&&c.id){const u=this._preferredColorScheme===es.Dark?o:c;this._themeMapping[r]={dark:o,light:c,default:u}}else{const u=o.id?o:c;this._themeMapping[`${r} ${u.variantName}`]={id:u.id,cssLocation:u.cssLocation}}})}get themeMapping(){return this._themeMapping}}class Ew{constructor(e){this._platform=e}async init(e,t){await this._platform.logger.wrapOrRun(t,"ThemeLoader.init",async s=>{let i=!0;const r=[],o=[],c=await Promise.all(e.map(u=>this._platform.request(u,{method:"GET",format:"json",cache:!0}).response())),l=new Mw(this._platform,this.preferredColorScheme),h=new Cw(this.preferredColorScheme),a=[];for(let u=0;u=200&&g<=299)){console.error(`Failed to load manifest at ${e[u]}, status: ${g}`),s.log({l:"Manifest fetch failed",location:e[u],status:g},Ge.Error),r.push(e[u]);continue}i=!1;try{if(f.extends){const v=c.findIndex(F=>"value"in F&&F.value.body.id===f.extends);if(v===-1)throw new Error(`Base manifest for derived theme at ${e[u]} not found!`);const{body:M}=c[v].value,R=e[v],N=l.parse(f,M,R,s);a.push(N)}else h.parse(f,e[u],s)}catch(v){console.error(v),o.push(v.message)}}if(await Promise.all(a),this._themeMapping=It(It({},h.themeMapping),l.themeMapping),i)throw new Error(`All configured theme manifests failed to load, the following were tried: ${r.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(s),s.log({l:"Preferred colorscheme",scheme:this.preferredColorScheme===es.Dark?"dark":"light"}),s.log({l:"Result",themeMapping:this._themeMapping})})}async setTheme(e,t,s){await this._platform.logger.wrapOrRun(s,{l:"change theme",name:e,variant:t},async i=>{let r,o,c=this._themeMapping[e];if("id"in c)r=c.cssLocation,o=c.variables;else{if(!t)throw new Error("themeVariant is undefined!");r=c[t].cssLocation,o=c[t].variables}await this._platform.replaceStylesheet(r,i),o?(s==null||s.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[s,i]of Object.entries(e))t.style.setProperty(`--${s}`,i);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 es.Dark:return(e=this._platform.config.defaultTheme)==null?void 0:e.dark;case es.Light:return(t=this._platform.config.defaultTheme)==null?void 0:t.light}}_findThemeDetailsFromId(e){var t,s;for(const[i,r]of Object.entries(this._themeMapping)){if("id"in r&&r.id===e)return{themeName:i,themeData:r};if("light"in r&&((t=r.light)==null?void 0:t.id)===e)return{themeName:i,themeData:r.light};if("dark"in r&&((s=r.dark)==null?void 0:s.id)===e)return{themeName:i,themeData:r.dark}}}_addDefaultThemeToMapping(e){e.wrap("addDefaultThemeToMapping",t=>{const s=this.getDefaultTheme();if(s){const i=this._findThemeDetailsFromId(s);if(i){this._themeMapping.Default={id:"default",cssLocation:i.themeData.cssLocation};const r=i.themeData.variables;r&&(this._themeMapping.Default.variables=r)}}t.log({l:"Default Theme",theme:s})})}get preferredColorScheme(){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return es.Dark;if(window.matchMedia("(prefers-color-scheme: light)").matches)return es.Light}}var Wc=(n=>(n[n.Minute=6e4]="Minute",n[n.Hours=36e5]="Hours",n[n.Day=864e5]="Day",n))(Wc||{});function Rw(n){let e=0,t=0,s=0;n>=864e5&&(e=Math.floor(n/864e5),n-=e*864e5),n>=36e5&&(t=Math.floor(n/36e5),n-=t*36e5),n>=6e4&&(s=Math.floor(n/6e4),n-=s*6e4);const i=Math.floor(n/1e3);let r="";return e&&(r=`${e}d `),(t||e)&&(r+=`${t}h `),(s||t||e)&&(r+=`${s}m `),r+=`${i}s`,r}class Tw{constructor(e){this.clock=e,this.todayMidnight=new Date,this.todayMidnight.setHours(0,0,0,0),this.relativeDayFormatter=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),this.weekdayFormatter=new Intl.DateTimeFormat(void 0,{weekday:"long"}),this.currentYearFormatter=new Intl.DateTimeFormat(void 0,{weekday:"long",month:"long",day:"numeric"}),this.otherYearFormatter=new Intl.DateTimeFormat(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),this.timeFormatter=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"})}formatTime(e){return this.timeFormatter.format(e)}formatMachineReadableDate(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}formatRelativeDate(e){let t=Math.floor((e.getTime()-this.todayMidnight.getTime())/Wc.Day);return t>=-1&&t<=1?Aw(this.relativeDayFormatter.format(t,"day")):t>-7&&t<0?this.weekdayFormatter.format(e):this.todayMidnight.getFullYear()===e.getFullYear()?this.currentYearFormatter.format(e):this.otherYearFormatter.format(e)}formatDuration(e){return Rw(e)}}function Aw(n){return n.slice(0,1).toLocaleUpperCase()+n.slice(1)}function ia(n){return new Promise(function(e,t){var s=document.createElement("script");s.setAttribute("src",n),s.onload=e,s.onerror=t,document.body.appendChild(s)})}async function xw(n){return window.msCrypto&&!window.crypto&&(window.crypto=window.msCrypto),n?(window.WebAssembly?(await ia(n.wasmBundle),await window.Olm.init({locateFile:()=>n.wasm})):(await ia(n.legacyBundle),await window.Olm.init()),window.Olm):null}function Vw(n){return n.startsWith("/")?n:new URL(n,document.location.href).pathname}async function Nw(n){const e=new Ky(n.worker,4);return await e.init(),await e.sendAll({type:"load_olm",path:Vw(n.olm.legacyBundle)}),new kg(e)}function Dw(n){if(!window.visualViewport)return;const e=()=>{const t=n.querySelector(".SessionView");if(!t)return;const s=n.querySelector(".bottom-aligned-scroll");let i,r,o;s&&(i=s.scrollTop,r=s.offsetHeight);const c=t.offsetTop+t.offsetHeight-window.visualViewport.height;n.style.setProperty("--ios-viewport-height",window.visualViewport.height.toString()+"px"),n.style.setProperty("--ios-viewport-top",c.toString()+"px"),s&&(o=s.offsetHeight,s.scrollTop=i+r-o)};return window.visualViewport.addEventListener("resize",e),()=>{window.visualViewport.removeEventListener("resize",e)}}class Uw{constructor({container:e,assetPaths:t,config:s,configURL:i,logger:r,options:o=null,cryptoExtras:c=null}){this._container=e,this._assetPaths=t,this._config=s,this._configURL=i,this.settingsStorage=new ug("hydrogen_setting_v1_"),this.clock=new Iy,this.encoding=new Sg,this.random=Math.random,this.logger=r!=null?r:this._createLogger(o==null?void 0:o.development),this.history=new Ey,this.onlineStatus=new Ry,this.timeFormatter=new Tw,this._serviceWorkerHandler=null,this.sessionInfoStorage=new dg("hydrogen_sessions_v1"),t.serviceWorker&&"serviceWorker"in navigator&&(this._serviceWorkerHandler=new My(this.sessionInfoStorage),this._serviceWorkerHandler.registerAndStart(t.serviceWorker)),this.notificationService=void 0,this._assetPaths.olm&&(this.crypto=new Oy(c)),this.storageFactory=new zd(this._serviceWorkerHandler),this.estimateStorageUsage=Py,typeof fetch=="function"?this.request=hg(this.clock.createTimeout,this._serviceWorkerHandler):this.request=bc;const l=!!window.MSInputMethodContext&&!!document.documentMode;this.isIE11=l;const h=/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1&&!window.MSStream;this.isIOS=h,this._disposables=new li,this._olmPromise=void 0,this._workerPromise=void 0,this.mediaDevices=new yw(navigator.mediaDevices),this.webRTC=new vw,this._themeLoader=new Ew(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:s,body:i}=await this.request(this._configURL,{method:"GET",format:"json",cache:!0}).response();if(s===404)throw new Error(`Could not find ${this._configURL}. Did you copy over config.sample.json?`);if(s>=400)throw new Error(`Got status ${s} while trying to fetch ${this._configURL}`);this._config=i}if(this.notificationService=new Cy(this._serviceWorkerHandler,this._config.push),this._themeLoader){const s=this.config.themeManifests;await((t=this._themeLoader)==null?void 0:t.init(s,e));const{themeName:i,themeVariant:r}=await this._themeLoader.getActiveTheme();e.log({l:"Active theme",name:i,variant:r}),await this._themeLoader.setTheme(i,r,e)}})}catch(e){throw this._container.innerText=e.message,e}}_createLogger(e){const t=new Ag({platform:this}),s=r=>{var o;return(o=r.e)!=null&&o.stack&&(r.e.stack=r.e.stack.replace(/\/\?loginToken=(.+)/,"?loginToken=")),r},i=new Ig({name:"hydrogen_logs",platform:this,serializedTransformer:s});return t.addReporter(i),e&&t.addReporter(new Cg),t}get updateService(){return this._serviceWorkerHandler}loadOlm(){return this._olmPromise||(this._olmPromise=xw(this._assetPaths.olm)),this._olmPromise}get config(){return this._config}async loadOlmWorker(){if(!window.WebAssembly)return this._workerPromise||(this._workerPromise=Nw(this._assetPaths)),this._workerPromise}createAndMountRootView(e){if(this.isIE11&&(this._container.className+=" legacy"),this.isIOS){this._container.className+=" ios";const s=Dw(this._container);s&&this._disposables.track(s)}this._container.addEventListener("error",$o,!0),this._disposables.track(()=>this._container.removeEventListener("error",$o,!0)),window.__hydrogenViewModel=e;const t=new vy(e);this._container.appendChild(t.mount())}setNavigation(e){var t;(t=this._serviceWorkerHandler)==null||t.setNavigation(e)}createBlob(e,t){return Ts.fromBuffer(e,t)}saveFileAs(e,t){navigator.msSaveBlob?navigator.msSaveBlob(e.nativeBlob,t):jy(this._container,this._assetPaths.downloadSandbox,e,t,this.isIOS)}async copyPlaintext(e){return await jf(e)}restart(){document.location.reload()}openFile(e=null){const t=document.createElement("input");t.setAttribute("type","file"),t.className="hidden",e&&t.setAttribute("accept",e);const s=new Promise(i=>{const r=()=>{t.removeEventListener("change",r,!0);const o=t.files[0];this._container.removeChild(t),o?i({name:o.name,blob:Ts.fromBlobUnsafe(o)}):i()};t.addEventListener("change",r,!0)});return this._container.appendChild(t),t.click(),s}openUrl(e){location.href=e}parseHTML(e){return _w(e)}async loadImage(e){return ji.fromBlob(e)}async loadVideo(e){return Bn.fromBlob(e)}hasReadPixelPermission(){return By()}get devicePixelRatio(){return window.devicePixelRatio||1}get version(){return"0.5.1"}get themeLoader(){return this._themeLoader}async replaceStylesheet(e,t){const s=await this.logger.wrapOrRun(t,{l:"replaceStylesheet",location:e},async i=>{let r;const o=document.querySelector("head");document.querySelectorAll(".theme").forEach(h=>h.remove());const c=document.createElement("link");c.href=e,c.rel="stylesheet",c.type="text/css",c.className="theme";const l=new Promise(h=>{c.onerror=()=>{r=new Error(`Failed to load stylesheet from ${e}`),i.catch(r),h()},c.onload=()=>{h()}});return o.appendChild(c),await l,r});if(s)throw s}get description(){var e;return"web-"+((e=navigator.userAgent)!=null?e:"")}dispose(){this._disposables.dispose()}}var Ow="./config.json",Pw="./assets/download-sandbox.48a866e9.html",Fw="./assets/main.bdb9a925.js",Lw="./assets/olm.3fc8dbfe.wasm",Kw="./assets/olm.cf9a793b.js",Bw="./assets/olm_legacy.bc22f405.js",zc={downloadSandbox:Pw,worker:Fw,olm:{wasm:Lw,legacyBundle:Bw,wasmBundle:Kw}};zc.serviceWorker="sw.js";const $w=new Uw({container:document.body,assetPaths:zc,configURL:Ow,options:{development:!1}});ng($w); //# sourceMappingURL=index.e65aa065.js.map