hydrogen-web/assets/index.ca5690cf.js

21 lines
471 KiB
JavaScript

var la=Object.defineProperty,ha=Object.defineProperties;var da=Object.getOwnPropertyDescriptors;var cs=Object.getOwnPropertySymbols;var fr=Object.prototype.hasOwnProperty,gr=Object.prototype.propertyIsEnumerable;var _r=(n,e,t)=>e in n?la(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ft=(n,e)=>{for(var t in e||(e={}))fr.call(e,t)&&_r(n,t,e[t]);if(cs)for(var t of cs(e))gr.call(e,t)&&_r(n,t,e[t]);return n},yr=(n,e)=>ha(n,da(e));var wr=(n,e)=>{var t={};for(var s in n)fr.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&cs)for(var s of cs(n))e.indexOf(s)<0&&gr.call(n,s)&&(t[s]=n[s]);return t};function xe(...n){const e={};for(const t of n)e[t]=t;return Object.freeze(e)}function vr(n){try{return new URL(n).origin}catch{return new URL(`https://${n}`).origin}}async function ua(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 ma(n,e){var s;n=vr(n);const t=await ua(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=vr(r))}return n}class ye extends Error{get name(){return"AbortError"}}class Ii{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 kt extends Ii{emit(e){for(const t of this._handlers)t(e)}waitFor(e){return e(this.get())?new _a(Promise.resolve(this.get())):new pa(this,e)}flatMap(e){return new fa(this,e)}}class pa{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 ye),this._reject=null)}}class _a{constructor(e){this.promise=e}dispose(){}}class we extends kt{constructor(e){super(),this._value=e}get(){return this._value}set(e){e!==this._value&&(this._value=e,this.emit(this._value))}}class ci extends we{constructor(e,t){super(e),this._freeCallback=t}onUnsubscribeLast(){super.onUnsubscribeLast(),this._freeCallback()}}class fa extends kt{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()}}class Mn{constructor(e){this._abortable=void 0;const t=i=>(this._abortable=i,i);this._progress=new we(void 0);const s=i=>{this._progress.set(i)};this.result=e(t,s)}get progress(){return this._progress}abort(){var e;(e=this._abortable)==null||e.abort(),this._abortable=void 0}}const ga={"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},br="application/octet-stream";class lt{constructor(e,t=null){this._blob=e,this._buffer=t,this._url=null}static fromBuffer(e,t){return t=t?t.split(";")[0].trim():"",ga[t]||(t=br),new lt(new Blob([e],{type:t}),e)}static fromBlob(e){return new lt(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||br}dispose(){this._url&&(URL.revokeObjectURL(this._url),this._url=null)}}function An(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 ya(n){if(n instanceof lt){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 xn extends Error{constructor(e,t){super(`${e}: ${t.message}`),this.cause=t}get name(){return"WrappedError"}}class Nn 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 qe extends Error{constructor(e,t){super(e||"ConnectionError"),this.isTimeout=t}get name(){return"ConnectionError"}}class wa{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 a,c;if(r==null||r.set("status",o.status),o.status>=200&&o.status<300||((a=i==null?void 0:i.allowedStatusCodes)==null?void 0:a.includes(o.status)))return r==null||r.finish(),o.body;if(o.status>=500){const l=new qe("Internal Server Error");throw r==null||r.catch(l),l}else if(o.status>=400&&!((c=o.body)!=null&&c.errcode)){const l=new qe(`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(l),l}else{const l=new Nn(e,t,o.body,o.status);throw r==null||r.set("errcode",l.errcode),r==null||r.catch(l),l}},o=>{if(o.name==="AbortError"&&this._sourceRequest){const a=new qe("Service worker aborted, either updating or hit #187.");throw r==null||r.catch(a),a}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 ls="/_matrix/client/r0",va="/_matrix/client/v3",ei="/_matrix/client/unstable/org.matrix.msc2697.v2";class Ze{constructor({homeserver:e,accessToken:t,request:s,reconnector:i}){this._homeserver=e,this._accessToken=t,this._requestFn=s,this._reconnector=i}_url(e,t=ls){return this._homeserver+t+e}_baseRequest(e,t,s,i,r,o){const a=An(s);t=`${t}?${a}`;let c;const l=new Map;if(o&&l.set("Authorization",`Bearer ${o}`),l.set("Accept","application/json"),i){const u=ya(i);l.set("Content-Type",u.mimeType),c=u.body}const h=this._requestFn(t,{method:e,headers:l,body:c,timeout:r==null?void 0:r.timeout,uploadProgress:r==null?void 0:r.uploadProgress,format:"json",cache:e!=="GET"}),d=new wa(e,t,h,r);return this._reconnector&&d.response().catch(u=>{u.name==="ConnectionError"&&this._reconnector.onRequestFailed(this)}),d}_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)||ls),t,s,i)}_put(e,t,s,i){return this._authedRequest("PUT",this._url(e,(i==null?void 0:i.prefix)||ls),t,s,i)}_get(e,t,s,i){return this._authedRequest("GET",this._url(e,(i==null?void 0:i.prefix)||ls),t,s,i)}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)}getLoginFlows(){return this._unauthedRequest("GET",this._url("/login"))}register(e,t,s,i,r=!0,o={}){o.allowedStatusCodes=[401];const a={auth:i,password:t,initial_device_displayname:s,inhibit_login:r};return e&&(a.username=e),this._unauthedRequest("POST",this._url("/register",va),void 0,a,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)}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 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)}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=ei,this._get("/dehydrated_device",void 0,void 0,e)}createDehydratedDevice(e,t={}){return t.prefix=ei,this._put("/dehydrated_device",{},e,t)}claimDehydratedDevice(e,t={}){return t.prefix=ei,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)}}class Dn{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 ye))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 $t=(n=>(n[n.Waiting=0]="Waiting",n[n.Reconnecting=1]="Reconnecting",n[n.Online=2]="Online",n))($t||{});class ba{constructor({retryDelay:e,createMeasure:t,onlineStatus:s}){this._onlineStatus=s,this._retryDelay=e,this._createTimeMeasure=t,this._state=new we(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 Sa(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 a=await s.digest("SHA-256",e);if(i.encode(new Uint8Array(a))!=o)throw new Error("Mismatched SHA-256 digest");var c;return t.v=="v1"||t.v=="v2"?c=64:c=128,await s.aes.decryptCTR({jwkKey:t.key,iv:r,data:e,counterLength:c})}async function Ia(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(),a=await t.aes.encryptCTR({jwkKey:r,iv:i,data:o}),c=await t.digest("SHA-256",a);return{blob:n.createBlob(a,"application/octet-stream"),info:{v:"v2",key:r,iv:s.encodeUnpadded(i),hashes:{sha256:s.encodeUnpadded(c)}}}}class Ea{constructor({homeserver:e,platform:t}){this._homeserver=e,this._platform=t}mxcUrlThumbnail(e,t,s,i){const r=this._parseMxcUrl(e);if(r){const[o,a]=r;return`${this._homeserver}/_matrix/media/r0/thumbnail/${encodeURIComponent(o)}/${encodeURIComponent(a)}`+"?"+An({width:Math.round(t),height:Math.round(s),method:i})}return null}mxcUrl(e){const t=this._parseMxcUrl(e);if(t){const[s,i]=t;return`${this._homeserver}/_matrix/media/r0/download/${encodeURIComponent(s)}/${encodeURIComponent(i)}`}else return null}_parseMxcUrl(e){const t="mxc://";return e.startsWith(t)?e.substr(t.length).split("/",2):null}async downloadEncryptedFile(e,t=!1){const s=this.mxcUrl(e.url),{body:i}=await this._platform.request(s,{method:"GET",format:"buffer",cache:t}).response(),r=await Sa(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 ka{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 ye),(e=this.responseCodeReject)==null||e.call(this,new ye))}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 Vn{constructor(e){this._scheduler=e}}for(const n of Object.getOwnPropertyNames(Ze.prototype))n!=="constructor"&&!n.startsWith("_")&&(Vn.prototype[n]=function(...e){return this._scheduler._hsApiRequest(n,e)});class Ra{constructor({hsApi:e,clock:t}){this._requests=new Set,this._stopped=!1,this._wrapper=new Vn(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 ka(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 Nn&&s.errcode==="M_LIMIT_EXCEEDED")Number.isSafeInteger(s.retry_after_ms)?await this._clock.createTimeout(s.retry_after_ms).elapsed():(t||(t=new Dn(this._clock.createTimeout)),await t.waitForRetry());else{e.responseReject(s);return}}this._stopped&&e.abort()}finally{this._requests.delete(e)}}}const Ca=3e4,L=xe("InitialSync","CatchupSync","Syncing","Stopped");function Ta(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 Ma{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 we(L.Stopped),this._error=null}get status(){return this._status}get error(){return this._error}start(){if(this._status.get()!==L.Stopped)return;this._error=null;let e=this._session.syncToken;e?this._status.set(L.CatchupSync):this._status.set(L.InitialSync),this._syncLoop(e)}async _syncLoop(e){for(;this._status.get()!==L.Stopped;){let t,s,i=this._status.get()===L.CatchupSync||this._status.get()===L.InitialSync;await this._logger.run("sync",async r=>{r.set("token",e),r.set("status",this._status.get());try{const o=this._status.get()===L.Syncing?Ca:0,a=await this._syncRequest(e,o,r);e=a.syncToken,t=a.roomStates,s=a.sessionChanges,this._status.get()!==L.Syncing&&a.hadToDeviceMessages?this._status.set(L.CatchupSync):this._status.set(L.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(L.Stopped)}this._status.get()!==L.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()===L.CatchupSync,r=(async()=>{try{await s.wrap("session",c=>this._session.afterSyncCompleted(e,i,c),s.level.Detail)}catch{}})(),a=t.filter(c=>c.room.needsAfterSyncCompleted(c.changes)).map(async c=>{try{await s.wrap("room",l=>c.room.afterSyncCompleted(c.changes,l),s.level.Detail)}catch{}});await Promise.all(a.concat(r))}async _syncRequest(e,t,s){var p;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(),a=!e,c=new Aa,l=this._parseInvites(o.rooms),{roomStates:h,archivedRoomStates:d}=await this._parseRoomsResponse(o.rooms,l,a,s);try{c.lock=await s.wrap("obtainSyncLock",()=>this._session.obtainSyncLock(o)),await s.wrap("prepare",_=>this._prepareSync(c,h,o,_)),await s.wrap("afterPrepareSync",_=>Promise.all(h.map(f=>f.room.afterPrepareSync(f.preparation,_)))),await s.wrap("write",async _=>this._writeSync(c,l,h,d,o,i,a,_))}finally{c.dispose()}s.wrap("after",_=>this._afterSync(c,l,h,d,_));const u=(p=o.to_device)==null?void 0:p.events;return{syncToken:o.next_batch,roomStates:h,sessionChanges:c.changes,hadToDeviceMessages:Array.isArray(u)&&u.length>0}}_openPrepareSyncTxn(){const e=this._storage.storeNames;return this._storage.readTxn([e.olmSessions,e.inboundGroupSessions,e.timelineFragments,e.timelineEvents])}async _prepareSync(e,t,s,i){var a,c;const r=await this._openPrepareSyncTxn();e.preparation=await i.wrap("session",l=>this._session.prepareSync(s,e.lock,r,l));const o=(a=e.preparation)==null?void 0:a.newKeysByRoom;if(o){const{hasOwnProperty:l}=Object.prototype;for(const h of o.keys())if(!(((c=s.rooms)==null?void 0:c.join)&&l.call(s.rooms.join,h))){let u=this._session.rooms.get(h);u&&t.push(new Sr(u,!1,{},u.membership))}}await Promise.all(t.map(async l=>{const h=o==null?void 0:o.get(l.room.id);l.preparation=await i.wrap("room",async d=>(l.isNewRoom&&await l.room.load(null,r,d),l.room.prepareSync(l.roomResponse,l.membership,h,r,d)),i.level.Detail)})),await r.complete()}async _writeSync(e,t,s,i,r,o,a,c){const l=await this._openSyncTxn();try{e.changes=await c.wrap("session",h=>this._session.writeSync(r,o,e.preparation,l,h)),await Promise.all(t.map(async h=>{h.changes=await c.wrap("invite",d=>h.invite.writeSync(h.membership,h.roomResponse,l,d))})),await Promise.all(s.map(async h=>{h.changes=await c.wrap("room",d=>h.room.writeSync(h.roomResponse,a,h.preparation,l,d))})),await Promise.all(i.map(async h=>{var u;const d=(u=h.roomState)==null?void 0:u.summaryChanges;h.changes=await c.wrap("archivedRoom",p=>h.archivedRoom.writeSync(d,h.roomResponse,h.membership,l,p))}))}catch(h){throw l.abort(c),l.getCause(h)}await l.complete(c)}_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",a=>{o.archivedRoom.afterSync(o.changes,a),o.archivedRoom.release()},r.level.Detail);for(let o of s)r.wrap("room",a=>o.room.afterSync(o.changes,a),r.level.Detail);for(let o of t)r.wrap("invite",a=>o.invite.afterSync(o.changes,a),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.deviceIdentities,e.outboundGroupSessions,e.operations,e.accountData,e.olmSessions,e.inboundGroupSessions])}async _parseRoomsResponse(e,t,s,i){const r=[],o=[];if(e){const a=["join","leave"];for(const c of a){const l=e[c];if(l)for(const[h,d]of Object.entries(l)){if(s&&Ta(d))continue;const u=this._session.invites.get(h);u&&t.push(new Ir(u,!1,null,c));const p=this._createRoomSyncState(h,d,c,s);p&&r.push(p);const _=await this._createArchivedRoomSyncState(h,p,d,c,s,i);_&&o.push(_)}}}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 Sr(o,r,t,s)}async _createArchivedRoomSyncState(e,t,s,i,r,o){let a;if((t==null?void 0:t.shouldAdd)&&!r?a=this._session.createOrGetArchivedRoomForSync(e):i==="leave"&&(t?a=this._session.createOrGetArchivedRoomForSync(e):a=await this._session.loadArchivedRoom(e,o)),a)return new xa(a,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 Ir(r,o,i,"invite"))}return t}stop(){this._status.get()!==L.Stopped&&(this._status.set(L.Stopped),this._currentRequest&&(this._currentRequest.abort(),this._currentRequest=null))}}class Aa{constructor(){this.lock=null,this.preparation=null,this.changes=null}dispose(){var e;(e=this.lock)==null||e.release()}}class Sr{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 xa{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 Ir{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"}}class Ls{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){}}function Na(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 Er=/[\\\"\x00-\x1F]/g,Ne={};for(var hs=0;hs<32;++hs)Ne[String.fromCharCode(hs)]="\\U"+("0000"+hs.toString(16)).slice(-4).toUpperCase();Ne["\b"]="\\b";Ne[" "]="\\t";Ne[`
`]="\\n";Ne["\f"]="\\f";Ne["\r"]="\\r";Ne['"']='\\"';Ne["\\"]="\\\\";function Ln(n){return Er.lastIndex=0,n.replace(Er,function(e){return Ne[e]})}function Ei(n){switch(typeof n){case"string":return'"'+Ln(n)+'"';case"number":return isFinite(n)?n:"null";case"boolean":return n;case"object":return n===null?"null":Array.isArray(n)?Da(n):Va(n);default:throw new Error("Cannot stringify: "+typeof n)}}function Da(n){for(var e="[",t="",s=0;s<n.length;++s)t+=e,e=",",t+=Ei(n[s]);return e!=","?"[]":t+"]"}function Va(n){var e="{",t="",s=Object.keys(n);s.sort();for(var i=0;i<s.length;++i){var r=s[i];t+=e+'"'+Ln(r)+'":',e=",",t+=Ei(n[r])}return e!=","?"{}":t+"}"}var On={stringify:Ei};const st=xe("Sync","Timeline","Retry"),ie="e2ee:",ki="m.olm.v1.curve25519-aes-sha2",ve="m.megolm.v1.aes-sha2";class z extends Error{constructor(e,t,s=null){super(`Decryption error ${e}${s?": "+JSON.stringify(s):""}`),this.code=e,this.event=t,this.details=s}}const Pn="ed25519";function Un(n,e,t,s,i,r=void 0){var l,h;const o=Object.assign({},i);delete o.unsigned,delete o.signatures;const a=On.stringify(o),c=(h=(l=i==null?void 0:i.signatures)==null?void 0:l[e])==null?void 0:h[`${Pn}:${t}`];try{if(!c)throw new Error("no signature");return n.ed25519_verify(s,a,c),!0}catch(d){if(r){const u=r.log({l:"Invalid signature, ignoring.",ed25519Key:s,canonicalJson:a,signature:c});u.error=d,u.logLevel=r.level.Warn}return!1}}function La(){return{type:"m.room.encryption",state_key:"",content:{algorithm:ve,rotation_period_ms:6048e5,rotation_period_msgs:100}}}const ds=Object.freeze({Joined:"joined",Invited:"invited",WorldReadable:"world_readable",Shared:"shared"});function us(n,e){switch(e){case ds.WorldReadable:return!0;case ds.Shared:return n!==void 0;case ds.Joined:return n==="join";case ds.Invited:return n==="invite"||n==="join";default:return!1}}function Oa(n,e,t,s,i){return e.length&&(n=e.reduce((r,o)=>Ba(r,o,t,s,i),n)),n}function Fn(n,e,t){var r,o;const s=(r=n==null?void 0:n.state)==null?void 0:r.events;Array.isArray(s)&&(t=s.reduce(e,t));const i=(o=n==null?void 0:n.timeline)==null?void 0:o.events;return Array.isArray(i)&&(t=i.reduce((a,c)=>(typeof c.state_key=="string"&&(t=e(t,c)),t),t)),t}function Pa(n,e,t,s){e.summary&&(n=Ka(n,e.summary)),t!==n.membership&&(n=n.cloneIfNeeded(),n.membership=t),e.account_data&&(n=e.account_data.events.reduce(Fa,n)),n=Fn(e,(r,o)=>Bn(r,o,s),n);const i=e.unread_notifications;return i&&(n=Ua(n,i)),n}function Ua(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 Fa(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 Bn(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===ve&&(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 a;e.sender===t?a=e.state_key:e.state_key===t&&(a=e.sender),a&&(n=n.cloneIfNeeded(),n.isDirectMessage=!0,n.dmUserId=a)}else o.membership==="leave"&&n.isDirectMessage&&n.dmUserId===e.state_key&&(n=n.cloneIfNeeded(),n.isDirectMessage=!1,n.dmUserId=null)}return n}function Ba(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 Ka(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 Ee{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 Ee(this)}serialize(){return Object.entries(this).reduce((e,[t,s])=>(t!=="cloned"&&s!==null&&(e[t]=s),e),{})}applyTimelineEntries(e,t,s,i){return Oa(this,e,t,s,i)}applySyncResponse(e,t,s){return Pa(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 $a{constructor(e){this._data=null,this.applyChanges(new Ee(null,e))}get data(){return this._data}writeClearUnread(e){const t=new Ee(this._data);return t.isUnread=!1,t.notificationCount=0,t.highlightCount=0,e.roomSummary.set(t.serialize()),t}writeHasFetchedMembers(e,t){const s=new Ee(this._data);return s.hasFetchedMembers=e,t.roomSummary.set(s.serialize()),s}writeIsTrackingMembers(e,t){const s=new Ee(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 Ee(e))}}var P=(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.deviceIdentities="deviceIdentities",n.olmSessions="olmSessions",n.inboundGroupSessions="inboundGroupSessions",n.outboundGroupSessions="outboundGroupSessions",n.groupSessionDecryptions="groupSessionDecryptions",n.operations="operations",n.accountData="accountData",n))(P||{});const Gt=Object.values(P);class Re extends Error{constructor(e,t=null){super(e),t&&(this.errcode=t.name),this.cause=t}get name(){return"StorageError"}}const F={get minStorageKey(){return 0},get middleStorageKey(){return 2147483647},get maxStorageKey(){return 4294967295}};class B{constructor(e,t){this.fragmentId=e,this.eventIndex=t}nextFragmentKey(){return new B(this.fragmentId+1,F.middleStorageKey)}nextKeyForDirection(e){return e.isForward?this.nextKey():this.previousKey()}previousKey(){return new B(this.fragmentId,this.eventIndex-1)}nextKey(){return new B(this.fragmentId,this.eventIndex+1)}static get maxKey(){return new B(F.maxStorageKey,F.maxStorageKey)}static get minKey(){return new B(F.minStorageKey,F.minStorageKey)}static get defaultLiveKey(){return B.defaultFragmentKey(F.minStorageKey)}static defaultFragmentKey(e){return new B(e,F.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 li=Number.MAX_SAFE_INTEGER;class Kn{constructor(e){this._fragmentIdComparer=e}compare(e){return this.fragmentId===e.fragmentId?this.entryIndex-e.entryIndex:this.fragmentId===li?1:e.fragmentId===li?-1:this._fragmentIdComparer.compare(this.fragmentId,e.fragmentId)}asEventKey(){return new B(this.fragmentId,this.entryIndex)}}function hi(n){var e;return((e=n.unsigned)==null?void 0:e.prev_content)||n.prev_content}const ge="m.room.redaction";function di(n){var e;return!!((e=n==null?void 0:n.unsigned)!=null&&e.redacted_because)}var U=(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))(U||{}),re=(n=>(n[n.DirectMessage=0]="DirectMessage",n[n.Private=1]="Private",n[n.Public=2]="Public",n))(re||{});function ja(n,e){var o,a;let t;const s=c=>{const l=e(c);l instanceof Promise&&(t=t!=null?t:[],t.push(l))},i=(o=n.state)==null?void 0:o.events;if(i)for(let c=0;c<i.length;c++)s(i[c]);let r=(a=n.timeline)==null?void 0:a.events;if(r)for(let c=0;c<r.length;c++){const l=r[c];typeof l.state_key=="string"&&s(l)}if(t)return Promise.all(t).then(()=>{})}const qa="m.reaction",We="m.annotation";function Wa(n,e){return{"m.relates_to":{event_id:n,key:e,rel_type:We}}}function Ri(n){var e;return n.event_id||((e=n["m.in_reply_to"])==null?void 0:e.event_id)}function $n(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 Ha(n){if(n.type===ge)return n.redacts;{const e=$e(n);if(e)return Ri(e)}return null}function ze(n){return n==null?void 0:n["m.relates_to"]}function $e(n){return ze(n.content)}class za{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 kr(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ga(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 Ja(n){return n==="m.emote"?"* ":""}function Qa(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 Ya(n,e,t){const s=Ga(n.content.msgtype),i=Ja(n.content.msgtype),r=n.sender,o=n.displayName||r,a=s||n.content.formatted_body||n.content.body&&kr(n.content.body)||"",c=`<mx-reply><blockquote>In reply to ${i}<a href="https://matrix.to/#/${r}">${o}</a><br />${a}</blockquote></mx-reply>`,h=(s||n.content.body||"").split(`
`);h[0]=`> ${i}<${r}> ${h[0]}`;const u=h.join(`
> `)+`
`+t,p=c+kr(t);return Qa(n.id,e,u,p)}class jn extends Kn{constructor(e){super(e),this._pendingRedactions=null,this._pendingAnnotations=null,this._contextEntry=null,this._contextForEntries=null}get isReply(){var e;return!!((e=this.relation)!=null&&e["m.in_reply_to"])}get isRedacting(){return!!this._pendingRedactions}get isRedacted(){return this.isRedacting}get isRedaction(){return this.eventType===ge}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===ge&&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===We&&this._addPendingAnnotation(e))return"pendingAnnotations"}}removeLocalRelation(e){var t;if(e.eventType===ge&&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)===We&&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 za,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 Wa(this.id,e)}reply(e,t){return Ya(this,e,t)}isRelatedToId(e){return e&&this.relatedEventId===e}haveAnnotation(e){var r,o,a;const t=((o=(r=this.annotations)==null?void 0:r[e])==null?void 0:o.me)||!1,s=(a=this.pendingAnnotations)==null?void 0:a.get(e),i=(s==null?void 0:s.willAnnotate)||!1;return t&&(!s||i)||!t&&i}get relation(){return ze(this.content)}get pendingAnnotations(){return this._pendingAnnotations}get annotations(){return null}}class Xa extends jn{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 li}get entryIndex(){return this._pendingEvent.queueIndex}get content(){return this._pendingEvent.content}get event(){return null}get eventType(){return this._pendingEvent.eventType}get stateKey(){return null}get sender(){var e;return(e=this._member)==null?void 0:e.userId}get displayName(){var e;return(e=this._member)==null?void 0:e.name}get avatarUrl(){var e;return(e=this._member)==null?void 0:e.avatarUrl}get timestamp(){return this._timestamp}get isPending(){return!0}get id(){return this._pendingEvent.txnId}get pendingEvent(){return this._pendingEvent}notifyUpdate(){}isRelatedToId(e){return e&&e===this._pendingEvent.relatedTxnId?!0:super.isRelatedToId(e)}get relatedEventId(){return this._pendingEvent.relatedEventId}get redactingEntry(){return this._redactingEntry}get contextEventId(){var e;return this.isReply?(e=this._pendingEvent.relatedEventId)!=null?e:this._pendingEvent.relatedTxnId:null}}const V=xe("Waiting","EncryptingAttachments","UploadingAttachments","Encrypting","Sending","Sent","Error"),Rr=["m.relates_to"];class Za{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=V.Waiting,this._sendRequest=null,this._attachmentsTotalBytes=0,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=ze(this.content);return e?Ri(e):this._data.relatedEventId}setRelatedEventId(e){const t=ze(this.content);t?$n(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=V.Encrypting,this._emitUpdate("status")}get contentForEncryption(){const e=Object.assign({},this._data.content);for(const t of Rr)delete e[t];return e}_preserveContentFields(e){const t=this._data.content;for(const s of Rr)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=V.Error,this._error=e,this._emitUpdate("status")}setWaiting(){this._status=V.Waiting,this._emitUpdate("status")}get status(){return this._status}get error(){return this._error}get hasStartedSending(){return this._status===V.Sending||this._status===V.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=V.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 ye}this._status=V.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=V.Sending,this._emitUpdate("status");const s=this._data.encryptedEventType||this._data.eventType,i=this._data.encryptedContent||this._data.content;s===ge?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,t.set("id",this._data.remoteId),this._status=V.Sent,this._emitUpdate("status")}dispose(){if(this._attachments)for(const e of Object.values(this._attachments))e.dispose()}}class ne extends jn{constructor(e,t){super(t),this._eventEntry=e,this._decryptionError=null,this._decryptionResult=null}clone(){const e=new ne(this._eventEntry,this._fragmentIdComparer);return e.updateFrom(this),e}updateFrom(e){e._decryptionResult&&!this._decryptionResult&&(this._decryptionResult=e._decryptionResult),e._decryptionError&&!this._decryptionError&&(this._decryptionError=e._decryptionError),this._contextForEntries=e.contextForEntries,this._contextEntry=e.contextEntry}get event(){return this._eventEntry.event}get fragmentId(){return this._eventEntry.fragmentId}get entryIndex(){return this._eventEntry.eventIndex}get content(){var e,t;return((t=(e=this._decryptionResult)==null?void 0:e.event)==null?void 0:t.content)||this._eventEntry.event.content}get prevContent(){return hi(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 Ha(this.event)}get isRedacted(){return super.isRedacted||di(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&&ze(e)||ze(this.content)}get contextEventId(){return this.isReply?this.relatedEventId:null}}function qn(n,e,t){return{fragmentId:n.fragmentId,eventIndex:n.eventIndex,roomId:e,event:t}}function jt(n,e,t){t.isForward?n.push(e):n.unshift(e)}function ec(n,e,t){return t.isForward?n.concat(e):e.concat(n)}const oe="m.room.member";class O{constructor(e){this._data=e}static fromUserId(e,t,s){return new O({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=hi(t),o=i==null?void 0:i.membership,a=(i==null?void 0:i.displayname)||(r==null?void 0:r.displayname),c=(i==null?void 0:i.avatar_url)||(r==null?void 0:r.avatar_url);return this._validateAndCreateMember(e,s,o,a,c)}static fromReplacingMemberEvent(e,t){const s=t&&t.state_key;if(typeof s!="string")return;const i=hi(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 O({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 Wn{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 Ci(n){return typeof n=="number"}const tc=["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},{}),sc={"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 ic(n,e){for(const i of Object.keys(e))tc[i]||delete e[i];const{content:t}=e,s=sc[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 rc(n,e){const t=[];for(;Ci(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 nc(n,e){const t=[];for(;Ci(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 oc(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=rc(s,e),r=nc(s,e),o=i.concat(s,r);t.push(o)}return t.map(s=>new ac(s))}class ti{constructor(e,t,s){this.id=e,this.previousId=t,this.nextId=s}}class ac{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 Cr extends Error{get name(){return"CompareError"}}class cc{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 Cr(`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 Cr(`${e} and ${t} are on different islands, can't tell order`);return s.compare(e,t)}rebuild(e){const t=oc(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 ti(e.id,e.previousId,e.nextId);this._fragmentsById.set(e.id,t),this.rebuild(this._fragmentsById.values())}append(e,t){const s=new ti(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 ti(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 lc(n){return"objectStore"in n?`${n.objectStore.name}.${n.name}`:n.name}function hc(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 Hn extends Re{constructor(e,t,s=null){const i=t&&"source"in t?t.source:t,r=i?lc(i):"",o=i?hc(i):"";let a=`${e} on ${o}.${r}`;s&&(a+=": ",typeof s.name=="string"&&(a+=`(name: ${s.name}) `),typeof s.code=="number"&&(a+=`(code: ${s.code}) `)),s&&(a+=s.message),super(a,s),this.storeName=r,this.databaseName=o}}class Ti extends Hn{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 Ie extends Hn{constructor(e,t,s,i){super(`${e}(${i.map(r=>JSON.stringify(r)).join(", ")}) failed`,t,s)}}const Tr={done:!0},Ge={done:!1};function Rs(n){const e=n.toString(16);return"0".repeat(8-e.length)+e}function ui(n){return parseInt(n,16)}function Mi(n,e,t,s=window.indexedDB){const i=s.open(n,t);return i.onupgradeneeded=async r=>{const o=r.target,a=o.result,c=o.transaction,l=r.oldVersion;try{await e(a,c,l,t)}catch{try{c.abort()}catch{}}},X(i)}function X(n){return new Promise((e,t)=>{n.addEventListener("success",s=>{e(s.target.result)}),n.addEventListener("error",s=>{const i=new Ti(s);t(i)})})}function Jt(n){return new Promise((e,t)=>{n.addEventListener("complete",()=>{e()}),n.addEventListener("abort",s=>{t(new ye)})})}function K(n,e){return new Promise((t,s)=>{n.onerror=i=>{s(new Ti(i))},n.onsuccess=i=>{const r=i.target.result;if(!r){t(!1);return}const o=e(r.value,r.key,r),a=o==null?void 0:o.done,c=o==null?void 0:o.jumpTo;a?t(!0):c?r.continue(c):r.continue()}}).catch(t=>{throw new Re("iterateCursor failed",t)})}async function dc(n,e){const t=[];return await K(n,s=>(t.push(s),{done:e(t)})),t}class Mr{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 X(this._target.count(e))}get(e){return X(this._target.get(e))}getKey(e){return this._target.supports("getKey")?X(this._target.getKey(e)):X(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 K(s,r=>(i.push(r),Ge)),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 K(t,(i,r)=>(s=r,Tr)),s}async iterateValues(e,t){const s=this._target.openCursor(e,"next");await K(s,(i,r,o)=>({done:t(i,r,o)}))}async iterateKeys(e,t){const s=this._target.openKeyCursor(e,"next");await K(s,(i,r,o)=>({done:t(r,o)}))}async findExistingKeys(e,t,s){const i=(d,u)=>t?-this.idbFactory.cmp(d,u):this.idbFactory.cmp(d,u),r=e.slice().sort(i),o=r[0],a=r[r.length-1],c=t?"prev":"next",l=this._target.openKeyCursor(this.IDBKeyRange.bound(o,a),c);let h=0;await K(l,(d,u,p)=>{for(;h<r.length&&i(r[h],u)<0;)h+=1;let _=!1;if(r[h]===u){const f=p.primaryKey;_=s(u,f),h+=1}return _||h>=r.length?Tr:{done:!1,jumpTo:r[h]}})}_reduce(e,t,s,i){let r=s;const o=this._openCursor(e,i);return K(o,a=>(r=t(r,a),Ge))}_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 K(i,o=>(r.push(o),{done:t(r,o)})),r}async _selectWhile(e,t,s){const i=this._openCursor(e,s),r=[];return await K(i,o=>{const a=t(o);return a&&r.push(o),{done:!a}}),r}async iterateWhile(e,t){const s=this._openCursor(e,"next");await K(s,i=>({done:!t(i)}))}async _find(e,t,s){const i=this._openCursor(e,s);let r;if(await K(i,a=>{const c=t(a);return c&&(r=a),{done:c}}))return r}}const Ue=!1;function Fe(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(a=>JSON.stringify(a)).join(", ")})`)}class Ar{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?(Ue&&Fe("openKeyCursor",[e,t],this._qt),this._qt.openKeyCursor(e,t)):(Ue&&Fe("openCursor",[e,t],this._qt),this.openCursor(e,t))}catch(s){throw new Ie("openKeyCursor",this._qt,s,[e,t])}}openCursor(e,t){try{return Ue&&Fe("openCursor",[],this._qt),this._qt.openCursor(e,t)}catch(s){throw new Ie("openCursor",this._qt,s,[e,t])}}put(e,t){try{return Ue&&Fe("put",[e,t],this._qt),this._qtStore.put(e,t)}catch(s){throw new Ie("put",this._qt,s,[e,t])}}add(e,t){try{return Ue&&Fe("add",[e,t],this._qt),this._qtStore.add(e,t)}catch(s){throw new Ie("add",this._qt,s,[e,t])}}get(e){try{return Ue&&Fe("get",[e],this._qt),this._qt.get(e)}catch(t){throw new Ie("get",this._qt,t,[e])}}getKey(e){try{return Ue&&Fe("getKey",[e],this._qt),this._qt.getKey(e)}catch(t){throw new Ie("getKey",this._qt,t,[e])}}delete(e){try{return Ue&&Fe("delete",[e],this._qt),this._qtStore.delete(e)}catch(t){throw new Ie("delete",this._qt,t,[e])}}count(e){try{return this._qt.count(e)}catch(t){throw new Ie("count",this._qt,t,[e])}}index(e){try{return this._qtStore.index(e)}catch(t){throw new Ie("index",this._qt,t,[e])}}get indexNames(){return Array.from(this._qtStore.indexNames)}}class zn extends Mr{constructor(e,t){super(new Ar(e),t)}get _idbStore(){return this._target}index(e){return new Mr(new Ar(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 X(this._idbStore.add(e)),!0}catch(s){if(s instanceof Ti)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)}_prepareErrorLog(e,t,s,i,r){t&&t.ensureRefId(),X(e).catch(o=>{let a;r?a=this._getKeys(r):i&&(a=[i]),this._transaction.addWriteError(o,t,s,a)})}_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 uc(n){return JSON.stringify(Gn(n))}function mc(n){return Jn(JSON.parse(n))}function Gn(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]=Gn(n[t]));return e}else return n}function Jn(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]=Jn(n[t]));return e}else return n}class Ai{constructor(e,t){this._sessionStore=e,this._localStorage=t}get _localStorageKeyPrefix(){return`${this._sessionStore.databaseName}.session.`}async get(e){const t=await this._sessionStore.get(e);if(t)return t.value}_writeKeyToLocalStorage(e,t){try{const s=this._localStorageKeyPrefix+e,i=uc(t);this._localStorage.setItem(s,i)}catch(s){console.error("could not write to localStorage",s)}}writeE2EEIdentityToLocalStorage(){this._sessionStore.iterateValues(void 0,(e,t)=>(t.startsWith(ie)&&this._writeKeyToLocalStorage(t,e.value),!1))}async tryRestoreE2EEIdentityFromLocalStorage(e){let t=!1;const s=this._localStorageKeyPrefix,i=s+ie;for(let r=0;r<this._localStorage.length;r+=1){const o=this._localStorage.key(r);if(o.startsWith(i)){const a=mc(this._localStorage.getItem(o)),c=o.substr(s.length),l=await this._sessionStore.getKey(c)===c;e.set(c,!l),l||(this._sessionStore.put({key:c,value:a}),t=!0)}}return t}set(e,t){e.startsWith(ie)&&this._writeKeyToLocalStorage(e,t),this._sessionStore.put({key:e,value:t})}add(e,t){e.startsWith(ie)&&this._writeKeyToLocalStorage(e,t),this._sessionStore.add({key:e,value:t})}remove(e){e.startsWith(ie)&&this._localStorage.removeItem(this._localStorageKeyPrefix+e),this._sessionStore.delete(e)}}class xr{constructor(e){this._summaryStore=e}getAll(){return this._summaryStore.selectAll()}set(e){this._summaryStore.put(e)}get(e){return this._summaryStore.get(e)}async has(e){const t=await this._summaryStore.getKey(e);return e===t}remove(e){this._summaryStore.delete(e)}}class pc{constructor(e){this._inviteStore=e}getAll(){return this._inviteStore.selectAll()}set(e){this._inviteStore.put(e)}remove(e){this._inviteStore.delete(e)}}var _e=(n=>(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))(_e||{});class mi{constructor(e){this._parentFilter=e}filter(e,t){return!(this._parentFilter&&!this._parentFilter.filter(e,t)||this._min!==void 0&&!Array.isArray(t)&&e.logLevel<this._min)}minLevel(e){return this._min=e,this}}function Cs(){}class _c{constructor(){this.item=new fc(this)}log(){}run(e,t){return t(this.item)}wrapOrRun(e,t,s){return e?e.wrap(t,s):this.run(t,s)}runDetached(e,t){return new Promise(s=>s(t(this.item))).then(Cs,Cs),this.item}async export(){}get level(){return _e}}class fc{constructor(e){this.logger=e}wrap(e,t){return t(this)}log(){return this}set(){return this}runDetached(e,t){return new Promise(s=>s(t(this))).then(Cs,Cs),this}wrapDetached(e,t){return this.refDetached()}refDetached(){}ensureRefId(){}get level(){return _e}get duration(){return 0}catch(e){return e}child(){return this}finish(){}serialize(){}}const gc=new _c;function ae(n,e,t){return`${n}|${Rs(e)}|${Rs(t)}`}function yc(n){const[e,t,s]=n.split("|");return{roomId:e,eventKey:new B(ui(t),ui(s))}}function ms(n,e){return`${n}|${e}`}function Nr(n){const[e,t]=n.split("|");return{roomId:e,eventId:t}}class ps{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(ae(e,this._only.fragmentId,this._only.eventIndex));if(this._lower&&!this._upper)return this._IDBKeyRange.bound(ae(e,this._lower.fragmentId,this._lower.eventIndex),ae(e,this._lower.fragmentId,F.maxStorageKey),this._lowerOpen,!1);if(!this._lower&&this._upper)return this._IDBKeyRange.bound(ae(e,this._upper.fragmentId,F.minStorageKey),ae(e,this._upper.fragmentId,this._upper.eventIndex),!1,this._upperOpen);if(this._lower&&this._upper)return this._IDBKeyRange.bound(ae(e,this._lower.fragmentId,this._lower.eventIndex),ae(e,this._upper.fragmentId,this._upper.eventIndex),this._lowerOpen,this._upperOpen)}catch(t){throw new Re("IDBKeyRange failed with data: "+JSON.stringify(this),t)}}}class wc{constructor(e){this._timelineStore=e}onlyRange(e){return new ps(this._timelineStore.IDBKeyRange,e)}upperBoundRange(e,t=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,void 0,e,void 0,t)}lowerBoundRange(e,t=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,e,void 0,t)}boundRange(e,t,s=!1,i=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,e,t,s,i)}async lastEvents(e,t,s){const i=B.maxKey;return i.fragmentId=t,this.eventsBefore(e,i,s)}async firstEvents(e,t,s){const i=B.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=>ms(e,o)),r=new Map;return await s.findExistingKeys(i,!1,(o,a)=>{const{eventId:c}=Nr(o),{eventKey:l}=yc(a);return r.set(c,l),!1}),r}async findFirstOccurringEventId(e,t){const s=this._timelineStore.index("byEventId"),i=t.map(c=>ms(e,c)),r=new Array(i.length);let o;function a(){for(let c=0;c<r.length;++c){if(r[c]===void 0)return;if(r[c]===!0)return i[c]}}return await s.findExistingKeys(i,!1,(c,l)=>{const h=i.indexOf(c);return r[h]=l,o=a(),!!o}),o&&Nr(o).eventId}tryInsert(e,t){return e.key=ae(e.roomId,e.fragmentId,e.eventIndex),e.eventIdKey=ms(e.roomId,e.event.event_id),this._timelineStore.tryAdd(e,t)}update(e){this._timelineStore.put(e)}get(e,t){return this._timelineStore.get(ae(e,t.fragmentId,t.eventIndex))}getByEventId(e,t){return this._timelineStore.index("byEventId").get(ms(e,t))}removeAllForRoom(e){const t=ae(e,F.minStorageKey,F.minStorageKey),s=ae(e,F.maxStorageKey,F.maxStorageKey),i=this._timelineStore.IDBKeyRange.bound(t,s);this._timelineStore.delete(i)}}const te="\0",G="\u{10FFFF}";function me(n,e,t,s){return`${n}|${e}|${t}|${s}`}function Dr(n){const[e,t,s,i]=n.split("|");return{roomId:e,targetEventId:t,relType:s,sourceEventId:i}}class vc{constructor(e){this._store=e}add(e,t,s,i){this._store.add({key:me(e,t,s,i)})}remove(e,t,s,i){this._store.delete(me(e,t,s,i))}removeAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(me(e,t,te,te),me(e,t,G,G),!0,!0);this._store.delete(s)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(me(e,te,te,te),me(e,G,G,G),!0,!0);this._store.delete(t)}async getForTargetAndType(e,t,s){const i=this._store.IDBKeyRange.bound(me(e,t,s,te),me(e,t,s,G),!0,!0);return(await this._store.selectAll(i)).map(o=>Dr(o.key))}async getAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(me(e,t,te,te),me(e,t,G,G),!0,!0);return(await this._store.selectAll(s)).map(r=>Dr(r.key))}}function Vr(n,e,t){return`${n}|${e}|${t}`}class bc{constructor(e){this._roomStateStore=e}get(e,t,s){const i=Vr(e,t,s);return this._roomStateStore.get(i)}set(e,t){const s=Vr(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}|${G}`,!0,!0);this._roomStateStore.delete(t)}}function _s(n,e){return`${n}|${e}`}function Sc(n){const[e,t]=n.split("|");return{roomId:e,userId:t}}class Qn{constructor(e){this._roomMembersStore=e}get(e,t){return this._roomMembersStore.get(_s(e,t))}set(e){e.key=_s(e.roomId,e.userId),this._roomMembersStore.put(e)}getAll(e){const t=this._roomMembersStore.IDBKeyRange.lowerBound(_s(e,""));return this._roomMembersStore.selectWhile(t,s=>s.roomId===e)}async getAllUserIds(e){const t=[],s=this._roomMembersStore.IDBKeyRange.lowerBound(_s(e,""));return await this._roomMembersStore.iterateKeys(s,i=>{const r=Sc(i);return r.roomId===e?(t.push(r.userId),!1):!0}),t}removeAllForRoom(e){const t=this._roomMembersStore.IDBKeyRange.bound(e,`${e}|${G}`,!0,!0);this._roomMembersStore.delete(t)}}function fs(n,e){return`${n}|${Rs(e)}`}class Ic{constructor(e){this._store=e}_allRange(e){try{return this._store.IDBKeyRange.bound(fs(e,F.minStorageKey),fs(e,F.maxStorageKey))}catch(t){throw new Re(`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=fs(e.roomId,e.id),this._store.add(e)}update(e){this._store.put(e)}get(e,t){return this._store.get(fs(e,t))}removeAllForRoom(e){this._store.delete(this._allRange(e))}}function Qe(n,e){return`${n}|${Rs(e)}`}function Ec(n){const[e,t]=n.split("|"),s=ui(t);return{roomId:e,queueIndex:s}}class kc{constructor(e){this._eventStore=e}async getMaxQueueIndex(e){const t=this._eventStore.IDBKeyRange.bound(Qe(e,F.minStorageKey),Qe(e,F.maxStorageKey),!1,!1),s=await this._eventStore.findMaxKey(t);if(s)return Ec(s).queueIndex}remove(e,t){const s=this._eventStore.IDBKeyRange.only(Qe(e,t));this._eventStore.delete(s)}async exists(e,t){const s=this._eventStore.IDBKeyRange.only(Qe(e,t));return!!await this._eventStore.getKey(s)}add(e){e.key=Qe(e.roomId,e.queueIndex),this._eventStore.add(e)}update(e){this._eventStore.put(e)}getAll(){return this._eventStore.selectAll()}removeAllForRoom(e){const t=Qe(e,F.minStorageKey),s=Qe(e,F.maxStorageKey),i=this._eventStore.IDBKeyRange.bound(t,s);this._eventStore.delete(i)}}class Rc{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 Ye(n,e){return`${n}|${e}`}function Cc(n){const[e,t]=n.split("|");return{userId:e,deviceId:t}}class Tc{constructor(e){this._store=e}getAllForUserId(e){const t=this._store.IDBKeyRange.lowerBound(Ye(e,""));return this._store.selectWhile(t,s=>s.userId===e)}async getAllDeviceIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(Ye(e,""));return await this._store.iterateKeys(s,i=>{const r=Cc(i);return r.userId===e?(t.push(r.deviceId),!1):!0}),t}get(e,t){return this._store.get(Ye(e,t))}set(e){e.key=Ye(e.userId,e.deviceId),this._store.put(e)}getByCurve25519Key(e){return this._store.index("byCurve25519Key").get(e)}remove(e,t){this._store.delete(Ye(e,t))}removeAllForUser(e){const t=this._store.IDBKeyRange.bound(Ye(e,te),Ye(e,G),!0,!0);this._store.delete(t)}}function Nt(n,e){return`${n}|${e}`}function Mc(n){const[e,t]=n.split("|");return{senderKey:e,sessionId:t}}class Ac{constructor(e){this._store=e}async getSessionIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(Nt(e,""));return await this._store.iterateKeys(s,i=>{const r=Mc(i);return r.senderKey===e?(t.push(r.sessionId),!1):!0}),t}getAll(e){const t=this._store.IDBKeyRange.lowerBound(Nt(e,""));return this._store.selectWhile(t,s=>s.senderKey===e)}get(e,t){return this._store.get(Nt(e,t))}set(e){e.key=Nt(e.senderKey,e.sessionId),this._store.put(e)}remove(e,t){this._store.delete(Nt(e,t))}}var Os=(n=>(n[n.NotBackedUp=0]="NotBackedUp",n[n.BackedUp=1]="BackedUp",n))(Os||{}),es=(n=>(n[n.DeviceMessage=1]="DeviceMessage",n[n.Backup=2]="Backup",n[n.Outbound=3]="Outbound",n))(es||{});function gt(n,e,t){return`${n}|${e}|${t}`}class xc{constructor(e){this._store=e}async has(e,t,s){const i=gt(e,t,s),r=await this._store.getKey(i);return i===r}get(e,t,s){return this._store.get(gt(e,t,s))}set(e){const t=e;t.key=gt(e.roomId,e.senderKey,e.sessionId),this._store.put(t)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(gt(e,te,te),gt(e,G,G));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(gt(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 Nc{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 gs(n,e,t){return`${n}|${e}|${t}`}class Dc{constructor(e){this._store=e}get(e,t,s){return this._store.get(gs(e,t,s))}set(e,t,s,i){i.key=gs(e,t,s),this._store.put(i)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(gs(e,te,te),gs(e,G,G));this._store.delete(t)}}function Ut(n,e){return`${n}|${e}`}class Vc{constructor(e){this._store=e}getAll(){return this._store.selectAll()}async getAllByTypeAndScope(e,t){const s=Ut(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=Ut(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(Ut(e,te),Ut(e,G));await this._store.index("byScopeAndType").iterateValues(t,(i,r,o)=>(o.delete(),!0))}}class Lc{constructor(e){this._store=e}async get(e){return await this._store.get(e)}set(e){this._store.put(e)}}class Oc{constructor(e,t,s,i){this.error=e,this.refItem=t,this.operationName=s,this.keys=i}}class Lr{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 Re(`Invalid store for transaction: ${e}, only ${this._allowedStoreNames.join(", ")} are allowed.`);return new zn(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(P.session,e=>new Ai(e,this._storage.localStorage))}get roomSummary(){return this._store(P.roomSummary,e=>new xr(e))}get archivedRoomSummary(){return this._store(P.archivedRoomSummary,e=>new xr(e))}get invites(){return this._store(P.invites,e=>new pc(e))}get timelineFragments(){return this._store(P.timelineFragments,e=>new Ic(e))}get timelineEvents(){return this._store(P.timelineEvents,e=>new wc(e))}get timelineRelations(){return this._store(P.timelineRelations,e=>new vc(e))}get roomState(){return this._store(P.roomState,e=>new bc(e))}get roomMembers(){return this._store(P.roomMembers,e=>new Qn(e))}get pendingEvents(){return this._store(P.pendingEvents,e=>new kc(e))}get userIdentities(){return this._store(P.userIdentities,e=>new Rc(e))}get deviceIdentities(){return this._store(P.deviceIdentities,e=>new Tc(e))}get olmSessions(){return this._store(P.olmSessions,e=>new Ac(e))}get inboundGroupSessions(){return this._store(P.inboundGroupSessions,e=>new xc(e))}get outboundGroupSessions(){return this._store(P.outboundGroupSessions,e=>new Nc(e))}get groupSessionDecryptions(){return this._store(P.groupSessionDecryptions,e=>new Dc(e))}get operations(){return this._store(P.operations,e=>new Vc(e))}get accountData(){return this._store(P.accountData,e=>new Lc(e))}async complete(e){try{await Jt(this._txn)}catch(t){throw this._writeErrors.length?(this._logWriteErrors(e),this._writeErrors[0].error):t}}getCause(e){return e instanceof Re&&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 Oc(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 Or="782rh281re38-boguskey";class Pc{constructor(e,t,s,i,r,o){this._db=e,this.idbFactory=t,this.IDBKeyRange=s,this._hasWebkitEarlyCloseTxnBug=i,this.storeNames=P,this.localStorage=r,this.logger=o}_validateStoreNames(e){const t=e.findIndex(s=>!Gt.includes(s));if(t!==-1)throw new Re(`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 X(t.objectStore(e[0]).get(Or)),new Lr(t,e,this)}catch(t){throw new Re("readTxn failed",t)}}async readWriteTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readwrite");return this._hasWebkitEarlyCloseTxnBug&&await X(t.objectStore(e[0]).get(Or)),new Lr(t,e,this)}catch(t){throw new Re("readWriteTxn failed",t)}}close(){this._db.close()}get databaseName(){return this._db.name}}async function Uc(n){const e=n.transaction(Gt,"readonly"),t={};return await Promise.all(Gt.map(async s=>{const i=t[s]=[],r=e.objectStore(s);await K(r.openCursor(),o=>(i.push(o),Ge))})),t}async function Fc(n,e){const t=n.transaction(Gt,"readwrite");for(const s of Gt){const i=t.objectStore(s);for(const r of e[s])i.add(r)}await Jt(t)}const Yn=[Kc,$c,jc,qc,Wc,Hc,zc,Gc,Jc,Qc,Yc,Xc,Zc,el,tl,sl];function Bc(n){return{databaseName:n.name,get idbFactory(){throw new Error("unused")},get IDBKeyRange(){throw new Error("unused")},addWriteError(){}}}function Kc(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 $c(n,e){const t=new Qn(n.createObjectStore("roomMembers",{keyPath:"key"})),s=e.objectStore("roomState");await K(s.openCursor(),i=>{if(i.event.type===oe){s.delete(i.key);const r=O.fromMemberEvent(i.roomId,i.event);r&&t.set(r.serialize())}return Ge})}async function jc(n,e,t){const s=e.objectStore("session");try{const r=await X(s.get(1));if(r){s.delete(1);const{syncToken:o,syncFilterId:a,serverVersions:c}=r.value,l=new Ai(s,t);l.set("sync",{token:o,filterId:a}),l.set("serverVersions",c)}}catch(i){e.abort(),console.error("could not migrate session",i.stack)}}function qc(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 Wc(n,e){var r;const t=e.objectStore("roomSummary"),s=e.objectStore("roomState"),i=[];await K(t.openCursor(),o=>(i.push(o),Ge));for(const o of i){const a=await X(s.get(`${o.roomId}|m.room.encryption|`));a&&(o.encryption=(r=a==null?void 0:a.event)==null?void 0:r.content,delete o.isEncrypted,t.put(o))}}function Hc(n){n.createObjectStore("accountData",{keyPath:"type"})}function zc(n){n.createObjectStore("invites",{keyPath:"roomId"})}function Gc(n){n.createObjectStore("archivedRoomSummary",{keyPath:"summary.roomId"})}async function Jc(n,e){try{const t=e.objectStore("operations");t.deleteIndex("byTypeAndScope"),await K(t.openCursor(),(s,i,r)=>{const{typeScopeKey:o}=s;delete s.typeScopeKey;const[a,c]=o.split("|");return s.scopeTypeKey=Ut(c,a),r.update(s),Ge}),t.createIndex("byScopeAndType","scopeTypeKey",{unique:!1})}catch(t){e.abort(),console.error("could not migrate operations",t.stack)}}function Qc(n){n.createObjectStore("timelineRelations",{keyPath:"key"})}function Yc(){}async function Xc(n,e){const t=e.objectStore("session"),s=await X(t.get("ssssKey"));s&&t.put({key:`${ie}ssssKey`,value:s.value})}async function Zc(n,e,t,s){const i=e.objectStore("session"),r=new Ai(new zn(i,Bc(n)),t);r.writeE2EEIdentityToLocalStorage();const o=await r.tryRestoreE2EEIdentityFromLocalStorage(s);s.set("restored",o)}async function el(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 K(s.openCursor(),(i,r,o)=>(r.startsWith(ie)||o.delete(),Ge));break}default:{s.clear();break}}}}async function tl(n,e,t,s){e.objectStore("inboundGroupSessions").createIndex("byBackup","backup",{unique:!1})}async function sl(n,e,t,s){const i=e.objectStore("inboundGroupSessions");let r=0,o=0;await K(i.openCursor(),(a,c,l)=>(a.session?(a.backup=Os.NotBackedUp,a.source=es.DeviceMessage,l.update(a),r+=1):o+=1,Ge)),s.set("countWithoutSession",o),s.set("countWithSession",r)}async function il(n){const e="hydrogen_webkit_test_inactive_txn_bug";try{const t=await Mi(e,r=>{r.createObjectStore("test",{keyPath:"key"})},1,n),s=t.transaction(["test"],"readonly");await X(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 Jt(i),t.close()}catch(t){if(t.name==="TransactionInactiveError")return!0}return!1}const Xn=n=>`hydrogen_session_${n}`,si=function(n,e,t,s){const i=(r,o,a,c)=>ol(r,o,a,c,t,s);return Mi(Xn(n),i,Yn.length,e)};async function rl(){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 nl{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)),rl().then(o=>{o||console.warn("no persisted storage, database can be evicted by browser")});const s=await il(this._idbFactory),i=await si(e,this._idbFactory,this._localStorage,t);return new Pc(i,this._idbFactory,this._IDBKeyRange,s,this._localStorage,t.logger)}delete(e){const t=Xn(e),s=this._idbFactory.deleteDatabase(t);return X(s)}async export(e,t){const s=await si(e,this._idbFactory,this._localStorage,t);return await Uc(s)}async import(e,t,s){const i=await si(e,this._idbFactory,this._localStorage,s);return await Fc(i,t)}}async function ol(n,e,t,s,i,r){const o=t||0;return r.wrap({l:"storage migration",oldVersion:t,version:s},async a=>{for(let c=o;c<s;++c){const l=Yn[c];await a.wrap(`v${c+1}`,h=>l(n,e,i,h))}})}class Zn{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=$e(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 a=await this._applyRelation(e,o,t,s);if(a)return a.map(c=>(t.timelineEvents.update(c),new ne(c,this._fragmentIdComparer)))}}return null}async writeGapRelation(e,t,s,i){const r=new ne(e,this._fragmentIdComparer),o=await this.writeRelation(r,s,i);if(t.isBackward&&!di(e.event)){const a=await s.timelineRelations.getAllForTarget(this._roomId,r.id);if(a.length)for(const c of a){const l=await s.timelineEvents.getByEventId(this._roomId,c.sourceEventId);if(l){const h=new ne(l,this._fragmentIdComparer);await this._applyRelation(h,e,s,i)}}}return o}async _applyRelation(e,t,s,i){if(e.eventType===ge)return i.wrap("redact",async r=>{const o=t.event,a=$e(o);if(this._applyRedaction(e.event,t,s,r)){const l=[t];if(a){const h=await this._reaggregateRelation(o,a,s,r);h&&l.push(h)}return l}return null});{const r=$e(e.event);if(r&&!di(t.event)&&r.rel_type===We&&i.wrap("react",c=>this._aggregateAnnotation(e.event,t,c)))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=$e(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),ic(e,r),delete t.annotations,!0}_aggregateAnnotation(e,t){const s=$e(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===We?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,We);return i.set("relations",o.length),delete r.annotations[t],al(r.annotations)&&delete r.annotations,await Promise.all(o.map(async a=>{const c=await s.timelineEvents.getByEventId(this._roomId,a.sourceEventId);c||i.log({l:"missing annotation",id:a.sourceEventId}),$e(c.event).key===t&&this._aggregateAnnotation(c.event,r,i)})),r}}function al(n){for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}class Me{constructor(e){this.isForward=e}get isBackward(){return!this.isForward}asApiString(){return this.isForward?"f":"b"}reverse(){return this.isForward?Me.Backward:Me.Forward}static get Forward(){return cl}static get Backward(){return ll}}const cl=new Me(!0),ll=new Me(!1);class ce extends Kn{constructor(e,t,s){super(s),this._fragment=e,this._isFragmentStart=t}static start(e,t){return new ce(e,!0,t)}static end(e,t){return new ce(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?F.minStorageKey:F.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 Ci(this.linkedFragmentId)}get direction(){return this.started?Me.Backward:Me.Forward}withUpdatedFragment(e){return new ce(e,this._isFragmentStart,this._fragmentIdComparer)}createNeighbourEntry(e){return new ce(e,!this._isFragmentStart,this._fragmentIdComparer)}addLocalRelation(){}removeLocalRelation(){}}function hl(n){const e=new Set;return n.filter(t=>e.has(t.event_id)?!1:(e.add(t.event_id),!0))}class dl{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:B.defaultLiveKey.eventIndex;this._lastLiveKey=new B(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:B.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:a,newFragment:c}=await this._replaceLiveFragment(o,e.fragmentId,s.prev_batch,i);t.push(ce.end(a,this._fragmentIdComparer)),t.push(ce.start(c,this._fragmentIdComparer)),r.log({l:"live fragment",limited:!0,id:e.fragmentId})}}else{let o=await this._createLiveFragment(i,s.prev_batch);e=new B(o.id,B.defaultLiveKey.eventIndex),t.push(ce.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!==oe&&(t.roomState.set(this._roomId,r),i+=1);s.set("stateEvents",i)}async _writeTimeline(e,t,s,i,r,o){const a=[],c=[];if(e!=null&&e.length){i=await this._ensureLiveFragment(i,a,t,r,o),o.set("timelineEvents",e.length);let l=0;for(const h of e){i=i.nextKey();const d=qn(i,this._roomId,h);let u=await s.lookupMemberAtEvent(h.sender,h,r);if(u&&(d.displayName=u.displayName,d.avatarUrl=u.avatarUrl),!await r.timelineEvents.tryInsert(d,o))continue;const _=new ne(d,this._fragmentIdComparer);a.push(_);const f=await this._relationWriter.writeRelation(_,r,o);f&&c.push(...f),typeof h.state_key=="string"&&h.type!==oe&&(l+=1,r.roomState.set(this._roomId,h))}o.set("timelineStateEventCount",l)}return{currentKey:i,entries:a,updatedEntries:c}}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:a}=e,c=a.findIndex(l=>l.event_id===o);if(c!==-1)return s.set("overlap_event_id",o),Object.assign({},e,{limited:!1,events:a.slice(c+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 a;Array.isArray(o==null?void 0:o.events)&&(a=hl(o.events));const{state:c}=e;let l;Array.isArray(c==null?void 0:c.events)&&(l=c.events);const h=this._memberWriter.prepareMemberSync(l,a,s);l&&await this._writeStateEvents(l,i,r);const{currentKey:d,entries:u,updatedEntries:p}=await this._writeTimeline(a,o,h,this._lastLiveKey,i,r),_=await h.write(i);return{entries:u,updatedEntries:p,newLiveKey:d,memberChanges:_}}afterSync(e){this._lastLiveKey=e}get lastMessageKey(){return this._lastLiveKey}}class eo{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 ul extends eo{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 ml{constructor(e){this._roomId=e,this._cache=new ul(5,t=>t.userId)}prepareMemberSync(e,t,s){return new pl(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 O(i))}if(!s||!s.equals(e))return t.roomMembers.set(e.serialize()),this._cache.set(e),new Wn(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 O(i),this._cache.set(s))}return s}}class pl{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===oe){const i=O.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===oe&&!(t!=null&&t.has(r))){const o=O.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===oe&&r.state_key===e){const o=O.fromMemberEvent(this._roomId,r);if(o)return o}}}}class _l{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(l=>l.event_id),o=await s.timelineEvents.getEventKeysForIds(this._roomId,r);i.set("existingEvents",o.size);const a=t.filter(l=>!o.has(l.event_id));i.set("nonOverlappingEvents",a.length);let c;if(e.hasLinkedFragment){i.set("linkedFragmentId",e.linkedFragmentId);for(const l of o.values())if(l.fragmentId===e.linkedFragmentId){i.set("foundLinkedFragment",!0);const h=await s.timelineFragments.get(this._roomId,e.linkedFragmentId);c=e.createNeighbourEntry(h);break}}return{nonOverlappingEvents:a,neighbourFragmentEntry:c}}async _findFragmentEdgeEventKey(e,t){const{fragmentId:s,direction:i}=e,r=await this._findFragmentEdgeEvent(s,i,t);return r?new B(r.fragmentId,r.eventIndex):B.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 a=[],c=[];let l=t;for(let h=0;h<e.length;++h){const d=e[h];l=l.nextKeyForDirection(s);const u=qn(l,this._roomId,d),p=this._findMember(d.sender,i,e,h,s);p&&(u.displayName=p.displayName,u.avatarUrl=p.avatarUrl);const _=await this._relationWriter.writeGapRelation(u,s,r,o);if(_&&c.push(..._),await r.timelineEvents.tryInsert(u,o)){const f=new ne(u,this._fragmentIdComparer);jt(a,f,s)}}return{entries:a,updatedEntries:c}}_findMember(e,t,s,i,r){function o(l){return l.type===oe&&l.state_key===e}const a=r.isBackward?1:-1;for(let l=i+a;l>=0&&l<s.length;l+=a){const h=s[l];if(o(h))return O.fromMemberEvent(this._roomId,h)}for(let l=i;l>=0&&l<s.length;l-=a){const h=s[l];if(o(h))return O.fromReplacingMemberEvent(this._roomId,h)}const c=t==null?void 0:t.find(o);if(c)return O.fromMemberEvent(this._roomId,c)}async _updateFragments(e,t,s,i,r,o){const{direction:a}=e,c=[];return jt(i,e,a),t?(o.set("closedGapWith",t.fragmentId),t.token=null,e.token=null,r.timelineFragments.update(t.fragment),jt(i,t,a),c.push(e.fragment),c.push(t.fragment)):e.token=s,r.timelineFragments.update(e.fragment),c}async writeFragmentFill(e,t,s,i){const{fragmentId:r,direction:o}=e,{chunk:a,start:c,state:l}=t;let{end:h}=t;if(!Array.isArray(a))throw new Error("Invalid chunk in response");if(typeof h!="string"&&typeof h!="undefined")throw new Error("Invalid end token in response");const d=await s.timelineFragments.get(this._roomId,r);if(!d)throw new Error(`Unknown fragment: ${r}`);if(e=e.withUpdatedFragment(d),e.token!==c)throw new Error("start is not equal to prev_batch or next_batch");if(a.length===0)return e.edgeReached=!0,await s.timelineFragments.update(e.fragment),{entries:[e],updatedEntries:[],fragments:[]};let u=await this._findFragmentEdgeEventKey(e,s);i.set("lastKey",u.toString());const{nonOverlappingEvents:p,neighbourFragmentEntry:_}=await this._findOverlappingEvents(e,a,s,i),{entries:f,updatedEntries:b}=await this._storeEvents(p,u,o,l,s,i),S=await this._updateFragments(e,_,h,f,s,i);return{entries:f,updatedEntries:b,fragments:S}}}class Rt extends Ii{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 <https://lodash.com/>
* Copyright JS Foundation and other contributors <https://js.foundation/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/function He(n,e,t){let s=0,i=n.length;for(;s<i;){let r=s+i>>>1,o=t(e,n[r]);o>0?s=r+1:o<0?i=r:s=i=r}return i}class Ct extends Ii{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)}}class qt extends Ct{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 fl extends Rt{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=He(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=He(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(a=>a.key===e);this._sortedPairs.splice(i,1);const r={key:e,value:t},o=He(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 gl extends Ct{constructor(e,t){super(),this._source=e,this._filter=t,this._included=null,this._subscription=null}setFilter(e){this._filter=e,this._subscription&&this._reapplyFilter()}_reapplyFilter(e=!1){if(this._filter){const t=this._included;this._included=this._included||new Map;for(const[s,i]of this._source){const r=this._filter(i,s);if(this._included.set(s,r),!e){const o=t?t.get(s):!0;this._emitForUpdate(o,r,s,i)}}}else{if(this._included&&!e)for(const[t,s]of this._source)this._included.get(t)||this.emitAdd(t,s);this._included=null}}onAdd(e,t){if(this._filter){const s=this._filter(t,e);if(this._included.set(e,s),!s)return}this.emitAdd(e,t)}onRemove(e,t){const s=!this._filter||this._included.get(e);this._included.delete(e),s&&this.emitRemove(e,t)}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=null,this._subscription=this._subscription()}onReset(){this._reapplyFilter(),this.emitReset()}[Symbol.iterator](){return new yl(this._source,this._included)}get size(){let e=0;return this._included.forEach(t=>{t&&(e+=1)}),e}get(e){const t=this._source.get(e);if(t&&this._filter(t,e))return t}}class yl{constructor(e,t){this._included=t,this._sourceIterator=e[Symbol.iterator]()}next(){for(;;){const e=this._sourceIterator.next();if(e.done)return e;const t=e.value[0];if(this._included.get(t))return e}}}class wl extends Ct{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)&&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,i,s,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._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 vl extends Ct{constructor(e){super(),this._sources=e,this._subscriptions=null}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 Sl(e,this).subscribe()),super.onSubscribeFirst()}_isKeyAtSourceOccluded(e,t){const s=this._sources.indexOf(e);for(let i=0;i<s;i+=1)if(this._sources[i].get(t)!==void 0)return!0;return!1}_getValueFromOccludedSources(e,t){const s=this._sources.indexOf(e);for(let i=s+1;i<this._sources.length;i+=1){const o=this._sources[i].get(t);if(o!==void 0)return o}}onUnsubscribeLast(){super.onUnsubscribeLast();for(const e of this._subscriptions)e.dispose()}[Symbol.iterator](){return new bl(this._sources)}get size(){return this._sources.reduce((e,t)=>e+t.size,0)}get(e){for(const t of this._sources){const s=t.get(e);if(s)return s}return null}}class bl{constructor(e){this._sources=e,this._sourceIndex=-1,this._currentIterator=null,this._encounteredKeys=new Set}next(){let e;for(;!e;){if(!this._currentIterator){if(this._sourceIndex+=1,this._sources.length<=this._sourceIndex)return{done:!0};this._currentIterator=this._sources[this._sourceIndex][Symbol.iterator]()}const t=this._currentIterator.next();if(t.done){this._currentIterator=null;continue}else{const s=t.value[0];this._encounteredKeys.has(s)||(this._encounteredKeys.add(s),e=t)}}return e}}class Sl{constructor(e,t){this._source=e,this._joinedMap=t,this._subscription=null}subscribe(){return this._subscription=this._source.subscribe(this),this}dispose(){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(this._source)}}class Il extends Rt{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<this._items.length&&t<this._items.length){const[s]=this._items.splice(e,1);this._items.splice(t,0,s),this.emitMove(e,t,s)}}update(e,t,s=null){e<this._items.length&&(this._items[e]=t,this.emitUpdate(e,t,s))}get array(){return this._items}at(e){if(this._items&&e>=0&&e<this._items.length)return this._items[e]}get length(){return this._items.length}[Symbol.iterator](){return this._items.values()}}function to(n,e,t,s){const i=e.findIndex(n);if(i!==-1){const r=e[i],o=s(r);return o!==!1&&t.emitUpdate(i,r,o),!0}return!1}class xi extends Rt{constructor(e){super(),this._items=[],this._comparator=e}setManyUnsorted(e){this.setManySorted(e)}setManySorted(e){for(let t of e)this.set(t)}findAndUpdate(e,t){return to(e,this._items,this,t)}getAndUpdate(e,t,s=null){const i=this.indexOf(e);if(i!==-1){const r=this._items[i],o=t(r,e);this._items[i]=o,this.emitUpdate(i,o,s)}}update(e,t=null){const s=this.indexOf(e);s!==-1&&(this._items[s]=e,this.emitUpdate(s,e,t))}indexOf(e){const t=He(this._items,e,this._comparator);return t<this._items.length&&this._comparator(this._items[t],e)===0?t:-1}_getNext(e){let t=He(this._items,e,this._comparator);for(;t<this._items.length&&this._comparator(this._items[t],e)<=0;)t+=1;return this.get(t)}set(e,t=null){const s=He(this._items,e,this._comparator);s>=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 El(this)}}class El{constructor(e){this._sortedArray=e,this._current=null}next(){if(this._sortedArray){if(this._current?this._current=this._sortedArray._getNext(this._current):this._current=this._sortedArray.get(0),this._current)return{value:this._current};this._sortedArray=null}if(!this._sortedArray)return{done:!0}}}class kl extends Rt{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 to(e,this._mappedValues,this,t)}get length(){return this._mappedValues.length}[Symbol.iterator](){return this._mappedValues.values()}}function Rl(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 Tl(n,e){const t=n._mappedValues[e];n._mappedValues.splice(e,1),n._removeCallback&&n._removeCallback(t),n.emitRemove(e,t)}function Ml(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 Al(n){n._mappedValues=[],n.emitReset()}class xl extends kl{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 Pr(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 Ll),this._flush())}onAdd(e,t){this._eventQueue&&(this._eventQueue.push(new Pr(e,t)),this._flush())}onUpdate(e,t,s){this._eventQueue&&(this._eventQueue.push(new Nl(e,t,s)),this._flush())}onRemove(e){this._eventQueue&&(this._eventQueue.push(new Dl(e)),this._flush())}onMove(e,t){this._eventQueue&&(this._eventQueue.push(new Vl(e,t)),this._flush())}onUnsubscribeLast(){this._sourceUnsubscribe(),this._eventQueue=null,this._mappedValues=null}}class Pr{constructor(e,t){this.index=e,this.value=t}async run(e){const t=await e._mapper(this.value);Rl(e,this.index,t)}}class Nl{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 Dl{constructor(e){this.index=e}async run(e){Tl(e,this.index)}}class Vl{constructor(e,t){this.fromIdx=e,this.toIdx=t}async run(e){Ml(e,this.fromIdx,this.toIdx)}}class Ll{async run(e){Al(e)}}class Ol extends Rt{constructor(...e){super(),this._sourceUnsubscribes=null,this._sourceLists=e}_offsetForSource(e){const t=this._sourceLists.indexOf(e);let s=0;for(let i=0;i<t;++i)s+=this._sourceLists[i].length;return s}onSubscribeFirst(){this._sourceUnsubscribes=this._sourceLists.map(e=>e.subscribe(this))}onUnsubscribeLast(){for(const e of this._sourceUnsubscribes)e()}onReset(){this.emitReset();let e=0;for(const t of this)this.emitAdd(e,t),e+=1}onAdd(e,t,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<this._sourceLists.length;++t)e+=this._sourceLists[t].length;return e}[Symbol.iterator](){let e=0,t=this._sourceLists[0][Symbol.iterator]();return{next:()=>{let 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}}}}Object.assign(Ct.prototype,{sortValues(n){return new fl(this,n)},mapValues(n,e){return new wl(this,n,e)},filterValues(n){return new gl(this,n)},join(...n){return new vl([this].concat(n))}});function ii(n){typeof n=="function"?n():n.dispose()}function Pl(n){return n&&(typeof n=="function"||typeof n.dispose=="function")}class Ni{constructor(){this._disposables=[]}track(e){if(!Pl(e))throw new Error("Not a disposable");return this.isDisposed?(console.warn("Disposables already disposed, disposing new value"),ii(e),e):(this._disposables.push(e),e)}untrack(e){if(this.isDisposed){console.warn("Disposables already disposed, cannot untrack");return}const t=this._disposables.indexOf(e);t>=0&&this._disposables.splice(t,1)}dispose(){if(this._disposables){for(const e of this._disposables)ii(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);ii(s)}else console.warn("disposable not found, did it leak?",e)}}class Ur{constructor(e,t){this.decryptRequest=null,this._promise=e(this,t)}complete(){return this._promise}dispose(){this.decryptRequest&&(this.decryptRequest.dispose(),this.decryptRequest=null)}}async function Ul(n,e,t,s,i,r){let o=[];const a=r.timelineEvents,c=r.timelineFragments;for(;o.length<s&&e;){let l;t.isForward?l=await a.eventsAfter(n,e,s):l=await a.eventsBefore(n,e,s);let h=l.map(d=>new ne(d,i));if(o=ec(o,h,t),o.length<s){const d=await c.get(n,e.fragmentId);let u=new ce(d,t.isBackward,i);if(jt(o,u,t),!u.token&&u.hasLinkedFragment){const p=await c.get(n,u.linkedFragmentId);i.add(p);const _=new ce(p,t.isForward,i);jt(o,_,t),e=_.asEventKey()}else e=null}}return o}class so{constructor({roomId:e,storage:t,fragmentIdComparer:s}){this._roomId=e,this._storage=t,this._fragmentIdComparer=s,this._decryptEntries=null}enableEncryption(e){this._decryptEntries=e}get readTxnStores(){const e=[this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineFragments];return this._decryptEntries&&e.push(this._storage.storeNames.inboundGroupSessions),e}readFrom(e,t,s,i){return new Ur(async(r,o)=>{const a=await this._storage.readTxn(this.readTxnStores);return await this._readFrom(e,t,s,r,a,o)},i)}readFromEnd(e,t=null,s){return new Ur(async(i,r)=>{const o=t||await this._storage.readTxn(this.readTxnStores),a=await o.timelineFragments.liveFragment(this._roomId);let c;if(!a)c=[];else{this._fragmentIdComparer.add(a);const l=ce.end(a,this._fragmentIdComparer),h=l.asEventKey();c=await this._readFrom(h,Me.Backward,e,i,o,r),c.unshift(l)}return c},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 ne(r,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o],i,t).complete(),o}}async _readFrom(e,t,s,i,r,o){const a=await Ul(this._roomId,e,t,s,this._fragmentIdComparer,r);if(this._decryptEntries){i.decryptRequest=this._decryptEntries(a,r,o);try{await i.decryptRequest.complete()}finally{i.decryptRequest=null}}return a}}class Fl extends ne{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 Bl{constructor(e){this._userId=e}get id(){return this._userId}}class Ts{constructor({roomId:e,storage:t,closeCallback:s,fragmentIdComparer:i,pendingEvents:r,clock:o,powerLevelsObservable:a,hsApi:c}){this._roomId=e,this._storage=t,this._closeCallback=s,this._fragmentIdComparer=i,this._disposables=new Ni,this._pendingEvents=r,this._clock=o,this._remoteEntries=new xi((l,h)=>l.compare(h)),this._ownMember=null,this._timelineReader=new so({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}),this._readerRequest=null,this._allEntries=null,this._contextEntriesNotInTimeline=new Map,this._decryptEntries=null,this._hsApi=c,this.initializePowerLevels(a)}initializePowerLevels(e){e&&(this._powerLevels=e.get(),this._disposables.track(e.subscribe(t=>this._powerLevels=t)))}async load(e,t,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 O(r):this._ownMember=O.fromUserId(this._roomId,e.id,t);const o=this._disposables.track(this._timelineReader.readFromEnd(20,i,s));try{const a=await o.complete();this._loadContextEntriesWhereNeeded(a),this._setupEntries(a)}finally{this._disposables.disposeTracked(o)}}_setupEntries(e){this._remoteEntries.setManySorted(e),this._pendingEvents?this._localEntries=new xl(this._pendingEvents,t=>this._mapPendingEventToEntry(t),(t,s)=>{t.notifyUpdate(s)},t=>this._applyAndEmitLocalRelationChange(t,s=>s.removeLocalRelation(t))):this._localEntries=new Il,this._allEntries=new Ol(this._remoteEntries,this._localEntries)}async _mapPendingEventToEntry(e){let t;e.eventType===ge&&(t=await this._getOrLoadEntry(e.relatedTxnId,e.relatedEventId));const s=new Xa({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 a=t(o);return a||!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(a=>this._emitUpdateForEntry(a,"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,We);for(const r of i){const o=await s.timelineEvents.getByEventId(this._roomId,r.sourceEventId);if(o&&o.event.sender===this._ownMember.userId&&$e(o.event).key===t){const a=new ne(o,this._fragmentIdComparer);return this._addLocalRelationsToNewRemoteEntries([a]),a}}return null}updateOwnMember(e){this._ownMember=e}_addLocalRelationsToNewRemoteEntries(e){var t;if(!!((t=this._localEntries)!=null&&t.hasSubscriptions))for(const 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,Ts._entryUpdater);const i=this._contextEntriesNotInTimeline.get(s.id);i&&(Ts._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._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(a=>a.type===oe&&a.user_id===s),r={event:t.event,displayName:i.content.displayname,avatarUrl:i.content.avatar_url},o=new Fl(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(),Me.Backward,e));try{const i=await s.complete();return this.addEntries(i),i.length<e}finally{this._disposables.disposeTracked(s)}}async _getOrLoadEntry(e,t){var s;if(e){for(const i of this._localEntries)if(i.id===e)return i}return t?(s=this.getByEventId(t))!=null?s:await this._getEventFromStorage(t):null}getByEventId(e){for(let t=0;t<this._remoteEntries.length;t+=1){const s=this._remoteEntries.get(t);if(s.id===e)return s}return null}get entries(){return this._allEntries}get remoteEntries(){return this._remoteEntries.array}dispose(){this._closeCallback&&(this._disposables.dispose(),this._closeCallback(),this._closeCallback=null)}enableEncryption(e){this._decryptEntries=e,this._timelineReader.enableEncryption(e)}get powerLevels(){return this._powerLevels}get me(){return this._ownMember}}async function Kl({roomId:n,storage:e,txn:t}){return t||(t=await e.readTxn([e.storeNames.roomMembers])),(await t.roomMembers.getAll(n)).map(i=>new O(i))}async function $l({summary:n,syncToken:e,roomId:t,hsApi:s,storage:i,setChangedMembersMap:r},o){const a=new Map;r(a);const c=await s.members(t,{at:e},{log:o}).response(),l=await i.readWriteTxn([i.storeNames.roomSummary,i.storeNames.roomMembers]);let h,d;try{h=n.writeHasFetchedMembers(!0,l);const{roomMembers:u}=l,p=c.chunk;if(!Array.isArray(p))throw new Error("malformed");o.set("members",p.length),d=await Promise.all(p.map(async _=>{const f=_==null?void 0:_.state_key;if(!f)throw new Error("malformed");const b=a.get(f);if(b)return b;{const S=O.fromMemberEvent(t,_);return S&&u.set(S.serialize()),S}}))}catch(u){throw l.abort(),u}finally{r(null)}return await l.complete(),n.applyChanges(h),d}async function jl(n,e){const{summary:t}=n;return t.data.hasFetchedMembers?Kl(n):e.wrapOrRun(n.log,"fetchMembers",s=>$l(n,s))}async function ql(n,e){const t=await Wl(n),{summary:s}=n;return!s.data.hasFetchedMembers&&!t?e.wrapOrRun(n.log,"fetchMember",i=>Hl(n,i)):t}async function Wl({roomId:n,userId:e,storage:t}){const i=await(await t.readTxn([t.storeNames.roomMembers])).roomMembers.get(n,e);return i?new O(i):null}async function Hl({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(c){if(c.name==="HomeServerError"&&c.errcode==="M_NOT_FOUND")return null;throw c}const o=new O({roomId:n,userId:e,membership:r.membership,avatarUrl:r.avatar_url,displayName:r.displayname}),a=await s.readWriteTxn([s.storeNames.roomMembers]);try{a.roomMembers.set(o.serialize())}catch(c){throw a.abort(),c}return await a.complete(),o}class zl{constructor(e){this._retentionCount=1,this._freeCallback=e}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._freeCallback()}}class Gl extends zl{constructor({members:e,closeCallback:t}){super(t),this._members=new qt;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 pi(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.length<s?n.map(i=>i.name).join(", ")+` and ${s} others`:null}class Di{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,a]of t.entries())(this._members.has(o)||e.indexOf(o)!==-1)&&i.set(o,a.member);for(const o of e)if(!this._members.has(o)&&!i.has(o)){const a=await s.roomMembers.get(this._roomId,o);if(a){const c=new O(a);i.set(c.userId,c)}}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)this._members.set(o.userId,o);const r=Array.from(this._members.values()).sort((o,a)=>o.name.localeCompare(a.name));this._roomName=pi(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 Jl{constructor(e){this._map=new Map,this._notifyEmpty=e}observe(e,t=null){let s=this._map.get(e);return s||(s=new Ql(this,t,e),this._map.set(e,s)),s}updateEvents(e){for(let t=0;t<e.length;t+=1){const s=e[t],i=this._map.get(s.id);i==null||i.update(s)}}_remove(e){this._map.delete(e),this._map.size===0&&this._notifyEmpty()}}class Ql extends kt{constructor(e,t,s){super(),this._eventMap=e,this._entry=t,this._id=s,Promise.resolve().then(()=>{this.hasSubscriptions||(this._eventMap._remove(this._id),this._eventMap=null)})}subscribe(e){if(!this._eventMap)throw new Error("ObservedEvent expired, subscribe right after calling room.observeEvent()");return super.subscribe(e)}onUnsubscribeLast(){this._eventMap._remove(this._id),this._eventMap=null,super.onUnsubscribeLast()}update(e){this._entry=e,this.emit(this._entry)}get(){return this._entry}}function Yl(n){return n||gc.item}const Xl="m.room.power_levels";class Es{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;const t=(s=this._plEvent)==null?void 0:s.content[e];return typeof t=="number"?t:50}_getEventTypeLevel(e){var s,i,r;const t=(i=(s=this._plEvent)==null?void 0:s.content.events)==null?void 0:i[e];if(typeof t=="number")return t;{const o=(r=this._plEvent)==null?void 0:r.content.events_default;return typeof o=="number"?o:0}}}const Zl="m.room.encrypted";class io extends Ls{constructor({roomId:e,storage:t,hsApi:s,mediaRepository:i,emitCollectionChange:r,user:o,createRoomEncryption:a,getSyncToken:c,platform:l}){super(),this._roomId=e,this._storage=t,this._hsApi=s,this._mediaRepository=i,this._summary=new $a(e),this._fragmentIdComparer=new cc([]),this._emitCollectionChange=r,this._timeline=null,this._user=o,this._changedMembersDuringSync=null,this._memberList=null,this._createRoomEncryption=a,this._roomEncryption=null,this._getSyncToken=c,this._platform=l,this._observedEvents=null,this._powerLevels=null,this._powerLevelLoading=null,this._observedMembers=null}async _eventIdsToEntries(e,t){const s=[];return await Promise.all(e.map(async i=>{const r=await t.timelineEvents.getByEventId(this._roomId,i);r&&s.push(new ne(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 a=this._getAdditionalTimelineRetryEntries(r,[e]);r=r.concat(a)}if(r.length){await this._decryptEntries(st.Retry,r,i,s).complete(),(o=this._timeline)==null||o.replaceEntries(r);const c=this._summary.data.applyTimelineEntries(r,!1,!1);await this._summary.writeAndApplyData(c,this._storage)&&this._emitUpdate()}}_setEncryption(e){return e&&!this._roomEncryption?(this._roomEncryption=e,this._timeline&&this._timeline.enableEncryption(this._decryptEntries.bind(this,st.Timeline)),!0):!1}_decryptEntries(e,t,s,i=null){return new eh(async(o,a)=>{if(s||(s=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions])),o.cancelled)return;const c=t.filter(_=>_.eventType===Zl).map(_=>_.event);if(o.preparation=await this._roomEncryption.prepareDecryptAll(c,null,e,s),o.cancelled)return;const l=await o.preparation.decrypt();if(o.preparation=null,o.cancelled)return;const h=[this._storage.storeNames.groupSessionDecryptions],d=this._isTimelineOpen;d&&h.push(this._storage.storeNames.deviceIdentities);const u=await this._storage.readWriteTxn(h);let p;try{p=await l.write(u,a),d&&await p.verifySenders(u)}catch(_){throw u.abort(),_}await u.complete(),p.applyToEntries(t),this._observedEvents&&this._observedEvents.updateEvents(t)},Yl(i))}async _getSyncRetryDecryptEntries(e,t,s){let r=(await Promise.all(e.map(async o=>{const a=await t.getEventIdsForMissingKey(o,s);if(a)return this._eventIdsToEntries(a,s)}))).reduce((o,a)=>a?o.concat(a):o,[]);if(this._timeline){const a=this._getAdditionalTimelineRetryEntries(r,e).map(c=>c.clone());r=r.concat(a)}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 Di(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 xn(`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 ql({summary:this._summary,roomId:this._roomId,userId:e,storage:this._storage,hsApi:this._hsApi},this._platform.logger);if(!s)return null;const i=new ci(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 jl({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 Gl({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 a,c;try{a=await this._writeGapFill(r.chunk,o,i);const l=new Zn({roomId:this._roomId,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});c=await new _l({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,relationWriter:l}).writeFragmentFill(e,r,o,i)}catch(l){throw o.abort(),l}await o.complete(),this._roomEncryption&&await this._decryptEntries(st.Timeline,c.entries,null,i).complete();for(const l of c.fragments)this._fragmentIdComparer.add(l);a&&this._applyGapFill(a),this._timeline&&(this._timeline.replaceEntries(c.updatedEntries),this._timeline.addEntries(c.entries))})}async _writeGapFill(e,t,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}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 Es({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 Es({createEvent:s.event,ownUserId:this._user.id,membership:this.membership});{const i=this.membership;return new Es({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 ci(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)}openTimeline(e=null){return this._platform.logger.wrapOrRun(e,"open timeline",async t=>{if(t.set("id",this.id),this._timeline)throw new Error("not dealing with load race here for now");this._timeline=new Ts({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,st.Timeline)),await this._timeline.load(this._user,this.membership,t)}catch(s){throw this._timeline.dispose(),s}return this._timeline})}_getPendingEvents(){return null}observeEvent(e){this._observedEvents||(this._observedEvents=new Jl(()=>{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 so({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}).readById(e)}dispose(){var e,t;(e=this._roomEncryption)==null||e.dispose(),(t=this._timeline)==null||t.dispose()}}class eh{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()}}function Ms(){const e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16);return"t"+"0".repeat(14-e.length)+e}function Fr(n){return n.startsWith("t")&&n.length===15}class th{constructor({roomId:e,storage:t,hsApi:s,pendingEvents:i}){i=i||[],this._roomId=e,this._storage=t,this._hsApi=s,this._pendingEvents=new xi((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 Za({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 qe?(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 a;if(o?a=this._pendingEvents.array.findIndex(c=>c.txnId===o):a=this._pendingEvents.array.findIndex(c=>c.remoteId===r.event_id),a!==-1){const c=this._pendingEvents.get(a),l=r.event_id;s.log({l:"removeRemoteEcho",queueIndex:c.queueIndex,remoteId:l,txnId:o}),t.pendingEvents.remove(c.roomId,c.queueIndex),i.push(c),await this._resolveRemoteIdInPendingRelations(o,l,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=ze(t);let o=null;if(r){const a=Ri(r);if(Fr(a)&&(o=a,$n(r,null)),r.rel_type===We&&this._pendingEvents.array.some(l=>{const h=ze(l.content);return l.eventType===e&&h&&h.key===r.key&&(l.relatedTxnId===o||h.event_id===r.event_id)})){i.set("already_annotating",!0);return}}await this._enqueueEvent(e,t,s,o,null,i)}async _enqueueEvent(e,t,s,i,r,o){const a=await this._createAndStoreEvent(e,t,i,r,s);this._pendingEvents.set(a),o.set("queueIndex",a.queueIndex),o.set("pendingEvents",this._pendingEvents.length),!this._isSending&&!this._offline&&this._sendLoop(o),this._sendLoopLogItem&&o.refDetached(this._sendLoopLogItem)}async enqueueRedaction(e,t,s){if(this._pendingEvents.array.some(a=>a.eventType===ge&&(a.relatedTxnId===e||a.relatedEventId===e))){s.set("already_redacting",!0);return}let r,o;if(Fr(e)){r=e;const a=e,c=this._pendingEvents.array.find(l=>l.txnId===a);if(c&&!c.remoteId&&c.status!==V.Sending){s.set("remove",r),await c.abort();return}else if(c)o=c.remoteId;else return}else{o=e;const a=this._pendingEvents.array.find(c=>c.remoteId===o);a&&(r=a.txnId)}s.set("relatedTxnId",r),s.set("relatedEventId",o),await this._enqueueEvent(ge,{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 a;try{const c=o.pendingEvents,l=await c.getMaxQueueIndex(this._roomId)||0,d=Math.max(l,this._currentQueueIndex)+1,u=e!==ge&&e!==qa&&!!this._roomEncryption;a=this._createPendingEvent({roomId:this._roomId,queueIndex:d,eventType:e,content:t,relatedTxnId:s,relatedEventId:i,txnId:Ms(),needsEncryption:u,needsUpload:!!r},r),c.add(a.data)}catch(c){throw o.abort(),c}return await o.complete(),a}dispose(){for(const e of this._pendingEvents)e.dispose()}}class ro{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 Ia(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"));ys(`${s}info.size`,t,this._transferredBlob.size),ys(`${s}info.mimetype`,t,this._unencryptedBlob.mimeType),this._encryptionInfo?ys(`${s}file`,t,Object.assign(this._encryptionInfo,{mimetype:this._unencryptedBlob.mimeType,url:this._mxcUrl})):ys(`${s}url`,t,this._mxcUrl)}dispose(){this._unencryptedBlob.dispose(),this._transferredBlob.dispose()}}function ys(n,e,t){const s=n.split(".");let i=e;for(let o=0;o<s.length-1;o+=1){const a=s[o];i[a]||(i[a]={}),i=i[a]}const r=s[s.length-1];i[r]=t}const sh="m.room.encrypted";class ih extends io{constructor(e){super(e);const{pendingEvents:t}=e,s=new Zn({roomId:this.id,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});this._syncWriter=new dl({roomId:this.id,fragmentIdComparer:this._fragmentIdComparer,relationWriter:s,memberWriter:new ml(this.id)}),this._sendQueue=new th({roomId:this.id,storage:this._storage,hsApi:this._hsApi,pendingEvents:t})}_setEncryption(e){return super._setEncryption(e)?(this._sendQueue.enableEncryption(this._roomEncryption),!0):!1}async prepareSync(e,t,s,i,r){var h;r.set("id",this.id),s&&r.set("newKeys",s.length);let o=this._summary.data.applySyncResponse(e,t,this._user.id),a=this._roomEncryption;!a&&o.encryption&&(r.set("enableEncryption",!0),a=this._createRoomEncryption(this,o.encryption));let c,l;if(a){let d=((h=e==null?void 0:e.timeline)==null?void 0:h.events)||[];s&&(c=await this._getSyncRetryDecryptEntries(s,a,i),c.length&&(r.set("retry",c.length),d=d.concat(c.map(u=>u.event)))),d=d.filter(u=>(u==null?void 0:u.type)===sh),d.length&&(l=await a.prepareDecryptAll(d,s,st.Sync,i))}return{roomEncryption:a,summaryChanges:o,decryptPreparation:l,decryptChanges:null,retryEntries:c}}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},a,c){var R;c.set("id",this.id);const l=s.isNewJoin(this._summary.data);l&&(a.roomState.removeAllForRoom(this.id),a.roomMembers.removeAllForRoom(this.id));const{entries:h,updatedEntries:d,newLiveKey:u,memberChanges:p}=await c.wrap("syncWriter",w=>this._syncWriter.writeSync(e,l,s.hasFetchedMembers,a,w),c.level.Detail);if(i){const w=await c.wrap("decryptChanges",I=>i.write(a,I));c.set("decryptionResults",w.results.size),c.set("decryptionErrors",w.errors.size),this._isTimelineOpen&&await w.verifySenders(a),w.applyToEntries(h),o!=null&&o.length&&(w.applyToEntries(o),d.push(...o))}c.set("newEntries",h.length),c.set("updatedEntries",d.length);let _;r&&(_=await r.writeSync(e,p,a,c),c.set("shouldFlushKeyShares",_.shouldFlush));const f=h.concat(d);s=s.applyTimelineEntries(f,t,!this._isTimelineOpen,this._user.id),s.membership!=="join"?a.roomSummary.remove(this.id):s=this._summary.writeData(s,a),s&&c.set("summaryChanges",s.changedKeys(this._summary.data));let b;s!=null&&s.needsHeroes&&(this._heroes||(this._heroes=new Di(this._roomId)),b=await this._heroes.calculateChanges(s.heroes,p,a));let S;Array.isArray((R=e.timeline)==null?void 0:R.events)&&(S=await this._sendQueue.removeRemoteEchos(e.timeline.events,a,c));const k=this._getPowerLevelsEvent(e);return{summaryChanges:s,roomEncryption:r,newEntries:h,updatedEntries:d,newLiveKey:u,removedPendingEvents:S,memberChanges:p,heroChanges:b,powerLevelsEvent:k,encryptionChanges:_}}afterSync(e,t){const{summaryChanges:s,newEntries:i,updatedEntries:r,newLiveKey:o,removedPendingEvents:a,memberChanges:c,powerLevelsEvent:l,heroChanges:h,roomEncryption:d,encryptionChanges:u}=e;if(t.set("id",this.id),this._syncWriter.afterSync(o),this._setEncryption(d),this._roomEncryption&&this._roomEncryption.afterSync(u),c.size){if(this._changedMembersDuringSync)for(const[_,f]of c.entries())this._changedMembersDuringSync.set(_,f.member);if(this._memberList&&this._memberList.afterSync(c),this._observedMembers&&this._updateObservedMembers(c),this._timeline){for(const[_,f]of c.entries())if(_===this._user.id){this._timeline.updateOwnMember(f.member);break}}}let p=!1;if(s&&(this._summary.applyChanges(s),this._summary.data.needsHeroes||(this._heroes=null),p=!0),this._heroes&&h){const _=this.name;this._heroes.applyChanges(h,this._summary.data,t),_!==this.name&&(p=!0)}l&&this._updatePowerLevels(l),p&&this._emitUpdate(),this._timeline&&(this._timeline.replaceEntries(r),this._timeline.addEntries(i)),this._observedEvents&&(this._observedEvents.updateEvents(r),this._observedEvents.updateEvents(i)),a&&this._sendQueue.emitRemovals(a)}_updateObservedMembers(e){for(const[t,s]of e){const i=this._observedMembers.get(t);i&&i.set(s.member)}}_getPowerLevelsEvent(e){var i,r,o;const t=a=>a.state_key===""&&a.type===Xl;return(o=(i=e.timeline)==null?void 0:i.events.find(t))!=null?o:(r=e.state)==null?void 0:r.events.find(t)}_updatePowerLevels(e){if(this._powerLevels){const t=new Es({powerLevelEvent:e,ownUserId:this._user.id,membership:this.membership});this._powerLevels.set(t)}}needsAfterSyncCompleted({encryptionChanges:e}){return e==null?void 0:e.shouldFlush}async afterSyncCompleted(e,t){t.set("id",this.id),this._roomEncryption&&await this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,null,t)}start(e,t){if(this._roomEncryption){const 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 xn(`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){if(this.isUnread||this.notificationCount)return await this._platform.logger.wrapOrRun(e,"clearUnread",async t=>{t.set("id",this.id);const s=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary]);let i;try{i=this._summary.writeClearUnread(s)}catch(r){throw s.abort(),r}await s.complete(),this._summary.applyChanges(i),this._emitUpdate();try{const r=await this._getLastEventId();r&&await this._hsApi.receipt(this._roomId,"m.read",r)}catch(r){if(r.name!=="ConnectionError")throw r}})}leave(e=null){return this._platform.logger.wrapOrRun(e,"leave room",async t=>{t.set("id",this.id),await this._hsApi.leave(this.id,{log:t}).response()})}_getPendingEvents(){return this._sendQueue.pendingEvents}writeIsTrackingMembers(e,t){return this._summary.writeIsTrackingMembers(e,t)}applyIsTrackingMembersChanges(e){this._summary.applyChanges(e)}createAttachment(e,t){return new ro({blob:e,filename:t,platform:this._platform})}dispose(){super.dispose(),this._sendQueue.dispose()}}class rh extends io{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 O(s):O.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=nh(t,this._user.id);if(o||e){const a=o||this._kickDetails;let c;o&&(c=await this._getKickAuthor(o.sender,i));const l=e||this._summary.data;return i.archivedRoomSummary.set({summary:l.serialize(),kickDetails:a}),{kickDetails:a,kickedBy:c,summaryData:l}}}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 nh(n,e){var s,i;const t=Fn(n,(r,o)=>(o.type===oe&&o.state_key===e&&o.sender!==o.state_key&&(r=o),r),null);if(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 oh(n,e,t){const s=await Promise.all(n.map(async i=>{const r=await e.profile(i,{log:t}).response();return new ah(i,r.displayname,r.avatar_url)}));return s.sort((i,r)=>i.name.localeCompare(r.name)),s}class ah{constructor(e,t,s){this.userId=e,this.displayName=t,this.avatarUrl=s}get name(){return this.displayName||this.userId}}class ch{constructor(e){this.userId=e}get displayName(){}get name(){return this.userId}get avatarUrl(){}}function lh(n){switch(n){case re.DirectMessage:case re.Private:return!0;case re.Public:return!1}}function hh(n){switch(n){case re.DirectMessage:return"trusted_private_chat";case re.Private:return"private_chat";case re.Public:return"public_chat"}}class dh extends Ls{constructor(e,t,s,i,r,o){var a;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?lh(t.type):t.isEncrypted,t.name)this._calculatedName=t.name;else{const c={joinCount:1,inviteCount:((a=t.invites)==null?void 0:a.length)||0},l=(t.invites||[]).map(h=>new ch(h));this._calculatedName=pi(l,c,o)}}async create(e,t){try{let s;if(this.options.avatar){const{avatar:o}=this.options,a=new ro({filename:o.name,blob:o.blob,platform:this.platform});await a.upload(e,()=>{},t),s={info:o.info},a.applyToContent("url",s)}const i={is_direct:this.options.type===re.DirectMessage,preset:hh(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(La()),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 oh(this.options.invites,e,t);const s={joinCount:1,inviteCount:this.options.invites.length};this._calculatedName=pi(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!==re.DirectMessage)return;const r=this.options.invites[0],o="m.direct";await i.wrap("set "+o,async a=>{try{const c=await t.readWriteTxn([t.storeNames.accountData]);let l;try{l=await c.accountData.get(o),l||(l={type:o,content:{}});const h=l.content;let d=h[r];d||(h[r]=d=[]),d.push(this._roomId),c.accountData.set(l),await c.complete()}catch(h){throw c.abort(),h}await s.setAccountData(e.id,o,l.content,{log:a}).response()}catch(c){a.catch(c)}})}}class uh extends Ls{constructor({roomId:e,user:t,hsApi:s,mediaRepository:i,emitCollectionRemove:r,emitCollectionUpdate:o,platform:a}){super(),this._roomId=e,this._user=t,this._hsApi=s,this._emitCollectionRemove=r,this._emitCollectionUpdate=o,this._mediaRepository=i,this._platform=a,this._inviteData=null,this._accepting=!1,this._rejecting=!1,this._accepted=!1,this._rejected=!1}get isInvite(){return!0}get id(){return this._roomId}get name(){return this._inviteData.name||this._inviteData.canonicalAlias}get isDirectMessage(){return this._inviteData.isDirectMessage}get avatarUrl(){return this._inviteData.avatarUrl}get avatarColorId(){return this._inviteData.avatarColorId||this.id}get timestamp(){return this._inviteData.timestamp}get isEncrypted(){return this._inviteData.isEncrypted}get inviter(){return this._inviter}isDirectMessageForUserId(e){return this.isDirectMessage&&this._inviter.userId===e}get isPublic(){return this._inviteData.joinRule==="public"}get canonicalAlias(){return this._inviteData.canonicalAlias}async accept(e=null){await this._platform.logger.wrapOrRun(e,"acceptInvite",async t=>{this._accepting=!0,this._emitChange("accepting"),await this._hsApi.join(this._roomId,{log:t}).response()})}async reject(e=null){await this._platform.logger.wrapOrRun(e,"rejectInvite",async t=>{this._rejecting=!0,this._emitChange("rejecting"),await this._hsApi.leave(this._roomId,{log:t}).response()})}get accepting(){return this._accepting}get accepted(){return this._accepted}get rejecting(){return this._rejecting}get rejected(){return this._rejected}get mediaRepository(){return this._mediaRepository}_emitChange(e){this.emit("change"),this._emitCollectionUpdate(this,e)}load(e,t){t.set("id",this.id),this._inviteData=e,this._inviter=e.inviter?new O(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 a=this._createSummaryData(o);let c;!a.name&&!a.canonicalAlias&&(c=await this._createHeroes(o,i));const l=this._getMyInvite(o);if(!l)return null;const h=this._getInviter(l,o),d=this._createData(o,l,h,a,c);return s.invites.set(d),{inviteData:d,inviter:h}}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,a=r?r.roomAvatarUrl:i.avatarUrl,c=(r==null?void 0:r.roomAvatarColorId)||this.id;return{roomId:this.id,isEncrypted:!!i.encryption,isDirectMessage:i.isDirectMessage,name:o,avatarUrl:a,avatarColorId:c,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)=>Bn(t,s,this._user.id),new Ee(null,this.id))}async _createHeroes(e,t){const s=e.filter(h=>h.type===oe),i=s.filter(h=>h.state_key!==this._user.id),r=i.reduce((h,d)=>{const u=O.fromMemberEvent(this.id,d);return h.set(u.userId,new Wn(u,null)),h},new Map),o=i.map(h=>h.state_key),a=new Di(this.id),c=await a.calculateChanges(o,r,null),l=new Ee(null,this.id);return l.joinCount=s.reduce((h,d)=>{var u;return h+(((u=d.content)==null?void 0:u.membership)==="join"?1:0)},0),l.inviteCount=s.reduce((h,d)=>{var u;return h+(((u=d.content)==null?void 0:u.membership)==="invite"?1:0)},0),a.applyChanges(c,l,t),a}_getMyInvite(e){return e.find(t=>t.type===oe&&t.state_key===this._user.id)}_getInviter(e,t){const s=t.find(i=>i.type===oe&&i.state_key===e.sender);if(s)return O.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 tt{constructor(e){this._description=e}static httpPusher(e,t,s,i){return new tt({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)}}function bt(n,e){return Vi(n,e,()=>[],(t,s)=>t.push(s))}function Vi(n,e,t,s){return n.reduce((i,r)=>{const o=e(r);let a=i.get(o);return a||(a=t(),i.set(o,a)),s(a,r),i},new Map)}function Br(n,e){return n.reduce((t,s)=>{const i=e(s);return t[i]?t[i]+=1:t[i]=1,t},{})}class mh{constructor({storage:e}){this._storage=e,this._olmDecryption=null,this._megolmDecryption=null}enableEncryption({olmDecryption:e,megolmDecryption:t}){this._olmDecryption=e,this._megolmDecryption=t}obtainSyncLock(e){var t;return(t=this._olmDecryption)==null?void 0:t.obtainDecryptionLock(e)}async prepareSync(e,t,s,i){i.set("messageTypes",Br(e,a=>a.type));const r=e.filter(a=>a.type==="m.room.encrypted");if(!this._olmDecryption){i.log("can't decrypt, encryption not enabled",i.level.Warn);return}const o=r.filter(a=>{var c;return((c=a.content)==null?void 0:c.algorithm)===ki});if(o.length){const a=await this._olmDecryption.decryptAll(o,t,s);i.set("decryptedTypes",Br(a.results,l=>{var h;return(h=l.event)==null?void 0:h.type}));for(const l of a.errors)i.child("decrypt_error").catch(l);const c=this._megolmDecryption.roomKeysFromDeviceMessages(a.results,i);return new ph(a,c)}}async writeSync(e,t){return e.olmDecryptChanges.write(t),(await Promise.all(e.newRoomKeys.map(i=>this._megolmDecryption.writeRoomKey(i,t)))).some(i=>!!i)}}class ph{constructor(e,t){this.olmDecryptChanges=e,this.newRoomKeys=t,this.newKeysByRoom=bt(t,s=>s.roomId)}}const Ft=ie+"olmAccount",_i=ie+"areDeviceKeysUploaded",ks=ie+"serverOTKCount";async function Kr(n,e,t,s,i){const r=n.pickle(e),o=await i.readWriteTxn([i.storeNames.session]);try{o.session.add(Ft,r),o.session.add(_i,t),o.session.add(ks,s)}catch(a){throw o.abort(),a}await o.complete()}class rt{static async load({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,txn:a}){const c=await a.session.get(Ft);if(c){const l=new e.Account,h=await a.session.get(_i);l.unpickle(t,c);const d=await a.session.get(ks);return new rt({pickleKey:t,hsApi:s,account:l,userId:i,deviceId:r,areDeviceKeysUploaded:h,serverOTKCount:d,olm:e,olmWorker:o})}}static async adoptDehydratedDevice({olm:e,dehydratedDevice:t,pickleKey:s,hsApi:i,userId:r,olmWorker:o,storage:a}){const c=t.adoptUnpickledOlmAccount(),l=JSON.parse(c.one_time_keys()),d=Object.entries(l.curve25519).length,u=!0;return await Kr(c,s,u,d,a),new rt({pickleKey:s,hsApi:i,account:c,userId:r,deviceId:t.deviceId,areDeviceKeysUploaded:u,serverOTKCount:d,olm:e,olmWorker:o})}static async create({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,storage:a}){const c=new e.Account;o?await o.createAccountAndOTKs(c,c.max_number_of_one_time_keys()):(c.create(),c.generate_one_time_keys(c.max_number_of_one_time_keys()));const l=!1,h=0;return a&&await Kr(c,t,l,h,a),new rt({pickleKey:t,hsApi:s,account:c,userId:i,deviceId:r,areDeviceKeysUploaded:l,serverOTKCount:h,olm:e,olmWorker:o})}constructor({pickleKey:e,hsApi:t,account:s,userId:i,deviceId:r,areDeviceKeysUploaded:o,serverOTKCount:a,olm:c,olmWorker:l}){this._olm=c,this._pickleKey=e,this._hsApi=t,this._account=s,this._userId=i,this._deviceId=r,this._areDeviceKeysUploaded=o,this._serverOTKCount=a,this._olmWorker=l,this._identityKeys=JSON.parse(this._account.identity_keys())}get identityKeys(){return this._identityKeys}setDeviceId(e){this._deviceId=e}async uploadKeys(e,t,s){var o;const i=JSON.parse(this._account.one_time_keys()),r=Object.entries(i.curve25519);if(r.length||!this._areDeviceKeysUploaded){const a={};if(!this._areDeviceKeysUploaded){s.set("identity",!0);const h=JSON.parse(this._account.identity_keys());a.device_keys=this._deviceKeysPayload(h)}r.length&&(s.set("otks",!0),a.one_time_keys=this._oneTimeKeysPayload(r));const c=t?this._deviceId:void 0,l=await this._hsApi.uploadKeys(c,a,{log:s}).response();this._serverOTKCount=(o=l==null?void 0:l.one_time_key_counts)==null?void 0:o.signed_curve25519,s.set("serverOTKCount",this._serverOTKCount),await this._updateSessionStorage(e,h=>{r.length&&(this._account.mark_keys_as_published(),h==null||h.set(Ft,this._account.pickle(this._pickleKey)),h==null||h.set(ks,this._serverOTKCount)),this._areDeviceKeysUploaded||(this._areDeviceKeysUploaded=!0,h==null||h.set(_i,this._areDeviceKeysUploaded))})}}async generateOTKsIfNeeded(e,t){const s=this._account.max_number_of_one_time_keys(),i=Math.floor(s/2);if(this._serverOTKCount<i){const r=JSON.parse(this._account.one_time_keys()),a=Object.entries(r.curve25519).length,c=i-a-this._serverOTKCount;return c>0&&await t.wrap("generate otks",l=>{l.set("max",s),l.set("server",this._serverOTKCount),l.set("unpublished",a),l.set("new",c),l.set("limit",i),this._account.generate_one_time_keys(c),this._updateSessionStorage(e,h=>{h.set(Ft,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(Ft,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(ks,i),s.set("otkCount",i),i}afterSync(e){Number.isSafeInteger(e)&&(this._serverOTKCount=e)}_deviceKeysPayload(e){const t={user_id:this._userId,device_id:this._deviceId,algorithms:[ki,ve],keys:{}};for(const[s,i]of Object.entries(e))t.keys[`${s}:${this._deviceId}`]=i;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(On.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 Li{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 _h(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 ts{constructor(e,t){this._keyDescription=e,this._binaryKey=t}withDescription(e){return new ts(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 _h(n,e,t){const{crypto:s,encoding:i}=t,{utf8:r,base64:o}=i,{derive:a,aes:c,hmac:l}=s,h=o.decode(e),d=new Uint8Array(8),u="\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",p=r.encode(""),_=await a.hkdf(n,d,p,"SHA-256",512),f=_.slice(0,32),b=_.slice(32),S=await c.encryptCTR({key:f,iv:h,data:r.encode(u)}),k=await l.compute(b,S,"SHA-256");return o.encode(k)}const fh=5e5,gh=256;async function yh(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||fh,i.encode(s.salt),"SHA-512",s.bits||gh);return new ts(n,r)}const Dt=[139,1];function wh(n,e,t,s){const i=s.encoding.base58.decode(e.replace(/ /g,""));let r=0;for(const a of i)r^=a;if(r!==0)throw new Error("Incorrect parity");for(let a=0;a<Dt.length;++a)if(i[a]!==Dt[a])throw new Error("Incorrect prefix");if(i.length!==Dt.length+t.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");const o=Uint8Array.from(i.slice(Dt.length,Dt.length+t.PRIVATE_KEY_LENGTH));return new ts(n,o)}const Oi=`${ie}ssssKey`,$r=`${ie}keyBackupVersion`;var Qt=(n=>(n[n.RecoveryKey=0]="RecoveryKey",n[n.Passphrase=1]="Passphrase",n))(Qt||{});async function no(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 Li(s,i.content)}async function vh(n,e,t){const s=await t.session.get($r);return t.session.set($r,e),t.session.set(Oi,{id:n.id,binaryKey:n.binaryKey}),s}async function bh(n){const e=await n.session.get(Oi);if(!e)return;const t=await n.accountData.get(`m.secret_storage.key.${e.id}`);if(t)return new ts(new Li(e.id,t.content),e.binaryKey)}async function Sh(n){n.session.remove(Oi)}async function Ih(n,e,t,s,i){const r=await no(t);if(!r)throw new Error("Could not find a default secret storage key in account data");return await oo(n,e,r,s,i)}async function oo(n,e,t,s,i){let r;if(n===1)r=await yh(t,e,s);else if(n===0)r=wh(t,e,i,s);else throw new Error(`Invalid type: ${n}`);return r}async function Eh(n,e,t){const s=await no(e);if(await(s==null?void 0:s.isCompatible(n,t)))return n.withDescription(s)}const ao="org.matrix.msc2697.v1.olm.libolm_pickle";async function kh(n,e,t,s){try{const i=await n.getDehydratedDevice({log:s}).response();if(i.device_data.algorithm===ao)return new Ch(i,e,t)}catch(i){i.name!=="HomeServerError"&&(s.error=i);return}}async function Rh(n,e,t,s,i){var a;const o=(await e.createDehydratedDevice({device_data:{algorithm:ao,account:n.pickleWithKey(t.binaryKey.slice()),passphrase:((a=t.description)==null?void 0:a.passphraseParams)||{}},initial_device_display_name:s}).response()).device_id;return n.setDeviceId(o),await n.uploadKeys(void 0,!0,i),o}class Ch{constructor(e,t,s){this._dehydratedDevice=e,this._olm=t,this._platform=s}async decrypt(e,t){const s=new Li("dehydrated_device",this._dehydratedDevice.device_data.passphrase),i=await oo(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 Th(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 Th{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 Mh{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 Ah{constructor(e){this.locks=e}release(){for(const e of this.locks)e.release()}}function co(n,e,t,s){return{session:n.pickle(s),sessionId:n.session_id(),senderKey:e,lastUsed:t}}class As{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=co(t,e,r,i);return new As(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 lo{constructor(e,t,s){this.event=e,this.senderCurve25519Key=t,this.claimedEd25519Key=s,this.roomTracked=!0}setDevice(e){this.device=e}setRoomNotTrackedYet(){this.roomTracked=!1}get isVerified(){return this.device?this.device.ed25519Key===this.claimedEd25519Key:!1}get isUnverified(){return this.device?!this.isVerified:!this.isVerificationUnknown}get isVerificationUnknown(){return!this.device&&!this.roomTracked}}var xs=(n=>(n[n.PreKey=0]="PreKey",n[n.Normal=1]="Normal",n))(xs||{});const jr=4;function ho(n){n.sort((e,t)=>t.data.lastUsed-e.data.lastUsed)}class xh{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 Ah(s)}async decryptAll(e,t,s){try{const i=bt(e,h=>{var d;return(d=h.content)==null?void 0:d.sender_key}),r=this.now(),o=await Promise.all(Array.from(i.entries()).map(([h,d])=>this._decryptAllForSenderKey(h,d,r,s))),a=o.reduce((h,d)=>h.concat(d.results),[]),c=o.reduce((h,d)=>h.concat(d.errors),[]),l=o.map(h=>h.senderKeyDecryption);return new Dh(l,a,c,this.account,t)}catch(i){throw t.release(),i}}async _decryptAllForSenderKey(e,t,s,i){const r=await this._getSessions(e,i),o=new Nh(e,r,s),a=[],c=[];for(const l of t)try{const h=this._decryptForSenderKey(o,l,s);a.push(h)}catch(h){c.push(h)}return{results:a,errors:c,senderKeyDecryption:o}}_decryptForSenderKey(e,t,s){const i=e.senderKey,r=this._getMessageAndValidateEvent(t);let o;try{o=e.decrypt(r)}catch(a){throw new z("OLM_BAD_ENCRYPTED_MESSAGE",t,{senderKey:i,error:a.message})}if(typeof o!="string"&&r.type===xs.PreKey){let a;try{a=this._createSessionAndDecrypt(i,r,s)}catch(c){throw new z(`Could not create inbound olm session: ${c.message}`,t,{senderKey:i,error:c})}e.addNewSession(a.session),o=a.plaintext}if(typeof o=="string"){let a;try{a=JSON.parse(o)}catch(c){throw new z("PLAINTEXT_NOT_JSON",t,{plaintext:o,error:c})}return this._validatePayload(a,t),new lo(a,i,a.keys.ed25519)}else throw new z("OLM_NO_MATCHING_SESSION",t,{knownSessionIds:e.sessions.map(a=>a.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=As.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 z("OLM_MISSING_CIPHERTEXT",e);const s=t==null?void 0:t[this.account.identityKeys.curve25519];if(!s)throw new z("OLM_NOT_INCLUDED_IN_RECIPIENTS",e);return s}async _getSessions(e,t){const i=(await t.olmSessions.getAll(e)).map(r=>new As(r,this.pickleKey,this.olm));return ho(i),i}_validatePayload(e,t){var s,i,r;if(e.sender!==t.sender)throw new z("OLM_FORWARDED_MESSAGE",t,{sentBy:t.sender,encryptedBy:e.sender});if(e.recipient!==this.ownUserId)throw new z("OLM_BAD_RECIPIENT",t,{recipient:e.recipient});if(((s=e.recipient_keys)==null?void 0:s.ed25519)!==this.account.identityKeys.ed25519)throw new z("OLM_BAD_RECIPIENT_KEY",t,{key:(i=e.recipient_keys)==null?void 0:i.ed25519});if(!e.type)throw new z("missing type on payload",t,{payload:e});if(typeof((r=e.keys)==null?void 0:r.ed25519)!="string")throw new z("Missing or invalid claimed ed25519 key on payload",t,{payload:e})}}class Nh{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 ho(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===xs.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===xs.PreKey)throw new Error(`Error decrypting prekey message with existing session id ${e.id}: ${i.message}`);return}}finally{e.unload(s)}}}class Dh{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>jr){const{senderKey:s,sessions:i}=t;for(let r=i.length-1;r>=jr;r-=1){const o=i[r];e.olmSessions.remove(s,o.id)}}}}finally{this.lock.release()}}}function Vh(n){return n.reduce((e,t)=>!e||t<e?t:e,null)}const qr="signed_curve25519",Wr=20;class Lh{constructor(e,t,s,i,r,o,a,c){this.account=e,this.pickleKey=t,this.olm=s,this.storage=i,this.now=r,this.ownUserId=o,this.olmUtil=a,this.senderKeyLock=c}async encrypt(e,t,s,i,r){let o=[];for(let a=0;a<s.length;a+=Wr){const c=s.slice(a,a+Wr),l=await this._encryptForMaxDevices(e,t,c,i,r);o=o.concat(l)}return o}async _encryptForMaxDevices(e,t,s,i,r){const o=await Promise.all(s.map(a=>this.senderKeyLock.takeLock(a.curve25519Key)));try{const{devicesWithoutSession:a,existingEncryptionTargets:c}=await this._findExistingSessions(s),l=this.now();let h=[];try{if(a.length){const p=await r.wrap("create sessions",_=>this._createNewSessions(a,i,l,_));h=h.concat(p)}await this._loadSessions(c),h=h.concat(c);const d={l:"encrypt",targets:h.length},u=r.wrap(d,()=>h.map(p=>{const _=this._encryptForDevice(e,t,p);return new Oh(_,p.device)}));return await this._storeSessions(h,l),u}finally{for(const d of h)d.dispose()}}finally{for(const a of o)a.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(o.curve25519Key))),i=e.filter((o,a)=>{const c=s[a];return!(c!=null&&c.length)}),r=e.map((o,a)=>{const c=s[a];if((c==null?void 0:c.length)>0){const l=Vh(c);return Yt.fromSessionId(o,l)}}).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)),a=i.encrypt(o);return{algorithm:ki,sender_key:this.account.identityKeys.curve25519,ciphertext:{[r.curve25519Key]:a}}}_buildPlainTextMessageForDevice(e,t,s){return{keys:{ed25519:this.account.identityKeys.ed25519},recipient_keys:{ed25519:s.ed25519Key},recipient:s.userId,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:a,oneTimeKey:c}=o;o.session=await this.account.createOutboundOlmSession(a.curve25519Key,c)}await this._storeSessions(r,s)}catch(o){for(const a of r)a.dispose();throw o}return r}async _claimOneTimeKeys(e,t,s){const i=Vi(t,c=>c.userId,()=>new Map,(c,l)=>c.set(l.deviceId,l)),r=Array.from(i.entries()).reduce((c,[l,h])=>(c[l]=Array.from(h.values()).reduce((d,u)=>(d[u.deviceId]=qr,d),{}),c),{}),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 a=o==null?void 0:o.one_time_keys;return this._verifyAndCreateOTKTargets(a,i,s)}_verifyAndCreateOTKTargets(e,t,s){var r;const i=[];for(const[o,a]of Object.entries(e))for(const[c,l]of Object.entries(a)){const[h,d]=Object.entries(l)[0],[u]=h.split(":");if(u===qr){const p=(r=t.get(o))==null?void 0:r.get(c);if(p&&Un(this.olmUtil,o,c,p.ed25519Key,d,s)){const f=Yt.fromOTK(p,d.key);i.push(f)}}}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(i.device.curve25519Key,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=co(i.session,i.device.curve25519Key,t,this.pickleKey);s.olmSessions.set(r)}}catch(i){throw s.abort(),i}await s.complete()}}class Yt{constructor(e,t,s){this.device=e,this.oneTimeKey=t,this.sessionId=s,this.session=null}static fromOTK(e,t){return new Yt(e,t,null)}static fromSessionId(e,t){return new Yt(e,null,t)}dispose(){this.session&&this.session.free()}}class Oh{constructor(e,t){this.content=e,this.device=t}}class Ph{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:a}=t,c=await s.groupSessionDecryptions.get(e,r,i);if(c&&c.eventId!==o){const h=c.timestamp<a?o:c.eventId;throw this._results.delete(o),new z("MEGOLM_REPLAYED_INDEX",event,{messageIndex:i,badEventId:h,otherEventId:c.eventId})}c||s.groupSessionDecryptions.set(e,r,i,{eventId:o,timestamp:a})}}function fi(n,e){if(n)for(const[t,s]of n.entries())e.set(t,s)}class Uh{constructor(e,t,s){this._roomId=e,this._sessionDecryptions=t,this._initialErrors=s}async decrypt(){try{const e=this._initialErrors,t=new Map,s=[];return await Promise.all(this._sessionDecryptions.map(async i=>{const r=await i.decryptAll();fi(r.errors,e),fi(r.results,t),s.push(...r.replayEntries)})),new Ph(this._roomId,t,e,s)}finally{this.dispose()}}dispose(){for(const e of this._sessionDecryptions)e.dispose()}}class Fh{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 Bh{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 a;if(this.olmWorker){const d=this.olmWorker.megolmDecrypt(i,o);this.decryptionRequests.push(d),a=await d.response()}else a=i.decrypt(o);const{plaintext:c}=a;let l;try{l=JSON.parse(c)}catch(d){throw new z("PLAINTEXT_NOT_JSON",r,{plaintext:c,err:d})}if(l.room_id!==this.key.roomId)throw new z("MEGOLM_WRONG_ROOM",r,{encryptedRoomId:l.room_id,eventRoomId:this.key.roomId});e.push(new Fh(this.key.sessionId,a.message_index,r));const h=new lo(l,this.key.senderKey,this.key.claimedEd25519Key);t.set(r.event_id,h)}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 Pi(n){var e;return(e=n.content)==null?void 0:e.sender_key}function Ui(n){var e;return(e=n.content)==null?void 0:e.session_id}function Kh(n){var e;return(e=n.content)==null?void 0:e.ciphertext}function $h(n){return typeof Pi(n)=="string"&&typeof Ui(n)=="string"&&typeof Kh(n)=="string"}class jh{constructor(){this.events=[]}get senderKey(){return Pi(this.events[0])}get sessionId(){return Ui(this.events[0])}}function gi(n){return Vi(n,e=>`${Pi(e)}|${Ui(e)}`,()=>new jh,(e,t)=>e.events.push(t))}class uo{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 mo(n,e){return n.first_known_index()<e.first_known_index()}class Fi extends uo{checkBetterThanKeyInStorage(e,t){return this._checkBetterThanKeyInStorage(e,void 0,t)}async write(e,t){let s;if(this.isBetter===void 0&&await this._checkBetterThanKeyInStorage(e,(r,o)=>{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 fo(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,(a,c)=>{this.isBetter=mo(o,a),r.isBetter=!this.isBetter,this.isBetter&&t&&t(o,c)})})}else this.isBetter=!0;return this.isBetter}get backupStatus(){return Os.NotBackedUp}}class qh extends Fi{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 es.DeviceMessage}loadInto(e){e.create(this.serializationKey)}}class Wh extends Fi{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 es.Outbound}loadInto(e){e.create(this.serializationKey)}}class Hh extends Fi{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 es.Backup}loadInto(e){e.import_session(this.serializationKey)}get backupStatus(){return Os.BackedUp}}class po extends uo{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 zh(n){var s;const e=(s=n.event.content)==null?void 0:s.session_key,t=new qh(n);if(typeof t.roomId=="string"&&typeof t.sessionId=="string"&&typeof t.senderKey=="string"&&typeof e=="string")return t}function _o(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 Hh(n,e,t)}async function fo(n,e,t,s){const i=await s.inboundGroupSessions.get(n,e,t);if(i)return new po(i)}class Gh{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 a=new Set(o.eventIds);for(const c of i)a.add(c);o.eventIds=Array.from(a)}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 l of t)$h(l)?o.push(l):r.set(l.event_id,new z("MEGOLM_INVALID_EVENT",l));const a=gi(o),c=[];return await Promise.all(Array.from(a.values()).map(async l=>{const h=await this.getRoomKey(e,l.senderKey,l.sessionId,s,i);if(h)c.push(new Bh(h,l.events,this.olmWorker,this.keyLoader));else for(const d of l.events)r.set(d.event_id,new z("MEGOLM_NO_SESSION",d))})),new Uh(e,c,r)}async getRoomKey(e,t,s,i,r){if(i){const c=i.find(l=>l.isForSession(e,t,s));if(c&&await c.checkBetterThanKeyInStorage(this.keyLoader,r))return c}const o=this.keyLoader.getCachedKey(e,t,s);if(o)return o;const a=await fo(e,t,s,r);if(a&&a.serializationKey)return a}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)!==ve||t.wrap("room_key",a=>{const c=zh(o);c?(a.set("roomId",c.roomId),a.set("id",c.sessionId),s.push(c)):(a.logLevel=a.level.Warn,a.set("invalid",!0))},t.level.Detail);return s}roomKeyFromBackup(e,t,s){return _o(e,t,s)}dispose(){this.keyLoader.dispose()}}class Jh extends eo{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._entries.length;e+=1)this._entries[e].dispose();this._entries.splice(0,this._entries.length)}async allocateOperation(e){let t;for(;(t=this.findIndexForAllocation(e))===-1;)await this.operationBecomesUnused();if(t<this.size){const s=this._getByIndexAndMoveUp(t);return s.isForKey(e)?(s.refCount+=1,s):(s.refCount=1,s.key=e,e.loadInto(s.session,this.pickleKey),s)}else{const s=new this.olm.InboundGroupSession;e.loadInto(s,this.pickleKey);const i=new Qh(e,s);return this._set(i),i}}releaseOperation(e){e.refCount-=1,e.refCount<=0&&this.resolveUnusedOperation&&(this.resolveUnusedOperation(),this.operationBecomesUnusedPromise=this.resolveUnusedOperation=void 0)}operationBecomesUnused(){return this.operationBecomesUnusedPromise||(this.operationBecomesUnusedPromise=new Promise(e=>{this.resolveUnusedOperation=e})),this.operationBecomesUnusedPromise}findIndexForAllocation(e){let t=this.findIndexSameKey(e);return t===-1&&(this.size<this.limit?t=this.size:(t=this.findIndexSameSessionUnused(e),t===-1&&(t=this.findIndexOldestUnused()))),t}findCachedKeyIndex(e,t,s){return this._entries.reduce((i,r,o,a)=>{const c=i===-1?void 0:a[i];return r.isBest===!0&&r.isForSameSession(e,t,s)&&(!c||r.isBetter(c))?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 Qh{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 mo(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 Yh="m.megolm_backup.v1.curve25519-aes-sha2";class Bi{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 a=r.init_with_private_key(t);if(a!==i)throw new Error(`Bad backup key, public key does not match. Calculated ${a} but expected ${i}`);o.set_recipient_key(a)}catch(a){throw r.free(),a}return new Bi(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:ve,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 Xh=200;class Ki{constructor(e,t,s,i,r,o,a=1e4){this.backupInfo=e,this.crypto=t,this.hsApi=s,this.keyLoader=i,this.storage=r,this.platform=o,this.maxDelay=a,this.operationInProgress=new we(void 0),this._stopped=!1,this._needsNewKey=!1,this._hasBackedUpAllKeys=!1}get hasStopped(){return this._stopped}get error(){return this._error}get version(){return this.backupInfo.version}get needsNewKey(){return this._needsNewKey}get hasBackedUpAllKeys(){return this._hasBackedUpAllKeys}async getRoomKey(e,t,s){const i=await this.hsApi.roomKeyForRoomAndSession(this.backupInfo.version,e,t,{log:s}).response();if(!i.session_data)return;const r=this.crypto.decryptRoomKey(i.session_data);if((r==null?void 0:r.algorithm)===ve)return _o(e,t,r);r!=null&&r.algorithm&&s.set("unknown algorithm",r.algorithm)}markAllForBackup(e){return e.inboundGroupSessions.markAllAsNotBackedUp()}flush(e){this.operationInProgress.get()||e.wrapDetached("flush key backup",async t=>{if(this._needsNewKey){t.set("needsNewKey",this._needsNewKey);return}this._stopped=!1,this._error=void 0,this._hasBackedUpAllKeys=!1;const s=this._runFlushOperation(t);this.operationInProgress.set(s);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.set(void 0)})}_runFlushOperation(e){return new Mn(async(t,s)=>{let i=0,r=0;for(;;){const o=this.platform.random()*this.maxDelay,a=this.platform.clock.createTimeout(o);t(a),await a.elapsed();const c=await this.storage.readTxn([P.inboundGroupSessions]);t(c),i=r+await c.inboundGroupSessions.countNonBackedUpSessions(),s(new Hr(i,r));const l=(await c.inboundGroupSessions.getFirstNonBackedUpSessions(Xh)).map(u=>new po(u));if(l.length===0){e.set("total",i);return}const h=await this.encodeKeysForBackup(l),d=this.hsApi.uploadRoomKeysToBackup(this.backupInfo.version,h,{log:e});t(d),await d.response(),await this.markKeysAsBackedUp(l,t),r+=l.length,s(new Hr(i,r))}})}async encodeKeysForBackup(e){const t={rooms:{}},s=t.rooms;for(const i of e){let r=s[i.roomId];r||(r=s[i.roomId]={sessions:{}}),r.sessions[i.sessionId]=await this.encodeRoomKey(i)}return t}async markKeysAsBackedUp(e,t){const s=await this.storage.readWriteTxn([P.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){return await this.keyLoader.useKey(e,t=>{const s=t.first_known_index(),i=t.export_session(s);return{first_message_index:s,forwarded_count:0,is_verified:!1,session_data:this.crypto.encryptRoomKey(e,i)}})}dispose(){this.crypto.dispose()}static async fromSecretStorage(e,t,s,i,r,o,a){const c=await s.readSecret("m.megolm_backup.v1",a);if(c){const l=new Uint8Array(e.encoding.base64.decode(c)),h=await i.roomKeysVersion().response();if(h.algorithm===Yh){const d=Bi.fromAuthData(h.auth_data,l,t);return new Ki(h,d,i,r,o,e)}else throw new Error(`Unknown backup algorithm: ${h.algorithm}`)}}}class Hr{constructor(e,t){this.total=e,this.finished=t}}class Zh{constructor({pickleKey:e,olm:t,account:s,keyLoader:i,storage:r,now:o,ownDeviceId:a}){this._pickleKey=e,this._olm=t,this._account=s,this._keyLoader=i,this._storage=r,this._now=o,this._ownDeviceId=a}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 Wh(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 a,c;try{let l=await o.outboundGroupSessions.get(e);a=await this._readOrCreateSession(r,l,e,i,o),c=this._encryptContent(e,r,t,s);const h=a?this._now():l.createdAt;this._writeSession(h,r,e,o)}catch(l){throw o.abort(),l}return await o.complete(),new ed(c,a)}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:ve,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:ve,chain_index:e.message_index()}}}class ed{constructor(e,t){this.content=e,this.roomKeyMessage=t}}class Wt{constructor(e,t,s,i){this._logger=s,this.start=s._now(),this._values=typeof e=="string"?{l:e}:e,this.logLevel=t,this._filterCreator=i}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._filterCreator)try{e=this._filterCreator(new mi(e),this)}catch(o){console.error("Error creating log filter",o)}let i=null;if(this._children&&(i=this._children.reduce((o,a)=>{const c=a.serialize(e,this.start,!1);return c&&(o===null&&(o=[]),o.push(c)),o},null)),e&&!e.filter(this,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()}}get level(){return _e}catch(e){return this.error=e,this.logLevel=_e.Error,this.finish(),e}child(e,t,s){this.end&&console.trace("log item is finished, additional logs will likely not be recorded"),t||(t=this.logLevel||_e.Info);const i=new Wt(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 go{constructor({platform:e,serializedTransformer:t=s=>s}){this._openItems=new Set,this._platform=e,this._serializedTransformer=t}log(e,t=_e.Info){const s=new Wt(e,t,this);s.end=s.start,this._persistItem(s,void 0,!1)}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=_e.Info);const r=new Wt(e,s,this);return this._run(r,t,s,!1,i),r}run(e,t,s,i){s===void 0&&(s=_e.Info);const r=new Wt(e,s,this);return this._run(r,t,s,!0,i)}_run(e,t,s,i,r){this._openItems.add(e);const o=()=>{let a=new mi;if(r)try{a=r(a,e)}catch(c){console.error("Error while creating log filter",c)}else a=a.minLevel(s);try{this._persistItem(e,a,!1)}catch(c){console.error("Could not persist log item",c)}this._openItems.delete(e)};try{let a=e.run(t);if(a instanceof Promise){if(a=a.then(c=>(o(),c),c=>{if(o(),i)throw c}),i)return a}else if(o(),i)return a}catch(a){if(o(),i)throw a}}_finishOpenItems(){for(const e of this._openItems){e.finish();try{this._persistItem(e,new mi,!0)}catch(t){console.error("Could not serialize log item",t)}}this._openItems.clear()}get level(){return _e}_now(){return this._platform.clock.now()}_createRefId(){return Math.round(this._platform.random()*Number.MAX_SAFE_INTEGER)}}class td extends go{_persistItem(e){yo(e)}async export(){}}const sd=["l","id"];function id(n){return Object.entries(n).filter(([e])=>!sd.includes(e)).reduce((e,[t,s])=>(e=e||{},e[t]=s,e),null)}function yo(n){const e=`${rd(n)} (${n.duration}ms)`,t=id(n.values),s=n.children||t;if(s?(n.error?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)yo(i);s&&console.groupEnd()}function rd(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&&n.error?`${n.values.l} failed`:typeof n.values.ref!="undefined"?`ref ${n.values.ref}`:n.values.l||n.values.type}const zr="m.room.encrypted",Gr="m.room.history_visibility",nd=60*1e3;class od{constructor({room:e,deviceTracker:t,olmEncryption:s,megolmEncryption:i,megolmDecryption:r,encryptionParams:o,storage:a,keyBackup:c,notifyMissingMegolmSession:l,clock:h}){this._room=e,this._deviceTracker=t,this._olmEncryption=s,this._megolmEncryption=i,this._megolmDecryption=r,this._encryptionParams=o,this._senderDeviceCache=new Map,this._storage=a,this._keyBackup=c,this._notifyMissingMegolmSession=l,this._clock=h,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(h=>h.isEncrypted&&!h.isDecrypted&&h.event).map(h=>h.event),i=gi(s),r=Array.from(i.values()),o=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]),a=await Promise.all(r.map(async h=>this._megolmDecryption.hasSession(this._room.id,h.senderKey,h.sessionId,o))),c=r.filter((h,d)=>!a[d]);if(c.length)for(var l=c.length-1;l>=0;l--){const h=c[l];await t.wrap("session",d=>this._requestMissingSessionFromBackup(h.senderKey,h.sessionId,d))}}notifyTimelineClosed(){this._senderDeviceCache=new Map}async writeSync(e,t,s,i){let r=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility,s);const o=[],a=[];if(await ja(e,l=>{var h;if(l.state_key===""&&l.type===Gr){const d=(h=l==null?void 0:l.content)==null?void 0:h.history_visibility;if(d!==r)return i.wrap({l:"history_visibility changed",from:r,to:d},async u=>{r=d;const p=await this._deviceTracker.writeHistoryVisibility(this._room,r,s,u);o.push(...p.added),a.push(...p.removed)})}}),t.size){const l=await this._deviceTracker.writeMemberChanges(this._room,t,r,s);o.push(...l.added),a.push(...l.removed)}a.length&&(i.log({l:"discardOutboundSession",leftUsers:a}),this._megolmEncryption.discardOutboundSession(this._room.id,s));let c=!1;return o.length&&(c=await this._addShareRoomKeyOperationForMembers(o,s,i)),{shouldFlush:c,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,Gr,"");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 c,l,h;const r=new Map,o=[];for(const d of e)d.redacted_because||((c=d.unsigned)==null?void 0:c.redacted_because)||(((l=d.content)==null?void 0:l.algorithm)!==ve&&r.set(d.event_id,new Error("Unsupported algorithm: "+((h=d.content)==null?void 0:h.algorithm))),o.push(d));const a=await this._megolmDecryption.prepareDecryptAll(this._room.id,o,t,i);return new ad(a,r,s,this,e)}async _processDecryptionResults(e,t,s,i,r,o){const a=e.filter(l=>{const h=s.get(l.event_id);return(h==null?void 0:h.code)==="MEGOLM_NO_SESSION"});if(!a.length)return;const c=gi(a);i===st.Sync&&await Promise.all(Array.from(c.values()).map(async l=>{const h=l.events.map(d=>d.event_id);return this._megolmDecryption.addMissingKeyEventIds(this._room.id,l.senderKey,l.sessionId,h,r)})),this._keyBackup&&o.wrapDetached("check key backup",async l=>{if(l.set("source",i),l.set("events",a.length),l.set("sessions",c.size),i===st.Sync){if(await this._clock.createTimeout(1e4).elapsed(),this._disposed)return;const h=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);await Promise.all(Array.from(c).map(async([d,u])=>{await this._megolmDecryption.hasSession(this._room.id,u.senderKey,u.sessionId,h)&&c.delete(d)}))}await Promise.all(Array.from(c.values()).map(h=>l.wrap("session",d=>this._requestMissingSessionFromBackup(h.senderKey,h.sessionId,d))))})}async _verifyDecryptionResult(e,t){let s=this._senderDeviceCache.get(e.senderCurve25519Key);s||(s=await this._deviceTracker.getDeviceByCurve25519Key(e.senderCurve25519Key,t),this._senderDeviceCache.set(e.senderCurve25519Key,s)),s?e.setDevice(s):this._room.isTrackingMembers||e.setRoomNotTrackedYet()}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 a=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions]);try{r=await this._megolmDecryption.writeRoomKey(i,a),s.set("isBetter",r),r&&(o=i.eventIds)}catch(c){throw a.abort(),c}await a.complete(),r&&await s.wrap("retryDecryption",c=>this._room.notifyRoomKey(i,o||[],c))}}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())<nd)){this._lastKeyPreShareTime=this._clock.createMeasure();try{this._keySharePromise=(async()=>{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",a=>this._shareNewRoomKey(r.roomKeyMessage,s,a))),{type:zr,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((c,l)=>c.add(l.userId),new Set));let o=await this._storage.readWriteTxn([this._storage.storeNames.operations]),a;try{a=this._writeRoomKeyShareOperation(e,r,o)}catch(c){throw o.abort(),c}await this._processShareRoomKeyOperation(a,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",a=>this._olmEncryption.encrypt("m.room_key",e.roomKeyMessage,i,t,a)),o=i.filter(a=>!r.some(c=>c.device===a));await s.wrap("send",a=>this._sendMessagesToDevices(zr,r,t,a)),o.length&&await s.wrap("missingDevices",async a=>{a.set("devices",o.map(h=>h.deviceId));const c=e.userIds.filter(h=>o.some(d=>d.userId===h));a.set("unsentUserIds",c),e.userIds=c,await this._updateOperationsStore(h=>h.update(e));const l=this._megolmEncryption.createWithheldMessage(e.roomKeyMessage,"m.no_olm","OTKs exhausted");await this._sendSharedMessageToDevices("org.matrix.room_key.withheld",l,o,t,a)}),await this._updateOperationsStore(a=>a.remove(e.id))}async _updateOperationsStore(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.operations]);try{e(t.operations)}catch(s){throw t.abort(),s}await t.complete()}async _sendSharedMessageToDevices(e,t,s,i,r){const o=bt(s,l=>l.userId),a={messages:Array.from(o.entries()).reduce((l,[h,d])=>(l[h]=d.reduce((u,p)=>(u[p.deviceId]=t,u),{}),l),{})},c=Ms();await i.sendToDevice(e,a,c,{log:r}).response()}async _sendMessagesToDevices(e,t,s,i){i.set("messages",t.length);const r=bt(t,c=>c.device.userId),o={messages:Array.from(r.entries()).reduce((c,[l,h])=>(c[l]=h.reduce((d,u)=>(d[u.device.deviceId]=u.content,d),{}),c),{})},a=Ms();await s.sendToDevice(e,o,a,{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 a=(i=o.content)==null?void 0:i.sender_key,c=(r=o.content)==null?void 0:r.session_id;return t.some(l=>a===l.senderKey&&c===l.sessionId)}}return!1})}dispose(){this._disposed=!0}}class ad{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 cd(await this._megolmDecryptionPreparation.decrypt(),this._extraErrors,this._source,this._roomEncryption,this._events)}dispose(){this._megolmDecryptionPreparation.dispose()}}class cd{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 fi(this._extraErrors,i),await this._roomEncryption._processDecryptionResults(this._events,s,i,this._source,e,t),new ld(s,i,this._roomEncryption)}}class ld{constructor(e,t,s){this.results=e,this.errors=t,this._roomEncryption=s}applyToEntries(e){for(const t of e){const s=this.results.get(t.id);if(s)t.setDecryptionResult(s);else{const i=this.errors.get(t.id);i&&t.setDecryptionError(i)}}}verifySenders(e){return Promise.all(Array.from(this.results.values()).map(t=>this._roomEncryption._verifyDecryptionResult(t,e)))}}const yi=0,Jr=1;function hd(n,e,t){if(n){if(!n.roomIds.includes(t))return n.roomIds.push(t),n}else return n={userId:e,roomIds:[t],deviceTrackingStatus:yi},n}function dd(n){var s;const e=n.device_id;return{userId:n.user_id,deviceId:e,ed25519Key:n.keys[`ed25519:${e}`],curve25519Key:n.keys[`curve25519:${e}`],algorithms:n.algorithms,displayName:(s=n.unsigned)==null?void 0:s.device_display_name}}class ud{constructor({storage:e,getSyncToken:t,olmUtil:s,ownUserId:i,ownDeviceId:r}){this._storage=e,this._getSyncToken=t,this._identityChangedForRoom=null,this._olmUtil=s,this._ownUserId=i,this._ownDeviceId=r}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.deviceTrackingStatus=yi,i.set(o))}))}async writeMemberChanges(e,t,s,i){const r=[],o=[];return await Promise.all(Array.from(t.values()).map(async a=>{if(us(a.membership,s))await this._addRoomToUserIdentity(a.roomId,a.userId,i)&&r.push(a.userId);else if(us(a.previousMembership,s)){const{roomId:c}=a;if(a.userId===this._ownUserId){const l=await i.roomMembers.getAllUserIds(c);await Promise.all(l.map(h=>this._removeRoomFromUserIdentity(c,h,i)))}else await this._removeRoomFromUserIdentity(c,a.userId,i);o.push(a.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]);try{let o;try{o=e.writeIsTrackingMembers(!0,r);const a=Array.from(i.members.values());s.set("members",a.length),await Promise.all(a.map(async c=>{us(c.membership,t)&&await this._addRoomToUserIdentity(c.roomId,c.userId,r)}))}catch(a){throw r.abort(),a}await r.complete(),e.applyIsTrackingMembersChanges(o)}finally{i.release()}}async writeHistoryVisibility(e,t,s,i){const r=[],o=[];return e.isTrackingMembers&&e.isEncrypted&&await i.wrap("rewriting userIdentities",async a=>{const c=await e.loadMemberList(s,a);try{const l=Array.from(c.members.values());a.set("members",l.length),await Promise.all(l.map(async h=>{us(h.membership,t)?await this._addRoomToUserIdentity(h.roomId,h.userId,s)&&r.push(h.userId):await this._removeRoomFromUserIdentity(h.roomId,h.userId,s)&&o.push(h.userId)}))}finally{c.release()}}),{added:r,removed:o}}async _addRoomToUserIdentity(e,t,s){const{userIdentities:i}=s,r=await i.get(t),o=hd(r,t,e);return o?(i.set(o),!0):!1}async _removeRoomFromUserIdentity(e,t,s){const{userIdentities:i,deviceIdentities:r}=s,o=await i.get(t);return o?(o.roomIds=o.roomIds.filter(a=>a!==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((c,l)=>(c[l]=[],c),{}),token:this._getSyncToken()},{log:s}).response(),r=s.wrap("verify",c=>this._filterVerifiedDeviceKeys(i.device_keys,c)),o=await this._storage.readWriteTxn([this._storage.storeNames.userIdentities,this._storage.storeNames.deviceIdentities]);let a;try{a=(await Promise.all(r.map(async({userId:l,verifiedKeys:h})=>{const d=h.map(dd);return await this._storeQueriedDevicesForUserId(l,d,o)}))).reduce((l,h)=>l.concat(h),[]),s.set("devices",a.length)}catch(c){throw o.abort(),c}return await o.complete(),a}async _storeQueriedDevicesForUserId(e,t,s){const i=await s.deviceIdentities.getAllDeviceIds(e);for(const c of i)t.every(l=>l.deviceId!==c)&&s.deviceIdentities.remove(e,c);const r=[],o=[];await Promise.all(t.map(async c=>{if(i.includes(c.deviceId)){const l=await s.deviceIdentities.get(c.userId,c.deviceId);if(l.ed25519Key!==c.ed25519Key){r.push(l);return}}r.push(c),o.push(c)}));for(const c of o)s.deviceIdentities.set(c);const a=await s.userIdentities.get(e);return a.deviceTrackingStatus=Jr,s.userIdentities.set(a),r}_filterVerifiedDeviceKeys(e,t){const s=new Set;return Object.entries(e).map(([r,o])=>{const c=Object.entries(o).filter(([l,h])=>{var b,S;const d=h.device_id;if(h.user_id!==r||d!==l)return!1;const p=(b=h.keys)==null?void 0:b[`ed25519:${l}`],_=(S=h.keys)==null?void 0:S[`curve25519:${l}`];if(typeof p!="string"||typeof _!="string")return!1;if(s.has(_))return t.log({l:"ignore device with duplicate curve25519 key",keys:h},t.level.Warn),!1;s.add(_);const f=this._hasValidSignature(h,t);return f||t.log({l:"ignore device with invalid signature",keys:h},t.level.Warn),f}).map(([,l])=>l);return{userId:r,verifiedKeys:c}})}_hasValidSignature(e,t){var o;const s=e.device_id,i=e.user_id,r=(o=e==null?void 0:e.keys)==null?void 0:o[`${Pn}:${s}`];return Un(this._olmUtil,i,s,r,e,t)}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._devicesForUserIds(e,r,i,t,s)}async devicesForRoomMembers(e,t,s,i){const r=await this._storage.readTxn([this._storage.storeNames.userIdentities]);return await this._devicesForUserIds(e,t,r,s,i)}async _devicesForUserIds(e,t,s,i,r){const a=(await Promise.all(t.map(f=>s.userIdentities.get(f)))).filter(f=>f&&f.roomIds.includes(e)),c=a.filter(f=>f.deviceTrackingStatus===Jr),l=a.filter(f=>f.deviceTrackingStatus===yi);r.set("uptodate",c.length),r.set("outdated",l.length);let h;l.length&&(h=await this._queryKeys(l.map(f=>f.userId),i,r));const d=await this._storage.readTxn([this._storage.storeNames.deviceIdentities]);let p=(await Promise.all(c.map(f=>d.deviceIdentities.getAllForUserId(f.userId)))).reduce((f,b)=>f.concat(b),[]);return h&&h.length&&(p=p.concat(h)),p.filter(f=>!(f.userId===this._ownUserId&&f.deviceId===this._ownDeviceId))}async getDeviceByCurve25519Key(e,t){return await t.deviceIdentities.getByCurve25519Key(e)}}class md{constructor(){this._map=new Map}async takeLock(e){let t=this._map.get(e);return t?await t.take():(t=new Mh,t.tryTake(),this._map.set(e,t)),t.released().then(()=>{Promise.resolve().then(()=>{t.isTaken||this._map.delete(e)})}),t}}class pd{constructor({key:e,platform:t}){this._key=e,this._platform=t}async readSecret(e,t){var r,o;const s=await t.accountData.get(e);if(!s)return;const i=(o=(r=s==null?void 0:s.content)==null?void 0:r.encrypted)==null?void 0:o[this._key.id];if(!i)throw new Error(`Secret ${s.type} is not encrypted for key ${this._key.id}`);if(this._key.algorithm==="m.secret_storage.v1.aes-hmac-sha2")return await this._decryptAESSecret(s.type,i);throw new Error(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`)}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),a=r.slice(32),c=s.decode(t.ciphertext);if(!await this._platform.crypto.hmac.verify(a,s.decode(t.mac),c,"SHA-256"))throw new Error("Bad MAC");const h=await this._platform.crypto.aes.decryptCTR({key:o,iv:s.decode(t.iv),data:c});return i.decode(h)}}const Xe="DEFAULT_KEY",Vt="pusher";class _d{constructor({storage:e,hsApi:t,sessionInfo:s,olm:i,olmWorker:r,platform:o,mediaRepository:a}){this._platform=o,this._storage=e,this._hsApi=t,this._mediaRepository=a,this._syncInfo=null,this._sessionInfo=s,this._rooms=new qt,this._roomUpdateCallback=(c,l)=>this._rooms.update(c.id,l),this._activeArchivedRooms=new Map,this._invites=new qt,this._inviteUpdateCallback=(c,l)=>this._invites.update(c.id,l),this._roomsBeingCreatedUpdateCallback=(c,l)=>{c.isCancelled?this._roomsBeingCreated.remove(c.id):this._roomsBeingCreated.update(c.id,l)},this._roomsBeingCreated=new qt,this._user=new Bl(s.userId),this._deviceMessageHandler=new mh({storage:e}),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 we(void 0),this._observedRoomStatus=new Map,i&&(this._olmUtil=new i.Utility,this._deviceTracker=new ud({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 we(!1)}get fingerprintKey(){var e;return(e=this._e2eeAccount)==null?void 0:e.identityKeys.ed25519}get hasSecretStorageKey(){return this._hasSecretStorageKey}get deviceId(){return this._sessionInfo.deviceId}get userId(){return this._sessionInfo.userId}_setupEncryption(){const e=new md,t=new xh(this._e2eeAccount,Xe,this._platform.clock.now,this._user.id,this._olm,e);this._olmEncryption=new Lh(this._e2eeAccount,Xe,this._olm,this._storage,this._platform.clock.now,this._user.id,this._olmUtil,e),this._keyLoader=new Jh(this._olm,Xe,20),this._megolmEncryption=new Zh({account:this._e2eeAccount,pickleKey:Xe,olm:this._olm,storage:this._storage,keyLoader:this._keyLoader,now:this._platform.clock.now,ownDeviceId:this._sessionInfo.deviceId}),this._megolmDecryption=new Gh(this._keyLoader,this._olmWorker),this._deviceMessageHandler.enableEncryption({olmDecryption:t,megolmDecryption:this._megolmDecryption})}_createRoomEncryption(e,t){var s;if(!this._olmEncryption)throw new Error("creating room encryption before encryption got globally enabled");return t.algorithm!==ve?null:new od({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=>{if(!this._olm)throw new Error("olm required");this._keyBackup.get()&&(this._keyBackup.get().dispose(),this._keyBackup.set(null));const r=await Ih(e,t,this._storage,this._platform,this._olm),o=await this._storage.readTxn([this._storage.storeNames.accountData]);if(await this._createKeyBackup(r,o,i))return await this._writeSSSSKey(r,i),this._keyBackup.get().flush(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 vh(e,i,r);if(t.set("previousBackupVersion",o),t.set("backupVersion",i),!!o&&o!==i){const a=await s.markAllForBackup(r);t.set("amountMarkedForBackup",a)}}catch(o){throw r.abort(),o}await r.complete()}async disableSecretStorage(){const e=await this._storage.readWriteTxn([this._storage.storeNames.session]);try{Sh(e)}catch(t){throw e.abort(),t}if(await e.complete(),this._keyBackup.get()){for(const t of this._rooms.values())t.isEncrypted&&t.enableKeyBackup(void 0);this._keyBackup.get().dispose(),this._keyBackup.set(null)}}_createKeyBackup(e,t,s){return s.wrap("enable key backup",async i=>{try{const r=new pd({key:e,platform:this._platform}),o=await Ki.fromSecretStorage(this._platform,this._olm,r,this._hsApi,this._keyLoader,this._storage,t);if(o){for(const a of this._rooms.values())a.isEncrypted&&a.enableKeyBackup(o);return this._keyBackup.set(o),!0}}catch(r){i.catch(r)}return!1})}get keyBackup(){return this._keyBackup}get hasIdentity(){return!!this._e2eeAccount}async createIdentity(e){this._olm&&(this._e2eeAccount||(this._e2eeAccount=await this._createNewAccount(this._sessionInfo.deviceId,this._storage),e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption()),await this._e2eeAccount.generateOTKsIfNeeded(this._storage,e),await e.wrap("uploadKeys",t=>this._e2eeAccount.uploadKeys(this._storage,!1,t)))}async dehydrateIdentity(e,t){return t.set("deviceId",e.deviceId),this._olm?e.deviceId!==this.deviceId?(t.set("wrong_device",!0),!1):this._e2eeAccount?(t.set("account_already_setup",!0),!1):await e.claim(this._hsApi,t)?(this._e2eeAccount=await rt.adoptDehydratedDevice({dehydratedDevice:e,hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,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 rt.create({hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,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 Rh(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._syncInfo=await t.session.get("sync"),this._olm&&(this._e2eeAccount=await rt.load({hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,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 c=>{const l=this.createInvite(c.roomId);e.wrap("invite",h=>l.load(c,h)),this._invites.add(l.id,l)})),o=await t.roomSummary.getAll(),a=Promise.all(o.map(async c=>{const l=this.createJoinedRoom(c.roomId,s.get(c.roomId));await e.wrap("room",h=>l.load(c,t,h)),this._rooms.add(l.id,l)}));await Promise.all([r,a]);for(const[c,l]of this.invites){const h=this.rooms.get(c);h&&h.setInvite(l)}}dispose(){var e,t,s,i;(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;for(const r of this._rooms.values())r.dispose();this._rooms=void 0}async start(e,t,s){var a;if(e){const c=await this._storage.readWriteTxn([this._storage.storeNames.session]);c.session.set("serverVersions",e),await c.complete()}if(!this._keyBackup.get()){t&&await s.wrap("SSSSKeyFromDehydratedDeviceKey",async h=>{const d=await Eh(t.key,this._storage,this._platform);d&&(h.set("success",!0),await this._writeSSSSKey(d))});const c=await this._storage.readTxn([this._storage.storeNames.session,this._storage.storeNames.accountData]),l=await bh(c);l&&await this._createKeyBackup(l,c,s)&&((a=this._keyBackup.get())==null||a.flush(s)),this._keyBackup.get()||this._keyBackup.set(null)}const r=await(await this._storage.readWriteTxn([this._storage.storeNames.operations])).operations.getAll(),o=bt(r,c=>c.scope);for(const c of this._rooms.values()){let l;const h=o.get(c.id);h&&(l=bt(h,d=>d.type)),c.start(l,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 ih({roomId:e,getSyncToken:this._getSyncToken,storage:this._storage,emitCollectionChange:this._roomUpdateCallback,hsApi:this._hsApi,mediaRepository:this._mediaRepository,pendingEvents:t,user:this._user,createRoomEncryption:this._createRoomEncryption,platform:this._platform})}_createArchivedRoom(e){const t=new rh({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 uh({roomId:e,hsApi:this._hsApi,emitCollectionUpdate:this._inviteUpdateCallback,mediaRepository:this._mediaRepository,user:this._user,platform:this._platform})}get roomsBeingCreated(){return this._roomsBeingCreated}createRoom(e){let t;return this._platform.logger.runDetached("create room",async s=>{const i=`local-${Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER)}`;t=new dh(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",a=>this._deviceMessageHandler.prepareSync(r,t,s,a))}async writeSync(e,t,s,i,r){const o={syncInfo:null,e2eeAccountChanges:null},a=e.next_batch;if(a!==this.syncToken){const d={token:a,filterId:t};i.session.set("sync",d),o.syncInfo=d}const c=e.device_one_time_keys_count;this._e2eeAccount&&c&&(o.e2eeAccountChanges=this._e2eeAccount.writeSync(c,i,r));const l=e.device_lists;this._deviceTracker&&Array.isArray(l==null?void 0:l.changed)&&l.changed.length&&await r.wrap("deviceLists",d=>this._deviceTracker.writeDeviceChanges(l.changed,i,d)),s&&(o.hasNewRoomKeys=await r.wrap("deviceMsgs",d=>this._deviceMessageHandler.writeSync(s,i,d)));const h=e.account_data;if(Array.isArray(h==null?void 0:h.events))for(const d of h.events)typeof d.type=="string"&&i.accountData.set(d);return o}afterSync({syncInfo:e,e2eeAccountChanges:t}){e&&(this._syncInfo=e),this._e2eeAccount&&this._e2eeAccount.afterSync(t)}async afterSyncCompleted(e,t,s){var i;t||await this._e2eeAccount.generateOTKsIfNeeded(this._storage,s)&&await s.wrap("uploadKeys",o=>this._e2eeAccount.uploadKeys(this._storage,!1,o)),e.hasNewRoomKeys&&((i=this._keyBackup.get())==null||i.flush(s))}_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()|U.Replaced)),s.dispose(),this._roomsBeingCreated.remove(s.id);return}}applyRoomCollectionChangesAfterSync(e,t,s,i){var r,o;for(const a of t)a.shouldAdd?(this._rooms.add(a.id,a.room),this._tryReplaceRoomBeingCreated(a.id,i)):a.shouldRemove&&this._rooms.remove(a.id);for(const a of e)a.shouldAdd?this._invites.add(a.id,a.invite):a.shouldRemove&&this._invites.remove(a.id);if(this._observedRoomStatus.size!==0){for(const a of s)a.shouldAdd&&((r=this._observedRoomStatus.get(a.id))==null||r.set(U.Archived));for(const a of t)a.shouldAdd&&((o=this._observedRoomStatus.get(a.id))==null||o.set(U.Joined));for(const a of e){const c=this._observedRoomStatus.get(a.id);if(c){const l=c.get()|U.Invited;if(a.shouldAdd)c.set(l);else if(a.shouldRemove){const h=l^U.Invited;c.set(h)}}}}}_forgetArchivedRoom(e){const t=this._observedRoomStatus.get(e);t&&t.set((t.get()|U.Archived)^U.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=tt.createDefaultPayload(this._sessionInfo.id),s=await this._platform.notificationService.enablePush(tt,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(Vt,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(Vt);if(!s)return!0;await new tt(s).disable(this._hsApi,e);const r=await this._storage.readWriteTxn([this._storage.storeNames.session]);return r.session.remove(Vt),await r.complete(),!0})}async arePushNotificationsEnabled(){return await this._platform.notificationService.isPushEnabled()?!!await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(Vt):!1}async checkPusherEnabledOnHomeserver(){const t=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(Vt);if(!t)return!1;const s=new tt(t),i=await this._hsApi.getPushers().response();return((i==null?void 0:i.pushers)||[]).map(o=>new tt(o)).some(o=>o.equals(s))}async getRoomStatus(e){if(!!this._roomsBeingCreated.get(e))return U.BeingCreated;if(!!this._rooms.get(e))return U.Joined;{const i=!!this._invites.get(e),o=await(await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary])).archivedRoomSummary.has(e);return i&&o?U.Invited|U.Archived:i?U.Invited:o?U.Archived:U.None}}async observeRoomStatus(e){let t=this._observedRoomStatus.get(e);if(!t){const s=await this.getRoomStatus(e);t=new ci(s,()=>{this._observedRoomStatus.delete(e)}),this._observedRoomStatus.set(e,t)}return t}createOrGetArchivedRoomForSync(e){let t=this._activeArchivedRooms.get(e);return t?t.retain():t=this._createArchivedRoom(e),t}loadArchivedRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"loadArchivedRoom",async 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 a=this._createArchivedRoom(e);return await a.load(o,r,s),a}})}joinRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"joinRoom",async s=>(await this._hsApi.joinIdOrAlias(e,{log:s}).response()).room_id)}}class fd{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 gd{constructor({homeserver:e,loginToken:t}){this.homeserver=e,this._loginToken=t}async login(e,t,s){return await e.tokenLogin(this._loginToken,Ms(),t,{log:s}).response()}}class yd{constructor(e){this._homeserver=e}get homeserver(){return this._homeserver}createSSORedirectURL(e){return`${this._homeserver}/_matrix/client/r0/login/sso/redirect?redirectUrl=${e}`}}class $i{constructor(e,t){this._session=e,this._params=t}setNextStage(e){this._nextStage=e}get nextStage(){return this._nextStage}}class wd extends $i{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.dummy"}}class vd extends $i{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 bd extends $i{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 Sd{constructor(e,t,s){this._hsApi=e,this._accountDetails=t,this._flowSelector=s!=null?s:i=>i[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,a=this._hsApi.register(s,i,r,t,o),c=await a.response(),l=await a.responseCode(),h=yr(ft({},c),{status:l});return this.parseRegistrationResponse(h,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 a of i.stages){const c=this._createRegistrationStage(a,t,s);r?(o.setNextStage(c),o=c):(r=c,o=c)}return r}async parseRegistrationResponse(e,t){var s;switch(e.status){case 200:this._sessionInfo=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 wd(t,s==null?void 0:s[e]);case"m.login.terms":return new vd(t,s==null?void 0:s[e]);case"org.matrix.msc3231.login.registration_token":case"m.login.registration_token":return new bd(t,s==null?void 0:s[e],e);default:throw new Error(`Unknown stage: ${e}`)}}get sessionInfo(){return this._sessionInfo}}const M=xe("NotLoading","Login","LoginFailed","QueryAccount","AccountSetup","Loading","SessionSetup","Migrating","FirstSync","Error","Ready"),Ce=xe("Connection","Credentials","Unknown");class ji{constructor(e){this._platform=e,this._sessionStartedByReconnector=!1,this._status=new we(M.NotLoading),this._error=null,this._loginFailure=null,this._reconnector=null,this._session=null,this._sync=null,this._sessionId=null,this._storage=null,this._requestScheduler=null,this._olmPromise=e.loadOlm(),this._workerPromise=e.loadOlmWorker(),this._accountSetup=void 0}createNewSessionId(){return Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER).toString()}get sessionId(){return this._sessionId}async startWithExistingSession(e){this._status.get()===M.NotLoading&&(this._status.set(M.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(M.Error)}}))}_parseLoginOptions(e,t){const s=e.flows,i={homeserver:t};for(const r of s)r.type==="m.login.password"?i.password=(o,a)=>new fd({homeserver:t,username:o,password:a}):r.type==="m.login.sso"&&s.find(o=>o.type==="m.login.token")?i.sso=new yd(t):r.type==="m.login.token"&&(i.token=o=>new gd({homeserver:t,loginToken:o}));return i}queryLogin(e){return new Mn(async t=>{e=await ma(e,(r,o)=>t(this._platform.request(r,o)));const s=new Ze({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,a=new Ze({homeserver:e,request:o});return new Sd(a,{username:t,password:s,initialDeviceDisplayName:i},r)}async startWithLogin(e,{inspectAccountSetup:t}={}){const s=this._status.get();s!==M.LoginFailed&&s!==M.NotLoading&&s!==M.Error||(this._resetStatus(),await this._platform.logger.run("login",async i=>{this._status.set(M.Login);const r=this._platform.clock;let o;try{const c=this._platform.request,l=new Ze({homeserver:e.homeserver,request:c}),h=await e.login(l,"Hydrogen",i),d=this.createNewSessionId();o={id:d,deviceId:h.device_id,userId:h.user_id,homeServer:e.homeserver,homeserver:e.homeserver,accessToken:h.access_token,lastUsed:r.now()},i.set("id",d)}catch(c){this._error=c,c.name==="HomeServerError"?(c.errcode==="M_FORBIDDEN"?this._loginFailure=Ce.Credentials:this._loginFailure=Ce.Unknown,i.set("loginFailure",this._loginFailure),this._status.set(M.LoginFailed)):c.name==="ConnectionError"?(this._loginFailure=Ce.Connection,this._status.set(M.LoginFailed)):this._status.set(M.Error);return}let a;t&&(a=await this._inspectAccountAfterLogin(o,i),a&&(o.deviceId=a.deviceId)),await this._platform.sessionInfoStorage.add(o);try{await this._loadSessionInfo(o,a,i),i.set("status",this._status.get())}catch(c){i.catch(c),a==null||a.dispose(),this._error=c,this._status.set(M.Error)}}))}async _loadSessionInfo(e,t,s){s.set("appVersion",this._platform.version);const i=this._platform.clock;this._sessionStartedByReconnector=!1,this._status.set(M.Loading),this._reconnector=new ba({onlineStatus:this._platform.onlineStatus,retryDelay:new Dn(i.createTimeout),createMeasure:i.createMeasure});const r=new Ze({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},a=await this._olmPromise;let c=null;this._workerPromise&&(c=await this._workerPromise),this._requestScheduler=new Ra({hsApi:r,clock:i}),this._requestScheduler.start();const l=new Ea({homeserver:e.homeServer,platform:this._platform});if(this._session=new _d({storage:this._storage,sessionInfo:o,hsApi:this._requestScheduler.hsApi,olm:a,olmWorker:c,mediaRepository:l,platform:this._platform}),await this._session.load(s),t?(await s.wrap("dehydrateIdentity",h=>this._session.dehydrateIdentity(t,h)),await this._session.setupDehydratedDevice(t.key,s)):this._session.hasIdentity||(this._status.set(M.SessionSetup),await s.wrap("createIdentity",h=>this._session.createIdentity(h))),this._sync=new Ma({hsApi:this._requestScheduler.hsApi,storage:this._storage,session:this._session,logger:this._platform.logger}),this._reconnectSubscription=this._reconnector.connectionStatus.subscribe(h=>{h===$t.Online&&this._platform.logger.runDetached("reconnect",async d=>{this._requestScheduler.start(),this._sync.start(),this._sessionStartedByReconnector=!0;const u=t;t=void 0,await d.wrap("session start",p=>this._session.start(this._reconnector.lastVersionsResponse,u,p))})}),await s.wrap("wait first sync",()=>this._waitForFirstSync()),!this._isDisposed&&(this._status.set(M.Ready),!this._sessionStartedByReconnector)){const h=await r.versions({timeout:1e4,log:s}).response();if(this._isDisposed)return;const d=t;t=void 0,await s.wrap("session start",u=>this._session.start(h,d,u))}}async _waitForFirstSync(){this._sync.start(),this._status.set(M.FirstSync),this._waitForFirstSyncHandle=this._sync.status.waitFor(e=>{var t;return e===L.Stopped?((t=this._sync.error)==null?void 0:t.name)!=="ConnectionError":e===L.Syncing});try{if(await this._waitForFirstSyncHandle.promise,this._sync.status.get()===L.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 a;this._status.set(M.QueryAccount);const i=new Ze({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request}),r=await this._olmPromise;let o;try{o=await kh(i,r,this._platform,s)}catch(c){if(c.name==="HomeServerError")s.set("not_supported",!0);else throw c}if(o){let c;const l=new Promise(d=>c=d);this._accountSetup=new Id(o,c),this._status.set(M.AccountSetup),await l;const h=(a=this._accountSetup)==null?void 0:a._dehydratedDevice;return this._accountSetup=null,h}})}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 Ze({homeserver:s.homeServer,accessToken:s.accessToken,request:this._platform.request}).logout({log:t}).response()}catch{}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(M.NotLoading),this._error=null,this._loginFailure=null}}class Id{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 A extends Ls{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 Ni),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;i<e.length;++i)s=s+e[i],i<t.length&&(s=s+t[i]);return s}emitChange(e){this._options.emitChange?this._options.emitChange(e):this.emit("change",e)}get platform(){return this._options.platform}get clock(){return this._options.platform.clock}get logger(){return this.platform.logger}get urlCreator(){return this._options.urlCreator}get navigation(){return this._options.navigation}}function he(n){let e=n.charAt(0);return(e==="!"||e==="@"||e==="#")&&(e=n.charAt(1)),e.toUpperCase()}function Ed(n){let e=0,t,s;if(n.length===0)return e;for(t=0;t<n.length;t++)s=n.charCodeAt(t),e=(e<<5)-e+s,e|=0;return Math.abs(e)}function de(n){return Ed(n)%8+1}function De(n,e,t,s){if(n){const i=e*t.devicePixelRatio;return s.mxcUrlThumbnail(n,i,i,"crop")}return null}const Qr=["roomBeingCreated","invite","room"];class qi extends A{constructor(e){super(e),this._isOpen=!1,this._hidden=!1}get hidden(){return this._hidden}set hidden(e){e!==this._hidden&&(this._hidden=e,this.emitChange("hidden"))}close(){this._isOpen&&(this._isOpen=!1,this.emitChange("isOpen"))}open(){this._isOpen||(this._isOpen=!0,this.emitChange("isOpen"))}get isOpen(){return this._isOpen}compare(e){return e.kind!==this.kind?Qr.indexOf(this.kind)-Qr.indexOf(e.kind):0}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._avatarSource.avatarColorId)}avatarUrl(e){return De(this._avatarSource.avatarUrl,e,this.platform,this._avatarSource.mediaRepository)}get avatarTitle(){return this.name}}class kd extends qi{constructor(e){super(e);const{room:t}=e;this._room=t,this._url=this.urlCreator.openRoomActionUrl(this._room.id)}get kind(){return"room"}get url(){return this._url}compare(e){const t=super.compare(e);if(t!==0)return t;const s=this._room,i=e._room;if(s.isLowPriority!==i.isLowPriority)return s.isLowPriority?1:-1;const r=s.lastMessageTimestamp,o=i.lastMessageTimestamp,a=Number.isSafeInteger(r),c=Number.isSafeInteger(o);if(a!==c)return c?1:-1;const l=o-r;if(l===0||!c||!a){const h=this.name.localeCompare(e.name);return h===0?this._room.id.localeCompare(e._room.id):h}return l}get isUnread(){return this._room.isUnread}get name(){return this._room.name||this.i18n`Empty Room`}get badgeCount(){return this._room.notificationCount}get isHighlighted(){return this._room.highlightCount!==0}get _avatarSource(){return this._room}}function wi(n,e){return n===e?0:n<e?-1:1}class Rd extends qi{constructor(e){super(e);const{invite:t}=e;this._invite=t,this._url=this.urlCreator.openRoomActionUrl(this._invite.id)}get busy(){return this._invite.accepting||this._invite.rejecting}get kind(){return"invite"}get url(){return this._url}get name(){return this._invite.name}get isHighlighted(){return!0}get isUnread(){return!0}get badgeCount(){return this.i18n`!`}get _avatarSource(){return this._invite}compare(e){const t=super.compare(e);if(t!==0)return t;const s=e._invite.timestamp-this._invite.timestamp;return s!==0?s:wi(this._invite.id,e._invite.id)}}class Cd extends qi{constructor(e){super(e);const{roomBeingCreated:t}=e;this._roomBeingCreated=t,this._url=this.urlCreator.openRoomActionUrl(this._roomBeingCreated.id)}get busy(){return!this._roomBeingCreated.error}get kind(){return"roomBeingCreated"}get isHighlighted(){return!this.busy}get badgeCount(){return!this.busy&&this.i18n`Failed`}get url(){return this._url}get name(){return this._roomBeingCreated.name}get _avatarSource(){return this._roomBeingCreated}compare(e){const t=super.compare(e);if(t!==0)return t;const s=wi(this.name,e.name);return s===0?wi(this._roomBeingCreated.id,e._roomBeingCreated.id):s}avatarUrl(e){var t;return(t=this._roomBeingCreated.avatarBlobUrl)!=null?t:super.avatarUrl(e)}}class Td{constructor(e){this._parts=e.split(" ").map(t=>t.toLowerCase().trim())}matches(e){const t=e.name.toLowerCase();return this._parts.every(s=>t.includes(s))}}class Md extends Ct{constructor(e,t){super(),this._source=e,this._apply=t,this._subscription=null}hasApply(){return!!this._apply}setApply(e){this._apply=e,e&&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()}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 Ad{constructor(e){this._observables=new Map,this._allowsChild=e,this._path=new ke([],e),this._pathObservable=new we(this._path)}get pathObservable(){return this._pathObservable}get path(){return this._path}push(e,...t){const s=this.path.with(new se(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 Nd(this,e),this._observables.set(e,t)),t}pathFrom(e){let t,s;for(s=0;s<e.length;s+=1){if(!this._allowsChild(t,e[s]))return new ke(e.slice(0,s),this._allowsChild);t=e[s]}return new ke(e,this._allowsChild)}segment(e,...t){return new se(e,...t)}}function xd(n,e){if(n===e)return!0;if(Array.isArray(n)&&Array.isArray(e)){const t=Math.max(n.length,e.length);for(let s=0;s<t;s+=1)if(n[s]!==e[s])return!1;return!0}return!1}class se{constructor(e,...t){this.type=e,this.value=t[0]===void 0?!0:t[0]}}class ke{constructor(e=[],t){this._segments=e,this._allowsChild=t}clone(){return new ke(this._segments.slice(),this._allowsChild)}with(e){let t=this._segments.length-1;do{if(this._allowsChild(this._segments[t],e)){const s=this._segments.slice(0,t+1);return s.push(e),new ke(s,this._allowsChild)}t-=1}while(t>=-1)}until(e){const t=this._segments.findIndex(s=>s.type===e);return t!==-1?new ke(this._segments.slice(0,t+1),this._allowsChild):new ke([],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 ke(r,this._allowsChild)}}}}get segments(){return this._segments}}class Nd extends kt{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();xd(e,this._lastSetValue)||(this._lastSetValue=e,this.emit(e))}}class Dd{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/${e}`;return this._history.pathAsUrl(t)}createSSOCallbackURL(){return window.location.origin}normalizeUrl(){this._history.replaceUrlSilently(`${window.location.origin}/${window.location.hash}`)}}function Vd(){return new Ad(Od)}function Ld({history:n,navigation:e}){return new Dd(n,e,Ud,Fd)}function Od(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";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";default:return!1}}function Pd(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 se("rooms",o)}}function Yr(n,e,...t){n.push(new se("right-panel")),n.push(new se(e,...t))}function vi(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 Ud(n,e,t){const s=n.substring(1).split("/"),i=s[Symbol.iterator](),r=[];let o;for(;!(o=i.next()).done;){const a=o.value;if(a==="rooms"){const c=i.next().value;if(c===void 0)break;const l=c.split(",");r.push(new se(a,l));const h=parseInt(i.next().value||"0",10),d=l[h];d?r.push(new se("room",d)):r.push(new se("empty-grid-tile",h))}else if(a==="open-room"){const c=i.next().value;if(!c)break;const l=e.get("rooms");if(l&&r.push(Pd(l,c,e)),r.push(new se("room",c)),s.findIndex(u=>u==="open-room")>=s.length-2){const u=e.segments,p=u.findIndex(_=>_.type==="right-panel");p!==-1&&r.push(...u.slice(p))}}else if(a==="last-session"){let c=e.get("session");typeof(c==null?void 0:c.value)!="string"&&t&&(c=new se("session",t)),c&&r.push(c)}else if(a==="details"||a==="members")Yr(r,a);else if(a==="member"){const c=i.next().value;if(!c)break;Yr(r,a,c)}else if(a.includes("loginToken")){const c=a.split("=").pop();r.push(new se("sso",c))}else{const c=i.next().value;r.push(new se(a,c))}}return r}function Fd(n){let e="",t;for(const s of n.segments){switch(s.type){case"rooms":e+=`/rooms/${s.value.join(",")}`;break;case"empty-grid-tile":e+=`/${s.value}`;break;case"room":(t==null?void 0:t.type)==="rooms"?e+=`/${t.value.indexOf(s.value)}`:e+=`/${s.type}/${s.value}`;break;case"right-panel":case"sso":continue;default:e+=`/${s.type}`,s.value&&s.value!==!0&&(e+=`/${s.value}`)}t=s}return e}class Bd extends A{constructor(e){super(e);const{session:t}=e;this._tileViewModelsMap=this._mapTileViewModels(t.roomsBeingCreated,t.invites,t.rooms),this._tileViewModelsFilterMap=new Md(this._tileViewModelsMap),this._tileViewModels=this._tileViewModelsFilterMap.sortValues((s,i)=>s.compare(i)),this._currentTileVM=null,this._setupNavigation(),this._closeUrl=this.urlCreator.urlForSegment("session"),this._settingsUrl=this.urlCreator.urlForSegment("settings"),this._createRoomUrl=this.urlCreator.urlForSegment("create-room")}_mapTileViewModels(e,t,s){return t.join(e,s).mapValues((r,o)=>{var l;let a;return r.isBeingCreated?a=new Cd(this.childOptions({roomBeingCreated:r,emitChange:o})):r.isInvite?a=new Rd(this.childOptions({invite:r,emitChange:o})):a=new kd(this.childOptions({room:r,emitChange:o})),((l=this.navigation.path.get("room"))==null?void 0:l.value)===r.id&&(a.open(),this._updateCurrentVM(a)),a})}_updateCurrentVM(e){var t;(t=this._currentTileVM)==null||t.close(),this._currentTileVM=e}get closeUrl(){return this._closeUrl}get settingsUrl(){return this._settingsUrl}get createRoomUrl(){return this._createRoomUrl}_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=vi(this.navigation,t)):e?(t=t.with(this.navigation.segment("rooms",[e.value])),t=t.with(e),t=vi(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 Td(e);return this._tileViewModelsFilterMap.setApply((i,r)=>{r.hidden=!s.matches(r)}),t}}}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 Kd extends Rt{constructor(e,t){super(),this._entries=e,this._tiles=null,this._entrySubscription=null,this._tileOptions=t,this._emitSpontanousUpdate=this._emitSpontanousUpdate.bind(this)}_createTile(e){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}_emitSpontanousUpdate(e,t){const s=e.lowerEntry,i=this._findTileIdx(s);this.emitUpdate(i,e,t)}onSubscribeFirst(){this._entrySubscription=this._entries.subscribe(this),this._populateTiles()}_populateTiles(){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(const s of this._tiles)s.setUpdateEmit(this._emitSpontanousUpdate)}_findTileIdx(e){return He(this._tiles,e,(t,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?this._tiles[e]:null}onUnsubscribeLast(){this._entrySubscription=this._entrySubscription();for(let e=0;e<this._tiles.length;e+=1)this._tiles[e].dispose();this._tiles=null}onReset(){this._buildInitialTiles(),this.emitReset()}onAdd(e,t){const s=this._findTileIdx(t),i=this._getTileAtIdx(s-1);if(i&&i.tryIncludeEntry(t)){this.emitUpdate(s-1,i);return}const r=this._getTileAtIdx(s);if(r&&r.tryIncludeEntry(t)){this.emitUpdate(s,r);return}const o=this._createTile(t);o&&(i&&(i.updateNextSibling(o),o.updatePreviousSibling(i)),r&&(o.updateNextSibling(r),r.updatePreviousSibling(o)),this._tiles.splice(s,0,o),this.emitAdd(s,o),o.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 a=this._createTile(t);a?(this._replaceTile(i,r,a,o.updateParams),a.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)}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=He(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 $d extends A{constructor(e){super(e);const{timeline:t,tileOptions:s}=e;this._timeline=this.track(t),this._tiles=new Kd(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._tiles.length-1)}else s=!0,this._setShowJumpDown(!1);s&&!this._topLoadingPromise&&(this._topLoadingPromise=this._timeline.loadAtTop(10).then(i=>{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 jd extends A{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"}}function Ht(n){return{w:n.width,h:n.height,mimetype:n.blob.mimeType,size:n.blob.size}}class ss extends A{constructor(e,t){super(t),this._entry=e,this._emitUpdate=void 0}get shape(){return null}get isContinuation(){return!1}get hasDateSeparator(){return!1}get id(){return this._entry.asEventKey()}get eventId(){return this._entry.id}get isPending(){return this._entry.isPending}get isUnsent(){return this._entry.isPending&&this._entry.pendingEvent.status!==V.Sent}get canAbortSending(){return this._entry.isPending&&!this._entry.pendingEvent.hasStartedSending}abortSending(){var e;(e=this._entry.pendingEvent)==null||e.abort()}setUpdateEmit(e){this._emitUpdate=e}emitChange(e){this._emitUpdate&&this._emitUpdate(this,e),super.emitChange(e)}get upperEntry(){return this._entry}get lowerEntry(){return this._entry}compare(e){return this.upperEntry.compare(e.upperEntry)}compareEntry(e){return this._entry.compare(e)}updateEntry(e,t){const 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(){}updateNextSibling(){}notifyVisible(){}dispose(){this.setUpdateEmit(null),super.dispose()}get _room(){return this._roomVM.room}get _roomVM(){return this._options.roomVM}get _timeline(){return this._options.timeline}get _powerLevels(){return this._timeline.powerLevels}get _ownMember(){return this._options.timeline.me}}class qd extends ss{constructor(e,t){super(e,t),this._loading=!1,this._error=null,this._isAtTop=!0,this._siblingChanged=!1}async fill(){if(!this._loading&&!this._entry.edgeReached){this._loading=!0,this.emitChange("isLoading");try{await this._room.fillGap(this._entry,10)}catch(e){throw console.error(`room.fillGap(): ${e.message}:
${e.stack}`),this._error=e,this.emitChange("error"),e}finally{this._loading=!1,this.emitChange("isLoading")}return!0}return!1}async notifyVisible(){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()}get shape(){return"gap"}get isLoading(){return this._loading}get error(){return this._error?`Could not load ${this._entry.prev_batch?"previous":"next"} messages: ${this._error.message}`:null}}class Wd{constructor(e){this._parentTile=e,this._map=new qt,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 Xr(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 Xr(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 Xr{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<e.key?-1:1:t}}async toggle(e=null){if(this._isToggling){console.log("busy toggling reaction already");return}this._isToggling=!0;try{await this._parentTile.toggleReaction(this.key,e)}finally{this._isToggling=!1}}}class Je extends ss{constructor(e,t){super(e,t),this._date=this._entry.timestamp?new Date(this._entry.timestamp):null,this._isContinuation=!1,this._reactions=null,this._replyTile=null,(this._entry.annotations||this._entry.pendingAnnotations)&&this._updateReactions(),this._updateReplyTileIfNeeded(void 0)}notifyVisible(){var e;super.notifyVisible(),(e=this._replyTile)==null||e.notifyVisible()}get _mediaRepository(){return this._room.mediaRepository}get permaLink(){return`https://matrix.to/#/${encodeURIComponent(this._room.id)}/${encodeURIComponent(this._entry.id)}`}get senderProfileLink(){return`https://matrix.to/#/${encodeURIComponent(this.sender)}`}get displayName(){return this._entry.displayName||this.sender}get sender(){return this._entry.sender}get memberPanelLink(){return`${this.urlCreator.urlUntilSegment("room")}/member/${this.sender}`}get avatarColorNumber(){return de(this._entry.sender)}avatarUrl(e){return De(this._entry.avatarUrl,e,this.platform,this._mediaRepository)}get avatarLetter(){return he(this.sender)}get avatarTitle(){return this.displayName}get date(){return this._date&&this._date.toLocaleDateString({},{month:"numeric",day:"numeric"})}get time(){return this._date&&this._date.toLocaleTimeString({},{hour:"numeric",minute:"2-digit"})}get isOwn(){return this._entry.sender===this._ownMember.userId}get isContinuation(){return this._isContinuation}get isUnverified(){return this._entry.isUnverified}get isReply(){return this._entry.isReply}_getContent(){return this._entry.content}updatePreviousSibling(e){super.updatePreviousSibling(e);let t=!1;if(e&&e instanceof Je&&e.sender===this.sender){const s=this._entry.timestamp,i=e._entry.timestamp;t=s-i<5*60*1e3}t!==this._isContinuation&&(this._isContinuation=t,this.emitChange("isContinuation"))}updateEntry(e,t){const s=super.updateEntry(e,t);return s.shouldUpdate&&this._updateReactions(),this._updateReplyTileIfNeeded(t),s}_updateReplyTileIfNeeded(e){var s,i;const t=this._entry.contextEntry;if(t){const r=(s=this._replyTile)==null?void 0:s.updateEntry(t,e);if((r==null?void 0:r.shouldReplace)||!this._replyTile){this.disposeTracked(this._replyTile);const a=this._options.tileClassForEntry(t);a&&(this._replyTile=new a(t,this._options))}r!=null&&r.shouldUpdate&&((i=this._replyTile)==null||i.emitChange())}}startReply(){this._roomVM.startReply(this._entry)}reply(e,t,s=null){return this._room.sendEvent("m.room.message",this._entry.reply(e,t),null,s)}redact(e,t){return this._room.sendRedaction(this._entry.id,e,t)}get canRedact(){return this._powerLevels.canRedactFromSender(this._entry.sender)}get reactions(){return this.shape!=="redacted"?this._reactions:null}get canReact(){return this._powerLevels.canSendType("m.reaction")}react(e,t=null){return this.logger.wrapOrRun(t,"react",async s=>{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 Wd(this)),this._reactions.update(e,t))}get replyTile(){return this._entry.contextEventId?this._replyTile:null}}const Hd="(?:https|http|ftp):\\/\\/",wo="[^\\s.,?!)]",Zr="[a-zA-Z0-9:.\\[\\]-]",zd=`${Zr}*(?=${Zr})${wo}`,Gd=`(?:[\\/#](?:[^\\s]*${wo})?)`,Jd=`${Hd}${zd}${Gd}?`,Qd=new RegExp(Jd,"gi");function vo(n,e){const t=n.matchAll(Qd);let s=0;for(let r of t){const o=n.slice(s,r.index);e(o,!1),e(r[0],!0);const a=r[0].length;s=r.index+a}const i=n.slice(s);e(i,!1)}function Yd(n){const e=[],t=n.split(`
`),s=(i,r)=>{r?e.push(new bi(i,[new St(i)])):e.push(new St(i))};for(let i=0;i<t.length;i+=1){const r=t[i];r.length&&vo(r,s),i>=t.length-1||e.push(new bo)}return new Wi(n,e)}function Xd(n){return new Wi(n,[new St(n)])}class Zd{constructor(e,t){this.level=e,this.inlines=t}get type(){return"header"}}class en{constructor(e,t){this.language=e,this.text=t}get type(){return"codeblock"}}class eu{constructor(e,t){this.items=t,this.startOffset=e}get type(){return"list"}}class tu{constructor(e,t){this.head=e,this.body=t}get type(){return"table"}}class su{get type(){return"rule"}}class bo{get type(){return"newline"}}class ws{constructor(e,t){this.format=e.toLowerCase(),this.children=t}get type(){return"format"}}class iu{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 ru{constructor(e,t,s){this.id=e,this.href=t,this.children=s}get type(){return"pill"}get avatarColorNumber(){return de(this.id)}get avatarInitials(){return he(this.id)}}class bi{constructor(e,t){this.url=e,this.inlines=t}get type(){return"link"}}class St{constructor(e){this.text=e}get type(){return"text"}}function nu(n){return n.type==="format"&&n.format==="blockquote"}class Wi{constructor(e,t){this.sourceString=e,this.parts=t}insertEmote(e){let t=0;for(;t<this.parts.length&&nu(this.parts[t]);t++);this.parts.splice(t,0,new St(e))}}const Bt=xe("Plain","Html");class So extends Je{constructor(e,t){super(e,t),this._messageBody=null,this._format=null}get shape(){return"message"}_parseBody(e){return Xd(e)}_getBodyFormat(){return Bt.Plain}get body(){const e=this._getBody(),t=this._getBodyFormat();return(!this._messageBody||this._messageBody.sourceString!==e||this._format!==t)&&(this._messageBody=this._parseBody(e,t),this._format=t),this._messageBody}}const ou=["EM","STRONG","CODE","DEL","SPAN"],au=["DIV","BLOCKQUOTE"],cu=["https","http","ftp","mailto","magnet"].map(n=>`${n}://`),lu="https://matrix.to",tn=`${lu}/#/`;class hu{constructor(e,t){this.result=e,this.mediaRepository=t}parsePillLink(e){if(!e.startsWith(tn))return null;const t=e.substring(tn.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||!cu.some(o=>i.startsWith(o)))return new ws("span",t);const r=this.parsePillLink(s);return r?new ru(r,s,t):new bi(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 eu(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 en(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 en(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,a=t.getAttributeValue(e,"alt"),c=t.getAttributeValue(e,"title");return new iu(i,r,o,a,c)}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 tu(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 bo;default:{if(!ou.includes(s))return null;const r=this.parseInlineNodes(i);return new ws(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 Zd(parseInt(s[1]),r)}case"UL":case"OL":return this.parseList(e);case"PRE":return this.parseCodeBlock(e);case"HR":return new su;case"IMG":return this.parseImage(e);case"P":{const r=this.parseInlineNodes(i);return new ws(s,r)}case"TABLE":return this.parseTable(e);default:{if(!au.includes(s))return null;const r=this.parseAnyNodes(i);return new ws(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 bi(i,[new St(i)])):t.push(new St(i))};return vo(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 du(n,e,t){const s=n.parseHTML(t),r=new hu(s,e).parseAnyNodes(s.rootNodes);return new Wi(t,r)}class uu extends So{_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()===Bt.Html?this._getFormattedBody():this._getPlainBody()}_getBodyFormat(){var e;return((e=this._getContent())==null?void 0:e.format)==="org.matrix.custom.html"?Bt.Html:Bt.Plain}_parseBody(e,t){var i;let s;return t===Bt.Html?s=du(this.platform,this._mediaRepository,e):s=Yd(e),((i=this._getContent())==null?void 0:i.msgtype)==="m.emote"&&s.insertEmote(`* ${this.displayName} `),s}}class sn extends Je{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 mu=300,pu=400;class Io extends Je{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===V.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 V.Waiting:return this.i18n`Waiting…`;case V.EncryptingAttachments:case V.Encrypting:return this.i18n`Encrypting…`;case V.UploadingAttachments:return this.i18n`Uploading…`;case V.Sending:return this.i18n`Sending…`;case V.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=mu/(e==null?void 0:e.h),s=pu/(e==null?void 0:e.w);return Math.min(s,t,1)}_isMainResourceImage(){return!0}}class _u extends Io{constructor(e,t){super(e,t),this._lightboxUrl=this.urlCreator.urlForSegments([this.navigation.segment("room",this._room.id),this.navigation.segment("lightbox",this._entry.id)])}get lightboxUrl(){return this.isPending?"":this._lightboxUrl}get shape(){return"image"}}class fu extends Io{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 gu(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 yu extends Je{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 V.Waiting:return this.i18n`Waiting to send ${t}`;case V.EncryptingAttachments:case V.Encrypting:return this.i18n`Encrypting ${t}`;case V.UploadingAttachments:{const r=Math.round(i.attachmentsSentBytes/i.attachmentsTotalBytes*100);return this.i18n`Uploading ${t}: ${r}%`}case V.Sending:case V.Sent:return this.i18n`Sending ${t}`;case V.Error:return this.i18n`Error: could not send ${t}: ${i.error.message}`;default:return`Unknown send status for ${t}`}}else{const i=gu((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 wu extends Je{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),a=parseFloat(r);let c;for(const l of s){const[h,d]=l.split("=");h==="u"&&(c=parseFloat(d))}if(this.platform.isIOS)return`http://maps.apple.com/?ll=${o},${a}`;{let l=`geo:${o},${a}`;return c&&(l=l+`;u=${c}`),l}}catch{return""}}get label(){return this.i18n`${this.displayName} sent their location`}}class vu extends ss{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 bu extends ss{get shape(){return"announcement"}get announcement(){var l,h;const{sender:e,content:t,prevContent:s,stateKey:i}=this._entry,r=this._entry.displayName||e,o=e===i?r:((l=this._entry.content)==null?void 0:l.displayname)||i,a=t&&t.membership,c=s&&s.membership;if(c==="join"&&a==="join"){if(t.avatar_url!==s.avatar_url)return`${r} changed their avatar`;if(t.displayname!==s.displayname)return t.displayname?`${(h=s.displayname)!=null?h:i} changed their name to ${t.displayname}`:`${i} removed their name (${s.displayname})`}else{if(a==="join")return`${o} joined the room`;if(a==="invite")return`${o} was invited to the room by ${r}`;if(c==="invite"){if(a==="join")return`${o} accepted the invitation to join the room`;if(a==="leave")return`${o} declined the invitation to join the room`}else if(a==="leave"){if(i===e)return`${o} left the room`;{const d=t.reason;return`${o} was kicked from the room by ${r}${d?`: ${d}`:""}`}}else if(a==="ban")return`${o} was banned from the room by ${r}`}return`${e} membership changed to ${t.membership}`}}class Su extends So{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 Iu extends ss{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 Eu extends Je{get shape(){return"missing-attachment"}get label(){const e=this._getContent().body;return this._getContent().msgtype==="m.image"?this.i18n`The image ${e} wasn't fully sent previously and could not be recovered.`:this.i18n`The file ${e} wasn't fully sent previously and could not be recovered.`}}function ku(n){if(n.isGap)return qd;if(n.isPending&&n.pendingEvent.isMissingAttachments)return Eu;if(n.eventType)switch(n.eventType){case"m.room.message":{if(n.isRedacted)return sn;const e=n.content;switch(e&&e.msgtype){case"m.text":case"m.notice":case"m.emote":return uu;case"m.image":return _u;case"m.video":return fu;case"m.file":return yu;case"m.location":return wu;default:return}}case"m.room.name":return vu;case"m.room.member":return bu;case"m.room.encrypted":return n.isRedacted?sn:Su;case"m.room.encryption":return Iu;default:return}}class rn extends A{constructor(e){super(e);const{room:t,tileClassForEntry:s}=e;this._room=t,this._timelineVM=null,this._tileClassForEntry=s!=null?s:ku,this._tileOptions=void 0,this._onRoomChange=this._onRoomChange.bind(this),this._timelineError=null,this._sendError=null,this._composerVM=null,t.isArchived?this._composerVM=this.track(new Cu(this.childOptions({archivedRoom:t}))):this._recreateComposerOnPowerLevelChange(),this._clearUnreadTimout=null,this._closeUrl=this.urlCreator.urlUntilSegment("session")}async load(){this._room.on("change",this._onRoomChange);try{const e=await this._room.openTimeline();this._tileOptions=this.childOptions({roomVM:this,timeline:e,tileClassForEntry:this._tileClassForEntry}),this._timelineVM=this.track(new $d(this.childOptions({tileOptions:this._tileOptions,timeline:e}))),this.emitChange("timelineViewModel")}catch(e){console.error(`room.openTimeline(): ${e.message}:
${e.stack}`),this._timelineError=e,this.emitChange("error")}this._clearUnreadAfterDelay()}async _recreateComposerOnPowerLevelChange(){const e=await this._room.observePowerLevels(),t=()=>e.get().canSendType("m.room.message");let s=t();const i=r=>{this._composerVM=this.disposeTracked(this._composerVM),r?this._composerVM=this.track(new jd(this)):this._composerVM=this.track(new Tu(this.childOptions())),this.emitChange("powerLevelObservable")};this.track(e.subscribe(()=>{const r=t();s!==r&&(i(r),s=r)})),i(s)}async _clearUnreadAfterDelay(){if(!(this._room.isArchived||this._clearUnreadTimout)){this._clearUnreadTimout=this.clock.createTimeout(2e3);try{await this._clearUnreadTimout.elapsed(),await this._room.clearUnread(),this._clearUnreadTimout=null}catch(e){if(e.name!=="AbortError")throw e}}}focus(){this._clearUnreadAfterDelay()}dispose(){super.dispose(),this._room.off("change",this._onRoomChange),this._room.isArchived&&this._room.release(),this._clearUnreadTimout&&(this._clearUnreadTimout.abort(),this._clearUnreadTimout=null)}_onRoomChange(){this._composerVM.emitChange(),this.emitChange()}get kind(){return"room"}get closeUrl(){return this._closeUrl}get name(){return this._room.name||this.i18n`Empty Room`}get id(){return this._room.id}get timelineViewModel(){return this._timelineVM}get isEncrypted(){return this._room.isEncrypted}get error(){return this._timelineError?`Something went wrong loading the timeline: ${this._timelineError.message}`:this._sendError?`Something went wrong sending your message: ${this._sendError.message}`:""}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._room.avatarColorId)}avatarUrl(e){return De(this._room.avatarUrl,e,this.platform,this._room.mediaRepository)}get avatarTitle(){return this.name}get canLeave(){return this._room.isJoined}leaveRoom(){this._room.leave()}get canForget(){return this._room.isArchived}forgetRoom(){this._room.forget()}get canRejoin(){return this._room.isArchived}rejoinRoom(){this._room.join()}_createTile(e){if(this._tileOptions){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}}async _processCommandJoin(e){var t,s,i,r;try{const o=await this._options.client.session.joinRoom(e);await(await this._options.client.session.observeRoomStatus(o)).waitFor(c=>c===U.Joined),this.navigation.push("room",o)}catch(o){let a;((t=o.statusCode)!=null?t:o.status)===400?a=new Error(`/join : '${e}' was not legal room ID or room alias`):((s=o.statusCode)!=null?s:o.status)===404||((i=o.statusCode)!=null?i:o.status)===502||o.message=="Internal Server Error"?a=new Error(`/join : room '${e}' not found`):((r=o.statusCode)!=null?r:o.status)===403?a=new Error(`/join : you're not invited to join '${e}'`):a=o,this._sendError=a,this._timelineError=null,this.emitChange("error")}}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._sendError=new Error("join syntax: /join <room-id>"),this._timelineError=null,this.emitChange("error");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._sendError=new Error(`no command name "${s}". To send the message instead of executing, please type "/${e}"`),this._timelineError=null,this.emitChange("error"),e=void 0}return{type:t,message:e}}async _sendMessage(e,t){if(!this._room.isArchived&&e){let s={type:"m.text",message:e};e.startsWith("//")?s.message=e.substring(1).trim():e.startsWith("/")&&(s=await this._processCommand(e));try{const i=s.type,r=s.message;i&&r&&(t?await t.reply(i,r):await this._room.sendEvent("m.room.message",{msgtype:i,body:r}))}catch(i){return console.error(`room.sendMessage(): ${i.message}:
${i.stack}`),this._sendError=i,this._timelineError=null,this.emitChange("error"),!1}return!0}return!1}async _pickAndSendFile(){try{const e=await this.platform.openFile();return e?this._sendFile(e):void 0}catch(e){console.error(e)}}async _sendFile(e){const t={body:e.name,msgtype:"m.file"};await this._room.sendEvent("m.room.message",t,{url:this._room.createAttachment(e.blob,e.name)})}async _pickAndSendVideo(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("video/*");if(!e)return;if(!e.blob.mimeType.startsWith("video/"))return this._sendFile(e);let t;try{t=await this.platform.loadVideo(e.blob)}catch(c){throw c instanceof window.MediaError&&c.code===4?new Error(`this browser does not support videos of type ${e==null?void 0:e.blob.mimeType}.`):c}const s={body:e.name,msgtype:"m.video",info:Ru(t)},i={url:this._room.createAttachment(t.blob,e.name)},o=await this.platform.settingsStorage.getInt("sentImageSizeLimit")||Math.min(t.maxDimension,800),a=await t.scale(o);s.info.thumbnail_info=Ht(a),i["info.thumbnail_url"]=this._room.createAttachment(a.blob,e.name),await this._room.sendEvent("m.room.message",s,i)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}async _pickAndSendPicture(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("image/*");if(!e)return;if(!e.blob.mimeType.startsWith("image/"))return this._sendFile(e);let t=await this.platform.loadImage(e.blob);const s=await this.platform.settingsStorage.getInt("sentImageSizeLimit");if(s&&t.maxDimension>s){const o=await t.scale(s);t.dispose(),t=o}const i={body:e.name,msgtype:"m.image",info:Ht(t)},r={url:this._room.createAttachment(t.blob,e.name)};if(t.maxDimension>600){const o=await t.scale(400);i.info.thumbnail_info=Ht(o),r["info.thumbnail_url"]=this._room.createAttachment(o.blob,e.name)}await this._room.sendEvent("m.room.message",i,r)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}get room(){return this._room}get composerViewModel(){return this._composerVM}openDetailsPanel(){let e=this.navigation.path.until("room");e=e.with(this.navigation.segment("right-panel",!0)),e=e.with(this.navigation.segment("details",!0)),this.navigation.applyPath(e)}startReply(e){this._room.isArchived||this._composerVM.setReplyingTo(e)}dismissError(){this._sendError=null,this.emitChange("error")}}function Ru(n){const e=Ht(n);return e.duration=n.duration,e}class Cu extends A{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 Tu extends A{get description(){return this.i18n`You do not have the powerlevel necessary to send messages`}get kind(){return"disabled"}}class Mu extends A{constructor(e){super(e);const{roomIdOrAlias:t,session:s}=e;this._session=s,this.roomIdOrAlias=t,this._error=null,this._busy=!1}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 Au extends A{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.urlCreator.urlUntilSegment("session"),this._invite.on("change",this._onInviteChange),this._inviter=null,this._invite.inviter&&(this._inviter=new xu(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 he(this.name)}get avatarColorNumber(){return de(this._invite.avatarColorId)}avatarUrl(e){return De(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 xu{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 he(this.name)}get avatarColorNumber(){return de(this._member.userId)}avatarUrl(e){return De(this._member.avatarUrl,e,this._platform,this._mediaRepository)}get avatarTitle(){return this.name}}class Nu extends A{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.urlCreator.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 he(this.name)}get avatarColorNumber(){return de(this._roomBeingCreated.avatarColorId)}get avatarTitle(){return this.name}avatarUrl(e){var t;return(t=this._roomBeingCreated.avatarBlobUrl)!=null?t:De(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 Du extends A{constructor(e){super(e),this._eventId=e.eventId,this._unencryptedImageUrl=null,this._decryptedImage=null,this._closeUrl=this.urlCreator.urlUntilSegment("room"),this._eventEntry=null,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 J=xe("Disconnected","Connecting","FirstSync","Sending","Syncing","SyncError");class Vu extends A{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.urlCreator.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!==J.Syncing}get statusLabel(){switch(this._status){case J.Disconnected:{const e=Math.round(this._reconnector.retryIn/1e3);return this.i18n`Disconnected, trying to reconnect in ${e}s…`}case J.Connecting:return this.i18n`Trying to reconnect now…`;case J.FirstSync:return this.i18n`Catching up with your conversations…`;case J.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 J.Connecting:case J.FirstSync:return!0;default:return!1}}_updateStatus(){const e=this._calculateState(this._reconnector.connectionStatus.get(),this._sync.status.get());e!==this._status&&(e===J.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!==$t.Online)switch(e){case $t.Reconnecting:return J.Connecting;case $t.Waiting:return J.Disconnected}else if(t!==L.Syncing)switch(t){case L.InitialSync:case L.CatchupSync:return J.FirstSync;case L.Stopped:return J.SyncError}else return J.Syncing}get isConnectNowShown(){return this._status===J.Disconnected}get isSecretStorageShown(){return this._status===J.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 nn(n){return n.map((e,t)=>{if(!n.slice(0,t).includes(e))return e})}class Lu extends A{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=vi(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=nn(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=nn(e);let t=!1;const s=this._height*this._width;for(let i=0;i<s;i+=1){const r=e[i],o=this._viewModelsObservables[i];if(!o&&r||o&&o.id!==r){if(o&&(this._viewModelsObservables[i]=this.disposeTracked(o)),r){const a=this._createRoomViewModelObservable(r);this._viewModelsObservables[i]=this.track(a),a.subscribe(c=>this._refreshRoomViewModel(c)),a.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)}}const ee=xe("Enabled","SetupKey","SetupPhrase","Pending","NewVersionAvailable"),Lt=xe("Writing","Stopped","Done","Pending");class Ou extends A{constructor(e){super(e),this._session=e.session,this._error=null,this._isBusy=!1,this._dehydratedDeviceId=void 0,this._status=void 0,this._backupOperation=this._session.keyBackup.flatMap(t=>t.operationInProgress),this._progress=this._backupOperation.flatMap(t=>t.progress),this.track(this._backupOperation.subscribe(()=>{this._reevaluateStatus(),this.emitChange("isBackingUp")})),this.track(this._progress.subscribe(()=>this.emitChange("backupPercentage"))),this._reevaluateStatus(),this.track(this._session.keyBackup.subscribe(()=>{this._reevaluateStatus()&&this.emitChange("status")}))}_reevaluateStatus(){if(this._isBusy)return!1;let e;const t=this._session.keyBackup.get();t?e=t.needsNewKey?ee.NewVersionAvailable:ee.Enabled:t===null?e=this.showPhraseSetup()?ee.SetupPhrase:ee.SetupKey:e=ee.Pending;const s=e!==this._status;return this._status=e,s}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;return(e=this._session.keyBackup.get())==null?void 0:e.version}get backupWriteStatus(){const e=this._session.keyBackup.get();if(e){if(e.hasStopped)return Lt.Stopped}else return Lt.Pending;return e.operationInProgress.get()?Lt.Writing:e.hasBackedUpAllKeys?Lt.Done:Lt.Pending}get backupError(){var e,t;return(t=(e=this._session.keyBackup.get())==null?void 0:e.error)==null?void 0:t.message}get status(){return this._status}get error(){var e;return(e=this._error)==null?void 0:e.message}showPhraseSetup(){this._status===ee.SetupKey&&(this._status=ee.SetupPhrase,this.emitChange("status"))}showKeySetup(){this._status===ee.SetupPhrase&&(this._status=ee.SetupKey,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))}catch(i){console.error(i),this._error=i,this.emitChange("error")}finally{this._isBusy=!1,this._reevaluateStatus(),this.emitChange("")}}enterSecurityPhrase(e,t){this._enterCredentials(Qt.Passphrase,e,t)}enterSecurityKey(e,t){this._enterCredentials(Qt.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._reevaluateStatus(),this.emitChange("")}}get isBackingUp(){return!!this._backupOperation.get()}get backupPercentage(){const e=this._progress.get();return e?Math.round(e.finished/e.total*100):0}get backupInProgressLabel(){const e=this._progress.get();return e?this.i18n`${e.finished} of ${e.total}`:this.i18n``}cancelBackup(){var e;(e=this._backupOperation.get())==null||e.abort()}startBackup(){var e;(e=this._session.keyBackup.get())==null||e.flush()}}async function Pu(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 a;try{a=await o.response()}catch(h){throw new Error(`Could not submit logs to ${t}, got error ${h.message}`)}const{status:c,body:l}=a;if(c<200||c>=300)throw new Error(`Could not submit logs to ${t}, got status code ${c} with body ${l}`)}class Uu{constructor(){this.supported=null,this.enabled=!1,this.updating=!1,this.enabledOnServer=null,this.serverError=null}}function Fu(n){const t=Math.ceil(n.length/4);let s="";for(let i=0;i<t;i+=1)s+=(s.length?" ":"")+n.slice(i*4,(i+1)*4);return s}class Bu extends A{constructor(e){super(e),this._updateService=e.updateService;const{client:t}=e;this._client=t,this._keyBackupViewModel=this.track(new Ou(this.childOptions({session:this._session}))),this._closeUrl=this.urlCreator.urlUntilSegment("session"),this._estimate=null,this.sentImageSizeLimit=null,this.minSentImageSizeLimit=400,this.maxSentImageSizeLimit=4e3,this.pushNotifications=new Uu,this._activeTheme=void 0,this._logsFeedbackMessage=void 0}get _session(){return this._client.session}async logout(){this.navigation.push("logout",this._client.sessionId)}setSentImageSizeLimit(e){e>this.maxSentImageSizeLimit||e<this.minSentImageSizeLimit?(this.sentImageSizeLimit=null,this.platform.settingsStorage.remove("sentImageSizeLimit")):(this.sentImageSizeLimit=Math.round(e),this.platform.settingsStorage.setInt("sentImageSizeLimit",e)),this.emitChange("sentImageSizeLimit")}async load(){this._estimate=await this.platform.estimateStorageUsage(),this.sentImageSizeLimit=await this.platform.settingsStorage.getInt("sentImageSizeLimit"),this.pushNotifications.supported=await this.platform.notificationService.supportsPush(),this.pushNotifications.enabled=await this._session.arePushNotificationsEnabled(),this._activeTheme=await this.platform.themeLoader.getActiveTheme(),this.emitChange("")}get closeUrl(){return this._closeUrl}get fingerprintKey(){const e=this._session.fingerprintKey;return e?Fu(e):null}get deviceId(){return this._session.deviceId}get userId(){return this._session.userId}get version(){const{updateService:e}=this.platform;return e?`${e.version} (${e.buildHash})`:this.i18n`development version`}checkForUpdate(){var e;(e=this.platform.updateService)==null||e.checkForUpdate()}get showUpdateButton(){return!!this.platform.updateService}get keyBackupViewModel(){return this._keyBackupViewModel}get storageQuota(){var e;return this._formatBytes((e=this._estimate)==null?void 0:e.quota)}get storageUsage(){var e;return this._formatBytes((e=this._estimate)==null?void 0:e.usage)}get themeMapping(){return this.platform.themeLoader.themeMapping}get activeTheme(){return this._activeTheme}_formatBytes(e){return typeof e=="number"?Math.round(e/(1024*1024)).toFixed(1)+" MB":this.i18n`unknown`}async exportLogs(){const e=await this.logger.export();this.platform.saveFileAs(e.asBlob(),`hydrogen-logs-${this.platform.clock.now()}.json`)}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(){const{bugReportEndpointUrl:e}=this.platform.config;if(e){this._logsFeedbackMessage=this.i18n`Sending logs…`,this.emitChange();try{const t=await this.logger.export();await Pu({app:"hydrogen",userAgent:this.platform.description,version:"0.3.1",text:`Submit logs from settings for user ${this._session.userId} on device ${this._session.deviceId}`},t.asBlob(),e,this.platform.request),this._logsFeedbackMessage=this.i18n`Logs sent succesfully!`,this.emitChange()}catch(t){this._logsFeedbackMessage=t.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 Ku extends A{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}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}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?re.Public:re.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?$u(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=Ht(t),this._avatarFileName=e.name,this.emitChange("hasAvatar")}}function $u(n){n.startsWith("#")&&(n=n.substr(1));const e=n.indexOf(":");return e!==-1&&(n=n.substr(0,e)),n}class on extends we{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&U.Replaced)if(e&U.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^U.Replaced));else return e&U.BeingCreated?this._sessionViewModel._createRoomBeingCreatedViewModel(this.id):e&U.Invited?this._sessionViewModel._createInviteViewModel(this.id):e&U.Joined?this._sessionViewModel._createRoomViewModelInstance(this.id):e&U.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 ju extends A{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 he(this.name)}get avatarColorNumber(){return de(this._room.avatarColorId)}avatarUrl(e){return De(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 qu extends A{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.urlCreator.openRoomActionUrl(e)}/member/${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 he(this.name)}get avatarColorNumber(){return de(this.userId)}avatarUrl(e){return De(this._member.avatarUrl,e,this.platform,this._mediaRepository)}get avatarTitle(){return this.name}}function Wu(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),a=n.getUserLevel(r.userId);if(o!==a)return a-o;const c=t(i.name),l=t(r.name);return e.compare(c,l)}}class Hu{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 zu extends A{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(Wu(i)),this.nameDisambiguator=new Hu,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,a=new qu(this.childOptions({member:i,emitChange:r,mediaRepository:o}));return this.nameDisambiguator.disambiguate(a),a},s=(i,r,o)=>{i.updateFrom(o),this.nameDisambiguator.disambiguate(i)};return e.mapValues(t,s)}}class Gu extends A{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()))}get name(){return this._member.name}get userId(){return this._member.userId}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")}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this.userId)}avatarUrl(e){return De(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:re.DirectMessage,invites:[this.userId]})).id),this.navigation.push("room",t)}}class Ju extends A{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",ju,()=>({room:this._room})),this._hookUpdaterToSegment("members",zu,()=>this._getMemberListArguments()),this._hookUpdaterToSegment("member",Gu,()=>this._getMemberDetailsArguments(),()=>{const e=`${this.urlCreator.urlUntilSegment("room")}/members`;this.urlCreator.pushUrl(e)})}_hookUpdaterToSegment(e,t,s,i){const r=this.navigation.observe(e),o=this._setupUpdater(e,t,s,i);this.track(r.subscribe(o))}_setupUpdater(e,t,s,i){const r=async(o=!1)=>{var c;if(o||(this._activeViewModel=this.disposeTracked(this._activeViewModel)),!!((c=this.navigation.path.get(e))!=null&&c.value)){const l=await s();if(!l&&i){i();return}this._activeViewModel=this.track(new t(this.childOptions(l)))}this.emitChange("activeViewModel")};return 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 Qu extends A{constructor(e){super(e);const{client:t}=e;this._client=this.track(t),this._sessionStatusViewModel=this.track(new Vu(this.childOptions({sync:t.sync,reconnector:t.reconnector,session:t.session}))),this._leftPanelViewModel=this.track(new Bd(this.childOptions({session:this._client.session}))),this._settingsViewModel=null,this._roomViewModelObservable=null,this._gridViewModel=null,this._createRoomViewModel=null,this._setupNavigation()}_setupNavigation(){const e=this.navigation.observe("rooms");this.track(e.subscribe(a=>{this._updateGrid(a)})),e.get()&&this._updateGrid(e.get());const t=this.navigation.observe("room");this.track(t.subscribe(a=>{this._gridViewModel||this._updateRoom(a),this._updateRightPanel()})),this._gridViewModel||this._updateRoom(t.get());const s=this.navigation.observe("settings");this.track(s.subscribe(a=>{this._updateSettings(a)})),this._updateSettings(s.get());const i=this.navigation.observe("create-room");this.track(i.subscribe(a=>{this._updateCreateRoom(a)})),this._updateCreateRoom(i.get());const r=this.navigation.observe("lightbox");this.track(r.subscribe(a=>{this._updateLightbox(a)})),this._updateLightbox(r.get());const o=this.navigation.observe("right-panel");this.track(o.subscribe(()=>this._updateRightPanel())),this._updateRightPanel()}get id(){return this._client.sessionId}start(){this._sessionStatusViewModel.start()}get activeMiddleViewModel(){var e;return((e=this._roomViewModelObservable)==null?void 0:e.get())||this._gridViewModel||this._settingsViewModel||this._createRoomViewModel}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}_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 Lu(this.childOptions({width:3,height:2,createRoomViewModelObservable:r=>new on(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 rn(this.childOptions({room:t}));return s.load(),s}return null}_createUnknownRoomViewModel(e){return new Mu(this.childOptions({roomIdOrAlias:e,session:this._client.session}))}async _createArchivedRoomViewModel(e){const t=await this._client.session.loadArchivedRoom(e);if(t){const s=new rn(this.childOptions({room:t}));return s.load(),s}return null}_createInviteViewModel(e){const t=this._client.session.invites.get(e);return t?new Au(this.childOptions({invite:t,mediaRepository:this._client.session.mediaRepository})):null}_createRoomBeingCreatedViewModel(e){const t=this._client.session.roomsBeingCreated.get(e);return t?new Nu(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 on(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 Bu(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 Ku(this.childOptions({session:this._client.session})))),this.emitChange("activeMiddleViewModel")}_updateLightbox(e){if(this._lightboxViewModel&&(this._lightboxViewModel=this.disposeTracked(this._lightboxViewModel)),e){const t=this._roomFromNavigation();this._lightboxViewModel=this.track(new Du(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 Ju(this.childOptions({room:s,session:this._client.session})))}this.emitChange("rightPanelViewModel")}notifyRoomReplaced(e,t){this.navigation.push("room",t)}}class Yu extends A{constructor(e){super(e),this._accountSetup=e.accountSetup,this._dehydratedDevice=void 0,this._decryptDehydratedDeviceViewModel=void 0,this._accountSetup.encryptedDehydratedDevice&&(this._decryptDehydratedDeviceViewModel=new Xu(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 Xu extends A{constructor(e,t){super(e.options),this._accountSetupViewModel=e,this._isBusy=!1,this._status=ee.SetupKey,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===ee.SetupKey&&(this._status=ee.SetupPhrase,this.emitChange("status"))}showKeySetup(){this._status===ee.SetupPhrase&&(this._status=ee.SetupKey,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(Qt.Passphrase,e)}enterSecurityKey(e){this._enterCredentials(Qt.RecoveryKey,e)}disable(){}}class Eo extends A{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.urlCreator.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===M.AccountSetup?this._accountSetupViewModel=new Yu(this.childOptions({accountSetup:this._client.accountSetup})):this._accountSetupViewModel=void 0,this.emitChange("loadLabel"),s===M.FirstSync&&this._client.sync.status.get()===L.CatchupSync||s===M.LoginFailed||s===M.Error||s===M.Ready));try{await this._waitHandle.promise}catch{return}const e=this._client.loadStatus.get(),t=this._client.loadError;if(e===M.FirstSync||e===M.Ready){const s=this._client;this._client=null,this._ready(s)}t&&console.error("session load error",t)}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()===M.AccountSetup?!1:this._loading}get loadLabel(){const e=this._client,t=this._getError();if(t||e&&e.loadStatus.get()===M.Error)return`Something went wrong: ${t&&t.message}.`;if(e)switch(e.loadStatus.get()){case M.QueryAccount:return"Querying account encryption setup\u2026";case M.AccountSetup:return"";case M.SessionSetup:return"Setting up your encryption keys\u2026";case M.Loading:return"Loading your conversations\u2026";case M.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.logout(),this.navigation.push("session",!0)}get accountSetupViewModel(){return this._accountSetupViewModel}}class Zu extends A{constructor(e){super(e);const{loginOptions:t,attemptLogin:s}=e;this._loginOptions=t,this._attemptLogin=s,this._isBusy=!1,this._errorMessage=""}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 Ce.Credentials:i=this.i18n`Your username and/or password don't seem to be correct.`;break;case Ce.Connection:i=this.i18n`Can't connect to ${this._loginOptions.homeserver}.`;break;case Ce.Unknown:i=this.i18n`Something went wrong while checking your login and password.`;break}i&&this._showError(i)}}class em extends A{constructor(e){super(e),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.urlCreator.createSSOCallbackURL());this.platform.openUrl(e)}}class tm extends A{constructor(e){super(e);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 Ce.Credentials:i=this.i18n`Your login token is invalid.`;break;case Ce.Connection:i=this.i18n`Can't connect to ${e}.`;break;case Ce.Unknown:i=this.i18n`Something went wrong while checking your login token.`;break}i&&this._showError(i)}}class sm extends A{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 ji(this.platform),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 tm(this.childOptions({client:this._client,attemptLogin:e=>this.attemptLogin(e),loginToken:this._loginToken}))),this.emitChange("completeSSOLoginViewModel")):this.queryHomeserver()}_showPasswordLogin(){this._passwordLoginViewModel=this.track(new Zu(this.childOptions({loginOptions:this._loginOptions,attemptLogin:e=>this.attemptLogin(e)}))),this.emitChange("passwordLoginViewModel")}_showSSOLogin(){this._startSSOLoginViewModel=this.track(new em(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!==M.Login).promise,this._setBusy(!1),t.get()===M.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 Eo(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 im extends A{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.urlCreator.urlForSegment("session",!0)}async logout(){this._busy=!0,this._showConfirm=!1,this.emitChange("busy");try{await new ji(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 rm extends A{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.urlCreator.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 de(this._sessionInfo.userId)}get avatarInitials(){return he(this._sessionInfo.userId)}}class nm extends A{constructor(e){super(e),this._sessions=new xi((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 rm(this.childOptions({sessionInfo:t}),this)))}get loadViewModel(){return this._loadViewModel}get sessions(){return this._sessions}get cancelUrl(){return this.urlCreator.urlForSegment("login")}}class om extends A{constructor(e){super(e),this._error=null,this._sessionPickerViewModel=null,this._sessionLoadViewModel=null,this._loginViewModel=null,this._logoutViewModel=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._applyNavigation(!0)}async _applyNavigation(e){var o,a,c;const t=this.navigation.path.get("login"),s=(o=this.navigation.path.get("logout"))==null?void 0:o.value,i=(a=this.navigation.path.get("session"))==null?void 0:a.value,r=(c=this.navigation.path.get("sso"))==null?void 0:c.value;if(t)this.activeSection!=="login"&&this._showLogin();else if(s)this.activeSection!=="logout"&&this._showLogout(s);else if(i===!0)this.activeSection!=="picker"&&this._showPicker();else if(i){if(!this._sessionViewModel||this._sessionViewModel.id!==i)if(this._pendingClient&&this._pendingClient.sessionId===i){const l=this._pendingClient;this._pendingClient=null,this._showSession(l)}else this._pendingClient&&(this._pendingClient.dispose(),this._pendingClient=null),this._showSessionLoader(i)}else if(r)this.urlCreator.normalizeUrl(),this.activeSection!=="login"&&this._showLogin(r);else try{if(!(e&&this.urlCreator.tryRestoreLastUrl())){const l=await this.platform.sessionInfoStorage.getAll();l.length===0?this.navigation.push("login"):l.length===1?this.navigation.push("session",l[0].id):this.navigation.push("session")}}catch(l){this._setSection(()=>this._error=l)}}async _showPicker(){this._setSection(()=>{this._sessionPickerViewModel=new nm(this.childOptions())});try{await this._sessionPickerViewModel.load()}catch(e){this._setSection(()=>this._error=e)}}_showLogin(e){this._setSection(()=>{this._loginViewModel=new sm(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 im(this.childOptions({sessionId:e}))})}_showSession(e){this._setSection(()=>{this._sessionViewModel=new Qu(this.childOptions({client:e})),this._sessionViewModel.start()})}_showSessionLoader(e){const t=new ji(this.platform);t.startWithExistingSession(e),this._setSection(()=>{this._sessionLoadViewModel=new Eo(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._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._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._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 sessionPickerViewModel(){return this._sessionPickerViewModel}get sessionLoadViewModel(){return this._sessionLoadViewModel}}async function am(n){try{await n.init();const e=Vd();n.setNavigation(e);const t=Ld({navigation:e,history:n.history});t.attach();const s=new om({platform:n,urlCreator:t,navigation:e});await s.load(),n.createAndMountRootView(s)}catch(e){console.error(`${e.message}:
${e.stack}`)}}function cm(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 qe(`Request timed out after ${e}ms`,!0):o})}function ko(n,e=Math.random){return n.includes("?")?n=n+"&":n=n+"?",n+`_cacheBuster=${Math.ceil(e()*Number.MAX_SAFE_INTEGER)}`}function Ro(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 lm{constructor(e,t){this._promise=e,this._xhr=t}abort(){this._xhr.abort()}response(){return this._promise}}function hm(n,{method:e,headers:t,timeout:s,format:i,uploadProgress:r}){const o=new XMLHttpRequest;if(r&&o.upload.addEventListener("progress",a=>r(a.loaded)),o.open(e,n),i==="buffer"&&(o.responseType="arraybuffer"),t)for(const[a,c]of t.entries())try{o.setRequestHeader(a,c)}catch(l){console.info(`Could not set ${a} header: ${l.message}`)}return s&&(o.timeout=s),o}function dm(n,e,t){return new Promise((s,i)=>{n.addEventListener("load",()=>s(n)),n.addEventListener("abort",()=>i(new ye)),n.addEventListener("error",()=>i(new qe(`Error ${e} ${t}`))),n.addEventListener("timeout",()=>i(new qe(`Timeout ${e} ${t}`,!0)))})}function Co(n,e){let{cache:t,format:s,body:i,method:r}=e;t||(n=ko(n));const o=hm(n,e),a=dm(o,r,n).then(c=>{const{status:l}=c;let h=null;return s==="buffer"?h=c.response:c.getResponseHeader("Content-Type")==="application/json"&&(h=JSON.parse(c.responseText)),{status:l,body:h}});return i!=null&&i.nativeBlob&&(i=i.nativeBlob),i instanceof Map&&(i=Ro(i)),o.send(i||null),new lm(a,o)}class an{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 um(n,e){return function(s,i){if(e!=null&&e.haltRequests)return new an(new Promise(()=>{}),{});if(i!=null&&i.uploadProgress)return Co(s,i);let{method:r,headers:o,body:a,timeout:c,format:l,cache:h=!1}=i;const d=typeof AbortController=="function"?new AbortController:null;a!=null&&a.nativeBlob&&(a=a.nativeBlob),a instanceof Map&&(a=Ro(a));let u={method:r,body:a};if(d&&(u=Object.assign(u,{signal:d.signal})),h||(s=ko(s)),u=Object.assign(u,{mode:"cors",credentials:"omit",referrer:"no-referrer",cache:"default"}),o){const f=new Headers;for(const[b,S]of o.entries())f.append(b,S);u.headers=f}const p=fetch(s,u).then(async f=>{const{status:b}=f;let S;try{l==="json"?S=await f.json():l==="buffer"?S=await f.arrayBuffer():l==="text"&&(S=await f.text())}catch(k){if(!(k.name==="SyntaxError"&&b>=400))throw k}return{status:b,body:S}},f=>{throw f.name==="AbortError"?new ye:f instanceof TypeError?new qe(`${r} ${s}: ${f.message}`):f}),_=new an(p,d);return c&&(_.promise=cm(n,c,_,_.promise)),_}}class mm{constructor(e){this._name=e}getAll(){const e=localStorage.getItem(this._name);if(e){const t=JSON.parse(e);if(Array.isArray(t))return Promise.resolve(t)}return Promise.resolve([])}async updateLastUsed(e,t){const s=await this.getAll();if(s){const 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 pm{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 _m{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 nt={};(function(){for(var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Uint8Array(256),t=0;t<n.length;t++)e[n.charCodeAt(t)]=t;nt.encode=function(s){var i=new Uint8Array(s),r,o=i.length,a="";for(r=0;r<o;r+=3)a+=n[i[r]>>2],a+=n[(i[r]&3)<<4|i[r+1]>>4],a+=n[(i[r+1]&15)<<2|i[r+2]>>6],a+=n[i[r+2]&63];return o%3===2?a=a.substring(0,a.length-1)+"=":o%3===1&&(a=a.substring(0,a.length-2)+"=="),a},nt.decode=function(s){var i=s.length*.75,r=s.length,o,a=0,c,l,h,d;s[s.length-1]==="="&&(i--,s[s.length-2]==="="&&i--);var u=new ArrayBuffer(i),p=new Uint8Array(u);for(o=0;o<r;o+=4)c=e[s.charCodeAt(o)],l=e[s.charCodeAt(o+1)],h=e[s.charCodeAt(o+2)],d=e[s.charCodeAt(o+3)],p[a++]=c<<2|l>>4,p[a++]=(l&15)<<4|h>>2,p[a++]=(h&3)<<6|d&63;return u}})();class fm{encodeUnpadded(e){const t=nt.encode(e),s=t.indexOf("=");return s!==-1?t.substr(0,s):t}encode(e){return nt.encode(e)}decode(e){return nt.decode(e)}}var To={isBuffer:function(n){return n instanceof Uint8Array},from:function(n){return n},allocUnsafe:function(n){return To.alloc(n)},alloc:function(n){return new Uint8Array(n)}},gm=Object.freeze(Object.defineProperty({__proto__:null,Buffer:To},Symbol.toStringTag,{value:"Module"})),ym=Na(gm),vs=ym.Buffer;function wm(n){if(n.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t<e.length;t++)e[t]=255;for(var s=0;s<n.length;s++){var i=n.charAt(s),r=i.charCodeAt(0);if(e[r]!==255)throw new TypeError(i+" is ambiguous");e[r]=s}var o=n.length,a=n.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function h(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=vs.from(p)),!vs.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var _=0,f=0,b=0,S=p.length;b!==S&&p[b]===0;)b++,_++;for(var k=(S-b)*l+1>>>0,R=new Uint8Array(k);b!==S;){for(var w=p[b],I=0,x=k-1;(w!==0||I<f)&&x!==-1;x--,I++)w+=256*R[x]>>>0,R[x]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");f=I,b++}for(var D=k-f;D!==k&&R[D]===0;)D++;for(var Le=a.repeat(_);D<k;++D)Le+=n.charAt(R[D]);return Le}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return vs.alloc(0);var _=0;if(p[_]!==" "){for(var f=0,b=0;p[_]===a;)f++,_++;for(var S=(p.length-_)*c+1>>>0,k=new Uint8Array(S);p[_];){var R=e[p.charCodeAt(_)];if(R===255)return;for(var w=0,I=S-1;(R!==0||w<b)&&I!==-1;I--,w++)R+=o*k[I]>>>0,k[I]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");b=w,_++}if(p[_]!==" "){for(var x=S-b;x!==S&&k[x]===0;)x++;var D=vs.allocUnsafe(f+(S-x));D.fill(0,0,f);for(var Le=f;x!==S;)D[Le++]=k[x++];return D}}}function u(p){var _=d(p);if(_)return _;throw new Error("Non-base"+o+" character")}return{encode:h,decodeUnsafe:d,decode:u}}var vm=wm,bm=vm,Sm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",cn=bm(Sm);class Im{encode(e){return cn.encode(e)}decode(e){return cn.decode(e)}}class Em{constructor(){this.utf8=new _m,this.base64=new fm,this.base58=new Im}}class km{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 a=await this._workerPool.send({type:"olm_create_outbound",accountPickle:r,theirIdentityKey:s,theirOneTimeKey:i,randomValues:o}).response();t.unpickle("",a)}dispose(){this._workerPool.dispose()}}class Rm extends go{constructor(e){super(e);const{name:t,flushInterval:s=60*1e3,limit:i=3e3}=e;this._name=t,this._limit=i,this._queuedItems=this._loadQueuedItems(),window.addEventListener("pagehide",this,!1),this._flushInterval=this._platform.clock.createInterval(()=>this._tryFlush(),s)}dispose(){window.removeEventListener("pagehide",this,!1),this._flushInterval.dispose()}handleEvent(e){e.type==="pagehide"&&this._finishAllAndFlush()}async _tryFlush(){const e=await this._openDB();try{const t=e.transaction(["logs"],"readwrite"),s=t.objectStore("logs"),i=this._queuedItems.length;for(const o of this._queuedItems)s.add(o);const r=await X(s.count());if(r>this._limit){let o=r-this._limit+Math.round(.1*this._limit);await K(s.openCursor(),(a,c,l)=>(l.delete(),o-=1,{done:o===0}))}await Jt(t),this._queuedItems.splice(0,i)}catch(t){console.error("Could not flush logs",t)}finally{try{e.close()}catch{}}}_finishAllAndFlush(){this._finishOpenItems(),this.log({l:"pagehide, closing logs",t:"navigation"}),this._persistQueuedItems(this._queuedItems)}_loadQueuedItems(){const e=`${this._name}_queuedItems`;try{const t=window.localStorage.getItem(e);if(t)return window.localStorage.removeItem(e),JSON.parse(t)}catch(t){console.error("Could not load queued log items",t)}return[]}_openDB(){return Mi(this._name,e=>e.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),1)}_persistItem(e,t,s){const i=e.serialize(t,void 0,s);if(i){const r=this._serializedTransformer(i);this._queuedItems.push({json:JSON.stringify(r)})}}_persistQueuedItems(e){try{window.localStorage.setItem(`${this._name}_queuedItems`,JSON.stringify(e))}catch(t){console.error("Could not persist queued log items in localStorage, they will likely be lost",t)}}async export(){const e=await this._openDB();try{const s=e.transaction(["logs"],"readonly").objectStore("logs"),r=(await dc(s.openCursor(),()=>!1)).concat(this._queuedItems);return new Cm(r,this,this._platform)}finally{try{e.close()}catch{}}}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 Jt(s)}finally{try{t.close()}catch{}}}}class Cm{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(){var r;const e={formatVersion:1,appVersion:(r=this._platform.updateService)==null?void 0:r.version,items:this._items.map(o=>JSON.parse(o.json))},t=JSON.stringify(e),s=this._platform.encoding.utf8.encode(t);return this._platform.createBlob(s,"application/json")}}function Mo(n){return typeof n!="object"||"nodeType"in n||Array.isArray(n)}function It(n,e){return Object.entries(n).reduce((t,[s,i])=>(typeof i=="function"&&(i=i(e)),i?t+(t.length?" ":"")+s:t),"")}function vt(n,e,t){e==="className"&&(e="class"),t===!1?n.removeAttribute(e):(t===!0&&(t=e),n.setAttribute(e,t))}function Tm(n,e,t){return Ao(Hi,n,e,t)}function Ao(n,e,t,s){t&&Mo(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"?It(o,void 0):!1),vt(i,r,o);if(s){Array.isArray(s)||(s=[s]);for(let r of s)typeof r=="string"&&(r=Te(r)),i.appendChild(r)}return i}function Te(n){return document.createTextNode(n)}const Hi="http://www.w3.org/1999/xhtml",Mm="http://www.w3.org/2000/svg",xo={[Hi]:["br","a","ol","ul","li","div","h1","h2","h3","h4","h5","h6","p","strong","em","span","img","section","main","article","aside","del","blockquote","table","thead","tbody","tr","th","td","hr","pre","code","button","time","input","textarea","select","option","label","form","progress","output","video"],[Mm]:["svg","g","path","circle","ellipse","rect","use"]},T={};for(const[n,e]of Object.entries(xo))for(const t of e)T[t]=function(s,i){return Ao(n,t,s,i)};function Xt(n,e){let t;try{t=n.mount(e)}catch(s){t=Am(s)}return t}function Am(n){const e=new Error().stack;let t=null;return e&&(t=e.split(`
`)[1]),T.div([T.h2("Something went wrong\u2026"),T.h3(n.message),T.p(`This occurred while running ${t}.`),T.pre(n.stack)])}function ln(n,e,t){if(e===n.childElementCount)n.appendChild(t);else{const i=n.children[e];n.insertBefore(t,i)}}function xm(n){n.innerHTML=""}function Nm(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 is{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=Tm(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(Xt(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),ln(this._root,e,Xt(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(),ln(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 No{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 Dm(n){for(const e of Object.values(n))if(typeof e=="function")return!0;return!1}class E extends No{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 Do(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 Do{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,vt(e,t,o))};this._addBinding(r),r()}_addClassNamesBinding(e,t){this._addAttributeBinding(e,"className",s=>It(t,s))}_addTextBinding(e){const t=e(this._value)+"",s=Te(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;Dm(i)?this._addClassNamesBinding(e,i):vt(e,s,It(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):vt(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=Te(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 a=t(i);i.parentNode&&i.parentNode.replaceChild(a,i),i=a}};return this._addBinding(r),i}el(e,t,s){return this.elNS(Hi,e,t,s)}elNS(e,t,s,i){let r;s&&(Mo(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),Xt(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(a=>a.root()===s);if(o!==-1){const[a]=r.splice(o,1);a.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 Ns(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 Ns(s,t))}mapSideEffect(e,t){let s=e(this._value);const i=()=>{const r=e(this._value);s!==r&&(t(r,s),s=r)};this._addBinding(i),t(s,void 0)}}for(const[n,e]of Object.entries(xo))for(const t of e)Do.prototype[t]=function(s,i){return this.elNS(n,t,s,i)};class Ns extends E{constructor(e,t){super(e),this._render=t}render(e,t){return this._render(e,t)}}function it(n,e,t=void 0){const s=!!n.avatarUrl(e);let i=It({avatar:!0,[`size-${e}`]:!0,[`usercolor${n.avatarColorNumber}`]:!s});t&&(i+=` ${t}`);const r=s?Vo(n,e):Te(n.avatarLetter),o=T.div({className:i,"data-testid":"avatar"},[r]);return s&&(vt(o,"data-avatar-letter",n.avatarLetter),vt(o,"data-avatar-color",n.avatarColorNumber)),o}function Vo(n,e){const t=e.toString();return T.img({src:n.avatarUrl(e),width:t,height:t,title:n.avatarTitle})}function Vm(n){const e=n.target,t=e.parentElement;return e.tagName==="IMG"&&t.classList.contains("avatar")}function hn(n){if(!Vm(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 ht extends No{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=it(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(Vo(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 Ot;function Ve(n,e=void 0){Ot===void 0&&(Ot=document.querySelector(".hydrogen"));const t=Object.assign({spinner:!0},e);return Ot!=null&&Ot.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 Lm 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 ht(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?Ve(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 Om 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 Pm extends E{render(e,t){const s=o=>o.gridEnabled?o.i18n`Show single room`:o.i18n`Enable grid layout`,i=e.view(new is({className:"RoomList",list:t.tileViewModels},o=>new Lm(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 Om({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.a({className:"button-utility create",href:t.createRoomUrl,"aria-label":t.i18n`Create room`,title:t.i18n`Create room`})]);return e.div({className:"LeftPanel"},[r,i])}}class zi{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=T.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=Um(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<i.top||e.right<i.left)return!1;if(i.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 Um(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 Y extends E{static option(e,t){return new Fm(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 Fm{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))}}function dn(n){return n.offsetTop+n.clientHeight}function un(n,e,t=n.children.length-1){for(var s=t;s>=0;s--)if(n.children[s].offsetTop<e)return s;return 0}class Bm extends E{constructor(e,t){super(e),this.viewClassForTile=t,this.anchoredBottom=0,this.stickToBottom=!0}render(e,t){requestAnimationFrame(()=>{this.restoreScrollPosition()}),this.tilesView=new Km(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=dn(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 c=i+r,l=un(t,c);this.anchoredNode=t.childNodes[l],this.anchoredBottom=dn(this.anchoredNode),o=l}let a=un(t,i,o);this.updateVisibleRange(a,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 Km extends is{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 $m extends E{render(e,t){return e.div({className:"TimelineLoadingView"},[Ve(e),e.div(t.isEncrypted?t.i18n`Loading encrypted messages…`:t.i18n`Loading messages…`)])}}class jm 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 a=r&&this._viewClassForTile(r);return a?o.div({className:"MessageComposer_replyPreview"},[o.span({className:"replying"},"Replying"),o.button({className:"cancel",onClick:()=>this._clearReplyingTo()},"Close"),o.view(new a(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 zi(new Y([Y.option(t.i18n`Send video`,()=>t.sendVideo()).setIcon("video"),Y.option(t.i18n`Send picture`,()=>t.sendPicture()).setIcon("picture"),Y.option(t.i18n`Send file`,()=>t.sendFile()).setIcon("file")])),this._attachmentPopup.trackInTemplateView(this),this._attachmentPopup.showRelativeTo(e.target,12)}}_adjustHeight(){this._rafResizeHandle||(this._rafResizeHandle=window.requestAnimationFrame(()=>{const e=this._input.scrollHeight;this._input.style.height=`${e}px`,this._rafResizeHandle=void 0}))}_clearHeight(){this._input.style.removeProperty("height")}}class qm extends E{render(e){return e.div({className:"DisabledComposerView"},e.h3(t=>t.description))}}class Lo 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 ht(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.div({className:"RoomView_error"},[e.if(s=>s.error,s=>s.div([s.p({},i=>i.error),s.button({className:"RoomView_error_closerButton",onClick:i=>t.dismissError(i)})]))]),e.mapView(s=>s.timelineViewModel,s=>s?new Bm(s,this._viewClassForTile):new $m(t)),e.mapView(s=>s.composerViewModel,s=>{switch(s==null?void 0:s.kind){case"composer":return new jm(t.composerViewModel,this._viewClassForTile);case"disabled":return new qm(t.composerViewModel)}})])])}_toggleOptionsMenu(e){if(this._optionsPopup&&this._optionsPopup.isOpen)this._optionsPopup.close();else{const t=this.value,s=[];if(s.push(Y.option(t.i18n`Room details`,()=>t.openDetailsPanel())),t.canLeave&&s.push(Y.option(t.i18n`Leave room`,()=>this._confirmToLeaveRoom()).setDestructive()),t.canForget&&s.push(Y.option(t.i18n`Forget room`,()=>t.forgetRoom()).setDestructive()),t.canRejoin&&s.push(Y.option(t.i18n`Rejoin room`,()=>t.rejoinRoom())),!s.length)return;this._optionsPopup=new zi(new Y(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 Wm extends E{render(e,t){return e.main({className:"UnknownRoomView middle"},e.div([e.h2([t.i18n`You are currently not in ${t.roomIdOrAlias}.`,e.br(),t.i18n`Want to join it?`]),e.button({className:"button-action primary",onClick:()=>t.join(),disabled:s=>s.busy},t.i18n`Join room`),e.if(s=>s.error,s=>s.p({className:"error"},t.error))]))}}class Et{constructor(e,t=void 0){typeof e=="function"&&!t&&(t=e,e=null),this._root=t?t(T,e):this.render(T,e)}mount(){return this._root}root(){return this._root}unmount(){}update(){}}class Oo extends Et{constructor(e="Loading"){super(e,(t,s)=>t.div({className:"LoadingView"},[Ve(t),s]))}}class Po 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 ht(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 Hm(t):new Oo(t.i18n`Setting up the room…`))])])}}class Hm 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 Uo extends E{render(e,t){var r;let s=[];t.isDirectMessage&&s.push(it(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=[it(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"},[it(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`}),it(t,32),e.div({className:"room-description"},[e.h2(o=>o.name)])]),e.if(o=>o.error,o=>o.div({className:"RoomView_error"},a=>a.error)),e.div({className:"InviteView_body"},[e.div({className:"InviteView_invite"},[...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 zm 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":c=>c.name,title:c=>c.name,className:{picture:!0,hidden:c=>!c.imageUrl},style:c=>`background-image: url('${c.imageUrl}'); max-width: ${c.imageWidth}px; max-height: ${c.imageHeight}px;`}),r=e.div({className:{loading:!0,hidden:c=>!!c.imageUrl}},[Ve(e),e.div(t.i18n`Loading image…`)]),o=e.div({className:"details"},[e.strong(c=>c.name),e.br(),"uploaded by ",e.strong(c=>c.sender),c=>` at ${c.time} on ${c.date}.`]),a=e.div({role:"dialog",className:"lightbox",onClick:c=>this.clickToClose(c),onKeydown:c=>this.closeOnEscKey(c)},[i,r,o,s]);return Gm(e,a),a}clickToClose(e){e.target===this.root()&&this.value.close()}closeOnEscKey(e){(e.key==="Escape"||e.key==="Esc")&&this.value.close()}}function Gm(n,e){const t=Jm(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 Jm(n){return n.querySelectorAll("a[href], button, textarea, input, select")}class Qm extends E{render(e,t){return e.div({className:{SessionStatusView:!0,hidden:s=>!s.isShown}},[Ve(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 Ym extends E{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const s=[];for(let i=0;i<t.height*t.width;i+=1)s.push(e.div({onClick:()=>t.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 Po(r):r.kind==="invite"?new Uo(r):new Lo(r,this._viewClassForTile):new Et(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 Fo extends E{render(e){return e.div([e.map(t=>t.status,(t,s,i)=>{switch(t){case"Enabled":return Xm(s,i);case"NewVersionAvailable":return Zm(s,i);case"SetupKey":return ep(s,i);case"SetupPhrase":return tp(s,i);case"Pending":return s.p(i.i18n`Waiting to go online…`)}}),e.map(t=>t.backupWriteStatus,(t,s,i)=>{switch(t){case"Writing":{const r=s.progress({min:0,max:100,value:o=>o.backupPercentage});return s.div(["Backup in progress ",r," ",o=>o.backupInProgressLabel])}case"Stopped":{let r;return i.backupError?r=`Backup has stopped because of an error: ${i.backupError}`:r="Backup has stopped",s.p(r," ",s.button({onClick:()=>i.startBackup()},"Backup now"))}case"Done":return s.p("All keys are backed up.");default:return null}})])}}function Xm(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 Zm(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 ep(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.`),Ko(n),Bo(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 tp(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.`),Ko(n),Bo(n,e,e.i18n`Security phrase`,(s,i)=>e.enterSecurityPhrase(s,i)),n.p([e.i18n`You can also `,t,e.i18n`.`])])}function Bo(n,e,t,s){let i;const r=()=>s(o.value,(i==null?void 0:i.checked)||!1),o=n.input({type:"password",disabled:c=>c.isBusy,placeholder:t}),a=[n.p([o,n.button({disabled:c=>c.isBusy,onClick:r},e.decryptAction)])];if(e.offerDehydratedDeviceSetup){i=n.input({type:"checkbox",id:"enable-dehydrated-device"});const c=n.a({href:"https://github.com/uhoreg/matrix-doc/blob/dehydration/proposals/2697-device-dehydration.md",target:"_blank",rel:"noopener"},"more info");a.push(n.p([i,n.label({for:i.id},[e.i18n`Back up my device as well (`,c,")"])]))}return n.div({className:"row"},[n.div({className:"label"},t),n.div({className:"content"},a)])}function Ko(n){return n.if(e=>e.error,(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 sp 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=(a,c,l,h="")=>a.div({className:`row ${h}`},[a.div({className:"label"},c),a.div({className:"content"},l)]),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:a=>a.isLoggingOut},t.i18n`Log out`))),r.push(e.h3("Key backup"),e.view(new Fo(t.keyBackupViewModel))),r.push(e.h3("Notifications"),e.map(a=>a.pushNotifications.supported,(a,c)=>{if(a===null)return c.p(t.i18n`Loading…`);if(a){const l=d=>d.pushNotifications.enabled?d.i18n`Push notifications are enabled`:d.i18n`Push notifications are disabled`,h=d=>d.pushNotifications.enabled?d.i18n`Disable`:d.i18n`Enable`;return i(c,l,c.button({onClick:()=>t.togglePushNotifications(),disabled:d=>d.pushNotifications.updating},h))}else return c.p(t.i18n`Push notifications are not supported on this browser`)}),e.if(a=>a.pushNotifications.supported&&a.pushNotifications.enabled,a=>a.div([a.p(["If you think push notifications are not being delivered, ",a.button({className:"link",onClick:()=>t.checkPushEnabledOnServer()},"check")," if they got disabled on the server"]),a.map(c=>c.pushNotifications.enabledOnServer,(c,l)=>{if(c===!0)return l.p("Push notifications are still enabled on the server, so everything should be working. Sometimes notifications can get dropped if they can't be delivered within a given time.");if(c===!1)return l.p("Push notifications have been disabled on the server, likely due to a bug. Please re-enable them by clicking Disable and then Enable again above.")}),a.map(c=>c.pushNotifications.serverError,(c,l)=>{if(c)return l.p("Couldn't not check on server: "+c.message)})]))),r.push(e.h3("Preferences"),i(e,t.i18n`Scale down images when sending`,this._imageCompressionRange(e,t)),e.if(a=>a.activeTheme,(a,c)=>i(a,c.i18n`Use the following theme`,this._themeOptions(a,c))));const o=[];return t.canSendLogsToServer&&o.push(e.button({onClick:Nm(()=>t.sendLogsToServer())},`Submit logs to ${t.logsServer}`)),o.push(e.button({onClick:()=>t.exportLogs()},"Download logs")),r.push(e.h3("Application"),i(e,t.i18n`Version`,s),i(e,t.i18n`Storage usage`,a=>`${a.storageUsage} / ${a.storageQuota}`),i(e,t.i18n`Debug logs`,o),e.p({className:{hidden:a=>!a.logsFeedbackMessage}},a=>a.logsFeedbackMessage),e.p(["Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited, the usernames of other users and the names of files you send. They do not contain messages. For more information, review our ",e.a({href:"https://element.io/privacy",target:"_blank",rel:"noopener"},"privacy policy"),"."])),e.main({className:"Settings middle"},[e.div({className:"middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close settings`}),e.h2("Settings")]),e.div({className:"SettingsBody"},r)])}_imageCompressionRange(e,t){const i=Math.ceil(t.minSentImageSizeLimit/32)*32,r=(Math.floor(t.maxSentImageSizeLimit/32)+1)*32,o=a=>t.setSentImageSizeLimit(parseInt(a.target.value,10));return[e.input({type:"range",step:32,min:i,max:r,value:a=>a.sentImageSizeLimit||r,onInput:o,onChange:o})," ",e.output(a=>a.sentImageSizeLimit?a.i18n`resize to ${a.sentImageSizeLimit}px`:a.i18n`no resizing`)]}_themeOptions(e,t){const{themeName:s,themeVariant:i}=t.activeTheme,r=[];for(const _ of Object.keys(t.themeMapping))r.push(e.option({value:_,selected:_===s},_));const o=e.select({onChange:_=>{const f=_.target.value;if(!("id"in t.themeMapping[f])){const b=h.checked?"dark":u.checked?"light":"default";a(b);return}t.changeThemeOption(f)}},r),a=_=>{const f=o.options[o.selectedIndex].value;t.changeThemeOption(f,_)},c=i==="dark",l=i==="light",h=e.input({type:"radio",name:"radio-chooser",value:"dark",id:"dark",checked:c}),d=e.input({type:"radio",name:"radio-chooser",value:"default",id:"default",checked:!(c||l)}),u=e.input({type:"radio",name:"radio-chooser",value:"light",id:"light",checked:l}),p=e.form({className:{hidden:()=>{const _=o.options[o.selectedIndex].value;return"id"in t.themeMapping[_]}},onChange:_=>a(_.target.value)},[d,e.label({for:"default"},"Match system theme"),h,e.label({for:"dark"},"dark"),u,e.label({for:"light"},"light")]);return e.div({className:"theme-chooser"},[o,p])}}class ip extends E{render(e,t){return e.main({className:"middle"},e.div({className:"CreateRoomView centered-column"},[e.h2("Create room"),e.form({className:"CreateRoomView_detailsForm form",onChange: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 ht(t,64):new Et(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 (<alias>, or #<alias> or #<alias>: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 rp 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 ht(t,52)),e.mapView(i=>i.isEncrypted,i=>new np(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?T.div({className:"RoomDetailsView_id"},[e.canonicalAlias]):""}_createRightPanelRow(e,t,s,i){const r=It(ft({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=It(ft({RoomDetailsView_label:!0},s));return e.button({className:"RoomDetailsView_row",onClick:r},[e.div({className:o},[t]),e.div({className:"RoomDetailsView_value"},i)])}}class np extends E{render(e,t){return e.div({className:"EncryptionIconView"},[e.div({className:t?"EncryptionIconView_encrypted":"EncryptionIconView_unencrypted"})])}}class op{constructor(e,t){this.start=e,this.end=t}get length(){return this.end-this.start}contains(e){return e.start>=this.start&&e.end<=this.end}containsIndex(e){return e>=this.start&&e<this.end}toLocalIndex(e){return e-this.start}intersects(e){return e.start<this.end&&this.start<e.end}forEachInIterator(e,t){let s=0;for(s=0;s<this.start;s+=1)e.next();for(s=0;s<this.length;s+=1){const i=e.next();if(i.done)break;t(i.value,this.start+s)}}[Symbol.iterator](){return new ap(this)}reverseIterable(){return new cp(this)}clampIndex(e,t=this.end-1){return Math.min(Math.max(this.start,e),t)}getIndexZone(e){return e<this.start?ot.Before:e<this.end?ot.Inside:ot.After}}var ot=(n=>(n[n.Before=1]="Before",n[n.Inside=2]="Inside",n[n.After=3]="After",n))(ot||{});class ap{constructor(e){this.range=e,this.idx=e.start-1}next(){return this.idx<this.range.end-1?(this.idx+=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}class cp{constructor(e){this.range=e,this.idx=e.end}[Symbol.iterator](){return this}next(){return this.idx>this.range.start?(this.idx-=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}function lp(n,e){let t=0;for(;t<e;)if(t+=1,n.next().done)return!1;return!0}function bs(n,e){if(lp(n,e)){const t=n.next();if(!t.done)return t.value}}var wt=(n=>(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))(wt||{});class zt extends op{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 zt(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,a=s!==0?Math.ceil(s/t):0,c=Math.min(a,o);return new zt(r,r+c,e,a)}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:bs(s[Symbol.iterator](),r);return this.createAddResult(r,o)}else return{type:4,newRange:this.deriveRange(1,0)}}queryRemove(e,t){if(e<this.end){const s=this.clampIndex(e);return this.createRemoveResult(s,t)}else return{type:4,newRange:this.deriveRange(-1,0)}}queryMove(e,t,s,i){const r=this.getIndexZone(e),o=this.getIndexZone(t);if(r===o){if(r===ot.Before||r===ot.After)return;if(r===ot.Inside)return{type:0,fromIdx:e,toIdx:t}}else{const a=this.clampIndex(t),c=this.clampIndex(e),l=a===t?s:bs(i[Symbol.iterator](),a);return{type:3,removeIdx:c,addIdx:a,value:l}}}createAddResult(e,t){if(this.viewportItemCount>this.length)return{type:1,addIdx:e,value:t,newRange:this.deriveRange(1,1)};{const 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.end<this.totalLength){const s=this.clampIndex(Number.MAX_SAFE_INTEGER),i=bs(t[Symbol.iterator](),s);return{type:3,removeIdx:e,value:i,addIdx:s,newRange:this.deriveRange(-1,0)}}else if(this.start!==0){const s=this.deriveRange(-1,0,1),i=s.start,r=bs(t[Symbol.iterator](),i);return{type:3,removeIdx:e,value:r,addIdx:i,newRange:s}}else return{type:2,removeIdx:e,newRange:this.deriveRange(-1,0)}}deriveRange(e,t,s=0){const i=this.start-s,r=this.totalLength+e,o=Math.min(Math.max(i,this.end-s+t),r);return new zt(i,o,r,this.viewportItemCount)}}class hp extends is{constructor(r,i){var o=r,{itemHeight:e,overflowItems:t=20}=o,s=wr(o,["itemHeight","overflowItems"]);super(s,i),this.itemHeight=e,this.overflowItems=t}handleEvent(e){e.type==="scroll"?this.handleScroll():super.handleEvent(e)}handleScroll(){const e=this._getVisibleRange();if(e.length!==0&&!this.renderRange.contains(e)){const t=this.renderRange;this.renderRange=e.expand(this.overflowItems),this.renderUpdate(t,this.renderRange)}}async loadList(){if(await new Promise(t=>requestAnimationFrame(t)),await new Promise(t=>requestAnimationFrame(t)),!this._list)return;this._subscription=this._list.subscribe(this);const e=this._getVisibleRange();this.renderRange=e.expand(this.overflowItems),this._childInstances=[],this.reRenderFullRange(this.renderRange)}_getVisibleRange(){const{clientHeight:e,scrollTop:t}=this.root();if(e===0)throw new Error("LazyListView height is 0");return zt.fromViewport(this._list.length,this.itemHeight,e,t)}reRenderFullRange(e){xm(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(Xt(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=T.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===wt.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===wt.Remove||e.type===wt.RemoveAndAdd)&&this.removeChild(this.renderRange.toLocalIndex(e.removeIdx)),e.newRange&&(this.renderRange=e.newRange,this.adjustPadding(this.renderRange)),(e.type===wt.Add||e.type===wt.RemoveAndAdd)&&this.addChild(this.renderRange.toLocalIndex(e.addIdx),e.value)}}class dp extends E{render(e,t){return e.li({className:"MemberTileView"},e.a({href:t.detailsUrl},[e.view(new ht(t,32)),e.div({className:"MemberTileView_name"},s=>s.name)]))}}class up extends hp{constructor(e){super({list:e.memberTileViewModels,className:"MemberListView",itemHeight:40},t=>new dp(t))}}class mp extends E{render(e,t){return e.div({className:"MemberDetailsView"},[e.view(new ht(t,128)),e.div({className:"MemberDetailsView_name"},e.h2(s=>s.name)),e.div({className:"MemberDetailsView_id"},t.userId),this._createSection(e,t.i18n`Role`,s=>s.role),this._createSection(e,t.i18n`Security`,t.isEncrypted?t.i18n`Messages in this room are end-to-end encrypted.`:t.i18n`Messages in this room are not end-to-end encrypted.`),this._createOptions(e,t)])}_createSection(e,t,s){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t),e.div({className:"MemberDetailsView_value"},s)])}_createOptions(e,t){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t.i18n`Options`),e.div({className:"MemberDetailsView_options"},[e.a({href:t.linkToUser,target:"_blank",rel:"noopener"},t.i18n`Open Link to User`),e.button({className:"text",onClick:()=>t.openDirectMessage()},t.i18n`Open direct message`)])])}}class pp extends E{render(e){return e.div({className:"RightPanelView"},[e.ifView(t=>t.activeViewModel,t=>new _p(t)),e.mapView(t=>t.activeViewModel,t=>this._viewFromType(t))])}_viewFromType(e){switch(e==null?void 0:e.type){case"room-details":return new rp(e);case"member-list":return new up(e);case"member-details":return new mp(e);default:return new Oo}}}class _p extends E{render(e,t){return e.div({className:"RightPanelView_buttons"},[e.button({className:{back:!0,"button-utility":!0,hide:!t.activeViewModel.shouldShowBackButton},onClick:()=>t.showPreviousPanel()}),e.button({className:"close button-utility",onClick:()=>t.closePanel()})])}}class fp extends is{constructor(e){const t={className:"Timeline_messageReactions",tagName:"div",list:e.reactions,onItemClick:s=>s.onClick()};super(t,s=>new gp(s))}}class gp 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 Tt 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:t.isUnverified,disabled:!this._interactive,continuation:o=>o.isContinuation},"data-event-id":t.eventId},s);e.mapSideEffect(o=>o.isContinuation,(o,a)=>{if(o&&a===!1)i.removeChild(i.querySelector(".Timeline_messageAvatar")),i.removeChild(i.querySelector(".Timeline_messageSender"));else if(!o&&!this._isReplyPreview){const c=T.a({href:t.memberPanelLink,className:"Timeline_messageAvatar"},[it(t,30)]),l=T.div({className:`Timeline_messageSender usercolor${t.avatarColorNumber}`},t.displayName);i.insertBefore(c,i.firstChild),i.insertBefore(l,i.firstChild)}});let r=null;return e.mapSideEffect(o=>o.reactions,o=>{o&&this._interactive&&!r?(r=new fp(o),this.addSubView(r),i.appendChild(Xt(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 zi(new Y(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 yp(e)),t.push(Y.option(e.i18n`Reply`,()=>e.startReply()))),e.canAbortSending?t.push(Y.option(e.i18n`Cancel`,()=>e.abortSending())):e.canRedact&&t.push(Y.option(e.i18n`Delete`,()=>e.redact()).setDestructive()),t}renderMessageBody(){}}class yp{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 wp 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",href:t.permaLink},"In reply to"),e.a({className:"pill",href:t.senderProfileLink},[it(t,12,void 0),t.displayName]),e.br(),e.view(i)]))}}class vp extends E{render(e){return e.blockquote({className:"ReplyPreviewView"},[e.div({className:"Timeline_messageBody statusMessage"},"This reply could not be found.")])}}class bp extends Tt{renderMessageBody(e,t){const s=e.time({className:{hidden:!t.date}},t.date+" "+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 vp:o?new wp(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 a of o.parts)i.appendChild($o(a));i.appendChild(s)}),i}}function Sp(n){const e=n.items.map(s=>T.li(at(s))),t=n.startOffset;return t?T.ol({start:t},e):T.ul(e)}function Ip(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),T.img(e)}function Ep(n){const e=`avatar size-12 usercolor${n.avatarColorNumber}`,t=T.div({class:e},Te(n.avatarInitials)),s=at(n.children);return s.unshift(t),T.a({class:"pill",href:n.href,rel:"noopener",target:"_blank"},s)}function kp(n){const e=[];if(n.head){const s=n.head.map(i=>T.th(at(i)));e.push(T.thead(T.tr(s)))}const t=[];for(const s of n.body){const i=s.map(r=>T.td(at(r)));t.push(T.tr(i))}return e.push(T.tbody(t)),T.table(e)}const Rp={header:n=>T["h"+Math.min(6,n.level)](at(n.inlines)),codeblock:n=>T.pre(T.code(Te(n.text))),table:n=>kp(n),code:n=>T.code(Te(n.text)),text:n=>Te(n.text),link:n=>T.a({href:n.url,className:"link",target:"_blank",rel:"noopener"},at(n.inlines)),pill:Ep,format:n=>T[n.format](at(n.children)),rule:()=>T.hr(),list:Sp,image:Ip,newline:()=>T.br()};function $o(n){const e=Rp[n.type];return e?e(n):Te(`[unknown part type ${n.type}]`)}function at(n){return Array.from(n,$o)}class jo extends Tt{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.date+" "+t.time)],o=e.div({className:{status:!0,hidden:a=>!a.status}},a=>a.status);if(r.push(o),t.isPending){const a=e.progress({min:0,max:100,value:c=>c.uploadPercentage,className:{hidden:c=>!c.isUploading}});r.push(a)}return e.div({className:"Timeline_messageBody"},[e.div({className:"media",style:`max-width: ${t.width}px`,"data-testid":"media"},r),e.if(a=>a.error,a=>a.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(Y.option(s,()=>e.downloadMedia()))}return t}}class Cp extends jo{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 Ds(n,e){return new Promise((t,s)=>{let i;const r=a=>{i(),s(a.target.error)},o=()=>{i(),t()};i=()=>{n.removeEventListener(e,o),n.removeEventListener("error",r)},n.addEventListener(e,o),n.addEventListener("error",r)})}class Tp extends jo{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=Ds(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 Mp extends Tt{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.date+" "+t.time)),e.p({className:"Timeline_messageBody statusMessage"},s)}}class Ap extends Tt{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},[e.span(t.label),e.a({className:"Timeline_locationLink",href:t.mapsLink,target:"_blank",rel:"noopener"},t.i18n`Open in maps`),e.time(t.date+" "+t.time)])}}class xp extends Tt{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},t.label)}}class Np extends E{constructor(e){super(e)}render(e){return e.li({className:"AnnouncementView"},e.div(t=>t.announcement))}onClick(){}}class Dp extends Tt{renderMessageBody(e){return e.p({className:"Timeline_messageBody statusMessage"},t=>t.description)}createMenuOptions(e){const t=super.createMenuOptions(e);return e.isRedacting&&t.push(Y.option(e.i18n`Cancel`,()=>e.abortPendingRedaction())),t}}class Vp extends E{constructor(e){super(e)}render(e){const t={GapView:!0,isLoading:s=>s.isLoading,isAtTop:s=>s.isAtTop};return e.li({className:t},[Ve(e),e.div(s=>s.isLoading?s.i18n`Loading more messages …`:s.i18n`Not loading!`),e.if(s=>s.error,s=>s.strong(i=>i.error))])}onClick(){}}function mn(n){switch(n.shape){case"gap":return Vp;case"announcement":return Np;case"message":case"message-status":return bp;case"image":return Cp;case"video":return Tp;case"file":return Mp;case"location":return Ap;case"missing-attachment":return xp;case"redacted":return Dp;default:throw new Error(`Tiles of shape "${n.shape}" are not supported, check the tileClassForEntry function in the view model`)}}class Lp extends E{render(e,t){return e.div({className:{SessionView:!0,"middle-shown":s=>!!s.activeMiddleViewModel,"right-shown":s=>!!s.rightPanelViewModel}},[e.view(new Qm(t.sessionStatusViewModel)),e.view(new Pm(t.leftPanelViewModel)),e.mapView(s=>s.activeMiddleViewModel,()=>t.roomGridViewModel?new Ym(t.roomGridViewModel,mn):t.settingsViewModel?new sp(t.settingsViewModel):t.createRoomViewModel?new ip(t.createRoomViewModel):t.currentRoomViewModel?t.currentRoomViewModel.kind==="invite"?new Uo(t.currentRoomViewModel):t.currentRoomViewModel.kind==="room"?new Lo(t.currentRoomViewModel,mn):t.currentRoomViewModel.kind==="roomBeingCreated"?new Po(t.currentRoomViewModel):new Wm(t.currentRoomViewModel):new Et(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 zm(s):null),e.mapView(s=>s.rightPanelViewModel,s=>s?new pp(s):null)])}}function qo(n){return "2832467534"?n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web/releases/tag/v0.3.1"},`Hydrogen v0.3.1 (${"2832467534"}) on Github`):n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web"},"Hydrogen on Github")}class Op 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"},a=>a.error)),e.form({onSubmit:o=>{o.preventDefault(),t.login(i.value,r.value)}},[e.if(o=>o.errorMessage,(o,a)=>o.p({className:"error"},a.i18n(a.errorMessage))),e.div({className:"form-row text"},[e.label({for:"username"},t.i18n`Username`),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 Pp 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 Fo(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 Ps 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"},[Ve(e,{hidden:i=>!i.loading}),e.p(i=>i.loadLabel),t,s]),e.ifView(i=>i.accountSetupViewModel,i=>new Pp(i.accountSetupViewModel))])}}class Up 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 Ps(t):null)])}}class Fp 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 Up(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,a)=>o.p({className:"error"},a.i18n(a.errorMessage)))])),e.if(i=>i.isFetchingLoginOptions,i=>i.div({className:"LoginView_query-spinner"},[Ve(i),i.p("Fetching available login options...")])),e.mapView(i=>i.passwordLoginViewModel,i=>i?new Op(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 Bp(i):null),e.mapView(i=>i.loadViewModel,i=>i?new Ps(i):null),e.p(qo(e))])}}class Bp 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 Kp extends E{render(e,t){const s=new Ns(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 Ns(t,r=>r.p({className:"status",hidden:o=>!o.showStatus},[Ve(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 $p extends E{render(e,t){return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionLoadView"},[e.view(new Ps(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 jp 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 qp extends E{render(e,t){const s=new is({list:t.sessions,parentProvidesUpdates:!1},i=>new jp(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 Ps(t.loadViewModel)),e.p(qo(e))])])}}class Wp extends E{render(e,t){return e.mapView(s=>s.activeSection,s=>{switch(s){case"error":return new Et(i=>i.div({className:"StatusView"},[i.h1("Something went wrong"),i.p(t.errorText)]));case"session":return new Lp(t.sessionViewModel);case"login":return new Fp(t.loginViewModel);case"logout":return new Kp(t.logoutViewModel);case"picker":return new qp(t.sessionPickerViewModel);case"redirecting":return new Et(i=>i.p("Redirecting..."));case"loading":return new $p(t.sessionLoadViewModel);default:throw new Error(`Unknown section: ${t.activeSection}`)}})}}class Hp{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 ye),clearTimeout(this._handle),this._handle=null,this._reject=null)}dispose(){this.abort()}}class zp{constructor(e,t){this._handle=setInterval(t,e)}dispose(){this._handle&&(clearInterval(this._handle),this._handle=null)}}class Gp{constructor(){this._start=window.performance.now()}measure(){return window.performance.now()-this._start}}class Jp{createMeasure(){return new Gp}createTimeout(e){return new Hp(e)}createInterval(e,t){return new zp(t,e)}now(){return Date.now()}}class Qp{constructor(){this._waitingForReply=new Map,this._messageIdCounter=0,this._navigation=null,this._registration=null,this._registrationPromise=null,this._currentController=null,this.haltRequests=!1}setNavigation(e){this._navigation=e}registerAndStart(e){this._registrationPromise=(async()=>{navigator.serviceWorker.addEventListener("message",this),navigator.serviceWorker.addEventListener("controllerchange",this),this._registration=await navigator.serviceWorker.register(e),await navigator.serviceWorker.ready,this._currentController=navigator.serviceWorker.controller,this._registration.addEventListener("updatefound",this),this._registrationPromise=null,this._registration.waiting&&this._registration.active&&this._proposeUpdate(),console.log("Service Worker registered")})()}_onMessage(e){const{data:t}=e,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)}_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 a=o.get("session");(!a||a.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);confirm(`Version ${e.version} (${e.buildHash}) is available. Reload to apply?`)&&(await this._sendAndWaitForReply("haltRequests"),this._send("skipWaiting",null,this._registration.waiting))}handleEvent(e){switch(e.type){case"message":this._onMessage(e);break;case"updatefound":this._registration.installing.addEventListener("statechange",this);break;case"statechange":{e.target.state==="installed"&&(this._proposeUpdate(),e.target.removeEventListener("statechange",this));break}case"controllerchange":this._currentController?document.location.reload():this._currentController=navigator.serviceWorker.controller;break}}async _send(e,t,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.3.1"}get buildHash(){return "2832467534"}async preventConcurrentSessionAccess(e){return this._sendAndWaitForReply("closeSession",{sessionId:e})}async getRegistration(){return this._registrationPromise&&await this._registrationPromise,this._registration}}class Yp{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(),a=o.keys.p256dh,c={endpoint:o.endpoint,auth:o.keys.auth,events_only:!0,default_payload:t};return e.httpPusher(this._pushConfig.gatewayUrl,this._pushConfig.appId,a,c)}}async disablePush(){var 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 Xp extends kt{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 Zp extends kt{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 Q(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 e_{constructor(e){this._subtleCrypto=e}async verify(e,t,s,i){const r={name:"HMAC",hash:{name:ct(i)}},o=await Q(this._subtleCrypto.importKey("raw",e,r,!1,["verify"]),"importKey");return await Q(this._subtleCrypto.verify(r,o,t,s),"verify")}async compute(e,t,s){const i={name:"HMAC",hash:{name:ct(s)}},r=await Q(this._subtleCrypto.importKey("raw",e,i,!1,["sign"]),"importKey"),o=await Q(this._subtleCrypto.sign(i,r,t),"sign");return new Uint8Array(o)}}class t_{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 Q(this._subtleCrypto.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),"importKey"),a=await Q(this._subtleCrypto.deriveBits({name:"PBKDF2",salt:s,iterations:t,hash:ct(i)},o,r),"deriveBits");return new Uint8Array(a)}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 Q(this._subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),"importKey"),a=await Q(this._subtleCrypto.deriveBits({name:"HKDF",salt:t,info:s,hash:ct(i)},o,r),"deriveBits");return new Uint8Array(a)}}class s_{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 a;try{const c=e||t,l=t?"jwk":"raw";a=await Q(this._subtleCrypto.importKey(l,c,o,!1,["decrypt"]),"importKey")}catch(c){throw new Error(`Could not import key for AES-CTR decryption: ${c.message}`)}try{const c=await Q(this._subtleCrypto.decrypt(o,a,i),"decrypt");return new Uint8Array(c)}catch(c){throw new Error(`Could not decrypt with AES-CTR: ${c.message}`)}}async encryptCTR({key:e,jwkKey:t,iv:s,data:i}){const r={name:"AES-CTR",counter:s,length:64};let o;const a=e||t,c=t?"jwk":"raw";try{o=await Q(this._subtleCrypto.importKey(c,a,r,!1,["encrypt"]),"importKey")}catch(l){throw new Error(`Could not import key for AES-CTR encryption: ${l.message}`)}try{const l=await Q(this._subtleCrypto.encrypt(r,o,i),"encrypt");return new Uint8Array(l)}catch(l){throw new Error(`Could not encrypt with AES-CTR: ${l.message}`)}}async generateKey(e,t=256){const s=await Q(this._subtleCrypto.generateKey({name:"AES-CTR",length:t},!0,["encrypt","decrypt"]));return Q(this._subtleCrypto.exportKey(e,s))}async generateIV(){return Wo(this._crypto)}}function Wo(n){const e=n.getRandomValues(new Uint8Array(8)),t=new Uint8Array(16);for(let s=0;s<e.length;s+=1)t[s]=e[s];return t}function pn(n){if(n.alg!=="A256CTR")throw new Error(`Unknown algorithm: ${n.alg}`);if(!n.key_ops.includes("decrypt"))throw new Error("decrypt missing from key_ops");if(n.kty!=="oct")throw new Error(`Invalid key type, "oct" expected: ${n.kty}`);const t=n.k.replace(/-/g,"+").replace(/_/g,"/");return nt.decode(t)}function i_(n){const e=nt.encode(n),t=e.indexOf("=");return t!==-1?e.substr(0,t):e}function r_(n){return i_(n).replace(/\+/g,"-").replace(/\//g,"_")}function n_(n){return{alg:"A256CTR",ext:!0,k:r_(n),key_ops:["encrypt","decrypt"],kty:"oct"}}class o_{constructor(e,t){this._aesjs=e,this._crypto=t}async decryptCTR({key:e,jwkKey:t,iv:s,data:i,counterLength:r=64}){if(r!==64)throw new Error(`Unsupported counter length: ${r}`);t&&(e=pn(t));const o=this._aesjs;var a=new o.ModeOfOperation.ctr(new Uint8Array(e),new o.Counter(new Uint8Array(s)));return a.decrypt(new Uint8Array(i))}async encryptCTR({key:e,jwkKey:t,iv:s,data:i}){t&&(e=pn(t));const r=this._aesjs;var o=new r.ModeOfOperation.ctr(new Uint8Array(e),new r.Counter(new Uint8Array(s)));return o.encrypt(new Uint8Array(i))}async generateKey(e,t=256){let s=crypto.getRandomValues(new Uint8Array(t/8));return e==="jwk"&&(s=n_(s)),s}async generateIV(){return Wo(this._crypto)}}function ct(n){if(n!=="SHA-256"&&n!=="SHA-512")throw new Error(`Invalid hash name: ${n}`);return n}class a_{constructor(e){const t=window.crypto||window.msCrypto,s=t.subtle||t.webkitSubtle;this._subtleCrypto=s,!s.deriveBits&&(e==null?void 0:e.aesjs)?this.aes=new o_(e.aesjs,t):this.aes=new s_(s,t),this.hmac=new e_(s),this.derive=new t_(s,this,e)}async digest(e,t){return await Q(this._subtleCrypto.digest(ct(e),t))}digestSize(e){switch(ct(e)){case"SHA-512":return 64;case"SHA-256":return 32;default:throw new Error(`Not implemented for ${ct(e)}`)}}}async function c_(){var n;if((n=navigator==null?void 0:navigator.storage)!=null&&n.estimate){const{quota:e,usage:t}=await navigator.storage.estimate();return{quota:e,usage:t}}else return{quota:null,usage:null}}class l_{constructor(e){this.worker=e,this.busy=!1}attach(e){this.worker.addEventListener("message",e),this.worker.addEventListener("error",e)}detach(e){this.worker.removeEventListener("message",e),this.worker.removeEventListener("error",e)}}class h_{constructor(e,t){this._promise=new Promise((s,i)=>{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 d_{constructor(e,t){this._workers=[];for(let s=0;s<t;++s){const i=new l_(new Worker(e));i.attach(this),this._workers[s]=i}this._requests=new Map,this._counter=0,this._pendingFlag=!1,this._init=null}init(){const e=new Promise((t,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 h_(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 ye),e._worker&&(e._worker.busy=!1),this._requests.delete(e._message.id),this._trySendPendingInNextTick()}}class Zt{static async fromBlob(e){const t=await _n(e),{width:s,height:i}=t;return new Zt(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 _n(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 a=o.getContext("2d"),c=await this._getDomElement();a.drawImage(c,0,0,i,r);let l=this.blob.mimeType==="image/jpeg"?"image/jpeg":"image/png",h;if(o.toBlob)h=await new Promise(u=>o.toBlob(u,l));else if(o.msToBlob)l="image/png",h=o.msToBlob();else throw new Error("canvas can't be turned into blob");const d=lt.fromBlob(h);return new Zt(d,i,r,null)}dispose(){this.blob.dispose()}}class Gi extends Zt{get duration(){if(typeof this._domElement.duration=="number")return Math.round(this._domElement.duration*1e3)}static async fromBlob(e){const t=await m_(e),{videoWidth:s,videoHeight:i}=t;return new Gi(e,s,i,t)}}function u_(){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 _n(n){const e=document.createElement("img"),t=Ds(e,"load");return e.src=n.url,await t,e}async function m_(n){const e=document.createElement("video");e.muted=!0;const t=Ds(e,"loadedmetadata");e.src=n.url,e.load(),await t;const s=Ds(e,"seeked");return await new Promise(i=>setTimeout(i,200)),e.currentTime=.1,await s,e}async function p_(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((a,c)=>{o=()=>{r.removeEventListener("load",a),r.removeEventListener("error",c)},r.addEventListener("load",a),r.addEventListener("error",c)}),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 __(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e<n.length;e++)t[e]=n[e];return t}else return Array.from(n)}var f_=Object.hasOwnProperty,fn=Object.setPrototypeOf,g_=Object.isFrozen,y_=Object.getPrototypeOf,w_=Object.getOwnPropertyDescriptor,Z=Object.freeze,Ae=Object.seal,v_=Object.create,Ho=typeof Reflect!="undefined"&&Reflect,Vs=Ho.apply,Si=Ho.construct;Vs||(Vs=function(e,t,s){return e.apply(t,s)});Z||(Z=function(e){return e});Ae||(Ae=function(e){return e});Si||(Si=function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(__(t))))});var b_=le(Array.prototype.forEach),gn=le(Array.prototype.pop),Pt=le(Array.prototype.push),et=le(String.prototype.toLowerCase),yn=le(String.prototype.match),Be=le(String.prototype.replace),S_=le(String.prototype.indexOf),I_=le(String.prototype.trim),Ke=le(RegExp.prototype.test),wn=E_(TypeError);function le(n){return function(e){for(var t=arguments.length,s=Array(t>1?t-1:0),i=1;i<t;i++)s[i-1]=arguments[i];return Vs(n,e,s)}}function E_(n){return function(){for(var e=arguments.length,t=Array(e),s=0;s<e;s++)t[s]=arguments[s];return Si(n,t)}}function C(n,e){fn&&fn(n,null);for(var t=e.length;t--;){var s=e[t];if(typeof s=="string"){var i=et(s);i!==s&&(g_(e)||(e[t]=i),s=i)}n[s]=!0}return n}function yt(n){var e=v_(null),t=void 0;for(t in n)Vs(f_,n,[t])&&(e[t]=n[t]);return e}function Ss(n,e){for(;n!==null;){var t=w_(n,e);if(t){if(t.get)return le(t.get);if(typeof t.value=="function")return le(t.value)}n=y_(n)}function s(i){return console.warn("fallback value for",i),null}return s}var vn=Z(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),ri=Z(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ni=Z(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),k_=Z(["animate","color-profile","cursor","discard","fedropshadow","feimage","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),oi=Z(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),R_=Z(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),bn=Z(["#text"]),Sn=Z(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),ai=Z(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),In=Z(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Is=Z(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),C_=Ae(/\{\{[\s\S]*|[\s\S]*\}\}/gm),T_=Ae(/<%[\s\S]*|[\s\S]*%>/gm),M_=Ae(/^data-[\-\w.\u00B7-\uFFFF]/),A_=Ae(/^aria-[\-\w]+$/),x_=Ae(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),N_=Ae(/^(?:\w+script|data):/i),D_=Ae(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Kt=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 pe(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e<n.length;e++)t[e]=n[e];return t}else return Array.from(n)}var V_=function(){return typeof window=="undefined"?null:window},L_=function(e,t){if((typeof e=="undefined"?"undefined":Kt(e))!=="object"||typeof e.createPolicy!="function")return null;var s=null,i="data-tt-policy-suffix";t.currentScript&&t.currentScript.hasAttribute(i)&&(s=t.currentScript.getAttribute(i));var r="dompurify"+(s?"#"+s:"");try{return e.createPolicy(r,{createHTML:function(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}};function zo(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:V_(),e=function(m){return zo(m)};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,a=n.Element,c=n.NodeFilter,l=n.NamedNodeMap,h=l===void 0?n.NamedNodeMap||n.MozNamedAttrMap:l,d=n.Text,u=n.Comment,p=n.DOMParser,_=n.trustedTypes,f=a.prototype,b=Ss(f,"cloneNode"),S=Ss(f,"nextSibling"),k=Ss(f,"childNodes"),R=Ss(f,"parentNode");if(typeof r=="function"){var w=s.createElement("template");w.content&&w.content.ownerDocument&&(s=w.content.ownerDocument)}var I=L_(_,t),x=I&&ns?I.createHTML(""):"",D=s,Le=D.implementation,Qo=D.createNodeIterator,Yo=D.createDocumentFragment,Xo=D.getElementsByTagName,Zo=t.importNode,Ji={};try{Ji=yt(s).documentMode?s.documentMode:{}}catch{}var ue={};e.isSupported=typeof R=="function"&&Le&&typeof Le.createHTMLDocument!="undefined"&&Ji!==9;var Fs=C_,Bs=T_,ea=M_,ta=A_,sa=N_,Qi=D_,Ks=x_,$=null,Yi=C({},[].concat(pe(vn),pe(ri),pe(ni),pe(oi),pe(bn))),j=null,Xi=C({},[].concat(pe(Sn),pe(ai),pe(In),pe(Is))),$s=null,js=null,Zi=!0,qs=!0,er=!1,dt=!1,ut=!1,Ws=!1,Hs=!1,mt=!1,rs=!1,tr=!0,ns=!1,sr=!0,zs=!0,Mt=!1,pt={},ia=C({},["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"]),ir=null,rr=C({},["audio","video","img","source","image","track"]),Gs=null,nr=C({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Js="http://www.w3.org/1998/Math/MathML",Qs="http://www.w3.org/2000/svg",Oe="http://www.w3.org/1999/xhtml",os=Oe,Ys=!1,_t=null,ra=s.createElement("form"),Xs=function(m){_t&&_t===m||((!m||(typeof m=="undefined"?"undefined":Kt(m))!=="object")&&(m={}),m=yt(m),$="ALLOWED_TAGS"in m?C({},m.ALLOWED_TAGS):Yi,j="ALLOWED_ATTR"in m?C({},m.ALLOWED_ATTR):Xi,Gs="ADD_URI_SAFE_ATTR"in m?C(yt(nr),m.ADD_URI_SAFE_ATTR):nr,ir="ADD_DATA_URI_TAGS"in m?C(yt(rr),m.ADD_DATA_URI_TAGS):rr,$s="FORBID_TAGS"in m?C({},m.FORBID_TAGS):{},js="FORBID_ATTR"in m?C({},m.FORBID_ATTR):{},pt="USE_PROFILES"in m?m.USE_PROFILES:!1,Zi=m.ALLOW_ARIA_ATTR!==!1,qs=m.ALLOW_DATA_ATTR!==!1,er=m.ALLOW_UNKNOWN_PROTOCOLS||!1,dt=m.SAFE_FOR_TEMPLATES||!1,ut=m.WHOLE_DOCUMENT||!1,mt=m.RETURN_DOM||!1,rs=m.RETURN_DOM_FRAGMENT||!1,tr=m.RETURN_DOM_IMPORT!==!1,ns=m.RETURN_TRUSTED_TYPE||!1,Hs=m.FORCE_BODY||!1,sr=m.SANITIZE_DOM!==!1,zs=m.KEEP_CONTENT!==!1,Mt=m.IN_PLACE||!1,Ks=m.ALLOWED_URI_REGEXP||Ks,os=m.NAMESPACE||Oe,dt&&(qs=!1),rs&&(mt=!0),pt&&($=C({},[].concat(pe(bn))),j=[],pt.html===!0&&(C($,vn),C(j,Sn)),pt.svg===!0&&(C($,ri),C(j,ai),C(j,Is)),pt.svgFilters===!0&&(C($,ni),C(j,ai),C(j,Is)),pt.mathMl===!0&&(C($,oi),C(j,In),C(j,Is))),m.ADD_TAGS&&($===Yi&&($=yt($)),C($,m.ADD_TAGS)),m.ADD_ATTR&&(j===Xi&&(j=yt(j)),C(j,m.ADD_ATTR)),m.ADD_URI_SAFE_ATTR&&C(Gs,m.ADD_URI_SAFE_ATTR),zs&&($["#text"]=!0),ut&&C($,["html","head","body"]),$.table&&(C($,["tbody"]),delete $s.tbody),Z&&Z(m),_t=m)},or=C({},["mi","mo","mn","ms","mtext"]),ar=C({},["foreignobject","desc","title","annotation-xml"]),as=C({},ri);C(as,ni),C(as,k_);var Zs=C({},oi);C(Zs,R_);var na=function(m){var g=R(m);(!g||!g.tagName)&&(g={namespaceURI:Oe,tagName:"template"});var y=et(m.tagName),N=et(g.tagName);if(m.namespaceURI===Qs)return g.namespaceURI===Oe?y==="svg":g.namespaceURI===Js?y==="svg"&&(N==="annotation-xml"||or[N]):Boolean(as[y]);if(m.namespaceURI===Js)return g.namespaceURI===Oe?y==="math":g.namespaceURI===Qs?y==="math"&&ar[N]:Boolean(Zs[y]);if(m.namespaceURI===Oe){if(g.namespaceURI===Qs&&!ar[N]||g.namespaceURI===Js&&!or[N])return!1;var q=C({},["title","style","font","a","script"]);return!Zs[y]&&(q[y]||!as[y])}return!1},Pe=function(m){Pt(e.removed,{element:m});try{m.parentNode.removeChild(m)}catch{try{m.outerHTML=x}catch{m.remove()}}},cr=function(m,g){try{Pt(e.removed,{attribute:g.getAttributeNode(m),from:g})}catch{Pt(e.removed,{attribute:null,from:g})}if(g.removeAttribute(m),m==="is"&&!j[m])if(mt||rs)try{Pe(g)}catch{}else try{g.setAttribute(m,"")}catch{}},lr=function(m){var g=void 0,y=void 0;if(Hs)m="<remove></remove>"+m;else{var N=yn(m,/^[\r\n\t ]+/);y=N&&N[0]}var q=I?I.createHTML(m):m;if(os===Oe)try{g=new p().parseFromString(q,"text/html")}catch{}if(!g||!g.documentElement){g=Le.createDocument(os,"template",null);try{g.documentElement.innerHTML=Ys?"":q}catch{}}var W=g.body||g.documentElement;return m&&y&&W.insertBefore(s.createTextNode(y),W.childNodes[0]||null),os===Oe?Xo.call(g,ut?"html":"body")[0]:ut?g.documentElement:W},hr=function(m){return Qo.call(m.ownerDocument||m,m,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT,null,!1)},oa=function(m){return m instanceof d||m instanceof u?!1:typeof m.nodeName!="string"||typeof m.textContent!="string"||typeof m.removeChild!="function"||!(m.attributes instanceof h)||typeof m.removeAttribute!="function"||typeof m.setAttribute!="function"||typeof m.namespaceURI!="string"||typeof m.insertBefore!="function"},At=function(m){return(typeof o=="undefined"?"undefined":Kt(o))==="object"?m instanceof o:m&&(typeof m=="undefined"?"undefined":Kt(m))==="object"&&typeof m.nodeType=="number"&&typeof m.nodeName=="string"},be=function(m,g,y){!ue[m]||b_(ue[m],function(N){N.call(e,g,y,_t)})},dr=function(m){var g=void 0;if(be("beforeSanitizeElements",m,null),oa(m)||yn(m.nodeName,/[\u0080-\uFFFF]/))return Pe(m),!0;var y=et(m.nodeName);if(be("uponSanitizeElement",m,{tagName:y,allowedTags:$}),!At(m.firstElementChild)&&(!At(m.content)||!At(m.content.firstElementChild))&&Ke(/<[/\w]/g,m.innerHTML)&&Ke(/<[/\w]/g,m.textContent))return Pe(m),!0;if(!$[y]||$s[y]){if(zs&&!ia[y]){var N=R(m)||m.parentNode,q=k(m)||m.childNodes;if(q&&N)for(var W=q.length,H=W-1;H>=0;--H)N.insertBefore(b(q[H],!0),S(m))}return Pe(m),!0}return m instanceof a&&!na(m)||(y==="noscript"||y==="noembed")&&Ke(/<\/no(script|embed)/i,m.innerHTML)?(Pe(m),!0):(dt&&m.nodeType===3&&(g=m.textContent,g=Be(g,Fs," "),g=Be(g,Bs," "),m.textContent!==g&&(Pt(e.removed,{element:m.cloneNode()}),m.textContent=g)),be("afterSanitizeElements",m,null),!1)},ur=function(m,g,y){if(sr&&(g==="id"||g==="name")&&(y in s||y in ra))return!1;if(!(qs&&!js[g]&&Ke(ea,g))){if(!(Zi&&Ke(ta,g))){if(!j[g]||js[g])return!1;if(!Gs[g]){if(!Ke(Ks,Be(y,Qi,""))){if(!((g==="src"||g==="xlink:href"||g==="href")&&m!=="script"&&S_(y,"data:")===0&&ir[m])){if(!(er&&!Ke(sa,Be(y,Qi,"")))){if(y)return!1}}}}}}return!0},mr=function(m){var g=void 0,y=void 0,N=void 0,q=void 0;be("beforeSanitizeAttributes",m,null);var W=m.attributes;if(!!W){var H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:j};for(q=W.length;q--;){g=W[q];var Se=g,xt=Se.name,pr=Se.namespaceURI;if(y=I_(g.value),N=et(xt),H.attrName=N,H.attrValue=y,H.keepAttr=!0,H.forceKeepAttr=void 0,be("uponSanitizeAttribute",m,H),y=H.attrValue,!H.forceKeepAttr&&(cr(xt,m),!!H.keepAttr)){if(Ke(/\/>/i,y)){cr(xt,m);continue}dt&&(y=Be(y,Fs," "),y=Be(y,Bs," "));var ca=m.nodeName.toLowerCase();if(!!ur(ca,N,y))try{pr?m.setAttributeNS(pr,xt,y):m.setAttribute(xt,y),gn(e.removed)}catch{}}}be("afterSanitizeAttributes",m,null)}},aa=function v(m){var g=void 0,y=hr(m);for(be("beforeSanitizeShadowDOM",m,null);g=y.nextNode();)be("uponSanitizeShadowNode",g,null),!dr(g)&&(g.content instanceof i&&v(g.content),mr(g));be("afterSanitizeShadowDOM",m,null)};return e.sanitize=function(v,m){var g=void 0,y=void 0,N=void 0,q=void 0,W=void 0;if(Ys=!v,Ys&&(v="<!-->"),typeof v!="string"&&!At(v)){if(typeof v.toString!="function")throw wn("toString is not a function");if(v=v.toString(),typeof v!="string")throw wn("dirty is not a string, aborting")}if(!e.isSupported){if(Kt(n.toStaticHTML)==="object"||typeof n.toStaticHTML=="function"){if(typeof v=="string")return n.toStaticHTML(v);if(At(v))return n.toStaticHTML(v.outerHTML)}return v}if(Ws||Xs(m),e.removed=[],typeof v=="string"&&(Mt=!1),!Mt)if(v instanceof o)g=lr("<!---->"),y=g.ownerDocument.importNode(v,!0),y.nodeType===1&&y.nodeName==="BODY"||y.nodeName==="HTML"?g=y:g.appendChild(y);else{if(!mt&&!dt&&!ut&&v.indexOf("<")===-1)return I&&ns?I.createHTML(v):v;if(g=lr(v),!g)return mt?null:x}g&&Hs&&Pe(g.firstChild);for(var H=hr(Mt?v:g);N=H.nextNode();)N.nodeType===3&&N===q||dr(N)||(N.content instanceof i&&aa(N.content),mr(N),q=N);if(q=null,Mt)return v;if(mt){if(rs)for(W=Yo.call(g.ownerDocument);g.firstChild;)W.appendChild(g.firstChild);else W=g;return tr&&(W=Zo.call(t,W,!0)),W}var Se=ut?g.outerHTML:g.innerHTML;return dt&&(Se=Be(Se,Fs," "),Se=Be(Se,Bs," ")),I&&ns?I.createHTML(Se):Se},e.setConfig=function(v){Xs(v),Ws=!0},e.clearConfig=function(){_t=null,Ws=!1},e.isValidAttribute=function(v,m,g){_t||Xs({});var y=et(v),N=et(m);return ur(y,N,g)},e.addHook=function(v,m){typeof m=="function"&&(ue[v]=ue[v]||[],Pt(ue[v],m))},e.removeHook=function(v){ue[v]&&gn(ue[v])},e.removeHooks=function(v){ue[v]&&(ue[v]=[])},e.removeAllHooks=function(){ue={}},e}var O_=zo();class P_{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 U_={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 F_(n){const e=O_.sanitize(n,U_),t=new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${e}</body></html>`,"text/html").body;return new P_(t)}var je=(n=>(n[n.Dark=0]="Dark",n[n.Light=1]="Light",n))(je||{});function B_(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 K_{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,a=new URL(o,new URL(this._manifestLocation,window.location.origin)),c=this._platform.request(a,{method:"GET",format:"text",cache:!0}).response();e.push(c);const l=r.searchParams;t[s]={svg:c,primary:l.get("primary"),secondary:l.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:a}=await i;if(!r)throw new Error(`Primary color variable ${r} not in list of variables!`);const c=this._resolvedVariables[r],l=this._resolvedVariables[o],h=B_(a,c,l),d=`url('data:image/svg+xml;utf8,${encodeURIComponent(h)}')`;t[s]=d}return t}}var Us={exports:{}},$_=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(a){return s[a]}.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(l){let h,d;const u={light:function(){return!_()},dark:_,lighten:S,darken:b,saturate:k,desaturate:function(w=0){return k(w*=-1)},increaseContrast:function(w=0){return R(w*=-1)},decreaseContrast:R,active:function(){return R(.123)},highlight:function(){return R(.1)},selected:function(){return R(.066)},text:function(){return d=f()?i("#333333"):i("#FFFFFF"),u},shadow:function(){return d=f()?i("#000000"):i("#FFFFFF"),u},hex:function(){const w=d;return d=h,"#"+w.map(I=>parseInt(I+"",10).toString(16).padStart(2,"0")).join("")},rgb:function(){const w=d;return d=h,`rgb(${w.join()})`},rgba:function(w=1){const I=d;return d=h,`rgba(${I.join()}, ${w})`},setHex:p,setRgb:function(w=[0,0,0]){let[I,x,D]=w;return I=c(I,0,255),x=c(x,0,255),D=c(D,0,255),h=[I,x,D],d=[I,x,D],u}};function p(w="#000000"){return h=i(w),d=h,u}function _(){const[w,I,x]=d;return d=h,(299*w+587*I+114*x)/1e3<128}function f(){const[w,I,x]=d;return(299*w+587*I+114*x)/1e3>=128}function b(w=0){return S(w*=-1)}function S(w=0){let[I,x,D]=a(d);return D=c(D+w,0,1),d=r([I,x,D]),u}function k(w=0){let[I,x,D]=a(d);return x=c(x+w,0,1),d=r([I,x,D]),u}function R(w=0){return f()?b(w):S(w)}return p(l),u}function i(l){if(typeof l!="string")throw new TypeError("Expected a string");(l=l.replace(/^#/,"")).length===3&&(l=l[0]+l[0]+l[1]+l[1]+l[2]+l[2]);var h=parseInt(l,16);return[h>>16,h>>8&255,255&h]}function r(l){const[h,d,u]=l;let p,_,f;if(d===0)p=_=f=u;else{const b=function(R,w,I){return I<0&&(I+=1),I>1&&(I-=1),I<.16666666666666666?R+6*(w-R)*I:I<.5?w:I<.6666666666666666?R+(w-R)*(.6666666666666666-I)*6:R},S=u<.5?u*(1+d):u+d-u*d,k=2*u-S;p=c(b(k,S,h+1/3),0,1),_=c(b(k,S,h),0,1),f=c(b(k,S,h-1/3),0,1)}return[Math.round(255*p),Math.round(255*_),Math.round(255*f)]}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 a});const o=s;function a(l){const h=l[0]/255,d=l[1]/255,u=l[2]/255,p=Math.max(h,d,u),_=Math.min(h,d,u);let f=(p+_)/2,b=(p+_)/2;const S=(p+_)/2;if(p===_)f=b=0;else{const k=p-_;switch(b=S>.5?k/(2-p-_):k/(p+_),p){case h:f=(d-u)/k+(d<u?6:0);break;case d:f=(u-h)/k+2;break;case u:f=(h-d)/k+4}f/=6}return[f,b,S]}function c(l,h,d){return l=(l=l<=d?l:d)>=h?l:h}}]);Us.exports=$_;var Go=Us.exports,Cn;const En=(Cn=Us.exports.offColor)!=null?Cn:Go.offColor;function kn(n,e,t,s){const i=parseInt(t);switch(s&&(e==="darker"?e="lighter":e==="lighter"&&(e="darker")),e){case"darker":return En(n).darken(i/100).hex();case"lighter":return En(n).lighten(i/100).hex()}}class j_{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,a=this._baseVariables[i];if(!a)if(this._aliases[i]){this._derivedAliases.push(e);return}else throw new Error(`Cannot find value for base variable "${i}"!`);return kn(a,r,o,this._isDark)}}_deriveAlias(e,t){const s=/(.+)--(.+)-(.+)/,i=e.match(s);if(i){const[,r,o,a]=i,c=t[r];if(!c)throw new Error(`Cannot find value for alias "${r}" when trying to derive ${e}!`);return kn(c,o,a,this._isDark)}}}var Tn;(Tn=Us.exports.offColor)!=null||Go.offColor;class q_{constructor(e,t){this._themeMapping={},this._preferredColorScheme=t,this._platform=e}async parse(e,t,s,i){await i.wrap("RuntimeThemeParser.parse",async()=>{var d;const{cssLocation:r,derivedVariables:o,icons:a}=this._getSourceData(t,s,i),c=e.name;if(!c)throw new Error("Theme name not found in manifest!");let l={},h={};for(const[u,p]of Object.entries((d=e.values)==null?void 0:d.variants))try{const _=`${e.id}-${u}`,{name:f,default:b,dark:S,variables:k}=p,R=new j_(k,o,S).toVariables();Object.assign(k,R);const w=await new K_(this._platform,a,k,s).toVariables();Object.assign(k,R,w);const I=`${c} ${f}`;if(b){Object.assign(S?l:h,{variantName:f,id:_,cssLocation:r,variables:k});continue}this._themeMapping[I]={cssLocation:r,id:_,variables:k}}catch(_){console.error(_);continue}if(l.id&&h.id){const u=this._preferredColorScheme===je.Dark?l:h;this._themeMapping[c]={dark:l,light:h,default:u}}else{const u=l.id?l:h;this._themeMapping[`${c} ${u.variantName}`]={id:u.id,cssLocation:u.cssLocation}}})}_getSourceData(e,t,s){return s.wrap("getSourceData",()=>{var c,l,h;const i=(c=e.source)==null?void 0:c["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=(l=e.source)==null?void 0:l["derived-variables"];if(!o)throw new Error(`Derived variables not found in source section for theme at ${t}`);const a=(h=e.source)==null?void 0:h.icon;if(!a)throw new Error(`Icon mapping not found in source section for theme at ${t}`);return{cssLocation:r,derivedVariables:o,icons:a}})}get themeMapping(){return this._themeMapping}}class W_{constructor(e){this._themeMapping={},this._preferredColorScheme=e}parse(e,t,s){s.wrap("BuiltThemeParser.parse",()=>{var c,l,h;const i=(c=e.source)==null?void 0:c["built-assets"],r=e.name;if(!r)throw new Error(`Theme name not found in manifest at ${t}`);let o={},a={};for(let[d,u]of Object.entries(i)){try{u=new URL(u,new URL(t,window.location.origin)).href}catch{continue}const p=(l=d.match(/.+-(.+)/))==null?void 0:l[1],_=(h=e.values)==null?void 0:h.variants[p];if(!_)throw new Error(`Variant ${p} is missing in manifest at ${t}`);const{name:f,default:b,dark:S}=_,k=`${r} ${f}`;if(b){const R=S?o:a;R.variantName=f,R.id=d,R.cssLocation=u;continue}this._themeMapping[k]={cssLocation:u,id:d}}if(o.id&&a.id){const d=this._preferredColorScheme===je.Dark?o:a;this._themeMapping[r]={dark:o,light:a,default:d}}else{const d=o.id?o:a;this._themeMapping[`${r} ${d.variantName}`]={id:d.id,cssLocation:d.cssLocation}}})}get themeMapping(){return this._themeMapping}}class H_{constructor(e){this._platform=e}async init(e,t){await this._platform.logger.wrapOrRun(t,"ThemeLoader.init",async s=>{const i=await Promise.all(e.map(c=>this._platform.request(c,{method:"GET",format:"json",cache:!0}).response())),r=new q_(this._platform,this.preferredColorScheme),o=new W_(this.preferredColorScheme),a=[];for(let c=0;c<i.length;++c){const{body:l}=i[c];try{if(l.extends){const h=i.findIndex(_=>_.body.id===l.extends);if(h===-1)throw new Error(`Base manifest for derived theme at ${e[c]} not found!`);const{body:d}=i[h],u=e[h],p=r.parse(l,d,u,s);a.push(p)}else o.parse(l,e[c],s)}catch(h){console.error(h)}}await Promise.all(a),this._themeMapping=ft(ft({},o.themeMapping),r.themeMapping),Object.assign(this._themeMapping,o.themeMapping,r.themeMapping),this._addDefaultThemeToMapping(s),s.log({l:"Preferred colorscheme",scheme:this.preferredColorScheme===je.Dark?"dark":"light"}),s.log({l:"Result",themeMapping:this._themeMapping})})}setTheme(e,t,s){this._platform.logger.wrapOrRun(s,{l:"change theme",name:e,variant:t},()=>{let i,r,o=this._themeMapping[e];if("id"in o)i=o.cssLocation,r=o.variables;else{if(!t)throw new Error("themeVariant is undefined!");i=o[t].cssLocation,r=o[t].variables}this._platform.replaceStylesheet(i),r?(s==null||s.log({l:"Derived Theme",variables:r}),this._injectCSSVariables(r)):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 je.Dark:return(e=this._platform.config.defaultTheme)==null?void 0:e.dark;case je.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 je.Dark;if(window.matchMedia("(prefers-color-scheme: light)").matches)return je.Light}}function Rn(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 z_(n){return window.msCrypto&&!window.crypto&&(window.crypto=window.msCrypto),n?(window.WebAssembly?(await Rn(n.wasmBundle),await window.Olm.init({locateFile:()=>n.wasm})):(await Rn(n.legacyBundle),await window.Olm.init()),window.Olm):null}function G_(n){return n.startsWith("/")?n:new URL(n,document.location.href).pathname}async function J_(n){const e=new d_(n.worker,4);return await e.init(),await e.sendAll({type:"load_olm",path:G_(n.olm.legacyBundle)}),new km(e)}function Q_(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 a=t.offsetTop+t.offsetHeight-window.visualViewport.height;n.style.setProperty("--ios-viewport-height",window.visualViewport.height.toString()+"px"),n.style.setProperty("--ios-viewport-top",a.toString()+"px"),s&&(o=s.offsetHeight,s.scrollTop=i+r-o)};return window.visualViewport.addEventListener("resize",e),()=>{window.visualViewport.removeEventListener("resize",e)}}class Y_{constructor({container:e,assetPaths:t,config:s,configURL:i,options:r=null,cryptoExtras:o=null}){this._container=e,this._assetPaths=t,this._config=s,this._configURL=i,this.settingsStorage=new pm("hydrogen_setting_v1_"),this.clock=new Jp,this.encoding=new Em,this.random=Math.random,this._createLogger(r==null?void 0:r.development),this.history=new Xp,this.onlineStatus=new Zp,this._serviceWorkerHandler=null,t.serviceWorker&&"serviceWorker"in navigator&&(this._serviceWorkerHandler=new Qp,this._serviceWorkerHandler.registerAndStart(t.serviceWorker)),this.notificationService=void 0,this._assetPaths.olm&&(this.crypto=new a_(o)),this.storageFactory=new nl(this._serviceWorkerHandler),this.sessionInfoStorage=new mm("hydrogen_sessions_v1"),this.estimateStorageUsage=c_,typeof fetch=="function"?this.request=um(this.clock.createTimeout,this._serviceWorkerHandler):this.request=Co;const a=!!window.MSInputMethodContext&&!!document.documentMode;this.isIE11=a;const c=/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1&&!window.MSStream;this.isIOS=c,this._disposables=new Ni,this._olmPromise=void 0,this._workerPromise=void 0,this._themeLoader=new H_(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 Yp(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}),this._themeLoader.setTheme(i,r,e)}})}catch(e){throw this._container.innerText=e.message,e}}_createLogger(e){const t=s=>{var i;return(i=s.e)!=null&&i.stack&&(s.e.stack=s.e.stack.replace(/\/\?loginToken=(.+)/,"?loginToken=<snip>")),s};e?this.logger=new td({platform:this}):this.logger=new Rm({name:"hydrogen_logs",platform:this,serializedTransformer:t})}get updateService(){return this._serviceWorkerHandler}loadOlm(){return this._olmPromise||(this._olmPromise=z_(this._assetPaths.olm)),this._olmPromise}get config(){return this._config}async loadOlmWorker(){if(!window.WebAssembly)return this._workerPromise||(this._workerPromise=J_(this._assetPaths)),this._workerPromise}createAndMountRootView(e){if(this.isIE11&&(this._container.className+=" legacy"),this.isIOS){this._container.className+=" ios";const s=Q_(this._container);s&&this._disposables.track(s)}this._container.addEventListener("error",hn,!0),this._disposables.track(()=>this._container.removeEventListener("error",hn,!0)),window.__hydrogenViewModel=e;const t=new Wp(e);this._container.appendChild(t.mount())}setNavigation(e){var t;(t=this._serviceWorkerHandler)==null||t.setNavigation(e)}createBlob(e,t){return lt.fromBuffer(e,t)}saveFileAs(e,t){navigator.msSaveBlob?navigator.msSaveBlob(e.nativeBlob,t):p_(this._container,this._assetPaths.downloadSandbox,e,t,this.isIOS)}openFile(e=null){const t=document.createElement("input");t.setAttribute("type","file"),t.className="hidden",e&&t.setAttribute("accept",e);const 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:lt.fromBlob(o)}):i()};t.addEventListener("change",r,!0)});return this._container.appendChild(t),t.click(),s}openUrl(e){location.href=e}parseHTML(e){return F_(e)}async loadImage(e){return Zt.fromBlob(e)}async loadVideo(e){return Gi.fromBlob(e)}hasReadPixelPermission(){return u_()}get devicePixelRatio(){return window.devicePixelRatio||1}get version(){return"0.3.1"}get themeLoader(){return this._themeLoader}replaceStylesheet(e){const t=document.querySelector("head");document.querySelectorAll(".theme").forEach(i=>i.remove());const s=document.createElement("link");s.href=e,s.rel="stylesheet",s.type="text/css",s.className="theme",t.appendChild(s)}get description(){var e;return(e=navigator.userAgent)!=null?e:"<unknown>"}dispose(){this._disposables.dispose()}}var X_="./config.json",Z_="./assets/download-sandbox.48a866e9.html",ef="./assets/main.bdb9a925.js",tf="./assets/olm.b3e0f9b4.wasm",sf="./assets/olm.92f1ccd0.js",rf="./assets/olm_legacy.9dc48f49.js",Jo={downloadSandbox:Z_,worker:ef,olm:{wasm:tf,legacyBundle:rf,wasmBundle:sf}};Jo.serviceWorker="sw.js";const nf=new Y_({container:document.body,assetPaths:Jo,configURL:X_,options:{development:!1}});am(nf);
//# sourceMappingURL=index.ca5690cf.js.map