@element-hq/element-call-embedded 0.10.0-rc.1 → 0.10.0-release-test.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-MJ21HWfZ.js","./matrix-sdk-crypto-wasm-D9e1T4vy.js","./polyfill-force-D1fv9_K0.js","./index-CXrddvUr.js","./polyfill-force-CykjiN0j.js"])))=>i.map(i=>d[i]);
2
- try{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="d3dc8af7-f29e-4b70-bce7-c15b0d64adfb",n._sentryDebugIdIdentifier="sentry-dbid-d3dc8af7-f29e-4b70-bce7-c15b0d64adfb")}catch{}function Bre(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};n.SENTRY_RELEASE={id:"embedded-v0.10.0-rc.1"}}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var HKe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qo(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function BKe(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var UT={exports:{}},$m={},FT={exports:{}},yt={};/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-mR1dxpYl.js","./matrix-sdk-crypto-wasm-D9e1T4vy.js","./polyfill-force-C4tXbxYu.js","./index-C-at1qWM.js","./polyfill-force-49S7yrpS.js"])))=>i.map(i=>d[i]);
2
+ try{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="524d25e4-4fd4-4fd6-b147-6b3c5ca367e4",n._sentryDebugIdIdentifier="sentry-dbid-524d25e4-4fd4-4fd6-b147-6b3c5ca367e4")}catch{}function Bre(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};n.SENTRY_RELEASE={id:"embedded-v0.10.0-release-test.2"}}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var HKe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qo(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function BKe(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var UT={exports:{}},$m={},FT={exports:{}},yt={};/**
3
3
  * @license React
4
4
  * react.production.min.js
5
5
  *
@@ -30,7 +30,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
30
30
  `)+`\r
31
31
  `},t2}var Q5;function Dse(){if(Q5)return mo;Q5=1;var n=Ase(),e=Nse(),t=qP();return mo.grammar=t,mo.write=e,mo.parse=n.parse,mo.parseParams=n.parseParams,mo.parseFmtpConfig=n.parseFmtpConfig,mo.parsePayloads=n.parsePayloads,mo.parseRemoteCandidates=n.parseRemoteCandidates,mo.parseImageAttributes=n.parseImageAttributes,mo.parseSimulcastStreamList=n.parseSimulcastStreamList,mo}var mk=Dse();function KP(n,e){if(typeof n.toBase64=="function")return n.toBase64(e);var t=btoa(n.reduce((r,i)=>r+String.fromCharCode(i),""));return e.omitPadding&&(t=t.replace(/={1,2}$/,"")),e.alphabet==="base64url"&&(t=t.replace(/\+/g,"-").replace(/\//g,"_")),t}function D_(n){return KP(n,{alphabet:"base64",omitPadding:!1})}function mH(n){return KP(n,{alphabet:"base64",omitPadding:!0})}function PE(n){return KP(n,{alphabet:"base64url",omitPadding:!0})}function jse(n,e){return typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(n,e):Uint8Array.from(atob(n),t=>t.charCodeAt(0))}function Oh(n){return jse(n.replace(/-/g,"+").replace(/_/g,"/"),{alphabet:"base64",lastChunkHandling:"loose"})}var Use="abcdefghijklmnopqrstuvwxyz",Fse="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$se="0123456789";function gH(n){var e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),PE(e)}function bs(n){return Hse(n,Fse+Use+$se)}function Hse(n,e){if(e.length<2||e.length>256)throw new Error("Character set must be between 2 and 256 characters long");if(n<1||n>32768)throw new Error("Requested random string length must be between 1 and 32768");for(var t=256-256%e.length,r=new Uint8Array(Math.floor(n*1.3)),i=r.length,s=[];s.length<n;){i===r.length&&(globalThis.crypto.getRandomValues(r),i=0);var o=r[i++];o<t&&s.push(e[o%e.length])}return s.join("")}var pc="org.matrix.msc3077.sdp_stream_metadata",sn=function(n){return n.Usermedia="m.usermedia",n.Screenshare="m.screenshare",n}({}),qg=null,gk=0,Bse=()=>(qg===null&&(qg=new AudioContext),gk++,qg),Vse=()=>{if(gk--,gk===0){var n;(n=qg)===null||n===void 0||n.close(),qg=null}},qse=200,vk=-60,Kse=8,ia=function(n){return n.NewStream="new_stream",n.MuteStateChanged="mute_state_changed",n.LocalVolumeChanged="local_volume_changed",n.VolumeChanged="volume_changed",n.ConnectedChanged="connected_changed",n.Speaking="speaking",n.Disposed="disposed",n}({});class dl extends En{constructor(e){super(),L(this,"stream",void 0),L(this,"sdpMetadataStreamId",void 0),L(this,"userId",void 0),L(this,"deviceId",void 0),L(this,"purpose",void 0),L(this,"speakingVolumeSamples",void 0),L(this,"client",void 0),L(this,"call",void 0),L(this,"roomId",void 0),L(this,"audioMuted",void 0),L(this,"videoMuted",void 0),L(this,"localVolume",1),L(this,"measuringVolumeActivity",!1),L(this,"audioContext",void 0),L(this,"analyser",void 0),L(this,"frequencyBinCount",void 0),L(this,"speakingThreshold",vk),L(this,"speaking",!1),L(this,"volumeLooperTimeout",void 0),L(this,"_disposed",!1),L(this,"_connected",!1),L(this,"onAddTrack",()=>{this.emit(ia.NewStream,this.stream)}),L(this,"onCallState",t=>{t===rt.Connected?this.connected=!0:t===rt.Connecting&&(this.connected=!1)}),L(this,"volumeLooper",()=>{if(this.analyser&&this.measuringVolumeActivity){this.analyser.getFloatFrequencyData(this.frequencyBinCount);var t=-1/0;for(var r of this.frequencyBinCount)r>t&&(t=r);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(t),this.emit(ia.VolumeChanged,t);var i=!1;for(var s of this.speakingVolumeSamples)if(s>this.speakingThreshold){i=!0;break}this.speaking!==i&&(this.speaking=i,this.emit(ia.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,qse)}}),this.client=e.client,this.call=e.call,this.roomId=e.roomId,this.userId=e.userId,this.deviceId=e.deviceId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(Kse).fill(-1/0),this.sdpMetadataStreamId=e.stream.id,this.updateStream(null,e.stream),this.stream=e.stream,this.hasAudioTrack&&this.initVolumeMeasuring(),e.call&&(e.call.addListener(ft.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(ia.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){if(t!==e){var r=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),r&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit(ia.NewStream,this.stream)}}initVolumeMeasuring(){if(this.hasAudioTrack){this.audioContext||(this.audioContext=Bse()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1;var e=this.audioContext.createMediaStreamSource(this.stream);e.connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}}getMember(){var e,t=this.client.getRoom(this.roomId);return(e=t==null?void 0:t.getMember(this.userId))!==null&&e!==void 0?e:null}isLocal(){return this.userId===this.client.getUserId()&&(this.deviceId===void 0||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return this.stream.getAudioTracks().length===0||this.audioMuted}isVideoMuted(){return this.stream.getVideoTracks().length===0||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){e!==null&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),t!==null&&(this.videoMuted=t),this.emit(ia.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(ia.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){var e=this.client.getMediaHandler(),t=this.stream.clone();return A.log("CallFeed clone() cloning stream (originalStreamId=".concat(this.stream.id,", newStreamId").concat(t.id,")")),this.purpose===sn.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new dl({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:t,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,t;clearTimeout(this.volumeLooperTimeout),(e=this.stream)===null||e===void 0||e.removeEventListener("addtrack",this.onAddTrack),(t=this.call)===null||t===void 0||t.removeListener(ft.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,Vse()),this._disposed=!0,this.emit(ia.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(ia.LocalVolumeChanged,e)}}var Gse=3e3,yk=function(n){return n.Incoming="Call.incoming",n}({});class Wse{constructor(e){L(this,"calls",void 0),L(this,"callEventBuffer",void 0),L(this,"nextSeqByCall",new Map),L(this,"toDeviceEventBuffers",new Map),L(this,"client",void 0),L(this,"candidateEventsByCall",void 0),L(this,"eventBufferPromiseChain",void 0),L(this,"onSync",()=>{var t=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(t)):this.eventBufferPromiseChain=this.evaluateEventBuffer(t)}),L(this,"onRoomTimeline",t=>{this.callEventBuffer.push(t)}),L(this,"onToDeviceEvent",t=>{var r=t.getContent();if(!r.call_id){this.callEventBuffer.push(t);return}if(this.nextSeqByCall.has(r.call_id)||this.nextSeqByCall.set(r.call_id,0),r.seq===void 0){this.callEventBuffer.push(t);return}var i=this.nextSeqByCall.get(r.call_id)||0;if(r.seq!==i){this.toDeviceEventBuffers.has(r.call_id)||this.toDeviceEventBuffers.set(r.call_id,[]);var s=this.toDeviceEventBuffers.get(r.call_id),o=s.findIndex(u=>u.getContent().seq>r.seq);o===-1?s.push(t):s.splice(o,0,t)}else{var a=r.call_id;this.callEventBuffer.push(t),this.nextSeqByCall.set(a,r.seq+1);for(var l=this.toDeviceEventBuffers.get(a),c=l&&l.shift();c&&c.getContent().seq===this.nextSeqByCall.get(a);)this.callEventBuffer.push(c),this.nextSeqByCall.set(a,c.getContent().seq+1),c=l.shift()}}),this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(Oe.Sync,this.onSync),this.client.on(ke.Timeline,this.onRoomTimeline),this.client.on(Oe.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(Oe.Sync,this.onSync),this.client.removeListener(ke.Timeline,this.onRoomTimeline),this.client.removeListener(Oe.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){var t=this;return F(function*(){yield Promise.all(e.map(u=>t.client.decryptEventIfNeeded(u)));var r=e.filter(u=>{var f=u.getType();return f.startsWith("m.call.")||f.startsWith("org.matrix.call.")}),i=new Set;for(var s of r){var o=s.getType();(o===ee.CallAnswer||o===ee.CallHangup)&&i.add(s.getContent().call_id)}for(var a of r){var l=a.getType(),c=a.getContent().call_id;if(!(l===ee.CallInvite&&i.has(c)))try{yield t.handleCallEvent(a)}catch(u){A.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",u)}}})()}handleCallEvent(e){var t=this;return F(function*(){var r;t.client.emit(Oe.ReceivedVoipEvent,e);var i=e.getContent(),s=e.getRoomId()||((r=t.client.groupCallEventHandler.getGroupCallById(i.conf_id))===null||r===void 0||(r=r.room)===null||r===void 0?void 0:r.roomId),o=i.conf_id,a=e.getType(),l=e.getSender(),c=i.call_id?t.calls.get(i.call_id):void 0,u,f;if(o){if(f=t.client.groupCallEventHandler.getGroupCallById(o),!f){A.warn("CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=".concat(o,", type=").concat(a,")"));return}if(u=i.device_id,!u){A.warn("CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=".concat(l,")")),f.emit(rn.Error,new _H(l));return}if(i.dest_session_id!==t.client.getSessionId()){A.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");return}}var p=l===t.client.credentials.userId&&(u===void 0||u===t.client.getDeviceId());if(s){if(a===ee.CallInvite){var m,v,g;if(p||e.getLocalAge()>i.lifetime-Gse||c&&c.state===rt.Ended||(c&&A.warn("CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=".concat(i.call_id,")")),i.invitee&&i.invitee!==t.client.getUserId()))return;var S=((m=t.client.getTurnServersExpiry())!==null&&m!==void 0?m:0)-Date.now();if(A.info("CallEventHandler handleCallEvent() current turn creds expire in "+S+" ms"),c=(v=Iv(t.client,s,{forceTURN:t.client.forceTURN,opponentDeviceId:u,groupCallId:o,opponentSessionId:i.sender_session_id}))!==null&&v!==void 0?v:void 0,!c){A.log("CallEventHandler handleCallEvent() this client does not support WebRTC (callId=".concat(i.call_id,")"));return}c.callId=i.call_id;var b=(g=f)===null||g===void 0?void 0:g.getGroupCallStats();b&&c.initStats(b);try{yield c.initWithInvite(e)}catch(N){if(N instanceof tl)if(N.code===Gg.UnknownDevice){var w;(w=f)===null||w===void 0||w.emit(rn.Error,N)}else A.error(N)}if(t.calls.set(c.callId,c),t.candidateEventsByCall.get(c.callId))for(var k of t.candidateEventsByCall.get(c.callId))c.onRemoteIceCandidatesReceived(k);var R;for(var I of t.calls.values()){var C,x=[rt.WaitLocalMedia,rt.CreateOffer,rt.InviteSent].includes(I.state);if(c.roomId===I.roomId&&I.direction===wc.Outbound&&((C=c.getOpponentMember())===null||C===void 0?void 0:C.userId)===I.invitee&&x){R=I;break}}R?R.callId>c.callId?(A.log("CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=".concat(c.callId,", outgoingId=").concat(R.callId,")")),R.replacedBy(c)):(A.log("CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=".concat(c.callId,", outgoingId=").concat(R.callId,")")),c.hangup(ct.Replaced,!0)):t.client.emit(yk.Incoming,c);return}else if(a===ee.CallCandidates){if(p)return;c?c.onRemoteIceCandidatesReceived(e):(t.candidateEventsByCall.has(i.call_id)||t.candidateEventsByCall.set(i.call_id,[]),t.candidateEventsByCall.get(i.call_id).push(e));return}else if([ee.CallHangup,ee.CallReject].includes(a)){if(c)c.state!==rt.Ended&&(a===ee.CallHangup?c.onHangupReceived(i):c.onRejectReceived(i),c.state===rt.Ended&&t.calls.delete(i.call_id));else{var O;c=(O=Iv(t.client,s,{opponentDeviceId:u,opponentSessionId:i.sender_session_id}))!==null&&O!==void 0?O:void 0,c&&(c.callId=i.call_id,c.initWithHangup(e),t.calls.set(i.call_id,c))}return}if(!c||!c.hasPeerConnection){A.info("CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=".concat(a,")"));return}if(e.getContent().party_id!==c.ourPartyId)switch(a){case ee.CallAnswer:p?c.state===rt.Ringing&&c.onAnsweredElsewhere(i):c.onAnswerReceived(e);break;case ee.CallSelectAnswer:c.onSelectAnswerReceived(e);break;case ee.CallNegotiate:c.onNegotiateReceived(e);break;case ee.CallAssertedIdentity:case ee.CallAssertedIdentityPrefix:c.onAssertedIdentityReceived(e);break;case ee.CallSDPStreamMetadataChanged:case ee.CallSDPStreamMetadataChangedPrefix:c.onSDPStreamMetadataChangedReceived(e);break}}})()}}var _k=function(n){return n.Incoming="GroupCall.incoming",n.Outgoing="GroupCall.outgoing",n.Ended="GroupCall.ended",n.Participants="GroupCall.participants",n}({});class zse{constructor(e){this.client=e,L(this,"groupCalls",new Map),L(this,"roomDeferreds",new Map),L(this,"onRoomsChanged",t=>{this.createGroupCallForRoom(t)}),L(this,"onRoomStateChanged",(t,r)=>{var i=t.getType();if(i===ee.GroupCallPrefix){var s=t.getStateKey(),o=t.getContent(),a=this.groupCalls.get(r.roomId);!a&&!o["m.terminated"]&&!t.isRedacted()?this.createGroupCallFromRoomStateEvent(t):a&&a.groupCallId===s?o["m.terminated"]||t.isRedacted()?a.terminate(!1):o["m.type"]!==a.type&&A.warn("GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=".concat(r.roomId,")")):a&&a.groupCallId!==s&&A.warn("GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=".concat(r.roomId,")"))}})}start(){var e=this;return F(function*(){e.client.getSyncState()!==Dt.Syncing&&(A.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise(i=>{var s=()=>{if(e.client.getSyncState()===Dt.Syncing)return e.client.off(Oe.Sync,s),i()};e.client.on(Oe.Sync,s)}));var t=e.client.getRooms();for(var r of t)e.createGroupCallForRoom(r);e.client.on(Oe.Room,e.onRoomsChanged),e.client.on(ut.Events,e.onRoomStateChanged)})()}stop(){this.client.removeListener(Oe.Room,this.onRoomsChanged),this.client.removeListener(ut.Events,this.onRoomStateChanged)}getRoomDeferred(e){var t=this.roomDeferreds.get(e);if(t===void 0){var r;t={prom:new Promise(i=>{r=i})},t.resolve=r,this.roomDeferreds.set(e,t)}return t}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find(t=>t.groupCallId===e)}createGroupCallForRoom(e){var t=e.currentState.getStateEvents(ee.GroupCallPrefix),r=t.sort((o,a)=>a.getTs()-o.getTs());for(var i of r){var s=i.getContent();if(!(s["m.terminated"]||i.isRedacted())){A.debug("GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=".concat(i.getStateKey(),", ts=").concat(i.getTs(),", roomId=").concat(e.roomId,", numOfPossibleCalls=").concat(t.length,")")),this.createGroupCallFromRoomStateEvent(i);break}}this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){var t=e.getRoomId(),r=e.getContent(),i=this.client.getRoom(t);if(!i){A.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=".concat(t,")"));return}var s=e.getStateKey(),o=r["m.type"];if(!Object.values(LE).includes(o)){A.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=".concat(o,", roomId=").concat(t,")"));return}var a=r["m.intent"];if(!Object.values(yH).includes(a)){A.warn("Received invalid group call intent (type=".concat(o,", roomId=").concat(t,")"));return}var l=!!r["io.element.ptt"],c;if(r!=null&&r.dataChannelsEnabled&&r!==null&&r!==void 0&&r.dataChannelOptions){var{ordered:u,maxPacketLifeTime:f,maxRetransmits:p,protocol:m}=r.dataChannelOptions;c={ordered:u,maxPacketLifeTime:f,maxRetransmits:p,protocol:m}}var v=new GP(this.client,i,o,l,a,s,(r==null?void 0:r.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,c,this.client.isVoipWithNoMediaAllowed,this.client.useLivekitForGroupCalls,r["io.element.livekit_service_url"]);return this.groupCalls.set(i.roomId,v),this.client.emit(_k.Incoming,v),v}}class Yse{constructor(){L(this,"bandwidth",{}),L(this,"bitrate",{}),L(this,"packetLoss",{}),L(this,"transport",[])}}class Jse{static buildBandwidthReport(e){var t=e.availableIncomingBitrate,r=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:r?Math.round(r/1e3):0}}}class Xse{static buildReport(e,t,r,i){var s=e==null?void 0:e.get(t.localCandidateId),o=e==null?void 0:e.get(t.remoteCandidateId);if(o&&s){var a=o.ip!==void 0?o.ip:o.address,l=o.port,c="".concat(a,":").concat(l),u=s.ip!==void 0?s.ip:s.address,f=s.port,p="".concat(u,":").concat(f),m=o.protocol;r.some(v=>v.ip===c&&v.type===m&&v.localIp===p)||r.push({ip:c,type:m,localIp:p,isFocus:i,localCandidateType:s.candidateType,remoteCandidateType:o.candidateType,networkType:s.networkType,rtt:t.currentRoundTripTime?t.currentRoundTripTime*1e3:NaN})}return r}}class Zse{constructor(){L(this,"ssrcToMid",{local:new Map,remote:new Map})}findMidBySsrc(e,t){var r;return this.ssrcToMid[t].forEach((i,s)=>{if(i.find(o=>o==e)){r=s;return}}),r}parse(e,t){var r=mk.parse(e),i=new Map;r.media.forEach(s=>{if(s.mid&&s.type==="video"||s.type==="audio"){var o,a=[];(o=s.ssrcs)===null||o===void 0||o.forEach(l=>{l.attribute==="cname"&&a.push("".concat(l.id))}),i.set("".concat(s.mid),a)}}),this.ssrcToMid[t]=i}getSsrcToMidMap(e){return this.ssrcToMid[e]}}class Qse{constructor(e){this.pc=e}getLocalTracks(e){var t=r=>r!==null&&r.kind===e;return this.pc.getTransceivers().filter(r=>r.currentDirection==="sendonly"||r.currentDirection==="sendrecv").filter(r=>r.sender!==null).map(r=>r.sender).map(r=>r.track).filter(t)}getTackById(e){return this.pc.getTransceivers().map(t=>{if((t==null?void 0:t.sender.track)!==null&&t.sender.track.id===e)return t.sender.track;if((t==null?void 0:t.receiver.track)!==null&&t.receiver.track.id===e)return t.receiver.track}).find(t=>t!==void 0)}getLocalTrackIdByMid(e){var t,r=this.pc.getTransceivers().find(i=>i.mid===e);return r==null||(t=r.sender)===null||t===void 0||(t=t.track)===null||t===void 0?void 0:t.id}getRemoteTrackIdByMid(e){var t,r=this.pc.getTransceivers().find(i=>i.mid===e);return r==null||(t=r.receiver)===null||t===void 0||(t=t.track)===null||t===void 0?void 0:t.id}getActiveSimulcastStreams(){return 3}getTransceiverByTrackId(e){return this.pc.getTransceivers().find(t=>t.receiver.track.id===e||t.sender.track!==null&&t.sender.track.id===e)}}class eoe{constructor(e,t,r){this.trackId=e,this.type=t,this.kind=r,L(this,"loss",{packetsTotal:0,packetsLost:0,isDownloadStream:!1}),L(this,"bitrate",{download:0,upload:0}),L(this,"resolution",{width:-1,height:-1}),L(this,"audioConcealment",{concealedAudio:0,totalAudioDuration:0}),L(this,"framerate",0),L(this,"jitter",0),L(this,"codec",""),L(this,"isAlive",!0),L(this,"isMuted",!1),L(this,"isEnabled",!0)}getType(){return this.type}setLoss(e){this.loss=e}getLoss(){return this.loss}setResolution(e){this.resolution=e}getResolution(){return this.resolution}setFramerate(e){this.framerate=e}getFramerate(){return this.framerate}setBitrate(e){this.bitrate=e}getBitrate(){return this.bitrate}setCodec(e){return this.codec=e,!0}getCodec(){return this.codec}resetBitrate(){this.bitrate={download:0,upload:0}}set alive(e){this.isAlive=e}get alive(){return this.isAlive}set muted(e){this.isMuted=e}get muted(){return this.isMuted}set enabled(e){this.isEnabled=e}get enabled(){return this.isEnabled}setJitter(e){this.jitter=e}getJitter(){return this.jitter}setAudioConcealment(e,t){this.audioConcealment.concealedAudio=e,this.audioConcealment.totalAudioDuration=t}getAudioConcealment(){return this.audioConcealment}}class toe{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,L(this,"track2stats",new Map)}findTrack2Stats(e,t){var r;if(e.trackIdentifier)r=e.trackIdentifier;else if(e.mid)r=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){var i=this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t);if(!i)return;r=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(r){var s=this.track2stats.get(r);if(!s){var o=this.mediaTrackHandler.getTackById(r);if(o!==void 0){var a=o.kind==="audio"?o.kind:"video";s=new eoe(r,t,a),this.track2stats.set(r,s)}else return}return s}}findLocalVideoTrackStats(e){var t=this.mediaTrackHandler.getLocalTracks("video");if(t.length!==0)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}findTransceiverByTrackId(e){return this.mediaTrackHandler.getTransceiverByTrackId(e)}}class sd{static getNonNegativeValue(e){var t=e;return typeof t!="number"&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}class hs{static buildFramerateResolution(e,t){var r={height:t.frameHeight,width:t.frameWidth},i=t.framesPerSecond;r.height&&r.width&&e.setResolution(r),e.setFramerate(Math.round(i||0))}static calculateSimulcastFramerate(e,t,r,i){var s=e.getFramerate();if(!s){if(r){var o=t.timestamp-r.timestamp;if(o>0&&t.framesSent){var a=t.framesSent-r.framesSent;s=a/o*1e3}}if(!s)return}s=i?Math.round(s/i):0,e.setFramerate(s)}static buildCodec(e,t,r){var i=e==null?void 0:e.get(r.codecId);if(i){var s=i.mimeType.split("/")[1];s&&t.setCodec(s)}}static buildBitrateReceived(e,t,r){e.setBitrate({download:hs.calculateBitrate(t.bytesReceived,r.bytesReceived,t.timestamp,r.timestamp),upload:0})}static buildBitrateSend(e,t,r){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,r.bytesSent,t.timestamp,r.timestamp)})}static buildPacketsLost(e,t,r){var i=t.type==="outbound-rtp"?"packetsSent":"packetsReceived",s=t[i];(!s||s<0)&&(s=0);var o=sd.getNonNegativeValue(r[i]),a=Math.max(0,s-o),l=sd.getNonNegativeValue(t.packetsLost),c=sd.getNonNegativeValue(r.packetsLost),u=Math.max(0,l-c);e.setLoss({packetsTotal:a+u,packetsLost:u,isDownloadStream:t.type!=="outbound-rtp"})}static calculateBitrate(e,t,r,i){var s=sd.getNonNegativeValue(e),o=sd.getNonNegativeValue(t),a=Math.max(0,s-o),l=r-i,c=0;return l>0&&(c=Math.round(a*8/l)),c}static setTrackStatsState(e,t){var r;if(t===void 0){e.alive=!1;return}var i=e.getType()==="remote"?t.receiver.track:t==null||(r=t.sender)===null||r===void 0?void 0:r.track;if(i==null){e.alive=!1;return}if(i.readyState==="ended"){e.alive=!1;return}e.muted=i.muted,e.enabled=i.enabled,e.alive=!0}static buildTrackSummary(e){var t={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},r={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},i=e.filter(o=>o.getType()==="remote"),s=i.filter(o=>o.kind==="audio");return i.forEach(o=>{var a=o.kind==="video"?t:r;if(a.count++,o.alive&&o.muted&&a.muted++,a.maxJitter<o.getJitter()&&(a.maxJitter=o.getJitter()),a.maxPacketLoss<o.getLoss().packetsLost&&(a.maxPacketLoss=o.getLoss().packetsLost),s.length>0){var l,c;a.concealedAudio+=(l=o.getAudioConcealment())===null||l===void 0?void 0:l.concealedAudio,a.totalAudio+=(c=o.getAudioConcealment())===null||c===void 0?void 0:c.totalAudioDuration}}),{audioTrackSummary:r,videoTrackSummary:t}}static buildJitter(e,t){if(t.type==="inbound-rtp"){var r=t==null?void 0:t.jitter;if(r!==void 0){var i=sd.getNonNegativeValue(r);e.setJitter(Math.round(i*1e3))}else e.setJitter(-1)}}static buildAudioConcealment(e,t){if(t.type==="inbound-rtp"){var r=1e3*(t==null?void 0:t.totalSamplesDuration)/(t==null?void 0:t.totalSamplesReceived),i=r*(t==null?void 0:t.concealedSamples),s=1e3*(t==null?void 0:t.totalSamplesDuration);e.setAudioConcealment(i,s)}}}class Kg{static build(e){var t={},r={download:0,upload:0},i={download:0,upload:0},s=0,o=0,a={local:new Map,remote:new Map},l={local:new Map,remote:new Map},c={local:new Map,remote:new Map},u=new Map,f=new Map,p=0,m=0,v=0,g=0,S=0,b=0;for(var[w,k]of e){var R=k.getLoss(),I=R.isDownloadStream?"download":"upload";if(r[I]+=R.packetsTotal,i[I]+=R.packetsLost,s+=k.getBitrate().download,o+=k.getBitrate().upload,k.kind==="audio"){var C=k.getAudioConcealment();S+=C.concealedAudio,b+=C.totalAudioDuration,p+=k.getBitrate().download,m+=k.getBitrate().upload}else v+=k.getBitrate().download,g+=k.getBitrate().upload;a[k.getType()].set(w,k.getResolution()),l[k.getType()].set(w,k.getFramerate()),c[k.getType()].set(w,k.getCodec()),k.getType()==="remote"&&(u.set(w,k.getJitter()),k.kind==="audio"&&f.set(w,k.getAudioConcealment())),k.resetBitrate()}return t.bitrate={upload:o,download:s},t.bitrate.audio={upload:m,download:p},t.bitrate.video={upload:g,download:v},t.packetLoss={total:Kg.calculatePacketLoss(i.download+i.upload,r.download+r.upload),download:Kg.calculatePacketLoss(i.download,r.download),upload:Kg.calculatePacketLoss(i.upload,r.upload)},t.audioConcealment=f,t.totalAudioConcealment={concealedAudio:S,totalAudioDuration:b},t.framerate=l,t.resolution=a,t.codec=c,t.jitter=u,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}class Dc{static buildCallFeedReport(e,t,r){var i=r.getTransceivers(),s=[],o=[];return i.forEach(a=>{var l,c=(l=a.sender)!==null&&l!==void 0&&l.track?Dc.buildTrackStats(a.sender.track,"sender"):null,u=Dc.buildTrackStats(a.receiver.track,"receiver");s.push({mid:a.mid==null?"null":a.mid,direction:a.direction,currentDirection:a.currentDirection==null?"null":a.currentDirection,sender:c,receiver:u})}),{callId:e,opponentMemberId:t,transceiver:s,callFeeds:o}}static buildTrackStats(e){var t,r,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"--",s=(t=e.getSettings())===null||t===void 0?void 0:t.deviceId,o=(r=e.getConstraints())===null||r===void 0?void 0:r.deviceId;return{id:e.id,kind:e.kind,settingDeviceId:s??"unknown",constrainDeviceId:o??"unknown",muted:e.muted,enabled:e.enabled,readyState:e.readyState,label:i}}static expandCallFeedReport(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unknown";return t.forEach(i=>{var s=i.stream.getAudioTracks(),o=i.stream.getVideoTracks(),a=s.length>0?Dc.buildTrackStats(i.stream.getAudioTracks()[0],i.purpose):null,l=o.length>0?Dc.buildTrackStats(i.stream.getVideoTracks()[0],i.purpose):null,c={stream:i.stream.id,type:i.isLocal()?"local":"remote",audio:a,video:l,purpose:i.purpose,prefix:r,isVideoMuted:i.isVideoMuted(),isAudioMuted:i.isAudioMuted()};e.callFeeds.push(c)}),e}}function eN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function S1(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?eN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):eN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}class noe{constructor(e,t,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;this.callId=e,this.opponentMemberId=t,this.pc=r,this.emitter=i,this.isFocus=s,L(this,"isActive",!0),L(this,"previousStatsReport",void 0),L(this,"currentStatsReport",void 0),L(this,"connectionStats",new Yse),L(this,"trackStats",void 0),r.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new toe(new Zse,new Qse(r))}processStats(e,t){var r=this;return F(function*(){var i={isFirstCollection:r.previousStatsReport===void 0,receivedMedia:0,receivedAudioMedia:0,receivedVideoMedia:0,audioTrackSummary:{count:0,muted:0,maxPacketLoss:0,maxJitter:0,concealedAudio:0,totalAudio:0},videoTrackSummary:{count:0,muted:0,maxPacketLoss:0,maxJitter:0,concealedAudio:0,totalAudio:0}};if(r.isActive){var s=r.pc.getStats();if(typeof(s==null?void 0:s.then)=="function")return s.then(o=>{var a,l;r.currentStatsReport=typeof(o==null?void 0:o.result)=="function"?o.result():o;try{r.processStatsReport(e,t)}catch(u){return r.handleError(u),i}r.previousStatsReport=r.currentStatsReport,i.receivedMedia=r.connectionStats.bitrate.download,i.receivedAudioMedia=((a=r.connectionStats.bitrate.audio)===null||a===void 0?void 0:a.download)||0,i.receivedVideoMedia=((l=r.connectionStats.bitrate.video)===null||l===void 0?void 0:l.download)||0;var c=hs.buildTrackSummary(Array.from(r.trackStats.getTrack2stats().values()));return S1(S1({},i),{},{audioTrackSummary:c.audioTrackSummary,videoTrackSummary:c.videoTrackSummary})}).catch(o=>(r.handleError(o),i));r.isActive=!1}return Promise.resolve(i)})()}processStatsReport(e,t){var r,i=new Map;i.callId=this.callId,i.opponentMemberId=this.opponentMemberId,(r=this.currentStatsReport)===null||r===void 0||r.forEach(s=>{var o=this.previousStatsReport?this.previousStatsReport.get(s.id):null;if(s.type==="candidate-pair"&&s.nominated&&s.state==="succeeded")this.connectionStats.bandwidth=Jse.buildBandwidthReport(s),this.connectionStats.transport=Xse.buildReport(this.currentStatsReport,s,this.connectionStats.transport,this.isFocus);else if(s.type==="inbound-rtp"||s.type==="outbound-rtp"){var a=this.trackStats.findTrack2Stats(s,s.type==="inbound-rtp"?"remote":"local");if(!a)return;if(o&&hs.buildPacketsLost(a,s,o),s.type==="inbound-rtp"){hs.buildFramerateResolution(a,s),o&&hs.buildBitrateReceived(a,s,o);var l=this.trackStats.findTransceiverByTrackId(a.trackId);hs.setTrackStatsState(a,l),hs.buildJitter(a,s),hs.buildAudioConcealment(a,s)}else o&&(i.set(a.trackId,sd.getNonNegativeValue(s.bytesSent)),hs.buildBitrateSend(a,s,o));hs.buildCodec(this.currentStatsReport,a,s)}else if(s.type==="track"&&s.kind==="video"&&!s.remoteSource){var c=this.trackStats.findLocalVideoTrackStats(s);if(!c)return;hs.buildFramerateResolution(c,s),hs.calculateSimulcastFramerate(c,s,o,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}}),this.emitter.emitByteSendReport(i),this.emitter.emitCallFeedReport(Dc.buildCallFeedReport(this.callId,this.opponentMemberId,this.pc)),this.processAndEmitConnectionStatsReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1,A.warn("CallStatsReportGatherer ".concat(this.callId," processStatsReport fails and set to inactive ").concat(e))}processAndEmitConnectionStatsReport(){var e=Kg.build(this.trackStats.getTrack2stats());e.callId=this.callId,e.opponentMemberId=this.opponentMemberId,this.connectionStats.bandwidth=e.bandwidth,this.connectionStats.bitrate=e.bitrate,this.connectionStats.packetLoss=e.packetLoss,this.emitter.emitConnectionStatsReport(S1(S1({},e),{},{transport:this.connectionStats.transport})),this.connectionStats.transport=[]}stopProcessingStats(){}onSignalStateChange(){this.pc.signalingState==="stable"&&(this.pc.currentRemoteDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp,"remote"),this.pc.currentLocalDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp,"local"))}setOpponentMemberId(e){this.opponentMemberId=e}}var vl=function(n){return n.CONNECTION_STATS="StatsReport.connection_stats",n.CALL_FEED_REPORT="StatsReport.call_feed_report",n.BYTE_SENT_STATS="StatsReport.byte_sent_stats",n.SUMMARY_STATS="StatsReport.summary_stats",n}({});class roe extends En{emitByteSendReport(e){this.emit(vl.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(vl.CONNECTION_STATS,e)}emitCallFeedReport(e){this.emit(vl.CALL_FEED_REPORT,e)}emitSummaryStatsReport(e){this.emit(vl.SUMMARY_STATS,e)}}class vH{constructor(e){this.emitter=e}build(e){var t=e.filter(u=>!u.isFirstCollection),r=t.length,i=e.length;if(r!==0){var s={receivedAudio:0,receivedVideo:0,receivedMedia:0,concealedAudio:0,totalAudio:0},o=0,a=0;t.forEach(u=>{this.countTrackListReceivedMedia(s,u),this.countConcealedAudio(s,u),o=this.buildMaxJitter(o,u),a=this.buildMaxPacketLoss(a,u)});var l=5,c={percentageReceivedMedia:Number((s.receivedMedia/r).toFixed(l)),percentageReceivedVideoMedia:Number((s.receivedVideo/r).toFixed(l)),percentageReceivedAudioMedia:Number((s.receivedAudio/r).toFixed(l)),maxJitter:o,maxPacketLoss:a,percentageConcealedAudio:Number(s.totalAudio>0?(s.concealedAudio/s.totalAudio).toFixed(l):0),peerConnections:i};this.emitter.emitSummaryStatsReport(c)}}static extendSummaryReport(e,t){var r=[],i=[];for(var s of t){i.push(s);for(var o of s[1])r.push(o)}e.opponentDevicesInCall=Math.max(0,r.length-1),e.opponentUsersInCall=Math.max(0,i.length-1),e.diffDevicesToPeerConnections=Math.max(0,r.length-1)-e.peerConnections,e.ratioPeerConnectionToDevices=Math.max(0,r.length-1)==0?0:e.peerConnections/(r.length-1)}countTrackListReceivedMedia(e,t){var r=!1,i=!1;(t.receivedAudioMedia>0||t.audioTrackSummary.count===0)&&(e.receivedAudio++,r=!0),(t.receivedVideoMedia>0||t.videoTrackSummary.count===0||t.videoTrackSummary.muted>0&&t.videoTrackSummary.muted===t.videoTrackSummary.count)&&(e.receivedVideo++,i=!0),i&&r&&e.receivedMedia++}buildMaxJitter(e,t){return e<t.videoTrackSummary.maxJitter&&(e=t.videoTrackSummary.maxJitter),e<t.audioTrackSummary.maxJitter&&(e=t.audioTrackSummary.maxJitter),e}buildMaxPacketLoss(e,t){return e<t.videoTrackSummary.maxPacketLoss&&(e=t.videoTrackSummary.maxPacketLoss),e<t.audioTrackSummary.maxPacketLoss&&(e=t.audioTrackSummary.maxPacketLoss),e}countConcealedAudio(e,t){e.concealedAudio+=t.audioTrackSummary.concealedAudio,e.totalAudio+=t.audioTrackSummary.totalAudio}}class ioe{constructor(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e4;this.groupCallId=e,this.userId=t,this.interval=r,L(this,"timer",void 0),L(this,"gatherers",new Map),L(this,"reports",new roe),L(this,"summaryStatsReportGatherer",new vH(this.reports))}start(){this.timer===void 0&&this.interval>0&&(this.timer=setInterval(()=>{this.processStats()},this.interval))}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.gatherers.forEach(e=>e.stopProcessingStats()))}hasStatsReportGatherer(e){return this.gatherers.has(e)}addStatsReportGatherer(e,t,r){return this.hasStatsReportGatherer(e)?!1:(this.gatherers.set(e,new noe(e,t,r,this.reports)),!0)}removeStatsReportGatherer(e){return this.gatherers.delete(e)}getStatsReportGatherer(e){return this.hasStatsReportGatherer(e)?this.gatherers.get(e):void 0}updateOpponentMember(e,t){var r;(r=this.getStatsReportGatherer(e))===null||r===void 0||r.setOpponentMemberId(t)}processStats(){var e=[];this.gatherers.forEach(t=>{e.push(t.processStats(this.groupCallId,this.userId))}),Promise.all(e).then(t=>this.summaryStatsReportGatherer.build(t)).catch(t=>{A.error("Could not build summary stats report",t)})}setInterval(e){this.interval=e}}function tN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function E1(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?tN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):tN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var yH=function(n){return n.Ring="m.ring",n.Prompt="m.prompt",n.Room="m.room",n}({}),LE=function(n){return n.Video="m.video",n.Voice="m.voice",n}({}),soe=function(n){return n.CallEnded="call_ended",n}({}),rn=function(n){return n.GroupCallStateChanged="group_call_state_changed",n.ActiveSpeakerChanged="active_speaker_changed",n.CallsChanged="calls_changed",n.UserMediaFeedsChanged="user_media_feeds_changed",n.ScreenshareFeedsChanged="screenshare_feeds_changed",n.LocalScreenshareStateChanged="local_screenshare_state_changed",n.LocalMuteStateChanged="local_mute_state_changed",n.ParticipantsChanged="participants_changed",n.Error="group_call_error",n}({}),Og=function(n){return n.ConnectionStats="GroupCall.connection_stats",n.ByteSentStats="GroupCall.byte_sent_stats",n.SummaryStats="GroupCall.summary_stats",n.CallFeedStats="GroupCall.call_feed_stats",n}({}),Gg=function(n){return n.NoUserMedia="no_user_media",n.UnknownDevice="unknown_device",n.PlaceCallFailed="place_call_failed",n}({});class bk extends Error{constructor(e,t,r){r?(super(t+": "+r),L(this,"code",void 0)):(super(t),L(this,"code",void 0)),this.code=e}}class _H extends bk{constructor(e){super(Gg.UnknownDevice,"No device found for "+e),this.userId=e}}var On=function(n){return n.LocalCallFeedUninitialized="local_call_feed_uninitialized",n.InitializingLocalCallFeed="initializing_local_call_feed",n.LocalCallFeedInitialized="local_call_feed_initialized",n.Entered="entered",n.Ended="ended",n}({}),nN=1e3*60*60;function w1(n){var e;return((e=n.getOpponentMember())===null||e===void 0?void 0:e.userId)||n.invitee||null}class GP extends En{constructor(e,t,r,i,s,o,a,l,c){var u,f,p=arguments.length>9&&arguments[9]!==void 0?arguments[9]:!1,m=arguments.length>10?arguments[10]:void 0;super(),this.client=e,this.room=t,this.type=r,this.isPtt=i,this.intent=s,this.dataChannelsEnabled=a,this.dataChannelOptions=l,this.useLivekit=p,L(this,"activeSpeakerInterval",1e3),L(this,"retryCallInterval",5e3),L(this,"participantTimeout",1e3*15),L(this,"pttMaxTransmitTime",1e3*20),L(this,"activeSpeaker",void 0),L(this,"localCallFeed",void 0),L(this,"localScreenshareFeed",void 0),L(this,"localDesktopCapturerSourceId",void 0),L(this,"userMediaFeeds",[]),L(this,"screenshareFeeds",[]),L(this,"groupCallId",void 0),L(this,"allowCallWithoutVideoAndAudio",void 0),L(this,"calls",new Map),L(this,"callHandlers",new Map),L(this,"activeSpeakerLoopInterval",void 0),L(this,"retryCallLoopInterval",void 0),L(this,"retryCallCounts",new Map),L(this,"reEmitter",void 0),L(this,"transmitTimer",null),L(this,"participantsExpirationTimer",null),L(this,"resendMemberStateTimer",null),L(this,"initWithAudioMuted",!1),L(this,"initWithVideoMuted",!1),L(this,"initCallFeedPromise",void 0),L(this,"_livekitServiceURL",void 0),L(this,"stats",void 0),L(this,"statsCollectIntervalTime",0),L(this,"onConnectionStats",v=>{this.emit(Og.ConnectionStats,{report:v})}),L(this,"onByteSentStats",v=>{this.emit(Og.ByteSentStats,{report:v})}),L(this,"onSummaryStats",v=>{vH.extendSummaryReport(v,this.participants),this.emit(Og.SummaryStats,{report:v})}),L(this,"onCallFeedReport",v=>{this.localCallFeed&&(v=Dc.expandCallFeedReport(v,[this.localCallFeed],"from-local-feed"));var g=[];this.forEachCall(S=>{S.callId===v.callId&&S.getFeeds().forEach(b=>g.push(b))}),v=Dc.expandCallFeedReport(v,g,"from-call-feed"),this.emit(Og.CallFeedStats,{report:v})}),L(this,"_state",On.LocalCallFeedUninitialized),L(this,"_participants",new Map),L(this,"_creationTs",null),L(this,"_enteredViaAnotherSession",!1),L(this,"onIncomingCall",v=>{var g,S;if(v.roomId===this.room.roomId){if(v.state!==rt.Ringing){A.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call no longer in ringing state - ignoring"));return}if(!v.groupCallId||v.groupCallId!==this.groupCallId){A.log("GroupCall ".concat(this.groupCallId," onIncomingCall() ignored because it doesn't match the current group call")),v.reject();return}var b=(g=v.getOpponentMember())===null||g===void 0?void 0:g.userId;if(b===void 0){A.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call with no member - ignoring"));return}if(this.useLivekit){A.info("Received incoming call whilst in signaling-only mode! Ignoring.");return}var w=(S=this.calls.get(b))!==null&&S!==void 0?S:new Map,k=w.get(v.getOpponentDeviceId());if((k==null?void 0:k.callId)!==v.callId){A.log("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call (userId=").concat(b,", callId=").concat(v.callId,")")),k&&k.hangup(ct.Replaced,!1),w.set(v.getOpponentDeviceId(),v),this.calls.set(b,w),this.initCall(v);var R=this.getLocalFeeds().map(C=>C.clone());if(!this.callExpected(v))for(var I of R)rr(I.stream.getAudioTracks(),!1),rr(I.stream.getVideoTracks(),!1);v.answerWithCallFeeds(R),this.emit(rn.CallsChanged,this.calls)}}}),L(this,"onRetryCallLoop",()=>{var v=!1;for(var[{userId:g},S]of this.participants){var b=this.calls.get(g),w=this.retryCallCounts.get(g);for(var[k,R]of S){var I,C,x=b==null?void 0:b.get(k),O=(I=(C=w)===null||C===void 0?void 0:C.get(k))!==null&&I!==void 0?I:0;(x==null?void 0:x.getOpponentSessionId())!==R.sessionId&&this.wantsOutgoingCall(g,k)&&O<3&&(w===void 0&&(w=new Map,this.retryCallCounts.set(g,w)),w.set(k,O+1),v=!0)}}v&&this.placeOutgoingCalls()}),L(this,"onCallFeedsChanged",v=>{var g=w1(v),S=v.getOpponentDeviceId();if(!g)throw new Error("Cannot change call feeds without user id");var b=this.getUserMediaFeed(g,S),w=v.remoteUsermediaFeed,k=w!==b,R=this.calls.get(g),I=R==null?void 0:R.get(S);if((I==null?void 0:I.callId)===v.callId){k&&(!b&&w?this.addUserMediaFeed(w):b&&w?this.replaceUserMediaFeed(b,w):b&&!w&&this.removeUserMediaFeed(b));var C=this.getScreenshareFeed(g,S),x=v.remoteScreensharingFeed,O=x!==C;O&&(!C&&x?this.addScreenshareFeed(x):C&&x?this.replaceScreenshareFeed(C,x):C&&!x&&this.removeScreenshareFeed(C))}}),L(this,"onCallStateChanged",(v,g,S)=>{var b;if(g!==rt.Ended){var w=this.localCallFeed.isAudioMuted();v.localUsermediaStream&&v.isMicrophoneMuted()!==w&&v.setMicrophoneMuted(w);var k=this.localCallFeed.isVideoMuted();v.localUsermediaStream&&v.isLocalVideoMuted()!==k&&v.setLocalVideoMuted(k);var R=(b=v.getOpponentMember())===null||b===void 0?void 0:b.userId;if(g===rt.Connected&&R){var I=this.retryCallCounts.get(R);I==null||I.delete(v.getOpponentDeviceId()),(I==null?void 0:I.size)===0&&this.retryCallCounts.delete(R)}}}),L(this,"onCallHangup",v=>{var g,S;if(v.hangupReason!==ct.Replaced){var b=(g=(S=v.getOpponentMember())===null||S===void 0?void 0:S.userId)!==null&&g!==void 0?g:this.room.getMember(v.invitee).userId,w=this.calls.get(b);(w==null?void 0:w.get(v.getOpponentDeviceId()))===v&&(this.disposeCall(v,v.hangupReason),w.delete(v.getOpponentDeviceId()),w.size===0&&this.calls.delete(b),this.emit(rn.CallsChanged,this.calls))}}),L(this,"onCallReplaced",(v,g)=>{var S=v.getOpponentMember().userId,b=this.calls.get(S);b===void 0&&(b=new Map,this.calls.set(S,b)),v.hangup(ct.Replaced,!1),this.initCall(g),b.set(v.getOpponentDeviceId(),g),this.emit(rn.CallsChanged,this.calls)}),L(this,"onActiveSpeakerLoop",()=>{var v=void 0,g=void 0;for(var S of this.userMediaFeeds)if(!(S.isLocal()&&this.userMediaFeeds.length>1)){var b=S.speakingVolumeSamples.reduce((k,R)=>k+Math.max(R,vk)),w=b/S.speakingVolumeSamples.length;(!v||w>v)&&(v=w,g=S)}g&&this.activeSpeaker!==g&&v&&v>vk&&(this.activeSpeaker=g,this.emit(rn.ActiveSpeakerChanged,this.activeSpeaker))}),L(this,"onRoomState",()=>this.updateParticipants()),L(this,"onParticipantsChanged",()=>{this.forEachCall(v=>{var g=this.callExpected(v);for(var S of v.getLocalFeeds())rr(S.stream.getAudioTracks(),!S.isAudioMuted()&&g),rr(S.stream.getVideoTracks(),!S.isVideoMuted()&&g)}),this.state===On.Entered&&!this.useLivekit&&this.placeOutgoingCalls()}),L(this,"onStateChanged",(v,g)=>{(v===On.Entered||g===On.Entered||v===On.Ended)&&(this.updateParticipants(),this.updateMemberState().catch(S=>A.error("GroupCall ".concat(this.groupCallId,' onStateChanged() failed to update member state devices"'),S)))}),L(this,"onLocalFeedsChanged",()=>{this.state===On.Entered&&this.updateMemberState().catch(v=>A.error("GroupCall ".concat(this.groupCallId," onLocalFeedsChanged() failed to update member state feeds"),v))}),this.reEmitter=new D$(this),this.groupCallId=o??od(),this._livekitServiceURL=m,this.creationTs=(u=(f=t.currentState.getStateEvents(ee.GroupCallPrefix,this.groupCallId))===null||f===void 0?void 0:f.getTs())!==null&&u!==void 0?u:null,this.updateParticipants(),t.on(ut.Update,this.onRoomState),this.on(rn.ParticipantsChanged,this.onParticipantsChanged),this.on(rn.GroupCallStateChanged,this.onStateChanged),this.on(rn.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!c}create(){var e=this;return F(function*(){return e.creationTs=Date.now(),e.client.groupCallEventHandler.groupCalls.set(e.room.roomId,e),e.client.emit(_k.Outgoing,e),yield e.sendCallStateEvent(),e})()}sendCallStateEvent(){var e=this;return F(function*(){var t={"m.intent":e.intent,"m.type":e.type,"io.element.ptt":e.isPtt,dataChannelsEnabled:e.dataChannelsEnabled,dataChannelOptions:e.dataChannelsEnabled?e.dataChannelOptions:void 0};e.livekitServiceURL&&(t["io.element.livekit_service_url"]=e.livekitServiceURL),yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallPrefix,t,e.groupCallId)})()}get livekitServiceURL(){return this._livekitServiceURL}updateLivekitServiceURL(e){return this._livekitServiceURL=e,this.sendCallStateEvent()}get state(){return this._state}set state(e){var t=this._state;e!==t&&(this._state=e,this.emit(rn.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){var t=this._participants,r=(s,o)=>s.sessionId===o.sessionId&&s.screensharing===o.screensharing,i=(s,o)=>i5(s,o,r);i5(e,t,i)||(this._participants=e,this.emit(rn.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(var t of this.calls.values())for(var r of t.values())e(r)}getLocalFeeds(){var e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return(e=(t=this.participants.get(this.room.getMember(this.client.getUserId())))===null||t===void 0?void 0:t.has(this.client.getDeviceId()))!==null&&e!==void 0?e:!1}callExpected(e){var t,r=w1(e),i=r===null?null:this.room.getMember(r),s=e.getOpponentDeviceId();return i!==null&&s!==void 0&&((t=this.participants.get(i))===null||t===void 0?void 0:t.get(s))!==void 0}initLocalCallFeed(){var e=this;return F(function*(){if(e.useLivekit){A.info("Livekit group call: not starting local call feed.");return}if(e.state!==On.LocalCallFeedUninitialized)throw new Error('Cannot initialize local call feed in the "'.concat(e.state,'" state.'));if(e.state=On.InitializingLocalCallFeed,e.initCallFeedPromise)return e.initCallFeedPromise;try{e.initCallFeedPromise=e.initLocalCallFeedInternal(),yield e.initCallFeedPromise}finally{e.initCallFeedPromise=void 0}})()}initLocalCallFeedInternal(){var e=this;return F(function*(){A.log("GroupCall ".concat(e.groupCallId," initLocalCallFeedInternal() running"));var t;try{t=yield e.client.getMediaHandler().getUserMediaStream(!0,e.type===LE.Video)}catch(i){if(e.allowCallWithoutVideoAndAudio)t=new MediaStream;else throw e.state=On.LocalCallFeedUninitialized,i}if(e._state!==On.InitializingLocalCallFeed)throw e.client.getMediaHandler().stopUserMediaStream(t),new Error("Group call disposed while gathering media stream");var r=new dl({client:e.client,roomId:e.room.roomId,userId:e.client.getUserId(),deviceId:e.client.getDeviceId(),stream:t,purpose:sn.Usermedia,audioMuted:e.initWithAudioMuted||t.getAudioTracks().length===0||e.isPtt,videoMuted:e.initWithVideoMuted||t.getVideoTracks().length===0});rr(t.getAudioTracks(),!r.isAudioMuted()),rr(t.getVideoTracks(),!r.isVideoMuted()),e.localCallFeed=r,e.addUserMediaFeed(r),e.state=On.LocalCallFeedInitialized})()}updateLocalUsermediaStream(e){var t=this;return F(function*(){if(t.localCallFeed){var r=t.localCallFeed.stream;t.localCallFeed.setNewStream(e);var i=t.localCallFeed.isAudioMuted(),s=t.localCallFeed.isVideoMuted();A.log("GroupCall ".concat(t.groupCallId," updateLocalUsermediaStream() (oldStreamId=").concat(r.id,", newStreamId=").concat(e.id,", micShouldBeMuted=").concat(i,", vidShouldBeMuted=").concat(s,")")),rr(e.getAudioTracks(),!i),rr(e.getVideoTracks(),!s),t.client.getMediaHandler().stopUserMediaStream(r)}})()}enter(){var e=this;return F(function*(){if(e.state===On.LocalCallFeedUninitialized)yield e.initLocalCallFeed();else if(e.state!==On.LocalCallFeedInitialized)throw new Error('Cannot enter call in the "'.concat(e.state,'" state'));A.log("GroupCall ".concat(e.groupCallId," enter() running")),e.state=On.Entered,e.client.on(yk.Incoming,e.onIncomingCall);for(var t of e.client.callEventHandler.calls.values())e.onIncomingCall(t);e.useLivekit||(e.retryCallLoopInterval=setInterval(e.onRetryCallLoop,e.retryCallInterval),e.activeSpeaker=void 0,e.onActiveSpeakerLoop(),e.activeSpeakerLoopInterval=setInterval(e.onActiveSpeakerLoop,e.activeSpeakerInterval))})()}dispose(){var e;this.localCallFeed&&(this.removeUserMediaFeed(this.localCallFeed),this.localCallFeed=void 0),this.localScreenshareFeed&&(this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0),this.client.getMediaHandler().stopAllStreams(),this.transmitTimer!==null&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),this.retryCallLoopInterval!==void 0&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),this.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===On.Entered&&(this.forEachCall(t=>t.hangup(ct.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(yk.Incoming,this.onIncomingCall),(e=this.stats)===null||e===void 0||e.stop())}leave(){this.dispose(),this.state=On.LocalCallFeedUninitialized}terminate(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!0;if(t.dispose(),t.room.off(ut.Update,t.onRoomState),t.client.groupCallEventHandler.groupCalls.delete(t.room.roomId),t.client.emit(_k.Ended,t),t.state=On.Ended,r){var i=t.room.currentState.getStateEvents(ee.GroupCallPrefix,t.groupCallId);yield t.client.sendStateEvent(t.room.roomId,ee.GroupCallPrefix,E1(E1({},i.getContent()),{},{"m.terminated":soe.CallEnded}),t.groupCallId)}})()}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}setMicrophoneMuted(e){var t=this;return F(function*(){if(!e&&!(yield t.client.getMediaHandler().hasAudioDevice()))return!1;var r=!e&&t.isPtt;t.isPtt&&(!e&&t.isMicrophoneMuted()?t.transmitTimer=setTimeout(()=>{t.setMicrophoneMuted(!0)},t.pttMaxTransmitTime):e&&!t.isMicrophoneMuted()&&(t.transmitTimer!==null&&clearTimeout(t.transmitTimer),t.transmitTimer=null)),t.forEachCall(o=>{var a;return(a=o.localUsermediaFeed)===null||a===void 0?void 0:a.setAudioVideoMuted(e,null)});var i=function(){var o=F(function*(){var a=[];t.forEachCall(l=>a.push(l.sendMetadataUpdate())),yield Promise.all(a).catch(l=>A.info("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() failed to send some metadata updates"),l))});return function(){return o.apply(this,arguments)}}();if(r&&(yield i()),t.localCallFeed){A.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() (streamId=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));var s=yield t.checkAudioPermissionIfNecessary(e);if(!s)return!1;t.localCallFeed.setAudioVideoMuted(e,null),rr(t.localCallFeed.stream.getAudioTracks(),!e)}else A.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no stream muted (muted=").concat(e,")")),t.initWithAudioMuted=e;return t.forEachCall(o=>rr(o.localUsermediaFeed.stream.getAudioTracks(),!e&&t.callExpected(o))),t.emit(rn.LocalMuteStateChanged,e,t.isLocalVideoMuted()),r||(yield i()),!0})()}checkAudioPermissionIfNecessary(e){var t=this;return F(function*(){try{if(!e&&t.localCallFeed&&!t.localCallFeed.hasAudioTrack){var r=yield t.client.getMediaHandler().getUserMediaStream(!0,!t.localCallFeed.isVideoMuted());if((r==null?void 0:r.getTracks().length)===0)return A.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device to receive local stream, muted=").concat(e)),!1}}catch{return A.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device or permission to receive local stream, muted=").concat(e)),!1}return!0})()}setLocalVideoMuted(e){var t=this;return F(function*(){if(!e&&!(yield t.client.getMediaHandler().hasVideoDevice()))return!1;if(t.localCallFeed){A.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() (stream=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));try{var r=yield t.client.getMediaHandler().getUserMediaStream(!0,!e);yield t.updateLocalUsermediaStream(r),t.localCallFeed.setAudioVideoMuted(null,e),rr(t.localCallFeed.stream.getVideoTracks(),!e)}catch{return A.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no device or permission to receive local stream, muted=").concat(e)),!1}}else A.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no stream muted (muted=").concat(e,")")),t.initWithVideoMuted=e;var i=[];return t.forEachCall(s=>i.push(s.setLocalVideoMuted(e))),yield Promise.all(i),t.forEachCall(s=>rr(s.localUsermediaFeed.stream.getVideoTracks(),!e&&t.callExpected(s))),t.emit(rn.LocalMuteStateChanged,t.isMicrophoneMuted(),e),!0})()}setScreensharingEnabled(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(e===r.isScreensharing())return e;if(e)try{A.log("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() is asking for screensharing permissions"));var s=yield r.client.getMediaHandler().getScreensharingStream(i),o=function*(c){var u=()=>{r.setScreensharingEnabled(!1),c.removeEventListener("ended",u)};c.addEventListener("ended",u)};for(var a of s.getTracks())yield*o(a);return A.log("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls")),r.localDesktopCapturerSourceId=i.desktopCapturerSourceId,r.localScreenshareFeed=new dl({client:r.client,roomId:r.room.roomId,userId:r.client.getUserId(),deviceId:r.client.getDeviceId(),stream:s,purpose:sn.Screenshare,audioMuted:!1,videoMuted:!1}),r.addScreenshareFeed(r.localScreenshareFeed),r.emit(rn.LocalScreenshareStateChanged,!0,r.localScreenshareFeed,r.localDesktopCapturerSourceId),r.forEachCall(l=>l.pushLocalFeed(r.localScreenshareFeed.clone())),!0}catch(l){if(i.throwOnFail)throw l;return A.error("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() enabling screensharing error"),l),r.emit(rn.Error,new bk(Gg.NoUserMedia,"Failed to get screen-sharing stream: ",l)),!1}else return r.forEachCall(l=>{l.localScreensharingFeed&&l.removeLocalFeed(l.localScreensharingFeed)}),r.client.getMediaHandler().stopScreensharingStream(r.localScreenshareFeed.stream),r.removeScreenshareFeed(r.localScreenshareFeed),r.localScreenshareFeed=void 0,r.localDesktopCapturerSourceId=void 0,r.emit(rn.LocalScreenshareStateChanged,!1,void 0,void 0),!1})()}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){var r=this.client.getUserId(),i=this.client.getDeviceId();return e>=r&&(e!==r||t>i)}placeOutgoingCalls(){var e=this,t=!1,r=function(a){var l,c=(l=e.calls.get(a))!==null&&l!==void 0?l:new Map,u=function(v){var g=c.get(v);if((g==null?void 0:g.getOpponentSessionId())!==p.sessionId&&e.wantsOutgoingCall(a,v)){t=!0,g!==void 0&&(A.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() replacing call (userId=").concat(a,", deviceId=").concat(v,", callId=").concat(g.callId,")")),g.hangup(ct.NewSession,!1));var S=Iv(e.client,e.room.roomId,{invitee:a,opponentDeviceId:v,opponentSessionId:p.sessionId,groupCallId:e.groupCallId});S===null?(A.error("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to create call (userId=").concat(a,", device=").concat(v,")")),c.delete(v)):(e.initCall(S),c.set(v,S),A.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() placing call (userId=").concat(a,", deviceId=").concat(v,", sessionId=").concat(p.sessionId,")")),S.placeCallWithCallFeeds(e.getLocalFeeds().map(b=>b.clone()),p.screensharing).then(()=>{e.dataChannelsEnabled&&S.createDataChannel("datachannel",e.dataChannelOptions)}).catch(b=>{A.warn("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to place call (userId=").concat(a,")"),b),b instanceof tl&&b.code===Gg.UnknownDevice?e.emit(rn.Error,b):e.emit(rn.Error,new bk(Gg.PlaceCallFailed,"Failed to place call to ".concat(a))),S.hangup(ct.SignallingFailed,!1),c.get(v)===S&&c.delete(v)}))}};for(var[f,p]of s)u(f);c.size>0?e.calls.set(a,c):e.calls.delete(a)};for(var[{userId:i},s]of this.participants)r(i);t&&this.emit(rn.CallsChanged,this.calls)}getMemberStateEvents(e){return e===void 0?this.room.currentState.getStateEvents(ee.GroupCallMemberPrefix):this.room.currentState.getStateEvents(ee.GroupCallMemberPrefix,e)}initCall(e){var t=w1(e);if(!t)throw new Error("Cannot init call without user id");var r=()=>this.onCallFeedsChanged(e),i=(l,c)=>this.onCallStateChanged(e,l,c),s=this.onCallHangup,o=l=>this.onCallReplaced(e,l),a=this.callHandlers.get(t);a===void 0&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:r,onCallStateChanged:i,onCallHangup:s,onCallReplaced:o}),e.on(ft.FeedsChanged,r),e.on(ft.State,i),e.on(ft.Hangup,s),e.on(ft.Replaced,o),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(ft)),e.initStats(this.getGroupCallStats()),r()}disposeCall(e,t){var r=w1(e),i=e.getOpponentDeviceId();if(!r)throw new Error("Cannot dispose call without user id");var s=this.callHandlers.get(r),{onCallFeedsChanged:o,onCallStateChanged:a,onCallHangup:l,onCallReplaced:c}=s.get(i);if(e.removeListener(ft.FeedsChanged,o),e.removeListener(ft.State,a),e.removeListener(ft.Hangup,l),e.removeListener(ft.Replaced,c),s.delete(r),s.size===0&&this.callHandlers.delete(r),e.hangupReason!==ct.Replaced){var u=this.getUserMediaFeed(r,i);u&&this.removeUserMediaFeed(u);var f=this.getScreenshareFeed(r,i);f&&this.removeScreenshareFeed(f)}}getUserMediaFeed(e,t){return this.userMediaFeeds.find(r=>r.userId===e&&r.deviceId===t)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(rn.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){var r=this.userMediaFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(r===-1)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(r,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(rn.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){var t=this.userMediaFeeds.findIndex(r=>r.userId===e.userId&&r.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(rn.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(rn.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find(r=>r.userId===e&&r.deviceId===t)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(rn.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){var r=this.screenshareFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(r===-1)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(r,1,t),e.dispose(),this.emit(rn.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){var t=this.screenshareFeeds.findIndex(r=>r.userId===e.userId&&r.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(rn.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){var e=this.room.getMember(this.client.getSafeUserId());if(!e){A.warn("GroupCall ".concat(this.groupCallId," updateParticipants() tried to update participants before local room member is available"));return}if(this.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===On.Ended){this.participants=new Map;return}var t=new Map,r=Date.now(),i=this.state===On.Entered||this.enteredViaAnotherSession,s=1/0;for(var o of this.getMemberStateEvents()){var a=this.room.getMember(o.getStateKey()),l=o.getContent(),c=Array.isArray(l["m.calls"])?l["m.calls"]:[],u=c.find(S=>S["m.call_id"]===this.groupCallId),f=Array.isArray(u==null?void 0:u["m.devices"])?u["m.devices"]:[],p=f.filter(S=>typeof S.device_id=="string"&&typeof S.session_id=="string"&&typeof S.expires_ts=="number"&&S.expires_ts>r&&Array.isArray(S.feeds));if(!i&&(a==null?void 0:a.userId)===this.client.getUserId()&&(p=p.filter(S=>S.device_id!==this.client.getDeviceId())),p.length>0&&(a==null?void 0:a.membership)===qe.Join){var m=new Map;t.set(a,m);for(var v of p)m.set(v.device_id,{sessionId:v.session_id,screensharing:v.feeds.some(S=>S.purpose===sn.Screenshare)}),v.expires_ts<s&&(s=v.expires_ts)}}if(i){var g=t.get(e);g===void 0&&(g=new Map,t.set(e,g)),g.has(this.client.getDeviceId())||g.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(S=>S.purpose===sn.Screenshare)})}this.participants=t,s<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),s-r))}updateDevices(e){var t=arguments,r=this;return F(function*(){var i,s=t.length>1&&t[1]!==void 0?t[1]:!1,o=Date.now(),a=r.client.getUserId(),l=r.getMemberStateEvents(a),c=(i=l==null?void 0:l.getContent())!==null&&i!==void 0?i:{},u=Array.isArray(c["m.calls"])?c["m.calls"]:[],f=null,p=[];for(var m of u)m["m.call_id"]===r.groupCallId?f=m:p.push(m);f===null&&(f={});var v=Array.isArray(f["m.devices"])?f["m.devices"]:[],g=v.filter(k=>typeof k.device_id=="string"&&typeof k.session_id=="string"&&typeof k.expires_ts=="number"&&k.expires_ts>o&&Array.isArray(k.feeds)),S=e(g);if(S!==null){var b=[...p];S.length>0&&b.push(E1(E1({},f),{},{"m.call_id":r.groupCallId,"m.devices":S}));var w={"m.calls":b};yield r.client.sendStateEvent(r.room.roomId,ee.GroupCallMemberPrefix,w,a,{keepAlive:s})}})()}addDeviceToMemberState(){var e=this;return F(function*(){yield e.updateDevices(t=>[...t.filter(r=>r.device_id!==e.client.getDeviceId()),{device_id:e.client.getDeviceId(),session_id:e.client.getSessionId(),expires_ts:Date.now()+nN,feeds:e.getLocalFeeds().map(r=>({purpose:r.purpose}))}])})()}updateMemberState(){var e=this;return F(function*(){e.resendMemberStateTimer!==null&&(clearInterval(e.resendMemberStateTimer),e.resendMemberStateTimer=null),e.state===On.Entered?(yield e.addDeviceToMemberState(),e.resendMemberStateTimer=setInterval(F(function*(){A.log("GroupCall ".concat(e.groupCallId,' updateMemberState() resending call member state"'));try{yield e.addDeviceToMemberState()}catch(t){A.error("GroupCall ".concat(e.groupCallId," updateMemberState() failed to resend call member state"),t)}}),nN*3/4)):yield e.updateDevices(t=>t.filter(r=>r.device_id!==e.client.getDeviceId()),!0)})()}cleanMemberState(){var e=this;return F(function*(){var{devices:t}=yield e.client.getDevices(),r=new Map(t.map(i=>[i.device_id,i]));yield e.updateDevices(i=>{var s=i.filter(o=>{var a=r.get(o.device_id);return(a==null?void 0:a.last_seen_ts)!==void 0&&!(o.device_id===e.client.getDeviceId()&&e.state!==On.Entered&&!e.enteredViaAnotherSession)});return s.length===i.length?null:s})})()}getGroupCallStats(){if(this.stats===void 0){var e=this.client.getUserId()||"unknown";this.stats=new ioe(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(vl.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(vl.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(vl.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(vl.CALL_FEED_REPORT,this.onCallFeedReport)}return this.stats}setGroupCallStatsInterval(e){this.statsCollectIntervalTime=e,this.stats!==void 0&&(this.stats.stop(),this.stats.setInterval(e),e>0&&this.stats.start())}}function rN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function C1(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?rN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):rN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var rt=function(n){return n.Fledgling="fledgling",n.InviteSent="invite_sent",n.WaitLocalMedia="wait_local_media",n.CreateOffer="create_offer",n.CreateAnswer="create_answer",n.Connecting="connecting",n.Connected="connected",n.Ringing="ringing",n.Ended="ended",n}({}),iN=function(n){return n.Voice="voice",n.Video="video",n}({}),wc=function(n){return n.Inbound="inbound",n.Outbound="outbound",n}({}),$n=function(n){return n.Local="local",n.Remote="remote",n}({}),ft=function(n){return n.Hangup="hangup",n.State="state",n.Error="error",n.Replaced="replaced",n.LocalHoldUnhold="local_hold_unhold",n.RemoteHoldUnhold="remote_hold_unhold",n.HoldUnhold="hold_unhold",n.FeedsChanged="feeds_changed",n.AssertedIdentityChanged="asserted_identity_changed",n.LengthChanged="length_changed",n.DataChannel="datachannel",n.SendVoipEvent="send_voip_event",n.PeerConnectionCreated="peer_connection_created",n}({}),ct=function(n){return n.UserHangup="user_hangup",n.LocalOfferFailed="local_offer_failed",n.NoUserMedia="no_user_media",n.UnknownDevices="unknown_devices",n.SendInvite="send_invite",n.CreateAnswer="create_answer",n.CreateOffer="create_offer",n.SendAnswer="send_answer",n.SetRemoteDescription="set_remote_description",n.SetLocalDescription="set_local_description",n.AnsweredElsewhere="answered_elsewhere",n.IceFailed="ice_failed",n.InviteTimeout="invite_timeout",n.Replaced="replaced",n.SignallingFailed="signalling_timeout",n.UserBusy="user_busy",n.Transferred="transferred",n.NewSession="new_session",n}({}),ooe="1",aoe="stun:turn.matrix.org",n2=60*1e3,loe=1e3,coe=30*1e3,uoe=2*1e3;class tl extends Error{constructor(e,t,r){super(t+": "+r),L(this,"code",void 0),this.code=e}}function od(){return Date.now().toString()+bs(16)}function sN(n){var e=[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:n?12e3:void 0}];return e}function go(n,e){return n+":"+e}class doe extends En{constructor(e){var t,r;if(super(),t=this,L(this,"roomId",void 0),L(this,"callId",void 0),L(this,"invitee",void 0),L(this,"hangupParty",void 0),L(this,"hangupReason",void 0),L(this,"direction",void 0),L(this,"ourPartyId",void 0),L(this,"peerConn",void 0),L(this,"toDeviceSeq",0),L(this,"isPtt",!1),L(this,"_state",rt.Fledgling),L(this,"client",void 0),L(this,"forceTURN",void 0),L(this,"turnServers",void 0),L(this,"candidateSendQueue",[]),L(this,"candidateSendTries",0),L(this,"candidatesEnded",!1),L(this,"feeds",[]),L(this,"transceivers",new Map),L(this,"inviteOrAnswerSent",!1),L(this,"waitForLocalAVStream",!1),L(this,"successor",void 0),L(this,"opponentMember",void 0),L(this,"opponentVersion",void 0),L(this,"opponentPartyId",void 0),L(this,"opponentCaps",void 0),L(this,"iceDisconnectedTimeout",void 0),L(this,"iceReconnectionTimeOut",void 0),L(this,"inviteTimeout",void 0),L(this,"removeTrackListeners",new Map),L(this,"remoteOnHold",!1),L(this,"callStatsAtEnd",void 0),L(this,"makingOffer",!1),L(this,"ignoreOffer",!1),L(this,"isSettingRemoteAnswerPending",!1),L(this,"responsePromiseChain",void 0),L(this,"remoteCandidateBuffer",new Map),L(this,"remoteAssertedIdentity",void 0),L(this,"remoteSDPStreamMetadata",void 0),L(this,"callLengthInterval",void 0),L(this,"callStartTime",void 0),L(this,"opponentDeviceId",void 0),L(this,"hasOpponentDeviceInfo",void 0),L(this,"opponentSessionId",void 0),L(this,"groupCallId",void 0),L(this,"stopVideoTrackTimer",void 0),L(this,"isOnlyDataChannelAllowed",void 0),L(this,"stats",void 0),L(this,"gotLocalIceCandidate",s=>{if(s.candidate){if(this.candidatesEnded&&A.warn("Call ".concat(this.callId," gotLocalIceCandidate() got candidate after candidates have ended!")),A.debug("Call ".concat(this.callId," got local ICE ").concat(s.candidate.sdpMid," ").concat(s.candidate.candidate)),this.callHasEnded())return;s.candidate.candidate===""?this.queueCandidate(null):this.queueCandidate(s.candidate)}}),L(this,"onIceGatheringStateChange",s=>{var o;A.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state changed to ").concat(this.peerConn.iceGatheringState)),((o=this.peerConn)===null||o===void 0?void 0:o.iceGatheringState)==="complete"&&(this.queueCandidate(null),A.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state complete, set candidates have ended")))}),L(this,"getLocalOfferFailed",s=>{A.error("Call ".concat(this.callId," getLocalOfferFailed() running"),s),this.emit(ft.Error,new tl(ct.LocalOfferFailed,"Failed to get local offer!",s),this),this.terminate($n.Local,ct.LocalOfferFailed,!1)}),L(this,"getUserMediaFailed",s=>{if(this.successor){this.successor.getUserMediaFailed(s);return}A.warn("Call ".concat(this.callId," getUserMediaFailed() failed to get user media - ending call"),s),this.emit(ft.Error,new tl(ct.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",s),this),this.terminate($n.Local,ct.NoUserMedia,!1)}),L(this,"placeCallFailed",s=>{if(this.successor){this.successor.placeCallFailed(s);return}A.warn("Call ".concat(this.callId," placeCallWithCallFeeds() failed - ending call"),s),this.emit(ft.Error,new tl(ct.IceFailed,"Couldn't start call! Invalid ICE server configuration.",s),this),this.terminate($n.Local,ct.IceFailed,!1)}),L(this,"onIceConnectionStateChanged",()=>{var s,o,a,l,c,u;if(!this.callHasEnded()){if(A.debug("Call ".concat(this.callId," onIceConnectionStateChanged() running (state=").concat((s=this.peerConn)===null||s===void 0?void 0:s.iceConnectionState,", conn=").concat((o=this.peerConn)===null||o===void 0?void 0:o.connectionState,")")),["connected","completed"].includes((a=(l=this.peerConn)===null||l===void 0?void 0:l.iceConnectionState)!==null&&a!==void 0?a:""))clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state=rt.Connected,!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(ft.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)},loe));else if(((c=this.peerConn)===null||c===void 0?void 0:c.iceConnectionState)=="failed"){var f;if(this.candidatesEnded=!1,(f=this.peerConn)!==null&&f!==void 0&&f.restartIce){var p;this.candidatesEnded=!1,A.debug("Call ".concat(this.callId," onIceConnectionStateChanged() ice restart (state=").concat((p=this.peerConn)===null||p===void 0?void 0:p.iceConnectionState,")")),this.peerConn.restartIce()}else A.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)")),this.hangup(ct.IceFailed,!1)}else((u=this.peerConn)===null||u===void 0?void 0:u.iceConnectionState)=="disconnected"&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var v,g,S;A.info("Call ".concat(this.callId," onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((v=this.peerConn)===null||v===void 0?void 0:v.iceConnectionState,", conn=").concat((g=this.peerConn)===null||g===void 0?void 0:g.connectionState,")")),(S=this.peerConn)!==null&&S!==void 0&&S.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},uoe),this.iceDisconnectedTimeout=setTimeout(()=>{A.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)")),this.hangup(ct.IceFailed,!1)},coe),this.state=rt.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(var m of this.getRemoteFeeds())m.setAudioVideoMuted(!0,!0)}}),L(this,"onSignallingStateChanged",()=>{var s;A.debug("Call ".concat(this.callId," onSignallingStateChanged() running (state=").concat((s=this.peerConn)===null||s===void 0?void 0:s.signalingState,")"))}),L(this,"onTrack",s=>{if(s.streams.length===0){A.warn("Call ".concat(this.callId," onTrack() called with streamless track streamless (kind=").concat(s.track.kind,")"));return}var o=s.streams[0];if(this.pushRemoteFeed(o),!this.removeTrackListeners.has(o)){var a=()=>{o.getTracks().length===0&&(A.info("Call ".concat(this.callId," onTrack() removing track (streamId=").concat(o.id,")")),this.deleteFeedByStream(o),o.removeEventListener("removetrack",a),this.removeTrackListeners.delete(o))};o.addEventListener("removetrack",a),this.removeTrackListeners.set(o,a)}}),L(this,"onDataChannel",s=>{this.emit(ft.DataChannel,s.channel,this)}),L(this,"onNegotiationNeeded",F(function*(){if(A.info("Call ".concat(t.callId," onNegotiationNeeded() negotiation is needed!")),t.state!==rt.CreateOffer&&t.opponentVersion===0){A.info("Call ".concat(t.callId," onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event"));return}t.queueGotLocalOffer()})),L(this,"onHangupReceived",s=>{A.debug("Call ".concat(this.callId," onHangupReceived() running")),this.partyIdMatches(s)||this.state===rt.Ringing?this.terminate($n.Remote,s.reason||ct.UserHangup,!0):A.info("Call ".concat(this.callId," onHangupReceived() ignoring message from party ID ").concat(s.party_id,": our partner is ").concat(this.opponentPartyId))}),L(this,"onRejectReceived",s=>{A.debug("Call ".concat(this.callId," onRejectReceived() running"));var o=[rt.InviteSent,rt.Ringing].includes(this.state)||this.state===rt.Fledgling&&this.direction===wc.Inbound;o?this.terminate($n.Remote,s.reason||ct.UserHangup,!0):A.debug("Call ".concat(this.callId," onRejectReceived() called in wrong state (state=").concat(this.state,")"))}),L(this,"onAnsweredElsewhere",s=>{A.debug("Call ".concat(this.callId," onAnsweredElsewhere() running")),this.terminate($n.Remote,ct.AnsweredElsewhere,!0)}),this.roomId=e.roomId,this.invitee=e.invitee,this.client=e.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=(r=e.forceTURN)!==null&&r!==void 0?r:!1,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=e.opponentDeviceId,this.opponentSessionId=e.opponentSessionId,this.groupCallId=e.groupCallId,this.turnServers=e.turnServers||[],this.turnServers.length===0&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:[aoe]});for(var i of this.turnServers)h$(i,["urls"]);this.callId=od(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){var e=this;return F(function*(){yield e.placeCall(!0,!1)})()}placeVideoCall(){var e=this;return F(function*(){yield e.placeCall(!0,!0)})()}createDataChannel(e,t){var r=this.peerConn.createDataChannel(e,t);return this.emit(ft.DataChannel,r,this),r}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return!!(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return!!(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(e){var t=this._state;this._state=e,this.emit(ft.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?iN.Video:iN.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===sn.Usermedia&&((t=e.stream)===null||t===void 0?void 0:t.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===sn.Usermedia&&!!((t=e.stream)!==null&&t!==void 0&&t.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return!!(!((e=this.transceivers.get(go(sn.Usermedia,"audio")))===null||e===void 0)&&e.sender)}get hasUserMediaVideoSender(){var e;return!!(!((e=this.transceivers.get(go(sn.Usermedia,"video")))===null||e===void 0)&&e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===sn.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===sn.Screenshare)}get localUsermediaStream(){var e;return(e=this.localUsermediaFeed)===null||e===void 0?void 0:e.stream}get localScreensharingStream(){var e;return(e=this.localScreensharingFeed)===null||e===void 0?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find(e=>e.purpose===sn.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===sn.Screenshare)}get remoteUsermediaStream(){var e;return(e=this.remoteUsermediaFeed)===null||e===void 0?void 0:e.stream}get remoteScreensharingStream(){var e;return(e=this.remoteScreensharingFeed)===null||e===void 0?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find(t=>t.stream.id===e)}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter(e=>e.isLocal())}getRemoteFeeds(){return this.feeds.filter(e=>!e.isLocal())}initOpponentCrypto(){var e=this;return F(function*(){var t;if(e.opponentDeviceId&&e.client.getUseE2eForGroupCall()){if(!e.client.getCrypto()){e.hasOpponentDeviceInfo=!0;return}var r=e.invitee||((t=e.getOpponentMember())===null||t===void 0?void 0:t.userId);throw r?(e.hasOpponentDeviceInfo=!1,new _H(r)):new Error("Couldn't find opponent user ID to init crypto")}})()}getLocalSDPStreamMetadata(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={};for(var r of this.getLocalFeeds())e&&(r.sdpMetadataStreamId=r.stream.id),t[r.sdpMetadataStreamId]={purpose:r.purpose,audio_muted:r.isAudioMuted(),video_muted:r.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(e);return}var t=this.getOpponentMember().userId,r=this.remoteSDPStreamMetadata[e.id].purpose,i=this.remoteSDPStreamMetadata[e.id].audio_muted,s=this.remoteSDPStreamMetadata[e.id].video_muted;if(!r){A.warn("Call ".concat(this.callId," pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){A.warn("Call ".concat(this.callId," pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.feeds.push(new dl({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:r,audioMuted:i,videoMuted:s})),this.emit(ft.FeedsChanged,this.feeds,this),A.info("Call ".concat(this.callId," pushRemoteFeed() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,", purpose=").concat(r,")"))}pushRemoteFeedWithoutMetadata(e){var t,r=this.getOpponentMember().userId,i=sn.Usermedia,s=(t=this.feeds.find(o=>!o.isLocal()))===null||t===void 0?void 0:t.stream;if(s&&e.id!==s.id){A.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){A.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.feeds.push(new dl({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:r,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i})),this.emit(ft.FeedsChanged,this.feeds,this),A.info("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,")"))}pushNewLocalFeed(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.client.getUserId();if(rr(e.getAudioTracks(),!0),rr(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)){A.warn("Call ".concat(this.callId," pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.pushLocalFeed(new dl({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),r)}pushLocalFeed(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(this.feeds.some(o=>e.stream.id===o.stream.id)){A.info("Call ".concat(this.callId," pushLocalFeed() ignoring duplicate local stream (streamId=").concat(e.stream.id,")"));return}if(this.feeds.push(e),r){var i=function(){A.info("Call ".concat(t.callId," pushLocalFeed() adding track to peer connection (id=").concat(s.id,", kind=").concat(s.kind,", streamId=").concat(e.stream.id,", streamPurpose=").concat(e.purpose,", enabled=").concat(s.enabled,")"));var a=go(e.purpose,s.kind);if(t.transceivers.has(a)){var l=t.transceivers.get(a);l.sender.replaceTrack(s),l.direction=l.direction==="inactive"?"sendonly":"sendrecv"}else{var c=t.peerConn.addTrack(s,e.stream),u=t.peerConn.getTransceivers().find(f=>f.sender===c);u?t.transceivers.set(a,u):A.warn("Call ".concat(t.callId," pushLocalFeed() didn't find a matching transceiver after adding track!"))}};for(var s of e.stream.getTracks())i()}A.info("Call ".concat(this.callId," pushLocalFeed() pushed stream (id=").concat(e.stream.id,", active=").concat(e.stream.active,", purpose=").concat(e.purpose,")")),this.emit(ft.FeedsChanged,this.feeds,this)}removeLocalFeed(e){var t=go(e.purpose,"audio"),r=go(e.purpose,"video");for(var i of[t,r])if(this.transceivers.has(i)){var s=this.transceivers.get(i);s.sender&&this.peerConn.removeTrack(s.sender)}e.purpose===sn.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(e.stream),this.deleteFeed(e)}deleteAllFeeds(){for(var e of this.feeds)(!e.isLocal()||!this.groupCallId)&&e.dispose();this.feeds=[],this.emit(ft.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){var t=this.getFeedByStreamId(e.id);if(!t){A.warn("Call ".concat(this.callId," deleteFeedByStream() didn't find the feed to delete (streamId=").concat(e.id,")"));return}this.deleteFeed(t)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(ft.FeedsChanged,this.feeds,this)}getCurrentCallStats(){var e=this;return F(function*(){return e.callHasEnded()?e.callStatsAtEnd:e.collectCallStats()})()}collectCallStats(){var e=this;return F(function*(){if(e.peerConn){var t=yield e.peerConn.getStats(),r=[];return t.forEach(i=>{r.push(i)}),r}})()}initWithInvite(e){var t=this;return F(function*(){var r,i=e.getContent();t.direction=wc.Inbound;var s=yield t.client.checkTurnServers();s||A.warn("Call ".concat(t.callId," initWithInvite() failed to get TURN credentials! Proceeding with call anyway..."));var o=i[pc];o?t.updateRemoteSDPStreamMetadata(o):A.debug("Call ".concat(t.callId," initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams")),t.peerConn=t.createPeerConnection(),t.emit(ft.PeerConnectionCreated,t.peerConn,t),t.chooseOpponent(e),yield t.initOpponentCrypto();try{yield t.peerConn.setRemoteDescription(i.offer),A.debug("Call ".concat(t.callId," initWithInvite() set remote description: ").concat(i.offer.type)),yield t.addBufferedIceCandidates()}catch(u){A.debug("Call ".concat(t.callId," initWithInvite() failed to set remote description"),u),t.terminate($n.Local,ct.SetRemoteDescription,!1);return}var a=(r=t.feeds.find(u=>!u.isLocal()))===null||r===void 0?void 0:r.stream;if(!t.isOnlyDataChannelAllowed&&(!a||a.getTracks().length===0)){A.error("Call ".concat(t.callId," initWithInvite() no remote stream or no tracks after setting remote description!")),t.terminate($n.Local,ct.SetRemoteDescription,!1);return}if(t.state=rt.Ringing,e.getLocalAge()){var l=setTimeout(()=>{if(t.state==rt.Ringing){var u;A.debug("Call ".concat(t.callId," initWithInvite() invite has expired. Hanging up.")),t.hangupParty=$n.Remote,t.state=rt.Ended,t.stopAllMedia(),t.peerConn.signalingState!="closed"&&t.peerConn.close(),(u=t.stats)===null||u===void 0||u.removeStatsReportGatherer(t.callId),t.emit(ft.Hangup,t)}},i.lifetime-e.getLocalAge()),c=u=>{u!==rt.Ringing&&(clearTimeout(l),t.off(ft.State,c))};t.on(ft.State,c)}})()}initWithHangup(e){this.state=rt.Ended}shouldAnswerWithMediaType(e,t,r){return e&&!t?(A.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(r," because the other side isn't sending it either.")),!1):!g$(e)&&e!==t&&!this.opponentSupportsSDPStreamMetadata()?(A.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(r,"=").concat(e," because the other side doesn't support it. Answering with ").concat(r,"=").concat(t,".")),t):e??t}answer(e,t){var r=this;return F(function*(){if(!r.inviteOrAnswerSent){if(e===!1&&t===!1)throw new Error("You CANNOT answer a call without media");if(!r.localUsermediaStream&&!r.waitForLocalAVStream){var i=r.state,s=r.shouldAnswerWithMediaType(e,r.hasRemoteUserMediaAudioTrack,"audio"),o=r.shouldAnswerWithMediaType(t,r.hasRemoteUserMediaVideoTrack,"video");r.state=rt.WaitLocalMedia,r.waitForLocalAVStream=!0;try{var a,l=yield r.client.getMediaHandler().getUserMediaStream(s,o);r.waitForLocalAVStream=!1;var c=new dl({client:r.client,roomId:r.roomId,userId:r.client.getUserId(),deviceId:(a=r.client.getDeviceId())!==null&&a!==void 0?a:void 0,stream:l,purpose:sn.Usermedia,audioMuted:!1,videoMuted:!1}),u=[c];r.localScreensharingFeed&&u.push(r.localScreensharingFeed),r.answerWithCallFeeds(u)}catch(f){if(o)A.warn("Call ".concat(r.callId," answer() failed to getUserMedia(), trying to getUserMedia() without video")),r.state=i,r.waitForLocalAVStream=!1,yield r.answer(s,!1);else{r.getUserMediaFailed(f);return}}}else r.waitForLocalAVStream&&(r.state=rt.WaitLocalMedia)}})()}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){A.debug("Call ".concat(this.callId," replacedBy() running (newCallId=").concat(e.callId,")")),this.state===rt.WaitLocalMedia?(A.debug("Call ".concat(this.callId," replacedBy() telling new call to wait for local media (newCallId=").concat(e.callId,")")),e.waitForLocalAVStream=!0):[rt.CreateOffer,rt.InviteSent].includes(this.state)&&(e.direction===wc.Outbound?e.queueGotCallFeedsForAnswer([]):(A.debug("Call ".concat(this.callId," replacedBy() handing local stream to new call(newCallId=").concat(e.callId,")")),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(t=>t.clone())))),this.successor=e,this.emit(ft.Replaced,e,this),this.hangup(ct.Replaced,!0)}hangup(e,t){if(!this.callHasEnded()&&(A.debug("Call ".concat(this.callId," hangup() ending call (reason=").concat(e,")")),this.terminate($n.Local,e,!t),![rt.Fledgling,rt.WaitLocalMedia].includes(this.state))){var r={};(this.opponentVersion&&this.opponentVersion!==0||e!==ct.UserHangup)&&(r.reason=e),this.sendVoipEvent(ee.CallHangup,r)}}reject(){if(this.state!==rt.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){A.info("Call ".concat(this.callId," reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=").concat(this.opponentVersion,")")),this.hangup(ct.UserHangup,!0);return}A.debug("Rejecting call: "+this.callId),this.terminate($n.Local,ct.UserHangup,!0),this.sendVoipEvent(ee.CallReject,{})}upgradeCall(e,t){var r=this;return F(function*(){if(!(!e&&!t)&&r.opponentSupportsSDPStreamMetadata())try{A.debug("Call ".concat(r.callId," upgradeCall() upgrading call (audio=").concat(e,", video=").concat(t,")"));var i=e||r.hasLocalUserMediaAudioTrack,s=t||r.hasLocalUserMediaVideoTrack,o=yield r.client.getMediaHandler().getUserMediaStream(i,s,!1);yield r.updateLocalUsermediaStream(o,e,t)}catch(a){A.error("Call ".concat(r.callId," upgradeCall() failed to upgrade the call"),a),r.emit(ft.Error,new tl(ct.NoUserMedia,"Failed to get camera access: ",a),r)}})()}opponentSupportsSDPStreamMetadata(){return!!this.remoteSDPStreamMetadata}isScreensharing(){return!!this.localScreensharingStream}setScreensharingEnabled(e,t){var r=this;return F(function*(){if(e&&r.isScreensharing())return A.warn("Call ".concat(r.callId," setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!")),!0;if(!e&&!r.isScreensharing())return A.warn("Call ".concat(r.callId," setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!")),!1;if(!r.opponentSupportsSDPStreamMetadata())return r.setScreensharingEnabledWithoutMetadataSupport(e,t);if(A.debug("Call ".concat(r.callId," setScreensharingEnabled() running (enabled=").concat(e,")")),e)try{var i=yield r.client.getMediaHandler().getScreensharingStream(t);return i?(r.pushNewLocalFeed(i,sn.Screenshare),!0):!1}catch(l){return A.error("Call ".concat(r.callId," setScreensharingEnabled() failed to get screen-sharing stream:"),l),!1}else{var s=r.transceivers.get(go(sn.Screenshare,"audio")),o=r.transceivers.get(go(sn.Screenshare,"video"));for(var a of[s,o])a&&a.sender&&r.peerConn.removeTrack(a.sender);return r.client.getMediaHandler().stopScreensharingStream(r.localScreensharingStream),r.deleteFeedByStream(r.localScreensharingStream),!1}})()}setScreensharingEnabledWithoutMetadataSupport(e,t){var r=this;return F(function*(){if(A.debug("Call ".concat(r.callId," setScreensharingEnabledWithoutMetadataSupport() running (enabled=").concat(e,")")),e)try{var i,s=yield r.client.getMediaHandler().getScreensharingStream(t);if(!s)return!1;var o=s.getTracks().find(p=>p.kind==="video"),a=(i=r.transceivers.get(go(sn.Usermedia,"video")))===null||i===void 0?void 0:i.sender;return a==null||a.replaceTrack(o??null),r.pushNewLocalFeed(s,sn.Screenshare,!1),!0}catch(p){return A.error("Call ".concat(r.callId," setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:"),p),!1}else{var l,c,u=(l=r.localUsermediaStream)===null||l===void 0?void 0:l.getTracks().find(p=>p.kind==="video"),f=(c=r.transceivers.get(go(sn.Usermedia,"video")))===null||c===void 0?void 0:c.sender;return f==null||f.replaceTrack(u??null),r.client.getMediaHandler().stopScreensharingStream(r.localScreensharingStream),r.deleteFeedByStream(r.localScreensharingStream),!1}})()}updateLocalUsermediaStream(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,s=t.length>2&&t[2]!==void 0?t[2]:!1,o=r.localUsermediaFeed,a=i||!o.isAudioMuted()&&!r.remoteOnHold,l=s||!o.isVideoMuted()&&!r.remoteOnHold;A.log("Call ".concat(r.callId," updateLocalUsermediaStream() running (streamId=").concat(e.id,", audio=").concat(a,", video=").concat(l,")")),rr(e.getAudioTracks(),a),rr(e.getVideoTracks(),l);for(var c of r.localUsermediaStream.getTracks())r.localUsermediaStream.removeTrack(c),c.stop();for(var u of e.getTracks())r.localUsermediaStream.addTrack(u);var f=function*(){var v=go(sn.Usermedia,p.kind),g=r.transceivers.get(v),S=g==null?void 0:g.sender,b=!1;if(S)try{A.info("Call ".concat(r.callId," updateLocalUsermediaStream() replacing track (id=").concat(p.id,", kind=").concat(p.kind,", streamId=").concat(e.id,", streamPurpose=").concat(o.purpose,")")),yield S.replaceTrack(p),g.direction=g.direction==="inactive"?"sendonly":"sendrecv",b=!0}catch(R){A.warn("Call ".concat(r.callId," updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead"),R)}if(!b){A.info("Call ".concat(r.callId," updateLocalUsermediaStream() adding track to peer connection (id=").concat(p.id,", kind=").concat(p.kind,", streamId=").concat(e.id,", streamPurpose=").concat(o.purpose,")"));var w=r.peerConn.addTrack(p,r.localUsermediaStream),k=r.peerConn.getTransceivers().find(R=>R.sender===w);k?r.transceivers.set(v,k):A.warn("Call ".concat(r.callId," updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!"))}};for(var p of e.getTracks())yield*f()})()}setLocalVideoMuted(e){var t=this;return F(function*(){var r;if(A.log("Call ".concat(t.callId," setLocalVideoMuted() running ").concat(e)),!e&&t.stopVideoTrackTimer!==void 0&&(clearTimeout(t.stopVideoTrackTimer),t.stopVideoTrackTimer=void 0),!(yield t.client.getMediaHandler().hasVideoDevice()))return t.isLocalVideoMuted();if(!t.hasUserMediaVideoSender&&!e){var i;return(i=t.localUsermediaFeed)===null||i===void 0||i.setAudioVideoMuted(null,e),yield t.upgradeCall(!1,!0),t.isLocalVideoMuted()}if(!e&&t.localUsermediaStream.getVideoTracks().length===0){var s=yield t.client.getMediaHandler().getUserMediaStream(!0,!0);yield t.updateLocalUsermediaStream(s)}return(r=t.localUsermediaFeed)===null||r===void 0||r.setAudioVideoMuted(null,e),t.updateMuteStatus(),yield t.sendMetadataUpdate(),e&&(t.stopVideoTrackTimer=setTimeout(()=>{for(var o of t.localUsermediaStream.getVideoTracks())o.stop(),t.localUsermediaStream.removeTrack(o)},120)),t.isLocalVideoMuted()})()}isLocalVideoMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isVideoMuted())!==null&&e!==void 0?e:!1}setMicrophoneMuted(e){var t=this;return F(function*(){var r;return A.log("Call ".concat(t.callId," setMicrophoneMuted() running ").concat(e)),(yield t.client.getMediaHandler().hasAudioDevice())?!e&&(!t.hasUserMediaAudioSender||!t.hasLocalUserMediaAudioTrack)?(yield t.upgradeCall(!0,!1),t.isMicrophoneMuted()):((r=t.localUsermediaFeed)===null||r===void 0||r.setAudioVideoMuted(e,null),t.updateMuteStatus(),yield t.sendMetadataUpdate(),t.isMicrophoneMuted()):t.isMicrophoneMuted()})()}isMicrophoneMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isAudioMuted())!==null&&e!==void 0?e:!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(var t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(ft.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==rt.Connected)return!1;var e=!0;for(var t of this.peerConn.getTransceivers()){var r=["inactive","recvonly"].includes(t.currentDirection);r||(e=!1)}return e}sendDtmfDigit(e){for(var t of this.peerConn.getSenders()){var r;if(((r=t.track)===null||r===void 0?void 0:r.kind)==="audio"&&t.dtmf){t.dtmf.insertDTMF(e);return}}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){var e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;A.log("Call ".concat(this.callId," updateMuteStatus stream ").concat(this.localUsermediaStream.id," micShouldBeMuted ").concat(e," vidShouldBeMuted ").concat(t)),rr(this.localUsermediaStream.getAudioTracks(),!e),rr(this.localUsermediaStream.getVideoTracks(),!t)}sendMetadataUpdate(){var e=this;return F(function*(){yield e.sendVoipEvent(ee.CallSDPStreamMetadataChangedPrefix,{[pc]:e.getLocalSDPStreamMetadata()})})()}gotCallFeedsForInvite(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(this.successor){this.successor.queueGotCallFeedsForAnswer(e);return}if(this.callHasEnded()){this.stopAllMedia();return}for(var r of e)this.pushLocalFeed(r);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=rt.CreateOffer,A.debug("Call ".concat(this.callId," gotUserMediaForInvite() run"))}sendAnswer(){var e=this;return F(function*(){var t={answer:{sdp:e.peerConn.localDescription.sdp,type:e.peerConn.localDescription.type},[pc]:e.getLocalSDPStreamMetadata(!0)};t.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1};var r=e.discardDuplicateCandidates();A.info("Call ".concat(e.callId," sendAnswer() discarding ").concat(r," candidates that will be sent in answer"));try{yield e.sendVoipEvent(ee.CallAnswer,t),e.inviteOrAnswerSent=!0}catch(o){e.state=rt.Ringing,o instanceof bn&&o.event&&e.client.cancelPendingEvent(o.event);var i=ct.SendAnswer,s="Failed to send answer";throw o.name=="UnknownDeviceError"&&(i=ct.UnknownDevices,s="Unknown devices present in the room"),e.emit(ft.Error,new tl(i,s,o),e),o}e.sendCandidateQueue()})()}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(e)):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){var r=mk.parse(e.sdp);r.media.forEach(i=>{var s=new Map,o=new Map;for(var a of i.rtp)s.set(a.payload,a.codec),o.set(a.codec,a.payload);for(var l of t)if(l.mediaType===i.type){if(!o.has(l.codec)){A.info("Call ".concat(this.callId," mungeSdp() ignoring SDP modifications for ").concat(l.codec," as it's not present."));continue}var c=[];l.enableDtx!==void 0&&c.push("usedtx=".concat(l.enableDtx?"1":"0")),l.maxAverageBitrate!==void 0&&c.push("maxaveragebitrate=".concat(l.maxAverageBitrate));var u=!1;for(var f of i.fmtp)s.get(f.payload)===l.codec&&(u=!0,f.config+=";"+c.join(";"));u||i.fmtp.push({payload:o.get(l.codec),config:c.join(";")})}}),e.sdp=mk.write(r)}createOffer(){var e=this;return F(function*(){var t=yield e.peerConn.createOffer();return e.mungeSdp(t,sN(e.isPtt)),t})()}createAnswer(){var e=this;return F(function*(){var t=yield e.peerConn.createAnswer();return e.mungeSdp(t,sN(e.isPtt)),t})()}gotCallFeedsForAnswer(e){var t=this;return F(function*(){if(!t.callHasEnded()){t.waitForLocalAVStream=!1;for(var r of e)t.pushLocalFeed(r);t.state=rt.CreateAnswer;var i;try{t.getRidOfRTXCodecs(),i=yield t.createAnswer()}catch(s){A.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() failed to create answer: "),s),t.terminate($n.Local,ct.CreateAnswer,!0);return}try{if(yield t.peerConn.setLocalDescription(i),t.callHasEnded()||(t.state=rt.Connecting,yield new Promise(s=>{setTimeout(s,200)}),t.callHasEnded()))return;t.sendAnswer()}catch(s){A.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() error setting local description!"),s),t.terminate($n.Local,ct.SetLocalDescription,!0);return}}})()}onRemoteIceCandidatesReceived(e){var t=this;return F(function*(){if(!t.callHasEnded()){var r=e.getContent(),i=r.candidates;if(!i){A.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!"));return}var s=r.version===0?null:r.party_id||null;if(t.opponentPartyId===void 0){if(s){A.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() buffering ").concat(i.length," candidates until we pick an opponent"));var o=t.remoteCandidateBuffer.get(s)||[];o.push(...i),t.remoteCandidateBuffer.set(s,o)}return}if(!t.partyIdMatches(r)){A.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates from party ID ").concat(r.party_id,": we have chosen party ID ").concat(t.opponentPartyId));return}yield t.addIceCandidates(i)}})()}onAnswerReceived(e){var t=this;return F(function*(){var r=e.getContent();if(A.debug("Call ".concat(t.callId," onAnswerReceived() running (hangupParty=").concat(r.party_id,")")),t.callHasEnded()){A.debug("Call ".concat(t.callId," onAnswerReceived() ignoring answer because call has ended"));return}if(t.opponentPartyId!==void 0){A.info("Call ".concat(t.callId," onAnswerReceived() ignoring answer from party ID ").concat(r.party_id,": we already have an answer/reject from ").concat(t.opponentPartyId));return}t.chooseOpponent(e),yield t.addBufferedIceCandidates(),t.state=rt.Connecting;var i=r[pc];i?t.updateRemoteSDPStreamMetadata(i):A.warn("Call ".concat(t.callId," onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));try{t.isSettingRemoteAnswerPending=!0,yield t.peerConn.setRemoteDescription(r.answer),t.isSettingRemoteAnswerPending=!1,A.debug("Call ".concat(t.callId," onAnswerReceived() set remote description: ").concat(r.answer.type))}catch(s){t.isSettingRemoteAnswerPending=!1,A.debug("Call ".concat(t.callId," onAnswerReceived() failed to set remote description"),s),t.terminate($n.Local,ct.SetRemoteDescription,!1);return}if(t.opponentPartyId!==null)try{yield t.sendVoipEvent(ee.CallSelectAnswer,{selected_party_id:t.opponentPartyId})}catch(s){A.warn("Call ".concat(t.callId," onAnswerReceived() failed to send select_answer event"),s)}})()}onSelectAnswerReceived(e){var t=this;return F(function*(){if(t.direction!==wc.Inbound){A.warn("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for an outbound call: ignoring"));return}var r=e.getContent().selected_party_id;if(r==null){A.warn("Call ".concat(t.callId," onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring"));return}r!==t.ourPartyId&&(A.info("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for party ID ").concat(r,": we are party ID ").concat(t.ourPartyId,".")),yield t.terminate($n.Remote,ct.AnsweredElsewhere,!0))})()}onNegotiateReceived(e){var t=this;return F(function*(){var r=e.getContent(),i=r.description;if(!i||!i.sdp||!i.type){A.info("Call ".concat(t.callId," onNegotiateReceived() ignoring invalid m.call.negotiate event"));return}var s=t.direction===wc.Inbound,o=!t.makingOffer&&(t.peerConn.signalingState==="stable"||t.isSettingRemoteAnswerPending),a=i.type==="offer"&&!o;if(t.ignoreOffer=!s&&a,t.ignoreOffer){A.info("Call ".concat(t.callId," onNegotiateReceived() ignoring colliding negotiate event because we're impolite"));return}var l=t.isLocalOnHold(),c=r[pc];c?t.updateRemoteSDPStreamMetadata(c):A.warn("Call ".concat(t.callId," onNegotiateReceived() received negotiation event without SDPStreamMetadata!"));try{if(t.isSettingRemoteAnswerPending=i.type=="answer",yield t.peerConn.setRemoteDescription(i),t.isSettingRemoteAnswerPending=!1,A.debug("Call ".concat(t.callId," onNegotiateReceived() set remote description: ").concat(i.type)),i.type==="offer"){var u,f;try{t.getRidOfRTXCodecs(),f=yield t.createAnswer()}catch(m){A.debug("Call ".concat(t.callId," onNegotiateReceived() failed to create answer: "),m),t.terminate($n.Local,ct.CreateAnswer,!0);return}yield t.peerConn.setLocalDescription(f),A.debug("Call ".concat(t.callId," onNegotiateReceived() create an answer")),t.sendVoipEvent(ee.CallNegotiate,{lifetime:n2,description:(u=t.peerConn.localDescription)===null||u===void 0?void 0:u.toJSON(),[pc]:t.getLocalSDPStreamMetadata(!0)})}}catch(m){t.isSettingRemoteAnswerPending=!1,A.warn("Call ".concat(t.callId," onNegotiateReceived() failed to complete negotiation"),m)}var p=t.isLocalOnHold();l!==p&&(t.emit(ft.LocalHoldUnhold,p,t),t.emit(ft.HoldUnhold,p))})()}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=v$(this.remoteSDPStreamMetadata||{},e,!0);for(var t of this.getRemoteFeeds()){var r,i=t.stream.id,s=this.remoteSDPStreamMetadata[i];t.setAudioVideoMuted(s==null?void 0:s.audio_muted,s==null?void 0:s.video_muted),t.purpose=(r=this.remoteSDPStreamMetadata[i])===null||r===void 0?void 0:r.purpose}}onSDPStreamMetadataChangedReceived(e){var t=e.getContent(),r=t[pc];this.updateRemoteSDPStreamMetadata(r)}onAssertedIdentityReceived(e){var t=this;return F(function*(){var r=e.getContent();r.asserted_identity&&(t.remoteAssertedIdentity={id:r.asserted_identity.id,displayName:r.asserted_identity.display_name},t.emit(ft.AssertedIdentityChanged,t))})()}callHasEnded(){return this.state===rt.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){var e=this;return F(function*(){e.makingOffer=!0;try{yield e.gotLocalOffer()}catch(t){e.getLocalOfferFailed(t);return}finally{e.makingOffer=!1}})()}gotLocalOffer(){var e=this;return F(function*(){if(A.debug("Call ".concat(e.callId," gotLocalOffer() running")),e.callHasEnded()){A.debug("Call ".concat(e.callId,' gotLocalOffer() ignoring newly created offer because the call has ended"'));return}var t;try{e.getRidOfRTXCodecs(),t=yield e.createOffer()}catch(u){A.debug("Call ".concat(e.callId," gotLocalOffer() failed to create offer: "),u),e.terminate($n.Local,ct.CreateOffer,!0);return}try{yield e.peerConn.setLocalDescription(t)}catch(u){A.debug("Call ".concat(e.callId," gotLocalOffer() error setting local description!"),u),e.terminate($n.Local,ct.SetLocalDescription,!0);return}if(e.peerConn.iceGatheringState==="gathering"&&(yield new Promise(u=>{setTimeout(u,200)})),!e.callHasEnded()){var r=e.state===rt.CreateOffer?ee.CallInvite:ee.CallNegotiate,i={lifetime:n2};if(r===ee.CallInvite&&e.invitee&&(i.invitee=e.invitee),e.state===rt.CreateOffer){var s;i.offer=(s=e.peerConn.localDescription)===null||s===void 0?void 0:s.toJSON()}else{var o;i.description=(o=e.peerConn.localDescription)===null||o===void 0?void 0:o.toJSON()}i.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1},i[pc]=e.getLocalSDPStreamMetadata(!0);var a=e.discardDuplicateCandidates();A.info("Call ".concat(e.callId," gotLocalOffer() discarding ").concat(a," candidates that will be sent in offer"));try{yield e.sendVoipEvent(r,i)}catch(u){A.error("Call ".concat(e.callId," gotLocalOffer() failed to send invite"),u),u instanceof bn&&u.event&&e.client.cancelPendingEvent(u.event);var l=ct.SignallingFailed,c="Signalling failed";e.state===rt.CreateOffer&&(l=ct.SendInvite,c="Failed to send invite"),u.name=="UnknownDeviceError"&&(l=ct.UnknownDevices,c="Unknown devices present in the room"),e.emit(ft.Error,new tl(l,c,u),e),e.terminate($n.Local,l,!1);return}e.sendCandidateQueue(),e.state===rt.CreateOffer&&(e.inviteOrAnswerSent=!0,e.state=rt.InviteSent,e.inviteTimeout=setTimeout(()=>{e.inviteTimeout=void 0,e.state===rt.InviteSent&&e.hangup(ct.InviteTimeout,!1)},n2))}})()}getRidOfRTXCodecs(){if(!(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)){var e=this.transceivers.get(go(sn.Screenshare,"video"));if(!(!e||!e.setCodecPreferences)){var t=RTCRtpReceiver.getCapabilities("video").codecs,r=RTCRtpSender.getCapabilities("video").codecs,i=[];for(var s of[...t,...r])if(s.mimeType!=="video/rtx"){i.push(s);try{e.setCodecPreferences(i)}catch(o){A.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",s,o),i.pop()}}}}}sendVoipEvent(e,t){var r=this;return F(function*(){var i=C1(C1({},t),{},{version:ooe,call_id:r.callId,party_id:r.ourPartyId,conf_id:r.groupCallId});if(r.opponentDeviceId){var s,o=r.toDeviceSeq++,a=C1(C1({},i),{},{device_id:r.client.deviceId,sender_session_id:r.client.getSessionId(),dest_session_id:r.opponentSessionId,seq:o,[IE]:Mse()});r.emit(ft.SendVoipEvent,{type:"toDevice",eventType:e,userId:r.invitee||((s=r.getOpponentMember())===null||s===void 0?void 0:s.userId),opponentDeviceId:r.opponentDeviceId,content:a},r);var l=r.invitee||r.getOpponentMember().userId;if(r.client.getUseE2eForGroupCall()){if(!r.hasOpponentDeviceInfo){A.warn("Call ".concat(r.callId," sendVoipEvent() failed: we do not have opponentDeviceInfo"));return}throw new Error("Unimplemented")}else yield r.client.sendToDevice(e,new Map([[l,new Map([[r.opponentDeviceId,a]])]]))}else{var c;r.emit(ft.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:r.roomId,content:i,userId:r.invitee||((c=r.getOpponentMember())===null||c===void 0?void 0:c.userId)},r),yield r.client.sendEvent(r.roomId,e,i)}})()}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,!(this.state===rt.Ringing||!this.inviteOrAnswerSent)){var t=this.direction===wc.Inbound?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},t)}}discardDuplicateCandidates(){for(var e=0,t=[],r=0;r<this.candidateSendQueue.length;r++){var i=this.candidateSendQueue[r];i.candidate===""?t.push(i):e++}return this.candidateSendQueue=t,e}transfer(e){var t=this;return F(function*(){var r=yield t.client.getProfileInfo(e),i=od(),s={replacement_id:od(),target_user:{id:e,display_name:r.displayname,avatar_url:r.avatar_url},create_call:i};yield t.sendVoipEvent(ee.CallReplaces,s),yield t.terminate($n.Local,ct.Transferred,!0)})()}transferToCall(e){var t=this;return F(function*(){var r,i,s=(r=e.getOpponentMember())===null||r===void 0?void 0:r.userId,o=s?yield t.client.getProfileInfo(s):void 0,a=(i=t.getOpponentMember())===null||i===void 0?void 0:i.userId,l=a?yield t.client.getProfileInfo(a):void 0,c=od(),u={replacement_id:od(),target_user:{id:a,display_name:l==null?void 0:l.displayname,avatar_url:l==null?void 0:l.avatar_url},await_call:c};yield e.sendVoipEvent(ee.CallReplaces,u);var f={replacement_id:od(),target_user:{id:s,display_name:o==null?void 0:o.displayname,avatar_url:o==null?void 0:o.avatar_url},create_call:c};yield t.sendVoipEvent(ee.CallReplaces,f),yield t.terminate($n.Local,ct.Transferred,!0),yield e.terminate($n.Local,ct.Transferred,!0)})()}terminate(e,t,r){var i=this;return F(function*(){var s;if(!i.callHasEnded()){i.hangupParty=e,i.hangupReason=t,i.state=rt.Ended,i.inviteTimeout&&(clearTimeout(i.inviteTimeout),i.inviteTimeout=void 0),i.iceDisconnectedTimeout!==void 0&&(clearTimeout(i.iceDisconnectedTimeout),i.iceDisconnectedTimeout=void 0),i.callLengthInterval&&(clearInterval(i.callLengthInterval),i.callLengthInterval=void 0),i.stopVideoTrackTimer!==void 0&&(clearTimeout(i.stopVideoTrackTimer),i.stopVideoTrackTimer=void 0);for(var[o,a]of i.removeTrackListeners)o.removeEventListener("removetrack",a);i.removeTrackListeners.clear(),i.callStatsAtEnd=yield i.collectCallStats(),i.stopAllMedia(),i.deleteAllFeeds(),i.peerConn&&i.peerConn.signalingState!=="closed"&&i.peerConn.close(),(s=i.stats)===null||s===void 0||s.removeStatsReportGatherer(i.callId),r&&i.emit(ft.Hangup,i),i.client.callEventHandler.calls.delete(i.callId)}})()}stopAllMedia(){A.debug("Call ".concat(this.callId," stopAllMedia() running"));for(var e of this.feeds)if(e.isLocal()&&e.purpose===sn.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===sn.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){A.debug("Call ".concat(this.callId," stopAllMedia() stopping stream (streamId=").concat(e.stream.id,")"));for(var t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(this.listeners(b$.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}sendCandidateQueue(){var e=this;return F(function*(){if(!(e.candidateSendQueue.length===0||e.callHasEnded())){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var r={candidates:t.map(a=>a.toJSON())};e.candidatesEnded&&r.candidates.push({candidate:""}),A.debug("Call ".concat(e.callId," sendCandidateQueue() attempting to send ").concat(t.length," candidates"));try{yield e.sendVoipEvent(ee.CallCandidates,r),e.candidateSendTries=0,e.sendCandidateQueue()}catch(a){if(a instanceof bn&&a.event&&e.client.cancelPendingEvent(a.event),e.candidateSendQueue.push(...t),e.candidateSendTries>5){A.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates on attempt ").concat(e.candidateSendTries,". Giving up on this call."),a);var i=ct.SignallingFailed,s="Signalling failed";e.emit(ft.Error,new tl(i,s,a),e),e.hangup(i,!1);return}var o=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,A.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates. Retrying in ").concat(o,"ms"),a),setTimeout(()=>{e.sendCandidateQueue()},o)}}})()}placeCall(e,t){var r=this;return F(function*(){if(!e)throw new Error("You CANNOT start a call without audio");r.state=rt.WaitLocalMedia;var i;try{var s,o=yield r.client.getMediaHandler().getUserMediaStream(e,t);rr(o.getAudioTracks(),!0),rr(o.getVideoTracks(),!0),i=new dl({client:r.client,roomId:r.roomId,userId:r.client.getUserId(),deviceId:(s=r.client.getDeviceId())!==null&&s!==void 0?s:void 0,stream:o,purpose:sn.Usermedia,audioMuted:!1,videoMuted:!1})}catch(a){r.getUserMediaFailed(a);return}try{yield r.placeCallWithCallFeeds([i])}catch(a){r.placeCallFailed(a);return}})()}placeCallWithCallFeeds(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;r.checkForErrorListener(),r.direction=wc.Outbound,yield r.initOpponentCrypto(),r.client.callEventHandler.calls.set(r.callId,r);var s=yield r.client.checkTurnServers();s||A.warn("Call ".concat(r.callId," placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...")),r.peerConn=r.createPeerConnection(),r.emit(ft.PeerConnectionCreated,r.peerConn,r),r.gotCallFeedsForInvite(e,i)})()}createPeerConnection(){var e,t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel);var r=this.getOpponentMember(),i=r?r.userId:"unknown";return(e=this.stats)===null||e===void 0||e.addStatsReportGatherer(this.callId,i,t),t}partyIdMatches(e){var t=e.version===0?null:e.party_id||null;return t===this.opponentPartyId}chooseOpponent(e){var t,r=e.getContent();if(A.debug("Call ".concat(this.callId," chooseOpponent() running (partyId=").concat(r.party_id,")")),this.opponentVersion=r.version,this.opponentVersion===0?this.opponentPartyId=null:this.opponentPartyId=r.party_id||null,this.opponentCaps=r.capabilities||{},this.opponentMember=(t=this.client.getRoom(this.roomId).getMember(e.getSender()))!==null&&t!==void 0?t:void 0,this.opponentMember){var i;(i=this.stats)===null||i===void 0||i.updateOpponentMember(this.callId,this.opponentMember.userId)}}addBufferedIceCandidates(){var e=this;return F(function*(){var t=e.remoteCandidateBuffer.get(e.opponentPartyId);t&&(A.info("Call ".concat(e.callId," addBufferedIceCandidates() adding ").concat(t.length," buffered candidates for opponent ").concat(e.opponentPartyId)),yield e.addIceCandidates(t)),e.remoteCandidateBuffer.clear()})()}addIceCandidates(e){var t=this;return F(function*(){for(var r of e){(r.sdpMid===null||r.sdpMid===void 0)&&(r.sdpMLineIndex===null||r.sdpMLineIndex===void 0)?A.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE end-of-candidates")):A.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE candidate (sdpMid=").concat(r.sdpMid,", candidate=").concat(r.candidate,")"));try{yield t.peerConn.addIceCandidate(r)}catch(i){t.ignoreOffer?A.debug("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate because ignoring offer"),i):A.info("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate"),i)}}})()}get hasPeerConnection(){return!!this.peerConn}initStats(e){this.stats=e,this.stats.start()}}function rr(n,e){for(var t of n)t.enabled=e}function Sk(){if(typeof window>"u"||typeof document>"u")return!1;try{var n,e,t,r=!!((n=(e=(t=window.RTCPeerConnection)!==null&&t!==void 0?t:window.RTCSessionDescription)!==null&&e!==void 0?e:window.RTCIceCandidate)!==null&&n!==void 0?n:navigator.mediaDevices);if(!r)return A.error("WebRTC is not supported in this browser / environment"),!1}catch(i){return A.error("Exception thrown when trying to access WebRTC",i),!1}return!0}function Iv(n,e,t){if(!Sk())return null;var r=t?t.forceTURN:!1,i={client:n,roomId:e,invitee:t==null?void 0:t.invitee,turnServers:n.getTurnServers(),forceTURN:n.forceTURN||r,opponentDeviceId:t==null?void 0:t.opponentDeviceId,opponentSessionId:t==null?void 0:t.opponentSessionId,groupCallId:t==null?void 0:t.groupCallId},s=new doe(i);return n.reEmitter.reEmit(s,Object.values(ft)),s}var Gc=function(n){return n.DontNotify="dont_notify",n.Notify="notify",n.Coalesce="coalesce",n}({}),WP=function(n){return n.Highlight="highlight",n.Sound="sound",n}({}),foe=function(n){return n.ExactEquals="==",n.LessThan="<",n.GreaterThan=">",n.GreaterThanOrEqual=">=",n.LessThanOrEqual="<=",n}({}),hoe="2";function poe(n){return n==="==2"||n==="2"}var ir=function(n){return n.EventMatch="event_match",n.EventPropertyIs="event_property_is",n.EventPropertyContains="event_property_contains",n.ContainsDisplayName="contains_display_name",n.RoomMemberCount="room_member_count",n.SenderNotificationPermission="sender_notification_permission",n.CallStarted="call_started",n.CallStartedPrefix="org.matrix.msc3914.call_started",n}({}),Lr=function(n){return n.Override="override",n.ContentSpecific="content",n.RoomSpecific="room",n.SenderSpecific="sender",n.Underride="underride",n}({}),Pr=function(n){return n.Master=".m.rule.master",n.IsUserMention=".m.rule.is_user_mention",n.IsRoomMention=".m.rule.is_room_mention",n.ContainsDisplayName=".m.rule.contains_display_name",n.ContainsUserName=".m.rule.contains_user_name",n.AtRoomNotification=".m.rule.roomnotif",n.DM=".m.rule.room_one_to_one",n.EncryptedDM=".m.rule.encrypted_room_one_to_one",n.Message=".m.rule.message",n.EncryptedMessage=".m.rule.encrypted",n.InviteToSelf=".m.rule.invite_for_me",n.MemberEvent=".m.rule.member_event",n.IncomingCall=".m.rule.call",n.SuppressNotices=".m.rule.suppress_notices",n.Tombstone=".m.rule.tombstone",n.PollStart=".m.rule.poll_start",n.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",n.PollEnd=".m.rule.poll_end",n.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",n.PollStartOneToOne=".m.rule.poll_start_one_to_one",n.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",n.PollEndOneToOne=".m.rule.poll_end_one_to_one",n.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",n}({});function oN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function aN(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?oN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):oN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var lN=[Lr.Override,Lr.ContentSpecific,Lr.RoomSpecific,Lr.SenderSpecific,Lr.Underride],moe={".m.rule.is_room_mention":{rule_id:".m.rule.is_room_mention",default:!0,enabled:!0,conditions:[{kind:ir.EventPropertyIs,key:"content.m\\.mentions.room",value:!0},{kind:ir.SenderNotificationPermission,key:"room"}],actions:[Gc.Notify,{set_tweak:WP.Highlight}]},".m.rule.reaction":{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:ir.EventMatch,key:"type",pattern:"m.reaction"}],actions:[Gc.DontNotify]},".org.matrix.msc3786.rule.room.server_acl":{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:ir.EventMatch,key:"type",pattern:ee.RoomServerAcl},{kind:ir.EventMatch,key:"state_key",pattern:""}],actions:[]}},zP=Symbol("UserDefinedRules"),goe=[Pr.Master,zP,Pr.SuppressNotices,Pr.InviteToSelf,Pr.MemberEvent,Pr.IsUserMention,Pr.ContainsDisplayName,Pr.IsRoomMention,Pr.AtRoomNotification,Pr.Tombstone,".m.rule.reaction",".m.rule.room.server_acl",".org.matrix.msc3786.rule.room.server_acl",".m.rule.suppress_edits"],voe={".org.matrix.msc3914.rule.room.call":{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:ir.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:ir.CallStarted}],actions:[Gc.Notify,{set_tweak:WP.Sound,value:"default"}]}},yoe=[zP,Pr.IncomingCall,".org.matrix.msc3914.rule.room.call",Pr.EncryptedDM,Pr.DM,Pr.Message,Pr.EncryptedMessage];function cN(n,e,t,r){var i=e.filter(m=>m.default),s=e.filter(m=>!m.default);function o(m){m===zP?l.push(...s):m in t?(A.warn("Adding default global ".concat(n," push rule ").concat(m)),l.push(t[m])):A.warn("Missing default global ".concat(n," push rule ").concat(m))}var a=0,l=[];for(var c of i){var u=r.indexOf(c.rule_id);if(u===-1){l.push(c);continue}for(;u>a;){var f=r[a];o(f),a+=1}l.push(c),a+=1}for(var p of r.slice(a))o(p);return l}class wo{constructor(e){this.client=e,L(this,"parsedKeys",new Map)}static actionListToActionsObject(e){var t={notify:!1,tweaks:{}};for(var r of e)r===Gc.Notify?t.notify=!0:typeof r=="object"&&(r.value===void 0&&(r.value=!0),t.tweaks[r.set_tweak]=r.value);return t}static rewriteDefaultRules(e){var t=JSON.parse(JSON.stringify(e));return t||(t={}),t.global||(t.global={}),t.global.override||(t.global.override=[]),t.global.underride||(t.global.underride=[]),t.global.override=cN(Lr.Override,t.global.override,moe,goe),t.global.underride=cN(Lr.Underride,t.global.underride,voe,yoe),t}static getPushRuleGlobRegex(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"i",[i,s]=t?["(?<=^|\\W)","(?=\\W|$)"]:["^","$"],o="".concat(t,"-").concat(r,"-").concat(e);return wo.cachedGlobToRegex[o]||(wo.cachedGlobToRegex[o]=new RegExp(i+"("+m$(e)+")"+s,r)),wo.cachedGlobToRegex[o]}updateCachedPushRuleKeys(e){e||(e={}),e.global||(e.global={}),e.global.override||(e.global.override=[]),e.global.room||(e.global.room=[]),e.global.sender||(e.global.sender=[]),e.global.underride||(e.global.underride=[]);var t=new Set(this.parsedKeys.keys());for(var r of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(var i of r)if(i.conditions)for(var s of i.conditions)s.kind===ir.EventMatch&&(t.delete(s.key),this.parsedKeys.set(s.key,wo.partsForDottedKey(s.key)));t.forEach(o=>this.parsedKeys.delete(o))}matchingRuleFromKindSet(e,t){for(var r of lN){var i=t[r];if(i){for(var s of i)if(s.enabled){var o=this.templateRuleToRaw(r,s);if(o&&this.ruleMatchesEvent(o,e))return aN(aN({},s),{},{kind:r})}}}return null}templateRuleToRaw(e,t){var r={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case Lr.Underride:case Lr.Override:r.conditions=t.conditions;break;case Lr.RoomSpecific:if(!t.rule_id)return null;r.conditions.push({kind:ir.EventMatch,key:"room_id",value:t.rule_id});break;case Lr.SenderSpecific:if(!t.rule_id)return null;r.conditions.push({kind:ir.EventMatch,key:"user_id",value:t.rule_id});break;case Lr.ContentSpecific:if(!t.pattern)return null;r.conditions.push({kind:ir.EventMatch,key:"content.body",pattern:t.pattern});break}return r}eventFulfillsCondition(e,t){switch(e.kind){case ir.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case ir.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case ir.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case ir.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case ir.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case ir.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case ir.CallStarted:case ir.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){var r=e.key;if(!r)return!1;var i=this.client.getRoom(t.getRoomId());return i!=null&&i.currentState?i.currentState.mayTriggerNotifOfType(r,t.getSender()):!1}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;var r=this.client.getRoom(t.getRoomId());if(!r||!r.currentState||!r.currentState.members)return!1;var i=r.currentState.getJoinedMemberCount(),s=e.is.match(/^([=<>]*)(\d*)$/);if(!s)return!1;var o=s[1],a=parseInt(s[2]);if(isNaN(a))return!1;switch(o){case"":case"==":return i==a;case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;default:return!1}}eventFulfillsDisplayNameCondition(e,t){var r,i=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(i=t.getClearContent()),!i||!i.body||typeof i.body!="string")return!1;var s=this.client.getRoom(t.getRoomId()),o=s==null||(r=s.currentState)===null||r===void 0?void 0:r.getMember(this.client.credentials.userId);if(!o)return!1;var a=o.name,l=new RegExp("(^|\\W)"+p$(a)+"(\\W|$)","i");return i.body.search(l)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;var r=this.valueForDottedKey(e.key,t);if(typeof r!="string")return!1;if(e.value)return e.value===r;if(typeof e.pattern!="string")return!1;var i=wo.getPushRuleGlobRegex(e.pattern,e.key==="content.body");return!!r.match(i)}eventFulfillsEventPropertyIsCondition(e,t){return!e.key||e.value===void 0?!1:e.value===this.valueForDottedKey(e.key,t)}eventFulfillsEventPropertyContains(e,t){if(!e.key||e.value===void 0)return!1;var r=this.valueForDottedKey(e.key,t);return Array.isArray(r)?r.includes(e.value):!1}eventFulfillsCallStartedCondition(e,t){return["m.ring","m.prompt"].includes(t.getContent()["m.intent"])&&!("m.terminated"in t.getContent())&&(t.getPrevContent()["m.terminated"]!==t.getContent()["m.terminated"]||Md(t.getPrevContent(),{}))}static partsForDottedKey(e){var t=[],r="",i=!1;for(var s of e){if(i){s==="\\"||s==="."?r+=s:r+="\\"+s,i=!1;continue}s=="."?(t.push(r),r=""):s=="\\"?i=!0:r+=s}return i&&(r+="\\"),t.push(r),t}valueForDottedKey(e,t){var r=this.parsedKeys.get(e);r===void 0&&(r=wo.partsForDottedKey(e),this.parsedKeys.set(e,r));var i,s=r[0],o=0;for(s==="content"?(i=t.getContent(),++o):s==="type"?(i=t.getType(),++o):i=t.event;o<r.length;++o){if(g$(i))return;var a=r[o];i=i[a]}return i}matchingRuleForEventWithRulesets(e,t){return!t||e.getSender()===this.client.getSafeUserId()?null:this.matchingRuleFromKindSet(e,t.global)}pushActionsForEventAndRulesets(e,t){var r=this.matchingRuleForEventWithRulesets(e,t);if(!r)return{};var i=wo.actionListToActionsObject(r.actions);return i.tweaks.highlight===void 0&&(i.tweaks.highlight=r.kind==Lr.ContentSpecific),{actions:i,rule:r}}ruleMatchesEvent(e,t){var r;return this.client.supportsIntentionalMentions()&&t.getContent()["m.mentions"]!==void 0&&(e.rule_id===Pr.ContainsUserName||e.rule_id===Pr.ContainsDisplayName||e.rule_id===Pr.AtRoomNotification)?!1:!((r=e.conditions)!==null&&r!==void 0&&r.some(i=>!this.eventFulfillsCondition(i,t)))}actionsForEvent(e){var{actions:t}=this.pushActionsForEventAndRulesets(e,this.client.pushRules);return t||{}}actionsAndRuleForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var t,r=this.getPushRuleAndKindById(e);return(t=r==null?void 0:r.rule)!==null&&t!==void 0?t:null}getPushRuleAndKindById(e){for(var t of["global"]){var r;if(((r=this.client.pushRules)===null||r===void 0?void 0:r[t])!==void 0){for(var i of lN)if(this.client.pushRules[t][i]!==void 0){for(var s of this.client.pushRules[t][i])if(s.rule_id===e)return{rule:s,kind:i}}}}return null}}L(wo,"cachedGlobToRegex",{});var kv=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"],_oe=kv[0],boe=kv[kv.length-1],gs=function(n){return n.SUCCESS="SUCCESS",n.IGNORE="IGNORE",n.PROMPT="PROMPT",n.FAIL_PROMPT="FAIL_PROMPT",n.FAIL_ERROR="FAIL_ERROR",n}({}),to=function(n){return n.Invalid="Invalid homeserver discovery response",n.GenericFailure="Failed to get autodiscovery configuration from server",n.InvalidHsBaseUrl="Invalid base_url for m.homeserver",n.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",n.InvalidIsBaseUrl="Invalid base_url for m.identity_server",n.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",n.InvalidIs="Invalid identity server discovery response",n.MissingWellknown="No .well-known JSON file found",n.InvalidJson="Invalid JSON",n.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",n}({});class it{static fromDiscoveryConfig(e){var t=this;return F(function*(){var r,i={"m.homeserver":{state:it.FAIL_ERROR,error:it.ERROR_INVALID,base_url:null},"m.identity_server":{state:it.PROMPT,error:null,base_url:null}};if(!(e!=null&&e["m.homeserver"]))return A.error("No m.homeserver key in config"),i["m.homeserver"].state=it.FAIL_PROMPT,i["m.homeserver"].error=it.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return A.error("No m.homeserver base_url in config"),i["m.homeserver"].state=it.FAIL_PROMPT,i["m.homeserver"].error=it.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var s=t.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!s)return A.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=it.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var o=yield t.fetchWellKnownObject("".concat(s,"/_matrix/client/versions"));if(!o||!Array.isArray((r=o.raw)===null||r===void 0?void 0:r.versions))return A.error("Invalid /versions response"),i["m.homeserver"].error=it.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=s,Promise.resolve(i);var a=new Set(o.raw.versions),l=!1;for(var c of kv)if(a.has(c)){l=!0;break}if(!l)return A.error("Homeserver does not meet version requirements"),i["m.homeserver"].error=it.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,i["m.homeserver"].base_url=s,Promise.resolve(i);i["m.homeserver"]={state:it.SUCCESS,error:null,base_url:s};var u="";if(e["m.identity_server"]){var f={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:it.FAIL_PROMPT,error:it.ERROR_INVALID_IS,base_url:null}};if(u=t.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!u)return A.error("Invalid base_url for m.identity_server"),f["m.identity_server"].error=it.ERROR_INVALID_IS_BASE_URL,Promise.resolve(f);var p=yield t.fetchWellKnownObject("".concat(u,"/_matrix/identity/v2"));if(!(p!=null&&p.raw)||p.action!==gs.SUCCESS)return A.error("Invalid /v2 response"),f["m.identity_server"].error=it.ERROR_INVALID_IDENTITY_SERVER,f["m.identity_server"].base_url=u,Promise.resolve(f)}return u&&u.toString().length>0&&(i["m.identity_server"]={state:it.SUCCESS,error:null,base_url:u}),Object.keys(e).forEach(m=>{if(m==="m.homeserver"||m==="m.identity_server"){var v=["error","state","base_url"];for(var g of Object.keys(e[m]))v.includes(g)||(i[m][g]=e[m][g])}else i[m]=e[m]}),Promise.resolve(i)})()}static findClientConfig(e){var t=this;return F(function*(){if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var r={"m.homeserver":{state:it.FAIL_ERROR,error:it.ERROR_INVALID,base_url:null},"m.identity_server":{state:it.PROMPT,error:null,base_url:null}},i=e.includes("://")?e:"https://".concat(e),s=yield t.fetchWellKnownObject("".concat(i,"/.well-known/matrix/client"));return!s||s.action!==gs.SUCCESS?(A.error("No response or error when parsing .well-known"),s.reason&&A.error(s.reason),s.action===gs.IGNORE?r["m.homeserver"]={state:it.PROMPT,error:null,base_url:null}:(r["m.homeserver"].state=it.FAIL_PROMPT,r["m.homeserver"].error=it.ERROR_INVALID),Promise.resolve(r)):it.fromDiscoveryConfig(s.raw)})()}static getRawClientConfig(e){var t=this;return F(function*(){var r;if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var i=yield t.fetchWellKnownObject("https://".concat(e,"/.well-known/matrix/client"));return i?(r=i.raw)!==null&&r!==void 0?r:{}:{}})()}static sanitizeWellKnownUrl(e){if(!e)return!1;try{var t,r;try{r=new URL(e)}catch(a){A.error("Could not parse url",a)}if(!((t=r)!==null&&t!==void 0&&t.hostname)||r.protocol!=="http:"&&r.protocol!=="https:")return!1;var i=r.port?":".concat(r.port):"",s=r.pathname?r.pathname:"",o="".concat(r.protocol,"//").concat(r.hostname).concat(i).concat(s);return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(a){return A.error(a),!1}}static fetch(e,t){return this.fetchFn?this.fetchFn(e,t):globalThis.fetch(e,t)}static setFetchFn(e){it.fetchFn=e}static fetchWellKnownObject(e){return F(function*(){var t;try{if(t=yield it.fetch(e,{method:ae.Get,signal:kE(5e3)}),t.status===404)return{raw:{},action:gs.IGNORE,reason:it.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:gs.FAIL_PROMPT,reason:"General failure"}}catch(o){var r=o,i="";return typeof r=="object"&&(i=r==null?void 0:r.message),{error:r,raw:{},action:gs.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield t.json(),action:gs.SUCCESS}}catch(o){var s=o;return{error:s,raw:{},action:gs.FAIL_PROMPT,reason:(s==null?void 0:s.name)==="SyntaxError"?it.ERROR_INVALID_JSON:it.ERROR_INVALID}}})()}}L(it,"ERROR_INVALID",to.Invalid);L(it,"ERROR_GENERIC_FAILURE",to.GenericFailure);L(it,"ERROR_INVALID_HS_BASE_URL",to.InvalidHsBaseUrl);L(it,"ERROR_INVALID_HOMESERVER",to.InvalidHomeserver);L(it,"ERROR_INVALID_IS_BASE_URL",to.InvalidIsBaseUrl);L(it,"ERROR_INVALID_IDENTITY_SERVER",to.InvalidIdentityServer);L(it,"ERROR_INVALID_IS",to.InvalidIs);L(it,"ERROR_MISSING_WELLKNOWN",to.MissingWellknown);L(it,"ERROR_INVALID_JSON",to.InvalidJson);L(it,"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION",to.UnsupportedHomeserverSpecVersion);L(it,"ALL_ERRORS",Object.keys(to));L(it,"FAIL_ERROR",gs.FAIL_ERROR);L(it,"FAIL_PROMPT",gs.FAIL_PROMPT);L(it,"PROMPT",gs.PROMPT);L(it,"SUCCESS",gs.SUCCESS);L(it,"fetchFn",void 0);var Ek=function(n){return n.IS="SERVICE_TYPE_IS",n.IM="SERVICE_TYPE_IM",n}({});class Soe{constructor(e){this.ourEvent=e,L(this,"timeline",void 0),L(this,"ourEventIndex",0),L(this,"paginateTokens",{[ht.Backward]:null,[ht.Forward]:null}),this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return this.paginateTokens[e?ht.Backward:ht.Forward]}setPaginateToken(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.paginateTokens[t?ht.Backward:ht.Forward]=e??null}addEvents(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}class OE{static fromJson(e,t){var r=e.context||{},i=(r.events_before||[]).map(t),s=(r.events_after||[]).map(t),o=new Soe(t(e.result)),a=o.ourEvent.threadRootId;return i=i.filter(l=>l.threadRootId===a),s=s.filter(l=>l.threadRootId===a),o.setPaginateToken(r.start,!0),o.addEvents(i,!0),o.addEvents(s,!1),o.setPaginateToken(r.end,!1),new OE(e.rank,o)}constructor(e,t){this.rank=e,this.context=t}}var bH=function(n){return n.Public="public",n.Private="private",n}({}),ME=function(n){return n.PrivateChat="private_chat",n.TrustedPrivateChat="trusted_private_chat",n.PublicChat="public_chat",n}({}),Wc=function(n){return n.Public="public",n.Invite="invite",n.Private="private",n.Knock="knock",n.Restricted="restricted",n}({}),Eoe=function(n){return n.RoomMembership="m.room_membership",n}({}),Xb=function(n){return n.CanJoin="can_join",n.Forbidden="forbidden",n}({}),YP=function(n){return n.Invited="invited",n.Joined="joined",n.Shared="shared",n.WorldReadable="world_readable",n}({});function uN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function dN(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?uN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):uN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function woe(n,e){var t=!!e.preventReEmit,r=e.decrypt!==!1;function i(s){var o=n.getRoom(s.room_id),a;o&&s.state_key===void 0&&(a=o.findEventById(s.event_id)),!a||a.status?a=new wi(s):(a.setUnsigned(dN(dN({},a.getUnsigned()),s.unsigned)),t=!0);var l=a.getServerAggregatedRelation(un.Replace);if(l!=null&&l.content){var c=i(l);a.makeReplaced(c)}var u=o==null?void 0:o.findThreadForEvent(a);return u&&a.setThread(u),a.isEncrypted()&&(t||n.reEmitter.reEmit(a,[Mt.Decrypted]),r&&n.decryptEventIfNeeded(a)),t||(n.reEmitter.reEmit(a,[Mt.Replaced,Mt.VisibilityChange]),o==null||o.reEmitter.reEmit(a,[Mt.BeforeRedaction])),a}return i}function fN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function mc(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?fN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):fN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}class hN{constructor(e,t,r){this.client=e,this.indexEvent=t,this.directory=r}get id(){var e=this.indexEvent.getStateKey();if(!e)throw new Error("State key not found for branch");return e}get isActive(){return this.indexEvent.getContent().active===!0}get version(){var e;return(e=this.indexEvent.getContent().version)!==null&&e!==void 0?e:1}get roomId(){return this.indexEvent.getRoomId()}delete(){var e=this;return F(function*(){yield e.client.sendStateEvent(e.roomId,ul.name,{},e.id),yield e.client.redactEvent(e.roomId,e.id);var t=(yield e.getVersionHistory())[1];t&&(yield t.delete())})()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){var t=this;return F(function*(){yield t.client.sendStateEvent(t.roomId,ul.name,mc(mc({},t.indexEvent.getContent()),{},{name:e}),t.id)})()}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){var t=this;return F(function*(){yield t.client.sendStateEvent(t.roomId,ul.name,mc(mc({},t.indexEvent.getContent()),{},{locked:e}),t.id)})()}getFileInfo(){var e=this;return F(function*(){var t=yield e.getFileEvent(),r=t.getOriginalContent().file,i=e.client.mxcUrlToHttp(r.url);if(!i)throw new Error("No HTTP URL available for ".concat(r.url));return{info:r,httpUrl:i}})()}getFileEvent(){var e=this;return F(function*(){var t=e.client.getRoom(e.roomId);if(!t)throw new Error("Unknown room");for(var r=t.getUnfilteredTimelineSet().findEventById(e.id);!r&&t.getLiveTimeline().getState(Le.BACKWARDS).paginationToken;)yield e.client.scrollback(t,100),r=t.getUnfilteredTimelineSet().findEventById(e.id);if(!r)throw new Error("Failed to find event");return yield e.client.decryptEventIfNeeded(r),r})()}createNewVersion(e,t,r,i){var s=this;return F(function*(){var o=yield s.directory.createFile(e,t,r,mc(mc({},i??{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:un.Replace,event_id:s.id}}));return yield s.client.sendStateEvent(s.roomId,ul.name,{active:!0,name:e,version:s.version+1},o.event_id),yield s.client.sendStateEvent(s.roomId,ul.name,mc(mc({},s.indexEvent.getContent()),{},{active:!1}),s.id),o})()}getVersionHistory(){var e=this;return F(function*(){var t=[];t.push(e);var r=e.client.getRoom(e.roomId);if(!r)throw new Error("Invalid or unknown room");var i=[...r.getLiveTimeline().getEvents()].reverse(),s,o=yield e.getFileEvent();do if(s=i.find(l=>l.replacingEventId()===o.getId()),s){var a=e.directory.getFile(s.getId());if(a)t.push(a),o=s;else break}while(s);return t})()}}function pN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function Xu(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?pN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):pN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var Coe={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[ee.RoomPowerLevels]:100,[ee.RoomHistoryVisibility]:100,[ee.RoomTombstone]:100,[ee.RoomEncryption]:100,[ee.RoomName]:50,[ee.RoomMessage]:50,[ee.RoomMessageEncrypted]:50,[ee.Sticker]:50},users:{}},Vf=function(n){return n.Viewer="viewer",n.Editor="editor",n.Owner="owner",n}({});class mN{constructor(e,t){if(this.client=e,this.roomId=t,L(this,"room",void 0),this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){var e=this.room.currentState.getStateEvents(ee.SpaceParent);return e!=null&&e.length?e.every(t=>{var r;return!((r=t.getContent())!==null&&r!==void 0&&r.via)}):!0}setName(e){var t=this;return F(function*(){yield t.client.sendStateEvent(t.roomId,ee.RoomName,{name:e},"")})()}invite(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,s=[r.retryInvite(e)];i&&s.push(...r.getDirectories().map(o=>o.invite(e,i))),yield Promise.all(s)})()}retryInvite(e){var t=this;return lie(F(function*(){yield t.client.invite(t.roomId,e).catch(r=>{throw(r==null?void 0:r.errcode)==="M_FORBIDDEN"?new f$.AbortError(r):r})}))}setPermissions(e,t){var r=this;return F(function*(){var i,s=r.room.currentState.getStateEvents(ee.RoomPowerLevels,"");if(Array.isArray(s))throw new Error("Unexpected return type for power levels");var o=(s==null?void 0:s.getContent())||{},a=o.users_default||0,l=o.events_default||50,c=((i=o.events)===null||i===void 0?void 0:i[ee.RoomPowerLevels])||100,u=o.users||{};switch(t){case Vf.Viewer:u[e]=a;break;case Vf.Editor:u[e]=l;break;case Vf.Owner:u[e]=c;break;default:throw new Error("Invalid role: "+t)}o.users=u,yield r.client.sendStateEvent(r.roomId,ee.RoomPowerLevels,o,"")})()}getPermissions(e){var t,r,i=this.room.currentState.getStateEvents(ee.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");var s=(i==null?void 0:i.getContent())||{},o=s.users_default||0,a=s.events_default||50,l=((t=s.events)===null||t===void 0?void 0:t[ee.RoomPowerLevels])||100,c=((r=s.users)===null||r===void 0?void 0:r[e])||o;return c>=l?Vf.Owner:c>=a?Vf.Editor:Vf.Viewer}createDirectory(e){var t=this;return F(function*(){var r=yield t.client.unstableCreateFileTree(e);return yield t.client.sendStateEvent(t.roomId,ee.SpaceChild,{via:[t.client.getDomain()]},r.roomId),yield t.client.sendStateEvent(r.roomId,ee.SpaceParent,{via:[t.client.getDomain()]},t.roomId),r})()}getDirectories(){var e=[],t=this.room.currentState.getStateEvents(ee.SpaceChild);for(var r of t)try{var i=r.getStateKey();if(i){var s=this.client.unstableGetFileTreeSpace(i);s&&e.push(s)}}catch(o){A.warn("Unable to create tree space instance for listing. Are we joined?",o)}return e}getDirectory(e){return this.getDirectories().find(t=>t.roomId===e)}delete(){var e=this;return F(function*(){var t=e.getDirectories();for(var r of t)yield r.delete();var i=[qe.Invite,qe.Knock,qe.Join],s=e.room.currentState.getStateEvents(ee.RoomMember);for(var o of s){var a=o.getStateKey()!==e.client.getUserId();if(a&&i.includes(o.getContent().membership)){var l=o.getStateKey();if(!l)throw new Error("State key not found for branch");yield e.client.kick(e.roomId,l,"Room deleted")}}yield e.client.leave(e.roomId)})()}getOrderedChildren(e){var t=e.map(r=>({roomId:r.getStateKey(),order:r.getContent().order})).filter(r=>r.roomId);return t.sort((r,i)=>{if(r.order&&!i.order)return-1;if(!r.order&&i.order)return 1;if(!r.order&&!i.order){var s,o,a,l,c=this.client.getRoom(r.roomId),u=this.client.getRoom(i.roomId);if(!c||!u)return M_(r.roomId,i.roomId);var f=(s=(o=c.currentState.getStateEvents(ee.RoomCreate,""))===null||o===void 0?void 0:o.getTs())!==null&&s!==void 0?s:0,p=(a=(l=u.currentState.getStateEvents(ee.RoomCreate,""))===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0;return f===p?M_(r.roomId,i.roomId):f-p}else return M_(r.order,i.order)}),t}getParentRoom(){var e=this.room.currentState.getStateEvents(ee.SpaceParent),t=e[0];if(!t)throw new Error("Expected to have a parent in a non-top level space");var r=t.getStateKey();if(!r)throw new Error("No state key found for parent");var i=this.client.getRoom(r);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;var e=this.getParentRoom(),t=e.currentState.getStateEvents(ee.SpaceChild),r=this.getOrderedChildren(t);return r.findIndex(i=>i.roomId===this.roomId)}setOrder(e){var t=this;return F(function*(){var r;if(t.isTopLevel)throw new Error("Cannot set order of top level spaces currently");var i=t.getParentRoom(),s=i.currentState.getStateEvents(ee.SpaceChild),o=t.getOrderedChildren(s);e=Math.max(Math.min(e,o.length-1),0);var a=t.getOrder(),l=a<e;l&&e===o.length-1?e--:!l&&e===0&&e++;var c=o[l?e:e-1],u=o[l?e+1:e],f=iu[0],p=!1;if(!c)u!=null&&u.order&&(f=n5(u.order));else if(e===o.length-1)u!=null&&u.order&&(f=Bm(u.order));else{var m=c==null?void 0:c.order,v=u==null?void 0:u.order;m&&v?m===v?f=Bm(m):f=cie(m,v):m?f=Bm(m):v?f=n5(v):p=!0}if(p){for(var g,S=0;S<=e;S++){var b=o[S];if(S===0&&(g=b.order),b.order)g=b.order;else{var w;g=g?Bm(g):iu[0];var k=i.currentState.getStateEvents(ee.SpaceChild,b.roomId),R=(w=k==null?void 0:k.getContent())!==null&&w!==void 0?w:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,ee.SpaceChild,Xu(Xu({},R),{},{order:g}),b.roomId)}}g&&(f=Bm(g))}var I=i.currentState.getStateEvents(ee.SpaceChild,t.roomId),C=(r=I==null?void 0:I.getContent())!==null&&r!==void 0?r:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,ee.SpaceChild,Xu(Xu({},C),{},{order:f}),t.roomId)})()}createFile(e,t,r,i){var s=this;return F(function*(){var{content_uri:o}=yield s.client.uploadContent(t,{includeFilename:!1});r.url=o;var a={msgtype:La.File,body:e,url:o,file:r};i=i??{},i["m.new_content"]&&(i["m.new_content"]=a);var l=yield s.client.sendMessage(s.roomId,Xu(Xu(Xu({},i),a),{},{[S$.name]:{}}));return yield s.client.sendStateEvent(s.roomId,ul.name,{active:!0,name:e},l.event_id),l})()}getFile(e){var t=this.room.currentState.getStateEvents(ul.name,e);return t?new hN(this.client,t,this):null}listFiles(){return this.listAllFiles().filter(e=>e.isActive)}listAllFiles(){var e,t=(e=this.room.currentState.getStateEvents(ul.name))!==null&&e!==void 0?e:[];return t.map(r=>new hN(this.client,r,this))}}var SH=function(n){return n.Recent="recent",n.Rank="rank",n}({}),ad=function(n){return n.LocalStreamsChanged="local_streams_changed",n}({});class Toe extends En{constructor(e){super(),this.client=e,L(this,"audioInput",void 0),L(this,"audioSettings",void 0),L(this,"videoInput",void 0),L(this,"localUserMediaStream",void 0),L(this,"userMediaStreams",[]),L(this,"screensharingStreams",[]),L(this,"getMediaStreamPromise",void 0)}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}setAudioInput(e){var t=this;return F(function*(){A.info("MediaHandler setAudioInput() running (deviceId=".concat(e,")")),t.audioInput!==e&&(t.audioInput=e,yield t.updateLocalUsermediaStreams())})()}setAudioSettings(e){var t=this;return F(function*(){A.info("MediaHandler setAudioSettings() running (opts=".concat(JSON.stringify(e),")")),t.audioSettings=Object.assign({},e),yield t.updateLocalUsermediaStreams()})()}setVideoInput(e){var t=this;return F(function*(){A.info("MediaHandler setVideoInput() running (deviceId=".concat(e,")")),t.videoInput!==e&&(t.videoInput=e,yield t.updateLocalUsermediaStreams())})()}setMediaInputs(e,t){var r=this;return F(function*(){A.log("MediaHandler setMediaInputs() running (audioInput: ".concat(e," videoInput: ").concat(t,")")),r.audioInput=e,r.videoInput=t,yield r.updateLocalUsermediaStreams()})()}updateLocalUsermediaStreams(){var e=this;return F(function*(){if(e.userMediaStreams.length!==0){var t=new Map;for(var r of e.client.callEventHandler.calls.values())t.set(r.callId,{audio:r.hasLocalUserMediaAudioTrack,video:r.hasLocalUserMediaVideoTrack});for(var i of e.userMediaStreams){A.log("MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=".concat(i.id,")"));for(var s of i.getTracks())s.stop()}e.userMediaStreams=[],e.localUserMediaStream=void 0;for(var o of e.client.callEventHandler.calls.values())if(!(o.callHasEnded()||!t.has(o.callId))){var{audio:a,video:l}=t.get(o.callId);A.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=".concat(o.callId,")"));var c=yield e.getUserMediaStream(a,l);o.callHasEnded()||(yield o.updateLocalUsermediaStream(c))}for(var u of e.client.groupCallEventHandler.groupCalls.values())if(u.localCallFeed){A.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=".concat(u.groupCallId,")"));var f=yield e.getUserMediaStream(!0,u.type===LE.Video);u.state!==On.Ended&&(yield u.updateLocalUsermediaStream(f))}e.emit(ad.LocalStreamsChanged)}})()}hasAudioDevice(){return F(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="audioinput").length>0}catch(t){return A.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}hasVideoDevice(){return F(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="videoinput").length>0}catch(t){return A.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}getUserMediaStream(e,t){var r=arguments,i=this;return F(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:!0;return i.getMediaStreamPromise?i.getMediaStreamPromise=i.getMediaStreamPromise.then(()=>i.getUserMediaStreamInternal(e,t,s)):i.getMediaStreamPromise=i.getUserMediaStreamInternal(e,t,s),i.getMediaStreamPromise})()}getUserMediaStreamInternal(e,t,r){var i=this;return F(function*(){var s=e&&(yield i.hasAudioDevice()),o=t&&(yield i.hasVideoDevice()),a,l=!0;if(i.localUserMediaStream){var c,u;s!==i.localUserMediaStream.getAudioTracks().length>0&&(l=!1),o!==i.localUserMediaStream.getVideoTracks().length>0&&(l=!1),s&&((c=i.localUserMediaStream.getAudioTracks()[0])===null||c===void 0||(c=c.getSettings())===null||c===void 0?void 0:c.deviceId)!==i.audioInput&&(l=!1),o&&((u=i.localUserMediaStream.getVideoTracks()[0])===null||u===void 0||(u=u.getSettings())===null||u===void 0?void 0:u.deviceId)!==i.videoInput&&(l=!1)}else l=!1;if(l){var v;if(a=i.localUserMediaStream.clone(),A.log("MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=".concat((v=i.localUserMediaStream)===null||v===void 0?void 0:v.id," newStreamId=").concat(a.id," shouldRequestAudio=").concat(s," shouldRequestVideo=").concat(o,")")),!s)for(var g of a.getAudioTracks())a.removeTrack(g);if(!o)for(var S of a.getVideoTracks())a.removeTrack(S)}else{var f=i.getUserMediaContraints(s,o);a=yield navigator.mediaDevices.getUserMedia(f),A.log("MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=".concat(a.id,", shouldRequestAudio=").concat(s,", shouldRequestVideo=").concat(o,", constraints=").concat(JSON.stringify(f),")"));for(var p of a.getTracks()){var m=p.getSettings();p.kind==="audio"?i.audioInput=m.deviceId:p.kind==="video"&&(i.videoInput=m.deviceId)}r&&(i.localUserMediaStream=a)}return r&&i.userMediaStreams.push(a),i.emit(ad.LocalStreamsChanged),a})()}stopUserMediaStream(e){A.log("MediaHandler stopUserMediaStream() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var r=this.userMediaStreams.indexOf(e);if(r!==-1&&(A.debug("MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=".concat(e.id,")"),e.id),this.userMediaStreams.splice(r,1)),this.emit(ad.LocalStreamsChanged),this.localUserMediaStream===e)this.localUserMediaStream=void 0;else for(var i of e.getTracks()){var s;if((s=this.localUserMediaStream)!==null&&s!==void 0&&s.getTrackById(i.id)){this.stopUserMediaStream(this.localUserMediaStream);break}}}getScreensharingStream(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{},i=e.length>1&&e[1]!==void 0?e[1]:!0,s;if(t.screensharingStreams.length===0){var o=t.getScreenshareContraints(r);r.desktopCapturerSourceId?(A.debug("MediaHandler getScreensharingStream() calling getUserMedia() (opts=".concat(JSON.stringify(r),")")),s=yield navigator.mediaDevices.getUserMedia(o)):(A.debug("MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=".concat(JSON.stringify(r),")")),s=yield navigator.mediaDevices.getDisplayMedia(o))}else{var a=t.screensharingStreams[t.screensharingStreams.length-1];A.log("MediaHandler getScreensharingStream() cloning (streamId=".concat(a.id,")")),s=a.clone()}return i&&t.screensharingStreams.push(s),t.emit(ad.LocalStreamsChanged),s})()}stopScreensharingStream(e){A.debug("MediaHandler stopScreensharingStream() stopping stream (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var r=this.screensharingStreams.indexOf(e);r!==-1&&(A.debug("MediaHandler stopScreensharingStream() splicing stream out (streamId=".concat(e.id,")")),this.screensharingStreams.splice(r,1)),this.emit(ad.LocalStreamsChanged)}stopAllStreams(){for(var e of this.userMediaStreams){A.log("MediaHandler stopAllStreams() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop()}for(var r of this.screensharingStreams)for(var i of r.getTracks())i.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(ad.LocalStreamsChanged)}getUserMediaContraints(e,t){var r=!!navigator.webkitGetUserMedia;return{audio:e?{deviceId:this.audioInput?{ideal:this.audioInput}:void 0,autoGainControl:this.audioSettings?{ideal:this.audioSettings.autoGainControl}:void 0,echoCancellation:this.audioSettings?{ideal:this.audioSettings.echoCancellation}:void 0,noiseSuppression:this.audioSettings?{ideal:this.audioSettings.noiseSuppression}:void 0}:!1,video:t?{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:r?{exact:640}:{ideal:640},height:r?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(e){var{desktopCapturerSourceId:t,audio:r}=e;return t?{audio:r??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:r??!1,video:!0}}}var gN=function(n){return n.RequestFinished="FINISHED",n.Complete="COMPLETE",n}({}),Ty=function(n){return n.PreProcess="ExtState.PreProcess",n.PostProcess="ExtState.PostProcess",n}({}),wk=function(n){return n.RoomData="SlidingSync.RoomData",n.Lifecycle="SlidingSync.Lifecycle",n}({}),Roe=3;class Ioe{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return Ty.PreProcess}onRequest(e){var t=this;return F(function*(){return e&&(A.log("ExtensionE2EE: invalidating all device lists due to missing 'pos'"),yield t.crypto.markAllTrackedUsersAsDirty()),{enabled:!0}})()}onResponse(e){var t=this;return F(function*(){e.device_lists&&(yield t.crypto.processDeviceLists(e.device_lists)),yield t.crypto.processKeyCounts(e.device_one_time_keys_count,e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]),t.crypto.onSyncCompleted({})})()}}class koe{constructor(e,t){this.client=e,this.cryptoCallbacks=t,L(this,"nextBatch",null)}name(){return"to_device"}when(){return Ty.PreProcess}onRequest(e){var t=this;return F(function*(){return{since:t.nextBatch!==null?t.nextBatch:void 0,limit:100,enabled:!0}})()}onResponse(e){var t=this;return F(function*(){var r=[],i=e.events||[];i.length>0&&t.cryptoCallbacks&&(i=yield t.cryptoCallbacks.preprocessToDeviceMessages(i)),i.map(pH).map(s=>{if(s.getType()==="m.key.verification.cancel"){var o=s.getContent().transaction_id;o&&r.push(o)}return s}).forEach(s=>{var o=s.getContent();if(s.getType()=="m.room.message"&&o.msgtype=="m.bad.encrypted"){A.log("Ignoring undecryptable to-device event from "+s.getSender());return}if(s.getType()==="m.key.verification.start"||s.getType()==="m.key.verification.request"){var a=o.transaction_id;r.includes(a)&&s.flagCancelled()}t.client.emit(Oe.ToDeviceEvent,s)}),t.nextBatch=e.next_batch})()}}class xoe{constructor(e){this.client=e}name(){return"account_data"}when(){return Ty.PostProcess}onRequest(e){return F(function*(){return{enabled:!0}})()}onResponse(e){var t=this;return F(function*(){e.global&&e.global.length>0&&t.processGlobalAccountData(e.global);for(var r in e.rooms){var i=Mh(t.client,r,e.rooms[r]),s=t.client.getRoom(r);if(!s){A.warn("got account data for room but room doesn't exist on client:",r);continue}s.addAccountData(i),i.forEach(o=>{t.client.emit(Oe.Event,o)})}})()}processGlobalAccountData(e){var t=Mh(this.client,void 0,e),r=t.reduce((i,s)=>(i[s.getType()]=this.client.store.getAccountData(s.getType()),i),{});this.client.store.storeAccountDataEvents(t),t.forEach(i=>{if(i.getType()===ee.PushRules){var s=i.getContent();this.client.setPushRules(s)}var o=r[i.getType()];return this.client.emit(Oe.AccountData,i,o),i})}}class Poe{constructor(e){this.client=e}name(){return"typing"}when(){return Ty.PostProcess}onRequest(e){return F(function*(){return{enabled:!0}})()}onResponse(e){var t=this;return F(function*(){if(e!=null&&e.rooms)for(var r in e.rooms)wH(t.client,r,[e.rooms[r]])})()}}class Loe{constructor(e){this.client=e}name(){return"receipts"}when(){return Ty.PostProcess}onRequest(e){return F(function*(){return{enabled:!0}})()}onResponse(e){var t=this;return F(function*(){if(e!=null&&e.rooms)for(var r in e.rooms)wH(t.client,r,[e.rooms[r]])})()}}class EH{constructor(e,t,r,i){this.slidingSync=e,this.client=t,L(this,"opts",void 0),L(this,"syncOpts",void 0),L(this,"syncState",null),L(this,"syncStateData",void 0),L(this,"lastPos",null),L(this,"failCount",0),L(this,"notifEvents",[]),this.opts=dH(r),this.syncOpts=fH(i),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[ke.Timeline,ke.TimelineReset]),this.slidingSync.on(wk.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(wk.RoomData,this.onRoomData.bind(this));var s=[new koe(this.client,this.syncOpts.cryptoCallbacks),new xoe(this.client),new Poe(this.client),new Loe(this.client)];this.syncOpts.cryptoCallbacks&&s.push(new Ioe(this.syncOpts.cryptoCallbacks)),s.forEach(o=>{this.slidingSync.registerExtension(o)})}onRoomData(e,t){var r=this;return F(function*(){var i=r.client.store.getRoom(e);if(!i){if(!t.initial){A.debug("initial flag not set but no stored room exists for room ",e,t);return}i=hH(r.client,e,r.opts)}yield r.processRoomData(r.client,i,t)})()}onLifecycle(e,t,r){switch(r&&A.debug("onLifecycle",e,r),e){case gN.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(Dt.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(Dt.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case gN.RequestFinished:if(r){if(this.failCount+=1,this.updateSyncState(this.failCount>Roe?Dt.Error:Dt.Reconnecting,{error:new bn(r)}),this.shouldAbortSync(new bn(r)))return}else this.failCount=0,A.log("SlidingSyncState.RequestFinished with ".concat(Object.keys((t==null?void 0:t.rooms)||[]).length," rooms"));break}}syncLeftRooms(){return F(function*(){return[]})()}peek(e){return F(function*(){return null})()}stopPeeking(){}setPresence(e){}getSyncState(){return this.syncState}getSyncStateData(){var e;return(e=this.syncStateData)!==null&&e!==void 0?e:null}createRoom(e){var{timelineSupport:t}=this.client,r=new xE(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(r,[ke.Name,ke.Redaction,ke.RedactionCancelled,ke.Receipt,ke.Tags,ke.LocalEchoUpdated,ke.AccountData,ke.MyMembership,ke.Timeline,ke.TimelineReset]),this.registerStateListeners(r),r}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[ut.Events,ut.Members,ut.NewMember,ut.Update]),e.currentState.on(ut.NewMember,(t,r,i)=>{var s;i.user=(s=this.client.getUser(i.userId))!==null&&s!==void 0?s:void 0,this.client.reEmitter.reEmit(i,[Wi.Name,Wi.Typing,Wi.PowerLevel,Wi.Membership])})}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(A.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(Dt.Error,{error:e}),!0):!1}processRoomData(e,t,r){var i=this;return F(function*(){r=Ooe(e,t.roomId,r);var s=Mh(i.client,t.roomId,r.required_state),o=Mh(i.client,t.roomId,r.timeline,!1),a=[];if(r.limited||r.initial){var l=new Set;t.getLiveTimeline().getEvents().forEach(w=>{l.add(w.getId())});for(var c=[],u=[],f=!1,p=o.length-1;p>=0;p--){var m=o[p];if(l.has(m.getId())){f=!0;continue}f?c.push(m):u.unshift(m)}o=u,c.length>0&&t.addEventsToTimeline(c,!0,!1,t.getLiveTimeline(),r.prev_batch)}var v=t.hasEncryptionStateEvent();if(r.notification_count!=null&&t.setUnreadNotificationCount(jt.Total,r.notification_count),r.highlight_count!=null&&(!v||v&&t.getUnreadNotificationCount(jt.Highlight)<=0)&&t.setUnreadNotificationCount(jt.Highlight,r.highlight_count),r.bump_stamp&&t.setBumpStamp(r.bump_stamp),Number.isInteger(r.invited_count)&&t.currentState.setInvitedMemberCount(r.invited_count),Number.isInteger(r.joined_count)&&t.currentState.setJoinedMemberCount(r.joined_count),r.invite_state){var g=Mh(i.client,t.roomId,r.invite_state);yield i.injectRoomEvents(t,g),r.initial&&(t.recalculate(),i.client.store.storeRoom(t),i.client.emit(Oe.Room,t)),g.forEach(w=>{i.client.emit(Oe.Event,w)});return}if(r.limited){var S;t.getLiveTimeline().setPaginationToken((S=r.prev_batch)!==null&&S!==void 0?S:null,Le.BACKWARDS)}yield i.injectRoomEvents(t,s,o,r.num_live),t.addEphemeralEvents(a),t.updateMyMembership(qe.Join),t.setMSC4186SummaryData(r.heroes,r.joined_count,r.invited_count),t.recalculate(),r.initial&&(e.store.storeRoom(t),e.emit(Oe.Room,t)),i.addNotifications(o);var b=function(){var w=F(function*(k){e.emit(Oe.Event,k),k.isState()&&k.getType()==ee.RoomEncryption&&i.syncOpts.cryptoCallbacks&&(yield i.syncOpts.cryptoCallbacks.onCryptoEvent(t,k))});return function(R){return w.apply(this,arguments)}}();yield yh(s,b),yield yh(o,b),a.forEach(function(w){e.emit(Oe.Event,w)}),t.decryptCriticalEvents()})()}injectRoomEvents(e,t){var r=arguments,i=this;return F(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:[],o=r.length>3&&r[3]!==void 0?r[3]:0,a=e.getLiveTimeline(),l=a.getEvents().length==0;if(l){for(var c of t)i.client.getPushActionsForEvent(c);a.initialiseState(t)}l||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));var u=[];o>0&&(u=s.slice(-1*o),s=s.slice(0,-1*u.length)),yield e.addLiveEvents(s,{fromCache:!0,addToState:!1}),u.length>0&&(yield e.addLiveEvents(u,{fromCache:!1,addToState:!1})),e.recalculate(),i.resolveInvites(e)})()}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var t=this.client;e.getMembersWithMembership(qe.Invite).forEach(function(r){if(!r.requestedProfileInfo){r.requestedProfileInfo=!0;var i=t.getUser(r.userId),s;i?s=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):s=t.getProfileInfo(r.userId),s.then(function(o){var a=r.events.member;a.getContent().membership===qe.Invite&&(a.getContent().avatar_url=o.avatar_url,a.getContent().displayname=o.displayname,r.setMembershipEvent(a,e.currentState))},function(o){})}})}}retryImmediately(){return!0}sync(){var e=this;return F(function*(){for(A.debug("Sliding sync init loop");!e.client.isGuest();)try{A.debug("Getting push rules...");var t=yield e.client.getPushRules();A.debug("Got push rules"),e.client.pushRules=t;break}catch(r){if(A.error("Getting push rules failed",r),e.shouldAbortSync(r))return}yield e.slidingSync.start()})()}stop(){A.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){var r=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(Oe.Sync,this.syncState,r,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(var t of e){var r=this.client.getPushActionsForEvent(t);r&&r.notify&&r.tweaks&&r.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this.notifEvents.forEach(e=>{var t;(t=this.client.getNotifTimelineSet())===null||t===void 0||t.addLiveEvent(e,{addToState:!1})}),this.notifEvents=[]}}function Ooe(n,e,t){if(!t.name)return t;for(var r of t.required_state)if(r.type===ee.RoomName&&r.state_key==="")return r.content={name:t.name},t;return t.required_state.push({event_id:"$fake-sliding-sync-name-event-"+e,state_key:"",type:ee.RoomName,content:{name:t.name},sender:n.getUserId(),origin_server_ts:new Date().getTime()}),t}function Mh(n,e,t){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=n.getEventMapper({decrypt:r});return t.map(function(s){return s.room_id=e,i(s)})}function wH(n,e,t){var r=Mh(n,e,t),i=n.getRoom(e);if(!i){A.warn("got ephemeral events for room but room doesn't exist on client:",e);return}i.addEphemeralEvents(r),r.forEach(s=>{n.emit(Oe.Event,s)})}var JP=new Kn("m.beacon_info","org.matrix.msc3672.beacon_info"),Ck=new Kn("m.beacon","org.matrix.msc3672.beacon");class ap{static RETRY_BACKOFF_RATELIMIT(e,t,r){return BP(r,t,!1)}static QUEUE_MESSAGES(e){return e.getType()===ee.RoomMessage||e.hasAssociation()?"message":null}constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ap.RETRY_BACKOFF_RATELIMIT,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ap.QUEUE_MESSAGES;this.retryAlgorithm=e,this.queueAlgorithm=t,L(this,"queues",{}),L(this,"activeQueues",[]),L(this,"procFn",null),L(this,"processQueue",r=>{var i=this.peekNextEvent(r);if(!i){this.disableQueue(r);return}this.queues[r].length,Promise.resolve().then(()=>this.procFn(i.event)).then(s=>{this.removeNextEvent(r),i.event.getId(),i.defer.resolve(s),this.processQueue(r)},s=>{i.attempts+=1;var o=this.retryAlgorithm(i.event,i.attempts,s);i.attempts,i.event.getId(),o===-1?(A.info("Queue '%s' giving up on event %s",r,i.event.getId()),this.clearQueue(r,s)):setTimeout(this.processQueue,o,r)})})}getQueueForEvent(e){var t=this.queueAlgorithm(e);return!t||!this.queues[t]?null:this.queues[t].map(function(r){return r.event})}removeEventFromQueue(e){var t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;var r=!1;return Hb(this.queues[t],i=>i.event.getId()===e.getId()?(r=!0,!0):!1),r}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){var t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);var r=ru();return this.queues[t].push({event:e,defer:r,attempts:0}),e.getId(),this.startProcessingQueues(),r.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter(e=>this.activeQueues.indexOf(e)===-1&&this.queues[e].length>0).forEach(e=>{this.activeQueues.push(e),this.processQueue(e)})}disableQueue(e){var t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),A.info("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){A.info("clearing queue '%s'",e);for(var r;r=this.removeNextEvent(e);)r.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t.shift()}}var vN=20;class Moe{constructor(e){var t=this;this.client=e,L(this,"sending",!1),L(this,"running",!0),L(this,"retryTimeout",null),L(this,"retryAttempts",0),L(this,"sendQueue",F(function*(){if(t.retryTimeout!==null&&clearTimeout(t.retryTimeout),t.retryTimeout=null,!(t.sending||!t.running)){A.debug("Attempting to send queued to-device messages"),t.sending=!0;var r;try{for(;t.running&&(r=yield t.client.store.getOldestToDeviceBatch(),r!==null);)yield t.sendBatch(r),yield t.client.store.removeToDeviceBatch(r.id),t.retryAttempts=0;if(!t.running)return;A.debug("All queued to-device messages sent")}catch(s){++t.retryAttempts;var i=ap.RETRY_BACKOFF_RATELIMIT(null,t.retryAttempts,s);if(i===-1){Math.floor(s.httpStatus/100)===4?(A.error("Fatal error when sending to-device message - dropping to-device batch!",s),yield t.client.store.removeToDeviceBatch(r.id)):A.info("Automatic retry limit reached for to-device messages.");return}A.info("Failed to send batch of to-device messages. Will retry in ".concat(i,"ms"),s),t.retryTimeout=setTimeout(t.sendQueue,i)}finally{t.sending=!1}}})),L(this,"onResumedSync",(r,i)=>{r===Dt.Syncing&&i!==Dt.Syncing&&(A.info("Resuming queue after resumed sync"),this.sendQueue())})}start(){this.running=!0,this.sendQueue(),this.client.on(Oe.Sync,this.onResumedSync)}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(Oe.Sync,this.onResumedSync)}queueBatch(e){var t=this;return F(function*(){for(var r=[],i=0;i<e.batch.length;i+=vN){var s={eventType:e.eventType,batch:e.batch.slice(i,i+vN),txnId:t.client.makeTxnId()};r.push(s);var o=s.batch.map(a=>"".concat(a.userId,"/").concat(a.deviceId," (msgid ").concat(a.payload[IE],")"));A.info("Enqueuing batch of to-device messages. type=".concat(e.eventType," txnid=").concat(s.txnId),o)}yield t.client.store.saveToDeviceBatches(r),t.sendQueue()})()}sendBatch(e){var t=this;return F(function*(){var r=new _l(()=>new Map);for(var i of e.batch)r.getOrCreate(i.userId).set(i.deviceId,i.payload);A.info("Sending batch of ".concat(e.batch.length," to-device messages with ID ").concat(e.id," and txnId ").concat(e.txnId)),yield t.client.sendToDevice(e.eventType,r,e.txnId)})()}}var r2=new is.UnstableValue("m.policies","org.matrix.msc3847.policies"),T1=new is.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),yN=function(n){return n.Ban="m.ban",n}({}),Ah=function(n){return n.User="m.policy.user",n.Room="m.policy.room",n.Server="m.policy.server",n}({}),_N={[Ah.User]:ee.PolicyRuleUser,[Ah.Room]:ee.PolicyRuleRoom,[Ah.Server]:ee.PolicyRuleServer};class Aoe{constructor(e){this.client=e}addRule(e,t,r){var i=this;return F(function*(){var s=yield i.getOrCreateTargetRoom(),o=yield i.client.sendStateEvent(s.roomId,_N[e],{entity:t,reason:r,recommendation:yN.Ban});return o.event_id})()}removeRule(e){var t=this;return F(function*(){yield t.client.redactEvent(e.getRoomId(),e.getId())})()}addSource(e){var t=this;return F(function*(){yield t.client.joinRoom(e);var r=(yield t.getOrCreateSourceRooms()).map(i=>i.roomId);return r.includes(e)?!1:(r.push(e),yield t.withIgnoreInvitesPolicies(i=>{i.sources=r}),!0)})()}getRuleForInvite(e){var t=this;return F(function*(){var{sender:r,roomId:i}=e,s=yield t.getOrCreateSourceRooms(),o=r.split(":")[1],a=i.split(":")[1];for(var l of s){var c=l.getUnfilteredTimelineSet().getLiveTimeline().getState(Le.FORWARDS);for(var{scope:u,entities:f}of[{scope:Ah.Room,entities:[i]},{scope:Ah.User,entities:[r]},{scope:Ah.Server,entities:[o,a]}]){var p=c.getStateEvents(_N[u]);for(var m of p){var v=m.getContent();if((v==null?void 0:v.recommendation)==yN.Ban){var g=v==null?void 0:v.entity;if(g){var S=void 0;try{S=new RegExp(m$(g))}catch{continue}for(var b of f)if(b&&S.test(b))return m}}}}}return null})()}getOrCreateTargetRoom(){var e=this;return F(function*(){var t=e.getIgnoreInvitesPolicies(),r=t.target;if(typeof r!="string"&&(r=null),r){var i=e.client.getRoom(r);if(i)return i;r=null}return r=(yield e.client.createRoom({name:"Individual Policy Room",preset:ME.PrivateChat})).room_id,yield e.withIgnoreInvitesPolicies(s=>{s.target=r}),e.client.getRoom(r)})()}getOrCreateSourceRooms(){var e=this;return F(function*(){var t=e.getIgnoreInvitesPolicies(),r=t.sources,i=!1;Array.isArray(r)||(i=!0,r=[]);var s=r.filter(a=>typeof a=="string").map(a=>e.client.getRoom(a)).filter(a=>!!a);if(s.length!=r.length&&(i=!0),s.length==0){var o=yield e.getOrCreateTargetRoom();i=!0,s=[o]}return i&&(yield e.withIgnoreInvitesPolicies(a=>{a.sources=r})),s})()}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}withIgnoreInvitesPolicies(e){var t=this;return F(function*(){var{policies:r,ignoreInvitesPolicies:i}=t.getPoliciesAndIgnoreInvitesPolicies();e(i),r[T1.name]=i,yield t.client.setAccountData(r2.name,r)})()}getPoliciesAndIgnoreInvitesPolicies(){var e={};for(var t of[r2.name,r2.altName]){var r;if(t){var i=(r=this.client.getAccountData(t))===null||r===void 0?void 0:r.getContent();if(i){e=i;break}}}var s={},o=!1;for(var a of[T1.name,T1.altName])if(a){var l=e[a];if(l&&typeof l=="object"){s=l,o=!0;break}}return o||(e[T1.name]=s),{policies:e,ignoreInvitesPolicies:s}}}var i2="matrix-js-sdk";function Noe(n){if(n.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<n.length;c++){const u=n.charAt(c),f=u.charCodeAt(0);if(e[f]!==255)throw new TypeError(u+" is ambiguous");e[f]=c}const t=n.length,r=n.charAt(0),i=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let u=0,f=0,p=0;const m=c.length;for(;p!==m&&c[p]===0;)p++,u++;const v=(m-p)*s+1>>>0,g=new Uint8Array(v);for(;p!==m;){let w=c[p],k=0;for(let R=v-1;(w!==0||k<f)&&R!==-1;R--,k++)w+=256*g[R]>>>0,g[R]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");f=k,p++}let S=v-f;for(;S!==v&&g[S]===0;)S++;let b=r.repeat(u);for(;S<v;++S)b+=n.charAt(g[S]);return b}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let u=0,f=0,p=0;for(;c[u]===r;)f++,u++;const m=(c.length-u)*i+1>>>0,v=new Uint8Array(m);for(;c[u];){let w=e[c.charCodeAt(u)];if(w===255)return;let k=0;for(let R=m-1;(w!==0||k<p)&&R!==-1;R--,k++)w+=t*v[R]>>>0,v[R]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");p=k,u++}let g=m-p;for(;g!==m&&v[g]===0;)g++;const S=new Uint8Array(f+(m-g));let b=f;for(;g!==m;)S[b++]=v[g++];return S}function l(c){const u=a(c);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var Doe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const zKe=Noe(Doe);var Rr=function(n){return n.UserTrustStatusChanged="userTrustStatusChanged",n.KeyBackupStatus="crypto.keyBackupStatus",n.KeyBackupFailed="crypto.keyBackupFailed",n.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",n.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",n.VerificationRequestReceived="crypto.verificationRequestReceived",n.WillUpdateDevices="crypto.willUpdateDevices",n.DevicesUpdated="crypto.devicesUpdated",n.KeysChanged="crossSigning.keysChanged",n.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",n.DehydratedDeviceCreated="dehydration.DehydratedDeviceCreated",n.DehydratedDeviceUploaded="dehydration.DehydratedDeviceUploaded",n.RehydrationStarted="dehydration.RehydrationStarted",n.RehydrationProgress="dehydration.RehydrationProgress",n.RehydrationCompleted="dehydration.RehydrationCompleted",n.RehydrationError="dehydration.RehydrationError",n.DehydrationKeyCached="dehydration.DehydrationKeyCached",n.DehydratedDeviceRotationError="dehydration.DehydratedDeviceRotationError",n}({}),bN=function(n){return n.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",n.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",n.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",n.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",n.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",n.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",n.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",n.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",n.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",n.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",n.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",n.UNKNOWN_ERROR="UNKNOWN_ERROR",n.MEGOLM_BAD_ROOM="MEGOLM_BAD_ROOM",n.MEGOLM_MISSING_FIELDS="MEGOLM_MISSING_FIELDS",n.OLM_DECRYPT_GROUP_MESSAGE_ERROR="OLM_DECRYPT_GROUP_MESSAGE_ERROR",n.OLM_BAD_ENCRYPTED_MESSAGE="OLM_BAD_ENCRYPTED_MESSAGE",n.OLM_BAD_RECIPIENT="OLM_BAD_RECIPIENT",n.OLM_BAD_RECIPIENT_KEY="OLM_BAD_RECIPIENT_KEY",n.OLM_BAD_ROOM="OLM_BAD_ROOM",n.OLM_BAD_SENDER_CHECK_FAILED="OLM_BAD_SENDER_CHECK_FAILED",n.OLM_BAD_SENDER="OLM_BAD_SENDER",n.OLM_FORWARDED_MESSAGE="OLM_FORWARDED_MESSAGE",n.OLM_MISSING_CIPHERTEXT="OLM_MISSING_CIPHERTEXT",n.OLM_NOT_INCLUDED_IN_RECIPIENTS="OLM_NOT_INCLUDED_IN_RECIPIENTS",n.UNKNOWN_ENCRYPTION_ALGORITHM="UNKNOWN_ENCRYPTION_ALGORITHM",n}({}),joe=function(n){return n[n.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",n[n.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",n}({});class YKe{constructor(e){this.errorOnVerifiedUserProblems=e,L(this,"kind",joe.AllDevicesIsolationMode)}}class JKe{constructor(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=r,L(this,"needsUserApproval",void 0),this.needsUserApproval=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}class XKe{constructor(e){var t,r,i,s,o;L(this,"signedByOwner",void 0),L(this,"crossSigningVerified",void 0),L(this,"tofu",void 0),L(this,"localVerified",void 0),L(this,"trustCrossSignedDevices",void 0),this.signedByOwner=(t=e.signedByOwner)!==null&&t!==void 0?t:!1,this.crossSigningVerified=(r=e.crossSigningVerified)!==null&&r!==void 0?r:!1,this.tofu=(i=e.tofu)!==null&&i!==void 0?i:!1,this.localVerified=(s=e.localVerified)!==null&&s!==void 0?s:!1,this.trustCrossSignedDevices=(o=e.trustCrossSignedDevices)!==null&&o!==void 0?o:!1}isVerified(){return this.localVerified||this.trustCrossSignedDevices&&this.crossSigningVerified}}var ZKe=function(n){return n.Fetch="fetch",n.LoadKeys="load_keys",n}({}),QKe=function(n){return n.Master="master",n.SelfSigning="self_signing",n.UserSigning="user_signing",n}({}),eGe=function(n){return n[n.NONE=0]="NONE",n[n.GREY=1]="GREY",n[n.RED=2]="RED",n}({}),tGe=function(n){return n[n.UNKNOWN=0]="UNKNOWN",n[n.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",n[n.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",n[n.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",n[n.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",n[n.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",n[n.SENT_IN_CLEAR=6]="SENT_IN_CLEAR",n[n.VERIFICATION_VIOLATION=7]="VERIFICATION_VIOLATION",n}({}),Uoe=new Uint8Array(8);function CH(n,e){return Tk.apply(this,arguments)}function Tk(){return Tk=F(function*(n,e){var t=yield globalThis.crypto.subtle.importKey("raw",n,{name:"HKDF"},!1,["deriveBits"]),r=yield globalThis.crypto.subtle.deriveBits({name:"HKDF",salt:Uoe,info:new TextEncoder().encode(e),hash:"SHA-256"},t,512),i=r.slice(0,32),s=r.slice(32),o=globalThis.crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["encrypt","decrypt"]),a=globalThis.crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([o,a])}),Tk.apply(this,arguments)}function TH(n,e,t,r){return Rk.apply(this,arguments)}function Rk(){return Rk=F(function*(n,e,t,r){var i;r?i=Oh(r):(i=new Uint8Array(16),globalThis.crypto.getRandomValues(i),i[8]&=127);var[s,o]=yield CH(e,t),a=new TextEncoder().encode(n),l=yield globalThis.crypto.subtle.encrypt({name:"AES-CTR",counter:i,length:64},s,a),c=yield globalThis.crypto.subtle.sign({name:"HMAC"},o,l);return{iv:D_(i),ciphertext:D_(new Uint8Array(l)),mac:D_(new Uint8Array(c))}}),Rk.apply(this,arguments)}function Foe(n,e,t){return Ik.apply(this,arguments)}function Ik(){return Ik=F(function*(n,e,t){var[r,i]=yield CH(e,t),s=Oh(n.ciphertext);if(!(yield globalThis.crypto.subtle.verify({name:"HMAC"},i,Oh(n.mac),s)))throw new Error("Error decrypting secret ".concat(t,": bad MAC"));var o=yield globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:Oh(n.iv),length:64},r,s);return new TextDecoder().decode(new Uint8Array(o))}),Ik.apply(this,arguments)}var ld="m.secret_storage.v1.aes-hmac-sha2";class RH{constructor(e,t){this.accountDataAdapter=e,this.callbacks=t}getDefaultKeyId(){var e=this;return F(function*(){var t,r=yield e.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return r&&(t=r.key)!==null&&t!==void 0?t:null})()}setDefaultKeyId(e){return new Promise((t,r)=>{var i=o=>{if(o.getType()==="m.secret_storage.default_key"){var a=o.getContent(),l=e===null?Object.keys(a).length===0:a.key===e;l&&(this.accountDataAdapter.removeListener(Oe.AccountData,i),t())}};this.accountDataAdapter.on(Oe.AccountData,i);var s=e===null?{}:{key:e};this.accountDataAdapter.setAccountData("m.secret_storage.default_key",s).catch(o=>{this.accountDataAdapter.removeListener(Oe.AccountData,i),r(o)})})}addKey(e,t,r){var i=this;return F(function*(){if(e!==ld)throw new Error("Unknown key algorithm ".concat(e));var s={algorithm:e};t.name&&(s.name=t.name),t.passphrase&&(s.passphrase=t.passphrase);var{iv:o,mac:a}=yield xk(t.key);if(s.iv=o,s.mac=a,!r)do r=bs(32);while(yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(r)));return yield i.accountDataAdapter.setAccountData("m.secret_storage.key.".concat(r),s),{keyId:r,keyInfo:s}})()}getKey(e){var t=this;return F(function*(){if(e||(e=yield t.getDefaultKeyId()),!e)return null;var r=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(e));return r?[e,r]:null})()}hasKey(e){var t=this;return F(function*(){var r=yield t.getKey(e);return!!r})()}checkKey(e,t){return F(function*(){if(t.algorithm===ld)if(t.mac){var{mac:r}=yield xk(e,t.iv);return kk(t.mac)===kk(r)}else return!0;else throw new Error("Unknown algorithm")})()}store(e,t,r){var i=this;return F(function*(){if(t===null){yield i.accountDataAdapter.setAccountData(e,{});return}var s={};if(!r){var o=yield i.getDefaultKeyId();if(!o)throw new Error("No keys specified and no default key present");r=[o]}if(r.length===0)throw new Error("Zero keys given to encrypt with!");for(var a of r){var l=yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(a));if(!l)throw new Error("Unknown key: "+a);if(l.algorithm===ld){var c={[a]:l},[,u]=yield i.getSecretStorageKey(c,e);s[a]=yield u.encrypt(t)}else A.warn("unknown algorithm for secret storage key "+a+": "+l.algorithm)}yield i.accountDataAdapter.setAccountData(e,{encrypted:s})})()}get(e){var t=this;return F(function*(){var r=yield t.accountDataAdapter.getAccountDataFromServer(e);if(r){if(!r.encrypted)throw new Error("Content is not encrypted!");var i={};for(var s of Object.keys(r.encrypted)){var o=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(s)),a=r.encrypted[s];(o==null?void 0:o.algorithm)===ld&&a.iv&&a.ciphertext&&a.mac&&(i[s]=o)}if(Object.keys(i).length===0)throw new Error("Could not decrypt ".concat(e," because none of ")+"the keys it is encrypted with are for a supported algorithm");var[l,c]=yield t.getSecretStorageKey(i,e),u=r.encrypted[l];return c.decrypt(u)}})()}isStored(e){var t=this;return F(function*(){var r=yield t.accountDataAdapter.getAccountDataFromServer(e);if(!(r!=null&&r.encrypted))return null;var i={};for(var s of Object.keys(r.encrypted)){var o=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(s));if(o){var a=r.encrypted[s];o.algorithm===ld&&a.iv&&a.ciphertext&&a.mac&&(i[s]=o)}}return Object.keys(i).length?i:null})()}getSecretStorageKey(e,t){var r=this;return F(function*(){if(!r.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");var i=yield r.callbacks.getSecretStorageKey({keys:e},t);if(!i)throw new Error("getSecretStorageKey callback returned falsey");if(i.length<2)throw new Error("getSecretStorageKey callback returned invalid data");var[s,o]=i;if(!e[s])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[s].algorithm===ld){var a={encrypt:function(c){return TH(c,o,t)},decrypt:function(c){return Foe(c,o,t)}};return[s,a]}else throw new Error("Unknown key type: "+e[s].algorithm)})()}}function kk(n){for(var e=n.length;e>=1&&n.charCodeAt(e-1)==61;)e--;return e<n.length?n.substring(0,e):n}var $oe="\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";function xk(n,e){return TH($oe,n,"",e)}const Hoe=Object.freeze(Object.defineProperty({__proto__:null,SECRET_STORAGE_ALGORITHM_V1_AES:ld,ServerSideSecretStorageImpl:RH,calculateKeyCheck:xk,trimTrailingEquals:kk},Symbol.toStringTag,{value:"Module"}));var IH=n=>n.type==="livekit"&&"livekit_service_url"in n,Pk=n=>IH(n)&&"livekit_alias"in n,XP=n=>n.type==="livekit"&&"focus_selection"in n,ZP=1e3*60*60*4,Boe=(n,e)=>{var t,r="Malformed session membership event: ";return typeof n.device_id!="string"&&e.push(r+"device_id must be string"),typeof n.call_id!="string"&&e.push(r+"call_id must be string"),typeof n.application!="string"&&e.push(r+"application must be a string"),typeof((t=n.focus_active)===null||t===void 0?void 0:t.type)!="string"&&e.push(r+"focus_active.type must be a string"),Array.isArray(n.foci_preferred)||e.push(r+"foci_preferred must be an array"),n.created_ts&&typeof n.created_ts!="number"&&e.push(r+"created_ts must be number"),n.scope&&typeof n.scope!="string"&&e.push(r+"scope must be string"),e.length===0};class SN{static equal(e,t){return Md(e.membershipData,t.membershipData)}constructor(e,t){this.parentEvent=e,L(this,"membershipData",void 0);var r=[];if(Boe(t,r))this.membershipData=t;else throw Error("unknown CallMembership data. Does not match MSC4143 call.member (".concat(r.join(" & "),") events this could be a legacy membership event: (").concat(t,")"))}get sender(){return this.parentEvent.getSender()}get eventId(){return this.parentEvent.getId()}get callId(){return this.membershipData.call_id}get deviceId(){return this.membershipData.device_id}get application(){return this.membershipData.application}get scope(){return this.membershipData.scope}get membershipID(){return this.createdTs().toString()}createdTs(){var e;return(e=this.membershipData.created_ts)!==null&&e!==void 0?e:this.parentEvent.getTs()}getAbsoluteExpiry(){var e;return this.createdTs()+((e=this.membershipData.expires)!==null&&e!==void 0?e:ZP)}getMsUntilExpiry(){return this.getAbsoluteExpiry()-Date.now()}isExpired(){return this.getMsUntilExpiry()<=0}getPreferredFoci(){return this.membershipData.foci_preferred}getFocusSelection(){var e=this.membershipData.focus_active;if(XP(e))return e.focus_selection}}var Sd=function(n){return n.Cancel="cancel",n.Restart="restart",n.Send="send",n}({}),QP=function(n){return n.TooNew="TOO_NEW",n}({});class eL extends Error{constructor(e){var t="Crypto store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again";super(t),this.reason=e,this.name="InvalidCryptoStoreError"}}L(eL,"TOO_NEW",QP.TooNew);class Voe extends Error{constructor(e,t){super(e),this.value=t}}class qoe extends Error{constructor(){super("MatrixClient has been stopped")}}class jc extends Error{constructor(e,t){super(e),this.clientEndpoint=t,this.name="UnsupportedDelayedEventsEndpointError"}}var Cc=function(n){return n.Disconnected="Disconnected",n.Connecting="Connecting",n.ConnectingFailed="ConnectingFailed",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Stuck="Stuck",n.Unknown="Unknown",n}({}),j_=(n,e,t)=>n.sender===e&&n.deviceId===t;class Koe{constructor(e,t){this.membershipLoopHandler=e,L(this,"logger",void 0),L(this,"running",!1),L(this,"wakeup",r=>{this.logger.error("Cannot call wakeup before calling `startWithJoin()`")}),L(this,"_actions",[]),this.logger=(t??A).getChild("[NewMembershipActionScheduler]")}get actions(){return this._actions}startWithJoin(){var e=this;return F(function*(){if(e.running){e.logger.error("Cannot call startWithJoin() on NewMembershipActionScheduler while already running");return}e.running=!0,e._actions=[{ts:Date.now(),type:ot.SendDelayedEvent}];try{for(var t=function*(){e._actions.sort((c,u)=>c.ts-u.ts);var i=e._actions[0],s=void 0,o=new Promise(c=>{e.wakeup=u=>{s=u,c()}});i.ts>Date.now()&&(yield Promise.race([o,nu(i.ts-Date.now())]));var a={};if(!s){e.logger.debug("Current MembershipManager processing: ".concat(i.type,`
32
32
  Queue:`),e._actions,`
33
- Date.now: "`.concat(Date.now()));try{a=yield e.membershipLoopHandler(i.type)}catch(c){throw Error("The MembershipManager shut down because of the end condition: ".concat(c))}}e._actions.splice(0,1);var l=s??a;"replace"in l?e._actions=l.replace:"insert"in l&&e._actions.push(...l.insert)};e._actions.length>0;)yield*t()}finally{e.running=!1}e.logger.debug("Leave MembershipManager ActionScheduler loop (no more actions)")})()}initiateJoin(){var e;(e=this.wakeup)===null||e===void 0||e.call(this,{replace:[{ts:Date.now(),type:ot.SendDelayedEvent}]})}initiateLeave(){var e;(e=this.wakeup)===null||e===void 0||e.call(this,{replace:[{ts:Date.now(),type:ot.SendScheduledDelayedLeaveEvent}]})}}var EN=function(n){return n.StatusChanged="StatusChanged",n}({}),ot=function(n){return n.SendDelayedEvent="SendDelayedEvent",n.SendJoinEvent="SendJoinEvent",n.RestartDelayedEvent="RestartDelayedEvent",n.UpdateExpiry="UpdateExpiry",n.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",n.SendLeaveEvent="SendLeaveEvent",n}({});class Zb extends En{isActivated(){return this.activated}isJoined(){return this.isActivated()}join(e,t,r){if(this.scheduler.running){this.logger.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=t,this.leavePromiseDefer=void 0,this.activated=!0,this.oldStatus=this.status,this.state=Zb.defaultState,this.scheduler.startWithJoin().catch(i=>{this.logger.error("MembershipManager stopped because: ",i),r==null||r(i)}).finally(()=>{if(this.activated=!1,this.oldStatus&&this.oldStatus!==this.status&&this.emit(EN.StatusChanged,this.oldStatus,this.status),!this.scheduler.running){var i;(i=this.leavePromiseDefer)===null||i===void 0||i.resolve(!0),this.leavePromiseDefer=void 0}})}leave(e){return this.scheduler.running?(this.leavePromiseDefer||(this.leavePromiseDefer=ru(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var t;return(t=this.leavePromiseDefer)===null||t===void 0?void 0:t.resolve(!1)},e)),this.leavePromiseDefer.promise):(this.logger.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}onRTCSessionMemberUpdate(e){var t=this;return F(function*(){var r=t.client.getUserId(),i=t.client.getDeviceId();if(r&&i&&t.isJoined()&&!e.some(o=>j_(o,r,i))){var s=[ot.SendDelayedEvent,ot.SendJoinEvent];t.logger.warn("Missing own membership: force re-join"),t.scheduler.actions.find(o=>s.includes(o.type))?t.logger.error("NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",t.scheduler.actions):(t.state.hasMemberStateEvent=!1,t.scheduler.initiateJoin())}return Promise.resolve()})()}getActiveFocus(){if(this.focusActive)if(XP(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else this.logger.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}constructor(e,t,r,i,s){super(),this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,L(this,"activated",!1),L(this,"logger",void 0),L(this,"leavePromiseDefer",void 0),L(this,"oldStatus",void 0),L(this,"scheduler",void 0),L(this,"state",void 0),L(this,"deviceId",void 0),L(this,"stateKey",void 0),L(this,"fociPreferred",void 0),L(this,"focusActive",void 0),L(this,"membershipServerSideExpiryTimeoutOverride",void 0),this.logger=(s??A).getChild("[NewMembershipManager]");var[o,a]=[this.client.getUserId(),this.client.getDeviceId()];if(o===null)throw Error("Missing userId in client");if(a===null)throw Error("Missing deviceId in client");this.deviceId=a,this.stateKey=this.makeMembershipStateKey(o,a),this.state=Zb.defaultState,this.scheduler=new Koe(l=>(this.oldStatus&&(this.logger.debug("MembershipManager applied action changes. Status: ".concat(this.oldStatus," -> ").concat(this.status)),this.oldStatus!==this.status&&this.emit(EN.StatusChanged,this.oldStatus,this.status)),this.oldStatus=this.status,this.logger.debug("MembershipManager before processing action. status=".concat(this.oldStatus)),this.membershipLoopHandler(l)),this.logger)}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1}}get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get membershipEventExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:ZP}get membershipEventExpiryTimeoutHeadroom(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeoutHeadroom)!==null&&e!==void 0?e:5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryTimeout*e-this.membershipEventExpiryTimeoutHeadroom}get membershipServerSideExpiryTimeout(){var e,t,r;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(r=this.joinConfig)===null||r===void 0?void 0:r.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get maximumRateLimitRetryCount(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.maximumRateLimitRetryCount)!==null&&e!==void 0?e:10}get maximumNetworkErrorRetryCount(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.maximumNetworkErrorRetryCount)!==null&&e!==void 0?e:10}membershipLoopHandler(e){var t=this;return F(function*(){switch(e){case ot.SendDelayedEvent:return t.state.delayId?t.cancelKnownDelayIdBeforeSendFirstDelayedEvent(t.state.delayId):t.sendOrResendDelayedLeaveEvent();case ot.RestartDelayedEvent:return t.state.delayId?t.restartDelayedEvent(t.state.delayId):Ls(ot.SendDelayedEvent);case ot.SendScheduledDelayedLeaveEvent:return t.state.hasMemberStateEvent?t.state.delayId?t.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(t.state.delayId):Ls(ot.SendLeaveEvent):{replace:[]};case ot.SendJoinEvent:return t.sendJoinEvent();case ot.UpdateExpiry:return t.updateExpiryOnJoinedEvent();case ot.SendLeaveEvent:return t.state.hasMemberStateEvent?t.sendFallbackLeaveEvent():{replace:[]}}})()}sendOrResendDelayedLeaveEvent(){var e=this;return F(function*(){return yield e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},ee.GroupCallMemberPrefix,{},e.stateKey).then(t=>(e.resetRateLimitCounter(ot.SendDelayedEvent),e.state.delayId=t.delay_id,e.state.hasMemberStateEvent?Ls(ot.RestartDelayedEvent,e.membershipKeepAlivePeriod):Ls(ot.SendJoinEvent))).catch(t=>{var r=ot.SendDelayedEvent;if(e.manageMaxDelayExceededSituation(t))return Ls(r);var i=e.actionUpdateFromErrors(t,r,"sendDelayedStateEvent");if(i)return i;if(e.state.hasMemberStateEvent){if(e.isUnsupportedDelayedEndpoint(t))return{};throw Error("Could not send delayed event, even though delayed events are supported. "+t)}else return e.isUnsupportedDelayedEndpoint(t)?e.logger.info("Not using delayed event because the endpoint is not supported"):e.logger.info("Not using delayed event because: "+t),Ls(ot.SendJoinEvent)})})()}cancelKnownDelayIdBeforeSendFirstDelayedEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Cancel).then(()=>(t.state.delayId=void 0,t.resetRateLimitCounter(ot.SendDelayedEvent),s2(ot.SendDelayedEvent))).catch(r=>{var i=ot.SendDelayedEvent,s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;if(t.isNotFoundError(r))return t.state.delayId=void 0,s2(i);if(t.isUnsupportedDelayedEndpoint(r))return s2(ot.SendJoinEvent);throw Error("We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle")})})()}restartDelayedEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Restart).then(()=>(t.resetRateLimitCounter(ot.RestartDelayedEvent),Ls(ot.RestartDelayedEvent,t.membershipKeepAlivePeriod))).catch(r=>{var i=ot.RestartDelayedEvent;if(t.isNotFoundError(r))return t.state.delayId=void 0,Ls(ot.SendDelayedEvent);if(t.isUnsupportedDelayedEndpoint(r))return{};var s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;throw Error("Could not restart delayed event, even though delayed events are supported. "+r)})})()}sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Send).then(()=>(t.state.hasMemberStateEvent=!1,t.resetRateLimitCounter(ot.SendScheduledDelayedLeaveEvent),{replace:[]})).catch(r=>{var i=ot.SendLeaveEvent;if(t.isUnsupportedDelayedEndpoint(r))return{};if(t.isNotFoundError(r))return t.state.delayId=void 0,Ls(i);var s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");return s||(t.logger.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",r),Ls(i))})})()}sendJoinEvent(){var e=this;return F(function*(){return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryTimeout),e.stateKey).then(()=>(e.state.startTime=Date.now(),e.state.expireUpdateIterations=1,e.state.hasMemberStateEvent=!0,e.resetRateLimitCounter(ot.SendJoinEvent),{insert:[{ts:Date.now(),type:ot.RestartDelayedEvent},{ts:e.computeNextExpiryActionTs(e.state.expireUpdateIterations),type:ot.UpdateExpiry}]})).catch(t=>{var r=e.actionUpdateFromErrors(t,ot.SendJoinEvent,"sendStateEvent");if(r)return r;throw t})})()}updateExpiryOnJoinedEvent(){var e=this;return F(function*(){var t=e.state.expireUpdateIterations+1;return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryTimeout*t),e.stateKey).then(()=>(e.resetRateLimitCounter(ot.UpdateExpiry),e.state.expireUpdateIterations=t,{insert:[{ts:e.computeNextExpiryActionTs(t),type:ot.UpdateExpiry}]})).catch(r=>{var i=e.actionUpdateFromErrors(r,ot.UpdateExpiry,"sendStateEvent");if(i)return i;throw r})})()}sendFallbackLeaveEvent(){var e=this;return F(function*(){return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,{},e.stateKey).then(()=>(e.resetRateLimitCounter(ot.SendLeaveEvent),e.state.hasMemberStateEvent=!1,{replace:[]})).catch(t=>{var r=e.actionUpdateFromErrors(t,ot.SendLeaveEvent,"sendStateEvent");if(r)return r;throw t})})()}makeMembershipStateKey(e,t){var r="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.fociPreferred)!==null&&t!==void 0?t:[]}}isNotFoundError(e){return e instanceof bn&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof bn&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var t=e.data["org.matrix.msc4140.max_delay"];return typeof t=="number"&&this.membershipServerSideExpiryTimeout>t&&(this.membershipServerSideExpiryTimeoutOverride=t),this.logger.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,t,r){var i=this.actionUpdateFromRateLimitError(e,r,t);if(i)return i;var s=this.actionUpdateFromNetworkErrorRetry(e,t);if(s)return s}actionUpdateFromRateLimitError(e,t,r){var i;if((e instanceof su||e instanceof bn)&&e.isRateLimitError()){var s=(i=this.state.rateLimitRetries.get(r))!==null&&i!==void 0?i:0;if(s<this.maximumRateLimitRetryCount){var o,a=5e3;try{var l;o=(l=e.getRetryAfterMs())!==null&&l!==void 0?l:a,this.logger.info("Rate limited by server, retrying in ".concat(o,"ms"))}catch(c){this.logger.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(a),c),o=a}return this.state.rateLimitRetries.set(r,s+1),Ls(r,o)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+t+"): "+e)}}actionUpdateFromNetworkErrorRetry(e,t){var r,i=(r=this.state.networkErrorRetries.get(t))!==null&&r!==void 0?r:0,s=this.callMemberEventRetryDelayMinimum/1e3+"s",o="("+i+"/"+this.maximumNetworkErrorRetryCount+")";if(e instanceof Error&&e.name==="AbortError")this.logger.warn("Network local timeout error while sending event, retrying in "+s+" "+o,e);else if(e instanceof Error&&e.message.includes("updating delayed event"))this.logger.warn("delayed event update timeout error, retrying in "+s+" "+o,e);else if(e instanceof Jd)this.logger.warn("Network connection error while sending event, retrying in "+s+" "+o,e);else if((e instanceof su||e instanceof bn)&&typeof e.httpStatus=="number"&&e.httpStatus>=500&&e.httpStatus<600)this.logger.warn("Server error while sending event, retrying in "+s+" "+o,e);else return;if(i<this.maximumNetworkErrorRetryCount)return this.state.networkErrorRetries.set(t,i+1),Ls(t,this.callMemberEventRetryDelayMinimum);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof jc}resetRateLimitCounter(e){this.state.rateLimitRetries.set(e,0),this.state.networkErrorRetries.set(e,0)}get status(){var e=this.scheduler.actions;if(e.length===1){var{type:t}=e[0];switch(t){case ot.SendDelayedEvent:case ot.SendJoinEvent:return Cc.Connecting;case ot.UpdateExpiry:return Cc.Connected;case ot.SendScheduledDelayedLeaveEvent:case ot.SendLeaveEvent:return Cc.Disconnecting}}else if(e.length===2){var r=e.map(s=>s.type);if((r.includes(ot.RestartDelayedEvent)||r.includes(ot.SendDelayedEvent)&&this.state.hasMemberStateEvent)&&r.includes(ot.UpdateExpiry))return Cc.Connected}else if(e.length===3){var i=e.map(s=>s.type);if(i.filter(s=>s===ot.RestartDelayedEvent).length===2&&i.includes(ot.UpdateExpiry))return Cc.Connected}return this.scheduler.running?(this.logger.error("MembershipManager has an unknown state. Actions: ",e),Cc.Unknown):Cc.Disconnected}}function Ls(n,e){return{insert:[{ts:Date.now()+(e??0),type:n}]}}function s2(n,e){return{replace:[{ts:Date.now()+0,type:n}]}}var Uc=function(n){return n.ReceivedKeys="received_keys",n}({});class kH extends En{constructor(e,t,r,i){super(),this.room=e,this.client=t,this.statistics=r,L(this,"logger",void 0),this.logger=(i??A).getChild("[RoomKeyTransport]")}start(){this.room.on(ke.Timeline,e=>void this.consumeCallEncryptionEvent(e))}stop(){this.room.off(ke.Timeline,e=>void this.consumeCallEncryptionEvent(e))}consumeCallEncryptionEvent(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;if(yield r.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){i?r.logger.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason)):(r.logger.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason," will retry once only")),setTimeout(()=>void r.consumeCallEncryptionEvent(e,!0),1e3));return}else i&&r.logger.info("Decryption succeeded for event ".concat(e.getId()," after retry"));if(e.getType()!==ee.CallEncryptionKeysPrefix)return Promise.resolve();if(!r.room)return r.logger.error("Got room state event for unknown room ".concat(e.getRoomId(),"!")),Promise.resolve();r.onEncryptionEvent(e)})()}sendKey(e,t,r){var i=this;return F(function*(){var s={keys:[{index:t,key:e}],device_id:i.client.getDeviceId(),call_id:"",sent_ts:Date.now()};try{yield i.client.sendEvent(i.room.roomId,ee.CallEncryptionKeysPrefix,s)}catch(a){i.logger.error("Failed to send call encryption keys",a);var o=a;throw o.event&&i.client.cancelPendingEvent(o.event),a}})()}onEncryptionEvent(e){var t=e.getSender(),r=e.getContent(),i=r.device_id,s=r.call_id;if(!t){this.logger.warn("Received m.call.encryption_keys with no userId: callId=".concat(s));return}if(s!==""){this.logger.warn("Received m.call.encryption_keys with unsupported callId: userId=".concat(t,", deviceId=").concat(i,", callId=").concat(s));return}if(!Array.isArray(r.keys)){this.logger.warn("Received m.call.encryption_keys where keys wasn't an array: callId=".concat(s));return}if(t===this.client.getUserId()&&i===this.client.getDeviceId()){this.logger.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;var o=Date.now()-(typeof r.sent_ts=="number"?r.sent_ts:e.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=o;for(var a of r.keys){if(!a){this.logger.info("Ignoring false-y key in keys event");continue}var l=a.key,c=a.index;!l||c===void 0||c===null||s===void 0||s===null||typeof i!="string"||typeof s!="string"||typeof l!="string"||typeof c!="number"?this.logger.warn("Malformed call encryption_key: userId=".concat(t,", deviceId=").concat(i,", encryptionKeyIndex=").concat(c," callId=").concat(s)):(this.logger.debug("onCallEncryption userId=".concat(t,":").concat(i," encryptionKeyIndex=").concat(c," age=").concat(o,"ms")),this.emit(Uc.ReceivedKeys,t,i,l,c,e.getTs()))}}}class Goe extends En{constructor(e,t,r,i,s,o){super(),this.userId=e,this.deviceId=t,this.roomId=r,this.client=i,this.statistics=s,L(this,"logger",void 0),L(this,"onToDeviceEvent",a=>{if(a.getType()===ee.CallEncryptionKeysPrefix){var l=this.getValidEventContent(a);l&&a.getSender()&&this.receiveCallKeyEvent(a.getSender(),l)}}),this.logger=(o??A).getChild("[ToDeviceKeyTransport]")}start(){this.client.on(Oe.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.off(Oe.ToDeviceEvent,this.onToDeviceEvent)}sendKey(e,t,r){var i=this;return F(function*(){var s={keys:{index:t,key:e},room_id:i.roomId,member:{claimed_device_id:i.deviceId},session:{call_id:"",application:"m.call",scope:"m.room"}},o=r.filter(a=>a.sender==null||a.deviceId==null?(i.logger.warn("Malformed call member: ".concat(a.sender,"|").concat(a.deviceId)),!1):!(a.sender==i.userId&&a.deviceId==i.deviceId)).map(a=>({userId:a.sender,deviceId:a.deviceId}));o.length>0?(yield i.client.encryptAndSendToDevice(ee.CallEncryptionKeysPrefix,o,s),i.statistics.counters.roomEventEncryptionKeysSent+=1):i.logger.warn("No targets found for sending key")})()}receiveCallKeyEvent(e,t){this.statistics.counters.roomEventEncryptionKeysReceived+=1;var r=Date.now(),i=r-(typeof t.sent_ts=="number"?t.sent_ts:r);this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=i,this.emit(Uc.ReceivedKeys,e,t.member.claimed_device_id,t.keys.key,t.keys.index,r)}getValidEventContent(e){var t=e.getContent(),r=t.room_id;if(!r){this.logger.warn("Malformed Event: invalid call encryption keys event, no roomId");return}if(r!==this.roomId){this.logger.warn("Malformed Event: Mismatch roomId");return}if(!t.keys||!t.keys.key||typeof t.keys.index!="number"){this.logger.warn("Malformed Event: Missing keys field");return}if(!t.member||!t.member.claimed_device_id){this.logger.warn("Malformed Event: Missing claimed_device_id");return}return t}}var xv=function(n){return n.EnabledTransportsChanged="enabled_transports_changed",n}({});class Lk extends En{constructor(e,t,r,i,s,o){var a;super(),a=this,L(this,"logger",void 0),L(this,"roomKeyTransport",void 0),L(this,"toDeviceTransport",void 0),L(this,"_enabled",{toDevice:!0,room:!1}),this.logger=(o??A).getChild("[RoomAndToDeviceTransport]"),this.roomKeyTransport=new kH(r,i,s,this.logger),this.toDeviceTransport=new Goe(e,t,r.roomId,i,s,this.logger),this.roomKeyTransport.on(Uc.ReceivedKeys,function(){a._enabled.room||(a.logger.debug("Received room key, enabling room key transport, disabling toDevice transport"),a.setEnabled({toDevice:!1,room:!0}));for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];a.emit(Uc.ReceivedKeys,...c)}),this.toDeviceTransport.on(Uc.ReceivedKeys,function(){if(a._enabled.toDevice){for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];a.emit(Uc.ReceivedKeys,...c)}else a.logger.debug("To Device transport is disabled, ignoring received keys")})}setEnabled(e){(this.enabled.toDevice!==e.toDevice||this.enabled.room!==e.room)&&(this._enabled=e,this.emit(xv.EnabledTransportsChanged,e))}get enabled(){return this._enabled}start(){this.roomKeyTransport.start(),this.toDeviceTransport.start()}stop(){this.roomKeyTransport.stop(),this.toDeviceTransport.stop()}sendKey(e,t,r){var i=this;return F(function*(){i.logger.debug("Sending key with index ".concat(t," to call members (count=").concat(r.length,") via:")+(i._enabled.room?"room transport":"")+(i._enabled.room&&i._enabled.toDevice?"and":"")+(i._enabled.toDevice?"to device transport":"")),i._enabled.room&&(yield i.roomKeyTransport.sendKey(e,t,r)),i._enabled.toDevice&&(yield i.toDeviceTransport.sendKey(e,t,r))})()}}class Woe{get updateEncryptionKeyThrottle(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.useKeyDelay)!==null&&e!==void 0?e:5e3}constructor(e,t,r,i,s,o,a){var l=this;this.userId=e,this.deviceId=t,this.getMemberships=r,this.transport=i,this.statistics=s,this.onEncryptionKeysChanged=o,L(this,"manageMediaKeys",!1),L(this,"keysEventUpdateTimeout",void 0),L(this,"makeNewKeyTimeout",void 0),L(this,"setNewKeyTimeouts",new Set),L(this,"encryptionKeys",new Map),L(this,"lastEncryptionKeyUpdateRequest",void 0),L(this,"lastMembershipFingerprints",void 0),L(this,"latestGeneratedKeyIndex",-1),L(this,"joinConfig",void 0),L(this,"logger",void 0),L(this,"joined",!1),L(this,"sendEncryptionKeysEvent",function(){var c=F(function*(u){if(l.keysEventUpdateTimeout!==void 0&&(clearTimeout(l.keysEventUpdateTimeout),l.keysEventUpdateTimeout=void 0),l.lastEncryptionKeyUpdateRequest=Date.now(),!!l.joined){var f=l.getKeysForParticipant(l.userId,l.deviceId);if(!f){l.logger.warn("Tried to send encryption keys event but no keys found!");return}if(typeof u!="number"&&l.latestGeneratedKeyIndex===-1){l.logger.warn("Tried to send encryption keys event but no current key index found!");return}var p=u??l.latestGeneratedKeyIndex;l.logger.info("Try sending encryption keys event. keyIndexToSend=".concat(p," (method parameter: ").concat(u,")"));var m=f[p];try{l.statistics.counters.roomEventEncryptionKeysSent+=1,yield l.transport.sendKey(mH(m),p,l.getMemberships()),l.logger.debug("sendEncryptionKeysEvent participantId=".concat(l.userId,":").concat(l.deviceId," numKeys=").concat(f.length," currentKeyIndex=").concat(l.latestGeneratedKeyIndex," keyIndexToSend=").concat(p),l.encryptionKeys)}catch(g){if(l.keysEventUpdateTimeout===void 0){var v=FP(g,5e3);l.logger.warn("Failed to send m.call.encryption_key, retrying in ".concat(v),g),l.keysEventUpdateTimeout=setTimeout(()=>void l.sendEncryptionKeysEvent(),v)}else l.logger.info("Not scheduling key resend as another re-send is already pending")}}});return function(u){return c.apply(this,arguments)}}()),L(this,"onTransportChanged",c=>{this.requestSendCurrentKey()}),L(this,"onNewKeyReceived",(c,u,f,p,m)=>{this.logger.debug("Received key over key transport ".concat(c,":").concat(u," at index ").concat(p)),this.setEncryptionKey(c,u,p,f,m)}),L(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,this.logger.info("Making new sender key for key rotation");var c=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(c)}}),this.logger=(a??A).getChild("[EncryptionManager]")}getEncryptionKeys(){return this.encryptionKeys}join(e){var t,r,i;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=(t=(r=this.joinConfig)===null||r===void 0?void 0:r.manageMediaKeys)!==null&&t!==void 0?t:this.manageMediaKeys,this.transport.on(Uc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof Lk&&this.transport.on(xv.EnabledTransportsChanged,this.onTransportChanged),this.transport.start(),(i=this.joinConfig)!==null&&i!==void 0&&i.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){this.encryptionKeys.set(U_(this.userId,this.deviceId),[]),this.transport.off(Uc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof Lk&&this.transport.off(xv.EnabledTransportsChanged,this.onTransportChanged),this.transport.stop(),this.makeNewKeyTimeout!==void 0&&(clearTimeout(this.makeNewKeyTimeout),this.makeNewKeyTimeout=void 0);for(var e of this.setNewKeyTimeouts)clearTimeout(e);this.setNewKeyTimeouts.clear(),this.manageMediaKeys=!1,this.joined=!1}onMembershipsUpdate(e){if(this.manageMediaKeys&&this.joined){var t=new Set(e.filter(c=>!j_(c,this.userId,this.deviceId)).map(o2)),r=new Set(this.getMemberships().filter(c=>!j_(c,this.userId,this.deviceId)).map(o2)),i=Array.from(t).some(c=>!r.has(c)),s=Array.from(r).some(c=>!t.has(c)),o=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),i)this.makeNewKeyTimeout||(this.logger.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay));else if(s)this.logger.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(o){var a=this.lastMembershipFingerprints,l=Array.from(o).some(c=>!a.has(c))||Array.from(a).some(c=>!o.has(c));l&&(this.logger.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}}makeNewSenderKey(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=gH(16),r=this.getNewEncryptionKeyIndex();return this.logger.info("Generated new key at index "+r),this.setEncryptionKey(this.userId,this.deviceId,r,t,Date.now(),e),r}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){this.logger.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}getKeysForParticipant(e,t){var r;return(r=this.encryptionKeys.get(U_(e,t)))===null||r===void 0?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!j_(e,this.userId,this.deviceId)).map(e=>"".concat(o2(e),":").concat(e.createdTs())))}getNewEncryptionKeyIndex(){return this.latestGeneratedKeyIndex===-1?0:(this.latestGeneratedKeyIndex+1)%256}setEncryptionKey(e,t,r,i,s){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1;this.logger.debug("Setting encryption key for ".concat(e,":").concat(t," at index ").concat(r));var a=Oh(i),l=U_(e,t);this.encryptionKeys.has(l)||this.encryptionKeys.set(l,[]);var c=this.encryptionKeys.get(l),u=c[r];if(u){if(u.timestamp>s){this.logger.info("Ignoring new key at index ".concat(r," for ").concat(l," as it is older than existing known key"));return}if(zoe(u.key,a)){u.timestamp=s;return}}if(e===this.userId&&t===this.deviceId&&(this.latestGeneratedKeyIndex=r),c[r]={key:a,timestamp:s},o){var f=setTimeout(()=>{this.setNewKeyTimeouts.delete(f),this.logger.info("Delayed-emitting key changed event for ".concat(l," index ").concat(r)),this.onEncryptionKeysChanged(a,r,l)},this.useKeyDelay);this.setNewKeyTimeouts.add(f)}else this.onEncryptionKeysChanged(a,r,l)}}var U_=(n,e)=>"".concat(n,":").concat(e);function zoe(n,e){return n===e?!0:!!n&&!!e&&n.length===e.length&&n.every((t,r)=>t===e[r])}var o2=n=>U_(n.sender,n.deviceId);class Yoe{get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get membershipExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:ZP}get membershipServerSideExpiryTimeout(){var e,t,r;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(r=this.joinConfig)===null||r===void 0?void 0:r.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get callMemberEventRetryJitter(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryJitter)!==null&&e!==void 0?e:2e3}constructor(e,t,r,i){var s=this;this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,L(this,"relativeExpiry",void 0),L(this,"memberEventTimeout",void 0),L(this,"ownFociPreferred",void 0),L(this,"ownFocusActive",void 0),L(this,"updateCallMembershipRunning",!1),L(this,"needCallMembershipUpdate",!1),L(this,"membershipServerSideExpiryTimeoutOverride",void 0),L(this,"disconnectDelayId",void 0),L(this,"triggerCallMembershipEventUpdate",F(function*(){if(s.updateCallMembershipRunning){s.needCallMembershipUpdate=!0;return}s.updateCallMembershipRunning=!0;try{do s.needCallMembershipUpdate=!1,yield s.updateCallMembershipEvent();while(s.needCallMembershipUpdate)}finally{s.updateCallMembershipRunning=!1}})),L(this,"delayDisconnection",F(function*(){try{var o=s.disconnectDelayId;yield qf(()=>s.client._unstable_updateDelayedEvent(o,Sd.Restart)),s.scheduleDelayDisconnection()}catch(a){A.error("Failed to delay our disconnection event:",a)}}))}off(e,t){return A.error("off is not implemented on LegacyMembershipManager"),this}on(e,t){return A.error("on is not implemented on LegacyMembershipManager"),this}isJoined(){return this.relativeExpiry!==void 0}isActivated(){return this.isJoined()}get status(){return Cc.Unknown}join(e,t){this.ownFocusActive=t,this.ownFociPreferred=e,this.relativeExpiry=this.membershipExpiryTimeout,this.triggerCallMembershipEventUpdate()}leave(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(t.relativeExpiry=void 0,t.ownFocusActive=void 0,t.memberEventTimeout&&(clearTimeout(t.memberEventTimeout),t.memberEventTimeout=void 0),r){var i=yield Promise.race([t.triggerCallMembershipEventUpdate(),nu(r,"timeout")]);return i!=="timeout"}else return yield t.triggerCallMembershipEventUpdate(),!0})()}onRTCSessionMemberUpdate(e){var t=this;return F(function*(){var r=i=>i.sender===t.client.getUserId()&&i.deviceId===t.client.getDeviceId();if(t.isJoined()&&!e.some(r))return A.warn("Missing own membership: force re-join"),t.triggerCallMembershipEventUpdate()})()}getActiveFocus(){if(this.ownFocusActive)if(XP(this.ownFocusActive)){if(this.ownFocusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else A.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.ownFociPreferred)!==null&&t!==void 0?t:[]}}updateCallMembershipEvent(){var e=this;return F(function*(){e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(Le.FORWARDS);if(!t)throw new Error("Couldn't get room state for room "+e.room.roomId);var r=e.client.getUserId(),i=e.client.getDeviceId();if(!r||!i)throw new Error("User ID or device ID was null!");var s={};s=e.makeNewMembership(i);try{if(e.isJoined()){var o=e.makeMembershipStateKey(r,i),a=function(){var p=F(function*(){try{var m=yield qf(()=>e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},ee.GroupCallMemberPrefix,{},o));e.disconnectDelayId=m.delay_id}catch(g){if(g instanceof bn&&g.errcode==="M_UNKNOWN"&&g.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var v=g.data["org.matrix.msc4140.max_delay"];if(typeof v=="number"&&e.membershipServerSideExpiryTimeout>v)return e.membershipServerSideExpiryTimeoutOverride=v,a()}A.error("Failed to prepare delayed disconnection event:",g)}});return function(){return p.apply(this,arguments)}}();if(yield a(),yield qf(()=>e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,s,o)),e.disconnectDelayId!==void 0)try{var l=e.disconnectDelayId;yield qf(()=>e.client._unstable_updateDelayedEvent(l,Sd.Restart))}catch(p){p instanceof bn&&p.errcode==="M_NOT_FOUND"&&(A.warn("Failed to update delayed disconnection event, prepare it again:",p),e.disconnectDelayId=void 0,yield a())}e.disconnectDelayId!==void 0&&e.scheduleDelayDisconnection()}else{var c=!1;if(e.disconnectDelayId!==void 0){try{var u=e.disconnectDelayId;yield qf(()=>e.client._unstable_updateDelayedEvent(u,Sd.Send)),c=!0}catch(p){A.error("Failed to send our delayed disconnection event:",p)}e.disconnectDelayId=void 0}c||(yield qf(()=>e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,{},e.makeMembershipStateKey(r,i))))}A.info("Sent updated call member event.")}catch(p){var f=e.callMemberEventRetryDelayMinimum+Math.random()*e.callMemberEventRetryJitter;A.warn("Failed to send call member event (retrying in ".concat(f,"): ").concat(p)),yield nu(f),yield e.triggerCallMembershipEventUpdate()}})()}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(()=>void this.delayDisconnection(),this.membershipKeepAlivePeriod)}makeMembershipStateKey(e,t){var r="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}}function qf(n){return Ok.apply(this,arguments)}function Ok(){return Ok=F(function*(n){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;;)try{return yield n()}catch(s){if(e>0&&s instanceof su&&s.isRateLimitError()){e--;var t=void 0,r=5e3;try{var i;t=(i=s.getRetryAfterMs())!==null&&i!==void 0?i:r,A.info("Rate limited by server, retrying in ".concat(t,"ms"))}catch(o){A.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(r),o),t=r}yield nu(t)}else throw s}}),Ok.apply(this,arguments)}var ar=function(n){return n.MembershipsChanged="memberships_changed",n.JoinStateChanged="join_state_changed",n.EncryptionKeyChanged="encryption_key_changed",n.MembershipManagerError="membership_manager_error",n}({});class Nh extends En{get callId(){return this._callId}static callMembershipsForRoom(e){var t=A.getChild("[MatrixRTCSession ".concat(e.roomId,"]")),r=e.getLiveTimeline().getState(Le.FORWARDS);if(!r)throw t.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var i=r.getStateEvents(ee.GroupCallMemberPrefix),s=[];for(var o of i){var a=o.getContent(),l=Object.keys(a).length;if(l!==0){var c=[];if(l>1&&"focus_active"in a?c.push(a):l===1&&"memberships"in a&&t.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),c.length!==0)for(var u of c)try{var f,p=new SN(o,u);if(p.callId!==""||p.scope!=="m.room"){t.info("Ignoring user-scoped call");continue}if(p.isExpired()){t.info("Ignoring expired device membership ".concat(p.sender,"/").concat(p.deviceId));continue}if(!e.hasMembershipState((f=p.sender)!==null&&f!==void 0?f:"",qe.Join)){t.info("Ignoring membership of user ".concat(p.sender," who is not in the room."));continue}s.push(p)}catch(m){t.warn("Couldn't construct call membership: ",m)}}}return s.sort((m,v)=>m.createdTs()-v.createdTs()),s.length>1&&t.debug("Call memberships in room ".concat(e.roomId,", in order: "),s.map(m=>[m.createdTs(),m.sender])),s}static roomSessionForRoom(e,t){var r=Nh.callMembershipsForRoom(t);return new Nh(e,t,r)}get room(){return this.roomSubset}constructor(e,t,r){var i;super(),this.client=e,this.roomSubset=t,this.memberships=r,L(this,"membershipManager",void 0),L(this,"encryptionManager",void 0),L(this,"_callId",void 0),L(this,"logger",void 0),L(this,"expiryTimeout",void 0),L(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),L(this,"reEmitter",new Mp(this)),L(this,"onRoomMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"onRTCSessionMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"recalculateSessionMembers",()=>{var o,a,l,c=this.memberships;this.memberships=Nh.callMembershipsForRoom(this.room),this._callId=(o=this._callId)!==null&&o!==void 0?o:(a=this.memberships[0])===null||a===void 0?void 0:a.callId;var u=c.length!=this.memberships.length||c.some((p,m)=>!SN.equal(p,this.memberships[m]));if(u){var f;this.logger.info("Memberships for call in room ".concat(this.roomSubset.roomId," have changed: emitting")),aie(this.logger,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit(ar.MembershipsChanged,c,this.memberships)}),(f=this.membershipManager)===null||f===void 0||f.onRTCSessionMemberUpdate(this.memberships)}(l=this.encryptionManager)===null||l===void 0||l.onMembershipsUpdate(c),this.setExpiryTimer()}),this.logger=A.getChild("[MatrixRTCSession ".concat(t.roomId,"]")),this._callId=(i=r[0])===null||i===void 0?void 0:i.callId;var s=this.roomSubset.getLiveTimeline().getState(Le.FORWARDS);s==null||s.on(ut.Members,this.onRoomMemberUpdate),this.setExpiryTimer()}isJoined(){var e,t;return(e=(t=this.membershipManager)===null||t===void 0?void 0:t.isJoined())!==null&&e!==void 0?e:!1}stop(){var e=this;return F(function*(){var t;yield(t=e.membershipManager)===null||t===void 0?void 0:t.leave(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0);var r=e.roomSubset.getLiveTimeline().getState(Le.FORWARDS);r==null||r.off(ut.Members,e.onRoomMemberUpdate)})()}joinRoomSession(e,t,r){if(this.isJoined()){this.logger.info("Already joined to session in room ".concat(this.roomSubset.roomId,": ignoring join call"));return}else{var i;(i=r==null?void 0:r.useNewMembershipManager)!==null&&i!==void 0&&i?this.membershipManager=new Zb(r,this.roomSubset,this.client,()=>this.getOldestMembership(),this.logger):this.membershipManager=new Yoe(r,this.roomSubset,this.client,()=>this.getOldestMembership());var s;r!=null&&r.useExperimentalToDeviceTransport?(this.logger.info("Using to-device with room fallback transport for encryption keys"),s=new Lk(this.client.getUserId(),this.client.getDeviceId(),this.roomSubset,this.client,this.statistics,this.logger),this.reEmitter.reEmit(s,[xv.EnabledTransportsChanged])):s=new kH(this.roomSubset,this.client,this.statistics),this.encryptionManager=new Woe(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(o,a,l)=>{this.emit(ar.EncryptionKeyChanged,o,a,l)},this.logger)}this.membershipManager.join(e,t,o=>{this.logger.error("MembershipManager encountered an unrecoverable error: ",o),this.emit(ar.MembershipManagerError,o),this.emit(ar.JoinStateChanged,this.isJoined())}),this.encryptionManager.join(r),this.emit(ar.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!t.isJoined())return t.logger.info("Not joined to session in room ".concat(t.roomSubset.roomId,": ignoring leave call")),!1;t.logger.info("Leaving call session in room ".concat(t.roomSubset.roomId)),t.encryptionManager.leave();var i=t.membershipManager.leave(r);return t.emit(ar.JoinStateChanged,!1),yield i})()}getActiveFocus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getFocusInUse(){var e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){var e;(e=this.encryptionManager)===null||e===void 0||e.getEncryptionKeys().forEach((t,r)=>{t.forEach((i,s)=>{this.emit(ar.EncryptionKeyChanged,i.key,s,r)})})}getEncryptionKeys(){var e,t,r=(e=(t=this.encryptionManager)===null||t===void 0?void 0:t.getEncryptionKeys())!==null&&e!==void 0?e:new Map;return Array.from(r.entries()).map(i=>{var[s,o]=i;return[s,o.map(a=>a.key)]}).values()}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var t of this.memberships){var r=t.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}}var a2=A.getChild("[MatrixRTCSessionManager]"),Qb=function(n){return n.SessionStarted="session_started",n.SessionEnded="session_ended",n}({});class Joe extends En{constructor(e){super(),this.client=e,L(this,"roomSessions",new Map),L(this,"onRoom",t=>{this.refreshRoom(t)}),L(this,"onRoomState",(t,r)=>{var i=this.client.getRoom(t.getRoomId());if(!i){a2.error("Got room state event for unknown room ".concat(t.getRoomId(),"!"));return}t.getType()==ee.GroupCallMemberPrefix&&this.refreshRoom(i)})}start(){for(var e of(t=this.client.getRooms())!==null&&t!==void 0?t:[]){var t,r=Nh.roomSessionForRoom(this.client,e);r.memberships.length>0&&this.roomSessions.set(e.roomId,r)}this.client.on(Oe.Room,this.onRoom),this.client.on(ut.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Oe.Room,this.onRoom),this.client.off(ut.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Nh.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}refreshRoom(e){var t=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!t;r.onRTCSessionMemberUpdate();var s=r.memberships.length>0;i&&!s?(a2.trace("Session ended for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(Qb.SessionEnded,e.roomId,this.roomSessions.get(e.roomId))):!i&&s&&(a2.trace("Session started for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(Qb.SessionStarted,e.roomId,this.roomSessions.get(e.roomId)))}}function l2(n){return e=>{var t,r;return((t=e.content)===null||t===void 0||(t=t["m.relates_to"])===null||t===void 0?void 0:t.event_id)!==n||((r=e.content)===null||r===void 0||(r=r["m.relates_to"])===null||r===void 0?void 0:r.rel_type)===Qt.name}}function xH(n){return Mk.apply(this,arguments)}function Mk(){return Mk=F(function*(n){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(n),t=yield globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(t)}),Mk.apply(this,arguments)}class Mg extends Error{}Mg.prototype.name="InvalidTokenError";function Xoe(n){return decodeURIComponent(atob(n).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function Zoe(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Xoe(e)}catch{return atob(e)}}function PH(n,e){if(typeof n!="string")throw new Mg("Invalid token specified: must be a string");e||(e={});const t=e.header===!0?0:1,r=n.split(".")[t];if(typeof r!="string")throw new Mg(`Invalid token specified: missing part #${t+1}`);let i;try{i=Zoe(r)}catch(s){throw new Mg(`Invalid token specified: invalid base64 for part #${t+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new Mg(`Invalid token specified: invalid json for part #${t+1} (${s.message})`)}}var Qoe={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},ca,ua,Pv=(n=>(n[n.NONE=0]="NONE",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(Pv||{});(n=>{function e(){ca=3,ua=Qoe}n.reset=e;function t(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");ca=i}n.setLevel=t;function r(i){ua=i}n.setLogger=r})(Pv||(Pv={}));var Qn=class sa{constructor(e){this._name=e}debug(...e){ca>=4&&ua.debug(sa._format(this._name,this._method),...e)}info(...e){ca>=3&&ua.info(sa._format(this._name,this._method),...e)}warn(...e){ca>=2&&ua.warn(sa._format(this._name,this._method),...e)}error(...e){ca>=1&&ua.error(sa._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const r=new sa(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){ca>=4&&ua.debug(sa._format(e),...t)}static info(e,...t){ca>=3&&ua.info(sa._format(e),...t)}static warn(e,...t){ca>=2&&ua.warn(sa._format(e),...t)}static error(e,...t){ca>=1&&ua.error(sa._format(e),...t)}};Pv.reset();var eS=class{static decode(n){try{return PH(n)}catch(e){throw Qn.error("JwtUtils.decode",e),e}}static async generateSignedJwt(n,e,t){const r=Do.encodeBase64Url(new TextEncoder().encode(JSON.stringify(n))),i=Do.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),s=`${r}.${i}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(s)),a=Do.encodeBase64Url(new Uint8Array(o));return`${s}.${a}`}},eae="10000000-1000-4000-8000-100000000000",Ak=n=>btoa([...new Uint8Array(n)].map(e=>String.fromCharCode(e)).join("")),LH=class oa{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return eae.replace(/[018]/g,t=>(+t^oa._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return oa.generateUUIDv4()+oa.generateUUIDv4()+oa.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return Ak(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Qn.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const i=new TextEncoder().encode([e,t].join(":"));return Ak(i)}static async hash(e,t){const r=new TextEncoder().encode(t),i=await crypto.subtle.digest(e,r);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await oa.hash("SHA-256",JSON.stringify(t));return oa.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:r,keyPair:i,nonce:s}){let o,a;const l={jti:window.crypto.randomUUID(),htm:r??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(o=await oa.hash("SHA-256",t),a=oa.encodeBase64Url(o),l.ath=a),s&&(l.nonce=s);try{const c=await crypto.subtle.exportKey("jwk",i.publicKey),u={alg:"ES256",typ:"dpop+jwt",jwk:{crv:c.crv,kty:c.kty,x:c.x,y:c.y}};return await eS.generateSignedJwt(u,l,i.privateKey)}catch(c){throw c instanceof TypeError?new Error(`Error exporting dpop public key: ${c.message}`):c}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await oa.customCalculateJwkThumbprint(t)}catch(t){throw t instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${t.message}`):t}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};LH.encodeBase64Url=n=>Ak(n).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Do=LH,tae=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Qn(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},tS=class F_ extends tae{constructor(){super(...arguments),this._logger=new Qn(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-F_.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=F_.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=F_.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=r;const i=Math.min(e,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},wN=class{static readParams(n,e="query"){if(!n)throw new TypeError("Invalid URL");const r=new URL(n,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(r.slice(1))}},Nk=";",lp=class extends Error{constructor(n,e){var t,r,i;if(super(n.error_description||n.error||""),this.form=e,this.name="ErrorResponse",!n.error)throw Qn.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=n.error,this.error_description=(t=n.error_description)!=null?t:null,this.error_uri=(r=n.error_uri)!=null?r:null,this.state=n.userState,this.session_state=(i=n.session_state)!=null?i:null,this.url_state=n.url_state}},nae=class extends Error{constructor(n){super(n),this.name="ErrorTimeout"}},rae=class{constructor(){this._logger=new Qn("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(n){return this._logger.create(`getItem('${n}')`),this._data[n]}setItem(n,e){this._logger.create(`setItem('${n}')`),this._data[n]=e}removeItem(n){this._logger.create(`removeItem('${n}')`),delete this._data[n]}get length(){return Object.getOwnPropertyNames(this._data).length}key(n){return Object.getOwnPropertyNames(this._data)[n]}},Dk=class extends Error{constructor(n,e){super(e),this.name="ErrorDPoPNonce",this.nonce=n}},tL=class{constructor(n=[],e=null,t={}){this._jwtHandler=e,this._extraHeaders=t,this._logger=new Qn("JsonService"),this._contentTypes=[],this._contentTypes.push(...n,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(n,e={}){const{timeoutInSeconds:t,...r}=e;if(!t)return await fetch(n,r);const i=new AbortController,s=setTimeout(()=>i.abort(),t*1e3);try{return await fetch(n,{...e,signal:i.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new nae("Network timed out"):o}finally{clearTimeout(s)}}async getJson(n,{token:e,credentials:t,timeoutInSeconds:r}={}){const i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};e&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+e),this.appendExtraHeaders(s);let o;try{i.debug("url:",n),o=await this.fetchWithTimeout(n,{method:"GET",headers:s,timeoutInSeconds:r,credentials:t})}catch(c){throw i.error("Network Error"),c}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(c=>a.startsWith(c))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${n}`)),o.ok&&this._jwtHandler&&(a!=null&&a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let l;try{l=await o.json()}catch(c){throw i.error("Error parsing JSON response",c),o.ok?c:new Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error("Error from server:",l),l.error?new lp(l):new Error(`${o.statusText} (${o.status}): ${JSON.stringify(l)}`);return l}async postForm(n,{body:e,basicAuth:t,timeoutInSeconds:r,initCredentials:i,extraHeaders:s}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...s};t!==void 0&&(a.Authorization="Basic "+t),this.appendExtraHeaders(a);let l;try{o.debug("url:",n),l=await this.fetchWithTimeout(n,{method:"POST",headers:a,body:e,timeoutInSeconds:r,credentials:i})}catch(p){throw o.error("Network error"),p}o.debug("HTTP response received, status",l.status);const c=l.headers.get("Content-Type");if(c&&!this._contentTypes.find(p=>c.startsWith(p)))throw new Error(`Invalid response Content-Type: ${c??"undefined"}, from URL: ${n}`);const u=await l.text();let f={};if(u)try{f=JSON.parse(u)}catch(p){throw o.error("Error parsing JSON response",p),l.ok?p:new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(o.error("Error from server:",f),l.headers.has("dpop-nonce")){const p=l.headers.get("dpop-nonce");throw new Dk(p,`${JSON.stringify(f)}`)}throw f.error?new lp(f,e):new Error(`${l.statusText} (${l.status}): ${JSON.stringify(f)}`)}return f}appendExtraHeaders(n){const e=this._logger.create("appendExtraHeaders"),t=Object.keys(this._extraHeaders),r=["authorization","accept","content-type"];t.length!==0&&t.forEach(i=>{if(r.includes(i.toLocaleLowerCase())){e.warn("Protected header could not be overridden",i,r);return}const s=typeof this._extraHeaders[i]=="function"?this._extraHeaders[i]():this._extraHeaders[i];s&&s!==""&&(n[i]=s)})}},OH=class{constructor(n){this._settings=n,this._logger=new Qn("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new tL(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const n=this._logger.create("getMetadata");if(this._metadata)return n.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw n.throw(new Error("No authority or metadataUrl configured on settings")),null;n.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return n.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,e),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(n=!0){return this._getMetadataProperty("token_endpoint",n)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(n=!0){return this._getMetadataProperty("revocation_endpoint",n)}getKeysEndpoint(n=!0){return this._getMetadataProperty("jwks_uri",n)}async _getMetadataProperty(n,e=!1){const t=this._logger.create(`_getMetadataProperty('${n}')`),r=await this.getMetadata();if(t.debug("resolved"),r[n]===void 0){if(e===!0){t.warn("Metadata does not contain optional property");return}t.throw(new Error("Metadata does not contain property "+n))}return r[n]}async getSigningKeys(){const n=this._logger.create("getSigningKeys");if(this._signingKeys)return n.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);n.debug("got jwks_uri",e);const t=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(n.debug("got key set",t),!Array.isArray(t.keys))throw n.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=t.keys,this._signingKeys}},AE=class{constructor({prefix:n="oidc.",store:e=localStorage}={}){this._logger=new Qn("WebStorageStateStore"),this._store=e,this._prefix=n}async set(n,e){this._logger.create(`set('${n}')`),n=this._prefix+n,await this._store.setItem(n,e)}async get(n){return this._logger.create(`get('${n}')`),n=this._prefix+n,await this._store.getItem(n)}async remove(n){this._logger.create(`remove('${n}')`),n=this._prefix+n;const e=await this._store.getItem(n);return await this._store.removeItem(n),e}async getAllKeys(){this._logger.create("getAllKeys");const n=await this._store.length,e=[];for(let t=0;t<n;t++){const r=await this._store.key(t);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return e}},iae="code",sae="openid",oae="client_secret_post",aae=60*15,jk=class{constructor({authority:n,metadataUrl:e,metadata:t,signingKeys:r,metadataSeed:i,client_id:s,client_secret:o,response_type:a=iae,scope:l=sae,redirect_uri:c,post_logout_redirect_uri:u,client_authentication:f=oae,prompt:p,display:m,max_age:v,ui_locales:g,acr_values:S,resource:b,response_mode:w,filterProtocolClaims:k=!0,loadUserInfo:R=!1,requestTimeoutInSeconds:I,staleStateAgeInSeconds:C=aae,mergeClaimsStrategy:x={array:"replace"},disablePKCE:O=!1,stateStore:N,revokeTokenAdditionalContentTypes:D,fetchRequestCredentials:j,refreshTokenAllowedScope:U,extraQueryParams:H={},extraTokenParams:K={},extraHeaders:B={},dpop:z,omitScopeWhenRequesting:W=!1}){var V;if(this.authority=n,e?this.metadataUrl=e:(this.metadataUrl=n,n&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=t,this.metadataSeed=i,this.signingKeys=r,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=l,this.redirect_uri=c,this.post_logout_redirect_uri=u,this.client_authentication=f,this.prompt=p,this.display=m,this.max_age=v,this.ui_locales=g,this.acr_values=S,this.resource=b,this.response_mode=w,this.filterProtocolClaims=k??!0,this.loadUserInfo=!!R,this.staleStateAgeInSeconds=C,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=W,this.disablePKCE=!!O,this.revokeTokenAdditionalContentTypes=D,this.fetchRequestCredentials=j||"same-origin",this.requestTimeoutInSeconds=I,N)this.stateStore=N;else{const q=typeof window<"u"?window.localStorage:new rae;this.stateStore=new AE({store:q})}if(this.refreshTokenAllowedScope=U,this.extraQueryParams=H,this.extraTokenParams=K,this.extraHeaders=B,this.dpop=z,this.dpop&&!((V=this.dpop)!=null&&V.store))throw new Error("A DPoPStore is required when dpop is enabled")}},lae=class{constructor(n,e){this._settings=n,this._metadataService=e,this._logger=new Qn("UserInfoService"),this._getClaimsFromJwt=async t=>{const r=this._logger.create("_getClaimsFromJwt");try{const i=eS.decode(t);return r.debug("JWT decoding successful"),i}catch(i){throw r.error("Error parsing JWT response"),i}},this._jsonService=new tL(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(n){const e=this._logger.create("getClaims");n||this._logger.throw(new Error("No token passed"));const t=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",t);const r=await this._jsonService.getJson(t,{token:n,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",r),r}},MH=class{constructor(n,e){this._settings=n,this._metadataService=e,this._logger=new Qn("TokenClient"),this._jsonService=new tL(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:n="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");t||o.throw(new Error("A client_id is required")),e||o.throw(new Error("A redirect_uri is required")),s.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:n,redirect_uri:e});for(const[f,p]of Object.entries(s))p!=null&&a.set(f,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw o.throw(new Error("A client_secret is required")),null;l=Do.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break}const c=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),u}async exchangeCredentials({grant_type:n="password",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,scope:r=this._settings.scope,...i}){const s=this._logger.create("exchangeCredentials");e||s.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:n});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[u,f]of Object.entries(i))f!=null&&o.set(u,f);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!t)throw s.throw(new Error("A client_secret is required")),null;a=Do.generateBasicAuth(e,t);break;case"client_secret_post":o.append("client_id",e),t&&o.append("client_secret",t);break}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),c}async exchangeRefreshToken({grant_type:n="refresh_token",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...s}){const o=this._logger.create("exchangeRefreshToken");e||o.throw(new Error("A client_id is required")),s.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:n});for(const[f,p]of Object.entries(s))Array.isArray(p)?p.forEach(m=>a.append(f,m)):p!=null&&a.set(f,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!t)throw o.throw(new Error("A client_secret is required")),null;l=Do.generateBasicAuth(e,t);break;case"client_secret_post":a.append("client_id",e),t&&a.append("client_secret",t);break}const c=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),u}async revoke(n){var e;const t=this._logger.create("revoke");n.token||t.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(e=n.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[s,o]of Object.entries(n))o!=null&&i.set(s,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug("got response")}},cae=class{constructor(n,e,t){this._settings=n,this._metadataService=e,this._claimsService=t,this._logger=new Qn("ResponseValidator"),this._userInfoService=new lae(this._settings,this._metadataService),this._tokenClient=new MH(this._settings,this._metadataService)}async validateSigninResponse(n,e,t){const r=this._logger.create("validateSigninResponse");this._processSigninState(n,e),r.debug("state processed"),await this._processCode(n,e,t),r.debug("code processed"),n.isOpenId&&this._validateIdTokenAttributes(n),r.debug("tokens validated"),await this._processClaims(n,e==null?void 0:e.skipUserInfo,n.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(n,e){const t=this._logger.create("validateCredentialsResponse");n.isOpenId&&n.id_token&&this._validateIdTokenAttributes(n),t.debug("tokens validated"),await this._processClaims(n,e,n.isOpenId),t.debug("claims processed")}async validateRefreshResponse(n,e){var t,r;const i=this._logger.create("validateRefreshResponse");n.userState=e.data,(t=n.session_state)!=null||(n.session_state=e.session_state),(r=n.scope)!=null||(n.scope=e.scope),n.isOpenId&&n.id_token&&(this._validateIdTokenAttributes(n,e.id_token),i.debug("ID Token validated")),n.id_token||(n.id_token=e.id_token,n.profile=e.profile);const s=n.isOpenId&&!!n.id_token;await this._processClaims(n,!1,s),i.debug("claims processed")}validateSignoutResponse(n,e){const t=this._logger.create("validateSignoutResponse");if(e.id!==n.state&&t.throw(new Error("State does not match")),t.debug("state validated"),n.userState=e.data,n.error)throw t.warn("Response was error",n.error),new lp(n)}_processSigninState(n,e){var t;const r=this._logger.create("_processSigninState");if(e.id!==n.state&&r.throw(new Error("State does not match")),e.client_id||r.throw(new Error("No client_id on state")),e.authority||r.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),n.userState=e.data,n.url_state=e.url_state,(t=n.scope)!=null||(n.scope=e.scope),n.error)throw r.warn("Response was error",n.error),new lp(n);e.code_verifier&&!n.code&&r.throw(new Error("Expected code in response"))}async _processClaims(n,e=!1,t=!0){const r=this._logger.create("_processClaims");if(n.profile=this._claimsService.filterProtocolClaims(n.profile),e||!this._settings.loadUserInfo||!n.access_token){r.debug("not loading user info");return}r.debug("loading user info");const i=await this._userInfoService.getClaims(n.access_token);r.debug("user info claims received from user info endpoint"),t&&i.sub!==n.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),n.profile=this._claimsService.mergeClaims(n.profile,this._claimsService.filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",n.profile)}async _processCode(n,e,t){const r=this._logger.create("_processCode");if(n.code){r.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:n.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:t,...e.extraTokenParams});Object.assign(n,i)}else r.debug("No code to process")}_validateIdTokenAttributes(n,e){var t;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=eS.decode((t=n.id_token)!=null?t:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const s=eS.decode(e);i.sub!==s.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==s.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==s.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&s.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}n.profile=i}},nS=class Uk{constructor(e){this.id=e.id||Do.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=tS.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Qn("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return Qn.createStatic("State","fromStorageString"),Promise.resolve(new Uk(JSON.parse(e)))}static async clearStaleState(e,t){const r=Qn.createStatic("State","clearStaleState"),i=tS.getEpochTime()-t,s=await e.getAllKeys();r.debug("got keys",s);for(let o=0;o<s.length;o++){const a=s[o],l=await e.get(a);let c=!1;if(l)try{const u=await Uk.fromStorageString(l);r.debug("got item from key:",a,u.created),u.created<=i&&(c=!0)}catch(u){r.error("Error parsing state for key:",a,u),c=!0}else r.debug("no item in storage for key:",a),c=!0;c&&(r.debug("removed item for key:",a),e.remove(a))}}},nL=class Fk extends nS{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(e){const t=e.code_verifier===!0?Do.generateCodeVerifier():e.code_verifier||void 0,r=t?await Do.generateCodeChallenge(t):void 0;return new Fk({...e,code_verifier:t,code_challenge:r})}toStorageString(){return new Qn("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(e){Qn.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return Fk.create(t)}},AH=class NH{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:o,state_data:a,response_mode:l,request_type:c,client_secret:u,nonce:f,url_state:p,resource:m,skipUserInfo:v,extraQueryParams:g,extraTokenParams:S,disablePKCE:b,dpopJkt:w,omitScopeWhenRequesting:k,...R}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const I=await nL.create({data:a,request_type:c,url_state:p,code_verifier:!b,client_id:r,authority:t,redirect_uri:i,response_mode:l,client_secret:u,scope:o,extraTokenParams:S,skipUserInfo:v}),C=new URL(e);C.searchParams.append("client_id",r),C.searchParams.append("redirect_uri",i),C.searchParams.append("response_type",s),k||C.searchParams.append("scope",o),f&&C.searchParams.append("nonce",f),w&&C.searchParams.append("dpop_jkt",w);let x=I.id;p&&(x=`${x}${Nk}${p}`),C.searchParams.append("state",x),I.code_challenge&&(C.searchParams.append("code_challenge",I.code_challenge),C.searchParams.append("code_challenge_method","S256")),m&&(Array.isArray(m)?m:[m]).forEach(N=>C.searchParams.append("resource",N));for(const[O,N]of Object.entries({response_mode:l,...R,...g}))N!=null&&C.searchParams.append(O,N.toString());return new NH({url:C.href,state:I})}};AH._logger=new Qn("SigninRequest");var uae=AH,dae="openid",$_=class{constructor(n){if(this.access_token="",this.token_type="",this.profile={},this.state=n.get("state"),this.session_state=n.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Nk);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Nk))}this.error=n.get("error"),this.error_description=n.get("error_description"),this.error_uri=n.get("error_uri"),this.code=n.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-tS.getEpochTime()}set expires_in(n){typeof n=="string"&&(n=Number(n)),n!==void 0&&n>=0&&(this.expires_at=Math.floor(n)+tS.getEpochTime())}get isOpenId(){var n;return((n=this.scope)==null?void 0:n.split(" ").includes(dae))||!!this.id_token}},fae=class{constructor({url:n,state_data:e,id_token_hint:t,post_logout_redirect_uri:r,extraQueryParams:i,request_type:s,client_id:o}){if(this._logger=new Qn("SignoutRequest"),!n)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(n);t&&a.searchParams.append("id_token_hint",t),o&&a.searchParams.append("client_id",o),r&&(a.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new nS({data:e,request_type:s}),a.searchParams.append("state",this.state.id)));for(const[l,c]of Object.entries({...i}))c!=null&&a.searchParams.append(l,c.toString());this.url=a.href}},hae=class{constructor(n){this.state=n.get("state"),this.error=n.get("error"),this.error_description=n.get("error_description"),this.error_uri=n.get("error_uri")}},pae=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],mae=["sub","iss","aud","exp","iat"],gae=class{constructor(n){this._settings=n,this._logger=new Qn("ClaimsService")}filterProtocolClaims(n){const e={...n};if(this._settings.filterProtocolClaims){let t;Array.isArray(this._settings.filterProtocolClaims)?t=this._settings.filterProtocolClaims:t=pae;for(const r of t)mae.includes(r)||delete e[r]}return e}mergeClaims(n,e){const t={...n};for(const[r,i]of Object.entries(e))if(t[r]!==i)if(Array.isArray(t[r])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")t[r]=i;else{const s=Array.isArray(t[r])?t[r]:[t[r]];for(const o of Array.isArray(i)?i:[i])s.includes(o)||s.push(o);t[r]=s}else typeof t[r]=="object"&&typeof i=="object"?t[r]=this.mergeClaims(t[r],i):t[r]=i;return t}},vae=class{constructor(n,e){this.keys=n,this.nonce=e}},rL=class{constructor(n,e){this._logger=new Qn("OidcClient"),this.settings=n instanceof jk?n:new jk(n),this.metadataService=e??new OH(this.settings),this._claimsService=new gae(this.settings),this._validator=new cae(this.settings,this.metadataService,this._claimsService),this._tokenClient=new MH(this.settings,this.metadataService)}async createSigninRequest({state:n,request:e,request_uri:t,request_type:r,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:l,response_type:c=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:f=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:v=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:S=this.settings.acr_values,resource:b=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:k=this.settings.extraQueryParams,extraTokenParams:R=this.settings.extraTokenParams,dpopJkt:I,omitScopeWhenRequesting:C=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if(c!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const O=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",O);const N=await uae.create({url:O,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:f,response_type:c,scope:u,state_data:n,url_state:l,prompt:p,display:m,max_age:v,ui_locales:g,id_token_hint:i,login_hint:s,acr_values:S,dpopJkt:I,resource:b,request:e,request_uri:t,extraQueryParams:k,extraTokenParams:R,request_type:r,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:C});await this.clearStaleState();const D=N.state;return await this.settings.stateStore.set(D.id,D.toStorageString()),N}async readSigninResponseState(n,e=!1){const t=this._logger.create("readSigninResponseState"),r=new $_(wN.readParams(n,this.settings.response_mode));if(!r.state)throw t.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await nL.fromStorageString(i),response:r}}async processSigninResponse(n,e){const t=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(n,!0);if(t.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const s=await this.getDpopProof(this.settings.dpop.store);e={...e,DPoP:s}}try{await this._validator.validateSigninResponse(i,r,e)}catch(s){if(s instanceof Dk&&this.settings.dpop){const o=await this.getDpopProof(this.settings.dpop.store,s.nonce);e.DPoP=o,await this._validator.validateSigninResponse(i,r,e)}else throw s}return i}async getDpopProof(n,e){let t,r;return(await n.getAllKeys()).includes(this.settings.client_id)?(r=await n.get(this.settings.client_id),r.nonce!==e&&e&&(r.nonce=e,await n.set(this.settings.client_id,r))):(t=await Do.generateDPoPKeys(),r=new vae(t,e),await n.set(this.settings.client_id,r)),await Do.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:n,password:e,skipUserInfo:t=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:n,password:e,...r}),s=new $_(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,t),s}async useRefreshToken({state:n,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let l;if(this.settings.refreshTokenAllowedScope===void 0)l=n.scope;else{const f=this.settings.refreshTokenAllowedScope.split(" ");l=(((o=n.scope)==null?void 0:o.split(" "))||[]).filter(m=>f.includes(m)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const f=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:f}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:n.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,...s})}catch(f){if(f instanceof Dk&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,f.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:n.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,...s});else throw f}const u=new $_(new URLSearchParams);return Object.assign(u,c),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...n,scope:l}),u}async createSignoutRequest({state:n,id_token_hint:e,client_id:t,request_type:r,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),a=await this.metadataService.getEndSessionEndpoint();if(!a)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",a),!t&&i&&!e&&(t=this.settings.client_id);const l=new fae({url:a,id_token_hint:e,client_id:t,post_logout_redirect_uri:i,state_data:n,extraQueryParams:s,request_type:r});await this.clearStaleState();const c=l.state;return c&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(n,e=!1){const t=this._logger.create("readSignoutResponseState"),r=new hae(wN.readParams(n,this.settings.response_mode));if(!r.state){if(t.debug("No state in response"),r.error)throw t.warn("Response was error:",r.error),new lp(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await nS.fromStorageString(i),response:r}}async processSignoutResponse(n){const e=this._logger.create("processSignoutResponse"),{state:t,response:r}=await this.readSignoutResponseState(n,!0);return t?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,t)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),nS.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(n,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:n,token_type_hint:e})}},oi=function(n){return n.NotSupported="OIDC authentication not supported",n.Misconfigured="OIDC is misconfigured",n.General="Something went wrong with OIDC discovery",n.OpSupport="Configured OIDC OP does not support required functions",n.DynamicRegistrationNotSupported="Dynamic registration not supported",n.DynamicRegistrationFailed="Dynamic registration failed",n.DynamicRegistrationInvalid="Dynamic registration invalid response",n.CodeExchangeFailed="Failed to exchange code for token",n.InvalidBearerTokenResponse="Invalid bearer token response",n.InvalidIdToken="Invalid ID token",n.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",n}({}),iL=n=>!!n&&typeof n=="object"&&!Array.isArray(n),yl=(n,e)=>!n[e]||!Wg(n,e)?(A.error("Missing or invalid property: ".concat(e)),!1):!0,Wg=(n,e)=>n[e]&&typeof n[e]!="string"?(A.error("Invalid property: ".concat(e)),!1):!0,CN=(n,e)=>n[e]&&(!Array.isArray(n[e])||!n[e].every(t=>typeof t=="string"))?(A.error("Invalid property: ".concat(e)),!1):!0,c2=(n,e,t)=>{var r=n[e];return!r||!Array.isArray(r)||!r.includes(t)?(A.error("Invalid property: ".concat(e,". ").concat(t," is required.")),!1):!0},DH=n=>{if(!iL(n))throw A.error("Issuer configuration not found or malformed"),new Error(oi.OpSupport);var e=[yl(n,"issuer"),yl(n,"authorization_endpoint"),yl(n,"token_endpoint"),yl(n,"revocation_endpoint"),Wg(n,"registration_endpoint"),Wg(n,"account_management_uri"),Wg(n,"device_authorization_endpoint"),CN(n,"account_management_actions_supported"),c2(n,"response_types_supported","code"),c2(n,"grant_types_supported","authorization_code"),c2(n,"code_challenge_methods_supported","S256"),CN(n,"prompt_values_supported")].some(t=>!t);if(!e)return n;throw A.error("Issuer configuration not valid"),new Error(oi.OpSupport)},jH=n=>{try{return PH(n)}catch(e){throw A.error("Could not decode id_token",e),e}},UH=(n,e,t,r)=>{try{if(!n)throw new Error("No ID token");var i=jH(n);if(i.iss!==e)throw new Error("Invalid issuer");var s=typeof i.aud=="string"?[i.aud]:i.aud;if(!s.includes(t))throw new Error("Invalid audience");if(r!==void 0&&i.nonce!==r)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(o){throw A.error("Invalid ID token",o),new Error(oi.InvalidIdToken)}};function FH(n){if(!iL(n))throw A.error("Stored user state not found"),new Error(oi.MissingOrInvalidStoredState);var e=[yl(n,"homeserverUrl"),yl(n,"nonce"),Wg(n,"identityServerUrl")].some(t=>!t);if(e)throw new Error(oi.MissingOrInvalidStoredState)}var yae=n=>iL(n)&&yl(n,"token_type")&&n.token_type.toLowerCase()==="bearer"&&yl(n,"access_token")&&yl(n,"refresh_token")&&(!("expires_in"in n)||typeof n.expires_in=="number");function $H(n){if(!yae(n))throw new Error(oi.InvalidBearerTokenResponse)}function TN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function rS(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?TN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):TN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var NE=n=>{var e=n??bs(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},_ae=function(){var n=F(function*(e){if(!globalThis.crypto.subtle)return A.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var t=yield xH(e);return PE(t)});return function(t){return n.apply(this,arguments)}}(),bae=n=>{var{redirectUri:e}=n;return{scope:NE(),redirectUri:e,state:bs(8),nonce:bs(8),codeVerifier:bs(64)}},Sae=function(){var n=F(function*(e,t,r){var{scope:i,redirectUri:s,state:o,nonce:a,codeVerifier:l}=r,c=new URL(e);return c.searchParams.append("response_mode","query"),c.searchParams.append("response_type","code"),c.searchParams.append("redirect_uri",s),c.searchParams.append("client_id",t),c.searchParams.append("state",o),c.searchParams.append("scope",i),c.searchParams.append("nonce",a),c.searchParams.append("code_challenge_method","S256"),c.searchParams.append("code_challenge",yield _ae(l)),c.toString()});return function(t,r,i){return n.apply(this,arguments)}}(),Eae=function(){var n=F(function*(e){var{metadata:t,redirectUri:r,clientId:i,homeserverUrl:s,identityServerUrl:o,nonce:a,prompt:l,urlState:c}=e,u=NE(),f=new rL(rS(rS({},t),{},{client_id:i,redirect_uri:r,authority:t.issuer,response_mode:"query",response_type:"code",scope:u,stateStore:new AE({prefix:"mx_oidc_",store:window.sessionStorage})})),p={homeserverUrl:s,nonce:a,identityServerUrl:o},m=yield f.createSigninRequest({state:p,nonce:a,prompt:l,url_state:c});return m.url});return function(t){return n.apply(this,arguments)}}(),wae=n=>({id_token:n.id_token,scope:n.scope,expires_at:n.expires_at,refresh_token:n.refresh_token,access_token:n.access_token,token_type:"Bearer"}),Cae=function(){var n=F(function*(e,t){var r=new URL(window.location.origin);r.searchParams.append("code",e),r.searchParams.append("state",t),Pv.setLogger(A);try{var i=new $_(r.searchParams),s=new AE({prefix:"mx_oidc_",store:window.sessionStorage}),o=yield s.get(i.state);if(!o)throw new Error(oi.MissingOrInvalidStoredState);var a=yield nL.fromStorageString(o),l=new rL(rS(rS({},a),{},{stateStore:s})),c=yield l.processSigninResponse(r.href),u=c.userState;FH(u),$H(c),UH(c.id_token,l.settings.authority,l.settings.client_id,u.nonce);var f=wae(c);return{oidcClientSettings:{clientId:l.settings.client_id,issuer:l.settings.authority},tokenResponse:f,homeserverUrl:u.homeserverUrl,identityServerUrl:u.identityServerUrl,idTokenClaims:c.profile}}catch(m){A.error("Oidc login failed",m);var p=m.message;throw Object.values(oi).includes(p)?m:new Error(oi.CodeExchangeFailed)}});return function(t,r){return n.apply(this,arguments)}}();function RN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function IN(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?RN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):RN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var sL=function(){var n=F(function*(e){var t=new URL(".well-known/openid-configuration",e),r=yield fetch(t,{method:ae.Get,signal:kE(5e3)}),i=yield r.json();return oL(i)});return function(t){return n.apply(this,arguments)}}(),oL=function(){var n=F(function*(e){var t=DH(e),r=new jk({authority:t.issuer,metadata:t,redirect_uri:"",client_id:""}),i=new OH(r);return IN(IN({},t),{},{signingKeys:yield i.getSigningKeys()})});return function(t){return n.apply(this,arguments)}}(),Tae="urn:ietf:params:oauth:grant-type:device_code",u2=(n,e)=>{if(!e)return!1;var t=new URL(e);return!(t.protocol!==n.protocol||t.hostname!==n.hostname&&!t.hostname.endsWith(".".concat(n.hostname)))},Rae=function(){var n=F(function*(e,t){if(!e.registration_endpoint)throw new Error(oi.DynamicRegistrationNotSupported);var r=["authorization_code","refresh_token"];if(r.some(u=>!e.grant_types_supported.includes(u)))throw new Error(oi.DynamicRegistrationNotSupported);var i=new URL(t.clientUri),s={client_name:t.clientName,client_uri:t.clientUri,response_types:["code"],grant_types:r,redirect_uris:t.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:t.applicationType,contacts:t.contacts,logo_uri:u2(i,t.logoUri)?t.logoUri:void 0,policy_uri:u2(i,t.policyUri)?t.policyUri:void 0,tos_uri:u2(i,t.tosUri)?t.tosUri:void 0},o={Accept:"application/json","Content-Type":"application/json"};try{var a=yield fetch(e.registration_endpoint,{method:ae.Post,headers:o,body:JSON.stringify(s)});if(a.status>=400)throw new Error(oi.DynamicRegistrationFailed);var l=yield a.json(),c=l.client_id;if(!c||typeof c!="string")throw new Error(oi.DynamicRegistrationInvalid);return c}catch(u){throw Object.values(oi).includes(u.message)?u:(A.error("Dynamic registration request failed",u),new Error(oi.DynamicRegistrationFailed))}});return function(t,r){return n.apply(this,arguments)}}();class Iae{constructor(e,t,r,i,s){this.idTokenClaims=s,L(this,"oidcClientReady",void 0),L(this,"oidcClient",void 0),L(this,"inflightRefreshRequest",void 0),this.oidcClientReady=this.initialiseOidcClient(e,t,i,r)}initialiseOidcClient(e,t,r,i){var s=this;return F(function*(){try{var o,a=yield sL(e),l=NE(r);s.oidcClient=new rL({metadata:a,signingKeys:(o=a.signingKeys)!==null&&o!==void 0?o:void 0,client_id:t,scope:l,redirect_uri:i,authority:a.issuer,stateStore:new AE({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(c){throw A.error("Failed to initialise OIDC client.",c),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var t=this;return F(function*(){t.inflightRefreshRequest||(t.inflightRefreshRequest=t.getNewTokens(e));try{var r=yield t.inflightRefreshRequest;return r}catch(i){throw i instanceof lp?new $P(i):i}finally{t.inflightRefreshRequest=void 0}})()}persistTokens(e){return F(function*(){})()}getNewTokens(e){var t=this;return F(function*(){if(!t.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");var r={refresh_token:e,session_state:"test",data:void 0,profile:t.idTokenClaims},i=yield t.oidcClient.useRefreshToken({state:r,timeoutInSeconds:300}),s={accessToken:i.access_token,refreshToken:i.refresh_token};return yield t.persistTokens(s),s})()}}var kae=["server","limit","since"];function kN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function dr(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):kN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var xae=3e3,xN=10*60*1e3,Pae=new Kn("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),cp=function(n){return n.Chronological="chronological",n.Detached="detached",n}({}),Lae=new SE("m.get_login_token","org.matrix.msc3882.get_login_token"),HH="uk.half-shot.msc2666",BH="uk.half-shot.msc2666.mutual_rooms",VH="uk.half-shot.msc2666.query_mutual_rooms",pa="org.matrix.msc4140",qH="uk.tcpip.msc4133",Qo="$",Oe=function(n){return n.Sync="sync",n.Event="event",n.ToDeviceEvent="toDeviceEvent",n.AccountData="accountData",n.Room="Room",n.DeleteRoom="deleteRoom",n.SyncUnexpectedError="sync.unexpectedError",n.ClientWellKnown="WellKnown.client",n.ReceivedVoipEvent="received_voip_event",n.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",n.TurnServers="turnServers",n.TurnServersError="turnServers.error",n}({}),Oae=new Kn("action","org.matrix.msc3824.action");class DE extends En{constructor(e){var t,r,i,s;super(),i=this,L(this,"logger",void 0),L(this,"reEmitter",new Mp(this)),L(this,"olmVersion",null),L(this,"usingExternalCrypto",!1),L(this,"_store",void 0),L(this,"deviceId",void 0),L(this,"credentials",void 0),L(this,"legacyPickleKey",void 0),L(this,"scheduler",void 0),L(this,"clientRunning",!1),L(this,"timelineSupport",!1),L(this,"urlPreviewCache",{}),L(this,"identityServer",void 0),L(this,"http",void 0),L(this,"cryptoBackend",void 0),L(this,"cryptoCallbacks",void 0),L(this,"callEventHandler",void 0),L(this,"groupCallEventHandler",void 0),L(this,"supportsCallTransfer",!1),L(this,"forceTURN",!1),L(this,"iceCandidatePoolSize",0),L(this,"idBaseUrl",void 0),L(this,"baseUrl",void 0),L(this,"isVoipWithNoMediaAllowed",void 0),L(this,"useLivekitForGroupCalls",void 0),L(this,"canSupportVoip",!1),L(this,"peekSync",null),L(this,"isGuestAccount",!1),L(this,"ongoingScrollbacks",{}),L(this,"notifTimelineSet",null),L(this,"legacyCryptoStore",void 0),L(this,"verificationMethods",void 0),L(this,"fallbackICEServerAllowed",!1),L(this,"syncApi",void 0),L(this,"roomNameGenerator",void 0),L(this,"pushRules",void 0),L(this,"syncLeftRoomsPromise",void 0),L(this,"syncedLeftRooms",!1),L(this,"clientOpts",void 0),L(this,"clientWellKnownIntervalID",void 0),L(this,"canResetTimelineCallback",void 0),L(this,"canSupport",new Map),L(this,"pushProcessor",new wo(this)),L(this,"serverVersionsPromise",void 0),L(this,"clientWellKnown",void 0),L(this,"clientWellKnownPromise",void 0),L(this,"turnServers",[]),L(this,"turnServersExpiry",0),L(this,"checkTurnServersIntervalID",void 0),L(this,"txnCtr",0),L(this,"mediaHandler",new Toe(this)),L(this,"sessionId",void 0),L(this,"eventsBeingEncrypted",new Set),L(this,"useE2eForGroupCall",!0),L(this,"toDeviceMessageQueue",void 0),L(this,"livekitServiceURL",void 0),L(this,"_secretStorage",void 0),L(this,"ignoredInvites",void 0),L(this,"matrixRTC",void 0),L(this,"serverCapabilitiesService",void 0),L(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&(Sk()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(Oe.Sync,this.startCallEventHandler))}),L(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(Oe.Sync,this.startMatrixRTC))}),L(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var a,l=((a=this.getRooms())!==null&&a!==void 0?a:[]).filter(f=>f.getUnreadNotificationCount(jt.Total)>0);for(var c of l){var u=this.getSafeUserId();c.fixupNotifications(u)}this.off(Oe.Sync,this.fixupRoomNotifications)}}),this.logger=(t=e.logger)!==null&&t!==void 0?t:A,e.baseUrl=GT(e.baseUrl),e.idBaseUrl=GT(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=(r=e.usingExternalCrypto)!==null&&r!==void 0?r:!1,this.store=e.store||new kse,this.deviceId=e.deviceId||null,this.sessionId=bs(10);var o=e.userId||null;this.credentials={userId:o},this.http=new oH(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:fr.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.pickleKey&&(this.legacyPickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(function(){var a=F(function*(l){var c=i.getRoom(l.getRoomId());l.status!==et.SENDING&&i.updatePendingEventStatus(c,l,et.SENDING);var u=yield i.sendEventHttpRequest(l);return c&&c.updatePendingEvent(l,et.SENT,u.event_id),u});return function(l){return a.apply(this,arguments)}}()),Sk()&&(this.callEventHandler=new Wse(this),this.groupCallEventHandler=new zse(this),this.canSupportVoip=!0,this.on(Oe.Sync,this.startCallEventHandler)),this.matrixRTC=new Joe(this),this.serverCapabilitiesService=new lH(this.http),this.on(Oe.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=e.iceCandidatePoolSize===void 0?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,e.useE2eForGroupCall!==void 0&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.livekitServiceURL=e.livekitServiceURL,this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new Moe(this),this.on(Mt.Decrypted,a=>{KH(this,a)}),this.ignoredInvites=new Aoe(this),this._secretStorage=new RH(this,(s=e.cryptoCallbacks)!==null&&s!==void 0?s:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>bl.createUser(t,this))}get store(){return this._store}startClient(e){var t=this;return F(function*(){if(!t.clientRunning){t.clientRunning=!0,t.on(Oe.Sync,t.startMatrixRTC);var r=t.getUserId();r&&t.store.storeUser(new bl(r)),t.canSupportVoip&&(t.checkTurnServersIntervalID=setInterval(()=>{t.checkTurnServers()},xN),t.checkTurnServers()),t.syncApi&&(t.logger.error("Still have sync object whilst not running: stopping old one"),t.syncApi.stop());try{yield t.getVersions();var{threads:i,list:s,fwdPagination:o}=yield t.doesServerSupportThread();fn.setServerSideSupport(i),fn.setServerSideListSupport(s),fn.setServerSideFwdPaginationSupport(o)}catch(a){t.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}t.clientOpts=e??{},t.clientOpts.slidingSync?t.syncApi=new EH(t.clientOpts.slidingSync,t,t.clientOpts,t.buildSyncApiOptions()):t.syncApi=new gd(t,t.clientOpts,t.buildSyncApiOptions()),t.syncApi.sync().catch(a=>t.logger.info("Sync startup aborted with an error:",a)),t.clientOpts.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*t.clientOpts.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.toDeviceMessageQueue.start(),t.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,r,i,s;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(Oe.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)===null||t===void 0||t.stop(),this.syncApi=void 0,(r=this.peekSync)===null||r===void 0||r.stopPeeking(),(i=this.callEventHandler)===null||i===void 0||i.stop(),(s=this.groupCallEventHandler)===null||s===void 0||s.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.clientWellKnownIntervalID!==void 0&&globalThis.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop(),this.matrixRTC.stop(),this.serverCapabilitiesService.stop())}clearStores(){var e=this;if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var t=[];t.push(this.store.deleteAllData()),this.legacyCryptoStore&&t.push(this.legacyCryptoStore.deleteAllData());var r=function(){var i=F(function*(){var s;try{if(s=globalThis.indexedDB,!s)return}catch{return}var o=function*(c){var u=new Promise((f,p)=>{e.logger.info("Removing IndexedDB instance ".concat(c));var m=s.deleteDatabase(c);m.onsuccess=v=>{e.logger.info("Removed IndexedDB instance ".concat(c)),f(0)},m.onerror=v=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(c,":"),v),f(0)},m.onblocked=v=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(c))}});yield u};for(var a of["".concat(i2,"::matrix-sdk-crypto"),"".concat(i2,"::matrix-sdk-crypto-meta")])yield*o(a)});return function(){return i.apply(this,arguments)}}();return t.push(r()),Promise.all(t).then()}getUserId(){var e,t;return(e=(t=this.credentials)===null||t===void 0?void 0:t.userId)!==null&&e!==void 0?e:null}getSafeUserId(){var e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){var e;return(e=this.credentials)!==null&&e!==void 0&&e.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){var e,t;return(e=(t=this.credentials)===null||t===void 0||(t=t.userId)===null||t===void 0?void 0:t.split(":")[0].substring(1))!==null&&e!==void 0?e:null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return Iv(this,e)}createGroupCall(e,t,r,i,s,o){var a=this;return F(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var l=a.getRoom(e);if(!l)throw new Error("Cannot find room ".concat(e));return new GP(a,l,t,r,i,void 0,s||a.isVoipWithNoMediaAllowed,o,a.isVoipWithNoMediaAllowed,a.useLivekitForGroupCalls,a.livekitServiceURL).create()})()}getLivekitServiceURL(){return this.livekitServiceURL}setLivekitServiceURL(e){this.livekitServiceURL=e}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return(e=(t=this.syncApi)===null||t===void 0?void 0:t.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===Dt.Prepared||e===Dt.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),(e=(t=this.syncApi)===null||t===void 0?void 0:t.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return F(function*(){var t=e.serverCapabilitiesService.getCachedCapabilities();return t||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initRustCrypto(){var e=arguments,t=this;return F(function*(){var r,i=e.length>0&&e[0]!==void 0?e[0]:{};if(t.cryptoBackend){t.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var s=t.getUserId();if(s===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var o=t.getDeviceId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");t.logger.debug("Downloading Rust crypto library");var a=yield Cv(()=>import("./index-MJ21HWfZ.js"),__vite__mapDeps([0,1]),import.meta.url),l=yield a.initRustCrypto({logger:t.logger,http:t.http,userId:s,deviceId:o,secretStorage:t.secretStorage,cryptoCallbacks:t.cryptoCallbacks,storePrefix:i.useIndexedDB===!1?null:i2,storeKey:i.storageKey,storePassphrase:i.storagePassword,legacyCryptoStore:t.legacyCryptoStore,legacyPickleKey:(r=t.legacyPickleKey)!==null&&r!==void 0?r:"DEFAULT_KEY",legacyMigrationProgressListener:(c,u)=>{t.emit(Rr.LegacyCryptoStoreMigrationProgress,c,u)}});l.setSupportedVerificationMethods(t.verificationMethods),t.cryptoBackend=l,t.on(Wi.Membership,l.onRoomMembership.bind(l)),t.on(Oe.Event,c=>{l.onLiveEventFromSync(c)}),t.reEmitter.reEmit(l,[Rr.VerificationRequestReceived,Rr.UserTrustStatusChanged,Rr.KeyBackupStatus,Rr.KeyBackupSessionsRemaining,Rr.KeyBackupFailed,Rr.KeyBackupDecryptionKeyCached,Rr.KeysChanged,Rr.DevicesUpdated,Rr.WillUpdateDevices,Rr.DehydratedDeviceCreated,Rr.DehydratedDeviceUploaded,Rr.RehydrationStarted,Rr.RehydrationProgress,Rr.RehydrationCompleted,Rr.RehydrationError,Rr.DehydrationKeyCached,Rr.DehydratedDeviceRotationError])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){var t=this.getRoom(e);return t?t.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,t,r){var i;t!==void 0?i=Ie("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Ie("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys";var s=r===void 0?void 0:{version:r};return{path:i,queryData:s}}deleteKeysFromBackup(e,t,r){var i=this;return F(function*(){var s=i.makeKeyBackupPath(e,t,r);yield i.http.authedRequest(ae.Delete,s.path,s.queryData,void 0,{prefix:fr.V3})})()}getMediaConfig(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=e?"/media/config":"/config";return this.http.authedRequest(ae.Get,t,void 0,void 0,{prefix:e?fr.V1:Lh.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.store.getRooms(),r=new Set;for(var i of t){var s,o=(s=i.findPredecessor(e))===null||s===void 0?void 0:s.roomId;o&&r.add(o)}return t.filter(a=>{var l=a.currentState.getStateEvents(ee.RoomTombstone,"");return!(l&&r.has(a.roomId))})}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){var r=this;return F(function*(){if(!r.clientRunning)return A.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),yield fk(5,()=>r.setAccountDataRaw(e,t));var i=r.store.getAccountData(e);if(i&&Md(i.event.content,t))return{};var s=ru();function o(l){l.getType()===e&&s.resolve()}r.addListener(Oe.AccountData,o);try{var a=yield fk(5,()=>r.setAccountDataRaw(e,t));return yield s.promise,a}finally{r.removeListener(Oe.AccountData,o)}})()}setAccountDataRaw(e,t){var r=Ie("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(ae.Put,r,void 0,t)}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t=this;return F(function*(){if(t.isInitialSyncComplete()){var r=t.store.getAccountData(e);return r?r.getContent():null}var i=Ie("/user/$userId/account_data/$type",{$userId:t.credentials.userId,$type:e});try{return yield t.http.authedRequest(ae.Get,i)}catch(o){var s;if(((s=o.data)===null||s===void 0?void 0:s.errcode)==="M_NOT_FOUND")return null;throw o}})()}deleteAccountData(e){var t=this;return F(function*(){var r=t.canSupport.get(vr.AccountDataDeletion);if(r===gr.Unsupported){yield t.setAccountData(e,{});return}var i=Ie("/user/$userId/account_data/$type",{$userId:t.getSafeUserId(),$type:e}),s=r===gr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield t.http.authedRequest(ae.Delete,i,void 0,void 0,s)})()}getIgnoredUsers(){var e=this.getAccountData(ee.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){var t={ignored_users:{}};return e.forEach(r=>{t.ignored_users[r]={}}),this.setAccountData(ee.IgnoredUserList,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};i.syncRoom===void 0&&(i.syncRoom=!0);var s=r.getRoom(e);if(s!=null&&s.hasMembershipState(r.credentials.userId,qe.Join))return s;var o=Promise.resolve();if(i.inviteSignUrl){var a=new URL(i.inviteSignUrl);a.searchParams.set("mxid",r.credentials.userId),o=r.http.requestOtherUrl(ae.Post,a)}var l={};i.viaServers&&(l.server_name=i.viaServers,l.via=i.viaServers);var c={},u=yield o;u&&(c.third_party_signed=u);var f=Ie("/join/$roomid",{$roomid:e}),p=yield r.http.authedRequest(ae.Post,f,l,c),m=p.room_id,v=r.getRoom(m);if(v!=null&&v.hasMembershipState(r.credentials.userId,qe.Join))return v;var g=new gd(r,r.clientOpts,r.buildSyncApiOptions()),S=g.createRoom(m);return i.syncRoom,S})()}knockRoom(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,qe.Knock))return Promise.resolve({room_id:r.roomId});var i=Ie("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);var o={};return t.reason&&(o.reason=t.reason),this.http.authedRequest(ae.Post,i,s,o)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,et.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![et.QUEUED,et.NOT_SENT,et.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===et.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===et.QUEUED&&this.scheduler.removeEventFromQueue(e);var t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,et.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,ee.RoomName,{name:t})}setRoomTopic(e,t,r){var i=G$(t,r);return this.sendStateEvent(e,ee.RoomTopic,i)}getRoomTags(e){var t=Ie("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(ae.Get,t)}setRoomTag(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=Ie("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(ae.Put,i,void 0,r)}deleteRoomTag(e,t){var r=Ie("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(ae.Delete,r)}setRoomAccountData(e,t,r){var i=Ie("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(ae.Put,i,void 0,r)}setPowerLevel(e,t,r){var i=this;return F(function*(){var s,o;if(i.clientRunning&&i.isInitialSyncComplete()){var a;o=(a=i.getRoom(e))===null||a===void 0||(a=a.currentState)===null||a===void 0||(a=a.getStateEvents(ee.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!o)try{o=yield i.getStateEvent(e,ee.RoomPowerLevels,"")}catch(u){if(u instanceof bn&&u.errcode==="M_NOT_FOUND")o={};else throw u}o=wE(o),(s=o)!==null&&s!==void 0&&s.users||(o.users={});var l=Array.isArray(t)?t:[t];for(var c of l)r==null?delete o.users[c]:o.users[c]=r;return i.sendStateEvent(e,ee.RoomPowerLevels,o,"")})()}unstable_createLiveBeacon(e,t){var r=this;return F(function*(){return r.unstable_setLiveBeacon(e,t)})()}unstable_setLiveBeacon(e,t){var r=this;return F(function*(){return r.sendStateEvent(e,JP.name,t,r.getUserId())})()}sendEvent(e,t,r,i,s){var o,a,l,c;return!(t!=null&&t.startsWith(Qo))&&t!==null?(c=i,l=r,a=t,o=null):(c=s,l=i,a=r,o=t),this.addThreadRelationIfNeeded(l,o,e),this.sendCompleteEvent(e,o,{type:a,content:l},c)}addThreadRelationIfNeeded(e,t,r){var i;if(t&&!((i=e["m.relates_to"])!==null&&i!==void 0&&i.rel_type)){var s,o,a=!!((s=e["m.relates_to"])!==null&&s!==void 0&&s["m.in_reply_to"]);e["m.relates_to"]=dr(dr({},e["m.relates_to"]),{},{rel_type:Qt.name,event_id:t,is_falling_back:!a});var l=(o=this.getRoom(r))===null||o===void 0?void 0:o.getThread(t);if(l&&!a){var c,u;e["m.relates_to"]["m.in_reply_to"]={event_id:(c=(u=l.lastReply(f=>f.isRelation(Qt.name)&&!f.status))===null||u===void 0?void 0:u.getId())!==null&&c!==void 0?c:t}}}}sendCompleteEvent(e,t,r,i,s){var o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());var l=new wi(Object.assign(r,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),c=this.getRoom(e),u=t?c==null?void 0:c.getThread(t):void 0;u&&l.setThread(u),o||(this.reEmitter.reEmit(l,[Mt.Replaced,Mt.VisibilityChange]),c==null||c.reEmitter.reEmit(l,[Mt.BeforeRedaction]));var f=l.getAssociatedId();if(f!=null&&f.startsWith("~")){var p=c==null?void 0:c.getPendingEvents().find(v=>v.getId()===f);p==null||p.once(Mt.LocalEventIdReplaced,()=>{l.updateAssociatedId(p.getId())})}var m=l.getType();return this.logger.debug("sendEvent of type ".concat(m," in ").concat(e," with txnId ").concat(a).concat(o?" (delayed event)":"")),l.setTxnId(a),l.setStatus(et.SENDING),o?this.encryptAndSendEvent(c,l,o):(c==null||c.addPendingEvent(l,a),l.status===et.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(c,l))}encryptAndSendEvent(e,t,r){var i=this;return F(function*(){if(r)return i.sendEventHttpRequest(t,r);try{var s;i.eventsBeingEncrypted.add(t.getId());try{yield i.encryptEventIfNeeded(t,e??void 0)}finally{s=!i.eventsBeingEncrypted.delete(t.getId())}if(s)return{};t.status===et.ENCRYPTING&&i.updatePendingEventStatus(e,t,et.SENDING);var o=null;return i.scheduler&&(o=i.scheduler.queueEvent(t),o&&i.scheduler.getQueueForEvent(t).length>1&&i.updatePendingEventStatus(e,t,et.QUEUED)),o||(o=i.sendEventHttpRequest(t),e&&(o=o.then(a=>(e.updatePendingEvent(t,et.SENT,a.event_id),a)))),yield o}catch(a){i.logger.error("Error sending event",a);try{t.error=a,i.updatePendingEventStatus(e,t,et.NOT_SENT)}catch(l){i.logger.error("Exception in error handler!",l)}throw a instanceof bn&&(a.event=t),a}})()}encryptEventIfNeeded(e,t){var r=this;return F(function*(){if(t&&(yield r.shouldEncryptEventForRoom(e,t))&&!(!r.cryptoBackend&&r.usingExternalCrypto)){if(!r.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");r.updatePendingEventStatus(t,e,et.ENCRYPTING),yield r.cryptoBackend.encryptEvent(e,t)}})()}shouldEncryptEventForRoom(e,t){var r=this;return F(function*(){var i;return e.isEncrypted()||e.getType()===ee.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||(yield(i=r.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(t.roomId)))})()}getEncryptedIfNeededEventType(e,t){var r;return t===ee.Reaction?t:(r=this.getRoom(e))!==null&&r!==void 0&&r.hasEncryptionStateEvent()?ee.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,r){e?e.updatePendingEvent(t,r):t.setStatus(r)}sendEventHttpRequest(e,t){var r=e.getTxnId();r||(r=this.makeTxnId(),e.setTxnId(r));var i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:r},s;if(e.isState()){var o="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(o="/rooms/$roomId/state/$eventType/$stateKey"),s=Ie(o,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";s=Ie(a,dr({$redactsEventId:e.event.redacts},i))}else s=Ie("/rooms/$roomId/send/$eventType/$txnId",i);var l=e.getWireContent();return t?this.http.authedRequest(ae.Put,s,PN(t),l):this.http.authedRequest(ae.Put,s,void 0,l).then(c=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(c.event_id)),c))}redactEvent(e,t,r,i,s){var o,a,l;(o=r)!==null&&o!==void 0&&o.startsWith(Qo)||(s=i,i=r,r=t,t=null);var c=(a=s)===null||a===void 0?void 0:a.reason,u={reason:c};if(((l=s)===null||l===void 0?void 0:l.with_rel_types)!==void 0){if(this.canSupport.get(vr.RelationBasedRedactions)===gr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(r," txnId: ").concat(i," threadId ").concat(t));var f=this.canSupport.get(vr.RelationBasedRedactions)===gr.Stable?ok.stable:ok.unstable;u[f]=s.with_rel_types}return this.sendCompleteEvent(e,t,{type:ee.RoomRedaction,content:u,redacts:r},i)}sendMessage(e,t,r,i){typeof t!="string"&&t!==null&&(i=r,r=t,t=null);var s=ee.RoomMessage,o=r;return this.sendEvent(e,t,s,o,i)}sendTextMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=H$(r);return this.sendMessage(e,t,o,i)}sendNotice(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=B$(r);return this.sendMessage(e,t,o,i)}sendEmoteMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=V$(r);return this.sendMessage(e,t,o,i)}sendImageMessage(e,t,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(o=i||"Image",i=r,r=t,t=null);var a={msgtype:La.Image,url:r,info:i,body:o};return this.sendMessage(e,t,a)}sendStickerMessage(e,t,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(o=i||"Sticker",i=r,r=t,t=null);var a={url:r,info:i,body:o};return this.sendEvent(e,t,ee.Sticker,a)}sendHtmlMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=U$(r,i);return this.sendMessage(e,t,o)}sendHtmlNotice(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=F$(r,i);return this.sendMessage(e,t,o)}sendHtmlEmote(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=$$(r,i);return this.sendMessage(e,t,o)}_unstable_sendDelayedEvent(e,t,r,i,s,o){var a=this;return F(function*(){if(!(yield a.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","sendDelayedEvent");return a.addThreadRelationIfNeeded(s,r,e),a.sendCompleteEvent(e,r,{type:i,content:s},t,o)})()}_unstable_sendDelayedStateEvent(e,t,r,i){var s=arguments,o=this;return F(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"",l=s.length>5&&s[5]!==void 0?s[5]:{};if(!(yield o.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","sendDelayedStateEvent");var c={$roomId:e,$eventType:r,$stateKey:a},u=Ie("/rooms/$roomId/state/$eventType",c);return a!==void 0&&(u=Ie(u+"/$stateKey",c)),o.http.authedRequest(ae.Put,u,PN(t),i,l)})()}_unstable_getDelayedEvents(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","getDelayedEvents");var r=e?{from:e}:void 0;return yield t.http.authedRequest(ae.Get,"/delayed_events",r,void 0,{prefix:"".concat(fr.Unstable,"/").concat(pa)})})()}_unstable_updateDelayedEvent(e,t){var r=arguments,i=this;return F(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(!(yield i.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","updateDelayedEvent");var o=Ie("/delayed_events/$delayId",{$delayId:e}),a={action:t};return yield i.http.authedRequest(ae.Post,o,void 0,a,dr(dr({},s),{},{prefix:"".concat(fr.Unstable,"/").concat(pa)}))})()}sendReceipt(e,t,r){var i=arguments,s=this;return F(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:!1;if(s.isGuest())return Promise.resolve({});var a=Ie("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),l=!o&&s.supportsThreads(),c=l?dr(dr({},r),{},{thread_id:up(e)}):r,u=s.http.authedRequest(ae.Post,a,void 0,c||{}),f=s.getRoom(e.getRoomId());return f&&s.credentials.userId&&f.addLocalEchoReceipt(s.credentials.userId,e,t,o),u})()}sendReadReceipt(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:vi.Read,s=t.length>2&&t[2]!==void 0?t[2]:!1;if(e){var o=e.getId(),a=r.getRoom(e.getRoomId());if(a!=null&&a.hasPendingEvent(o))throw new Error("Cannot set read receipt to a pending event (".concat(o,")"));return r.sendReceipt(e,i,{},s)}})()}setRoomReadMarkers(e,t,r,i){var s=this;return F(function*(){var o=s.getRoom(e);if(o!=null&&o.hasPendingEvent(t))throw new Error("Cannot set read marker to a pending event (".concat(t,")"));var a;if(r){if(a=r.getId(),o!=null&&o.hasPendingEvent(a))throw new Error("Cannot set read receipt to a pending event (".concat(a,")"));o==null||o.addLocalEchoReceipt(s.credentials.userId,r,vi.Read)}var l;if(i){if(l=i.getId(),o!=null&&o.hasPendingEvent(l))throw new Error("Cannot set read receipt to a pending event (".concat(l,")"));o==null||o.addLocalEchoReceipt(s.credentials.userId,i,vi.ReadPrivate)}return yield s.setRoomReadMarkersHttpRequest(e,t,a,l)})()}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;var r=new URL(e);r.hash="",e=r.toString();var i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var s=this.http.authedRequest(ae.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:Lh.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,t,r){if(this.isGuest())return Promise.resolve({});var i=Ie("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:t};return t&&(s.timeout=r||2e4),this.http.authedRequest(ae.Put,i,void 0,s)}getRoomUpgradeHistory(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getRoom(e);if(!i)return[];var s=this.findPredecessorRooms(i,t,r),o=this.findSuccessorRooms(i,t,r);return[...s,i,...o]}findPredecessorRooms(e,t,r){for(var i,s=[],o=new Set([e.roomId]),a=(i=e.findPredecessor(r))===null||i===void 0?void 0:i.roomId;a!==null;){var l;if(a){if(o.has(a))break;o.add(a)}var c=this.getRoom(a);if(c===null)break;if(t){var u=c.currentState.getStateEvents(ee.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}s.splice(0,0,c),e=c,a=(l=e.findPredecessor(r))===null||l===void 0?void 0:l.roomId}return s}findSuccessorRooms(e,t,r){for(var i=[],s=e.currentState.getStateEvents(ee.RoomTombstone,"");s;){var o=this.getRoom(s.getContent().replacement_room);if(!o||o.roomId===e.roomId)break;if(t){var a,l=(a=o.findPredecessor(r))===null||a===void 0?void 0:a.roomId;if(!l||l!==e.roomId)break}i.push(o);var c=new Set(i.map(u=>u.roomId));if(c.size<i.length)return i.slice(0,i.length-1);e=o,s=e.currentState.getStateEvents(ee.RoomTombstone,"")}return i}invite(e,t,r){return this.membershipChange(e,t,qe.Invite,r)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}inviteByThreePid(e,t,r){var i=this;return F(function*(){var s,o=Ie("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new bn({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var l={id_server:a,medium:t,address:r};if((s=i.identityServer)!==null&&s!==void 0&&s.getAccessToken){var c=yield i.identityServer.getAccessToken();c&&(l.id_access_token=c)}return i.http.authedRequest(ae.Post,o,void 0,l)})()}leave(e){return this.membershipChange(e,void 0,qe.Leave)}leaveRoomChain(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this.getRoomUpgradeHistory(e),i=r;if(!t){i=[];for(var s of r)if(i.push(s),s.roomId===e)break}var o={},a=[],l=u=>this.leave(u).then(()=>{delete o[u]}).catch(f=>{o[u]=f});for(var c of i)a.push(l(c.roomId));return Promise.all(a).then(()=>o)}ban(e,t,r){return this.membershipChange(e,t,qe.Ban,r)}forget(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,s=Ie("/rooms/$room_id/forget",{$room_id:e}),o=yield r.http.authedRequest(ae.Post,s);return i&&(r.store.removeRoom(e),r.emit(Oe.DeleteRoom,e)),o})()}unban(e,t){var r=Ie("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(ae.Post,r,void 0,i)}kick(e,t,r){var i=Ie("/rooms/$roomId/kick",{$roomId:e}),s={user_id:t,reason:r};return this.http.authedRequest(ae.Post,i,void 0,s)}membershipChange(e,t,r,i){var s=Ie("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(ae.Post,s,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||t){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||t){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,t){var r=Ie("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(ae.Put,r,void 0,t)}setDisplayName(e){var t=this;return F(function*(){var r=yield t.setProfileInfo("displayname",{displayname:e}),i=t.getUser(t.getUserId());return i&&(i.displayName=e,i.emit(qr.DisplayName,i.events.presence,i)),r})()}setAvatarUrl(e){var t=this;return F(function*(){var r=yield t.setProfileInfo("avatar_url",{avatar_url:e}),i=t.getUser(t.getUserId());return i&&(i.avatarUrl=e,i.emit(qr.AvatarUrl,i.events.presence,i)),r})()}mxcUrlToHttp(e,t,r,i,s,o,a){return TE(this.baseUrl,e,t,r,i,s,o,a)}setSyncPresence(e){var t=this;return F(function*(){var r;(r=t.syncApi)===null||r===void 0||r.setPresence(e)})()}setPresence(e){var t=this;return F(function*(){var r=Ie("/presence/$userId/status",{$userId:t.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield t.http.authedRequest(ae.Put,r,void 0,e)})()}getPresence(e){var t=Ie("/presence/$userId/status",{$userId:e});return this.http.authedRequest(ae.Get,t)}scrollback(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:30,r=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){var s=Date.now()-i.errorTs;r=Math.max(xae-s,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var o=this.store.scrollback(e,t).length;if(o===t)return Promise.resolve(e);t=t-o;var a=new Promise((l,c)=>{nu(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,ht.Backward)).then(u=>{var f,p,m=u.chunk.map(this.getEventMapper());if(u.state){var v=u.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(v)}var[g,S,b]=e.partitionThreadedEvents(m);this.processAggregatedTimelineEvents(e,g),e.addEventsToTimeline(g,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,S,!0),b.forEach(w=>e.relations.aggregateChildEvent(w)),e.oldState.paginationToken=(f=u.end)!==null&&f!==void 0?f:null,u.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,m,(p=u.end)!==null&&p!==void 0?p:null,!0),delete this.ongoingScrollbacks[e.roomId],l(e)}).catch(u=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(u)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return woe(this,e||{})}getEventTimeline(e,t){var r=this;return F(function*(){var i,s,o,a;if(!r.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(e!=null&&e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&r.supportsThreads())return r.getThreadTimeline(e,t);var l=Ie("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),c=void 0;(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(c={filter:JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER)});var u=yield r.http.authedRequest(ae.Get,l,c);if(!u.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);var f=r.getEventMapper(),p=f(u.event);if(p.isRelation(Qt.name)){r.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var m=[...u.events_after.reverse().map(f),p,...u.events_before.map(f)],v=e.getTimelineForEvent(m[0].getId());v?v.getState(Le.BACKWARDS).setUnknownStateEvents(u.state.map(f)):(v=e.addTimeline(),v.initialiseState(u.state.map(f)),v.getState(Le.FORWARDS).paginationToken=u.end);var[g,S,b]=e.room.partitionThreadedEvents(m);return e.addEventsToTimeline(g,!0,!1,v,u.start),r.processThreadEvents(e.room,S,!0),r.processAggregatedTimelineEvents(e.room,g),b.forEach(w=>e.relations.aggregateChildEvent(w)),(s=(o=e.getTimelineForEvent(t))!==null&&o!==void 0?o:(a=e.room.findThreadForEvent(p))===null||a===void 0?void 0:a.liveTimeline)!==null&&s!==void 0?s:v})()}getThreadTimeline(e,t){var r=this;return F(function*(){var i;if(!r.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var s=Ie("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),o={limit:"0"};(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(o.filter=JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER));var a=yield r.http.authedRequest(ae.Get,s,o),l=r.getEventMapper(),c=l(a.event);if(e.canContain(c)){var u=r.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported;if(fn.hasServerSideSupport)if(fn.hasServerSideFwdPaginationSupport){var f,p,m;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var v=e.thread,g=yield r.fetchRelations(e.room.roomId,v.id,null,null,{dir:ht.Backward,from:a.start,recurse:u||void 0}),S=yield r.fetchRelations(e.room.roomId,v.id,null,null,{dir:ht.Forward,from:a.end,recurse:u||void 0}),b=[...S.chunk.reverse().filter(l2(v.id)).map(l),c,...g.chunk.filter(l2(v.id)).map(l)];for(var w of b){var k;yield(k=e.thread)===null||k===void 0?void 0:k.processEvent(w)}var R=e.getTimelineForEvent(c.getId());if(R?R.getState(Le.BACKWARDS).setUnknownStateEvents(a.state.map(l)):(R=e.addTimeline(),R.initialiseState(a.state.map(l))),e.addEventsToTimeline(b,!0,!1,R,S.next_batch),!g.next_batch){var I=yield r.fetchRoomEvent(e.room.roomId,v.id);e.addEventsToTimeline([l(I)],!0,!1,R,null)}return R.setPaginationToken((f=g.next_batch)!==null&&f!==void 0?f:null,ht.Backward),R.setPaginationToken((p=S.next_batch)!==null&&p!==void 0?p:null,ht.Forward),r.processAggregatedTimelineEvents(e.room,b),(m=e.getTimelineForEvent(t))!==null&&m!==void 0?m:R}else{for(var C,x=e.thread,O=yield r.fetchRelations(e.room.roomId,x.id,Qt.name,null,{dir:ht.Backward,from:a.start,recurse:u||void 0}),N=[],D=a.end;D;){var j,U=yield r.fetchRelations(e.room.roomId,x.id,Qt.name,null,{dir:ht.Forward,from:D,recurse:u||void 0});D=(j=U.next_batch)!==null&&j!==void 0?j:null,N.push(...U.chunk)}var H=[...N.reverse().map(l),c,...O.chunk.map(l)];for(var K of H){var B;yield(B=e.thread)===null||B===void 0?void 0:B.processEvent(K)}var z=e.getLiveTimeline();if(z.getState(Le.BACKWARDS).setUnknownStateEvents(a.state.map(l)),e.addEventsToTimeline(H,!0,!1,z,null),!O.next_batch){var W=yield r.fetchRoomEvent(e.room.roomId,x.id);e.addEventsToTimeline([l(W)],!0,!1,z,null)}return z.setPaginationToken((C=O.next_batch)!==null&&C!==void 0?C:null,ht.Backward),z.setPaginationToken(null,ht.Forward),r.processAggregatedTimelineEvents(e.room,H),z}}})()}getLatestTimeline(e){var t=this;return F(function*(){if(!t.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");var r;if(e.threadListType!==null){var i,s=yield t.createThreadListMessagesRequest(e.room.roomId,null,1,ht.Backward,e.threadListType,e.getFilter());r=(i=s.chunk)===null||i===void 0?void 0:i[0]}else if(e.thread&&fn.hasServerSideSupport){var o,a=t.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported,l=yield t.fetchRelations(e.room.roomId,e.thread.id,Qt.name,null,{dir:ht.Backward,limit:1,recurse:a||void 0});r=(o=l.chunk)===null||o===void 0?void 0:o[0]}else{var c,u,f=Ie("/rooms/$roomId/messages",{$roomId:e.room.roomId}),p={dir:"b"};(c=t.clientOpts)!==null&&c!==void 0&&c.lazyLoadMembers&&(p.filter=JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER));var m=yield t.http.authedRequest(ae.Get,f,p);r=(u=m.chunk)===null||u===void 0?void 0:u[0]}if(!r)throw new Error("No message returned when trying to construct getLatestTimeline");return t.getEventTimeline(e,r.event_id)})()}createMessagesRequest(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,s=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,a=Ie("/rooms/$roomId/messages",{$roomId:e}),l={limit:i.toString(),dir:s};t&&(l.from=t);var c=null;if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(c=Object.assign({},Bi.LAZY_LOADING_MESSAGES_FILTER)),o){var u;c=c||{},Object.assign(c,(u=o.getRoomTimelineFilterComponent())===null||u===void 0?void 0:u.toJSON())}return c&&(l.filter=JSON.stringify(c)),this.http.authedRequest(ae.Get,a,l)}createThreadListMessagesRequest(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:ht.Backward,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:So.All,a=arguments.length>5?arguments[5]:void 0,l=Ie("/rooms/$roomId/threads",{$roomId:e}),c={limit:i.toString(),dir:s,include:GH(o)};t&&(c.from=t);var u={};if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(u=dr({},Bi.LAZY_LOADING_MESSAGES_FILTER)),a){var f;u=dr(dr({},u),(f=a.getRoomTimelineFilterComponent())===null||f===void 0?void 0:f.toJSON())}Object.keys(u).length&&(c.filter=JSON.stringify(u));var p={prefix:fn.hasServerSideListSupport===si.Stable?fr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(ae.Get,l,c,void 0,p).then(m=>{var v;return dr(dr({},m),{},{chunk:(v=m.chunk)===null||v===void 0?void 0:v.reverse(),start:m.prev_batch,end:m.next_batch})})}paginateEventTimeline(e,t){var r=this,i=e.getTimelineSet()===this.notifTimelineSet,s=this.getRoom(e.getRoomId()),o=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;t=t||{};var l=t.backwards||!1;if(i&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");var c=l?Le.BACKWARDS:Le.FORWARDS,u=e.getPaginationToken(c),f=e.paginationRequests[c];if(f)return f;var p,m,v;if(i){var g;p="/notifications",m={limit:((g=t.limit)!==null&&g!==void 0?g:30).toString(),only:"highlight"},u&&u!=="end"&&(m.from=u),v=this.http.authedRequest(ae.Get,p,m).then(function(){var R=F(function*(I){var C=I.next_token,x=[];I.notifications=I.notifications.filter(Ro);for(var O=0;O<I.notifications.length;O++){var N=I.notifications[O],D=r.getEventMapper()(N.event);r.getPushDetailsForEvent(D,!0),D.event.room_id=N.room_id,x[O]=D}var j=e.getTimelineSet();return j.addEventsToTimeline(x,l,!1,e,C),r.processAggregatedTimelineEvents(j.room,x),l&&!I.next_token&&e.setPaginationToken(null,c),!!I.next_token});return function(I){return R.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else if(o!==null){if(!s)throw new Error("Unknown room "+e.getRoomId());if(!fn.hasServerSideFwdPaginationSupport&&c===ht.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");v=this.createThreadListMessagesRequest(e.getRoomId(),u,t.limit,c,o,e.getFilter()).then(R=>{if(R.state){var I=e.getState(c),C=R.state.filter(Ro).map(this.getEventMapper());I.setUnknownStateEvents(C)}var x=R.end,O=R.chunk.filter(Ro).map(this.getEventMapper()),N=e.getTimelineSet();return N.addEventsToTimeline(O,l,!1,e,x),this.processAggregatedTimelineEvents(s,O),this.processThreadRoots(s,O,l),l&&R.end==R.start&&e.setPaginationToken(null,c),R.end!==R.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else if(a){var S,b,w=this.getRoom((S=e.getRoomId())!==null&&S!==void 0?S:void 0);if(!w)throw new Error("Unknown room "+e.getRoomId());var k=this.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported;v=this.fetchRelations((b=e.getRoomId())!==null&&b!==void 0?b:"",a.id,null,null,{dir:c,limit:t.limit,from:u??void 0,recurse:k||void 0}).then(function(){var R=F(function*(I){var C=r.getEventMapper(),x=I.chunk.filter(Ro).filter(l2(a.id)).map(C);for(var O of x.slice().reverse()){yield a==null?void 0:a.processEvent(O);var N=O.getSender();(!l||(a==null?void 0:a.getEventReadUpTo(N))===null)&&w.addLocalEchoReceipt(N,O,vi.Read)}var D=I.next_batch,j=e.getTimelineSet();if(j.addEventsToTimeline(x,l,!1,e,D??null),!D&&l){var U,H,K=(U=a.rootEvent)!==null&&U!==void 0?U:C(yield r.fetchRoomEvent((H=e.getRoomId())!==null&&H!==void 0?H:"",a.id));j.addEventsToTimeline([K],!0,!1,e,null)}return r.processAggregatedTimelineEvents(j.room,x),l&&!D&&e.setPaginationToken(null,c),!!D});return function(I){return R.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else{if(!s)throw new Error("Unknown room "+e.getRoomId());v=this.createMessagesRequest(e.getRoomId(),u,t.limit,c,e.getFilter()).then(R=>{if(R.state){var I=e.getState(c),C=R.state.filter(Ro).map(this.getEventMapper());I.setUnknownStateEvents(C)}var x=R.end,O=R.chunk.filter(Ro).map(this.getEventMapper()),N=e.getTimelineSet(),[D,,j]=s.partitionThreadedEvents(O);N.addEventsToTimeline(D,l,!1,e,x),this.processAggregatedTimelineEvents(s,D),this.processThreadRoots(s,D.filter(H=>H.getServerAggregatedRelation(Qt.name)),!1),j.forEach(H=>s.relations.aggregateChildEvent(H));var U=R.end===void 0||R.end===R.start;return l&&U&&e.setPaginationToken(null,c),!U}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}return v}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(t=this.peekSync)===null||t===void 0||t.stopPeeking(),this.peekSync=new gd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,r)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){var r=this.sendStateEvent(e,ee.RoomGuestAccess,{guest_access:t.allowJoin?Xb.CanJoin:Xb.Forbidden},""),i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,ee.RoomHistoryVisibility,{history_visibility:YP.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestTokenFromEndpoint(e,t){var r=this;return F(function*(){var i=Object.assign({},t);return r.http.request(ae.Post,e,void 0,i)})()}getRoomPushRule(e,t){if(this.pushRules){var r;return(r=this.pushRules[e])===null||r===void 0||(r=r.room)===null||r===void 0?void 0:r.find(i=>i.rule_id===t)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,r){var i,s=!1,o=this.getRoomPushRule(e,t);if(o!=null&&o.actions.includes(Gc.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,Lr.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,Lr.RoomSpecific,t,{actions:[Gc.DontNotify]});else if(!s){var a=ru();this.deletePushRule(e,Lr.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,Lr.RoomSpecific,t,{actions:[Gc.DontNotify]}).then(()=>{a.resolve()}).catch(l=>{a.reject(l)})}).catch(l=>{a.reject(l)}),i=a.promise}if(i)return new Promise((l,c)=>{i.then(()=>{this.getPushRules().then(u=>{this.pushRules=u,l()}).catch(u=>{c(u)})}).catch(u=>{this.getPushRules().then(f=>{this.pushRules=f,c(u)}).catch(f=>{c(u)})})})}searchMessageText(e){var t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){var t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:SH.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(r,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;var t={body:e._query,next_batch:e.next_batch},r=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,t){var r,i,s=t.search_categories.room_events;e.count=s.count,e.next_batch=s.next_batch;var o=new Set(s.highlights);e.highlights.forEach(m=>{o.add(m)}),e.highlights=Array.from(o);for(var a=this.getEventMapper(),l=(r=(i=s.results)===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0,c=0;c<l;c++){var u=OE.fromJson(s.results[c],a),f=this.getRoom(u.context.getEvent().getRoomId());if(f)for(var p of u.context.getTimeline())p.setMetadata(f.currentState,!1);e.results.push(u)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new gd(this,this.clientOpts,this.buildSyncApiOptions());return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then(()=>{this.logger.debug("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=void 0}),this.syncLeftRoomsPromise}createFilter(e){var t=Ie("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(ae.Post,t,void 0,e).then(r=>{var i=Bi.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,r){if(r){var i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}var s=Ie("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(ae.Get,s).then(o=>{var a=Bi.fromJson(e,t,o);return this.store.storeFilter(a),a})}getOrCreateFilter(e,t){var r=this;return F(function*(){var i=r.store.getFilterIdByName(e),s;if(i){try{var o=yield r.getFilter(r.credentials.userId,i,!0);if(o){var a=o.getDefinition(),l=t.getDefinition();Md(a,l)&&(s=i)}}catch(u){if(u.errcode!=="M_UNKNOWN"&&u.errcode!=="M_NOT_FOUND")throw u}s||r.store.setFilterIdByName(e,void 0)}if(s)return s;var c=yield r.createFilter(t.getDefinition());return r.store.setFilterIdByName(e,c.filterId),c.filterId})()}getOpenIdToken(){var e=Ie("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(ae.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(ae.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return F(function*(){if(e.canSupportVoip){var t=!1,r=e.turnServersExpiry-Date.now();if(r>xN)e.logger.debug("TURN creds are valid for another "+r+" ms: not fetching new ones."),t=!0;else{e.logger.debug("Fetching new TURN credentials");try{var i=yield e.turnServer();if(i.uris){e.logger.debug("Got TURN URIs: "+i.uris+" refresh in "+i.ttl+" secs");var s={urls:i.uris,username:i.username,credential:i.password};e.turnServers=[s],e.turnServersExpiry=Date.now()+i.ttl*1e3,t=!0,e.emit(Oe.TurnServers,e.turnServers)}}catch(o){e.logger.error("Failed to get TURN URIs",o),o.httpStatus===403?(e.logger.info("TURN access unavailable for this account: stopping credentials checks"),e.checkTurnServersIntervalID!==null&&globalThis.clearInterval(e.checkTurnServersIntervalID),e.checkTurnServersIntervalID=void 0,e.emit(Oe.TurnServersError,o,!0)):e.emit(Oe.TurnServersError,o,!1)}}return t}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=Ie("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(ae.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){var t=Ie("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(ae.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var t=Ie("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(ae.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return F(function*(){var t;e.clientWellKnownPromise=it.getRawClientConfig((t=e.getDomain())!==null&&t!==void 0?t:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(Oe.ClientWellKnown,e.clientWellKnown)})()}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){var e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(r=>{var[i,s]=r;return e.includes(typeof s)}).reduce((r,i)=>{var[s,o]=i;return r[s]=o,r},{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){var t=this;return F(function*(){var r=yield t.doesServerSupportUnstableFeature(HH),i=yield t.doesServerSupportUnstableFeature(BH),s=yield t.doesServerSupportUnstableFeature(VH);if(!r&&!i&&!s)throw Error("Server does not support the Mutual Rooms API");var o,a;s?(o="/uk.half-shot.msc2666/user/mutual_rooms",a={user_id:e}):(o=Ie("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var l=[],c=null;do{var u={};c!=null&&s&&(u.batch_token=c);var f=yield t.http.authedRequest(ae.Get,o,dr(dr({},a),u),void 0,{prefix:fr.Unstable});l.push(...f.joined),f.next_batch_token!==void 0?c=f.next_batch_token:c=null}while(c!=null);return l})()}getVersions(){var e=this;return F(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(ae.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(r=>{throw e.serverVersionsPromise=void 0,r});var t=yield e.serverVersionsPromise;return e.canSupport=yield Tse(t),e.serverVersionsPromise})()}isVersionSupported(e){var t=this;return F(function*(){var{versions:r}=yield t.getVersions();return r&&r.includes(e)})()}doesServerSupportUnstableFeature(e){var t=this;return F(function*(){var r=yield t.getVersions();if(!r)return!1;var i=r.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var t=this;return F(function*(){var r=yield t.getVersions();if(!r)return!1;var i=r.unstable_features,s=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i["io.element.e2ee_forced.".concat(s)]})()}doesServerSupportThread(){var e=this;return F(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:si.Stable,list:si.Stable,fwdPagination:si.Stable};try{var[t,r,i,s,o,a]=yield Promise.all([e.doesServerSupportUnstableFeature("org.matrix.msc3440"),e.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3856"),e.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3715"),e.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:H_(r,t),list:H_(s,i),fwdPagination:H_(a,o)}}catch{return{threads:si.None,list:si.None,fwdPagination:si.None}}})()}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!==null&&e!==void 0&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,r,i){var s=arguments,o=this;return F(function*(){var a,l,c=s.length>4&&s[4]!==void 0?s[4]:{dir:ht.Backward},u=i?o.getEncryptedIfNeededEventType(e,i):null,[f,p]=yield Promise.all([o.fetchRoomEvent(e,t),o.fetchRelations(e,t,r,u,c)]),m=o.getEventMapper(),v=f?m(f):void 0,g=p.chunk.map(m);if(u===ee.RoomMessageEncrypted){var S=v?g.concat(v):g;yield Promise.all(S.map(b=>o.decryptEventIfNeeded(b))),i!==null&&(g=g.filter(b=>b.getType()===i))}return v&&r===un.Replace&&(g=g.filter(b=>b.getSender()===v.getSender())),{originalEvent:v??null,events:g,nextBatch:(a=p.next_batch)!==null&&a!==void 0?a:null,prevBatch:(l=p.prev_batch)!==null&&l!==void 0?l:null}})()}generateClientSecret(){return bs(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case Ek.IS:return this.http.getUrl("/terms",void 0,Xa.V2,t);case Ek.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,t,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return r&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(t=this.idBaseUrl)!==null&&t!==void 0&&t.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=GT(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){var e;return(e=this.http.opts.refreshToken)!==null&&e!==void 0?e:null}setAccessToken(e){this.http.opts.accessToken=e,this.serverVersionsPromise=void 0}isLoggedIn(){return this.http.opts.accessToken!==void 0}makeTxnId(){return"m"+new Date().getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(ae.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,r,i,s,o,a){r&&(i.session=r);var l={auth:i,refresh_token:!0};return e!=null&&(l.username=e),t!=null&&(l.password=t),o!=null&&(l.guest_access_token=o),a!=null&&(l.inhibit_login=a),this.registerRequest(l)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,t){var r={};return t&&(r.kind=t),this.http.request(ae.Post,"/register",r,e)}refreshToken(e){var t=r=>this.http.authedRequest(ae.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return t(fr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return t(fr.V1);throw r})}loginFlows(){return this.http.request(ae.Get,"/login")}login(e,t){return this.loginRequest(dr(dr({},t),{},{type:e})).then(r=>(r.access_token&&r.user_id&&(this.http.opts.accessToken=r.access_token,this.credentials={userId:r.user_id}),r))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"sso",r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,s="/login/"+t+"/redirect";r&&(s+="/"+r);var o={redirectUrl:e,[Oae.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}loginRequest(e){var t=this;return F(function*(){return yield t.http.authedRequest(ae.Post,"/login",void 0,e)})()}logout(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!1;return r&&(t.stopClient(),t.http.abort()),t.http.authedRequest(ae.Post,"/logout")})()}deactivateAccount(e,t){var r={};return e&&(r.auth=e),t!==void 0&&(r.erase=t),this.http.authedRequest(ae.Post,"/account/deactivate",void 0,r)}requestLoginToken(e){var t=this;return F(function*(){var r={auth:e};return t.http.authedRequest(ae.Post,"/login/get_token",void 0,r,{prefix:fr.V1})})()}getFallbackAuthUrl(e,t){var r=Ie("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:t}).href}createRoom(e){var t=this;return F(function*(){var r,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(r=t.identityServer)!==null&&r!==void 0&&r.getAccessToken){var s=yield t.identityServer.getAccessToken();if(s)for(var o of i)o.id_access_token=s}return t.http.authedRequest(ae.Post,"/createRoom",void 0,e)})()}fetchRelations(e,t,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:ht.Backward},o=s;fn.hasServerSideFwdPaginationSupport===si.Experimental&&(o=QA("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(vr.RelationsRecursion)===gr.Unstable&&(o=QA("recurse","org.matrix.msc3981.recurse",o));var a=XI(o),l="/rooms/$roomId/relations/$eventId";r!==null?(l+="/$relationType",i!==null&&(l+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
33
+ Date.now: "`.concat(Date.now()));try{a=yield e.membershipLoopHandler(i.type)}catch(c){throw Error("The MembershipManager shut down because of the end condition: ".concat(c))}}e._actions.splice(0,1);var l=s??a;"replace"in l?e._actions=l.replace:"insert"in l&&e._actions.push(...l.insert)};e._actions.length>0;)yield*t()}finally{e.running=!1}e.logger.debug("Leave MembershipManager ActionScheduler loop (no more actions)")})()}initiateJoin(){var e;(e=this.wakeup)===null||e===void 0||e.call(this,{replace:[{ts:Date.now(),type:ot.SendDelayedEvent}]})}initiateLeave(){var e;(e=this.wakeup)===null||e===void 0||e.call(this,{replace:[{ts:Date.now(),type:ot.SendScheduledDelayedLeaveEvent}]})}}var EN=function(n){return n.StatusChanged="StatusChanged",n}({}),ot=function(n){return n.SendDelayedEvent="SendDelayedEvent",n.SendJoinEvent="SendJoinEvent",n.RestartDelayedEvent="RestartDelayedEvent",n.UpdateExpiry="UpdateExpiry",n.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",n.SendLeaveEvent="SendLeaveEvent",n}({});class Zb extends En{isActivated(){return this.activated}isJoined(){return this.isActivated()}join(e,t,r){if(this.scheduler.running){this.logger.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=t,this.leavePromiseDefer=void 0,this.activated=!0,this.oldStatus=this.status,this.state=Zb.defaultState,this.scheduler.startWithJoin().catch(i=>{this.logger.error("MembershipManager stopped because: ",i),r==null||r(i)}).finally(()=>{if(this.activated=!1,this.oldStatus&&this.oldStatus!==this.status&&this.emit(EN.StatusChanged,this.oldStatus,this.status),!this.scheduler.running){var i;(i=this.leavePromiseDefer)===null||i===void 0||i.resolve(!0),this.leavePromiseDefer=void 0}})}leave(e){return this.scheduler.running?(this.leavePromiseDefer||(this.leavePromiseDefer=ru(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var t;return(t=this.leavePromiseDefer)===null||t===void 0?void 0:t.resolve(!1)},e)),this.leavePromiseDefer.promise):(this.logger.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}onRTCSessionMemberUpdate(e){var t=this;return F(function*(){var r=t.client.getUserId(),i=t.client.getDeviceId();if(r&&i&&t.isJoined()&&!e.some(o=>j_(o,r,i))){var s=[ot.SendDelayedEvent,ot.SendJoinEvent];t.logger.warn("Missing own membership: force re-join"),t.scheduler.actions.find(o=>s.includes(o.type))?t.logger.error("NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",t.scheduler.actions):(t.state.hasMemberStateEvent=!1,t.scheduler.initiateJoin())}return Promise.resolve()})()}getActiveFocus(){if(this.focusActive)if(XP(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else this.logger.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}constructor(e,t,r,i,s){super(),this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,L(this,"activated",!1),L(this,"logger",void 0),L(this,"leavePromiseDefer",void 0),L(this,"oldStatus",void 0),L(this,"scheduler",void 0),L(this,"state",void 0),L(this,"deviceId",void 0),L(this,"stateKey",void 0),L(this,"fociPreferred",void 0),L(this,"focusActive",void 0),L(this,"membershipServerSideExpiryTimeoutOverride",void 0),this.logger=(s??A).getChild("[NewMembershipManager]");var[o,a]=[this.client.getUserId(),this.client.getDeviceId()];if(o===null)throw Error("Missing userId in client");if(a===null)throw Error("Missing deviceId in client");this.deviceId=a,this.stateKey=this.makeMembershipStateKey(o,a),this.state=Zb.defaultState,this.scheduler=new Koe(l=>(this.oldStatus&&(this.logger.debug("MembershipManager applied action changes. Status: ".concat(this.oldStatus," -> ").concat(this.status)),this.oldStatus!==this.status&&this.emit(EN.StatusChanged,this.oldStatus,this.status)),this.oldStatus=this.status,this.logger.debug("MembershipManager before processing action. status=".concat(this.oldStatus)),this.membershipLoopHandler(l)),this.logger)}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1}}get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get membershipEventExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:ZP}get membershipEventExpiryTimeoutHeadroom(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeoutHeadroom)!==null&&e!==void 0?e:5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryTimeout*e-this.membershipEventExpiryTimeoutHeadroom}get membershipServerSideExpiryTimeout(){var e,t,r;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(r=this.joinConfig)===null||r===void 0?void 0:r.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get maximumRateLimitRetryCount(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.maximumRateLimitRetryCount)!==null&&e!==void 0?e:10}get maximumNetworkErrorRetryCount(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.maximumNetworkErrorRetryCount)!==null&&e!==void 0?e:10}membershipLoopHandler(e){var t=this;return F(function*(){switch(e){case ot.SendDelayedEvent:return t.state.delayId?t.cancelKnownDelayIdBeforeSendFirstDelayedEvent(t.state.delayId):t.sendOrResendDelayedLeaveEvent();case ot.RestartDelayedEvent:return t.state.delayId?t.restartDelayedEvent(t.state.delayId):Ls(ot.SendDelayedEvent);case ot.SendScheduledDelayedLeaveEvent:return t.state.hasMemberStateEvent?t.state.delayId?t.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(t.state.delayId):Ls(ot.SendLeaveEvent):{replace:[]};case ot.SendJoinEvent:return t.sendJoinEvent();case ot.UpdateExpiry:return t.updateExpiryOnJoinedEvent();case ot.SendLeaveEvent:return t.state.hasMemberStateEvent?t.sendFallbackLeaveEvent():{replace:[]}}})()}sendOrResendDelayedLeaveEvent(){var e=this;return F(function*(){return yield e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},ee.GroupCallMemberPrefix,{},e.stateKey).then(t=>(e.resetRateLimitCounter(ot.SendDelayedEvent),e.state.delayId=t.delay_id,e.state.hasMemberStateEvent?Ls(ot.RestartDelayedEvent,e.membershipKeepAlivePeriod):Ls(ot.SendJoinEvent))).catch(t=>{var r=ot.SendDelayedEvent;if(e.manageMaxDelayExceededSituation(t))return Ls(r);var i=e.actionUpdateFromErrors(t,r,"sendDelayedStateEvent");if(i)return i;if(e.state.hasMemberStateEvent){if(e.isUnsupportedDelayedEndpoint(t))return{};throw Error("Could not send delayed event, even though delayed events are supported. "+t)}else return e.isUnsupportedDelayedEndpoint(t)?e.logger.info("Not using delayed event because the endpoint is not supported"):e.logger.info("Not using delayed event because: "+t),Ls(ot.SendJoinEvent)})})()}cancelKnownDelayIdBeforeSendFirstDelayedEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Cancel).then(()=>(t.state.delayId=void 0,t.resetRateLimitCounter(ot.SendDelayedEvent),s2(ot.SendDelayedEvent))).catch(r=>{var i=ot.SendDelayedEvent,s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;if(t.isNotFoundError(r))return t.state.delayId=void 0,s2(i);if(t.isUnsupportedDelayedEndpoint(r))return s2(ot.SendJoinEvent);throw Error("We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle")})})()}restartDelayedEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Restart).then(()=>(t.resetRateLimitCounter(ot.RestartDelayedEvent),Ls(ot.RestartDelayedEvent,t.membershipKeepAlivePeriod))).catch(r=>{var i=ot.RestartDelayedEvent;if(t.isNotFoundError(r))return t.state.delayId=void 0,Ls(ot.SendDelayedEvent);if(t.isUnsupportedDelayedEndpoint(r))return{};var s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;throw Error("Could not restart delayed event, even though delayed events are supported. "+r)})})()}sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){var t=this;return F(function*(){return yield t.client._unstable_updateDelayedEvent(e,Sd.Send).then(()=>(t.state.hasMemberStateEvent=!1,t.resetRateLimitCounter(ot.SendScheduledDelayedLeaveEvent),{replace:[]})).catch(r=>{var i=ot.SendLeaveEvent;if(t.isUnsupportedDelayedEndpoint(r))return{};if(t.isNotFoundError(r))return t.state.delayId=void 0,Ls(i);var s=t.actionUpdateFromErrors(r,i,"updateDelayedEvent");return s||(t.logger.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",r),Ls(i))})})()}sendJoinEvent(){var e=this;return F(function*(){return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryTimeout),e.stateKey).then(()=>(e.state.startTime=Date.now(),e.state.expireUpdateIterations=1,e.state.hasMemberStateEvent=!0,e.resetRateLimitCounter(ot.SendJoinEvent),{insert:[{ts:Date.now(),type:ot.RestartDelayedEvent},{ts:e.computeNextExpiryActionTs(e.state.expireUpdateIterations),type:ot.UpdateExpiry}]})).catch(t=>{var r=e.actionUpdateFromErrors(t,ot.SendJoinEvent,"sendStateEvent");if(r)return r;throw t})})()}updateExpiryOnJoinedEvent(){var e=this;return F(function*(){var t=e.state.expireUpdateIterations+1;return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryTimeout*t),e.stateKey).then(()=>(e.resetRateLimitCounter(ot.UpdateExpiry),e.state.expireUpdateIterations=t,{insert:[{ts:e.computeNextExpiryActionTs(t),type:ot.UpdateExpiry}]})).catch(r=>{var i=e.actionUpdateFromErrors(r,ot.UpdateExpiry,"sendStateEvent");if(i)return i;throw r})})()}sendFallbackLeaveEvent(){var e=this;return F(function*(){return yield e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,{},e.stateKey).then(()=>(e.resetRateLimitCounter(ot.SendLeaveEvent),e.state.hasMemberStateEvent=!1,{replace:[]})).catch(t=>{var r=e.actionUpdateFromErrors(t,ot.SendLeaveEvent,"sendStateEvent");if(r)return r;throw t})})()}makeMembershipStateKey(e,t){var r="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.fociPreferred)!==null&&t!==void 0?t:[]}}isNotFoundError(e){return e instanceof bn&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof bn&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var t=e.data["org.matrix.msc4140.max_delay"];return typeof t=="number"&&this.membershipServerSideExpiryTimeout>t&&(this.membershipServerSideExpiryTimeoutOverride=t),this.logger.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,t,r){var i=this.actionUpdateFromRateLimitError(e,r,t);if(i)return i;var s=this.actionUpdateFromNetworkErrorRetry(e,t);if(s)return s}actionUpdateFromRateLimitError(e,t,r){var i;if((e instanceof su||e instanceof bn)&&e.isRateLimitError()){var s=(i=this.state.rateLimitRetries.get(r))!==null&&i!==void 0?i:0;if(s<this.maximumRateLimitRetryCount){var o,a=5e3;try{var l;o=(l=e.getRetryAfterMs())!==null&&l!==void 0?l:a,this.logger.info("Rate limited by server, retrying in ".concat(o,"ms"))}catch(c){this.logger.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(a),c),o=a}return this.state.rateLimitRetries.set(r,s+1),Ls(r,o)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+t+"): "+e)}}actionUpdateFromNetworkErrorRetry(e,t){var r,i=(r=this.state.networkErrorRetries.get(t))!==null&&r!==void 0?r:0,s=this.callMemberEventRetryDelayMinimum/1e3+"s",o="("+i+"/"+this.maximumNetworkErrorRetryCount+")";if(e instanceof Error&&e.name==="AbortError")this.logger.warn("Network local timeout error while sending event, retrying in "+s+" "+o,e);else if(e instanceof Error&&e.message.includes("updating delayed event"))this.logger.warn("delayed event update timeout error, retrying in "+s+" "+o,e);else if(e instanceof Jd)this.logger.warn("Network connection error while sending event, retrying in "+s+" "+o,e);else if((e instanceof su||e instanceof bn)&&typeof e.httpStatus=="number"&&e.httpStatus>=500&&e.httpStatus<600)this.logger.warn("Server error while sending event, retrying in "+s+" "+o,e);else return;if(i<this.maximumNetworkErrorRetryCount)return this.state.networkErrorRetries.set(t,i+1),Ls(t,this.callMemberEventRetryDelayMinimum);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof jc}resetRateLimitCounter(e){this.state.rateLimitRetries.set(e,0),this.state.networkErrorRetries.set(e,0)}get status(){var e=this.scheduler.actions;if(e.length===1){var{type:t}=e[0];switch(t){case ot.SendDelayedEvent:case ot.SendJoinEvent:return Cc.Connecting;case ot.UpdateExpiry:return Cc.Connected;case ot.SendScheduledDelayedLeaveEvent:case ot.SendLeaveEvent:return Cc.Disconnecting}}else if(e.length===2){var r=e.map(s=>s.type);if((r.includes(ot.RestartDelayedEvent)||r.includes(ot.SendDelayedEvent)&&this.state.hasMemberStateEvent)&&r.includes(ot.UpdateExpiry))return Cc.Connected}else if(e.length===3){var i=e.map(s=>s.type);if(i.filter(s=>s===ot.RestartDelayedEvent).length===2&&i.includes(ot.UpdateExpiry))return Cc.Connected}return this.scheduler.running?(this.logger.error("MembershipManager has an unknown state. Actions: ",e),Cc.Unknown):Cc.Disconnected}}function Ls(n,e){return{insert:[{ts:Date.now()+(e??0),type:n}]}}function s2(n,e){return{replace:[{ts:Date.now()+0,type:n}]}}var Uc=function(n){return n.ReceivedKeys="received_keys",n}({});class kH extends En{constructor(e,t,r,i){super(),this.room=e,this.client=t,this.statistics=r,L(this,"logger",void 0),this.logger=(i??A).getChild("[RoomKeyTransport]")}start(){this.room.on(ke.Timeline,e=>void this.consumeCallEncryptionEvent(e))}stop(){this.room.off(ke.Timeline,e=>void this.consumeCallEncryptionEvent(e))}consumeCallEncryptionEvent(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;if(yield r.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){i?r.logger.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason)):(r.logger.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason," will retry once only")),setTimeout(()=>void r.consumeCallEncryptionEvent(e,!0),1e3));return}else i&&r.logger.info("Decryption succeeded for event ".concat(e.getId()," after retry"));if(e.getType()!==ee.CallEncryptionKeysPrefix)return Promise.resolve();if(!r.room)return r.logger.error("Got room state event for unknown room ".concat(e.getRoomId(),"!")),Promise.resolve();r.onEncryptionEvent(e)})()}sendKey(e,t,r){var i=this;return F(function*(){var s={keys:[{index:t,key:e}],device_id:i.client.getDeviceId(),call_id:"",sent_ts:Date.now()};try{yield i.client.sendEvent(i.room.roomId,ee.CallEncryptionKeysPrefix,s)}catch(a){i.logger.error("Failed to send call encryption keys",a);var o=a;throw o.event&&i.client.cancelPendingEvent(o.event),a}})()}onEncryptionEvent(e){var t=e.getSender(),r=e.getContent(),i=r.device_id,s=r.call_id;if(!t){this.logger.warn("Received m.call.encryption_keys with no userId: callId=".concat(s));return}if(s!==""){this.logger.warn("Received m.call.encryption_keys with unsupported callId: userId=".concat(t,", deviceId=").concat(i,", callId=").concat(s));return}if(!Array.isArray(r.keys)){this.logger.warn("Received m.call.encryption_keys where keys wasn't an array: callId=".concat(s));return}if(t===this.client.getUserId()&&i===this.client.getDeviceId()){this.logger.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;var o=Date.now()-(typeof r.sent_ts=="number"?r.sent_ts:e.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=o;for(var a of r.keys){if(!a){this.logger.info("Ignoring false-y key in keys event");continue}var l=a.key,c=a.index;!l||c===void 0||c===null||s===void 0||s===null||typeof i!="string"||typeof s!="string"||typeof l!="string"||typeof c!="number"?this.logger.warn("Malformed call encryption_key: userId=".concat(t,", deviceId=").concat(i,", encryptionKeyIndex=").concat(c," callId=").concat(s)):(this.logger.debug("onCallEncryption userId=".concat(t,":").concat(i," encryptionKeyIndex=").concat(c," age=").concat(o,"ms")),this.emit(Uc.ReceivedKeys,t,i,l,c,e.getTs()))}}}class Goe extends En{constructor(e,t,r,i,s,o){super(),this.userId=e,this.deviceId=t,this.roomId=r,this.client=i,this.statistics=s,L(this,"logger",void 0),L(this,"onToDeviceEvent",a=>{if(a.getType()===ee.CallEncryptionKeysPrefix){var l=this.getValidEventContent(a);l&&a.getSender()&&this.receiveCallKeyEvent(a.getSender(),l)}}),this.logger=(o??A).getChild("[ToDeviceKeyTransport]")}start(){this.client.on(Oe.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.off(Oe.ToDeviceEvent,this.onToDeviceEvent)}sendKey(e,t,r){var i=this;return F(function*(){var s={keys:{index:t,key:e},room_id:i.roomId,member:{claimed_device_id:i.deviceId},session:{call_id:"",application:"m.call",scope:"m.room"}},o=r.filter(a=>a.sender==null||a.deviceId==null?(i.logger.warn("Malformed call member: ".concat(a.sender,"|").concat(a.deviceId)),!1):!(a.sender==i.userId&&a.deviceId==i.deviceId)).map(a=>({userId:a.sender,deviceId:a.deviceId}));o.length>0?(yield i.client.encryptAndSendToDevice(ee.CallEncryptionKeysPrefix,o,s),i.statistics.counters.roomEventEncryptionKeysSent+=1):i.logger.warn("No targets found for sending key")})()}receiveCallKeyEvent(e,t){this.statistics.counters.roomEventEncryptionKeysReceived+=1;var r=Date.now(),i=r-(typeof t.sent_ts=="number"?t.sent_ts:r);this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=i,this.emit(Uc.ReceivedKeys,e,t.member.claimed_device_id,t.keys.key,t.keys.index,r)}getValidEventContent(e){var t=e.getContent(),r=t.room_id;if(!r){this.logger.warn("Malformed Event: invalid call encryption keys event, no roomId");return}if(r!==this.roomId){this.logger.warn("Malformed Event: Mismatch roomId");return}if(!t.keys||!t.keys.key||typeof t.keys.index!="number"){this.logger.warn("Malformed Event: Missing keys field");return}if(!t.member||!t.member.claimed_device_id){this.logger.warn("Malformed Event: Missing claimed_device_id");return}return t}}var xv=function(n){return n.EnabledTransportsChanged="enabled_transports_changed",n}({});class Lk extends En{constructor(e,t,r,i,s,o){var a;super(),a=this,L(this,"logger",void 0),L(this,"roomKeyTransport",void 0),L(this,"toDeviceTransport",void 0),L(this,"_enabled",{toDevice:!0,room:!1}),this.logger=(o??A).getChild("[RoomAndToDeviceTransport]"),this.roomKeyTransport=new kH(r,i,s,this.logger),this.toDeviceTransport=new Goe(e,t,r.roomId,i,s,this.logger),this.roomKeyTransport.on(Uc.ReceivedKeys,function(){a._enabled.room||(a.logger.debug("Received room key, enabling room key transport, disabling toDevice transport"),a.setEnabled({toDevice:!1,room:!0}));for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];a.emit(Uc.ReceivedKeys,...c)}),this.toDeviceTransport.on(Uc.ReceivedKeys,function(){if(a._enabled.toDevice){for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];a.emit(Uc.ReceivedKeys,...c)}else a.logger.debug("To Device transport is disabled, ignoring received keys")})}setEnabled(e){(this.enabled.toDevice!==e.toDevice||this.enabled.room!==e.room)&&(this._enabled=e,this.emit(xv.EnabledTransportsChanged,e))}get enabled(){return this._enabled}start(){this.roomKeyTransport.start(),this.toDeviceTransport.start()}stop(){this.roomKeyTransport.stop(),this.toDeviceTransport.stop()}sendKey(e,t,r){var i=this;return F(function*(){i.logger.debug("Sending key with index ".concat(t," to call members (count=").concat(r.length,") via:")+(i._enabled.room?"room transport":"")+(i._enabled.room&&i._enabled.toDevice?"and":"")+(i._enabled.toDevice?"to device transport":"")),i._enabled.room&&(yield i.roomKeyTransport.sendKey(e,t,r)),i._enabled.toDevice&&(yield i.toDeviceTransport.sendKey(e,t,r))})()}}class Woe{get updateEncryptionKeyThrottle(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.useKeyDelay)!==null&&e!==void 0?e:5e3}constructor(e,t,r,i,s,o,a){var l=this;this.userId=e,this.deviceId=t,this.getMemberships=r,this.transport=i,this.statistics=s,this.onEncryptionKeysChanged=o,L(this,"manageMediaKeys",!1),L(this,"keysEventUpdateTimeout",void 0),L(this,"makeNewKeyTimeout",void 0),L(this,"setNewKeyTimeouts",new Set),L(this,"encryptionKeys",new Map),L(this,"lastEncryptionKeyUpdateRequest",void 0),L(this,"lastMembershipFingerprints",void 0),L(this,"latestGeneratedKeyIndex",-1),L(this,"joinConfig",void 0),L(this,"logger",void 0),L(this,"joined",!1),L(this,"sendEncryptionKeysEvent",function(){var c=F(function*(u){if(l.keysEventUpdateTimeout!==void 0&&(clearTimeout(l.keysEventUpdateTimeout),l.keysEventUpdateTimeout=void 0),l.lastEncryptionKeyUpdateRequest=Date.now(),!!l.joined){var f=l.getKeysForParticipant(l.userId,l.deviceId);if(!f){l.logger.warn("Tried to send encryption keys event but no keys found!");return}if(typeof u!="number"&&l.latestGeneratedKeyIndex===-1){l.logger.warn("Tried to send encryption keys event but no current key index found!");return}var p=u??l.latestGeneratedKeyIndex;l.logger.info("Try sending encryption keys event. keyIndexToSend=".concat(p," (method parameter: ").concat(u,")"));var m=f[p];try{l.statistics.counters.roomEventEncryptionKeysSent+=1,yield l.transport.sendKey(mH(m),p,l.getMemberships()),l.logger.debug("sendEncryptionKeysEvent participantId=".concat(l.userId,":").concat(l.deviceId," numKeys=").concat(f.length," currentKeyIndex=").concat(l.latestGeneratedKeyIndex," keyIndexToSend=").concat(p),l.encryptionKeys)}catch(g){if(l.keysEventUpdateTimeout===void 0){var v=FP(g,5e3);l.logger.warn("Failed to send m.call.encryption_key, retrying in ".concat(v),g),l.keysEventUpdateTimeout=setTimeout(()=>void l.sendEncryptionKeysEvent(),v)}else l.logger.info("Not scheduling key resend as another re-send is already pending")}}});return function(u){return c.apply(this,arguments)}}()),L(this,"onTransportChanged",c=>{this.requestSendCurrentKey()}),L(this,"onNewKeyReceived",(c,u,f,p,m)=>{this.logger.debug("Received key over key transport ".concat(c,":").concat(u," at index ").concat(p)),this.setEncryptionKey(c,u,p,f,m)}),L(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,this.logger.info("Making new sender key for key rotation");var c=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(c)}}),this.logger=(a??A).getChild("[EncryptionManager]")}getEncryptionKeys(){return this.encryptionKeys}join(e){var t,r,i;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=(t=(r=this.joinConfig)===null||r===void 0?void 0:r.manageMediaKeys)!==null&&t!==void 0?t:this.manageMediaKeys,this.transport.on(Uc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof Lk&&this.transport.on(xv.EnabledTransportsChanged,this.onTransportChanged),this.transport.start(),(i=this.joinConfig)!==null&&i!==void 0&&i.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){this.encryptionKeys.set(U_(this.userId,this.deviceId),[]),this.transport.off(Uc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof Lk&&this.transport.off(xv.EnabledTransportsChanged,this.onTransportChanged),this.transport.stop(),this.makeNewKeyTimeout!==void 0&&(clearTimeout(this.makeNewKeyTimeout),this.makeNewKeyTimeout=void 0);for(var e of this.setNewKeyTimeouts)clearTimeout(e);this.setNewKeyTimeouts.clear(),this.manageMediaKeys=!1,this.joined=!1}onMembershipsUpdate(e){if(this.manageMediaKeys&&this.joined){var t=new Set(e.filter(c=>!j_(c,this.userId,this.deviceId)).map(o2)),r=new Set(this.getMemberships().filter(c=>!j_(c,this.userId,this.deviceId)).map(o2)),i=Array.from(t).some(c=>!r.has(c)),s=Array.from(r).some(c=>!t.has(c)),o=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),i)this.makeNewKeyTimeout||(this.logger.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay));else if(s)this.logger.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(o){var a=this.lastMembershipFingerprints,l=Array.from(o).some(c=>!a.has(c))||Array.from(a).some(c=>!o.has(c));l&&(this.logger.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}}makeNewSenderKey(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=gH(16),r=this.getNewEncryptionKeyIndex();return this.logger.info("Generated new key at index "+r),this.setEncryptionKey(this.userId,this.deviceId,r,t,Date.now(),e),r}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){this.logger.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}getKeysForParticipant(e,t){var r;return(r=this.encryptionKeys.get(U_(e,t)))===null||r===void 0?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!j_(e,this.userId,this.deviceId)).map(e=>"".concat(o2(e),":").concat(e.createdTs())))}getNewEncryptionKeyIndex(){return this.latestGeneratedKeyIndex===-1?0:(this.latestGeneratedKeyIndex+1)%256}setEncryptionKey(e,t,r,i,s){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1;this.logger.debug("Setting encryption key for ".concat(e,":").concat(t," at index ").concat(r));var a=Oh(i),l=U_(e,t);this.encryptionKeys.has(l)||this.encryptionKeys.set(l,[]);var c=this.encryptionKeys.get(l),u=c[r];if(u){if(u.timestamp>s){this.logger.info("Ignoring new key at index ".concat(r," for ").concat(l," as it is older than existing known key"));return}if(zoe(u.key,a)){u.timestamp=s;return}}if(e===this.userId&&t===this.deviceId&&(this.latestGeneratedKeyIndex=r),c[r]={key:a,timestamp:s},o){var f=setTimeout(()=>{this.setNewKeyTimeouts.delete(f),this.logger.info("Delayed-emitting key changed event for ".concat(l," index ").concat(r)),this.onEncryptionKeysChanged(a,r,l)},this.useKeyDelay);this.setNewKeyTimeouts.add(f)}else this.onEncryptionKeysChanged(a,r,l)}}var U_=(n,e)=>"".concat(n,":").concat(e);function zoe(n,e){return n===e?!0:!!n&&!!e&&n.length===e.length&&n.every((t,r)=>t===e[r])}var o2=n=>U_(n.sender,n.deviceId);class Yoe{get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get membershipExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:ZP}get membershipServerSideExpiryTimeout(){var e,t,r;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(r=this.joinConfig)===null||r===void 0?void 0:r.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get callMemberEventRetryJitter(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryJitter)!==null&&e!==void 0?e:2e3}constructor(e,t,r,i){var s=this;this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,L(this,"relativeExpiry",void 0),L(this,"memberEventTimeout",void 0),L(this,"ownFociPreferred",void 0),L(this,"ownFocusActive",void 0),L(this,"updateCallMembershipRunning",!1),L(this,"needCallMembershipUpdate",!1),L(this,"membershipServerSideExpiryTimeoutOverride",void 0),L(this,"disconnectDelayId",void 0),L(this,"triggerCallMembershipEventUpdate",F(function*(){if(s.updateCallMembershipRunning){s.needCallMembershipUpdate=!0;return}s.updateCallMembershipRunning=!0;try{do s.needCallMembershipUpdate=!1,yield s.updateCallMembershipEvent();while(s.needCallMembershipUpdate)}finally{s.updateCallMembershipRunning=!1}})),L(this,"delayDisconnection",F(function*(){try{var o=s.disconnectDelayId;yield qf(()=>s.client._unstable_updateDelayedEvent(o,Sd.Restart)),s.scheduleDelayDisconnection()}catch(a){A.error("Failed to delay our disconnection event:",a)}}))}off(e,t){return A.error("off is not implemented on LegacyMembershipManager"),this}on(e,t){return A.error("on is not implemented on LegacyMembershipManager"),this}isJoined(){return this.relativeExpiry!==void 0}isActivated(){return this.isJoined()}get status(){return Cc.Unknown}join(e,t){this.ownFocusActive=t,this.ownFociPreferred=e,this.relativeExpiry=this.membershipExpiryTimeout,this.triggerCallMembershipEventUpdate()}leave(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(t.relativeExpiry=void 0,t.ownFocusActive=void 0,t.memberEventTimeout&&(clearTimeout(t.memberEventTimeout),t.memberEventTimeout=void 0),r){var i=yield Promise.race([t.triggerCallMembershipEventUpdate(),nu(r,"timeout")]);return i!=="timeout"}else return yield t.triggerCallMembershipEventUpdate(),!0})()}onRTCSessionMemberUpdate(e){var t=this;return F(function*(){var r=i=>i.sender===t.client.getUserId()&&i.deviceId===t.client.getDeviceId();if(t.isJoined()&&!e.some(r))return A.warn("Missing own membership: force re-join"),t.triggerCallMembershipEventUpdate()})()}getActiveFocus(){if(this.ownFocusActive)if(XP(this.ownFocusActive)){if(this.ownFocusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else A.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.ownFociPreferred)!==null&&t!==void 0?t:[]}}updateCallMembershipEvent(){var e=this;return F(function*(){e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(Le.FORWARDS);if(!t)throw new Error("Couldn't get room state for room "+e.room.roomId);var r=e.client.getUserId(),i=e.client.getDeviceId();if(!r||!i)throw new Error("User ID or device ID was null!");var s={};s=e.makeNewMembership(i);try{if(e.isJoined()){var o=e.makeMembershipStateKey(r,i),a=function(){var p=F(function*(){try{var m=yield qf(()=>e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},ee.GroupCallMemberPrefix,{},o));e.disconnectDelayId=m.delay_id}catch(g){if(g instanceof bn&&g.errcode==="M_UNKNOWN"&&g.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var v=g.data["org.matrix.msc4140.max_delay"];if(typeof v=="number"&&e.membershipServerSideExpiryTimeout>v)return e.membershipServerSideExpiryTimeoutOverride=v,a()}A.error("Failed to prepare delayed disconnection event:",g)}});return function(){return p.apply(this,arguments)}}();if(yield a(),yield qf(()=>e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,s,o)),e.disconnectDelayId!==void 0)try{var l=e.disconnectDelayId;yield qf(()=>e.client._unstable_updateDelayedEvent(l,Sd.Restart))}catch(p){p instanceof bn&&p.errcode==="M_NOT_FOUND"&&(A.warn("Failed to update delayed disconnection event, prepare it again:",p),e.disconnectDelayId=void 0,yield a())}e.disconnectDelayId!==void 0&&e.scheduleDelayDisconnection()}else{var c=!1;if(e.disconnectDelayId!==void 0){try{var u=e.disconnectDelayId;yield qf(()=>e.client._unstable_updateDelayedEvent(u,Sd.Send)),c=!0}catch(p){A.error("Failed to send our delayed disconnection event:",p)}e.disconnectDelayId=void 0}c||(yield qf(()=>e.client.sendStateEvent(e.room.roomId,ee.GroupCallMemberPrefix,{},e.makeMembershipStateKey(r,i))))}A.info("Sent updated call member event.")}catch(p){var f=e.callMemberEventRetryDelayMinimum+Math.random()*e.callMemberEventRetryJitter;A.warn("Failed to send call member event (retrying in ".concat(f,"): ").concat(p)),yield nu(f),yield e.triggerCallMembershipEventUpdate()}})()}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(()=>void this.delayDisconnection(),this.membershipKeepAlivePeriod)}makeMembershipStateKey(e,t){var r="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}}function qf(n){return Ok.apply(this,arguments)}function Ok(){return Ok=F(function*(n){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;;)try{return yield n()}catch(s){if(e>0&&s instanceof su&&s.isRateLimitError()){e--;var t=void 0,r=5e3;try{var i;t=(i=s.getRetryAfterMs())!==null&&i!==void 0?i:r,A.info("Rate limited by server, retrying in ".concat(t,"ms"))}catch(o){A.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(r),o),t=r}yield nu(t)}else throw s}}),Ok.apply(this,arguments)}var ar=function(n){return n.MembershipsChanged="memberships_changed",n.JoinStateChanged="join_state_changed",n.EncryptionKeyChanged="encryption_key_changed",n.MembershipManagerError="membership_manager_error",n}({});class Nh extends En{get callId(){return this._callId}static callMembershipsForRoom(e){var t=A.getChild("[MatrixRTCSession ".concat(e.roomId,"]")),r=e.getLiveTimeline().getState(Le.FORWARDS);if(!r)throw t.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var i=r.getStateEvents(ee.GroupCallMemberPrefix),s=[];for(var o of i){var a=o.getContent(),l=Object.keys(a).length;if(l!==0){var c=[];if(l>1&&"focus_active"in a?c.push(a):l===1&&"memberships"in a&&t.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),c.length!==0)for(var u of c)try{var f,p=new SN(o,u);if(p.callId!==""||p.scope!=="m.room"){t.info("Ignoring user-scoped call");continue}if(p.isExpired()){t.info("Ignoring expired device membership ".concat(p.sender,"/").concat(p.deviceId));continue}if(!e.hasMembershipState((f=p.sender)!==null&&f!==void 0?f:"",qe.Join)){t.info("Ignoring membership of user ".concat(p.sender," who is not in the room."));continue}s.push(p)}catch(m){t.warn("Couldn't construct call membership: ",m)}}}return s.sort((m,v)=>m.createdTs()-v.createdTs()),s.length>1&&t.debug("Call memberships in room ".concat(e.roomId,", in order: "),s.map(m=>[m.createdTs(),m.sender])),s}static roomSessionForRoom(e,t){var r=Nh.callMembershipsForRoom(t);return new Nh(e,t,r)}get room(){return this.roomSubset}constructor(e,t,r){var i;super(),this.client=e,this.roomSubset=t,this.memberships=r,L(this,"membershipManager",void 0),L(this,"encryptionManager",void 0),L(this,"_callId",void 0),L(this,"logger",void 0),L(this,"expiryTimeout",void 0),L(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),L(this,"reEmitter",new Mp(this)),L(this,"onRoomMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"onRTCSessionMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"recalculateSessionMembers",()=>{var o,a,l,c=this.memberships;this.memberships=Nh.callMembershipsForRoom(this.room),this._callId=(o=this._callId)!==null&&o!==void 0?o:(a=this.memberships[0])===null||a===void 0?void 0:a.callId;var u=c.length!=this.memberships.length||c.some((p,m)=>!SN.equal(p,this.memberships[m]));if(u){var f;this.logger.info("Memberships for call in room ".concat(this.roomSubset.roomId," have changed: emitting")),aie(this.logger,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit(ar.MembershipsChanged,c,this.memberships)}),(f=this.membershipManager)===null||f===void 0||f.onRTCSessionMemberUpdate(this.memberships)}(l=this.encryptionManager)===null||l===void 0||l.onMembershipsUpdate(c),this.setExpiryTimer()}),this.logger=A.getChild("[MatrixRTCSession ".concat(t.roomId,"]")),this._callId=(i=r[0])===null||i===void 0?void 0:i.callId;var s=this.roomSubset.getLiveTimeline().getState(Le.FORWARDS);s==null||s.on(ut.Members,this.onRoomMemberUpdate),this.setExpiryTimer()}isJoined(){var e,t;return(e=(t=this.membershipManager)===null||t===void 0?void 0:t.isJoined())!==null&&e!==void 0?e:!1}stop(){var e=this;return F(function*(){var t;yield(t=e.membershipManager)===null||t===void 0?void 0:t.leave(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0);var r=e.roomSubset.getLiveTimeline().getState(Le.FORWARDS);r==null||r.off(ut.Members,e.onRoomMemberUpdate)})()}joinRoomSession(e,t,r){if(this.isJoined()){this.logger.info("Already joined to session in room ".concat(this.roomSubset.roomId,": ignoring join call"));return}else{var i;(i=r==null?void 0:r.useNewMembershipManager)!==null&&i!==void 0&&i?this.membershipManager=new Zb(r,this.roomSubset,this.client,()=>this.getOldestMembership(),this.logger):this.membershipManager=new Yoe(r,this.roomSubset,this.client,()=>this.getOldestMembership());var s;r!=null&&r.useExperimentalToDeviceTransport?(this.logger.info("Using to-device with room fallback transport for encryption keys"),s=new Lk(this.client.getUserId(),this.client.getDeviceId(),this.roomSubset,this.client,this.statistics,this.logger),this.reEmitter.reEmit(s,[xv.EnabledTransportsChanged])):s=new kH(this.roomSubset,this.client,this.statistics),this.encryptionManager=new Woe(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(o,a,l)=>{this.emit(ar.EncryptionKeyChanged,o,a,l)},this.logger)}this.membershipManager.join(e,t,o=>{this.logger.error("MembershipManager encountered an unrecoverable error: ",o),this.emit(ar.MembershipManagerError,o),this.emit(ar.JoinStateChanged,this.isJoined())}),this.encryptionManager.join(r),this.emit(ar.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!t.isJoined())return t.logger.info("Not joined to session in room ".concat(t.roomSubset.roomId,": ignoring leave call")),!1;t.logger.info("Leaving call session in room ".concat(t.roomSubset.roomId)),t.encryptionManager.leave();var i=t.membershipManager.leave(r);return t.emit(ar.JoinStateChanged,!1),yield i})()}getActiveFocus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getFocusInUse(){var e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){var e;(e=this.encryptionManager)===null||e===void 0||e.getEncryptionKeys().forEach((t,r)=>{t.forEach((i,s)=>{this.emit(ar.EncryptionKeyChanged,i.key,s,r)})})}getEncryptionKeys(){var e,t,r=(e=(t=this.encryptionManager)===null||t===void 0?void 0:t.getEncryptionKeys())!==null&&e!==void 0?e:new Map;return Array.from(r.entries()).map(i=>{var[s,o]=i;return[s,o.map(a=>a.key)]}).values()}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var t of this.memberships){var r=t.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}}var a2=A.getChild("[MatrixRTCSessionManager]"),Qb=function(n){return n.SessionStarted="session_started",n.SessionEnded="session_ended",n}({});class Joe extends En{constructor(e){super(),this.client=e,L(this,"roomSessions",new Map),L(this,"onRoom",t=>{this.refreshRoom(t)}),L(this,"onRoomState",(t,r)=>{var i=this.client.getRoom(t.getRoomId());if(!i){a2.error("Got room state event for unknown room ".concat(t.getRoomId(),"!"));return}t.getType()==ee.GroupCallMemberPrefix&&this.refreshRoom(i)})}start(){for(var e of(t=this.client.getRooms())!==null&&t!==void 0?t:[]){var t,r=Nh.roomSessionForRoom(this.client,e);r.memberships.length>0&&this.roomSessions.set(e.roomId,r)}this.client.on(Oe.Room,this.onRoom),this.client.on(ut.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Oe.Room,this.onRoom),this.client.off(ut.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Nh.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}refreshRoom(e){var t=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!t;r.onRTCSessionMemberUpdate();var s=r.memberships.length>0;i&&!s?(a2.trace("Session ended for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(Qb.SessionEnded,e.roomId,this.roomSessions.get(e.roomId))):!i&&s&&(a2.trace("Session started for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(Qb.SessionStarted,e.roomId,this.roomSessions.get(e.roomId)))}}function l2(n){return e=>{var t,r;return((t=e.content)===null||t===void 0||(t=t["m.relates_to"])===null||t===void 0?void 0:t.event_id)!==n||((r=e.content)===null||r===void 0||(r=r["m.relates_to"])===null||r===void 0?void 0:r.rel_type)===Qt.name}}function xH(n){return Mk.apply(this,arguments)}function Mk(){return Mk=F(function*(n){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(n),t=yield globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(t)}),Mk.apply(this,arguments)}class Mg extends Error{}Mg.prototype.name="InvalidTokenError";function Xoe(n){return decodeURIComponent(atob(n).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function Zoe(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Xoe(e)}catch{return atob(e)}}function PH(n,e){if(typeof n!="string")throw new Mg("Invalid token specified: must be a string");e||(e={});const t=e.header===!0?0:1,r=n.split(".")[t];if(typeof r!="string")throw new Mg(`Invalid token specified: missing part #${t+1}`);let i;try{i=Zoe(r)}catch(s){throw new Mg(`Invalid token specified: invalid base64 for part #${t+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new Mg(`Invalid token specified: invalid json for part #${t+1} (${s.message})`)}}var Qoe={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},ca,ua,Pv=(n=>(n[n.NONE=0]="NONE",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(Pv||{});(n=>{function e(){ca=3,ua=Qoe}n.reset=e;function t(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");ca=i}n.setLevel=t;function r(i){ua=i}n.setLogger=r})(Pv||(Pv={}));var Qn=class sa{constructor(e){this._name=e}debug(...e){ca>=4&&ua.debug(sa._format(this._name,this._method),...e)}info(...e){ca>=3&&ua.info(sa._format(this._name,this._method),...e)}warn(...e){ca>=2&&ua.warn(sa._format(this._name,this._method),...e)}error(...e){ca>=1&&ua.error(sa._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const r=new sa(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){ca>=4&&ua.debug(sa._format(e),...t)}static info(e,...t){ca>=3&&ua.info(sa._format(e),...t)}static warn(e,...t){ca>=2&&ua.warn(sa._format(e),...t)}static error(e,...t){ca>=1&&ua.error(sa._format(e),...t)}};Pv.reset();var eS=class{static decode(n){try{return PH(n)}catch(e){throw Qn.error("JwtUtils.decode",e),e}}static async generateSignedJwt(n,e,t){const r=Do.encodeBase64Url(new TextEncoder().encode(JSON.stringify(n))),i=Do.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),s=`${r}.${i}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(s)),a=Do.encodeBase64Url(new Uint8Array(o));return`${s}.${a}`}},eae="10000000-1000-4000-8000-100000000000",Ak=n=>btoa([...new Uint8Array(n)].map(e=>String.fromCharCode(e)).join("")),LH=class oa{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return eae.replace(/[018]/g,t=>(+t^oa._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return oa.generateUUIDv4()+oa.generateUUIDv4()+oa.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return Ak(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Qn.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const i=new TextEncoder().encode([e,t].join(":"));return Ak(i)}static async hash(e,t){const r=new TextEncoder().encode(t),i=await crypto.subtle.digest(e,r);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await oa.hash("SHA-256",JSON.stringify(t));return oa.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:r,keyPair:i,nonce:s}){let o,a;const l={jti:window.crypto.randomUUID(),htm:r??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(o=await oa.hash("SHA-256",t),a=oa.encodeBase64Url(o),l.ath=a),s&&(l.nonce=s);try{const c=await crypto.subtle.exportKey("jwk",i.publicKey),u={alg:"ES256",typ:"dpop+jwt",jwk:{crv:c.crv,kty:c.kty,x:c.x,y:c.y}};return await eS.generateSignedJwt(u,l,i.privateKey)}catch(c){throw c instanceof TypeError?new Error(`Error exporting dpop public key: ${c.message}`):c}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await oa.customCalculateJwkThumbprint(t)}catch(t){throw t instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${t.message}`):t}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};LH.encodeBase64Url=n=>Ak(n).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Do=LH,tae=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Qn(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},tS=class F_ extends tae{constructor(){super(...arguments),this._logger=new Qn(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-F_.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=F_.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=F_.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=r;const i=Math.min(e,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},wN=class{static readParams(n,e="query"){if(!n)throw new TypeError("Invalid URL");const r=new URL(n,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(r.slice(1))}},Nk=";",lp=class extends Error{constructor(n,e){var t,r,i;if(super(n.error_description||n.error||""),this.form=e,this.name="ErrorResponse",!n.error)throw Qn.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=n.error,this.error_description=(t=n.error_description)!=null?t:null,this.error_uri=(r=n.error_uri)!=null?r:null,this.state=n.userState,this.session_state=(i=n.session_state)!=null?i:null,this.url_state=n.url_state}},nae=class extends Error{constructor(n){super(n),this.name="ErrorTimeout"}},rae=class{constructor(){this._logger=new Qn("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(n){return this._logger.create(`getItem('${n}')`),this._data[n]}setItem(n,e){this._logger.create(`setItem('${n}')`),this._data[n]=e}removeItem(n){this._logger.create(`removeItem('${n}')`),delete this._data[n]}get length(){return Object.getOwnPropertyNames(this._data).length}key(n){return Object.getOwnPropertyNames(this._data)[n]}},Dk=class extends Error{constructor(n,e){super(e),this.name="ErrorDPoPNonce",this.nonce=n}},tL=class{constructor(n=[],e=null,t={}){this._jwtHandler=e,this._extraHeaders=t,this._logger=new Qn("JsonService"),this._contentTypes=[],this._contentTypes.push(...n,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(n,e={}){const{timeoutInSeconds:t,...r}=e;if(!t)return await fetch(n,r);const i=new AbortController,s=setTimeout(()=>i.abort(),t*1e3);try{return await fetch(n,{...e,signal:i.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new nae("Network timed out"):o}finally{clearTimeout(s)}}async getJson(n,{token:e,credentials:t,timeoutInSeconds:r}={}){const i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};e&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+e),this.appendExtraHeaders(s);let o;try{i.debug("url:",n),o=await this.fetchWithTimeout(n,{method:"GET",headers:s,timeoutInSeconds:r,credentials:t})}catch(c){throw i.error("Network Error"),c}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(c=>a.startsWith(c))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${n}`)),o.ok&&this._jwtHandler&&(a!=null&&a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let l;try{l=await o.json()}catch(c){throw i.error("Error parsing JSON response",c),o.ok?c:new Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error("Error from server:",l),l.error?new lp(l):new Error(`${o.statusText} (${o.status}): ${JSON.stringify(l)}`);return l}async postForm(n,{body:e,basicAuth:t,timeoutInSeconds:r,initCredentials:i,extraHeaders:s}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...s};t!==void 0&&(a.Authorization="Basic "+t),this.appendExtraHeaders(a);let l;try{o.debug("url:",n),l=await this.fetchWithTimeout(n,{method:"POST",headers:a,body:e,timeoutInSeconds:r,credentials:i})}catch(p){throw o.error("Network error"),p}o.debug("HTTP response received, status",l.status);const c=l.headers.get("Content-Type");if(c&&!this._contentTypes.find(p=>c.startsWith(p)))throw new Error(`Invalid response Content-Type: ${c??"undefined"}, from URL: ${n}`);const u=await l.text();let f={};if(u)try{f=JSON.parse(u)}catch(p){throw o.error("Error parsing JSON response",p),l.ok?p:new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(o.error("Error from server:",f),l.headers.has("dpop-nonce")){const p=l.headers.get("dpop-nonce");throw new Dk(p,`${JSON.stringify(f)}`)}throw f.error?new lp(f,e):new Error(`${l.statusText} (${l.status}): ${JSON.stringify(f)}`)}return f}appendExtraHeaders(n){const e=this._logger.create("appendExtraHeaders"),t=Object.keys(this._extraHeaders),r=["authorization","accept","content-type"];t.length!==0&&t.forEach(i=>{if(r.includes(i.toLocaleLowerCase())){e.warn("Protected header could not be overridden",i,r);return}const s=typeof this._extraHeaders[i]=="function"?this._extraHeaders[i]():this._extraHeaders[i];s&&s!==""&&(n[i]=s)})}},OH=class{constructor(n){this._settings=n,this._logger=new Qn("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new tL(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const n=this._logger.create("getMetadata");if(this._metadata)return n.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw n.throw(new Error("No authority or metadataUrl configured on settings")),null;n.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return n.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,e),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(n=!0){return this._getMetadataProperty("token_endpoint",n)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(n=!0){return this._getMetadataProperty("revocation_endpoint",n)}getKeysEndpoint(n=!0){return this._getMetadataProperty("jwks_uri",n)}async _getMetadataProperty(n,e=!1){const t=this._logger.create(`_getMetadataProperty('${n}')`),r=await this.getMetadata();if(t.debug("resolved"),r[n]===void 0){if(e===!0){t.warn("Metadata does not contain optional property");return}t.throw(new Error("Metadata does not contain property "+n))}return r[n]}async getSigningKeys(){const n=this._logger.create("getSigningKeys");if(this._signingKeys)return n.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);n.debug("got jwks_uri",e);const t=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(n.debug("got key set",t),!Array.isArray(t.keys))throw n.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=t.keys,this._signingKeys}},AE=class{constructor({prefix:n="oidc.",store:e=localStorage}={}){this._logger=new Qn("WebStorageStateStore"),this._store=e,this._prefix=n}async set(n,e){this._logger.create(`set('${n}')`),n=this._prefix+n,await this._store.setItem(n,e)}async get(n){return this._logger.create(`get('${n}')`),n=this._prefix+n,await this._store.getItem(n)}async remove(n){this._logger.create(`remove('${n}')`),n=this._prefix+n;const e=await this._store.getItem(n);return await this._store.removeItem(n),e}async getAllKeys(){this._logger.create("getAllKeys");const n=await this._store.length,e=[];for(let t=0;t<n;t++){const r=await this._store.key(t);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return e}},iae="code",sae="openid",oae="client_secret_post",aae=60*15,jk=class{constructor({authority:n,metadataUrl:e,metadata:t,signingKeys:r,metadataSeed:i,client_id:s,client_secret:o,response_type:a=iae,scope:l=sae,redirect_uri:c,post_logout_redirect_uri:u,client_authentication:f=oae,prompt:p,display:m,max_age:v,ui_locales:g,acr_values:S,resource:b,response_mode:w,filterProtocolClaims:k=!0,loadUserInfo:R=!1,requestTimeoutInSeconds:I,staleStateAgeInSeconds:C=aae,mergeClaimsStrategy:x={array:"replace"},disablePKCE:O=!1,stateStore:N,revokeTokenAdditionalContentTypes:D,fetchRequestCredentials:j,refreshTokenAllowedScope:U,extraQueryParams:H={},extraTokenParams:K={},extraHeaders:B={},dpop:z,omitScopeWhenRequesting:W=!1}){var V;if(this.authority=n,e?this.metadataUrl=e:(this.metadataUrl=n,n&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=t,this.metadataSeed=i,this.signingKeys=r,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=l,this.redirect_uri=c,this.post_logout_redirect_uri=u,this.client_authentication=f,this.prompt=p,this.display=m,this.max_age=v,this.ui_locales=g,this.acr_values=S,this.resource=b,this.response_mode=w,this.filterProtocolClaims=k??!0,this.loadUserInfo=!!R,this.staleStateAgeInSeconds=C,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=W,this.disablePKCE=!!O,this.revokeTokenAdditionalContentTypes=D,this.fetchRequestCredentials=j||"same-origin",this.requestTimeoutInSeconds=I,N)this.stateStore=N;else{const q=typeof window<"u"?window.localStorage:new rae;this.stateStore=new AE({store:q})}if(this.refreshTokenAllowedScope=U,this.extraQueryParams=H,this.extraTokenParams=K,this.extraHeaders=B,this.dpop=z,this.dpop&&!((V=this.dpop)!=null&&V.store))throw new Error("A DPoPStore is required when dpop is enabled")}},lae=class{constructor(n,e){this._settings=n,this._metadataService=e,this._logger=new Qn("UserInfoService"),this._getClaimsFromJwt=async t=>{const r=this._logger.create("_getClaimsFromJwt");try{const i=eS.decode(t);return r.debug("JWT decoding successful"),i}catch(i){throw r.error("Error parsing JWT response"),i}},this._jsonService=new tL(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(n){const e=this._logger.create("getClaims");n||this._logger.throw(new Error("No token passed"));const t=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",t);const r=await this._jsonService.getJson(t,{token:n,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",r),r}},MH=class{constructor(n,e){this._settings=n,this._metadataService=e,this._logger=new Qn("TokenClient"),this._jsonService=new tL(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:n="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");t||o.throw(new Error("A client_id is required")),e||o.throw(new Error("A redirect_uri is required")),s.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:n,redirect_uri:e});for(const[f,p]of Object.entries(s))p!=null&&a.set(f,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw o.throw(new Error("A client_secret is required")),null;l=Do.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break}const c=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),u}async exchangeCredentials({grant_type:n="password",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,scope:r=this._settings.scope,...i}){const s=this._logger.create("exchangeCredentials");e||s.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:n});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[u,f]of Object.entries(i))f!=null&&o.set(u,f);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!t)throw s.throw(new Error("A client_secret is required")),null;a=Do.generateBasicAuth(e,t);break;case"client_secret_post":o.append("client_id",e),t&&o.append("client_secret",t);break}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),c}async exchangeRefreshToken({grant_type:n="refresh_token",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...s}){const o=this._logger.create("exchangeRefreshToken");e||o.throw(new Error("A client_id is required")),s.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:n});for(const[f,p]of Object.entries(s))Array.isArray(p)?p.forEach(m=>a.append(f,m)):p!=null&&a.set(f,p);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!t)throw o.throw(new Error("A client_secret is required")),null;l=Do.generateBasicAuth(e,t);break;case"client_secret_post":a.append("client_id",e),t&&a.append("client_secret",t);break}const c=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),u}async revoke(n){var e;const t=this._logger.create("revoke");n.token||t.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(e=n.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[s,o]of Object.entries(n))o!=null&&i.set(s,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug("got response")}},cae=class{constructor(n,e,t){this._settings=n,this._metadataService=e,this._claimsService=t,this._logger=new Qn("ResponseValidator"),this._userInfoService=new lae(this._settings,this._metadataService),this._tokenClient=new MH(this._settings,this._metadataService)}async validateSigninResponse(n,e,t){const r=this._logger.create("validateSigninResponse");this._processSigninState(n,e),r.debug("state processed"),await this._processCode(n,e,t),r.debug("code processed"),n.isOpenId&&this._validateIdTokenAttributes(n),r.debug("tokens validated"),await this._processClaims(n,e==null?void 0:e.skipUserInfo,n.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(n,e){const t=this._logger.create("validateCredentialsResponse");n.isOpenId&&n.id_token&&this._validateIdTokenAttributes(n),t.debug("tokens validated"),await this._processClaims(n,e,n.isOpenId),t.debug("claims processed")}async validateRefreshResponse(n,e){var t,r;const i=this._logger.create("validateRefreshResponse");n.userState=e.data,(t=n.session_state)!=null||(n.session_state=e.session_state),(r=n.scope)!=null||(n.scope=e.scope),n.isOpenId&&n.id_token&&(this._validateIdTokenAttributes(n,e.id_token),i.debug("ID Token validated")),n.id_token||(n.id_token=e.id_token,n.profile=e.profile);const s=n.isOpenId&&!!n.id_token;await this._processClaims(n,!1,s),i.debug("claims processed")}validateSignoutResponse(n,e){const t=this._logger.create("validateSignoutResponse");if(e.id!==n.state&&t.throw(new Error("State does not match")),t.debug("state validated"),n.userState=e.data,n.error)throw t.warn("Response was error",n.error),new lp(n)}_processSigninState(n,e){var t;const r=this._logger.create("_processSigninState");if(e.id!==n.state&&r.throw(new Error("State does not match")),e.client_id||r.throw(new Error("No client_id on state")),e.authority||r.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),n.userState=e.data,n.url_state=e.url_state,(t=n.scope)!=null||(n.scope=e.scope),n.error)throw r.warn("Response was error",n.error),new lp(n);e.code_verifier&&!n.code&&r.throw(new Error("Expected code in response"))}async _processClaims(n,e=!1,t=!0){const r=this._logger.create("_processClaims");if(n.profile=this._claimsService.filterProtocolClaims(n.profile),e||!this._settings.loadUserInfo||!n.access_token){r.debug("not loading user info");return}r.debug("loading user info");const i=await this._userInfoService.getClaims(n.access_token);r.debug("user info claims received from user info endpoint"),t&&i.sub!==n.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),n.profile=this._claimsService.mergeClaims(n.profile,this._claimsService.filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",n.profile)}async _processCode(n,e,t){const r=this._logger.create("_processCode");if(n.code){r.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:n.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:t,...e.extraTokenParams});Object.assign(n,i)}else r.debug("No code to process")}_validateIdTokenAttributes(n,e){var t;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=eS.decode((t=n.id_token)!=null?t:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const s=eS.decode(e);i.sub!==s.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==s.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==s.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&s.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}n.profile=i}},nS=class Uk{constructor(e){this.id=e.id||Do.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=tS.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Qn("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return Qn.createStatic("State","fromStorageString"),Promise.resolve(new Uk(JSON.parse(e)))}static async clearStaleState(e,t){const r=Qn.createStatic("State","clearStaleState"),i=tS.getEpochTime()-t,s=await e.getAllKeys();r.debug("got keys",s);for(let o=0;o<s.length;o++){const a=s[o],l=await e.get(a);let c=!1;if(l)try{const u=await Uk.fromStorageString(l);r.debug("got item from key:",a,u.created),u.created<=i&&(c=!0)}catch(u){r.error("Error parsing state for key:",a,u),c=!0}else r.debug("no item in storage for key:",a),c=!0;c&&(r.debug("removed item for key:",a),e.remove(a))}}},nL=class Fk extends nS{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(e){const t=e.code_verifier===!0?Do.generateCodeVerifier():e.code_verifier||void 0,r=t?await Do.generateCodeChallenge(t):void 0;return new Fk({...e,code_verifier:t,code_challenge:r})}toStorageString(){return new Qn("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(e){Qn.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return Fk.create(t)}},AH=class NH{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:o,state_data:a,response_mode:l,request_type:c,client_secret:u,nonce:f,url_state:p,resource:m,skipUserInfo:v,extraQueryParams:g,extraTokenParams:S,disablePKCE:b,dpopJkt:w,omitScopeWhenRequesting:k,...R}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const I=await nL.create({data:a,request_type:c,url_state:p,code_verifier:!b,client_id:r,authority:t,redirect_uri:i,response_mode:l,client_secret:u,scope:o,extraTokenParams:S,skipUserInfo:v}),C=new URL(e);C.searchParams.append("client_id",r),C.searchParams.append("redirect_uri",i),C.searchParams.append("response_type",s),k||C.searchParams.append("scope",o),f&&C.searchParams.append("nonce",f),w&&C.searchParams.append("dpop_jkt",w);let x=I.id;p&&(x=`${x}${Nk}${p}`),C.searchParams.append("state",x),I.code_challenge&&(C.searchParams.append("code_challenge",I.code_challenge),C.searchParams.append("code_challenge_method","S256")),m&&(Array.isArray(m)?m:[m]).forEach(N=>C.searchParams.append("resource",N));for(const[O,N]of Object.entries({response_mode:l,...R,...g}))N!=null&&C.searchParams.append(O,N.toString());return new NH({url:C.href,state:I})}};AH._logger=new Qn("SigninRequest");var uae=AH,dae="openid",$_=class{constructor(n){if(this.access_token="",this.token_type="",this.profile={},this.state=n.get("state"),this.session_state=n.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Nk);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Nk))}this.error=n.get("error"),this.error_description=n.get("error_description"),this.error_uri=n.get("error_uri"),this.code=n.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-tS.getEpochTime()}set expires_in(n){typeof n=="string"&&(n=Number(n)),n!==void 0&&n>=0&&(this.expires_at=Math.floor(n)+tS.getEpochTime())}get isOpenId(){var n;return((n=this.scope)==null?void 0:n.split(" ").includes(dae))||!!this.id_token}},fae=class{constructor({url:n,state_data:e,id_token_hint:t,post_logout_redirect_uri:r,extraQueryParams:i,request_type:s,client_id:o}){if(this._logger=new Qn("SignoutRequest"),!n)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(n);t&&a.searchParams.append("id_token_hint",t),o&&a.searchParams.append("client_id",o),r&&(a.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new nS({data:e,request_type:s}),a.searchParams.append("state",this.state.id)));for(const[l,c]of Object.entries({...i}))c!=null&&a.searchParams.append(l,c.toString());this.url=a.href}},hae=class{constructor(n){this.state=n.get("state"),this.error=n.get("error"),this.error_description=n.get("error_description"),this.error_uri=n.get("error_uri")}},pae=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],mae=["sub","iss","aud","exp","iat"],gae=class{constructor(n){this._settings=n,this._logger=new Qn("ClaimsService")}filterProtocolClaims(n){const e={...n};if(this._settings.filterProtocolClaims){let t;Array.isArray(this._settings.filterProtocolClaims)?t=this._settings.filterProtocolClaims:t=pae;for(const r of t)mae.includes(r)||delete e[r]}return e}mergeClaims(n,e){const t={...n};for(const[r,i]of Object.entries(e))if(t[r]!==i)if(Array.isArray(t[r])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")t[r]=i;else{const s=Array.isArray(t[r])?t[r]:[t[r]];for(const o of Array.isArray(i)?i:[i])s.includes(o)||s.push(o);t[r]=s}else typeof t[r]=="object"&&typeof i=="object"?t[r]=this.mergeClaims(t[r],i):t[r]=i;return t}},vae=class{constructor(n,e){this.keys=n,this.nonce=e}},rL=class{constructor(n,e){this._logger=new Qn("OidcClient"),this.settings=n instanceof jk?n:new jk(n),this.metadataService=e??new OH(this.settings),this._claimsService=new gae(this.settings),this._validator=new cae(this.settings,this.metadataService,this._claimsService),this._tokenClient=new MH(this.settings,this.metadataService)}async createSigninRequest({state:n,request:e,request_uri:t,request_type:r,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:l,response_type:c=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:f=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:v=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:S=this.settings.acr_values,resource:b=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:k=this.settings.extraQueryParams,extraTokenParams:R=this.settings.extraTokenParams,dpopJkt:I,omitScopeWhenRequesting:C=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if(c!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const O=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",O);const N=await uae.create({url:O,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:f,response_type:c,scope:u,state_data:n,url_state:l,prompt:p,display:m,max_age:v,ui_locales:g,id_token_hint:i,login_hint:s,acr_values:S,dpopJkt:I,resource:b,request:e,request_uri:t,extraQueryParams:k,extraTokenParams:R,request_type:r,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:C});await this.clearStaleState();const D=N.state;return await this.settings.stateStore.set(D.id,D.toStorageString()),N}async readSigninResponseState(n,e=!1){const t=this._logger.create("readSigninResponseState"),r=new $_(wN.readParams(n,this.settings.response_mode));if(!r.state)throw t.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await nL.fromStorageString(i),response:r}}async processSigninResponse(n,e){const t=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(n,!0);if(t.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const s=await this.getDpopProof(this.settings.dpop.store);e={...e,DPoP:s}}try{await this._validator.validateSigninResponse(i,r,e)}catch(s){if(s instanceof Dk&&this.settings.dpop){const o=await this.getDpopProof(this.settings.dpop.store,s.nonce);e.DPoP=o,await this._validator.validateSigninResponse(i,r,e)}else throw s}return i}async getDpopProof(n,e){let t,r;return(await n.getAllKeys()).includes(this.settings.client_id)?(r=await n.get(this.settings.client_id),r.nonce!==e&&e&&(r.nonce=e,await n.set(this.settings.client_id,r))):(t=await Do.generateDPoPKeys(),r=new vae(t,e),await n.set(this.settings.client_id,r)),await Do.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:n,password:e,skipUserInfo:t=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:n,password:e,...r}),s=new $_(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,t),s}async useRefreshToken({state:n,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let l;if(this.settings.refreshTokenAllowedScope===void 0)l=n.scope;else{const f=this.settings.refreshTokenAllowedScope.split(" ");l=(((o=n.scope)==null?void 0:o.split(" "))||[]).filter(m=>f.includes(m)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const f=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:f}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:n.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,...s})}catch(f){if(f instanceof Dk&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,f.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:n.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:r,extraHeaders:i,...s});else throw f}const u=new $_(new URLSearchParams);return Object.assign(u,c),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...n,scope:l}),u}async createSignoutRequest({state:n,id_token_hint:e,client_id:t,request_type:r,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),a=await this.metadataService.getEndSessionEndpoint();if(!a)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",a),!t&&i&&!e&&(t=this.settings.client_id);const l=new fae({url:a,id_token_hint:e,client_id:t,post_logout_redirect_uri:i,state_data:n,extraQueryParams:s,request_type:r});await this.clearStaleState();const c=l.state;return c&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(n,e=!1){const t=this._logger.create("readSignoutResponseState"),r=new hae(wN.readParams(n,this.settings.response_mode));if(!r.state){if(t.debug("No state in response"),r.error)throw t.warn("Response was error:",r.error),new lp(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await nS.fromStorageString(i),response:r}}async processSignoutResponse(n){const e=this._logger.create("processSignoutResponse"),{state:t,response:r}=await this.readSignoutResponseState(n,!0);return t?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,t)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),nS.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(n,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:n,token_type_hint:e})}},oi=function(n){return n.NotSupported="OIDC authentication not supported",n.Misconfigured="OIDC is misconfigured",n.General="Something went wrong with OIDC discovery",n.OpSupport="Configured OIDC OP does not support required functions",n.DynamicRegistrationNotSupported="Dynamic registration not supported",n.DynamicRegistrationFailed="Dynamic registration failed",n.DynamicRegistrationInvalid="Dynamic registration invalid response",n.CodeExchangeFailed="Failed to exchange code for token",n.InvalidBearerTokenResponse="Invalid bearer token response",n.InvalidIdToken="Invalid ID token",n.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",n}({}),iL=n=>!!n&&typeof n=="object"&&!Array.isArray(n),yl=(n,e)=>!n[e]||!Wg(n,e)?(A.error("Missing or invalid property: ".concat(e)),!1):!0,Wg=(n,e)=>n[e]&&typeof n[e]!="string"?(A.error("Invalid property: ".concat(e)),!1):!0,CN=(n,e)=>n[e]&&(!Array.isArray(n[e])||!n[e].every(t=>typeof t=="string"))?(A.error("Invalid property: ".concat(e)),!1):!0,c2=(n,e,t)=>{var r=n[e];return!r||!Array.isArray(r)||!r.includes(t)?(A.error("Invalid property: ".concat(e,". ").concat(t," is required.")),!1):!0},DH=n=>{if(!iL(n))throw A.error("Issuer configuration not found or malformed"),new Error(oi.OpSupport);var e=[yl(n,"issuer"),yl(n,"authorization_endpoint"),yl(n,"token_endpoint"),yl(n,"revocation_endpoint"),Wg(n,"registration_endpoint"),Wg(n,"account_management_uri"),Wg(n,"device_authorization_endpoint"),CN(n,"account_management_actions_supported"),c2(n,"response_types_supported","code"),c2(n,"grant_types_supported","authorization_code"),c2(n,"code_challenge_methods_supported","S256"),CN(n,"prompt_values_supported")].some(t=>!t);if(!e)return n;throw A.error("Issuer configuration not valid"),new Error(oi.OpSupport)},jH=n=>{try{return PH(n)}catch(e){throw A.error("Could not decode id_token",e),e}},UH=(n,e,t,r)=>{try{if(!n)throw new Error("No ID token");var i=jH(n);if(i.iss!==e)throw new Error("Invalid issuer");var s=typeof i.aud=="string"?[i.aud]:i.aud;if(!s.includes(t))throw new Error("Invalid audience");if(r!==void 0&&i.nonce!==r)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(o){throw A.error("Invalid ID token",o),new Error(oi.InvalidIdToken)}};function FH(n){if(!iL(n))throw A.error("Stored user state not found"),new Error(oi.MissingOrInvalidStoredState);var e=[yl(n,"homeserverUrl"),yl(n,"nonce"),Wg(n,"identityServerUrl")].some(t=>!t);if(e)throw new Error(oi.MissingOrInvalidStoredState)}var yae=n=>iL(n)&&yl(n,"token_type")&&n.token_type.toLowerCase()==="bearer"&&yl(n,"access_token")&&yl(n,"refresh_token")&&(!("expires_in"in n)||typeof n.expires_in=="number");function $H(n){if(!yae(n))throw new Error(oi.InvalidBearerTokenResponse)}function TN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function rS(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?TN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):TN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var NE=n=>{var e=n??bs(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},_ae=function(){var n=F(function*(e){if(!globalThis.crypto.subtle)return A.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var t=yield xH(e);return PE(t)});return function(t){return n.apply(this,arguments)}}(),bae=n=>{var{redirectUri:e}=n;return{scope:NE(),redirectUri:e,state:bs(8),nonce:bs(8),codeVerifier:bs(64)}},Sae=function(){var n=F(function*(e,t,r){var{scope:i,redirectUri:s,state:o,nonce:a,codeVerifier:l}=r,c=new URL(e);return c.searchParams.append("response_mode","query"),c.searchParams.append("response_type","code"),c.searchParams.append("redirect_uri",s),c.searchParams.append("client_id",t),c.searchParams.append("state",o),c.searchParams.append("scope",i),c.searchParams.append("nonce",a),c.searchParams.append("code_challenge_method","S256"),c.searchParams.append("code_challenge",yield _ae(l)),c.toString()});return function(t,r,i){return n.apply(this,arguments)}}(),Eae=function(){var n=F(function*(e){var{metadata:t,redirectUri:r,clientId:i,homeserverUrl:s,identityServerUrl:o,nonce:a,prompt:l,urlState:c}=e,u=NE(),f=new rL(rS(rS({},t),{},{client_id:i,redirect_uri:r,authority:t.issuer,response_mode:"query",response_type:"code",scope:u,stateStore:new AE({prefix:"mx_oidc_",store:window.sessionStorage})})),p={homeserverUrl:s,nonce:a,identityServerUrl:o},m=yield f.createSigninRequest({state:p,nonce:a,prompt:l,url_state:c});return m.url});return function(t){return n.apply(this,arguments)}}(),wae=n=>({id_token:n.id_token,scope:n.scope,expires_at:n.expires_at,refresh_token:n.refresh_token,access_token:n.access_token,token_type:"Bearer"}),Cae=function(){var n=F(function*(e,t){var r=new URL(window.location.origin);r.searchParams.append("code",e),r.searchParams.append("state",t),Pv.setLogger(A);try{var i=new $_(r.searchParams),s=new AE({prefix:"mx_oidc_",store:window.sessionStorage}),o=yield s.get(i.state);if(!o)throw new Error(oi.MissingOrInvalidStoredState);var a=yield nL.fromStorageString(o),l=new rL(rS(rS({},a),{},{stateStore:s})),c=yield l.processSigninResponse(r.href),u=c.userState;FH(u),$H(c),UH(c.id_token,l.settings.authority,l.settings.client_id,u.nonce);var f=wae(c);return{oidcClientSettings:{clientId:l.settings.client_id,issuer:l.settings.authority},tokenResponse:f,homeserverUrl:u.homeserverUrl,identityServerUrl:u.identityServerUrl,idTokenClaims:c.profile}}catch(m){A.error("Oidc login failed",m);var p=m.message;throw Object.values(oi).includes(p)?m:new Error(oi.CodeExchangeFailed)}});return function(t,r){return n.apply(this,arguments)}}();function RN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function IN(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?RN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):RN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var sL=function(){var n=F(function*(e){var t=new URL(".well-known/openid-configuration",e),r=yield fetch(t,{method:ae.Get,signal:kE(5e3)}),i=yield r.json();return oL(i)});return function(t){return n.apply(this,arguments)}}(),oL=function(){var n=F(function*(e){var t=DH(e),r=new jk({authority:t.issuer,metadata:t,redirect_uri:"",client_id:""}),i=new OH(r);return IN(IN({},t),{},{signingKeys:yield i.getSigningKeys()})});return function(t){return n.apply(this,arguments)}}(),Tae="urn:ietf:params:oauth:grant-type:device_code",u2=(n,e)=>{if(!e)return!1;var t=new URL(e);return!(t.protocol!==n.protocol||t.hostname!==n.hostname&&!t.hostname.endsWith(".".concat(n.hostname)))},Rae=function(){var n=F(function*(e,t){if(!e.registration_endpoint)throw new Error(oi.DynamicRegistrationNotSupported);var r=["authorization_code","refresh_token"];if(r.some(u=>!e.grant_types_supported.includes(u)))throw new Error(oi.DynamicRegistrationNotSupported);var i=new URL(t.clientUri),s={client_name:t.clientName,client_uri:t.clientUri,response_types:["code"],grant_types:r,redirect_uris:t.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:t.applicationType,contacts:t.contacts,logo_uri:u2(i,t.logoUri)?t.logoUri:void 0,policy_uri:u2(i,t.policyUri)?t.policyUri:void 0,tos_uri:u2(i,t.tosUri)?t.tosUri:void 0},o={Accept:"application/json","Content-Type":"application/json"};try{var a=yield fetch(e.registration_endpoint,{method:ae.Post,headers:o,body:JSON.stringify(s)});if(a.status>=400)throw new Error(oi.DynamicRegistrationFailed);var l=yield a.json(),c=l.client_id;if(!c||typeof c!="string")throw new Error(oi.DynamicRegistrationInvalid);return c}catch(u){throw Object.values(oi).includes(u.message)?u:(A.error("Dynamic registration request failed",u),new Error(oi.DynamicRegistrationFailed))}});return function(t,r){return n.apply(this,arguments)}}();class Iae{constructor(e,t,r,i,s){this.idTokenClaims=s,L(this,"oidcClientReady",void 0),L(this,"oidcClient",void 0),L(this,"inflightRefreshRequest",void 0),this.oidcClientReady=this.initialiseOidcClient(e,t,i,r)}initialiseOidcClient(e,t,r,i){var s=this;return F(function*(){try{var o,a=yield sL(e),l=NE(r);s.oidcClient=new rL({metadata:a,signingKeys:(o=a.signingKeys)!==null&&o!==void 0?o:void 0,client_id:t,scope:l,redirect_uri:i,authority:a.issuer,stateStore:new AE({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(c){throw A.error("Failed to initialise OIDC client.",c),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var t=this;return F(function*(){t.inflightRefreshRequest||(t.inflightRefreshRequest=t.getNewTokens(e));try{var r=yield t.inflightRefreshRequest;return r}catch(i){throw i instanceof lp?new $P(i):i}finally{t.inflightRefreshRequest=void 0}})()}persistTokens(e){return F(function*(){})()}getNewTokens(e){var t=this;return F(function*(){if(!t.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");var r={refresh_token:e,session_state:"test",data:void 0,profile:t.idTokenClaims},i=yield t.oidcClient.useRefreshToken({state:r,timeoutInSeconds:300}),s={accessToken:i.access_token,refreshToken:i.refresh_token};return yield t.persistTokens(s),s})()}}var kae=["server","limit","since"];function kN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function dr(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):kN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var xae=3e3,xN=10*60*1e3,Pae=new Kn("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),cp=function(n){return n.Chronological="chronological",n.Detached="detached",n}({}),Lae=new SE("m.get_login_token","org.matrix.msc3882.get_login_token"),HH="uk.half-shot.msc2666",BH="uk.half-shot.msc2666.mutual_rooms",VH="uk.half-shot.msc2666.query_mutual_rooms",pa="org.matrix.msc4140",qH="uk.tcpip.msc4133",Qo="$",Oe=function(n){return n.Sync="sync",n.Event="event",n.ToDeviceEvent="toDeviceEvent",n.AccountData="accountData",n.Room="Room",n.DeleteRoom="deleteRoom",n.SyncUnexpectedError="sync.unexpectedError",n.ClientWellKnown="WellKnown.client",n.ReceivedVoipEvent="received_voip_event",n.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",n.TurnServers="turnServers",n.TurnServersError="turnServers.error",n}({}),Oae=new Kn("action","org.matrix.msc3824.action");class DE extends En{constructor(e){var t,r,i,s;super(),i=this,L(this,"logger",void 0),L(this,"reEmitter",new Mp(this)),L(this,"olmVersion",null),L(this,"usingExternalCrypto",!1),L(this,"_store",void 0),L(this,"deviceId",void 0),L(this,"credentials",void 0),L(this,"legacyPickleKey",void 0),L(this,"scheduler",void 0),L(this,"clientRunning",!1),L(this,"timelineSupport",!1),L(this,"urlPreviewCache",{}),L(this,"identityServer",void 0),L(this,"http",void 0),L(this,"cryptoBackend",void 0),L(this,"cryptoCallbacks",void 0),L(this,"callEventHandler",void 0),L(this,"groupCallEventHandler",void 0),L(this,"supportsCallTransfer",!1),L(this,"forceTURN",!1),L(this,"iceCandidatePoolSize",0),L(this,"idBaseUrl",void 0),L(this,"baseUrl",void 0),L(this,"isVoipWithNoMediaAllowed",void 0),L(this,"useLivekitForGroupCalls",void 0),L(this,"canSupportVoip",!1),L(this,"peekSync",null),L(this,"isGuestAccount",!1),L(this,"ongoingScrollbacks",{}),L(this,"notifTimelineSet",null),L(this,"legacyCryptoStore",void 0),L(this,"verificationMethods",void 0),L(this,"fallbackICEServerAllowed",!1),L(this,"syncApi",void 0),L(this,"roomNameGenerator",void 0),L(this,"pushRules",void 0),L(this,"syncLeftRoomsPromise",void 0),L(this,"syncedLeftRooms",!1),L(this,"clientOpts",void 0),L(this,"clientWellKnownIntervalID",void 0),L(this,"canResetTimelineCallback",void 0),L(this,"canSupport",new Map),L(this,"pushProcessor",new wo(this)),L(this,"serverVersionsPromise",void 0),L(this,"clientWellKnown",void 0),L(this,"clientWellKnownPromise",void 0),L(this,"turnServers",[]),L(this,"turnServersExpiry",0),L(this,"checkTurnServersIntervalID",void 0),L(this,"txnCtr",0),L(this,"mediaHandler",new Toe(this)),L(this,"sessionId",void 0),L(this,"eventsBeingEncrypted",new Set),L(this,"useE2eForGroupCall",!0),L(this,"toDeviceMessageQueue",void 0),L(this,"livekitServiceURL",void 0),L(this,"_secretStorage",void 0),L(this,"ignoredInvites",void 0),L(this,"matrixRTC",void 0),L(this,"serverCapabilitiesService",void 0),L(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&(Sk()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(Oe.Sync,this.startCallEventHandler))}),L(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(Oe.Sync,this.startMatrixRTC))}),L(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var a,l=((a=this.getRooms())!==null&&a!==void 0?a:[]).filter(f=>f.getUnreadNotificationCount(jt.Total)>0);for(var c of l){var u=this.getSafeUserId();c.fixupNotifications(u)}this.off(Oe.Sync,this.fixupRoomNotifications)}}),this.logger=(t=e.logger)!==null&&t!==void 0?t:A,e.baseUrl=GT(e.baseUrl),e.idBaseUrl=GT(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=(r=e.usingExternalCrypto)!==null&&r!==void 0?r:!1,this.store=e.store||new kse,this.deviceId=e.deviceId||null,this.sessionId=bs(10);var o=e.userId||null;this.credentials={userId:o},this.http=new oH(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:fr.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.pickleKey&&(this.legacyPickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(function(){var a=F(function*(l){var c=i.getRoom(l.getRoomId());l.status!==et.SENDING&&i.updatePendingEventStatus(c,l,et.SENDING);var u=yield i.sendEventHttpRequest(l);return c&&c.updatePendingEvent(l,et.SENT,u.event_id),u});return function(l){return a.apply(this,arguments)}}()),Sk()&&(this.callEventHandler=new Wse(this),this.groupCallEventHandler=new zse(this),this.canSupportVoip=!0,this.on(Oe.Sync,this.startCallEventHandler)),this.matrixRTC=new Joe(this),this.serverCapabilitiesService=new lH(this.http),this.on(Oe.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=e.iceCandidatePoolSize===void 0?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,e.useE2eForGroupCall!==void 0&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.livekitServiceURL=e.livekitServiceURL,this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new Moe(this),this.on(Mt.Decrypted,a=>{KH(this,a)}),this.ignoredInvites=new Aoe(this),this._secretStorage=new RH(this,(s=e.cryptoCallbacks)!==null&&s!==void 0?s:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>bl.createUser(t,this))}get store(){return this._store}startClient(e){var t=this;return F(function*(){if(!t.clientRunning){t.clientRunning=!0,t.on(Oe.Sync,t.startMatrixRTC);var r=t.getUserId();r&&t.store.storeUser(new bl(r)),t.canSupportVoip&&(t.checkTurnServersIntervalID=setInterval(()=>{t.checkTurnServers()},xN),t.checkTurnServers()),t.syncApi&&(t.logger.error("Still have sync object whilst not running: stopping old one"),t.syncApi.stop());try{yield t.getVersions();var{threads:i,list:s,fwdPagination:o}=yield t.doesServerSupportThread();fn.setServerSideSupport(i),fn.setServerSideListSupport(s),fn.setServerSideFwdPaginationSupport(o)}catch(a){t.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}t.clientOpts=e??{},t.clientOpts.slidingSync?t.syncApi=new EH(t.clientOpts.slidingSync,t,t.clientOpts,t.buildSyncApiOptions()):t.syncApi=new gd(t,t.clientOpts,t.buildSyncApiOptions()),t.syncApi.sync().catch(a=>t.logger.info("Sync startup aborted with an error:",a)),t.clientOpts.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*t.clientOpts.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.toDeviceMessageQueue.start(),t.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,r,i,s;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(Oe.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)===null||t===void 0||t.stop(),this.syncApi=void 0,(r=this.peekSync)===null||r===void 0||r.stopPeeking(),(i=this.callEventHandler)===null||i===void 0||i.stop(),(s=this.groupCallEventHandler)===null||s===void 0||s.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.clientWellKnownIntervalID!==void 0&&globalThis.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop(),this.matrixRTC.stop(),this.serverCapabilitiesService.stop())}clearStores(){var e=this;if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var t=[];t.push(this.store.deleteAllData()),this.legacyCryptoStore&&t.push(this.legacyCryptoStore.deleteAllData());var r=function(){var i=F(function*(){var s;try{if(s=globalThis.indexedDB,!s)return}catch{return}var o=function*(c){var u=new Promise((f,p)=>{e.logger.info("Removing IndexedDB instance ".concat(c));var m=s.deleteDatabase(c);m.onsuccess=v=>{e.logger.info("Removed IndexedDB instance ".concat(c)),f(0)},m.onerror=v=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(c,":"),v),f(0)},m.onblocked=v=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(c))}});yield u};for(var a of["".concat(i2,"::matrix-sdk-crypto"),"".concat(i2,"::matrix-sdk-crypto-meta")])yield*o(a)});return function(){return i.apply(this,arguments)}}();return t.push(r()),Promise.all(t).then()}getUserId(){var e,t;return(e=(t=this.credentials)===null||t===void 0?void 0:t.userId)!==null&&e!==void 0?e:null}getSafeUserId(){var e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){var e;return(e=this.credentials)!==null&&e!==void 0&&e.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){var e,t;return(e=(t=this.credentials)===null||t===void 0||(t=t.userId)===null||t===void 0?void 0:t.split(":")[0].substring(1))!==null&&e!==void 0?e:null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return Iv(this,e)}createGroupCall(e,t,r,i,s,o){var a=this;return F(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var l=a.getRoom(e);if(!l)throw new Error("Cannot find room ".concat(e));return new GP(a,l,t,r,i,void 0,s||a.isVoipWithNoMediaAllowed,o,a.isVoipWithNoMediaAllowed,a.useLivekitForGroupCalls,a.livekitServiceURL).create()})()}getLivekitServiceURL(){return this.livekitServiceURL}setLivekitServiceURL(e){this.livekitServiceURL=e}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return(e=(t=this.syncApi)===null||t===void 0?void 0:t.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===Dt.Prepared||e===Dt.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),(e=(t=this.syncApi)===null||t===void 0?void 0:t.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return F(function*(){var t=e.serverCapabilitiesService.getCachedCapabilities();return t||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initRustCrypto(){var e=arguments,t=this;return F(function*(){var r,i=e.length>0&&e[0]!==void 0?e[0]:{};if(t.cryptoBackend){t.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var s=t.getUserId();if(s===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var o=t.getDeviceId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");t.logger.debug("Downloading Rust crypto library");var a=yield Cv(()=>import("./index-mR1dxpYl.js"),__vite__mapDeps([0,1]),import.meta.url),l=yield a.initRustCrypto({logger:t.logger,http:t.http,userId:s,deviceId:o,secretStorage:t.secretStorage,cryptoCallbacks:t.cryptoCallbacks,storePrefix:i.useIndexedDB===!1?null:i2,storeKey:i.storageKey,storePassphrase:i.storagePassword,legacyCryptoStore:t.legacyCryptoStore,legacyPickleKey:(r=t.legacyPickleKey)!==null&&r!==void 0?r:"DEFAULT_KEY",legacyMigrationProgressListener:(c,u)=>{t.emit(Rr.LegacyCryptoStoreMigrationProgress,c,u)}});l.setSupportedVerificationMethods(t.verificationMethods),t.cryptoBackend=l,t.on(Wi.Membership,l.onRoomMembership.bind(l)),t.on(Oe.Event,c=>{l.onLiveEventFromSync(c)}),t.reEmitter.reEmit(l,[Rr.VerificationRequestReceived,Rr.UserTrustStatusChanged,Rr.KeyBackupStatus,Rr.KeyBackupSessionsRemaining,Rr.KeyBackupFailed,Rr.KeyBackupDecryptionKeyCached,Rr.KeysChanged,Rr.DevicesUpdated,Rr.WillUpdateDevices,Rr.DehydratedDeviceCreated,Rr.DehydratedDeviceUploaded,Rr.RehydrationStarted,Rr.RehydrationProgress,Rr.RehydrationCompleted,Rr.RehydrationError,Rr.DehydrationKeyCached,Rr.DehydratedDeviceRotationError])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){var t=this.getRoom(e);return t?t.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,t,r){var i;t!==void 0?i=Ie("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Ie("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys";var s=r===void 0?void 0:{version:r};return{path:i,queryData:s}}deleteKeysFromBackup(e,t,r){var i=this;return F(function*(){var s=i.makeKeyBackupPath(e,t,r);yield i.http.authedRequest(ae.Delete,s.path,s.queryData,void 0,{prefix:fr.V3})})()}getMediaConfig(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=e?"/media/config":"/config";return this.http.authedRequest(ae.Get,t,void 0,void 0,{prefix:e?fr.V1:Lh.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.store.getRooms(),r=new Set;for(var i of t){var s,o=(s=i.findPredecessor(e))===null||s===void 0?void 0:s.roomId;o&&r.add(o)}return t.filter(a=>{var l=a.currentState.getStateEvents(ee.RoomTombstone,"");return!(l&&r.has(a.roomId))})}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){var r=this;return F(function*(){if(!r.clientRunning)return A.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),yield fk(5,()=>r.setAccountDataRaw(e,t));var i=r.store.getAccountData(e);if(i&&Md(i.event.content,t))return{};var s=ru();function o(l){l.getType()===e&&s.resolve()}r.addListener(Oe.AccountData,o);try{var a=yield fk(5,()=>r.setAccountDataRaw(e,t));return yield s.promise,a}finally{r.removeListener(Oe.AccountData,o)}})()}setAccountDataRaw(e,t){var r=Ie("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(ae.Put,r,void 0,t)}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t=this;return F(function*(){if(t.isInitialSyncComplete()){var r=t.store.getAccountData(e);return r?r.getContent():null}var i=Ie("/user/$userId/account_data/$type",{$userId:t.credentials.userId,$type:e});try{return yield t.http.authedRequest(ae.Get,i)}catch(o){var s;if(((s=o.data)===null||s===void 0?void 0:s.errcode)==="M_NOT_FOUND")return null;throw o}})()}deleteAccountData(e){var t=this;return F(function*(){var r=t.canSupport.get(vr.AccountDataDeletion);if(r===gr.Unsupported){yield t.setAccountData(e,{});return}var i=Ie("/user/$userId/account_data/$type",{$userId:t.getSafeUserId(),$type:e}),s=r===gr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield t.http.authedRequest(ae.Delete,i,void 0,void 0,s)})()}getIgnoredUsers(){var e=this.getAccountData(ee.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){var t={ignored_users:{}};return e.forEach(r=>{t.ignored_users[r]={}}),this.setAccountData(ee.IgnoredUserList,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};i.syncRoom===void 0&&(i.syncRoom=!0);var s=r.getRoom(e);if(s!=null&&s.hasMembershipState(r.credentials.userId,qe.Join))return s;var o=Promise.resolve();if(i.inviteSignUrl){var a=new URL(i.inviteSignUrl);a.searchParams.set("mxid",r.credentials.userId),o=r.http.requestOtherUrl(ae.Post,a)}var l={};i.viaServers&&(l.server_name=i.viaServers,l.via=i.viaServers);var c={},u=yield o;u&&(c.third_party_signed=u);var f=Ie("/join/$roomid",{$roomid:e}),p=yield r.http.authedRequest(ae.Post,f,l,c),m=p.room_id,v=r.getRoom(m);if(v!=null&&v.hasMembershipState(r.credentials.userId,qe.Join))return v;var g=new gd(r,r.clientOpts,r.buildSyncApiOptions()),S=g.createRoom(m);return i.syncRoom,S})()}knockRoom(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,qe.Knock))return Promise.resolve({room_id:r.roomId});var i=Ie("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);var o={};return t.reason&&(o.reason=t.reason),this.http.authedRequest(ae.Post,i,s,o)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,et.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![et.QUEUED,et.NOT_SENT,et.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===et.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===et.QUEUED&&this.scheduler.removeEventFromQueue(e);var t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,et.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,ee.RoomName,{name:t})}setRoomTopic(e,t,r){var i=G$(t,r);return this.sendStateEvent(e,ee.RoomTopic,i)}getRoomTags(e){var t=Ie("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(ae.Get,t)}setRoomTag(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=Ie("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(ae.Put,i,void 0,r)}deleteRoomTag(e,t){var r=Ie("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(ae.Delete,r)}setRoomAccountData(e,t,r){var i=Ie("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(ae.Put,i,void 0,r)}setPowerLevel(e,t,r){var i=this;return F(function*(){var s,o;if(i.clientRunning&&i.isInitialSyncComplete()){var a;o=(a=i.getRoom(e))===null||a===void 0||(a=a.currentState)===null||a===void 0||(a=a.getStateEvents(ee.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!o)try{o=yield i.getStateEvent(e,ee.RoomPowerLevels,"")}catch(u){if(u instanceof bn&&u.errcode==="M_NOT_FOUND")o={};else throw u}o=wE(o),(s=o)!==null&&s!==void 0&&s.users||(o.users={});var l=Array.isArray(t)?t:[t];for(var c of l)r==null?delete o.users[c]:o.users[c]=r;return i.sendStateEvent(e,ee.RoomPowerLevels,o,"")})()}unstable_createLiveBeacon(e,t){var r=this;return F(function*(){return r.unstable_setLiveBeacon(e,t)})()}unstable_setLiveBeacon(e,t){var r=this;return F(function*(){return r.sendStateEvent(e,JP.name,t,r.getUserId())})()}sendEvent(e,t,r,i,s){var o,a,l,c;return!(t!=null&&t.startsWith(Qo))&&t!==null?(c=i,l=r,a=t,o=null):(c=s,l=i,a=r,o=t),this.addThreadRelationIfNeeded(l,o,e),this.sendCompleteEvent(e,o,{type:a,content:l},c)}addThreadRelationIfNeeded(e,t,r){var i;if(t&&!((i=e["m.relates_to"])!==null&&i!==void 0&&i.rel_type)){var s,o,a=!!((s=e["m.relates_to"])!==null&&s!==void 0&&s["m.in_reply_to"]);e["m.relates_to"]=dr(dr({},e["m.relates_to"]),{},{rel_type:Qt.name,event_id:t,is_falling_back:!a});var l=(o=this.getRoom(r))===null||o===void 0?void 0:o.getThread(t);if(l&&!a){var c,u;e["m.relates_to"]["m.in_reply_to"]={event_id:(c=(u=l.lastReply(f=>f.isRelation(Qt.name)&&!f.status))===null||u===void 0?void 0:u.getId())!==null&&c!==void 0?c:t}}}}sendCompleteEvent(e,t,r,i,s){var o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());var l=new wi(Object.assign(r,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),c=this.getRoom(e),u=t?c==null?void 0:c.getThread(t):void 0;u&&l.setThread(u),o||(this.reEmitter.reEmit(l,[Mt.Replaced,Mt.VisibilityChange]),c==null||c.reEmitter.reEmit(l,[Mt.BeforeRedaction]));var f=l.getAssociatedId();if(f!=null&&f.startsWith("~")){var p=c==null?void 0:c.getPendingEvents().find(v=>v.getId()===f);p==null||p.once(Mt.LocalEventIdReplaced,()=>{l.updateAssociatedId(p.getId())})}var m=l.getType();return this.logger.debug("sendEvent of type ".concat(m," in ").concat(e," with txnId ").concat(a).concat(o?" (delayed event)":"")),l.setTxnId(a),l.setStatus(et.SENDING),o?this.encryptAndSendEvent(c,l,o):(c==null||c.addPendingEvent(l,a),l.status===et.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(c,l))}encryptAndSendEvent(e,t,r){var i=this;return F(function*(){if(r)return i.sendEventHttpRequest(t,r);try{var s;i.eventsBeingEncrypted.add(t.getId());try{yield i.encryptEventIfNeeded(t,e??void 0)}finally{s=!i.eventsBeingEncrypted.delete(t.getId())}if(s)return{};t.status===et.ENCRYPTING&&i.updatePendingEventStatus(e,t,et.SENDING);var o=null;return i.scheduler&&(o=i.scheduler.queueEvent(t),o&&i.scheduler.getQueueForEvent(t).length>1&&i.updatePendingEventStatus(e,t,et.QUEUED)),o||(o=i.sendEventHttpRequest(t),e&&(o=o.then(a=>(e.updatePendingEvent(t,et.SENT,a.event_id),a)))),yield o}catch(a){i.logger.error("Error sending event",a);try{t.error=a,i.updatePendingEventStatus(e,t,et.NOT_SENT)}catch(l){i.logger.error("Exception in error handler!",l)}throw a instanceof bn&&(a.event=t),a}})()}encryptEventIfNeeded(e,t){var r=this;return F(function*(){if(t&&(yield r.shouldEncryptEventForRoom(e,t))&&!(!r.cryptoBackend&&r.usingExternalCrypto)){if(!r.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");r.updatePendingEventStatus(t,e,et.ENCRYPTING),yield r.cryptoBackend.encryptEvent(e,t)}})()}shouldEncryptEventForRoom(e,t){var r=this;return F(function*(){var i;return e.isEncrypted()||e.getType()===ee.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||(yield(i=r.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(t.roomId)))})()}getEncryptedIfNeededEventType(e,t){var r;return t===ee.Reaction?t:(r=this.getRoom(e))!==null&&r!==void 0&&r.hasEncryptionStateEvent()?ee.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,r){e?e.updatePendingEvent(t,r):t.setStatus(r)}sendEventHttpRequest(e,t){var r=e.getTxnId();r||(r=this.makeTxnId(),e.setTxnId(r));var i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:r},s;if(e.isState()){var o="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(o="/rooms/$roomId/state/$eventType/$stateKey"),s=Ie(o,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";s=Ie(a,dr({$redactsEventId:e.event.redacts},i))}else s=Ie("/rooms/$roomId/send/$eventType/$txnId",i);var l=e.getWireContent();return t?this.http.authedRequest(ae.Put,s,PN(t),l):this.http.authedRequest(ae.Put,s,void 0,l).then(c=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(c.event_id)),c))}redactEvent(e,t,r,i,s){var o,a,l;(o=r)!==null&&o!==void 0&&o.startsWith(Qo)||(s=i,i=r,r=t,t=null);var c=(a=s)===null||a===void 0?void 0:a.reason,u={reason:c};if(((l=s)===null||l===void 0?void 0:l.with_rel_types)!==void 0){if(this.canSupport.get(vr.RelationBasedRedactions)===gr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(r," txnId: ").concat(i," threadId ").concat(t));var f=this.canSupport.get(vr.RelationBasedRedactions)===gr.Stable?ok.stable:ok.unstable;u[f]=s.with_rel_types}return this.sendCompleteEvent(e,t,{type:ee.RoomRedaction,content:u,redacts:r},i)}sendMessage(e,t,r,i){typeof t!="string"&&t!==null&&(i=r,r=t,t=null);var s=ee.RoomMessage,o=r;return this.sendEvent(e,t,s,o,i)}sendTextMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=H$(r);return this.sendMessage(e,t,o,i)}sendNotice(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=B$(r);return this.sendMessage(e,t,o,i)}sendEmoteMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=V$(r);return this.sendMessage(e,t,o,i)}sendImageMessage(e,t,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(o=i||"Image",i=r,r=t,t=null);var a={msgtype:La.Image,url:r,info:i,body:o};return this.sendMessage(e,t,a)}sendStickerMessage(e,t,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(o=i||"Sticker",i=r,r=t,t=null);var a={url:r,info:i,body:o};return this.sendEvent(e,t,ee.Sticker,a)}sendHtmlMessage(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=U$(r,i);return this.sendMessage(e,t,o)}sendHtmlNotice(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=F$(r,i);return this.sendMessage(e,t,o)}sendHtmlEmote(e,t,r,i){var s;!((s=t)!==null&&s!==void 0&&s.startsWith(Qo))&&t!==null&&(i=r,r=t,t=null);var o=$$(r,i);return this.sendMessage(e,t,o)}_unstable_sendDelayedEvent(e,t,r,i,s,o){var a=this;return F(function*(){if(!(yield a.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","sendDelayedEvent");return a.addThreadRelationIfNeeded(s,r,e),a.sendCompleteEvent(e,r,{type:i,content:s},t,o)})()}_unstable_sendDelayedStateEvent(e,t,r,i){var s=arguments,o=this;return F(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"",l=s.length>5&&s[5]!==void 0?s[5]:{};if(!(yield o.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","sendDelayedStateEvent");var c={$roomId:e,$eventType:r,$stateKey:a},u=Ie("/rooms/$roomId/state/$eventType",c);return a!==void 0&&(u=Ie(u+"/$stateKey",c)),o.http.authedRequest(ae.Put,u,PN(t),i,l)})()}_unstable_getDelayedEvents(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","getDelayedEvents");var r=e?{from:e}:void 0;return yield t.http.authedRequest(ae.Get,"/delayed_events",r,void 0,{prefix:"".concat(fr.Unstable,"/").concat(pa)})})()}_unstable_updateDelayedEvent(e,t){var r=arguments,i=this;return F(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(!(yield i.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","updateDelayedEvent");var o=Ie("/delayed_events/$delayId",{$delayId:e}),a={action:t};return yield i.http.authedRequest(ae.Post,o,void 0,a,dr(dr({},s),{},{prefix:"".concat(fr.Unstable,"/").concat(pa)}))})()}sendReceipt(e,t,r){var i=arguments,s=this;return F(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:!1;if(s.isGuest())return Promise.resolve({});var a=Ie("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),l=!o&&s.supportsThreads(),c=l?dr(dr({},r),{},{thread_id:up(e)}):r,u=s.http.authedRequest(ae.Post,a,void 0,c||{}),f=s.getRoom(e.getRoomId());return f&&s.credentials.userId&&f.addLocalEchoReceipt(s.credentials.userId,e,t,o),u})()}sendReadReceipt(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:vi.Read,s=t.length>2&&t[2]!==void 0?t[2]:!1;if(e){var o=e.getId(),a=r.getRoom(e.getRoomId());if(a!=null&&a.hasPendingEvent(o))throw new Error("Cannot set read receipt to a pending event (".concat(o,")"));return r.sendReceipt(e,i,{},s)}})()}setRoomReadMarkers(e,t,r,i){var s=this;return F(function*(){var o=s.getRoom(e);if(o!=null&&o.hasPendingEvent(t))throw new Error("Cannot set read marker to a pending event (".concat(t,")"));var a;if(r){if(a=r.getId(),o!=null&&o.hasPendingEvent(a))throw new Error("Cannot set read receipt to a pending event (".concat(a,")"));o==null||o.addLocalEchoReceipt(s.credentials.userId,r,vi.Read)}var l;if(i){if(l=i.getId(),o!=null&&o.hasPendingEvent(l))throw new Error("Cannot set read receipt to a pending event (".concat(l,")"));o==null||o.addLocalEchoReceipt(s.credentials.userId,i,vi.ReadPrivate)}return yield s.setRoomReadMarkersHttpRequest(e,t,a,l)})()}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;var r=new URL(e);r.hash="",e=r.toString();var i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var s=this.http.authedRequest(ae.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:Lh.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,t,r){if(this.isGuest())return Promise.resolve({});var i=Ie("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:t};return t&&(s.timeout=r||2e4),this.http.authedRequest(ae.Put,i,void 0,s)}getRoomUpgradeHistory(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getRoom(e);if(!i)return[];var s=this.findPredecessorRooms(i,t,r),o=this.findSuccessorRooms(i,t,r);return[...s,i,...o]}findPredecessorRooms(e,t,r){for(var i,s=[],o=new Set([e.roomId]),a=(i=e.findPredecessor(r))===null||i===void 0?void 0:i.roomId;a!==null;){var l;if(a){if(o.has(a))break;o.add(a)}var c=this.getRoom(a);if(c===null)break;if(t){var u=c.currentState.getStateEvents(ee.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}s.splice(0,0,c),e=c,a=(l=e.findPredecessor(r))===null||l===void 0?void 0:l.roomId}return s}findSuccessorRooms(e,t,r){for(var i=[],s=e.currentState.getStateEvents(ee.RoomTombstone,"");s;){var o=this.getRoom(s.getContent().replacement_room);if(!o||o.roomId===e.roomId)break;if(t){var a,l=(a=o.findPredecessor(r))===null||a===void 0?void 0:a.roomId;if(!l||l!==e.roomId)break}i.push(o);var c=new Set(i.map(u=>u.roomId));if(c.size<i.length)return i.slice(0,i.length-1);e=o,s=e.currentState.getStateEvents(ee.RoomTombstone,"")}return i}invite(e,t,r){return this.membershipChange(e,t,qe.Invite,r)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}inviteByThreePid(e,t,r){var i=this;return F(function*(){var s,o=Ie("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new bn({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var l={id_server:a,medium:t,address:r};if((s=i.identityServer)!==null&&s!==void 0&&s.getAccessToken){var c=yield i.identityServer.getAccessToken();c&&(l.id_access_token=c)}return i.http.authedRequest(ae.Post,o,void 0,l)})()}leave(e){return this.membershipChange(e,void 0,qe.Leave)}leaveRoomChain(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this.getRoomUpgradeHistory(e),i=r;if(!t){i=[];for(var s of r)if(i.push(s),s.roomId===e)break}var o={},a=[],l=u=>this.leave(u).then(()=>{delete o[u]}).catch(f=>{o[u]=f});for(var c of i)a.push(l(c.roomId));return Promise.all(a).then(()=>o)}ban(e,t,r){return this.membershipChange(e,t,qe.Ban,r)}forget(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,s=Ie("/rooms/$room_id/forget",{$room_id:e}),o=yield r.http.authedRequest(ae.Post,s);return i&&(r.store.removeRoom(e),r.emit(Oe.DeleteRoom,e)),o})()}unban(e,t){var r=Ie("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(ae.Post,r,void 0,i)}kick(e,t,r){var i=Ie("/rooms/$roomId/kick",{$roomId:e}),s={user_id:t,reason:r};return this.http.authedRequest(ae.Post,i,void 0,s)}membershipChange(e,t,r,i){var s=Ie("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(ae.Post,s,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||t){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||t){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,t){var r=Ie("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(ae.Put,r,void 0,t)}setDisplayName(e){var t=this;return F(function*(){var r=yield t.setProfileInfo("displayname",{displayname:e}),i=t.getUser(t.getUserId());return i&&(i.displayName=e,i.emit(qr.DisplayName,i.events.presence,i)),r})()}setAvatarUrl(e){var t=this;return F(function*(){var r=yield t.setProfileInfo("avatar_url",{avatar_url:e}),i=t.getUser(t.getUserId());return i&&(i.avatarUrl=e,i.emit(qr.AvatarUrl,i.events.presence,i)),r})()}mxcUrlToHttp(e,t,r,i,s,o,a){return TE(this.baseUrl,e,t,r,i,s,o,a)}setSyncPresence(e){var t=this;return F(function*(){var r;(r=t.syncApi)===null||r===void 0||r.setPresence(e)})()}setPresence(e){var t=this;return F(function*(){var r=Ie("/presence/$userId/status",{$userId:t.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield t.http.authedRequest(ae.Put,r,void 0,e)})()}getPresence(e){var t=Ie("/presence/$userId/status",{$userId:e});return this.http.authedRequest(ae.Get,t)}scrollback(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:30,r=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){var s=Date.now()-i.errorTs;r=Math.max(xae-s,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var o=this.store.scrollback(e,t).length;if(o===t)return Promise.resolve(e);t=t-o;var a=new Promise((l,c)=>{nu(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,ht.Backward)).then(u=>{var f,p,m=u.chunk.map(this.getEventMapper());if(u.state){var v=u.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(v)}var[g,S,b]=e.partitionThreadedEvents(m);this.processAggregatedTimelineEvents(e,g),e.addEventsToTimeline(g,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,S,!0),b.forEach(w=>e.relations.aggregateChildEvent(w)),e.oldState.paginationToken=(f=u.end)!==null&&f!==void 0?f:null,u.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,m,(p=u.end)!==null&&p!==void 0?p:null,!0),delete this.ongoingScrollbacks[e.roomId],l(e)}).catch(u=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(u)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return woe(this,e||{})}getEventTimeline(e,t){var r=this;return F(function*(){var i,s,o,a;if(!r.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(e!=null&&e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&r.supportsThreads())return r.getThreadTimeline(e,t);var l=Ie("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),c=void 0;(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(c={filter:JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER)});var u=yield r.http.authedRequest(ae.Get,l,c);if(!u.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);var f=r.getEventMapper(),p=f(u.event);if(p.isRelation(Qt.name)){r.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var m=[...u.events_after.reverse().map(f),p,...u.events_before.map(f)],v=e.getTimelineForEvent(m[0].getId());v?v.getState(Le.BACKWARDS).setUnknownStateEvents(u.state.map(f)):(v=e.addTimeline(),v.initialiseState(u.state.map(f)),v.getState(Le.FORWARDS).paginationToken=u.end);var[g,S,b]=e.room.partitionThreadedEvents(m);return e.addEventsToTimeline(g,!0,!1,v,u.start),r.processThreadEvents(e.room,S,!0),r.processAggregatedTimelineEvents(e.room,g),b.forEach(w=>e.relations.aggregateChildEvent(w)),(s=(o=e.getTimelineForEvent(t))!==null&&o!==void 0?o:(a=e.room.findThreadForEvent(p))===null||a===void 0?void 0:a.liveTimeline)!==null&&s!==void 0?s:v})()}getThreadTimeline(e,t){var r=this;return F(function*(){var i;if(!r.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var s=Ie("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),o={limit:"0"};(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(o.filter=JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER));var a=yield r.http.authedRequest(ae.Get,s,o),l=r.getEventMapper(),c=l(a.event);if(e.canContain(c)){var u=r.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported;if(fn.hasServerSideSupport)if(fn.hasServerSideFwdPaginationSupport){var f,p,m;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var v=e.thread,g=yield r.fetchRelations(e.room.roomId,v.id,null,null,{dir:ht.Backward,from:a.start,recurse:u||void 0}),S=yield r.fetchRelations(e.room.roomId,v.id,null,null,{dir:ht.Forward,from:a.end,recurse:u||void 0}),b=[...S.chunk.reverse().filter(l2(v.id)).map(l),c,...g.chunk.filter(l2(v.id)).map(l)];for(var w of b){var k;yield(k=e.thread)===null||k===void 0?void 0:k.processEvent(w)}var R=e.getTimelineForEvent(c.getId());if(R?R.getState(Le.BACKWARDS).setUnknownStateEvents(a.state.map(l)):(R=e.addTimeline(),R.initialiseState(a.state.map(l))),e.addEventsToTimeline(b,!0,!1,R,S.next_batch),!g.next_batch){var I=yield r.fetchRoomEvent(e.room.roomId,v.id);e.addEventsToTimeline([l(I)],!0,!1,R,null)}return R.setPaginationToken((f=g.next_batch)!==null&&f!==void 0?f:null,ht.Backward),R.setPaginationToken((p=S.next_batch)!==null&&p!==void 0?p:null,ht.Forward),r.processAggregatedTimelineEvents(e.room,b),(m=e.getTimelineForEvent(t))!==null&&m!==void 0?m:R}else{for(var C,x=e.thread,O=yield r.fetchRelations(e.room.roomId,x.id,Qt.name,null,{dir:ht.Backward,from:a.start,recurse:u||void 0}),N=[],D=a.end;D;){var j,U=yield r.fetchRelations(e.room.roomId,x.id,Qt.name,null,{dir:ht.Forward,from:D,recurse:u||void 0});D=(j=U.next_batch)!==null&&j!==void 0?j:null,N.push(...U.chunk)}var H=[...N.reverse().map(l),c,...O.chunk.map(l)];for(var K of H){var B;yield(B=e.thread)===null||B===void 0?void 0:B.processEvent(K)}var z=e.getLiveTimeline();if(z.getState(Le.BACKWARDS).setUnknownStateEvents(a.state.map(l)),e.addEventsToTimeline(H,!0,!1,z,null),!O.next_batch){var W=yield r.fetchRoomEvent(e.room.roomId,x.id);e.addEventsToTimeline([l(W)],!0,!1,z,null)}return z.setPaginationToken((C=O.next_batch)!==null&&C!==void 0?C:null,ht.Backward),z.setPaginationToken(null,ht.Forward),r.processAggregatedTimelineEvents(e.room,H),z}}})()}getLatestTimeline(e){var t=this;return F(function*(){if(!t.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");var r;if(e.threadListType!==null){var i,s=yield t.createThreadListMessagesRequest(e.room.roomId,null,1,ht.Backward,e.threadListType,e.getFilter());r=(i=s.chunk)===null||i===void 0?void 0:i[0]}else if(e.thread&&fn.hasServerSideSupport){var o,a=t.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported,l=yield t.fetchRelations(e.room.roomId,e.thread.id,Qt.name,null,{dir:ht.Backward,limit:1,recurse:a||void 0});r=(o=l.chunk)===null||o===void 0?void 0:o[0]}else{var c,u,f=Ie("/rooms/$roomId/messages",{$roomId:e.room.roomId}),p={dir:"b"};(c=t.clientOpts)!==null&&c!==void 0&&c.lazyLoadMembers&&(p.filter=JSON.stringify(Bi.LAZY_LOADING_MESSAGES_FILTER));var m=yield t.http.authedRequest(ae.Get,f,p);r=(u=m.chunk)===null||u===void 0?void 0:u[0]}if(!r)throw new Error("No message returned when trying to construct getLatestTimeline");return t.getEventTimeline(e,r.event_id)})()}createMessagesRequest(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,s=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,a=Ie("/rooms/$roomId/messages",{$roomId:e}),l={limit:i.toString(),dir:s};t&&(l.from=t);var c=null;if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(c=Object.assign({},Bi.LAZY_LOADING_MESSAGES_FILTER)),o){var u;c=c||{},Object.assign(c,(u=o.getRoomTimelineFilterComponent())===null||u===void 0?void 0:u.toJSON())}return c&&(l.filter=JSON.stringify(c)),this.http.authedRequest(ae.Get,a,l)}createThreadListMessagesRequest(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:ht.Backward,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:So.All,a=arguments.length>5?arguments[5]:void 0,l=Ie("/rooms/$roomId/threads",{$roomId:e}),c={limit:i.toString(),dir:s,include:GH(o)};t&&(c.from=t);var u={};if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(u=dr({},Bi.LAZY_LOADING_MESSAGES_FILTER)),a){var f;u=dr(dr({},u),(f=a.getRoomTimelineFilterComponent())===null||f===void 0?void 0:f.toJSON())}Object.keys(u).length&&(c.filter=JSON.stringify(u));var p={prefix:fn.hasServerSideListSupport===si.Stable?fr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(ae.Get,l,c,void 0,p).then(m=>{var v;return dr(dr({},m),{},{chunk:(v=m.chunk)===null||v===void 0?void 0:v.reverse(),start:m.prev_batch,end:m.next_batch})})}paginateEventTimeline(e,t){var r=this,i=e.getTimelineSet()===this.notifTimelineSet,s=this.getRoom(e.getRoomId()),o=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;t=t||{};var l=t.backwards||!1;if(i&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");var c=l?Le.BACKWARDS:Le.FORWARDS,u=e.getPaginationToken(c),f=e.paginationRequests[c];if(f)return f;var p,m,v;if(i){var g;p="/notifications",m={limit:((g=t.limit)!==null&&g!==void 0?g:30).toString(),only:"highlight"},u&&u!=="end"&&(m.from=u),v=this.http.authedRequest(ae.Get,p,m).then(function(){var R=F(function*(I){var C=I.next_token,x=[];I.notifications=I.notifications.filter(Ro);for(var O=0;O<I.notifications.length;O++){var N=I.notifications[O],D=r.getEventMapper()(N.event);r.getPushDetailsForEvent(D,!0),D.event.room_id=N.room_id,x[O]=D}var j=e.getTimelineSet();return j.addEventsToTimeline(x,l,!1,e,C),r.processAggregatedTimelineEvents(j.room,x),l&&!I.next_token&&e.setPaginationToken(null,c),!!I.next_token});return function(I){return R.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else if(o!==null){if(!s)throw new Error("Unknown room "+e.getRoomId());if(!fn.hasServerSideFwdPaginationSupport&&c===ht.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");v=this.createThreadListMessagesRequest(e.getRoomId(),u,t.limit,c,o,e.getFilter()).then(R=>{if(R.state){var I=e.getState(c),C=R.state.filter(Ro).map(this.getEventMapper());I.setUnknownStateEvents(C)}var x=R.end,O=R.chunk.filter(Ro).map(this.getEventMapper()),N=e.getTimelineSet();return N.addEventsToTimeline(O,l,!1,e,x),this.processAggregatedTimelineEvents(s,O),this.processThreadRoots(s,O,l),l&&R.end==R.start&&e.setPaginationToken(null,c),R.end!==R.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else if(a){var S,b,w=this.getRoom((S=e.getRoomId())!==null&&S!==void 0?S:void 0);if(!w)throw new Error("Unknown room "+e.getRoomId());var k=this.canSupport.get(vr.RelationsRecursion)!==gr.Unsupported;v=this.fetchRelations((b=e.getRoomId())!==null&&b!==void 0?b:"",a.id,null,null,{dir:c,limit:t.limit,from:u??void 0,recurse:k||void 0}).then(function(){var R=F(function*(I){var C=r.getEventMapper(),x=I.chunk.filter(Ro).filter(l2(a.id)).map(C);for(var O of x.slice().reverse()){yield a==null?void 0:a.processEvent(O);var N=O.getSender();(!l||(a==null?void 0:a.getEventReadUpTo(N))===null)&&w.addLocalEchoReceipt(N,O,vi.Read)}var D=I.next_batch,j=e.getTimelineSet();if(j.addEventsToTimeline(x,l,!1,e,D??null),!D&&l){var U,H,K=(U=a.rootEvent)!==null&&U!==void 0?U:C(yield r.fetchRoomEvent((H=e.getRoomId())!==null&&H!==void 0?H:"",a.id));j.addEventsToTimeline([K],!0,!1,e,null)}return r.processAggregatedTimelineEvents(j.room,x),l&&!D&&e.setPaginationToken(null,c),!!D});return function(I){return R.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}else{if(!s)throw new Error("Unknown room "+e.getRoomId());v=this.createMessagesRequest(e.getRoomId(),u,t.limit,c,e.getFilter()).then(R=>{if(R.state){var I=e.getState(c),C=R.state.filter(Ro).map(this.getEventMapper());I.setUnknownStateEvents(C)}var x=R.end,O=R.chunk.filter(Ro).map(this.getEventMapper()),N=e.getTimelineSet(),[D,,j]=s.partitionThreadedEvents(O);N.addEventsToTimeline(D,l,!1,e,x),this.processAggregatedTimelineEvents(s,D),this.processThreadRoots(s,D.filter(H=>H.getServerAggregatedRelation(Qt.name)),!1),j.forEach(H=>s.relations.aggregateChildEvent(H));var U=R.end===void 0||R.end===R.start;return l&&U&&e.setPaginationToken(null,c),!U}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=v}return v}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(t=this.peekSync)===null||t===void 0||t.stopPeeking(),this.peekSync=new gd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,r)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){var r=this.sendStateEvent(e,ee.RoomGuestAccess,{guest_access:t.allowJoin?Xb.CanJoin:Xb.Forbidden},""),i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,ee.RoomHistoryVisibility,{history_visibility:YP.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestTokenFromEndpoint(e,t){var r=this;return F(function*(){var i=Object.assign({},t);return r.http.request(ae.Post,e,void 0,i)})()}getRoomPushRule(e,t){if(this.pushRules){var r;return(r=this.pushRules[e])===null||r===void 0||(r=r.room)===null||r===void 0?void 0:r.find(i=>i.rule_id===t)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,r){var i,s=!1,o=this.getRoomPushRule(e,t);if(o!=null&&o.actions.includes(Gc.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,Lr.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,Lr.RoomSpecific,t,{actions:[Gc.DontNotify]});else if(!s){var a=ru();this.deletePushRule(e,Lr.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,Lr.RoomSpecific,t,{actions:[Gc.DontNotify]}).then(()=>{a.resolve()}).catch(l=>{a.reject(l)})}).catch(l=>{a.reject(l)}),i=a.promise}if(i)return new Promise((l,c)=>{i.then(()=>{this.getPushRules().then(u=>{this.pushRules=u,l()}).catch(u=>{c(u)})}).catch(u=>{this.getPushRules().then(f=>{this.pushRules=f,c(u)}).catch(f=>{c(u)})})})}searchMessageText(e){var t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){var t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:SH.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(r,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;var t={body:e._query,next_batch:e.next_batch},r=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,t){var r,i,s=t.search_categories.room_events;e.count=s.count,e.next_batch=s.next_batch;var o=new Set(s.highlights);e.highlights.forEach(m=>{o.add(m)}),e.highlights=Array.from(o);for(var a=this.getEventMapper(),l=(r=(i=s.results)===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0,c=0;c<l;c++){var u=OE.fromJson(s.results[c],a),f=this.getRoom(u.context.getEvent().getRoomId());if(f)for(var p of u.context.getTimeline())p.setMetadata(f.currentState,!1);e.results.push(u)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new gd(this,this.clientOpts,this.buildSyncApiOptions());return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then(()=>{this.logger.debug("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=void 0}),this.syncLeftRoomsPromise}createFilter(e){var t=Ie("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(ae.Post,t,void 0,e).then(r=>{var i=Bi.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,r){if(r){var i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}var s=Ie("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(ae.Get,s).then(o=>{var a=Bi.fromJson(e,t,o);return this.store.storeFilter(a),a})}getOrCreateFilter(e,t){var r=this;return F(function*(){var i=r.store.getFilterIdByName(e),s;if(i){try{var o=yield r.getFilter(r.credentials.userId,i,!0);if(o){var a=o.getDefinition(),l=t.getDefinition();Md(a,l)&&(s=i)}}catch(u){if(u.errcode!=="M_UNKNOWN"&&u.errcode!=="M_NOT_FOUND")throw u}s||r.store.setFilterIdByName(e,void 0)}if(s)return s;var c=yield r.createFilter(t.getDefinition());return r.store.setFilterIdByName(e,c.filterId),c.filterId})()}getOpenIdToken(){var e=Ie("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(ae.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(ae.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return F(function*(){if(e.canSupportVoip){var t=!1,r=e.turnServersExpiry-Date.now();if(r>xN)e.logger.debug("TURN creds are valid for another "+r+" ms: not fetching new ones."),t=!0;else{e.logger.debug("Fetching new TURN credentials");try{var i=yield e.turnServer();if(i.uris){e.logger.debug("Got TURN URIs: "+i.uris+" refresh in "+i.ttl+" secs");var s={urls:i.uris,username:i.username,credential:i.password};e.turnServers=[s],e.turnServersExpiry=Date.now()+i.ttl*1e3,t=!0,e.emit(Oe.TurnServers,e.turnServers)}}catch(o){e.logger.error("Failed to get TURN URIs",o),o.httpStatus===403?(e.logger.info("TURN access unavailable for this account: stopping credentials checks"),e.checkTurnServersIntervalID!==null&&globalThis.clearInterval(e.checkTurnServersIntervalID),e.checkTurnServersIntervalID=void 0,e.emit(Oe.TurnServersError,o,!0)):e.emit(Oe.TurnServersError,o,!1)}}return t}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=Ie("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(ae.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){var t=Ie("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(ae.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var t=Ie("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(ae.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return F(function*(){var t;e.clientWellKnownPromise=it.getRawClientConfig((t=e.getDomain())!==null&&t!==void 0?t:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(Oe.ClientWellKnown,e.clientWellKnown)})()}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){var e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(r=>{var[i,s]=r;return e.includes(typeof s)}).reduce((r,i)=>{var[s,o]=i;return r[s]=o,r},{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){var t=this;return F(function*(){var r=yield t.doesServerSupportUnstableFeature(HH),i=yield t.doesServerSupportUnstableFeature(BH),s=yield t.doesServerSupportUnstableFeature(VH);if(!r&&!i&&!s)throw Error("Server does not support the Mutual Rooms API");var o,a;s?(o="/uk.half-shot.msc2666/user/mutual_rooms",a={user_id:e}):(o=Ie("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var l=[],c=null;do{var u={};c!=null&&s&&(u.batch_token=c);var f=yield t.http.authedRequest(ae.Get,o,dr(dr({},a),u),void 0,{prefix:fr.Unstable});l.push(...f.joined),f.next_batch_token!==void 0?c=f.next_batch_token:c=null}while(c!=null);return l})()}getVersions(){var e=this;return F(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(ae.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(r=>{throw e.serverVersionsPromise=void 0,r});var t=yield e.serverVersionsPromise;return e.canSupport=yield Tse(t),e.serverVersionsPromise})()}isVersionSupported(e){var t=this;return F(function*(){var{versions:r}=yield t.getVersions();return r&&r.includes(e)})()}doesServerSupportUnstableFeature(e){var t=this;return F(function*(){var r=yield t.getVersions();if(!r)return!1;var i=r.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var t=this;return F(function*(){var r=yield t.getVersions();if(!r)return!1;var i=r.unstable_features,s=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i["io.element.e2ee_forced.".concat(s)]})()}doesServerSupportThread(){var e=this;return F(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:si.Stable,list:si.Stable,fwdPagination:si.Stable};try{var[t,r,i,s,o,a]=yield Promise.all([e.doesServerSupportUnstableFeature("org.matrix.msc3440"),e.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3856"),e.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3715"),e.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:H_(r,t),list:H_(s,i),fwdPagination:H_(a,o)}}catch{return{threads:si.None,list:si.None,fwdPagination:si.None}}})()}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!==null&&e!==void 0&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,r,i){var s=arguments,o=this;return F(function*(){var a,l,c=s.length>4&&s[4]!==void 0?s[4]:{dir:ht.Backward},u=i?o.getEncryptedIfNeededEventType(e,i):null,[f,p]=yield Promise.all([o.fetchRoomEvent(e,t),o.fetchRelations(e,t,r,u,c)]),m=o.getEventMapper(),v=f?m(f):void 0,g=p.chunk.map(m);if(u===ee.RoomMessageEncrypted){var S=v?g.concat(v):g;yield Promise.all(S.map(b=>o.decryptEventIfNeeded(b))),i!==null&&(g=g.filter(b=>b.getType()===i))}return v&&r===un.Replace&&(g=g.filter(b=>b.getSender()===v.getSender())),{originalEvent:v??null,events:g,nextBatch:(a=p.next_batch)!==null&&a!==void 0?a:null,prevBatch:(l=p.prev_batch)!==null&&l!==void 0?l:null}})()}generateClientSecret(){return bs(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case Ek.IS:return this.http.getUrl("/terms",void 0,Xa.V2,t);case Ek.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,t,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return r&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(t=this.idBaseUrl)!==null&&t!==void 0&&t.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=GT(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){var e;return(e=this.http.opts.refreshToken)!==null&&e!==void 0?e:null}setAccessToken(e){this.http.opts.accessToken=e,this.serverVersionsPromise=void 0}isLoggedIn(){return this.http.opts.accessToken!==void 0}makeTxnId(){return"m"+new Date().getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(ae.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,r,i,s,o,a){r&&(i.session=r);var l={auth:i,refresh_token:!0};return e!=null&&(l.username=e),t!=null&&(l.password=t),o!=null&&(l.guest_access_token=o),a!=null&&(l.inhibit_login=a),this.registerRequest(l)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,t){var r={};return t&&(r.kind=t),this.http.request(ae.Post,"/register",r,e)}refreshToken(e){var t=r=>this.http.authedRequest(ae.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return t(fr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return t(fr.V1);throw r})}loginFlows(){return this.http.request(ae.Get,"/login")}login(e,t){return this.loginRequest(dr(dr({},t),{},{type:e})).then(r=>(r.access_token&&r.user_id&&(this.http.opts.accessToken=r.access_token,this.credentials={userId:r.user_id}),r))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"sso",r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,s="/login/"+t+"/redirect";r&&(s+="/"+r);var o={redirectUrl:e,[Oae.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}loginRequest(e){var t=this;return F(function*(){return yield t.http.authedRequest(ae.Post,"/login",void 0,e)})()}logout(){var e=arguments,t=this;return F(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!1;return r&&(t.stopClient(),t.http.abort()),t.http.authedRequest(ae.Post,"/logout")})()}deactivateAccount(e,t){var r={};return e&&(r.auth=e),t!==void 0&&(r.erase=t),this.http.authedRequest(ae.Post,"/account/deactivate",void 0,r)}requestLoginToken(e){var t=this;return F(function*(){var r={auth:e};return t.http.authedRequest(ae.Post,"/login/get_token",void 0,r,{prefix:fr.V1})})()}getFallbackAuthUrl(e,t){var r=Ie("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:t}).href}createRoom(e){var t=this;return F(function*(){var r,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(r=t.identityServer)!==null&&r!==void 0&&r.getAccessToken){var s=yield t.identityServer.getAccessToken();if(s)for(var o of i)o.id_access_token=s}return t.http.authedRequest(ae.Post,"/createRoom",void 0,e)})()}fetchRelations(e,t,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:ht.Backward},o=s;fn.hasServerSideFwdPaginationSupport===si.Experimental&&(o=QA("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(vr.RelationsRecursion)===gr.Unstable&&(o=QA("recurse","org.matrix.msc3981.recurse",o));var a=XI(o),l="/rooms/$roomId/relations/$eventId";r!==null?(l+="/$relationType",i!==null&&(l+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
34
34
  relations as relationType is null`)),i=null);var c=Ie(l+"?"+a,{$roomId:e,$eventId:t,$relationType:r,$eventType:i});return this.http.authedRequest(ae.Get,c,void 0,void 0,{prefix:fr.V1})}roomState(e){var t=Ie("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(ae.Get,t)}fetchRoomEvent(e,t){var r=Ie("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(ae.Get,r)}members(e,t,r,i){var s={};t&&(s.membership=t),r&&(s.not_membership=r),i&&(s.at=i);var o=XI(s),a=Ie("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(ae.Get,a)}upgradeRoom(e,t){var r=Ie("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(ae.Post,r,void 0,{new_version:t})}getStateEvent(e,t,r){var i={$roomId:e,$eventType:t,$stateKey:r},s=Ie("/rooms/$roomId/state/$eventType",i);return r!==void 0&&(s=Ie(s+"/$stateKey",i)),this.http.authedRequest(ae.Get,s)}sendStateEvent(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},o={$roomId:e,$eventType:t,$stateKey:i},a=Ie("/rooms/$roomId/state/$eventType",o);return i!==void 0&&(a=Ie(a+"/$stateKey",o)),this.http.authedRequest(ae.Put,a,void 0,r,s)}roomInitialSync(e,t){var r,i=Ie("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(ae.Get,i,{limit:(r=t==null?void 0:t.toString())!==null&&r!==void 0?r:"30"})}setRoomReadMarkersHttpRequest(e,t,r,i){var s=this;return F(function*(){var o=Ie("/rooms/$roomId/read_markers",{$roomId:e}),a={[vi.FullyRead]:t,[vi.Read]:r};return((yield s.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield s.isVersionSupported("v1.4")))&&(a[vi.ReadPrivate]=i),s.http.authedRequest(ae.Post,o,void 0,a)})()}getJoinedRooms(){var e=Ie("/joined_rooms",{});return this.http.authedRequest(ae.Get,e)}getJoinedRoomMembers(e){var t=Ie("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(ae.Get,t)}publicRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{server:t,limit:r,since:i}=e,s=Mie(e,kae);if(Object.keys(s).length===0){var o={server:t,limit:r,since:i};return this.http.authedRequest(ae.Get,"/publicRooms",o)}else{var a={server:t},l=dr({limit:r,since:i},s);return this.http.authedRequest(ae.Post,"/publicRooms",a,l)}}createAlias(e,t){var r=Ie("/directory/room/$alias",{$alias:e}),i={room_id:t};return this.http.authedRequest(ae.Put,r,void 0,i)}deleteAlias(e){var t=Ie("/directory/room/$alias",{$alias:e});return this.http.authedRequest(ae.Delete,t)}getLocalAliases(e){var t=Ie("/rooms/$roomId/aliases",{$roomId:e}),r=fr.V3;return this.http.authedRequest(ae.Get,t,void 0,void 0,{prefix:r})}getRoomIdForAlias(e){var t=Ie("/directory/room/$alias",{$alias:e});return this.http.authedRequest(ae.Get,t)}getRoomDirectoryVisibility(e){var t=Ie("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(ae.Get,t)}setRoomDirectoryVisibility(e,t){var r=Ie("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(ae.Put,r,void 0,{visibility:t})}searchUserDirectory(e){var{term:t,limit:r}=e,i={search_term:t};return r!==void 0&&(i.limit=r),this.http.authedRequest(ae.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){var r=t?Ie("/profile/$userId/$info",{$userId:e,$info:t}):Ie("/profile/$userId",{$userId:e});return this.http.authedRequest(ae.Get,r)}doesServerSupportExtendedProfiles(){var e=this;return F(function*(){return e.doesServerSupportUnstableFeature(qH)})()}getExtendedProfileRequestPrefix(){var e=this;return F(function*(){return(yield e.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"))?fr.V3:"/_matrix/client/unstable/uk.tcpip.msc4133"})()}getExtendedProfile(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");return t.http.authedRequest(ae.Get,Ie("/profile/$userId",{$userId:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getExtendedProfileProperty(e,t){var r=this;return F(function*(){if(!(yield r.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=yield r.http.authedRequest(ae.Get,Ie("/profile/$userId/$key",{$userId:e,$key:t}),void 0,void 0,{prefix:yield r.getExtendedProfileRequestPrefix()});return i[t]})()}setExtendedProfileProperty(e,t){var r=this;return F(function*(){if(!(yield r.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=r.getUserId();yield r.http.authedRequest(ae.Put,Ie("/profile/$userId/$key",{$userId:i,$key:e}),void 0,{[e]:t},{prefix:yield r.getExtendedProfileRequestPrefix()})})()}deleteExtendedProfileProperty(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=t.getUserId();yield t.http.authedRequest(ae.Delete,Ie("/profile/$userId/$key",{$userId:r,$key:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}patchExtendedProfile(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=t.getUserId();return t.http.authedRequest(ae.Patch,Ie("/profile/$userId",{$userId:r}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}setExtendedProfile(e){var t=this;return F(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=t.getUserId();yield t.http.authedRequest(ae.Put,Ie("/profile/$userId",{$userId:r}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getThreePids(){return this.http.authedRequest(ae.Get,"/account/3pid")}addThreePidOnly(e){var t=this;return F(function*(){var r="/account/3pid/add";return t.http.authedRequest(ae.Post,r,void 0,e)})()}bindThreePid(e){var t=this;return F(function*(){var r="/account/3pid/bind";return t.http.authedRequest(ae.Post,r,void 0,e)})()}unbindThreePid(e,t){var r=this;return F(function*(){var i="/account/3pid/unbind",s={medium:e,address:t,id_server:r.getIdentityServerUrl(!0)};return r.http.authedRequest(ae.Post,i,void 0,s)})()}deleteThreePid(e,t){var r="/account/3pid/delete";return this.http.authedRequest(ae.Post,r,void 0,{medium:e,address:t})}setPassword(e,t,r){var i="/account/password",s={auth:e,new_password:t,logout_devices:r};return this.http.authedRequest(ae.Post,i,void 0,s)}getDevices(){return this.http.authedRequest(ae.Get,"/devices")}getDevice(e){var t=Ie("/devices/$device_id",{$device_id:e});return this.http.authedRequest(ae.Get,t)}setDeviceDetails(e,t){var r=Ie("/devices/$device_id",{$device_id:e});return this.http.authedRequest(ae.Put,r,void 0,t)}deleteDevice(e,t){var r=Ie("/devices/$device_id",{$device_id:e}),i={};return t&&(i.auth=t),this.http.authedRequest(ae.Delete,r,void 0,i)}deleteMultipleDevices(e,t){var r={devices:e};t&&(r.auth=t);var i="/delete_devices";return this.http.authedRequest(ae.Post,i,void 0,r)}getPushers(){var e=this;return F(function*(){var t=yield e.http.authedRequest(ae.Get,"/pushers");return(yield e.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(t.pushers=t.pushers.map(r=>(r.hasOwnProperty(ak.name)||(r[ak.name]=!0),r))),t})()}setPusher(e){var t="/pushers/set";return this.http.authedRequest(ae.Post,t,void 0,e)}removePusher(e,t){var r="/pushers/set",i={pushkey:e,app_id:t,kind:null};return this.http.authedRequest(ae.Post,r,void 0,i)}setLocalNotificationSettings(e,t){var r="".concat(C$.name,".").concat(e);return this.setAccountData(r,t)}getPushRules(){return this.http.authedRequest(ae.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=wo.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,r,i){var s=Ie("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this.http.authedRequest(ae.Put,s,void 0,i)}deletePushRule(e,t,r){var i=Ie("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this.http.authedRequest(ae.Delete,i)}setPushRuleEnabled(e,t,r,i){var s=Ie("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:r});return this.http.authedRequest(ae.Put,s,void 0,{enabled:i})}setPushRuleActions(e,t,r,i){var s=Ie("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:r});return this.http.authedRequest(ae.Put,s,void 0,{actions:i})}search(e,t){var{body:r,next_batch:i}=e,s={};return i&&(s.next_batch=i),this.http.authedRequest(ae.Post,"/search",s,r,{abortSignal:t})}uploadKeysRequest(e,t){return this.http.authedRequest(ae.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(ae.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e){var{token:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r={device_keys:{}};return t!==void 0&&(r.token=t),e.forEach(i=>{r.device_keys[i]=[]}),this.http.authedRequest(ae.Post,"/keys/query",void 0,r)}claimOneTimeKeys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"signed_curve25519",r=arguments.length>2?arguments[2]:void 0,i={};t===void 0&&(t="signed_curve25519");for(var[s,o]of e){var a=i[s]||{};qb(i,s,a),qb(a,o,t)}var l={one_time_keys:i};r&&(l.timeout=r);var c="/keys/claim";return this.http.authedRequest(ae.Post,c,void 0,l)}getKeyChanges(e,t){var r={from:e,to:t};return this.http.authedRequest(ae.Get,"/keys/changes",r)}uploadDeviceSigningKeys(e,t){var r=Object.assign({},t);return e&&Object.assign(r,{auth:e}),this.http.authedRequest(ae.Post,"/keys/device_signing/upload",void 0,r,{prefix:fr.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");var t=this.http.getUrl("/account/register",void 0,Xa.V2,this.idBaseUrl);return this.http.requestOtherUrl(ae.Post,t,e)}requestEmailToken(e,t,r,i,s){var o={client_secret:t,email:e,send_attempt:r==null?void 0:r.toString()};return i&&(o.next_link=i),this.http.idServerRequest(ae.Post,"/validate/email/requestToken",o,Xa.V2,s)}requestMsisdnToken(e,t,r,i,s,o){var a={client_secret:r,country:e,phone_number:t,send_attempt:i==null?void 0:i.toString()};return s&&(a.next_link=s),this.http.idServerRequest(ae.Post,"/validate/msisdn/requestToken",a,Xa.V2,o)}submitMsisdnToken(e,t,r,i){var s={sid:e,client_secret:t,token:r};return this.http.idServerRequest(ae.Post,"/validate/msisdn/submitToken",s,Xa.V2,i??void 0)}submitMsisdnTokenOtherUrl(e,t,r,i){var s={sid:t,client_secret:r,token:i};return this.http.requestOtherUrl(ae.Post,e,s)}getIdentityHashDetails(e){return this.http.idServerRequest(ae.Get,"/hash_details",void 0,Xa.V2,e)}identityHashedLookup(e,t){var r=this;return F(function*(){var i={},s=yield r.getIdentityHashDetails(t);if(!s||!s.lookup_pepper||!s.algorithms)throw new Error("Unsupported identity server: bad response");i.pepper=s.lookup_pepper;var o={};if(s.algorithms.includes("sha256"))i.addresses=yield Promise.all(e.map(function(){var p=F(function*(m){var v=m[0].toLowerCase(),g=m[1].toLowerCase(),S=yield xH("".concat(v," ").concat(g," ").concat(i.pepper)),b=PE(S);return o[b]=m[0],b});return function(m){return p.apply(this,arguments)}}())),i.algorithm="sha256";else if(s.algorithms.includes("none"))i.addresses=e.map(p=>{var m=p[0].toLowerCase(),v=p[1].toLowerCase(),g="".concat(m," ").concat(v);return o[g]=p[0],g}),i.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");var a=yield r.http.idServerRequest(ae.Post,"/lookup",i,Xa.V2,t);if(!(a!=null&&a.mappings))return[];var l=[];for(var c of Object.keys(a.mappings)){var u=a.mappings[c],f=o[c];if(!f)throw new Error("Identity server returned more results than expected");l.push({address:f,mxid:u})}return l})()}lookupThreePid(e,t,r){var i=this;return F(function*(){var s=yield i.identityHashedLookup([[t,e]],r),o=s.find(l=>l.address===t);if(!o)return{};var a={address:t,medium:e,mxid:o.mxid};return a})()}bulkLookupThreePids(e,t){var r=this;return F(function*(){var i=yield r.identityHashedLookup(e.map(l=>[l[1],l[0]]),t),s=[],o=function*(c){var u=e.find(f=>f[1]===c.address);if(!u)throw new Error("Identity sever returned unexpected results");s.push([u[0],c.address,c.mxid])};for(var a of i)yield*o(a);return{threepids:s}})()}getIdentityAccount(e){return this.http.idServerRequest(ae.Get,"/account",void 0,Xa.V2,e)}sendToDevice(e,t,r){var i=Ie("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:r||this.makeTxnId()}),s={messages:pd(t)},o=new Map;for(var[a,l]of t)o.set(a,Array.from(l.keys()));return this.logger.debug("PUT ".concat(i),o),this.http.authedRequest(ae.Put,i,void 0,s)}encryptAndSendToDevice(e,t,r){var i=this;return F(function*(){if(!i.cryptoBackend)throw new Error("Cannot encrypt to device event, your client does not support encryption.");var s=yield i.cryptoBackend.encryptToDeviceMessages(e,t,r);yield i.queueToDevice(s)})()}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(ae.Get,"/thirdparty/protocols").then(e=>{if(!e||typeof e!="object")throw new Error("/thirdparty/protocols did not return an object: ".concat(e));return e})}getThirdpartyLocation(e,t){var r=Ie("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(ae.Get,r,t)}getThirdpartyUser(e,t){var r=Ie("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(ae.Get,r,t)}getTerms(e,t){var r=this.termsUrlForService(e,t);return this.http.requestOtherUrl(ae.Get,r)}agreeToTerms(e,t,r,i){var s=this.termsUrlForService(e,t),o={Authorization:"Bearer "+r};return this.http.requestOtherUrl(ae.Post,s,{user_accepts:i},{headers:o})}reportEvent(e,t,r,i){var s=Ie("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(ae.Post,s,void 0,{score:r,reason:i})}reportRoom(e,t){var r=Ie("/rooms/$roomId/report",{$roomId:e});return this.http.authedRequest(ae.Post,r,void 0,{reason:t})}getRoomHierarchy(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0,o=Ie("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(i),max_depth:r==null?void 0:r.toString(),from:s,limit:t==null?void 0:t.toString()};return this.http.authedRequest(ae.Get,o,a,void 0,{prefix:fr.V1}).catch(l=>{if(l.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(ae.Get,o,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw l})}unstableCreateFileTree(e){var t=this;return F(function*(){var{room_id:r}=yield t.createRoom({name:e,preset:ME.PrivateChat,power_level_content_override:dr(dr({},Coe),{},{users:{[t.getUserId()]:100}}),creation_content:{[Kb]:Ph.Space},initial_state:[{type:rk.name,state_key:sk.name,content:{[ik.name]:!0}},{type:ee.RoomEncryption,state_key:"",content:{algorithm:"m.megolm.v1.aes-sha2"}}]});return new mN(t,r)})()}unstableGetFileTreeSpace(e){var t,r,i=this.getRoom(e);if((i==null?void 0:i.getMyMembership())!==qe.Join)return null;var s=i.currentState.getStateEvents(ee.RoomCreate,""),o=i.currentState.getStateEvents(rk.name,sk.name);if(!s)throw new Error("Expected single room create event");return!(o!=null&&(t=o.getContent())!==null&&t!==void 0&&t[ik.name])||((r=s.getContent())===null||r===void 0?void 0:r[Kb])!==Ph.Space?null:new mN(this,e)}slidingSync(e,t,r){var i={};e.pos&&(i.pos=e.pos,delete e.pos),e.timeout&&(i.timeout=e.timeout,delete e.timeout);var s=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(ae.Post,"/sync",i,e,{prefix:"/_matrix/client/unstable/org.matrix.simplified_msc3575",baseUrl:t,localTimeoutMs:s,abortSignal:r})}supportsThreads(){var e;return((e=this.clientOpts)===null||e===void 0?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){return this.canSupport.get(vr.IntentionalMentions)!==gr.Unsupported}getRoomSummary(e,t){var r=this;return F(function*(){var i={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{var s=Ie("/summary/$roomid",{$roomid:e});return yield r.http.authedRequest(ae.Get,s,{via:t},void 0,i)}catch(a){if(a instanceof bn&&a.errcode==="M_UNRECOGNIZED"){var o=Ie("/rooms/$roomid/summary",{$roomid:e});return yield r.http.authedRequest(ae.Get,o,{via:t},void 0,i)}else throw a}})()}processThreadEvents(e,t,r){e.processThreadedEvents(t,r)}processThreadRoots(e,t,r){this.supportsThreads()&&e.processThreadRoots(t,r)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){t!=null&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}whoami(){var e=this;return F(function*(){return e.http.authedRequest(ae.Get,"/account/whoami")})()}timestampToEvent(e,t,r){var i=this;return F(function*(){var s=Ie("/rooms/$roomId/timestamp_to_event",{$roomId:e}),o={ts:t.toString(),dir:r};try{return yield i.http.authedRequest(ae.Get,s,o,void 0,{prefix:fr.V1})}catch(a){if(a.errcode==="M_UNRECOGNIZED"&&(a.httpStatus===400||a.httpStatus===404||a.httpStatus===405))return yield i.http.authedRequest(ae.Get,s,o,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw a}})()}getAuthIssuer(){var e=this;return F(function*(){return e.http.request(ae.Get,"/auth_issuer",void 0,void 0,{prefix:fr.Unstable+"/org.matrix.msc2965"})})()}getAuthMetadata(){var e=this;return F(function*(){var t;try{t=yield e.http.request(ae.Get,"/auth_metadata",void 0,void 0,{prefix:fr.Unstable+"/org.matrix.msc2965"})}catch(i){if(i instanceof bn&&i.errcode==="M_UNRECOGNIZED"){var{issuer:r}=yield e.getAuthIssuer();return sL(r)}throw i}return oL(t)})()}}L(DE,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY");function PN(n){return Object.fromEntries(Object.entries(n).map(e=>{var[t,r]=e;return["".concat(pa,".").concat(t),r]}))}function KH(n,e){var t,r=n.getUserId(),i=e.getId(),s=n.getRoom(e.getRoomId());if(!(!s||!r||!i)){if(!s.findEventById(i)){A.info("Decrypted event ".concat(e.getId()," is not in room ").concat(s.roomId,": ignoring"));return}var o=!!e.threadRootId&&!e.isThreadRoot,a;if(o){var l=s.getThread(e.threadRootId);a=l?l.hasUserReadEvent(r,i):!0}else a=s.hasUserReadEvent(r,i);if(!a){var c=n.getPushActionsForEvent(e,!0),u=!!(c!=null&&(t=c.tweaks)!==null&&t!==void 0&&t.highlight);if(u){var f=s.getUnreadCountForEventContext(jt.Highlight,e)+1;o?s.setThreadUnreadNotificationCount(e.threadRootId,jt.Highlight,f):s.setUnreadNotificationCount(jt.Highlight,f)}var p=!!(c!=null&&c.notify);if(p){var m=s.getUnreadCountForEventContext(jt.Total,e)+1;o?s.setThreadUnreadNotificationCount(e.threadRootId,jt.Total,m):s.setUnreadNotificationCount(jt.Total,m)}}}}function up(n){return Lv(n)?wy:n.threadRootId}function Lv(n){if(!n.threadRootId||n.isThreadRoot)return!0;if(!n.isRelation())return A.warn("Event is not a relation or a thread root, but still has a threadRootId! id=".concat(n.getId())),!0;if(n.isRelation(Qt.name))return!1;var e=n.relationEventId===n.threadRootId;return e}function LN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function ON(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?LN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):LN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var yi=function(n){return n.New="Thread.new",n.Update="Thread.update",n.NewReply="Thread.newReply",n.ViewThread="Thread.viewThread",n.Delete="Thread.delete",n}({}),si=function(n){return n[n.None=0]="None",n[n.Experimental=1]="Experimental",n[n.Stable=2]="Stable",n}({});function H_(n,e){return n?si.Stable:e?si.Experimental:si.None}class fn extends J${constructor(e,t,r){var i,s;if(super(),i=this,this.id=e,this.rootEvent=t,L(this,"timelineSet",void 0),L(this,"_currentUserParticipated",!1),L(this,"reEmitter",void 0),L(this,"lastEvent",void 0),L(this,"replyCount",0),L(this,"lastPendingEvent",void 0),L(this,"pendingReplyCount",0),L(this,"room",void 0),L(this,"client",void 0),L(this,"pendingEventOrdering",void 0),L(this,"processRootEventPromise",void 0),L(this,"initialEventsFetched",!fn.hasServerSideSupport),L(this,"initalEventFetchProm",void 0),L(this,"replayEvents",[]),L(this,"onTimelineReset",F(function*(){yield i.processRootEventPromise,i.processRootEventPromise=void 0})),L(this,"onBeforeRedaction",(o,a)=>{o!=null&&o.isRelation(Qt.name)&&this.room.eventShouldLiveIn(o).threadId===this.id&&o.getId()!==this.id&&!a.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(yi.Update,this))}),L(this,"onRedaction",function(){var o=F(function*(a,l,c){if(c===i.id)if(i.replyCount<=0){for(var u of i.timeline)i.clearEventMetadata(u);i.lastEvent=i.rootEvent,i._currentUserParticipated=!1,i.emit(yi.Delete,i)}else{var f;((f=i.lastEvent)===null||f===void 0?void 0:f.getId())===a.getAssociatedId()&&(yield i.processRootEventPromise,i.processRootEventPromise=void 0),yield i.updateThreadMetadata()}});return function(a,l,c){return o.apply(this,arguments)}}()),L(this,"onTimelineEvent",(o,a,l)=>{if(!l){var c=o.getSender();c&&a&&this.shouldSendLocalEchoReceipt(c,o)&&a.addLocalEchoReceipt(c,o,vi.Read),o.getId()!==this.id&&o.isRelation(Qt.name)&&this.replyCount++}this.onEcho(o,l??!1)}),L(this,"onLocalEcho",o=>{this.onEcho(o,!1)}),L(this,"onEcho",function(){var o=F(function*(a,l){a.threadRootId===i.id&&i.lastEvent!==a&&(yield i.updateThreadMetadata(),a.isRelation(Qt.name)&&(l||(i.lastEvent=void 0,i.emit(yi.NewReply,i,a))))});return function(a,l){return o.apply(this,arguments)}}()),this.setMaxListeners(1e3),!(r!=null&&r.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=r.room,this.client=r.client,this.pendingEventOrdering=(s=r.pendingEventOrdering)!==null&&s!==void 0?s:cp.Chronological,this.timelineSet=new _h(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new Mp(this),this.reEmitter.reEmit(this.timelineSet,[ke.Timeline,ke.TimelineReset]),this.room.on(Mt.BeforeRedaction,this.onBeforeRedaction),this.room.on(ke.Redaction,this.onRedaction),this.room.on(ke.LocalEchoUpdated,this.onLocalEcho),this.room.on(ke.TimelineReset,this.onTimelineReset),this.timelineSet.on(ke.Timeline,this.onTimelineEvent),this.processReceipts(r.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}fetchRootEvent(){var e=this;return F(function*(){try{var t=yield e.client.fetchRoomEvent(e.roomId,e.id),r=e.client.getEventMapper();e.rootEvent=r(t)}catch(i){A.error("Failed to fetch thread root to construct thread with",i)}yield e.processEvent(e.rootEvent)})()}static setServerSideSupport(e){fn.hasServerSideSupport=e,e!==si.Stable&&(Dh.setPreferUnstable(!0),jh.setPreferUnstable(!0),Qt.setPreferUnstable(!0))}static setServerSideListSupport(e){fn.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){fn.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,t){var r,i=(r=this.client.canSupport.get(vr.RelationsRecursion))!==null&&r!==void 0?r:gr.Unsupported;if(i===gr.Unsupported){var s,o=(s=this.getReadReceiptForUserId(e))===null||s===void 0?void 0:s.eventId;if(o){var a=this.findEventById(o);if(a&&a.getTs()>t.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(Le.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState,addToState:!1})}insertEventIntoTimeline(e){var t=e.getId();t&&(this.findEventById(t)||this.timelineSet.insertEventIntoTimeline(e,this.liveTimeline,this.roomState,!1))}addEvents(e,t){e.forEach(r=>this.addEvent(r,t,!1)),this.updateThreadMetadata()}addEvent(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;this.setEventMetadata(e);var i=this.lastReply(),s=!i||e.localTimestamp>=i.localTimestamp;if(!fn.hasServerSideSupport)this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e);else if(e.isRelation(un.Annotation)||e.isRelation(un.Replace)){this.addRelatedThreadEvent(e,t);return}else!t&&s?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):t?this.addEventToTimeline(e,t):this.insertEventIntoTimeline(e);e.getId()!==this.id&&e.isRelation(Qt.name)&&!t&&s&&(this.lastEvent=void 0),r&&(this.emit(yi.NewReply,this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,t){var r,i;if(this.initialEventsFetched){var o,a=(o=this.client.canSupport.get(vr.RelationsRecursion))!==null&&o!==void 0?o:gr.Unsupported;a===gr.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,t)}else{var s;(s=this.replayEvents)===null||s===void 0||s.push(e)}(r=this.timelineSet.relations)===null||r===void 0||r.aggregateParentEvent(e),(i=this.timelineSet.relations)===null||i===void 0||i.aggregateChildEvent(e,this.timelineSet)}processEvent(e){var t=this;return F(function*(){e&&(t.setEventMetadata(e),yield t.fetchEditsWhereNeeded(e))})()}processReceipts(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];for(var{eventId:t,receiptType:r,userId:i,receipt:s,synthetic:o}of e)this.addReceiptToStructure(t,r,i,s,o)}getRootEventBundledRelationship(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.rootEvent;return e==null?void 0:e.getServerAggregatedRelation(Qt.name)}processRootEvent(){var e=this;return F(function*(){var t=e.getRootEventBundledRelationship();if(fn.hasServerSideSupport&&t){e.replyCount=t.count,e._currentUserParticipated=!!t.current_user_participated;var r=e.client.getEventMapper();e.lastEvent=r(ON(ON({},t.latest_event),{},{room_id:e.roomId})),e.updatePendingReplyCount(),yield e.processEvent(e.lastEvent)}})()}updatePendingReplyCount(){var e=this.pendingEventOrdering===cp.Detached?this.room.getPendingEvents():this.events,t=e.filter(r=>{var i;return r.threadRootId===this.id&&r.isRelation(Qt.name)&&r.status!==null&&r.getId()!==((i=this.lastEvent)===null||i===void 0?void 0:i.getId())});this.lastPendingEvent=t.length?t[t.length-1]:void 0,this.pendingReplyCount=t.length}resetLiveTimeline(e,t){var r=this;return F(function*(){var i=r.liveTimeline;r.timelineSet.resetLiveTimeline(e??void 0,t??void 0);var s=r.liveTimeline,o,a;if(e){var l=yield r.client.createMessagesRequest(r.roomId,e,1,ht.Forward);o=l.end}if(t){var c=yield r.client.createMessagesRequest(r.roomId,t,1,ht.Backward);a=c.start}t&&i.getPaginationToken(ht.Forward)===t&&i.setPaginationToken(a??null,ht.Forward),e&&s.getPaginationToken(ht.Backward)===e&&s.setPaginationToken(o??null,ht.Backward)})()}updateThreadFromRootEvent(){var e=this;return F(function*(){fn.hasServerSideSupport&&(!e.initialEventsFetched&&!e.lastEvent&&(yield e.processRootEvent()),yield e.fetchRootEvent()),yield e.processRootEvent()})()}updateThreadMetadata(){var e=this;return F(function*(){if(e.updatePendingReplyCount(),e.processRootEventPromise||(e.processRootEventPromise=e.updateThreadFromRootEvent()),yield e.processRootEventPromise,!e.initialEventsFetched)if(e.initalEventFetchProm)yield e.initalEventFetchProm;else try{e.timelineSet.resetLiveTimeline(),e.replyCount===0&&e.rootEvent?(e.timelineSet.addEventsToTimeline([e.rootEvent],!0,!1,e.liveTimeline,null),e.liveTimeline.setPaginationToken(null,ht.Backward)):(e.initalEventFetchProm=e.client.paginateEventTimeline(e.liveTimeline,{backwards:!0}),yield e.initalEventFetchProm),e.initialEventsFetched=!0;for(var t of e.replayEvents)e.addEvent(t,!1);e.replayEvents=null,e.emit(ke.TimelineReset,e.room,e.timelineSet,!0)}catch(r){A.error("Failed to load start of newly created thread: ",r),e.initialEventsFetched=!1}e.emit(yi.Update,e)})()}fetchEditsWhereNeeded(){var e=arguments,t=this;return F(function*(){var r,i=(r=t.client.canSupport.get(vr.RelationsRecursion))!==null&&r!==void 0?r:gr.Unsupported;if(i===gr.Unsupported){for(var s=e.length,o=new Array(s),a=0;a<s;a++)o[a]=e[a];return Promise.all(o.filter(Mae).map(function(){var l=F(function*(c){try{var u=yield t.client.relations(t.roomId,c.getId(),un.Replace,c.getType(),{limit:1});if(u.events.length){var f=u.events[0];c.makeReplaced(f),t.insertEventIntoTimeline(f)}}catch(p){A.error("Failed to load edits for encrypted thread event",p)}});return function(c){return l.apply(this,arguments)}}()))}})()}setEventMetadata(e){e&&(Le.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){if(e){var t;e.setThread(void 0),(t=e.event)===null||t===void 0||(t=t.unsigned)===null||t===void 0||(t=t["m.relations"])===null||t===void 0||delete t[Qt.name]}}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:i=>i.isRelation(Qt.name),t=this.timeline.length-1;t>=0;t--){var r=this.timeline[t];if(e(r))return r}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return(e=(t=this.lastPendingEvent)!==null&&t!==void 0?t:this.lastEvent)!==null&&e!==void 0?e:this.lastReply()}get timeline(){return this.events}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof wi}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){var r=e===this.client.getUserId(),i=this.timeline[this.timeline.length-1];if(r&&i){var s=i.getTs()<this.room.getOldestThreadedReceiptTs(),o=i.getId();if(s&&o)return o}var a=super.getEventReadUpTo(e,t);if(i){var l=this.room.getLastUnthreadedReceiptFor(e);if(!l)return a;for(var c=((u=this.timeline)===null||u===void 0?void 0:u.length)-1;c>=0;--c){var u,f,p=this.timeline[c];if(p.getId()===a)return a;if(p.getTs()<l.ts)return(f=p.getId())!==null&&f!==void 0?f:a}}return a}hasUserReadEvent(e,t){if(e===this.client.getUserId()){var r,i,s,o,a,l,c=((r=(i=this.lastReply())===null||i===void 0?void 0:i.getTs())!==null&&r!==void 0?r:0)<this.room.getOldestThreadedReceiptTs(),u=(s=(o=this.room.getLastUnthreadedReceiptFor(e))===null||o===void 0?void 0:o.ts)!==null&&s!==void 0?s:0,f=((a=this===null||this===void 0||(l=this.lastReply())===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0)<u;if(c||f)return!0}return this.room.hasUserReadEvent(e,t)}setUnread(e,t){return this.room.setThreadUnreadNotificationCount(this.id,e,t)}getLastUnthreadedReceiptFor(e){return this.room.getLastUnthreadedReceiptFor(e)}}L(fn,"hasServerSideSupport",si.None);L(fn,"hasServerSideListSupport",si.None);L(fn,"hasServerSideFwdPaginationSupport",si.None);function Mae(n){return n.isEncrypted()&&(n.isRelation(Qt.name)||n.isThreadRoot)}var Dh=new EE("related_by_senders","io.element.relation_senders"),jh=new EE("related_by_rel_types","io.element.relation_types"),Qt=new EE("m.thread","io.element.thread"),So=function(n){return n[n.My=0]="My",n[n.All=1]="All",n}({});function GH(n){switch(n){case So.My:return"participated";default:return"all"}}class MN extends Error{constructor(e,t,r){super(t),this.code=e,L(this,"detailedString",void 0),this.name="DecryptionError",this.detailedString=Aae(this,r)}}function Aae(n,e){var t=n.name+"[msg: "+n.message;return e&&(t+=", "+Object.keys(e).map(r=>r+": "+e[r]).join(", ")),t+="]",t}var AN=Object.freeze({visible:!0}),Mt=function(n){return n.Decrypted="Event.decrypted",n.BeforeRedaction="Event.beforeRedaction",n.VisibilityChange="Event.visibilityChange",n.LocalEventIdReplaced="Event.localEventIdReplaced",n.Status="Event.status",n.Replaced="Event.replaced",n.RelationsCreated="Event.relationsCreated",n.SentinelUpdated="Event.sentinelUpdated",n}({});class wi extends En{setMetadata(e,t){var r,i,s=this.isState()&&this.getType()===ee.RoomMember&&this.getSender()===this.getStateKey(),o=!1;if(s||!((r=this.sender)!==null&&r!==void 0&&(r=r.events)!==null&&r!==void 0&&r.member)){var a=e.getSentinelMember(this.getSender());a!==this.sender&&(o=!0),this.sender=a}if(s||!((i=this.target)!==null&&i!==void 0&&(i=i.events)!==null&&i!==void 0&&i.member)&&this.getType()===ee.RoomMember){var l=e.getSentinelMember(this.getStateKey());l!==this.target&&(o=!0),this.target=l}this.isState()&&t&&(this.forwardLooking=!1),o&&this.emit(Mt.SentinelUpdated)}constructor(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.event=t,L(this,"pushDetails",{}),L(this,"_replacingEvent",null),L(this,"_localRedactionEvent",null),L(this,"_isCancelled",!1),L(this,"clearEvent",void 0),L(this,"visibility",AN),L(this,"_hasCachedExtEv",!1),L(this,"_cachedExtEv",void 0),L(this,"_decryptionFailureReason",null),L(this,"senderCurve25519Key",null),L(this,"claimedEd25519Key",null),L(this,"forwardingCurve25519KeyChain",[]),L(this,"untrusted",null),L(this,"decryptionPromise",null),L(this,"retryDecryption",!1),L(this,"txnId",void 0),L(this,"thread",void 0),L(this,"threadId",void 0),L(this,"localTimestamp",void 0),L(this,"sender",null),L(this,"target",null),L(this,"status",null),L(this,"error",null),L(this,"forwardLooking",!0),L(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach(i=>{typeof t[i]=="string"&&(t[i]=KT(t[i]))}),["membership","avatar_url","displayname"].forEach(i=>{var s;typeof((s=t.content)===null||s===void 0?void 0:s[i])=="string"&&(t.content[i]=KT(t.content[i]))}),["rel_type"].forEach(i=>{var s;typeof((s=t.content)===null||s===void 0||(s=s["m.relates_to"])===null||s===void 0?void 0:s[i])=="string"&&(t.content["m.relates_to"][i]=KT(t.content["m.relates_to"][i]))}),this.txnId=t.txn_id;var r=this.getAge();this.localTimestamp=r!==void 0?Date.now()-r:(e=this.getTs())!==null&&e!==void 0?e:Date.now(),this.reEmitter=new Mp(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=is.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){var e=Object.assign({},this.getContent());if(this.getWireType()===ee.RoomMessageEncrypted)for(var[t,r]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||e[t]===void 0&&(e[t]=r);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getDetails(){var e=this.getRoomId();if(e){var t;return"id=".concat(this.getId()," type=").concat(this.getWireType()," sender=").concat(this.getSender()," room=").concat(e," ts=").concat((t=this.getDate())===null||t===void 0?void 0:t.toISOString())}else{var r=this.getContent()[IE];return"msgid=".concat(r," type=").concat(this.getWireType()," sender=").concat(this.getSender())}}getOriginalContent(){var e;if(this._localRedactionEvent)return{};if(this.clearEvent){var t;return(t=this.clearEvent.content)!==null&&t!==void 0?t:{}}return(e=this.event.content)!==null&&e!==void 0?e:{}}getContent(){if(this._localRedactionEvent)return{};if(this._replacingEvent){var e;return(e=this._replacingEvent.getContent()["m.new_content"])!==null&&e!==void 0?e:{}}else return this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e;if(!this.isState()){var t=(e=this.getWireContent())===null||e===void 0?void 0:e["m.relates_to"];if((t==null?void 0:t.rel_type)===Qt.name)return t.event_id;if(this.thread)return this.thread.id;if(this.threadId!==void 0)return this.threadId;var r=this.getUnsigned();if(typeof r[Gb.name]=="string")return r[Gb.name]}}get isThreadRoot(){if(this.isState())return!1;var e=this.getServerAggregatedRelation(Qt.name);return!!e||this.threadRootId===this.getId()}get replyEventId(){var e;return(e=this.getWireContent()["m.relates_to"])===null||e===void 0||(e=e["m.in_reply_to"])===null||e===void 0?void 0:e.event_id}get relationEventId(){var e;return(e=this.getWireContent())===null||e===void 0||(e=e["m.relates_to"])===null||e===void 0?void 0:e.event_id}getPrevContent(){return this.getUnsigned().prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return this.event.state_key!==void 0}getMembershipAtEvent(){var e=this.getUnsigned();return T$.findIn(e)}makeEncrypted(e,t,r,i){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=r,this.claimedEd25519Key=i}isBeingDecrypted(){return this.decryptionPromise!=null}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){return this._decryptionFailureReason!==null}get decryptionFailureReason(){return this._decryptionFailureReason}get isEncryptedDisabledForUnverifiedDevices(){return this.decryptionFailureReason===bN.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}attemptDecryption(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(!r.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");var s=r.clearEvent&&!r.isDecryptionFailure(),o=i.forceRedecryptIfUntrusted&&r.isKeySourceUntrusted();if(s&&!o)throw new Error("Attempt to decrypt event which has already been decrypted");return r.decryptionPromise?(A.log("Event ".concat(r.getId()," already being decrypted; queueing a retry")),r.retryDecryption=!0,r.decryptionPromise):(r.decryptionPromise=r.decryptionLoop(e,i),r.decryptionPromise)})()}getKeyRequestRecipients(e){var t=[{userId:e,deviceId:"*"}];return t}decryptionLoop(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};for(yield Promise.resolve();;){r.retryDecryption=!1;var s=void 0;try{var o=yield e.decryptEvent(r);i.isRetry===!0&&A.info("Decrypted event on retry (".concat(r.getDetails(),")")),r.setClearData(o),r._decryptionFailureReason=null}catch(l){var a=l instanceof MN?l.detailedString:String(l);if(s=l,r.retryDecryption){A.log("Error decrypting event (".concat(r.getDetails(),"), but retrying: ").concat(a));continue}A.warn("Error decrypting event (".concat(r.getDetails(),"): ").concat(a)),r.setClearDataForDecryptionFailure(String(l)),r._decryptionFailureReason=l instanceof MN?l.code:bN.UNKNOWN_ERROR}r.decryptionPromise=null,r.retryDecryption=!1,r.setPushDetails(),i.emit!==!1&&r.emit(Mt.Decrypted,r,s);return}})()}setClearData(e){var t,r;this.clearEvent=e.clearEvent,this.senderCurve25519Key=(t=e.senderCurve25519Key)!==null&&t!==void 0?t:null,this.claimedEd25519Key=(r=e.claimedEd25519Key)!==null&&r!==void 0?r:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}setClearDataForDecryptionFailure(e){this.clearEvent={type:ee.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: ".concat(e," **")}},this.senderCurve25519Key=null,this.claimedEd25519Key=null,this.forwardingCurve25519KeyChain=[],this.untrusted=!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===ee.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return this.claimedEd25519Key?{ed25519:this.claimedEd25519Key}:{}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return!!this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(e){this.event.unsigned=e}unmarkLocallyRedacted(){var e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(Mt.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,r,i=(t=e==null?void 0:e.visible)!==null&&t!==void 0?t:!0,s=(r=e==null?void 0:e.reason)!==null&&r!==void 0?r:null,o=!1;(this.visibility.visible!==i||!this.visibility.visible&&this.visibility.reason!==s)&&(o=!0),o&&(i?this.visibility=AN:this.visibility=Object.freeze({visible:!1,reason:s}),this.emit(Mt.VisibilityChange,this,i))}messageVisibility(){return this.visibility}makeRedacted(e,t){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(Mt.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(var r in this.event)this.event.hasOwnProperty(r)&&!Nae.has(r)&&delete this.event[r];this.isEncrypted()&&(this.clearEvent=void 0);var i=this.getType()in NN?NN[this.getType()]:{},s=this.getContent();for(var o in s)s.hasOwnProperty(o)&&!i[o]&&delete s[o];!this.isThreadRoot&&this.threadRootId&&this.threadRootId!==this.getId()&&(this.moveAllRelatedToMainTimeline(t),e.moveToMainTimeline(t)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){var t=this.thread;if(this.moveToMainTimeline(e),t)for(var r of t.events){var i;((i=r.getRelation())===null||i===void 0?void 0:i.event_id)===this.getId()&&r.moveAllRelatedToMainTimeline(e)}}moveToMainTimeline(e){var t;(t=this.thread)===null||t===void 0||t.timelineSet.removeEvent(this.getId()),this.setThread(void 0);var r=e.getLiveTimeline();r.getTimelineSet().insertEventIntoTimeline(this,r,r.getState(Le.FORWARDS),!1)}isRedacted(){return!!this.getUnsigned().redacted_because}isRedaction(){return this.getType()===ee.RoomRedaction}asVisibilityChange(){if(!md.matches(this.getType()))return null;var e=this.getRelation();if(!e||e.rel_type!="m.reference")return null;var t=e.event_id;if(!t)return null;var r=this.getWireContent(),i=!!r.visible,s=r.reason;return s&&typeof s!="string"?null:{visible:i,reason:s,eventId:t}}isVisibilityEvent(){return md.matches(this.getType())}getRedactionEvent(){var e,t;if(!this.isRedacted())return null;if((e=this.clearEvent)!==null&&e!==void 0&&e.unsigned){var r,i;return(r=(i=this.clearEvent)===null||i===void 0?void 0:i.unsigned.redacted_because)!==null&&r!==void 0?r:null}else return(t=this.event.unsigned)!==null&&t!==void 0&&t.redacted_because?this.event.unsigned.redacted_because:{}}getPushActions(){return this.pushDetails.actions||null}getPushDetails(){return this.pushDetails}setPushDetails(e,t){this.pushDetails={actions:e,rule:t}}handleRemoteEcho(e){var t,r=this.getUnsigned(),i=this.getId();this.event=e,r.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=r.redacted_because),this.setStatus(null),this.getId()!==i&&this.emit(Mt.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-((t=this.getAge())!==null&&t!==void 0?t:0)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(Mt.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(Mt.LocalEventIdReplaced,this)}isRelation(e){var t,r=(t=this.getWireContent())===null||t===void 0?void 0:t["m.relates_to"];return this.isState()&&(r!=null&&r.rel_type)&&[un.Replace,un.Thread].includes(r.rel_type)?!1:!!(r!=null&&r.rel_type&&r.event_id&&(!e||r.rel_type===e))}getRelation(){var e;return this.isRelation()&&(e=this.getWireContent()["m.relates_to"])!==null&&e!==void 0?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=e??null,this.emit(Mt.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return(t=this.getUnsigned()["m.relations"])===null||t===void 0?void 0:t[e]}replacingEventId(){var e=this.getServerAggregatedRelation(un.Replace);if(e)return e.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e=this.getServerAggregatedRelation(un.Replace);if(e){var t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent){var r;return(r=this._replacingEvent.getDate())!==null&&r!==void 0?r:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){var e=this.getRelation();if(this.replyEventId)return this.replyEventId;if(e)return e.event_id;if(this.isRedaction())return this.event.redacts}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){var t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){var e=new wi(JSON.parse(JSON.stringify(this.event)));for(var[t,r]of Object.entries(this))t!=="event"&&(e[t]=r);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;var t=ZI(this.event),r=ZI(e.event);return JSON.stringify(t)===JSON.stringify(r)}toJSON(){var e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.isState()||(this.thread&&this.reEmitter.stopReEmitting(this.thread,[yi.Update]),this.thread=e,this.setThreadId(e==null?void 0:e.id),e&&this.reEmitter.reEmit(e,[yi.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}}var Nae=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),NN={[ee.RoomMember]:{membership:1},[ee.RoomJoinRules]:{join_rule:1},[ee.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}},fs=function(n){return n[n.NotStarted=0]="NotStarted",n[n.InProgress=1]="InProgress",n[n.Finished=2]="Finished",n}(fs||{}),ut=function(n){return n.Events="RoomState.events",n.Members="RoomState.members",n.NewMember="RoomState.newMember",n.Update="RoomState.update",n.BeaconLiveness="RoomState.BeaconLiveness",n.Marker="RoomState.Marker",n}({});class Ov extends En{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{status:fs.NotStarted};super(),this.roomId=e,this.oobMemberFlags=t,L(this,"reEmitter",new Mp(this)),L(this,"sentinels",{}),L(this,"displayNameToUserIds",new Map),L(this,"userIdsToDisplayNames",{}),L(this,"tokenToInvite",{}),L(this,"joinedMemberCount",null),L(this,"summaryJoinedMemberCount",null),L(this,"invitedMemberCount",null),L(this,"summaryInvitedMemberCount",null),L(this,"modified",-1),L(this,"members",{}),L(this,"events",new Map),L(this,"paginationToken",null),L(this,"beacons",new Map),L(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((e,t)=>t.membership===qe.Join?e+1:e,0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return this.summaryInvitedMemberCount!==null?this.summaryInvitedMemberCount:(this.invitedMemberCount===null&&(this.invitedMemberCount=this.getMembers().reduce((e,t)=>t.membership===qe.Invite?e+1:e,0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter(t=>!e.includes(t.userId))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;var t=this.sentinels[e];if(t===void 0){t=new wv(this.roomId,e);var r=this.members[e];r!=null&&r.events.member&&t.setMembershipEvent(r.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return t===void 0?[]:null;if(t===void 0)return Array.from(this.events.get(e).values());var r=this.events.get(e).get(t);return r||null}get hasLiveBeacons(){var e;return!!((e=this.liveBeaconIds)!==null&&e!==void 0&&e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){var e=new Ov(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=fs.NotStarted,Array.from(this.events.values()).forEach(r=>{e.setStateEvents(Array.from(r.values()))}),this.oobMemberFlags.status=t,this.summaryInvitedMemberCount!==null&&e.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==fs.Finished&&this.getMembers().forEach(r=>{if(r.isOutOfBand()){var i;(i=e.getMember(r.userId))===null||i===void 0||i.markOutOfBand()}}),e}setUnknownStateEvents(e){var t=e.filter(r=>!this.events.has(r.getType())||!this.events.get(r.getType()).has(r.getStateKey()));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach(r=>{if(!(r.getRoomId()!==this.roomId||!r.isState())){JP.matches(r.getType())&&this.setBeacon(r);var i=this.getStateEventMatching(r);if(this.setStateEvent(r),r.getType()===ee.RoomMember){var s;this.updateDisplayNameCache(r.getStateKey(),(s=r.getContent().displayname)!==null&&s!==void 0?s:""),this.updateThirdPartyTokenCache(r)}this.emit(ut.Events,r,this,i)}}),this.onBeaconLivenessChange(),e.forEach(r=>{if(!(r.getRoomId()!==this.roomId||!r.isState()))if(r.getType()===ee.RoomMember){var i=r.getStateKey();(r.getContent().membership===qe.Leave||r.getContent().membership===qe.Ban)&&(r.getContent().avatar_url=r.getContent().avatar_url||r.getPrevContent().avatar_url,r.getContent().displayname=r.getContent().displayname||r.getPrevContent().displayname);var s=this.getOrCreateMember(i,r);s.setMembershipEvent(r,this),this.updateMember(s),this.emit(ut.Members,r,this,s)}else if(r.getType()===ee.RoomPowerLevels){if(r.getStateKey()!=="")return;var o=Object.values(this.members);o.forEach(a=>{var l=a.getLastModifiedTime();a.setPowerLevelEvent(r),l!==a.getLastModifiedTime()&&this.emit(ut.Members,r,this,a)}),this.sentinels={}}else E$.matches(r.getType())&&this.emit(ut.Marker,r,t)}),this.emit(ut.Update,this)}processBeaconEvents(e,t){var r=this;return F(function*(){if(!(!e.length||!r.beacons.size)){var i=[...r.beacons.values()].reduce((c,u)=>(c[u.beaconInfoId]=u,c),{}),s=(c,u)=>{if(Ck.matches(u.getType())){var f=i[c];f&&f.addLocations([u])}},o=function*(u){var f,p=(f=u.getRelation())===null||f===void 0?void 0:f.event_id;if(!p||!i[p])return{v:void 0};if(!Ck.matches(u.getType())&&!u.isEncrypted())return{v:void 0};try{yield t.decryptEventIfNeeded(u),s(p,u)}catch{u.isDecryptionFailure()&&u.once(Mt.Decrypted,F(function*(){s(p,u)}))}},a;for(var l of e)if(a=yield*o(l),a)return a.v}})()}getOrCreateMember(e,t){var r=this.members[e];return r||(r=new wv(this.roomId,e),this.members[e]=r,this.emit(ut.NewMember,t,this,r)),r}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){var t=zb(e);if(this.beacons.has(t)){var r=this.beacons.get(t);if(e.isRedacted()){var i;r.beaconInfoId===((i=e.getRedactionEvent())===null||i===void 0?void 0:i.redacts)&&(r.destroy(),this.beacons.delete(t));return}return r.update(e)}if(!e.isRedacted()){var s=new z$(e);this.reEmitter.reEmit(s,[yn.New,yn.Update,yn.Destroy,yn.LivenessChange]),this.emit(yn.New,e,s),s.on(yn.LivenessChange,this.onBeaconLivenessChange.bind(this)),s.on(yn.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(s.identifier,s)}}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(e=>e.isLive).map(e=>e.identifier),this.emit(ut.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,r;return(t=(r=this.events.get(e.getType()))===null||r===void 0?void 0:r.get(e.getStateKey()))!==null&&t!==void 0?t:null}updateMember(e){var t=this.getStateEvents(ee.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===fs.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===fs.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===fs.NotStarted&&(this.oobMemberFlags.status=fs.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===fs.InProgress&&(this.oobMemberFlags.status=fs.NotStarted)}clearOutOfBandMembers(){var e=0;Object.keys(this.members).forEach(t=>{var r=this.members[t];r.isOutOfBand()&&(++e,delete this.members[t])}),A.log("LL: RoomState removed ".concat(e," members...")),this.oobMemberFlags.status=fs.NotStarted}setOutOfBandMembers(e){A.log("LL: RoomState about to set ".concat(e.length," OOB members ...")),this.oobMemberFlags.status===fs.InProgress&&(A.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=fs.Finished,e.forEach(t=>this.setOutOfBandMember(t)),this.emit(ut.Update,this))}setOutOfBandMember(e){if(e.getType()===ee.RoomMember){var t=e.getStateKey(),r=this.getMember(t);if(!(r&&!r.isOutOfBand())){var i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),i.markOutOfBand(),this.updateDisplayNameCache(i.userId,i.name),this.setStateEvent(e),this.updateMember(i),this.emit(ut.Members,e,this,i)}}}setTypingEvent(e){Object.values(this.members).forEach(function(t){t.setTypingEvent(e)})}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return(t=this.displayNameToUserIds.get(Kc(e)))!==null&&t!==void 0?t:[]}maySendRedactionForEvent(e,t){var r=this.getMember(t);if(!r||r.membership===qe.Leave||e.status||e.isRedacted())return!1;var i=this.maySendEvent(ee.RoomRedaction,t);return i?e.getSender()===t?!0:this.hasSufficientPowerLevelFor("redact",r.powerLevel):!1}hasSufficientPowerLevelFor(e,t){var r=this.getStateEvents(ee.RoomPowerLevels,""),i={};r&&(i=r.getContent());var s=50;return e5(i[e])&&(s=i[e]),t>=s}maySendMessage(e){return this.maySendEventOfType(ee.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return t.isGuest()||!t.credentials.userId?!1:this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,r){var i=this.getStateEvents(ee.RoomPowerLevels,""),s,o={},a=0,l=0,c=0;if(i){s=i.getContent(),o=s.events||{},Number.isSafeInteger(s.state_default)?a=s.state_default:a=50;var u=s.users&&s.users[t];Number.isSafeInteger(u)?c=u:Number.isSafeInteger(s.users_default)&&(c=s.users_default),Number.isSafeInteger(s.events_default)&&(l=s.events_default)}var f=r?a:l;return Number.isSafeInteger(o[e])&&(f=o[e]),c>=f}mayTriggerNotifOfType(e,t){var r=this.getMember(t);if(!r)return!1;var i=this.getStateEvents(ee.RoomPowerLevels,""),s=50;return i&&i.getContent()&&i.getContent().notifications&&e5(i.getContent().notifications[e])&&(s=i.getContent().notifications[e]),r.powerLevel>=s}getJoinRule(){var e,t=this.getStateEvents(ee.RoomJoinRules,""),r=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return r.join_rule||Wc.Invite}getHistoryVisibility(){var e,t=this.getStateEvents(ee.RoomHistoryVisibility,""),r=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return r.history_visibility||YP.Shared}getGuestAccess(){var e,t=this.getStateEvents(ee.RoomGuestAccess,""),r=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return r.guest_access||Xb.Forbidden}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(e){var t=this.getStateEvents(ee.RoomPredecessor,"");if(t){var r=t.getContent(),i=r.predecessor_room_id,s=r.last_known_event_id;typeof s!="string"&&(s=void 0);var o=r.via_servers;if(Array.isArray(o)||(o=void 0),typeof i=="string")return{roomId:i,eventId:s,viaServers:o}}}var a=this.getStateEvents(ee.RoomCreate,"");if(a){var l=a.getContent().predecessor;if(l){var c=l.room_id;if(typeof c=="string"){var u=l.event_id;return(typeof u!="string"||u==="")&&(u=void 0),{roomId:c,eventId:u}}}}return null}updateThirdPartyTokenCache(e){if(e.getContent().third_party_invite){var t=(e.getContent().third_party_invite.signed||{}).token;if(t){var r=this.getStateEvents(ee.RoomThirdPartyInvite,t);r&&(this.tokenToInvite[t]=e)}}}updateDisplayNameCache(e,t){var r=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],r){var i=Kc(r),s=this.displayNameToUserIds.get(i);if(s){var o=s.filter(u=>u!==e);this.displayNameToUserIds.set(i,o)}}this.userIdsToDisplayNames[e]=t;var a=t&&Kc(t);if(a){var l,c=(l=this.displayNameToUserIds.get(a))!==null&&l!==void 0?l:[];c.push(e),this.displayNameToUserIds.set(a,c)}}}function DN(n){var e=typeof n=="string"&&!!n&&n!=="undefined"&&n!=="null";return e||typeof n=="number"}class Mv{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};L(this,"rooms",{}),L(this,"users",{}),L(this,"syncToken",null),L(this,"filters",new _l(()=>new Map)),L(this,"accountData",new Map),L(this,"localStorage",void 0),L(this,"oobMembers",new Map),L(this,"pendingEvents",{}),L(this,"clientOptions",void 0),L(this,"pendingToDeviceBatches",[]),L(this,"nextToDeviceBatchId",0),L(this,"createUser",void 0),L(this,"onRoomMember",(t,r,i)=>{var s;if(i.membership!==qe.Invite){var o=this.users[i.userId]||((s=this.createUser)===null||s===void 0?void 0:s.call(this,i.userId));i.name&&(o.setDisplayName(i.name),i.events.member&&o.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&o.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[o.userId]=o}}),this.localStorage=e.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(e){this.syncToken=e}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on(ut.Members,this.onRoomMember),e.currentState.getMembers().forEach(t=>{this.onRoomMember(null,e.currentState,t)})}setUserCreator(e){this.createUser=e}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(ut.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map(function(e){return e.summary})}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,r,i){}storeFilter(e){!(e!=null&&e.userId)||!(e!=null&&e.filterId)||this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var r;return((r=this.filters.get(e))===null||r===void 0?void 0:r.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;var t="mxjssdk_memory_filter_"+e;try{var r=this.localStorage.getItem(t);if(DN(r))return r}catch{}return null}setFilterIdByName(e,t){if(this.localStorage){var r="mxjssdk_memory_filter_"+e;try{DN(t)?this.localStorage.setItem(r,t):this.localStorage.removeItem(r)}catch{}}}storeAccountDataEvents(e){e.forEach(t=>{var r=!Object.keys(t.getContent()).length;r?this.accountData.delete(t.getType()):this.accountData.set(t.getType(),t)})}getAccountData(e){return this.accountData.get(e)}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){return Promise.resolve()}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters=new _l(()=>new Map),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,t){return this.oobMembers.set(e,t),Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers.delete(e),Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}getPendingEvents(e){var t=this;return F(function*(){var r;return(r=t.pendingEvents[e])!==null&&r!==void 0?r:[]})()}setPendingEvents(e,t){var r=this;return F(function*(){r.pendingEvents[e]=t})()}saveToDeviceBatches(e){for(var t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}getOldestToDeviceBatch(){var e=this;return F(function*(){return e.pendingToDeviceBatches.length===0?null:e.pendingToDeviceBatches[0]})()}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(t=>t.id!==e),Promise.resolve()}destroy(){return F(function*(){})()}}var WH=(n=>(n.ToWidget="toWidget",n.FromWidget="fromWidget",n))(WH||{});function Dae(n){if(n==="toWidget")return"fromWidget";if(n==="fromWidget")return"toWidget";throw new Error("Invalid direction")}var Tc=(n=>(n.MSC2762="org.matrix.msc2762",n.MSC2871="org.matrix.msc2871",n.MSC2873="org.matrix.msc2873",n.MSC2931="org.matrix.msc2931",n.MSC2974="org.matrix.msc2974",n.MSC2876="org.matrix.msc2876",n.MSC3819="org.matrix.msc3819",n.MSC3846="town.robin.msc3846",n.MSC3869="org.matrix.msc3869",n.MSC3973="org.matrix.msc3973",n.MSC4039="org.matrix.msc4039",n))(Tc||{});const jae=["0.0.1","0.0.2","org.matrix.msc2762","org.matrix.msc2871","org.matrix.msc2873","org.matrix.msc2931","org.matrix.msc2974","org.matrix.msc2876","org.matrix.msc3819","town.robin.msc3846","org.matrix.msc3869","org.matrix.msc3973","org.matrix.msc4039"];class Uae extends RE.EventEmitter{constructor(e,t,r,i){super(),this.sendDirection=e,this.initialWidgetId=t,this.transportWindow=r,this.inboundWindow=i,this.strictOriginCheck=!1,this.targetOrigin="*",this.timeoutSeconds=10,this._ready=!1,this._widgetId=null,this.outboundRequests=new Map,this.stopController=new AbortController,this._widgetId=t}get ready(){return this._ready}get widgetId(){return this._widgetId||null}get nextRequestId(){const e=`widgetapi-${Date.now()}`;let t=0,r=e;for(;this.outboundRequests.has(r);)r=`${e}-${t++}`;return this.outboundRequests.set(r,null),r}sendInternal(e){console.log(`[PostmessageTransport] Sending object to ${this.targetOrigin}: `,e),this.transportWindow.postMessage(e,this.targetOrigin)}reply(e,t){return this.sendInternal({...e,response:t})}send(e,t){return this.sendComplete(e,t).then(r=>r.response)}sendComplete(e,t){if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));const r={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:e,data:t};return e===mr.UpdateVisibility&&(r.visible=t.visible),new Promise((i,s)=>{const o=f=>{u(),i(f)},a=f=>{u(),s(f)},l=setTimeout(()=>a(new Error("Request timed out")),(this.timeoutSeconds||1)*1e3),c=()=>a(new Error("Transport stopped"));this.stopController.signal.addEventListener("abort",c);const u=()=>{this.outboundRequests.delete(r.requestId),clearTimeout(l),this.stopController.signal.removeEventListener("abort",c)};this.outboundRequests.set(r.requestId,{request:r,resolve:o,reject:a}),this.sendInternal(r)})}start(){this.inboundWindow.addEventListener("message",e=>{this.handleMessage(e)}),this._ready=!0}stop(){this._ready=!1,this.stopController.abort()}handleMessage(e){if(this.stopController.signal.aborted||!e.data||this.strictOriginCheck&&e.origin!==window.origin)return;const t=e.data;if(!(!t.action||!t.requestId||!t.widgetId))if(t.response){if(t.api!==this.sendDirection)return;this.handleResponse(t)}else{const r=t;if(r.api!==Dae(this.sendDirection))return;this.handleRequest(r)}}handleRequest(e){if(this.widgetId){if(this.widgetId!==e.widgetId)return}else this._widgetId=e.widgetId;this.emit("message",new CustomEvent("message",{detail:e}))}handleResponse(e){if(e.widgetId!==this.widgetId)return;const t=this.outboundRequests.get(e.requestId);if(t)if($ae(e.response)){const{message:r,...i}=e.response.error;t.reject(new iS(r,i))}else t.resolve(e)}}var mr=(n=>(n.SupportedApiVersions="supported_api_versions",n.Capabilities="capabilities",n.NotifyCapabilities="notify_capabilities",n.ThemeChange="theme_change",n.LanguageChange="language_change",n.TakeScreenshot="screenshot",n.UpdateVisibility="visibility",n.OpenIDCredentials="openid_credentials",n.WidgetConfig="widget_config",n.CloseModalWidget="close_modal",n.ButtonClicked="button_clicked",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.UpdateTurnServers="update_turn_servers",n))(mr||{}),In=(n=>(n.SupportedApiVersions="supported_api_versions",n.ContentLoaded="content_loaded",n.SendSticker="m.sticker",n.UpdateAlwaysOnScreen="set_always_on_screen",n.GetOpenIDCredentials="get_openid",n.CloseModalWidget="close_modal",n.OpenModalWidget="open_modal",n.SetModalButtonEnabled="set_button_enabled",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.WatchTurnServers="watch_turn_servers",n.UnwatchTurnServers="unwatch_turn_servers",n.BeeperReadRoomAccountData="com.beeper.read_room_account_data",n.MSC2876ReadEvents="org.matrix.msc2876.read_events",n.MSC2931Navigate="org.matrix.msc2931.navigate",n.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",n.MSC3869ReadRelations="org.matrix.msc3869.read_relations",n.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",n.MSC4039GetMediaConfigAction="org.matrix.msc4039.get_media_config",n.MSC4039UploadFileAction="org.matrix.msc4039.upload_file",n.MSC4039DownloadFileAction="org.matrix.msc4039.download_file",n.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",n))(In||{}),fh=(n=>(n.Allowed="allowed",n.Blocked="blocked",n.PendingUserConfirmation="request",n))(fh||{}),zH=(n=>(n.Custom="m.custom",n.JitsiMeet="m.jitsi",n.Stickerpicker="m.stickerpicker",n))(zH||{}),YH=(n=>(n.Close="m.close",n))(YH||{}),aa=(n=>(n.Send="send",n.Receive="receive",n))(aa||{});class ii{constructor(e,t,r,i,s){this.direction=e,this.eventType=t,this.kind=r,this.keyStr=i,this.raw=s}matchesAsStateEvent(e,t,r){return this.kind!=="state_event"||this.direction!==e||this.eventType!==t?!1:this.keyStr===null||this.keyStr===r}matchesAsToDeviceEvent(e,t){return!(this.kind!=="to_device"||this.direction!==e||this.eventType!==t)}matchesAsRoomEvent(e,t,r=null){if(this.kind!=="event"||this.direction!==e||this.eventType!==t)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===r)return!0}else return!0;return!1}matchesAsRoomAccountData(e,t){return!(this.kind!=="room_account"||this.direction!==e||this.eventType!==t)}static forStateEvent(e,t,r){t=t.replace(/#/g,"\\#"),r=r!=null?`#${r}`:"";const i=`org.matrix.msc2762.${e}.state_event:${t}${r}`;return ii.findEventCapabilities([i])[0]}static forToDeviceEvent(e,t){const r=`org.matrix.msc3819.${e}.to_device:${t}`;return ii.findEventCapabilities([r])[0]}static forRoomEvent(e,t){const r=`org.matrix.msc2762.${e}.event:${t}`;return ii.findEventCapabilities([r])[0]}static forRoomMessageEvent(e,t){t=t??"";const r=`org.matrix.msc2762.${e}.event:m.room.message#${t}`;return ii.findEventCapabilities([r])[0]}static forRoomAccountData(e,t){const r=`com.beeper.capabilities.${e}.room_account_data:${t}`;return ii.findEventCapabilities([r])[0]}static findEventCapabilities(e){const t=[];for(const r of e){let i=null,s,o=null;if(r.startsWith("org.matrix.msc2762.send.event:")?(i="send",o="event",s=r.substring(30)):r.startsWith("org.matrix.msc2762.send.state_event:")?(i="send",o="state_event",s=r.substring(36)):r.startsWith("org.matrix.msc3819.send.to_device:")?(i="send",o="to_device",s=r.substring(34)):r.startsWith("org.matrix.msc2762.receive.event:")?(i="receive",o="event",s=r.substring(33)):r.startsWith("org.matrix.msc2762.receive.state_event:")?(i="receive",o="state_event",s=r.substring(39)):r.startsWith("org.matrix.msc3819.receive.to_device:")?(i="receive",o="to_device",s=r.substring(37)):r.startsWith("com.beeper.capabilities.receive.room_account_data:")&&(i="receive",o="room_account",s=r.substring(50)),i===null||o===null||s===void 0)continue;const a=s.startsWith("m.room.message#")||o==="state_event";let l=null;if(s.includes("#")&&a){const c=s.split("#"),u=c.findIndex(f=>!f.endsWith("\\"));s=c.slice(0,u+1).map(f=>f.endsWith("\\")?f.substring(0,f.length-1):f).join("#"),l=c.slice(u+1).join("#")}t.push(new ii(i,s,o,l,r))}return t}}var cd=(n=>(n.AnyRoom="*",n))(cd||{});const bE=class bE extends Error{constructor(e,t){super(e),this.data=t}};bE.prototype.name=bE.name;let iS=bE;class Fae extends RE.EventEmitter{constructor(e=null,t=null){if(super(),this.clientOrigin=t,this.capabilitiesFinished=!1,this.supportsMSC2974Renegotiate=!1,this.requestedCapabilities=[],this.turnServerWatchers=0,!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");this.transport=new Uae(WH.FromWidget,e,window.parent,window),this.transport.targetOrigin=t,this.transport.on("message",this.handleMessage.bind(this))}hasCapability(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}requestCapability(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}requestCapabilities(e){e.forEach(t=>this.requestCapability(t))}requestCapabilityForRoomTimeline(e){this.requestCapability(`org.matrix.msc2762.timeline:${e}`)}requestCapabilityToSendState(e,t){this.requestCapability(ii.forStateEvent(aa.Send,e,t).raw)}requestCapabilityToReceiveState(e,t){this.requestCapability(ii.forStateEvent(aa.Receive,e,t).raw)}requestCapabilityToSendToDevice(e){this.requestCapability(ii.forToDeviceEvent(aa.Send,e).raw)}requestCapabilityToReceiveToDevice(e){this.requestCapability(ii.forToDeviceEvent(aa.Receive,e).raw)}requestCapabilityToSendEvent(e){this.requestCapability(ii.forRoomEvent(aa.Send,e).raw)}requestCapabilityToReceiveEvent(e){this.requestCapability(ii.forRoomEvent(aa.Receive,e).raw)}requestCapabilityToSendMessage(e){this.requestCapability(ii.forRoomMessageEvent(aa.Send,e).raw)}requestCapabilityToReceiveMessage(e){this.requestCapability(ii.forRoomMessageEvent(aa.Receive,e).raw)}requestCapabilityToReceiveRoomAccountData(e){this.requestCapability(ii.forRoomAccountData(aa.Receive,e).raw)}requestOpenIDConnectToken(){return new Promise((e,t)=>{this.transport.sendComplete(In.GetOpenIDCredentials,{}).then(r=>{const i=r.response;if(i.state===fh.Allowed)e(i);else if(i.state===fh.Blocked)t(new Error("User declined to verify their identity"));else if(i.state===fh.PendingUserConfirmation){const s=o=>{o.preventDefault();const a=o.detail;a.data.original_request_id===r.requestId&&(a.data.state===fh.Allowed?(e(a.data),this.transport.reply(a,{})):a.data.state===fh.Blocked?(t(new Error("User declined to verify their identity")),this.transport.reply(a,{})):(t(new Error("Invalid state on reply: "+i.state)),this.transport.reply(a,{error:{message:"Invalid state"}})),this.off(`action:${mr.OpenIDCredentials}`,s))};this.on(`action:${mr.OpenIDCredentials}`,s)}else t(new Error("Invalid state: "+i.state))}).catch(t)})}updateRequestedCapabilities(){return this.transport.send(In.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}sendContentLoaded(){return this.transport.send(In.ContentLoaded,{}).then()}sendSticker(e){return this.transport.send(In.SendSticker,e).then()}setAlwaysOnScreen(e){return this.transport.send(In.UpdateAlwaysOnScreen,{value:e}).then(t=>t.success)}openModalWidget(e,t,r=[],i={},s=zH.Custom){return this.transport.send(In.OpenModalWidget,{type:s,url:e,name:t,buttons:r,data:i}).then()}closeModalWidget(e={}){return this.transport.send(In.CloseModalWidget,e).then()}sendRoomEvent(e,t,r,i,s){return this.sendEvent(e,void 0,t,r,i,s)}sendStateEvent(e,t,r,i,s,o){return this.sendEvent(e,t,r,i,s,o)}sendEvent(e,t,r,i,s,o){return this.transport.send(In.SendEvent,{type:e,content:r,...t!==void 0&&{state_key:t},...i!==void 0&&{room_id:i},...s!==void 0&&{delay:s},...o!==void 0&&{parent_delay_id:o}})}updateDelayedEvent(e,t){return this.transport.send(In.MSC4157UpdateDelayedEvent,{delay_id:e,action:t})}sendToDevice(e,t,r){return this.transport.send(In.SendToDevice,{type:e,encrypted:t,messages:r})}readRoomAccountData(e,t){const r={type:e};return t&&(t.includes(cd.AnyRoom)?r.room_ids=cd.AnyRoom:r.room_ids=t),this.transport.send(In.BeeperReadRoomAccountData,r).then(i=>i.events)}readRoomEvents(e,t,r,i,s){const o={type:e,msgtype:r};return t!==void 0&&(o.limit=t),i&&(i.includes(cd.AnyRoom)?o.room_ids=cd.AnyRoom:o.room_ids=i),s&&(o.since=s),this.transport.send(In.MSC2876ReadEvents,o).then(a=>a.events)}async readEventRelations(e,t,r,i,s,o,a,l){if(!(await this.getClientVersions()).includes(Tc.MSC3869))throw new Error("The read_relations action is not supported by the client.");const u={event_id:e,rel_type:r,event_type:i,room_id:t,to:a,from:o,limit:s,direction:l};return this.transport.send(In.MSC3869ReadRelations,u)}readStateEvents(e,t,r,i){const s={type:e,state_key:r===void 0?!0:r};return t!==void 0&&(s.limit=t),i&&(i.includes(cd.AnyRoom)?s.room_ids=cd.AnyRoom:s.room_ids=i),this.transport.send(In.MSC2876ReadEvents,s).then(o=>o.events)}setModalButtonEnabled(e,t){if(e===YH.Close)throw new Error("The close button cannot be disabled");return this.transport.send(In.SetModalButtonEnabled,{button:e,enabled:t}).then()}navigateTo(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(In.MSC2931Navigate,{uri:e}).then()}async*getTurnServers(){let e;const t=async r=>{r.preventDefault(),e(r.detail.data),await this.transport.reply(r.detail,{})};if(this.on(`action:${mr.UpdateTurnServers}`,t),this.turnServerWatchers===0)try{await this.transport.send(In.WatchTurnServers,{})}catch(r){throw this.off(`action:${mr.UpdateTurnServers}`,t),r}this.turnServerWatchers++;try{for(;;)yield await new Promise(r=>e=r)}finally{this.off(`action:${mr.UpdateTurnServers}`,t),this.turnServerWatchers--,this.turnServerWatchers===0&&await this.transport.send(In.UnwatchTurnServers,{})}}async searchUserDirectory(e,t){if(!(await this.getClientVersions()).includes(Tc.MSC3973))throw new Error("The user_directory_search action is not supported by the client.");const i={search_term:e,limit:t};return this.transport.send(In.MSC3973UserDirectorySearch,i)}async getMediaConfig(){if(!(await this.getClientVersions()).includes(Tc.MSC4039))throw new Error("The get_media_config action is not supported by the client.");const t={};return this.transport.send(In.MSC4039GetMediaConfigAction,t)}async uploadFile(e){if(!(await this.getClientVersions()).includes(Tc.MSC4039))throw new Error("The upload_file action is not supported by the client.");const r={file:e};return this.transport.send(In.MSC4039UploadFileAction,r)}async downloadFile(e){if(!(await this.getClientVersions()).includes(Tc.MSC4039))throw new Error("The download_file action is not supported by the client.");const r={content_uri:e};return this.transport.send(In.MSC4039DownloadFileAction,r)}start(){this.transport.start(),this.getClientVersions().then(e=>{e.includes(Tc.MSC2974)&&(this.supportsMSC2974Renegotiate=!0)})}handleMessage(e){const t=new CustomEvent(`action:${e.detail.action}`,{detail:e.detail,cancelable:!0});if(this.emit(`action:${e.detail.action}`,t),!t.defaultPrevented)switch(e.detail.action){case mr.SupportedApiVersions:return this.replyVersions(e.detail);case mr.Capabilities:return this.handleCapabilities(e.detail);case mr.UpdateVisibility:return this.transport.reply(e.detail,{});case mr.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}replyVersions(e){this.transport.reply(e,{supported_versions:jae})}getClientVersions(){return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(In.SupportedApiVersions,{}).then(e=>(this.cachedClientVersions=e.supported_versions,e.supported_versions)).catch(e=>(console.warn("non-fatal error getting supported client versions: ",e),[]))}handleCapabilities(e){return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then(t=>(t.includes(Tc.MSC2871)?this.once(`action:${mr.NotifyCapabilities}`,r=>{this.approvedCapabilities=r.detail.data.approved,this.emit("ready")}):this.emit("ready"),this.capabilitiesFinished=!0,this.transport.reply(e,{capabilities:this.requestedCapabilities})))}}var zg=(n=>(n.Screenshots="m.capability.screenshot",n.StickerSending="m.sticker",n.AlwaysOnScreen="m.always_on_screen",n.RequiresClient="io.element.requires_client",n.MSC2931Navigate="org.matrix.msc2931.navigate",n.MSC3846TurnServers="town.robin.msc3846.turn_servers",n.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",n.MSC4039UploadFile="org.matrix.msc4039.upload_file",n.MSC4039DownloadFile="org.matrix.msc4039.download_file",n.MSC4157SendDelayedEvent="org.matrix.msc4157.send.delayed_event",n.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",n))(zg||{});function $ae(n){const e=n.error;return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}function jN(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function R1(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?jN(Object(t),!0).forEach(function(r){L(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):jN(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function Hae(n){var e,t,r,i=2;for(typeof Symbol<"u"&&(t=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(t&&(e=n[t])!=null)return e.call(n);if(r&&(e=n[r])!=null)return new B_(e.call(n));t="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function B_(n){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var r=t.done;return Promise.resolve(t.value).then(function(i){return{value:i,done:r}})}return B_=function(r){this.s=r,this.n=r.next},B_.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(r){var i=this.s.return;return i===void 0?Promise.resolve({value:r,done:!0}):e(i.apply(this.s,arguments))},throw:function(r){var i=this.s.return;return i===void 0?Promise.reject(r):e(i.apply(this.s,arguments))}},new B_(n)}var V_=function(n){return n.PendingEventsChanged="PendingEvent.pendingEventsChanged",n}({});class JH extends DE{constructor(e,t,r,i,s){var o,a,l,c,u,f,p,m,v,g,S,b,w;super(i),o=this,this.widgetApi=e,this.capabilities=t,this.roomId=r,L(this,"room",void 0),L(this,"widgetApiReady",void 0),L(this,"lifecycle",void 0),L(this,"syncState",null),L(this,"pendingSendingEventsTxId",[]),L(this,"eventEmitter",new En),L(this,"updateTxId",function(){var I=F(function*(C){if(C.getSender()===o.getUserId()&&o.pendingSendingEventsTxId.some(D=>C.getType()===D.type)){for(var x,O=(x=o.pendingSendingEventsTxId.find(D=>D.id===C.getId()))===null||x===void 0?void 0:x.txId;!O&&o.pendingSendingEventsTxId.length>0;){var N;yield new Promise(D=>o.eventEmitter.once(V_.PendingEventsChanged,()=>D())),O=(N=o.pendingSendingEventsTxId.find(D=>D.id===C.getId()))===null||N===void 0?void 0:N.txId}O&&(C.setTxnId(O),C.setUnsigned(R1(R1({},C.getUnsigned()),{},{transaction_id:O}))),o.pendingSendingEventsTxId=o.pendingSendingEventsTxId.filter(D=>D.id!==C.getId()),o.pendingSendingEventsTxId.length===0&&o.eventEmitter.emit(V_.PendingEventsChanged)}});return function(C){return I.apply(this,arguments)}}()),L(this,"onEvent",function(){var I=F(function*(C){if(C.preventDefault(),C.detail.data.room_id===o.roomId){var x=new wi(C.detail.data);yield o.updateTxId(x),o.syncApi instanceof gd?yield o.syncApi.injectRoomEvents(o.room,[],void 0,[x]):yield o.syncApi.injectRoomEvents(o.room,[],[x]),o.emit(Oe.Event,x),o.setSyncState(Dt.Syncing),A.info("Received event ".concat(x.getId()," ").concat(x.getType()," ").concat(x.getStateKey()))}else{var{event_id:O,room_id:N}=C.detail.data;A.info("Received event ".concat(O," for a different room ").concat(N,"; discarding"))}yield o.ack(C)});return function(C){return I.apply(this,arguments)}}()),L(this,"onToDevice",function(){var I=F(function*(C){C.preventDefault();var x=new wi({type:C.detail.data.type,sender:C.detail.data.sender,content:C.detail.data.content});C.detail.data.encrypted&&x.makeEncrypted(ee.RoomMessageEncrypted,{},"",""),o.emit(Oe.ToDeviceEvent,x),o.setSyncState(Dt.Syncing),yield o.ack(C)});return function(C){return I.apply(this,arguments)}}());var k=this.widgetApi.transport.send.bind(this.widgetApi.transport);this.widgetApi.transport.send=function(){var I=F(function*(C,x){try{return yield k(C,x)}catch(O){UN(O)}});return function(C,x){return I.apply(this,arguments)}}();var R=this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);this.widgetApi.transport.sendComplete=function(){var I=F(function*(C,x){try{return yield R(C,x)}catch(O){UN(O)}});return function(C,x){return I.apply(this,arguments)}}(),this.widgetApiReady=new Promise(I=>this.widgetApi.once("ready",I)),((a=t.sendEvent)!==null&&a!==void 0&&a.length||(l=t.receiveEvent)!==null&&l!==void 0&&l.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||t.receiveMessage===!0||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(c=t.sendState)!==null&&c!==void 0&&c.length||(u=t.receiveState)!==null&&u!==void 0&&u.length)&&e.requestCapabilityForRoomTimeline(r),(f=t.sendEvent)===null||f===void 0||f.forEach(I=>e.requestCapabilityToSendEvent(I)),(p=t.receiveEvent)===null||p===void 0||p.forEach(I=>e.requestCapabilityToReceiveEvent(I)),t.sendMessage===!0?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach(I=>e.requestCapabilityToSendMessage(I)),t.receiveMessage===!0?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach(I=>e.requestCapabilityToReceiveMessage(I)),(m=t.sendState)===null||m===void 0||m.forEach(I=>{var{eventType:C,stateKey:x}=I;return e.requestCapabilityToSendState(C,x)}),(v=t.receiveState)===null||v===void 0||v.forEach(I=>{var{eventType:C,stateKey:x}=I;return e.requestCapabilityToReceiveState(C,x)}),(g=t.sendToDevice)===null||g===void 0||g.forEach(I=>e.requestCapabilityToSendToDevice(I)),(S=t.receiveToDevice)===null||S===void 0||S.forEach(I=>e.requestCapabilityToReceiveToDevice(I)),t.sendDelayedEvents&&((b=t.sendEvent)!==null&&b!==void 0&&b.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||(w=t.sendState)!==null&&w!==void 0&&w.length)&&e.requestCapability(zg.MSC4157SendDelayedEvent),t.updateDelayedEvents&&e.requestCapability(zg.MSC4157UpdateDelayedEvent),t.turnServers&&e.requestCapability(zg.MSC3846TurnServers),e.on("action:".concat(mr.SendEvent),this.onEvent),e.on("action:".concat(mr.SendToDevice),this.onToDevice),e.start(),s&&e.sendContentLoaded()}startClient(){var e=arguments,t=this;return F(function*(){var r,i,s=e.length>0&&e[0]!==void 0?e[0]:{};t.lifecycle=new AbortController;var o=t.getUserId();o&&t.store.storeUser(new bl(o)),s.slidingSync?t.syncApi=new EH(s.slidingSync,t,s,t.buildSyncApiOptions()):t.syncApi=new gd(t,s,t.buildSyncApiOptions()),t.room=t.syncApi.createRoom(t.roomId),t.store.storeRoom(t.room),yield t.widgetApiReady,yield Promise.all((r=(i=t.capabilities.receiveState)===null||i===void 0?void 0:i.map(function(){var a=F(function*(l){var{eventType:c,stateKey:u}=l,f=yield t.widgetApi.readStateEvents(c,void 0,u,[t.roomId]),p=f.map(m=>new wi(m));t.syncApi instanceof gd?yield t.syncApi.injectRoomEvents(t.room,void 0,p):yield t.syncApi.injectRoomEvents(t.room,p),p.forEach(m=>{t.emit(Oe.Event,m),A.info("Backfilled event ".concat(m.getId()," ").concat(m.getType()," ").concat(m.getStateKey()))})});return function(l){return a.apply(this,arguments)}}()))!==null&&r!==void 0?r:[]),s.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*s.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.setSyncState(Dt.Syncing),A.info("Finished backfilling events"),t.matrixRTC.start(),t.capabilities.turnServers&&t.watchTurnServers()})()}stopClient(){this.widgetApi.off("action:".concat(mr.SendEvent),this.onEvent),this.widgetApi.off("action:".concat(mr.SendToDevice),this.onToDevice),super.stopClient(),this.lifecycle.abort()}joinRoom(e){var t=this;return F(function*(){if(e===t.roomId)return t.room;throw new Error("Unknown room: ".concat(e))})()}encryptAndSendEvent(e,t,r){var i=this;return F(function*(){var s=t.event.redacts?R1(R1({},t.getContent()),{},{redacts:t.event.redacts}):t.getContent();if(r){var o=yield i.widgetApi.sendRoomEvent(t.getType(),s,e.roomId,"delay"in r?r.delay:void 0,"parent_delay_id"in r?r.parent_delay_id:void 0).catch(ea);return i.validateSendDelayedEventResponse(o)}var a=t.getTxnId();a&&i.pendingSendingEventsTxId.push({type:t.getType(),id:void 0,txId:a});var l;try{l=yield i.widgetApi.sendRoomEvent(t.getType(),s,e.roomId).catch(ea)}catch(c){throw i.updatePendingEventStatus(e,t,et.NOT_SENT),c}return e.updatePendingEvent(t,et.SENT,l.event_id),i.pendingSendingEventsTxId.forEach(c=>{c.txId===a&&(c.id=l.event_id)}),i.eventEmitter.emit(V_.PendingEventsChanged),{event_id:l.event_id}})()}sendStateEvent(e,t,r){var i=arguments,s=this;return F(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:"",a=yield s.widgetApi.sendStateEvent(t,o,r,e).catch(ea);if(a.event_id===void 0)throw new Error("'event_id' absent from response to an event request");return{event_id:a.event_id}})()}_unstable_sendDelayedStateEvent(e,t,r,i){var s=arguments,o=this;return F(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"";if(!(yield o.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","sendDelayedStateEvent");var l=yield o.widgetApi.sendStateEvent(r,a,i,e,"delay"in t?t.delay:void 0,"parent_delay_id"in t?t.parent_delay_id:void 0).catch(ea);return o.validateSendDelayedEventResponse(l)})()}validateSendDelayedEventResponse(e){if(e.delay_id===void 0)throw new Error("'delay_id' absent from response to a delayed event request");return{delay_id:e.delay_id}}_unstable_updateDelayedEvent(e,t){var r=this;return F(function*(){if(!(yield r.doesServerSupportUnstableFeature(pa)))throw new jc("Server does not support the delayed events API","updateDelayedEvent");return yield r.widgetApi.updateDelayedEvent(e,t).catch(ea),{}})()}encryptAndSendToDevice(e,t,r){var i=this;return F(function*(){var s=new _l(()=>new Map);for(var{userId:o,deviceId:a}of t)s.getOrCreate(o).set(a,r);yield i.widgetApi.sendToDevice(e,!0,pd(s)).catch(ea)})()}sendToDevice(e,t){var r=this;return F(function*(){return yield r.widgetApi.sendToDevice(e,!1,pd(t)).catch(ea),{}})()}getOpenIdToken(){var e=this;return F(function*(){var t=yield e.widgetApi.requestOpenIDConnectToken().catch(ea);return{access_token:t.access_token,expires_in:t.expires_in,matrix_server_name:t.matrix_server_name,token_type:t.token_type}})()}queueToDevice(e){var t=this;return F(function*(){var{eventType:r,batch:i}=e,s=new _l(()=>new Map);for(var{userId:o,deviceId:a,payload:l}of i)s.getOrCreate(o).set(a,l);yield t.widgetApi.sendToDevice(r,!1,pd(s)).catch(ea)})()}sendToDeviceViaWidgetApi(e,t,r){var i=this;return F(function*(){yield i.widgetApi.sendToDevice(e,t,pd(r)).catch(ea)})()}checkTurnServers(){var e=this;return F(function*(){return e.turnServers.length>0})()}getSyncState(){return this.syncState}setSyncState(e){var t=this.syncState;this.syncState=e,this.emit(Oe.Sync,e,t)}ack(e){var t=this;return F(function*(){yield t.widgetApi.transport.reply(e.detail,{})})()}watchTurnServers(){var e=this;return F(function*(){var t=e.widgetApi.getTurnServers(),r=()=>{t.return(void 0)};e.lifecycle.signal.addEventListener("abort",r);try{var i=!1,s=!1,o;try{for(var a=Hae(t),l;i=!(l=yield a.next()).done;i=!1){var c=l.value;e.turnServers=[{urls:c.uris,username:c.username,credential:c.password}],e.emit(Oe.TurnServers,e.turnServers),A.log("Received TURN server: ".concat(c.uris))}}catch(u){s=!0,o=u}finally{try{i&&a.return!=null&&(yield a.return())}finally{if(s)throw o}}}catch(u){A.warn("Error watching TURN servers",u)}finally{e.lifecycle.signal.removeEventListener("abort",r)}})()}}function UN(n){throw n instanceof iS&&n.data.matrix_api_error?bn.fromWidgetApiErrorData(n.data.matrix_api_error):n}function ea(n){throw n instanceof Error&&n.message==="Request timed out"?new Jd("widget api timeout"):n}class Bae{constructor(){L(this,"unthreadedReadReceipts",new Map),L(this,"threadedReadReceipts",new _l(()=>new Map))}setUnthreaded(e,t){this.unthreadedReadReceipts.set(e,t)}setThreaded(e,t,r){this.threadedReadReceipts.getOrCreate(e).set(t,r)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(var e of this.threadedReadReceipts.values())for(var t of e.entries())yield t}consumeEphemeralEvents(e){e==null||e.forEach(t=>{t.type!==ee.Receipt||!t.content||Object.keys(t.content).forEach(r=>{Object.entries(t.content[r]).forEach(i=>{var[s,o]=i;if(PP(s))for(var a of Object.keys(o)){var l=t.content[r][s][a],c={data:t.content[r][s][a],type:s,eventId:r};l.thread_id?this.setThreaded(l.thread_id,a,c):this.setUnthreaded(a,c)}})})})}buildAccumulatedReceiptEvent(e){var t={type:ee.Receipt,room_id:e,content:{}},r=new _l(()=>new _l(()=>new Map));for(var[i,s]of this.allUnthreaded())r.getOrCreate(s.eventId).getOrCreate(s.type).set(i,s.data);for(var[o,a]of this.allThreaded())r.getOrCreate(a.eventId).getOrCreate(a.type).set(o,a.data);return t.content=pd(r),r.size>0?t:null}}var Za=function(n){return n.Invite="invite",n.Leave="leave",n.Join="join",n.Knock="knock",n}({});function Vae(n){return"_localTs"in n&&n._localTs!==void 0}class XH{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.opts=e,L(this,"accountData",{}),L(this,"inviteRooms",{}),L(this,"knockRooms",{}),L(this,"joinRooms",{}),L(this,"nextBatch",null),this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){!e.account_data||!e.account_data.events||e.account_data.events.forEach(t=>{this.accountData[t.type]=t})}accumulateRooms(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach(r=>{this.accumulateRoom(r,Za.Invite,e.rooms.invite[r],t)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(r=>{this.accumulateRoom(r,Za.Join,e.rooms.join[r],t)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(r=>{this.accumulateRoom(r,Za.Leave,e.rooms.leave[r],t)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(r=>{this.accumulateRoom(r,Za.Knock,e.rooms.knock[r],t)}))}accumulateRoom(e,t,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;switch(t){case Za.Invite:this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,r);break;case Za.Knock:this.accumulateKnockState(e,r);break;case Za.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,r,i);break;case Za.Leave:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:A.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!(!t.invite_state||!t.invite_state.events)){if(!this.inviteRooms[e]){this.inviteRooms[e]={invite_state:t.invite_state};return}var r=this.inviteRooms[e];t.invite_state.events.forEach(i=>{for(var s=!1,o=0;o<r.invite_state.events.length;o++){var a=r.invite_state.events[o];a.type===i.type&&a.state_key==i.state_key&&(r.invite_state.events[o]=i,s=!0)}s||r.invite_state.events.push(i)})}}accumulateKnockState(e,t){if(!(!t.knock_state||!t.knock_state.events)){if(!this.knockRooms[e]){this.knockRooms[e]={knock_state:t.knock_state};return}var r=this.knockRooms[e];t.knock_state.events.forEach(i=>{for(var s=!1,o=0;o<r.knock_state.events.length;o++){var a=r.knock_state.events[o];a.type===i.type&&a.state_key==i.state_key&&(r.knock_state.events[o]=i,s=!0)}s||r.knock_state.events.push(i)})}}accumulateJoinState(e,t){var r,i,s,o,a,l,c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_receipts:new Bae});var u=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach(I=>{u._accountData[I.type]=I}),t.unread_notifications&&(u._unreadNotifications=t.unread_notifications),u._unreadThreadNotifications=(r=(i=t[Tv.stable])!==null&&i!==void 0?i:t[Tv.unstable])!==null&&r!==void 0?r:void 0,t.summary){var f,p,m,v="m.heroes",g="m.invited_member_count",S="m.joined_member_count",b=u._summary,w=t.summary;b[v]=(f=w[v])!==null&&f!==void 0?f:b[v],b[S]=(p=w[S])!==null&&p!==void 0?p:b[S],b[g]=(m=w[g])!==null&&m!==void 0?m:b[g]}if(u._receipts.consumeEphemeralEvents((s=t.ephemeral)===null||s===void 0?void 0:s.events),t.timeline&&t.timeline.limited&&(u._timeline=[]),(o=t.state)===null||o===void 0||(o=o.events)===null||o===void 0||o.forEach(I=>{I1(u._currentState,I)}),(a=t["org.matrix.msc4222.state_after"])===null||a===void 0||(a=a.events)===null||a===void 0||a.forEach(I=>{I1(u._currentState,I)}),(l=t.timeline)===null||l===void 0||(l=l.events)===null||l===void 0||l.forEach((I,C)=>{var x;t["org.matrix.msc4222.state_after"]||I1(u._currentState,I);var O;if(c)O=I;else{var N;O=Object.assign({},I),O.unsigned!==void 0&&(O.unsigned=Object.assign({},O.unsigned));var D=(N=I.unsigned)===null||N===void 0?void 0:N.age;D!==void 0&&(O._localTs=Date.now()-D)}u._timeline.push({event:O,token:C===0&&(x=t.timeline.prev_batch)!==null&&x!==void 0?x:null})}),u._timeline.length>this.opts.maxTimelineEntries){for(var k=u._timeline.length-this.opts.maxTimelineEntries,R=k;R<u._timeline.length;R++)if(u._timeline[R].token){u._timeline=u._timeline.slice(R,u._timeline.length);break}}}getJSON(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={join:{},invite:{},knock:{},leave:{}};Object.keys(this.inviteRooms).forEach(i=>{t.invite[i]=this.inviteRooms[i]}),Object.keys(this.knockRooms).forEach(i=>{t.knock[i]=this.knockRooms[i]}),Object.keys(this.joinRooms).forEach(i=>{var s=this.joinRooms[i],o={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},"org.matrix.msc4222.state_after":{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:s._unreadNotifications,unread_thread_notifications:s._unreadThreadNotifications,summary:s._summary};Object.keys(s._accountData).forEach(p=>{o.account_data.events.push(s._accountData[p])});var a=s._receipts.buildAccumulatedReceiptEvent(i);a&&o.ephemeral.events.push(a),s._timeline.forEach(p=>{if(!o.timeline.prev_batch){if(!p.token)return;o.timeline.prev_batch=p.token}var m;!e&&Vae(p.event)?(m=Object.assign({},p.event),m.unsigned!==void 0&&(m.unsigned=Object.assign({},m.unsigned)),delete m._localTs,m.unsigned=m.unsigned||{},m.unsigned.age=Date.now()-p.event._localTs):m=p.event,o.timeline.events.push(m)});for(var l=Object.create(null),c=o.timeline.events.length-1;c>=0;c--){var u=o.timeline.events[c];if(!(u.state_key===null||u.state_key===void 0)){var f=wE(u);f.unsigned&&(f.unsigned.prev_content&&(f.content=f.unsigned.prev_content),f.unsigned.prev_sender&&(f.sender=f.unsigned.prev_sender)),I1(l,f)}}Object.keys(s._currentState).forEach(p=>{Object.keys(s._currentState[p]).forEach(m=>{var v=s._currentState[p][m];o["org.matrix.msc4222.state_after"].events.push(v),l[p]&&l[p][m]&&(v=l[p][m]),o.state.events.push(v)})}),t.join[i]=o});var r=[];return Object.keys(this.accountData).forEach(i=>{r.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:t,accountData:r}}getNextBatchToken(){return this.nextBatch}}function I1(n,e){e.state_key===null||e.state_key===void 0||!e.type||(n[e.type]||(n[e.type]=Object.create(null)),n[e.type][e.state_key]=e)}var ZH=function(n){return n[n.Blocked=-1]="Blocked",n[n.Unverified=0]="Unverified",n[n.Verified=1]="Verified",n}({});class qae{constructor(e){L(this,"deviceId",void 0),L(this,"userId",void 0),L(this,"algorithms",void 0),L(this,"keys",void 0),L(this,"verified",void 0),L(this,"signatures",void 0),L(this,"displayName",void 0),L(this,"dehydrated",!1),this.deviceId=e.deviceId,this.userId=e.userId,this.algorithms=e.algorithms,this.keys=e.keys,this.verified=e.verified||ZH.Unverified,this.signatures=e.signatures||new Map,this.displayName=e.displayName,this.dehydrated=!!e.dehydrated}getFingerprint(){return this.keys.get("ed25519:".concat(this.deviceId))}getIdentityKey(){return this.keys.get("curve25519:".concat(this.deviceId))}}var FN=function(){},Kae=10;class Gae{constructor(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.client=e,this.timelineSet=t,L(this,"windowLimit",void 0),L(this,"start",void 0),L(this,"end",void 0),L(this,"eventCount",0),this.windowLimit=i.windowLimit||1e3,(r=t.room)===null||r===void 0||r.on(ke.Timeline,this.onTimelineEvent.bind(this))}load(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20,r=i=>{if(!i)throw new Error("No timeline given to initFields");var s,o=i.getEvents();if(!e)s=o.length;else if(s=o.findIndex(c=>c.getId()===e),s<0)throw new Error("getEventTimeline result didn't include requested event");var a=Math.min(o.length,s+Math.ceil(t/2)),l=Math.max(0,a-t);this.start=new $k(i,l-i.getBaseIndex()),this.end=new $k(i,a-i.getBaseIndex()),this.eventCount=a-l};return this.timelineSet.getTimelineForEvent(e)?(r(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(r):(r(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){if(e==Le.BACKWARDS){var t;return(t=this.start)!==null&&t!==void 0?t:null}else if(e==Le.FORWARDS){var r;return(r=this.end)!==null&&r!==void 0?r:null}else throw new Error("Invalid direction '"+e+"'")}extend(e,t){var r=this.getTimelineIndex(e);if(!r)return!1;var i=e==Le.BACKWARDS?r.retreat(t):r.advance(t);if(i){this.eventCount+=i,FN("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");var s=this.eventCount-this.windowLimit;return s>0&&this.unpaginate(s,e!=Le.BACKWARDS),!0}return!1}onTimelineEvent(e,t,r,i){i&&this.onEventRemoved()}onEventRemoved(){var e=this.getEvents();e.length>0&&e[e.length-1]===void 0&&this.end&&this.end.index--}canPaginate(e){var t=this.getTimelineIndex(e);if(!t)return!1;if(e==Le.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;var r=t.timeline.getNeighbouringTimeline(e),i=t.timeline.getPaginationToken(e);return!!r||!!i}paginate(e,t){var r=arguments,i=this;return F(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:!0,o=r.length>3&&r[3]!==void 0?r[3]:Kae,a=i.getTimelineIndex(e);if(!a)return!1;if(a.pendingPaginate)return a.pendingPaginate;if(i.extend(e,t))return!0;if(!s||o===0)return!1;var l=a.timeline.getPaginationToken(e);if(!l)return!1;var c=i.client.paginateEventTimeline(a.timeline,{backwards:e==Le.BACKWARDS,limit:t}).finally(function(){a.pendingPaginate=void 0}).then(u=>u?i.paginate(e,t,!0,o-1):i.paginate(e,t,!1,0));return a.pendingPaginate=c,c})()}unpaginate(e,t){var r=t?this.start:this.end;if(!r)throw new Error("Attempting to unpaginate startOfTimeline=".concat(t," but don't have this direction"));if(e>this.eventCount||e<0)throw new Error("Attemting to unpaginate ".concat(e," events, but only have ").concat(this.eventCount," in the timeline"));for(;e>0;){var i=t?r.advance(e):r.retreat(e);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=i,this.eventCount-=i,FN("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];for(var e=[],t=this.start.timeline;t;){var r,i,s=t.getEvents(),o=0,a=s.length;t===this.start.timeline&&(o=this.start.index+t.getBaseIndex()),t===((r=this.end)===null||r===void 0?void 0:r.timeline)&&(a=this.end.index+t.getBaseIndex());for(var l=o;l<a;l++)e.push(s[l]);if(t===((i=this.end)===null||i===void 0?void 0:i.timeline))break;t=t.getNeighbouringTimeline(Le.FORWARDS)}return e}}class $k{constructor(e,t){this.timeline=e,this.index=t,L(this,"pendingPaginate",void 0)}minIndex(){return this.timeline.getBaseIndex()*-1}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;var t;if(e<0){if(t=Math.max(e,this.minIndex()-this.index),t<0)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;var r=this.timeline.getNeighbouringTimeline(e<0?Le.BACKWARDS:Le.FORWARDS);return r?(this.timeline=r,e<0?this.index=this.maxIndex():this.index=this.minIndex(),this.advance(e)):0}retreat(e){return this.advance(e*-1)*-1}}var tg="m.login.email.identity",$N="m.login.msisdn",Hk=function(n){return n.Password="m.login.password",n.Recaptcha="m.login.recaptcha",n.Terms="m.login.terms",n.Email="m.login.email.identity",n.Msisdn="m.login.msisdn",n.Sso="m.login.sso",n.SsoUnstable="org.matrix.login.sso",n.Dummy="m.login.dummy",n.RegistrationToken="m.login.registration_token",n.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token",n}({});class QH extends Error{constructor(e,t,r){super(e),this.required_stages=t,this.flows=r,L(this,"name","NoAuthFlowFoundError")}}class aL{constructor(e){var t=this;L(this,"matrixClient",void 0),L(this,"inputs",void 0),L(this,"clientSecret",void 0),L(this,"requestCallback",void 0),L(this,"busyChangedCallback",void 0),L(this,"stateUpdatedCallback",void 0),L(this,"requestEmailTokenCallback",void 0),L(this,"supportedStages",void 0),L(this,"data",void 0),L(this,"emailSid",void 0),L(this,"requestingEmailToken",!1),L(this,"attemptAuthDeferred",null),L(this,"chosenFlow",null),L(this,"currentStage",null),L(this,"emailAttempt",1),L(this,"submitPromise",null),L(this,"requestEmailToken",F(function*(){if(t.requestingEmailToken)A.warn("Could not request email token: Already requesting");else{A.trace("Requesting email token. Attempt: "+t.emailAttempt),t.requestingEmailToken=!0;try{var r=yield t.requestEmailTokenCallback(t.inputs.emailAddress,t.clientSecret,t.emailAttempt++,t.data.session);t.emailSid=r.sid,A.trace("Email token request succeeded")}finally{t.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{flows:[]},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=e.emailSid,e.supportedStages!==void 0&&(this.supportedStages=new Set(e.supportedStages))}attemptAuth(){var e=this;return F(function*(){var t;e.attemptAuthDeferred=ru();var r=e.attemptAuthDeferred.promise;if((t=e.data)!==null&&t!==void 0&&(t=t.flows)!==null&&t!==void 0&&t.length)e.startNextAuthStage();else{var i;(i=e.busyChangedCallback)===null||i===void 0||i.call(e,!0);var s=e.data.session?{session:e.data.session}:null;e.doRequest(s).finally(()=>{var o;(o=e.busyChangedCallback)===null||o===void 0||o.call(e,!1)})}return r})()}poll(){var e=this;return F(function*(){if(e.data.session&&e.attemptAuthDeferred&&!e.submitPromise){var t={};if(e.currentStage==tg&&e.emailSid){var r={sid:e.emailSid,client_secret:e.clientSecret},i=e.matrixClient.getIdentityServerUrl();i&&(r.id_server=new URL(i).host),t={type:tg,threepid_creds:r}}e.submitAuthDict(t,!0)}})()}getSessionId(){var e;return(e=this.data)===null||e===void 0?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return(t=this.data)===null||t===void 0||(t=t.params)===null||t===void 0?void 0:t[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e){var t=arguments,r=this;return F(function*(){var i,s=t.length>1&&t[1]!==void 0?t[1]:!1;if(!r.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");if(!s){var o;(o=r.busyChangedCallback)===null||o===void 0||o.call(r,!0)}for(;r.submitPromise;)try{yield r.submitPromise}catch{}var a;(i=r.data)!==null&&i!==void 0&&i.session?a=Object.assign({session:r.data.session},e):a=e;try{r.submitPromise=r.doRequest(a,s),yield r.submitPromise}finally{if(r.submitPromise=null,!s){var l;(l=r.busyChangedCallback)===null||l===void 0||l.call(r,!1)}}})()}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e){var t=arguments,r=this;return F(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;try{var s=yield r.requestCallback(e,i);r.attemptAuthDeferred.resolve(s),r.attemptAuthDeferred=null}catch(v){var o,a,l,c,u=v instanceof bn?v:null,f=(o=u==null||(a=u.data)===null||a===void 0?void 0:a.flows)!==null&&o!==void 0?o:null,p=((l=r.data)===null||l===void 0?void 0:l.flows)||!!f;if(!u||u.httpStatus!==401||!u.data||!p)if(i)A.log("Background poll request failed doing UI auth: ignoring",v);else{var m;(m=r.attemptAuthDeferred)===null||m===void 0||m.reject(v)}u&&!u.data&&(u.data={}),u&&!u.data.flows&&!u.data.completed&&!u.data.session&&(u.data.flows=r.data.flows,u.data.completed=r.data.completed,u.data.session=r.data.session),u&&(r.data=u.data);try{r.startNextAuthStage()}catch(g){r.attemptAuthDeferred.reject(g),r.attemptAuthDeferred=null;return}if(!r.emailSid&&(c=r.chosenFlow)!==null&&c!==void 0&&c.stages.includes(Hk.Email))try{yield r.requestEmailToken()}catch(g){r.attemptAuthDeferred.reject(g),r.attemptAuthDeferred=null}}})()}startNextAuthStage(){var e,t,r=this.chooseStage();if(!r)throw new Error("No incomplete flows from the server");if(this.currentStage=r,r===Hk.Dummy){this.submitAuthDict({type:"m.login.dummy"});return}if((e=this.data)!==null&&e!==void 0&&e.errcode||(t=this.data)!==null&&t!==void 0&&t.error){var i,s;this.stateUpdatedCallback(r,{errcode:((i=this.data)===null||i===void 0?void 0:i.errcode)||"",error:((s=this.data)===null||s===void 0?void 0:s.error)||""});return}this.stateUpdatedCallback(r,r===tg?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),A.log("Active flow => %s",JSON.stringify(this.chosenFlow));var e=this.firstUncompletedStage(this.chosenFlow);return A.log("Next stage: %s",e),e}scoreFlow(e){var t=e.stages.length;return this.supportedStages!==void 0&&(t+=e.stages.filter(r=>!this.supportedStages.has(r)).length*10),t}chooseFlow(){var e,t=((e=this.data)===null||e===void 0?void 0:e.flows)||[],r=!!this.inputs.emailAddress||!!this.emailSid,i=!!this.inputs.phoneCountry&&!!this.inputs.phoneNumber;t.sort((u,f)=>this.scoreFlow(u)-this.scoreFlow(f));for(var s of t){var o=!1,a=!1;for(var l of s.stages)l===tg?o=!0:l==$N&&(a=!0);if(o==r&&a==i)return s}var c=[];throw r&&c.push(tg),i&&c.push($N),new QH("No appropriate authentication flow found",c,t)}firstUncompletedStage(e){var t,r=((t=this.data)===null||t===void 0?void 0:t.completed)||[];return e.stages.find(i=>!r.includes(i))}}function eB(n,e){return new Promise((t,r)=>{var i=!0,s=n.open(e);s.onupgradeneeded=()=>{i=!1},s.onblocked=()=>r(s.error),s.onsuccess=()=>{var o=s.result;o.close(),i||n.deleteDatabase(e),t(i)},s.onerror=()=>r(s.error)})}var tB=[n=>{n.createObjectStore("users",{keyPath:["userId"]}),n.createObjectStore("accountData",{keyPath:["type"]}),n.createObjectStore("sync",{keyPath:["clobber"]})},n=>{var e=n.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]});e.createIndex("room","room_id")},n=>{n.createObjectStore("client_options",{keyPath:["clobber"]})},n=>{n.createObjectStore("to_device_queue",{autoIncrement:!0})}],Wae=tB.length;function k1(n,e,t){var r=n.openCursor(e);return new Promise((i,s)=>{var o=[];r.onerror=()=>{var a;s(new Error("Query failed: "+((a=r.error)===null||a===void 0?void 0:a.name)))},r.onsuccess=()=>{var a=r.result;if(!a){i(o);return}o.push(t(a)),a.continue()}})}function Zu(n){return new Promise((e,t)=>{n.oncomplete=function(r){e(r)},n.onerror=function(){t(n.error)}})}function nB(n){return new Promise((e,t)=>{n.onsuccess=function(r){e(r)},n.onerror=function(){t(n.error)}})}function zae(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n),n.onerror=r=>t(r)})}function d2(n){return nB(n).then(e=>n.result)}class HN{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),eB(e,t)}constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"default";this.indexedDB=e,L(this,"dbName",void 0),L(this,"syncAccumulator",void 0),L(this,"db",void 0),L(this,"disconnected",!0),L(this,"_isNewlyCreated",!1),L(this,"syncToDatabasePromise",void 0),L(this,"pendingUserPresenceData",[]),this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new XH}connect(e){var t=this;if(!this.disconnected)return A.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,A.log("LocalIndexedDBStoreBackend.connect: connecting...");var r=this.indexedDB.open(this.dbName,Wae);return r.onupgradeneeded=i=>{var s=r.result,o=i.oldVersion;A.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(o)),o<1&&(this._isNewlyCreated=!0),tB.forEach((a,l)=>{o<=l&&a(s)})},r.onblocked=()=>{A.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},A.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),nB(r).then(F(function*(){A.log("LocalIndexedDBStoreBackend.connect: connected"),t.db=r.result,t.db.onversionchange=()=>{var i;(i=t.db)===null||i===void 0||i.close(),t.disconnected=!0,t.db=void 0},t.db.onclose=()=>{t.disconnected=!0,t.db=void 0,e==null||e()},yield t.init()}))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(e=>{var[t,r]=e;A.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:r.nextBatch,rooms:r.roomsData,account_data:{events:t}},!0)})}getOutOfBandMembers(e){return new Promise((t,r)=>{var i=this.db.transaction(["oob_membership_events"],"readonly"),s=i.objectStore("oob_membership_events"),o=s.index("room"),a=IDBKeyRange.only(e),l=o.openCursor(a),c=[],u=!1;l.onsuccess=()=>{var f=l.result;if(!f)return!c.length&&!u?t(null):t(c);var p=f.value;p.oob_written?u=!0:c.push(p),f.continue()},l.onerror=f=>{r(f)}}).then(t=>(A.log("LL: got ".concat(t==null?void 0:t.length," membershipEvents from storage for room ").concat(e," ...")),t))}setOutOfBandMembers(e,t){var r=this;return F(function*(){A.log("LL: backend about to store ".concat(t.length)+" members for ".concat(e));var i=r.db.transaction(["oob_membership_events"],"readwrite"),s=i.objectStore("oob_membership_events");t.forEach(a=>{s.put(a)});var o={room_id:e,oob_written:!0,state_key:0};s.put(o),yield Zu(i),A.log("LL: backend done storing for ".concat(e,"!"))})()}clearOutOfBandMembers(e){var t=this;return F(function*(){var r=t.db.transaction(["oob_membership_events"],"readonly"),i=r.objectStore("oob_membership_events"),s=i.index("room"),o=IDBKeyRange.only(e),a=d2(s.openKeyCursor(o,"next")).then(v=>(v==null?void 0:v.primaryKey)[1]),l=d2(s.openKeyCursor(o,"prev")).then(v=>(v==null?void 0:v.primaryKey)[1]),[c,u]=yield Promise.all([a,l]),f=t.db.transaction(["oob_membership_events"],"readwrite"),p=f.objectStore("oob_membership_events"),m=IDBKeyRange.bound([e,c],[e,u]);A.log("LL: Deleting all users + marker in storage for room ".concat(e,", with key range:"),[e,c],[e,u]),yield zae(p.delete(m))})()}clearDatabase(){return new Promise(e=>{var t;A.log("Removing indexeddb instance: ".concat(this.dbName)),(t=this.db)===null||t===void 0||t.close();var r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{A.log("can't yet delete indexeddb ".concat(this.dbName," because it is open elsewhere"))},r.onerror=()=>{var i;A.warn("unable to delete js-sdk store indexeddb: ".concat((i=r.error)===null||i===void 0?void 0:i.name)),e()},r.onsuccess=()=>{A.log("Removed indexeddb instance: ".concat(this.dbName)),e()}})}getSavedSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(wE(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(e)})}syncToDatabase(e){var t=this;return F(function*(){return t.syncToDatabasePromise?(A.warn("Skipping syncToDatabase() as persist already in flight"),t.pendingUserPresenceData.push(...e),t.syncToDatabasePromise):(e.unshift(...t.pendingUserPresenceData),t.syncToDatabasePromise=t.doSyncToDatabase(e),t.syncToDatabasePromise)})()}doSyncToDatabase(e){var t=this;return F(function*(){try{var r=t.syncAccumulator.getJSON(!0);yield Promise.all([t.persistUserPresenceEvents(e),t.persistAccountData(r.accountData),t.persistSyncData(r.nextBatch,r.roomsData)])}finally{t.syncToDatabasePromise=void 0}})()}persistSyncData(e,t){return A.log("Persisting sync data up to",e),Uf(()=>{var r=this.db.transaction(["sync"],"readwrite"),i=r.objectStore("sync");return i.put({clobber:"-",nextBatch:e,roomsData:t}),Zu(r).then(()=>{A.log("Persisted sync data up to",e)})})}persistAccountData(e){return Uf(()=>{var t=this.db.transaction(["accountData"],"readwrite"),r=t.objectStore("accountData");for(var i of e)r.put(i);return Zu(t).then()})}persistUserPresenceEvents(e){return Uf(()=>{var t=this.db.transaction(["users"],"readwrite"),r=t.objectStore("users");for(var i of e)r.put({userId:i[0],event:i[1]});return Zu(t).then()})}getUserPresenceEvents(){return Uf(()=>{var e=this.db.transaction(["users"],"readonly"),t=e.objectStore("users");return k1(t,void 0,r=>[r.value.userId,r.value.event])})}loadAccountData(){return A.log("LocalIndexedDBStoreBackend: loading account data..."),Uf(()=>{var e=this.db.transaction(["accountData"],"readonly"),t=e.objectStore("accountData");return k1(t,void 0,r=>r.value).then(r=>(A.log("LocalIndexedDBStoreBackend: loaded account data"),r))})}loadSyncData(){return A.log("LocalIndexedDBStoreBackend: loading sync data..."),Uf(()=>{var e=this.db.transaction(["sync"],"readonly"),t=e.objectStore("sync");return k1(t,void 0,r=>r.value).then(r=>(A.log("LocalIndexedDBStoreBackend: loaded sync data"),r.length>1&&A.warn("loadSyncData: More than 1 sync row found."),r.length>0?r[0]:{}))})}getClientOptions(){return Promise.resolve().then(()=>{var e=this.db.transaction(["client_options"],"readonly"),t=e.objectStore("client_options");return k1(t,void 0,r=>{var i;return(i=r.value)===null||i===void 0?void 0:i.options}).then(r=>r[0])})}storeClientOptions(e){var t=this;return F(function*(){var r=t.db.transaction(["client_options"],"readwrite"),i=r.objectStore("client_options");i.put({clobber:"-",options:e}),yield Zu(r)})()}saveToDeviceBatches(e){var t=this;return F(function*(){var r=t.db.transaction(["to_device_queue"],"readwrite"),i=r.objectStore("to_device_queue");for(var s of e)i.add(s);yield Zu(r)})()}getOldestToDeviceBatch(){var e=this;return F(function*(){var t=e.db.transaction(["to_device_queue"],"readonly"),r=t.objectStore("to_device_queue"),i=yield d2(r.openCursor());if(!i)return null;var s=i.value;return{id:i.key,txnId:s.txnId,eventType:s.eventType,batch:s.batch}})()}removeToDeviceBatch(e){var t=this;return F(function*(){var r=t.db.transaction(["to_device_queue"],"readwrite"),i=r.objectStore("to_device_queue");i.delete(e),yield Zu(r)})()}destroy(){var e=this;return F(function*(){var t;(t=e.db)===null||t===void 0||t.close()})()}}class Yae{constructor(e,t){this.workerFactory=e,this.dbName=t,L(this,"worker",void 0),L(this,"nextSeq",0),L(this,"inFlight",{}),L(this,"startPromise",void 0),L(this,"onWorkerMessage",r=>{var i=r.data;if(i.command=="closed"){var s;(s=this.onClose)===null||s===void 0||s.call(this)}else if(i.command=="cmd_success"||i.command=="cmd_fail"){if(i.seq===void 0){A.error("Got reply from worker with no seq");return}var o=this.inFlight[i.seq];if(o===void 0){A.error("Got reply for unknown seq "+i.seq);return}if(delete this.inFlight[i.seq],i.command=="cmd_success")o.resolve(i.result);else{var a=new Error(i.error.message);a.name=i.error.name,o.reject(a)}}else A.warn("Unrecognised message from worker: ",i)})}connect(e){return this.onClose=e,this.ensureStarted().then(()=>this.doCmd("connect"))}clearDatabase(){return this.ensureStarted().then(()=>this.doCmd("clearDatabase"))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}saveToDeviceBatches(e){var t=this;return F(function*(){return t.doCmd("saveToDeviceBatches",[e])})()}getOldestToDeviceBatch(){var e=this;return F(function*(){return e.doCmd("getOldestToDeviceBatch")})()}removeToDeviceBatch(e){var t=this;return F(function*(){return t.doCmd("removeToDeviceBatch",[e])})()}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{A.log("IndexedDB worker is ready")})),this.startPromise}doCmd(e,t){return Promise.resolve().then(()=>{var r,i=this.nextSeq++,s=ru();return this.inFlight[i]=s,(r=this.worker)===null||r===void 0||r.postMessage({command:e,seq:i,args:t}),s.promise})}destroy(){var e=this;return F(function*(){var t;(t=e.worker)===null||t===void 0||t.terminate()})()}}var Jae=1e3*60*5;class rB extends Mv{static exists(e,t){return HN.exists(e,t)}constructor(e){if(super(e),L(this,"backend",void 0),L(this,"startedUp",!1),L(this,"syncTs",0),L(this,"userModifiedMap",{}),L(this,"emitter",new En),L(this,"onClose",()=>{this.emitter.emit("closed")}),L(this,"getSavedSync",this.degradable(()=>this.backend.getSavedSync(),"getSavedSync")),L(this,"isNewlyCreated",this.degradable(()=>this.backend.isNewlyCreated(),"isNewlyCreated")),L(this,"getSavedSyncToken",this.degradable(()=>this.backend.getNextBatchToken(),"getSavedSyncToken")),L(this,"deleteAllData",this.degradable(()=>(super.deleteAllData(),this.backend.clearDatabase().then(()=>{A.log("Deleted indexeddb data.")},t=>{throw A.error("Failed to delete indexeddb data: ".concat(t)),t})),null)),L(this,"reallySave",this.degradable(()=>{this.syncTs=Date.now();var t=[];for(var r of this.getUsers())this.userModifiedMap[r.userId]!==r.getLastModifiedTime()&&r.events.presence&&(t.push([r.userId,r.events.presence.event]),this.userModifiedMap[r.userId]=r.getLastModifiedTime());return this.backend.syncToDatabase(t)},null)),L(this,"setSyncData",this.degradable(t=>this.backend.setSyncData(t),"setSyncData")),L(this,"getOutOfBandMembers",this.degradable(t=>this.backend.getOutOfBandMembers(t),"getOutOfBandMembers")),L(this,"setOutOfBandMembers",this.degradable((t,r)=>(super.setOutOfBandMembers(t,r),this.backend.setOutOfBandMembers(t,r)),"setOutOfBandMembers")),L(this,"clearOutOfBandMembers",this.degradable(t=>(super.clearOutOfBandMembers(t),this.backend.clearOutOfBandMembers(t)),"clearOutOfBandMembers")),L(this,"getClientOptions",this.degradable(()=>this.backend.getClientOptions(),"getClientOptions")),L(this,"storeClientOptions",this.degradable(t=>(super.storeClientOptions(t),this.backend.storeClientOptions(t)),"storeClientOptions")),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new Yae(e.workerFactory,e.dbName):this.backend=new HN(e.indexedDB,e.dbName)}on(e,t){this.emitter.on(e,t)}startup(){return this.startedUp?(A.log("IndexedDBStore.startup: already started"),Promise.resolve()):(A.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then(()=>(A.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{A.log("IndexedDBStore.startup: processing presence events"),e.forEach(t=>{var[r,i]=t;if(!this.createUser)throw new Error("`IndexedDBStore.startup` must be called after assigning it to the client, not before!");var s=this.createUser(r);i&&s.setPresenceEvent(new wi(i)),this.userModifiedMap[s.userId]=s.getLastModifiedTime(),this.storeUser(s)}),this.startedUp=!0}))}destroy(){return this.backend.destroy()}wantsSave(){var e=Date.now();return e-this.syncTs>Jae}save(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){var r=this,i=t?super[t]:null;return F(function*(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];try{return yield e.call(r,...o)}catch(l){A.error("IndexedDBStore failure, degrading to MemoryStore",l),r.emitter.emit("degraded",l);try{A.log("IndexedDBStore trying to delete degraded data"),yield r.backend.clearDatabase(),A.log("IndexedDBStore delete after degrading succeeded")}catch(c){A.warn("IndexedDBStore delete after degrading failed",c)}if(i)return i.call(r,...o)}})}getPendingEvents(e){var t=()=>super.getPendingEvents,r=this;return F(function*(){if(!r.localStorage)return t().call(r,e);var i=r.localStorage.getItem(f2(e));if(i)try{return JSON.parse(i)}catch(s){A.error("Could not parse persisted pending events",s)}return[]})()}setPendingEvents(e,t){var r=()=>super.setPendingEvents,i=this;return F(function*(){if(!i.localStorage)return r().call(i,e,t);t.length>0?i.localStorage.setItem(f2(e),JSON.stringify(t)):i.localStorage.removeItem(f2(e))})()}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function f2(n){return"mx_pending_events_".concat(n)}var jo="crypto.",BN=jo+"migration",h2=jo+"account",Xae=jo+"cross_signing_keys",q_=jo+"inboundgroupsessions/",Zae=jo+"inboundgroupsessions.withheld/",Qae=jo+"rooms/",p2=jo+"sessionsneedingbackup";function Kf(n){return jo+"sessions/"+n}function m2(n,e){return q_+n+"/"+e}function ele(n,e){return Zae+n+"/"+e}function tle(n){return Qae+n}class jE extends CE{static exists(e){for(var t=e.length,r=0;r<t;r++){var i;if((i=e.key(r))!==null&&i!==void 0&&i.startsWith(jo))return!0}return!1}constructor(e){super(),this.store=e}containsData(){var e=this;return F(function*(){return jE.exists(e.store)})()}getMigrationState(){var e=this;return F(function*(){var t;return(t=Os(e.store,BN))!==null&&t!==void 0?t:sp.NOT_STARTED})()}setMigrationState(e){var t=this;return F(function*(){Qu(t.store,BN,e)})()}countEndToEndSessions(e,t){for(var r=0,i=0;i<this.store.length;++i){var s=this.store.key(i);if(s!=null&&s.startsWith(Kf(""))){var o=Os(this.store,s);r+=Object.keys(o??{}).length}}t(r)}_getEndToEndSessions(e){var t=Os(this.store,Kf(e)),r={};for(var[i,s]of Object.entries(t||{}))typeof s=="string"?r[i]={session:s}:r[i]=s;return r}getEndToEndSession(e,t,r,i){var s,o=this._getEndToEndSessions(e);i((s=o[t])!==null&&s!==void 0?s:{})}getEndToEndSessions(e,t,r){var i;r((i=this._getEndToEndSessions(e))!==null&&i!==void 0?i:{})}storeEndToEndSession(e,t,r,i){var s=this._getEndToEndSessions(e)||{};s[t]=r,Qu(this.store,Kf(e),s)}getEndToEndSessionsBatch(){var e=this;return F(function*(){for(var t=[],r=0;r<e.store.length;++r){var i;if((i=e.store.key(r))!==null&&i!==void 0&&i.startsWith(Kf(""))){var s=e.store.key(r).split("/")[1];for(var o of Object.values(e._getEndToEndSessions(s)))if(t.push(o),t.length>=op)return t}}return t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return F(function*(){for(var{deviceKey:r,sessionId:i}of e){var s=t._getEndToEndSessions(r)||{};delete s[i],Object.keys(s).length===0?t.store.removeItem(Kf(r)):Qu(t.store,Kf(r),s)}})()}getEndToEndInboundGroupSession(e,t,r,i){i(Os(this.store,m2(e,t)),Os(this.store,ele(e,t)))}storeEndToEndInboundGroupSession(e,t,r,i){Qu(this.store,m2(e,t),r)}countEndToEndInboundGroupSessions(){var e=this;return F(function*(){for(var t=0,r=0;r<e.store.length;++r){var i=e.store.key(r);i!=null&&i.startsWith(q_)&&(t+=1)}return t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return F(function*(){for(var t=Os(e.store,p2)||{},r=[],i=0;i<e.store.length;++i){var s=e.store.key(i);if(s!=null&&s.startsWith(q_)){var o=s.slice(q_.length);if(r.push({senderKey:o.slice(0,43),sessionId:o.slice(44),sessionData:Os(e.store,s),needsBackup:o in t}),r.length>=op)return r}}return r.length===0?null:r})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return F(function*(){for(var{senderKey:r,sessionId:i}of e){var s=m2(r,i);t.store.removeItem(s)}})()}getEndToEndRooms(e,t){for(var r={},i=tle(""),s=0;s<this.store.length;++s){var o=this.store.key(s);if(o!=null&&o.startsWith(i)){var a=o.slice(i.length);r[a]=Os(this.store,o)}}t(r)}markSessionsNeedingBackup(e){var t=Os(this.store,p2)||{};for(var r of e)t[r.senderKey+"/"+r.sessionId]=!0;return Qu(this.store,p2,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(h2),Promise.resolve()}getAccount(e,t){var r=Os(this.store,h2);t(r)}storeAccount(e,t){Qu(this.store,h2,t)}getCrossSigningKeys(e,t){var r=Os(this.store,Xae);t(r)}getSecretStorePrivateKey(e,t,r){var i=Os(this.store,jo+"ssss_cache.".concat(r));t(i)}storeSecretStorePrivateKey(e,t,r){Qu(this.store,jo+"ssss_cache.".concat(t),r)}doTxn(e,t,r){return Promise.resolve(r(null))}}function Os(n,e){try{return JSON.parse(n.getItem(e))}catch(t){A.log("Error: Failed to get key %s: %s",e,t.message),A.log(t.stack)}return null}function Qu(n,e,t){n.setItem(e,JSON.stringify(t))}let nle=class{constructor(e){this.db=e,L(this,"nextTxnId",0),e.onversionchange=()=>{A.log("versionchange for indexeddb ".concat(this.db.name,": closing")),e.close()}}containsData(){return F(function*(){throw Error("Not implemented for Backend")})()}startup(){var e=this;return F(function*(){return e})()}deleteAllData(){return F(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")})()}getMigrationState(){var e=this;return F(function*(){var t=sp.NOT_STARTED;return yield e.doTxn("readonly",[Lt.STORE_ACCOUNT],r=>{var i=r.objectStore(Lt.STORE_ACCOUNT),s=i.get(tk);s.onsuccess=()=>{var o;t=(o=s.result)!==null&&o!==void 0?o:sp.NOT_STARTED}}),t})()}setMigrationState(e){var t=this;return F(function*(){yield t.doTxn("readwrite",[Lt.STORE_ACCOUNT],r=>{var i=r.objectStore(Lt.STORE_ACCOUNT);i.put(e,tk)})})()}getAccount(e,t){var r=e.objectStore("account"),i=r.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}storeAccount(e,t){var r=e.objectStore("account");r.put(t,"-")}getCrossSigningKeys(e,t){var r=e.objectStore("account"),i=r.get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}getSecretStorePrivateKey(e,t,r){var i=e.objectStore("account"),s=i.get("ssss_cache:".concat(r));s.onsuccess=function(){try{t(s.result||null)}catch(o){Di(e,o)}}}storeSecretStorePrivateKey(e,t,r){var i=e.objectStore("account");i.put(r,"ssss_cache:".concat(t))}countEndToEndSessions(e,t){var r=e.objectStore("sessions"),i=r.count();i.onsuccess=function(){try{t(i.result)}catch(s){Di(e,s)}}}getEndToEndSessions(e,t,r){var i=t.objectStore("sessions"),s=i.index("deviceKey"),o=s.openCursor(e),a={};o.onsuccess=function(){var l=o.result;if(l)a[l.value.sessionId]={session:l.value.session,lastReceivedMessageTs:l.value.lastReceivedMessageTs},l.continue();else try{r(a)}catch(c){Di(t,c)}}}getEndToEndSession(e,t,r,i){var s=r.objectStore("sessions"),o=s.get([e,t]);o.onsuccess=function(){try{o.result?i({session:o.result.session,lastReceivedMessageTs:o.result.lastReceivedMessageTs}):i(null)}catch(a){Di(r,a)}}}storeEndToEndSession(e,t,r,i){var s=i.objectStore("sessions");s.put({deviceKey:e,sessionId:t,session:r.session,lastReceivedMessageTs:r.lastReceivedMessageTs})}getEndToEndSessionsBatch(){var e=this;return F(function*(){var t=[];return yield e.doTxn("readonly",[Lt.STORE_SESSIONS],r=>{var i=r.objectStore(Lt.STORE_SESSIONS),s=i.openCursor();s.onsuccess=function(){try{var o=s.result;o&&(t.push(o.value),t.length<op&&o.continue())}catch(a){Di(r,a)}}}),t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return F(function*(){yield t.doTxn("readwrite",[Lt.STORE_SESSIONS],function(){var r=F(function*(i){try{var s=i.objectStore(Lt.STORE_SESSIONS),o=function*(){var u=s.delete([a,l]);yield new Promise(f=>{u.onsuccess=f})};for(var{deviceKey:a,sessionId:l}of e)yield*o()}catch(c){Di(i,c)}});return function(i){return r.apply(this,arguments)}}())})()}getEndToEndInboundGroupSession(e,t,r,i){var s=!1,o=!1,a=r.objectStore("inbound_group_sessions"),l=a.get([e,t]);l.onsuccess=function(){try{l.result?s=l.result.session:s=null,o!==!1&&i(s,o)}catch(f){Di(r,f)}};var c=r.objectStore("inbound_group_sessions_withheld"),u=c.get([e,t]);u.onsuccess=function(){try{u.result?o=u.result.session:o=null,s!==!1&&i(s,o)}catch(f){Di(r,f)}}}storeEndToEndInboundGroupSession(e,t,r,i){var s=i.objectStore("inbound_group_sessions");s.put({senderCurve25519Key:e,sessionId:t,session:r})}countEndToEndInboundGroupSessions(){var e=this;return F(function*(){var t=0;return yield e.doTxn("readonly",[Lt.STORE_INBOUND_GROUP_SESSIONS],r=>{var i=r.objectStore(Lt.STORE_INBOUND_GROUP_SESSIONS),s=i.count();s.onsuccess=()=>{t=s.result}}),t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return F(function*(){var t=[];return yield e.doTxn("readonly",[Lt.STORE_INBOUND_GROUP_SESSIONS,Lt.STORE_BACKUP],r=>{var i=r.objectStore(Lt.STORE_INBOUND_GROUP_SESSIONS),s=r.objectStore(Lt.STORE_BACKUP),o=i.openCursor();o.onsuccess=function(){try{var a=o.result;if(a){var l=s.get(a.key);l.onsuccess=()=>{t.push({senderKey:a.value.senderCurve25519Key,sessionId:a.value.sessionId,sessionData:a.value.session,needsBackup:l.result!==void 0}),t.length<op&&a.continue()}}}catch(c){Di(r,c)}}}),t.length===0?null:t})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return F(function*(){yield t.doTxn("readwrite",[Lt.STORE_INBOUND_GROUP_SESSIONS],function(){var r=F(function*(i){try{var s=i.objectStore(Lt.STORE_INBOUND_GROUP_SESSIONS),o=function*(){var u=s.delete([a,l]);yield new Promise(f=>{u.onsuccess=f})};for(var{senderKey:a,sessionId:l}of e)yield*o()}catch(c){Di(i,c)}});return function(i){return r.apply(this,arguments)}}())})()}getEndToEndDeviceData(e,t){var r=e.objectStore("device_data"),i=r.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}getEndToEndRooms(e,t){var r={},i=e.objectStore("rooms"),s=i.openCursor();s.onsuccess=function(){var o=s.result;if(o)r[o.key]=o.value,o.continue();else try{t(r)}catch(a){Di(e,a)}}}markSessionsNeedingBackup(e,t){var r=this;return F(function*(){t||(t=r.db.transaction("sessions_needing_backup","readwrite"));var i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map(s=>new Promise((o,a)=>{var l=i.put({senderCurve25519Key:s.senderKey,sessionId:s.sessionId});l.onsuccess=o,l.onerror=a})))})()}doTxn(e,t,r){var i=this.db.transaction(t,e),s=sle(i),o=r(i);return s.then(()=>o)}};var iB=[n=>{ile(n)},n=>{n.createObjectStore("account")},n=>{var e=n.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]});e.createIndex("deviceKey","deviceKey")},n=>{n.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{n.createObjectStore("device_data")},n=>{n.createObjectStore("rooms")},n=>{n.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{n.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{var e=n.createObjectStore("session_problems",{keyPath:["deviceKey","time"]});e.createIndex("deviceKey","deviceKey"),n.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},n=>{n.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},n=>{n.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],sB=iB.length;function rle(n,e){A.log("Upgrading IndexedDBCryptoStore from version ".concat(e)+" to ".concat(sB)),iB.forEach((t,r)=>{e<=r&&t(n)})}function ile(n){var e=n.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});e.createIndex("session",["requestBody.room_id","requestBody.session_id"]),e.createIndex("state","state")}function Di(n,e){n._mx_abortexception=e;try{n.abort()}catch{}}function sle(n){return new Promise((e,t)=>{n.oncomplete=()=>{n._mx_abortexception!==void 0&&t(n._mx_abortexception),e(null)},n.onerror=r=>{n._mx_abortexception!==void 0?t(n._mx_abortexception):(A.log("Error performing indexeddb txn",r),t(n.error))},n.onabort=r=>{n._mx_abortexception!==void 0?t(n._mx_abortexception):(A.log("Error performing indexeddb txn",r),t(n.error))}})}class Lt{static exists(e,t){return eB(e,t)}static existsAndIsNotMigrated(e,t){return new Promise((r,i)=>{var s=!0,o=e.open(t);o.onupgradeneeded=()=>{s=!1},o.onblocked=()=>i(o.error),o.onsuccess=()=>{var a=o.result;if(!s)a.close(),e.deleteDatabase(t),r(!1);else{var l=a.transaction([Lt.STORE_ACCOUNT],"readonly"),c=l.objectStore(Lt.STORE_ACCOUNT),u=c.get(tk);u.onsuccess=()=>{var f,p=(f=u.result)!==null&&f!==void 0?f:sp.NOT_STARTED;r(p===sp.NOT_STARTED)},u.onerror=()=>{i(u.error)},a.close()}},o.onerror=()=>i(o.error)})}constructor(e,t){this.indexedDB=e,this.dbName=t,L(this,"backendPromise",void 0),L(this,"backend",void 0)}containsData(){var e=this;return F(function*(){return Lt.exists(e.indexedDB,e.dbName)})()}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}A.log("connecting to indexeddb ".concat(this.dbName));var r=this.indexedDB.open(this.dbName,sB);r.onupgradeneeded=i=>{var s=r.result,o=i.oldVersion;rle(s,o)},r.onblocked=()=>{A.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{A.log("Error connecting to indexeddb",i),t(r.error)},r.onsuccess=()=>{var i=r.result;A.log("connected to indexeddb ".concat(this.dbName)),e(new nle(i))}}).then(e=>e.doTxn("readonly",[Lt.STORE_INBOUND_GROUP_SESSIONS,Lt.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],t=>{e.getEndToEndInboundGroupSession("","",t,()=>{})}).then(()=>e)).catch(e=>{if(e.name==="VersionError")throw A.warn("Crypto DB is too new for us to use!",e),new eL(QP.TooNew);A.warn("unable to connect to indexeddb ".concat(this.dbName)+": falling back to localStorage store: ".concat(e));try{return new jE(globalThis.localStorage)}catch(t){return A.warn("unable to open localStorage: falling back to in-memory store: ".concat(t)),new CE}}).then(e=>(this.backend=e,e)),this.backendPromise)}deleteAllData(){return new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}A.log("Removing indexeddb instance: ".concat(this.dbName));var r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{A.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{A.log("Error deleting data from indexeddb",i),t(r.error)},r.onsuccess=()=>{A.log("Removed indexeddb instance: ".concat(this.dbName)),e()}}).catch(e=>{A.warn("unable to delete IndexedDBCryptoStore: ".concat(e))})}getMigrationState(){return this.backend.getMigrationState()}setMigrationState(e){return this.backend.setMigrationState(e)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,r){this.backend.getSecretStorePrivateKey(e,t,r)}storeSecretStorePrivateKey(e,t,r){this.backend.storeSecretStorePrivateKey(e,t,r)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,r,i){this.backend.getEndToEndSession(e,t,r,i)}getEndToEndSessions(e,t,r){this.backend.getEndToEndSessions(e,t,r)}storeEndToEndSession(e,t,r,i){this.backend.storeEndToEndSession(e,t,r,i)}countEndToEndInboundGroupSessions(){return this.backend.countEndToEndInboundGroupSessions()}getEndToEndSessionsBatch(){return this.backend.getEndToEndSessionsBatch()}deleteEndToEndSessionsBatch(e){return this.backend.deleteEndToEndSessionsBatch(e)}getEndToEndInboundGroupSession(e,t,r,i){this.backend.getEndToEndInboundGroupSession(e,t,r,i)}storeEndToEndInboundGroupSession(e,t,r,i){this.backend.storeEndToEndInboundGroupSession(e,t,r,i)}getEndToEndInboundGroupSessionsBatch(){return this.backend.getEndToEndInboundGroupSessionsBatch()}deleteEndToEndInboundGroupSessionsBatch(e){return this.backend.deleteEndToEndInboundGroupSessionsBatch(e)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}doTxn(e,t,r,i){return this.backend.doTxn(e,t,r,i)}}L(Lt,"STORE_ACCOUNT","account");L(Lt,"STORE_SESSIONS","sessions");L(Lt,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions");L(Lt,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld");L(Lt,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions");L(Lt,"STORE_PARKED_SHARED_HISTORY","parked_shared_history");L(Lt,"STORE_DEVICE_DATA","device_data");L(Lt,"STORE_ROOMS","rooms");L(Lt,"STORE_BACKUP","sessions_needing_backup");var ole=function(n){return n.Email="email",n.Phone="msisdn",n}({}),ale=new Kn("delegated_oidc_compatibility","org.matrix.msc3824.delegated_oidc_compatibility"),lle=function(n){return n.Gitlab="gitlab",n.Github="github",n.Apple="apple",n.Google="google",n.Facebook="facebook",n.Twitter="twitter",n}({}),cle=function(n){return n.LOGIN="login",n.REGISTER="register",n}({}),ule="us.cloke.msc4175.tz";class dle{constructor(e){L(this,"relations",void 0),this.relations=e.filter(t=>!!t)}getRelations(){return this.relations.reduce((e,t)=>[...e,...t.getRelations()],[])}on(e,t){this.relations.forEach(r=>r.on(e,t))}off(e,t){this.relations.forEach(r=>r.off(e,t))}}var fle=function(n){return n.Global="Global",n.SetItemError="setItem",n.GetItemError="getItem",n.RemoveItemError="removeItem",n.ClearError="clear",n.QuotaExceededError="QuotaExceededError",n}({});class hle extends En{}var ple=new hle,oB=()=>new CE;function aB(n){oB=n}function lB(n){var e,t,r;return n.store=(e=n.store)!==null&&e!==void 0?e:new Mv({localStorage:globalThis.localStorage}),n.scheduler=(t=n.scheduler)!==null&&t!==void 0?t:new ap,n.cryptoStore=(r=n.cryptoStore)!==null&&r!==void 0?r:oB(),n}function UE(n){return new DE(lB(n))}function cB(n,e,t,r){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return new JH(n,e,t,lB(r),i)}const mle=Object.freeze(Object.defineProperty({__proto__:null,AuthType:Hk,AutoDiscovery:it,AutoDiscoveryAction:gs,AutoDiscoveryError:to,Beacon:z$,BeaconEvent:yn,CallEvent:ft,CallFeedEvent:ia,Category:Za,ClientEvent:Oe,ClientPrefix:fr,ClientStoppedError:qoe,ConditionKind:ir,ConditionOperator:foe,ConnectionError:Jd,ContentHelpers:qie,DELEGATED_OIDC_COMPATIBILITY:ale,DEVICE_CODE_SCOPE:Tae,DMMemberCountCondition:hoe,Device:qae,DeviceVerification:ZH,Direction:ht,DuplicateStrategy:Vg,EVENT_VISIBILITY_CHANGE_TYPE:md,EventEmitterEvents:b$,EventStatus:et,EventTimeline:Le,EventTimelineSet:_h,EventType:ee,FILTER_RELATED_BY_REL_TYPES:jh,FILTER_RELATED_BY_SENDERS:Dh,FeatureSupport:si,Filter:Bi,GET_LOGIN_TOKEN_CAPABILITY:Lae,GroupCall:GP,GroupCallEvent:rn,GroupCallIntent:yH,GroupCallState:On,GroupCallStatsReportEvent:Og,GroupCallType:LE,GuestAccess:Xb,HTTPError:su,HistoryVisibility:YP,HttpApiEvent:dk,IdentityPrefix:Xa,IdentityProviderBrand:lle,IndexedDBCryptoStore:Lt,IndexedDBStore:rB,InteractiveAuth:aL,InvalidCryptoStoreError:eL,InvalidCryptoStoreState:QP,JoinRule:Wc,KNOWN_SAFE_ROOM_VERSION:cH,KeySignatureUploadError:Voe,KnownMembership:qe,LOCAL_NOTIFICATION_SETTINGS_PREFIX:C$,LocalStorageCryptoStore:jE,LocalStorageErrors:fle,LocationAssetType:ip,MAIN_ROOM_TIMELINE:wy,MAXIMUM_MATRIX_VERSION:boe,MINIMUM_MATRIX_VERSION:_oe,MSC3912_RELATION_BASED_REDACTIONS_PROP:ok,M_ASSET:Sy,M_BEACON:Ck,M_BEACON_INFO:JP,M_HTML:jie,M_LOCATION:Ey,M_MESSAGE:Die,M_POLL_END:Yb,M_POLL_KIND_DISCLOSED:Gie,M_POLL_KIND_UNDISCLOSED:Wie,M_POLL_RESPONSE:Rv,M_POLL_START:zie,M_TEXT:DP,M_TIMESTAMP:_u,M_TOPIC:jP,MatrixClient:DE,MatrixError:bn,MatrixEvent:wi,MatrixEventEvent:Mt,MatrixHttpApi:oH,MatrixScheduler:ap,MediaHandlerEvent:ad,MediaPrefix:Lh,MemoryCryptoStore:CE,MemoryStore:Mv,Method:ae,MsgType:La,NoAuthFlowFoundError:QH,NotificationCountType:jt,OidcError:oi,OidcTokenRefresher:Iae,PUSHER_DEVICE_ID:Sie,PUSHER_ENABLED:ak,PendingEventOrdering:cp,Poll:X$,PollEvent:xc,Preset:ME,ProfileKeyMSC4175Timezone:ule,PushRuleActionName:Gc,PushRuleKind:Lr,REFERENCE_RELATION:j$,ReceiptType:vi,RelatedRelations:dle,RelationType:un,Relations:NP,RelationsEvent:N_,RestrictedAllowType:Eoe,Room:xE,RoomCreateTypeField:Kb,RoomEvent:ke,RoomMember:wv,RoomMemberEvent:Wi,RoomNameType:ra,RoomState:Ov,RoomStateEvent:ut,RoomSummary:N$,RoomType:Ph,RoomVersionStability:aH,RoomWidgetClient:JH,RoomWidgetClientEvent:V_,RuleId:Pr,SERVICE_TYPES:Ek,SSOAction:cle,SUPPORTED_MATRIX_VERSIONS:kv,SearchOrderBy:SH,SearchResult:OE,SecretStorage:Hoe,ServerCapabilities:lH,SetPresence:uH,SlidingSyncEvent:wk,StatsReport:vl,SyncAccumulator:XH,SyncState:Dt,THREAD_RELATION_TYPE:Qt,Thread:fn,ThreadEvent:yi,ThreadFilterType:So,ThreepidMedium:ole,TimelineIndex:$k,TimelineWindow:Gae,ToDeviceMessageId:IE,TokenRefreshError:tH,TokenRefreshLogoutError:$P,TweakName:WP,TypedEventEmitter:En,UNSIGNED_MEMBERSHIP_FIELD:T$,UNSIGNED_THREAD_ID_FIELD:Gb,UNSTABLE_ELEMENT_FUNCTIONAL_USERS:w$,UNSTABLE_MSC2666_MUTUAL_ROOMS:BH,UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS:VH,UNSTABLE_MSC2666_SHARED_ROOMS:HH,UNSTABLE_MSC2716_MARKER:E$,UNSTABLE_MSC3088_ENABLED:ik,UNSTABLE_MSC3088_PURPOSE:rk,UNSTABLE_MSC3089_BRANCH:ul,UNSTABLE_MSC3089_LEAF:S$,UNSTABLE_MSC3089_TREE_SUBTYPE:sk,UNSTABLE_MSC3852_LAST_SEEN_UA:Pae,UNSTABLE_MSC4133_EXTENDED_PROFILES:qH,UNSTABLE_MSC4140_DELAYED_EVENTS:pa,UnsupportedDelayedEventsEndpointError:jc,UpdateDelayedEventAction:Sd,User:bl,UserEvent:qr,Visibility:bH,anySignal:nH,calculateRetryBackoff:BP,completeAuthorizationCodeGrant:Cae,createClient:UE,createNewMatrixCall:Iv,createRoomWidgetClient:cB,decodeBase64:Oh,decodeIdToken:jH,determineFeatureSupport:H_,discoverAndValidateOIDCIssuerWellKnown:sL,encodeBase64:D_,encodeUnpaddedBase64:mH,encodeUnpaddedBase64Url:PE,fixNotificationCountOnDecryption:KH,generateAuthorizationParams:bae,generateAuthorizationUrl:Sae,generateOidcAuthorizationUrl:Eae,generateScope:NE,getBeaconInfoIdentifier:zb,getHttpUriForMxc:TE,inMainTimelineForReceipt:Lv,isDmMemberCountCondition:poe,isEventTypeSame:Uie,isPollEvent:Z$,isTimestampInDuration:ck,localStorageErrorsEventsEmitter:ple,parseErrorResponse:HP,registerOidcClient:Rae,retryNetworkOperation:fk,safeGetRetryAfterMs:FP,setCryptoStoreFactory:aB,threadFilterTypeToFilter:GH,threadIdForReceipt:up,timeoutSignal:kE,validateAuthMetadata:DH,validateAuthMetadataAndKeys:oL,validateBearerTokenResponse:$H,validateIdToken:UH,validateStoredUserState:FH},Symbol.toStringTag,{value:"Module"}));if(globalThis.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");globalThis.__js_sdk_entrypoint=!0;var Bk;try{Bk=globalThis.indexedDB}catch{}Bk&&aB(()=>new Lt(Bk,"matrix-js-sdk:crypto"));globalThis.matrixcs=mle;var _=xP();const Ce=qo(_),uB=Bre({__proto__:null,default:Ce},[_]);var x1={},g2={exports:{}},ji={},v2={exports:{}},y2={};/**
35
35
  * @license React
36
36
  * scheduler.production.min.js
@@ -199,7 +199,7 @@ total: ${r}ms
199
199
  peerConnection: ${i}ms
200
200
  websocket: ${s}ms`)}}function Wt(n){return typeof n=="function"}function wZ(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var sI=wZ(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
201
201
  `+t.map(function(r,i){return i+1+") "+r.toString()}).join(`
202
- `):"",this.name="UnsubscriptionError",this.errors=t}});function QS(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Gy=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=gu(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(Wt(u))try{u()}catch(g){s=g instanceof sI?g.errors:[g]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var p=gu(f),m=p.next();!m.done;m=p.next()){var v=m.value;try{Fj(v)}catch(g){s=s??[],g instanceof sI?s=Qs(Qs([],Zs(s)),Zs(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new sI(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Fj(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&QS(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&QS(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),CZ=Gy.EMPTY;function TZ(n){return n instanceof Gy||n&&"closed"in n&&Wt(n.remove)&&Wt(n.add)&&Wt(n.unsubscribe)}function Fj(n){Wt(n)?n():n.unsubscribe()}var NAe={Promise:void 0},DAe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Qs([n,e],Zs(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function RZ(n){DAe.setTimeout(function(){throw n})}function eE(){}function Lb(n){n()}var g4=function(n){no(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,TZ(t)&&t.add(r)):r.destination=FAe,r}return e.create=function(t,r,i){return new sy(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Gy),jAe=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){h_(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){h_(r)}else h_(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){h_(t)}},n}(),sy=function(n){no(e,n);function e(t,r,i){var s=n.call(this)||this,o;return Wt(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new jAe(o),s}return e}(g4);function h_(n){RZ(n)}function UAe(n){throw n}var FAe={closed:!0,next:eE,error:UAe,complete:eE},v4=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function xu(n){return n}function $Ae(n){return n.length===0?xu:n.length===1?n[0]:function(t){return n.reduce(function(r,i){return i(r)},t)}}var jn=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=BAe(e)?e:new sy(e,t,r);return Lb(function(){var o=i,a=o.operator,l=o.source;s.add(a?a.call(s,l):l?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=$j(t),new t(function(i,s){var o=new sy({next:function(a){try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[v4]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return $Ae(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=$j(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function $j(n){var e;return(e=n??NAe.Promise)!==null&&e!==void 0?e:Promise}function HAe(n){return n&&Wt(n.next)&&Wt(n.error)&&Wt(n.complete)}function BAe(n){return n&&n instanceof g4||HAe(n)&&TZ(n)}function VAe(n){return Wt(n==null?void 0:n.lift)}function jr(n){return function(e){if(VAe(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function er(n,e,t,r,i){return new qAe(n,e,t,r,i)}var qAe=function(n){no(e,n);function e(t,r,i,s,o,a){var l=n.call(this,t)||this;return l.onFinalize=o,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(u){t.error(u)}}:n.prototype._next,l._error=s?function(c){try{s(c)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,l._complete=i?function(){try{i()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(g4),KAe=wZ(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Or=function(n){no(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new Hj(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new KAe},e.prototype.next=function(t){var r=this;Lb(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=gu(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(t)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;Lb(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;Lb(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?CZ:(this.currentObservers=null,a.push(t),new Gy(function(){r.currentObservers=null,QS(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new jn;return t.source=this,t},e.create=function(t,r){return new Hj(t,r)},e}(jn),Hj=function(n){no(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:CZ},e}(Or),rs=function(n){no(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e}(Or),y4={now:function(){return(y4.delegate||Date).now()},delegate:void 0},GAe=function(n){no(e,n);function e(t,r,i){t===void 0&&(t=1/0),r===void 0&&(r=1/0),i===void 0&&(i=y4);var s=n.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=i,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(t){var r=this,i=r.isStopped,s=r._buffer,o=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;i||(s.push(t),!o&&s.push(a.now()+l)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),i=this,s=i._infiniteTimeWindow,o=i._buffer,a=o.slice(),l=0;l<a.length&&!t.closed;l+=s?1:2)t.next(a[l]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,i=t._timestampProvider,s=t._buffer,o=t._infiniteTimeWindow,a=(o?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!o){for(var l=i.now(),c=0,u=1;u<s.length&&s[u]<=l;u+=2)c=u;c&&s.splice(0,c+1)}},e}(Or),WAe=function(n){no(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Gy),Bj={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,Qs([n,e],Zs(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},zAe=function(n){no(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),Bj.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&Bj.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,QS(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(WAe),Vj=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=y4.now,n}(),YAe=function(n){no(e,n);function e(t,r){r===void 0&&(r=Vj.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(Vj),Mw=new YAe(zAe),JAe=Mw,tE=new jn(function(n){return n.complete()});function IZ(n){return n&&Wt(n.schedule)}function _4(n){return n[n.length-1]}function b4(n){return Wt(_4(n))?n.pop():void 0}function Wy(n){return IZ(_4(n))?n.pop():void 0}function XAe(n,e){return typeof _4(n)=="number"?n.pop():e}var S4=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function kZ(n){return Wt(n==null?void 0:n.then)}function xZ(n){return Wt(n[v4])}function PZ(n){return Symbol.asyncIterator&&Wt(n==null?void 0:n[Symbol.asyncIterator])}function LZ(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ZAe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var OZ=ZAe();function MZ(n){return Wt(n==null?void 0:n[OZ])}function AZ(n){return c6(this,arguments,function(){var t,r,i,s;return pw(this,function(o){switch(o.label){case 0:t=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Tl(t.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Tl(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Tl(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function NZ(n){return Wt(n==null?void 0:n.getReader)}function Sr(n){if(n instanceof jn)return n;if(n!=null){if(xZ(n))return QAe(n);if(S4(n))return e5e(n);if(kZ(n))return t5e(n);if(PZ(n))return DZ(n);if(MZ(n))return n5e(n);if(NZ(n))return r5e(n)}throw LZ(n)}function QAe(n){return new jn(function(e){var t=n[v4]();if(Wt(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function e5e(n){return new jn(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function t5e(n){return new jn(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,RZ)})}function n5e(n){return new jn(function(e){var t,r;try{for(var i=gu(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function DZ(n){return new jn(function(e){i5e(n,e).catch(function(t){return e.error(t)})})}function r5e(n){return DZ(AZ(n))}function i5e(n,e){var t,r,i,s;return l6(this,void 0,void 0,function(){var o,a;return pw(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=u6(n),l.label=1;case 1:return[4,t.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function eu(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function jZ(n,e){return e===void 0&&(e=0),jr(function(t,r){t.subscribe(er(r,function(i){return eu(r,n,function(){return r.next(i)},e)},function(){return eu(r,n,function(){return r.complete()},e)},function(i){return eu(r,n,function(){return r.error(i)},e)}))})}function UZ(n,e){return e===void 0&&(e=0),jr(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function s5e(n,e){return Sr(n).pipe(UZ(e),jZ(e))}function o5e(n,e){return Sr(n).pipe(UZ(e),jZ(e))}function a5e(n,e){return new jn(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function l5e(n,e){return new jn(function(t){var r;return eu(t,e,function(){r=n[OZ](),eu(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return Wt(r==null?void 0:r.return)&&r.return()}})}function FZ(n,e){if(!n)throw new Error("Iterable cannot be null");return new jn(function(t){eu(t,e,function(){var r=n[Symbol.asyncIterator]();eu(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function c5e(n,e){return FZ(AZ(n),e)}function u5e(n,e){if(n!=null){if(xZ(n))return s5e(n,e);if(S4(n))return a5e(n,e);if(kZ(n))return o5e(n,e);if(PZ(n))return FZ(n,e);if(MZ(n))return l5e(n,e);if(NZ(n))return c5e(n,e)}throw LZ(n)}function zy(n,e){return e?u5e(n,e):Sr(n)}function Ct(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n);return zy(n,t)}function d5e(n){return!!n&&(n instanceof jn||Wt(n.lift)&&Wt(n.subscribe))}function f5e(n){return n instanceof Date&&!isNaN(n)}function Ne(n,e){return jr(function(t,r){var i=0;t.subscribe(er(r,function(s){r.next(n.call(e,s,i++))}))})}var h5e=Array.isArray;function p5e(n,e){return h5e(e)?n.apply(void 0,Qs([],Zs(e))):n(e)}function E4(n){return Ne(function(e){return p5e(n,e)})}var m5e=Array.isArray,g5e=Object.getPrototypeOf,v5e=Object.prototype,y5e=Object.keys;function $Z(n){if(n.length===1){var e=n[0];if(m5e(e))return{args:e,keys:null};if(_5e(e)){var t=y5e(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function _5e(n){return n&&typeof n=="object"&&g5e(n)===v5e}function HZ(n,e){return n.reduce(function(t,r,i){return t[r]=e[i],t},{})}function Hn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n),r=b4(n),i=$Z(n),s=i.args,o=i.keys;if(s.length===0)return zy([],t);var a=new jn(b5e(s,t,o?function(l){return HZ(o,l)}:xu));return r?a.pipe(E4(r)):a}function b5e(n,e,t){return t===void 0&&(t=xu),function(r){qj(e,function(){for(var i=n.length,s=new Array(i),o=i,a=i,l=function(u){qj(e,function(){var f=zy(n[u],e),p=!1;f.subscribe(er(r,function(m){s[u]=m,p||(p=!0,a--),a||r.next(t(s.slice()))},function(){--o||r.complete()}))},r)},c=0;c<i;c++)l(c)},r)}}function qj(n,e,t){n?eu(t,n,e):e()}function S5e(n,e,t,r,i,s,o,a){var l=[],c=0,u=0,f=!1,p=function(){f&&!l.length&&!c&&e.complete()},m=function(g){return c<r?v(g):l.push(g)},v=function(g){c++;var S=!1;Sr(t(g,u++)).subscribe(er(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{c--;for(var b=function(){var w=l.shift();o||v(w)};l.length&&c<r;)b();p()}catch(w){e.error(w)}}))};return n.subscribe(er(e,m,function(){f=!0,p()})),function(){}}function Yy(n,e,t){return t===void 0&&(t=1/0),Wt(e)?Yy(function(r,i){return Ne(function(s,o){return e(r,s,i,o)})(Sr(n(r,i)))},t):(typeof e=="number"&&(t=e),jr(function(r,i){return S5e(r,i,n,t)}))}function BZ(n){return n===void 0&&(n=1/0),Yy(xu,n)}function E5e(){return BZ(1)}function nE(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return E5e()(zy(n,Wy(n)))}function w5e(n){return new jn(function(e){Sr(n()).subscribe(e)})}function C5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=b4(n),r=$Z(n),i=r.args,s=r.keys,o=new jn(function(a){var l=i.length;if(!l){a.complete();return}for(var c=new Array(l),u=l,f=l,p=function(v){var g=!1;Sr(i[v]).subscribe(er(a,function(S){g||(g=!0,f--),c[v]=S},function(){return u--},void 0,function(){(!u||!g)&&(f||a.next(s?HZ(s,c):c),a.complete())}))},m=0;m<l;m++)p(m)});return t?o.pipe(E4(t)):o}var T5e=["addListener","removeListener"],R5e=["addEventListener","removeEventListener"],I5e=["on","off"];function Ea(n,e,t,r){if(Wt(t)&&(r=t,t=void 0),r)return Ea(n,e,t).pipe(E4(r));var i=Zs(P5e(n)?R5e.map(function(a){return function(l){return n[a](e,l,t)}}):k5e(n)?T5e.map(Kj(n,e)):x5e(n)?I5e.map(Kj(n,e)):[],2),s=i[0],o=i[1];if(!s&&S4(n))return Yy(function(a){return Ea(a,e,t)})(Sr(n));if(!s)throw new TypeError("Invalid event target");return new jn(function(a){var l=function(){for(var c=[],u=0;u<arguments.length;u++)c[u]=arguments[u];return a.next(1<c.length?c:c[0])};return s(l),function(){return o(l)}})}function Kj(n,e){return function(t){return function(r){return n[t](e,r)}}}function k5e(n){return Wt(n.addListener)&&Wt(n.removeListener)}function x5e(n){return Wt(n.on)&&Wt(n.off)}function P5e(n){return Wt(n.addEventListener)&&Wt(n.removeEventListener)}function Bc(n,e,t){n===void 0&&(n=0),t===void 0&&(t=JAe);var r=-1;return e!=null&&(IZ(e)?t=e:r=e),new jn(function(i){var s=f5e(n)?+n-t.now():n;s<0&&(s=0);var o=0;return t.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function tP(n,e){return n===void 0&&(n=0),e===void 0&&(e=Mw),n<0&&(n=0),Bc(n,n,e)}function oy(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n),r=XAe(n,1/0),i=n;return i.length?i.length===1?Sr(i[0]):BZ(r)(zy(i,t)):tE}var L5e=Array.isArray;function O5e(n){return n.length===1&&L5e(n[0])?n[0]:n}function Uo(n,e){return jr(function(t,r){var i=0;t.subscribe(er(r,function(s){return n.call(e,s,i++)&&r.next(s)}))})}function M5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return n=O5e(n),n.length===1?Sr(n[0]):new jn(A5e(n))}function A5e(n){return function(e){for(var t=[],r=function(s){t.push(Sr(n[s]).subscribe(er(e,function(o){if(t){for(var a=0;a<t.length;a++)a!==s&&t[a].unsubscribe();t=null}e.next(o)})))},i=0;t&&!e.closed&&i<n.length;i++)r(i)}}function N5e(n){return jr(function(e,t){var r=!1,i=null,s=null,o=!1,a=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var c=i;i=null,t.next(c)}o&&t.complete()},l=function(){s=null,o&&t.complete()};e.subscribe(er(t,function(c){r=!0,i=c,s||Sr(n(c)).subscribe(s=er(t,a,l))},function(){o=!0,(!r||!s||s.closed)&&t.complete()}))})}function D5e(n,e,t,r,i){return function(s,o){var a=t,l=e,c=0;s.subscribe(er(o,function(u){var f=c++;l=a?n(l,u,f):(a=!0,u),o.next(l)},i))}}function nP(n){return n<=0?function(){return tE}:jr(function(e,t){var r=0;e.subscribe(er(t,function(i){++r<=n&&(t.next(i),n<=r&&t.complete())}))})}function j5e(n){return Ne(function(){return n})}function U5e(n,e){return Yy(function(t,r){return Sr(n(t,r)).pipe(nP(1),j5e(t))})}function F5e(n,e){e===void 0&&(e=Mw);var t=Bc(n,e);return U5e(function(){return t})}function ya(n,e){return e===void 0&&(e=xu),n=n??$5e,jr(function(t,r){var i,s=!0;t.subscribe(er(r,function(o){var a=e(o);(s||!n(i,a))&&(s=!1,i=a,r.next(o))}))})}function $5e(n,e){return n===e}function H5e(n,e){return ya(function(t,r){return t[n]===r[n]})}function VZ(n){return jr(function(e,t){try{e.subscribe(t)}finally{t.add(n)}})}function el(n,e){return jr(D5e(n,e,arguments.length>=2,!0))}function B5e(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Or}:e,r=n.resetOnError,i=r===void 0?!0:r,s=n.resetOnComplete,o=s===void 0?!0:s,a=n.resetOnRefCountZero,l=a===void 0?!0:a;return function(c){var u,f,p,m=0,v=!1,g=!1,S=function(){f==null||f.unsubscribe(),f=void 0},b=function(){S(),u=p=void 0,v=g=!1},w=function(){var k=u;b(),k==null||k.unsubscribe()};return jr(function(k,R){m++,!g&&!v&&S();var I=p=p??t();R.add(function(){m--,m===0&&!g&&!v&&(f=oI(w,l))}),I.subscribe(R),!u&&m>0&&(u=new sy({next:function(C){return I.next(C)},error:function(C){g=!0,S(),f=oI(b,i,C),I.error(C)},complete:function(){v=!0,S(),f=oI(b,o),I.complete()}}),Sr(k).subscribe(u))})(c)}}function oI(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var i=new sy({next:function(){i.unsubscribe(),n()}});return Sr(e.apply(void 0,Qs([],Zs(t)))).subscribe(i)}}function V5e(n,e,t){var r,i,s,o,a=!1;return n&&typeof n=="object"?(r=n.bufferSize,o=r===void 0?1/0:r,i=n.windowTime,e=i===void 0?1/0:i,s=n.refCount,a=s===void 0?!1:s,t=n.scheduler):o=n??1/0,B5e({connector:function(){return new GAe(o,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:a})}function q5e(n){return Uo(function(e,t){return n<=t})}function dn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n);return jr(function(r,i){(t?nE(n,r,t):nE(n,r)).subscribe(i)})}function Pt(n,e){return jr(function(t,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};t.subscribe(er(r,function(l){i==null||i.unsubscribe();var c=0,u=s++;Sr(n(l,u)).subscribe(i=er(r,function(f){return r.next(e?e(l,f,u,c++):f)},function(){i=null,a()}))},function(){o=!0,a()}))})}function K5e(){return Pt(xu)}function G5e(n,e){return jr(function(t,r){var i=e;return Pt(function(s,o){return n(i,s,o)},function(s,o){return i=o,o})(t).subscribe(r),function(){i=null}})}function W5e(n){return jr(function(e,t){Sr(n).subscribe(er(t,function(){return t.complete()},eE)),!t.closed&&e.subscribe(t)})}function z5e(n,e,t){var r=Wt(n)||e||t?{next:n,error:e,complete:t}:n;return r?jr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(er(s,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),s.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),s.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),s.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):xu}function rP(n,e){return jr(function(t,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,l=a===void 0?!1:a,c=!1,u=null,f=null,p=!1,m=function(){f==null||f.unsubscribe(),f=null,l&&(S(),p&&r.complete())},v=function(){f=null,p&&r.complete()},g=function(b){return f=Sr(n(b)).subscribe(er(r,m,v))},S=function(){if(c){c=!1;var b=u;u=null,r.next(b),!p&&g(b)}};t.subscribe(er(r,function(b){c=!0,u=b,!(f&&!f.closed)&&(o?S():g(b))},function(){p=!0,!(l&&c&&f&&!f.closed)&&r.complete()}))})}function Y5e(n,e,t){e===void 0&&(e=Mw);var r=Bc(n,e);return rP(function(){return r},t)}function J5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=b4(n);return jr(function(r,i){for(var s=n.length,o=new Array(s),a=n.map(function(){return!1}),l=!1,c=function(f){Sr(n[f]).subscribe(er(i,function(p){o[f]=p,!l&&!a[f]&&(a[f]=!0,(l=a.every(xu))&&(a=null))},eE))},u=0;u<s;u++)c(u);r.subscribe(er(i,function(f){if(l){var p=Qs([f],Zs(o));i.next(t?t.apply(void 0,Qs([],Zs(p))):p)}}))})}function X5e(n,e,t){if(!t)return _.useState(e)[0];const[r]=_.useState(()=>new rs(t)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return n(()=>{if(s.current){s.current=!1;return}r.next(t)},t),i}function ay(n,e){return X5e(_.useEffect,n,e)}var Z5e=()=>new Or,Q5e=n=>n+1|0,eNe=()=>{const n=_.useState(0)[1];return _.useRef(()=>n(Q5e)).current},qZ=typeof window>"u"?_.useEffect:_.useLayoutEffect,Gj=n=>{var e;return(e=n[1])!=null&&e.next?n[1]:{next:n[1],error:n[2],complete:n[3]}};function tNe(n,e){const t=_.useRef(e),r=_.useRef(),i=_.useRef();return qZ(()=>{t.current=e,r.current=Gj(e)}),n(()=>{const s=t.current[0];r.current||(r.current=Gj(t.current));const o=s.subscribe({next:a=>{var l,c;s===t.current[0]&&((c=(l=r.current).next)==null||c.call(l,a))},error:a=>{s===t.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{var a,l;s===t.current[0]&&((l=(a=r.current).complete)==null||l.call(a))}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function nNe(n,e,t,r){return tNe(_.useEffect,[n,e,t,r])}function rNe(n,e,t){if(d5e(e)){const r=e,[i,s]=_.useState(()=>r instanceof rs||r.value!==void 0?r.value:t);return n(r,s),_.useDebugValue(i),i}else{const r=e,[i,s]=_.useState(t),[o]=_.useState(Z5e),[a]=_.useState(()=>r(o,i)),l=_.useRef(c=>o.next(c)).current;return n(a,s),_.useDebugValue(i),[i,l]}}function ly(n,e){return rNe(nNe,n,e)}function tt(n){const e=eNe(),t=_.useRef(n),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let l;return n.subscribe({next:c=>{s.current=!0,l=c},error:c=>{r.current=c}}).unsubscribe(),l});if(qZ(()=>{t.current=n}),_.useEffect(()=>{r.current=null;const l=t.current;let c=o;const u=l.subscribe({next:f=>{l===t.current&&(i.current?a(()=>f):c=f)},error:f=>{l===t.current&&(r.current=f,e())}});return i.current||c!==o&&a(()=>c),i.current=!0,()=>{u.unsubscribe()}},[n]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function iNe(n){const[e]=_.useState(()=>new rs(n)),[t]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[t,e]}class ui{constructor(e,t){this.defaultValue=t,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=t;if(r!==null)try{i=JSON.parse(r)}catch(s){A.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new rs(i),this.value$=this._value$}}function Xn(n){return[tt(n.value$),n.setValue]}const KZ=new ui("opt-in-analytics",null),Aw=()=>{const n=Xn(KZ);return Et.instance.isEnabled()?n:[!1,null]},GZ=new ui("developer-settings-tab",!1),WZ=new ui("duplicate-tiles",0),zZ=new ui("show-non-member-tiles",!1),w4=new ui("debug-tile-layout",!1),cy=new ui("show-connection-stats",!1),sNe=new ui("audio-input",void 0),oNe=new ui("audio-output",void 0),aNe=new ui("video-input",void 0),YZ=new ui("hand-raised-show-timer",!1),JZ=new ui("reactions-show",!0),C4=new ui("reactions-play-sound",!0),XZ=new ui("sound-effect-volume",.5),ZZ=new ui("new-membership-manager",!0),T4=new ui("experimental-to-device-transport",!0),Wj=new ui("always-show-self",!0);var Nw=(n=>(n[n.Guest=0]="Guest",n[n.Registered=1]="Registered",n))(Nw||{});const da=class da{constructor(e){this.posthog=e,this.enabled=!1,this.anonymity=0,this.platformSuperProperties={},this.registrationType=0,this.optInListener=null,this.sanitizeProperties=(i,s)=>(this.anonymity==1&&(i.$referrer=null,i.$referring_domain=null,i.$initial_referrer=null,i.$initial_referring_domain=null,i.$device_id=null),i.$current_url=i.$current_url.split("/").slice(0,3).join(""),i),this.eventCallEnded=new TAe,this.eventSignup=new IAe,this.eventCallStarted=new RAe,this.eventLogin=new kAe,this.eventMuteMicrophone=new xAe,this.eventMuteCamera=new PAe,this.eventUndecryptableToDevice=new LAe,this.eventQualitySurvey=new OAe,this.eventCallDisconnected=new MAe,this.eventCallConnectDuration=new AAe;let t,r;t=Yr().posthogApiKey??void 0,r=Yr().posthogApiHost??void 0,t&&r?(this.posthog.init(t,{api_host:r,autocapture:!1,mask_all_text:!0,mask_all_element_attributes:!0,capture_pageview:!1,sanitize_properties:this.sanitizeProperties,respect_dnt:!0,advanced_disable_decide:!0}),this.enabled=!0):(A.info("Posthog is not enabled because there is no api key or no host given in the config"),this.enabled=!1)}static hasInstance(){return!!this.internalInstance}static get instance(){return this.internalInstance||(this.internalInstance=new da(rAe)),this.internalInstance}static resetInstance(){this.internalInstance=null}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){var t,r;return{appVersion:"embedded-v0.10.0-rc.1",matrixBackend:Ge?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:Ge||(r=(t=window.matrixclient)==null?void 0:t.getCrypto())==null?void 0:r.getVersion()}}capture(e,t,r){this.enabled&&this.posthog.capture(e,{...t},r)}isEnabled(){return this.enabled}setAnonymity(e){this.enabled&&(e==0||e==1)&&(this.posthog.reset(),this.updateSuperProperties()),this.anonymity=e}static getRandomAnalyticsId(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16)).join("")}async identifyUser(e){if(this.anonymity==2&&this.enabled){let t=await this.getAnalyticsId();try{if(!t&&!Ge){const r=e();await this.setAccountAnalyticsId(r),t=await this.hashedEcAnalyticsId(r)}}catch(r){A.log("Unable to identify user for tracking"+(r==null?void 0:r.toString()))}t?this.posthog.identify(t):A.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let t;if(Ge)t=Yr().posthogUserId;else{const r=await e.getAccountDataFromServer(da.ANALYTICS_EVENT_TYPE);t=(r==null?void 0:r.id)??null}return t?await this.hashedEcAnalyticsId(t):null}async hashedEcAnalyticsId(e){const t=window.matrixclient,r="ec"+e+t.getUserId(),i=await crypto.subtle.digest("sha-256",new TextEncoder().encode(r)),s=new Int32Array(i);return Array.from(s).map(o=>Math.abs(o).toString(16).padStart(2,"0")).join("")}async setAccountAnalyticsId(e){if(!Ge){const t=window.matrixclient,r=await t.getAccountDataFromServer(da.ANALYTICS_EVENT_TYPE);await t.setAccountData(da.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){var e;this.enabled&&this.posthog.reset(),(e=this.optInListener)==null||e.unsubscribe(),this.optInListener=null,this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>A.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=da.getPlatformProperties(),this.registerSuperProperties({...this.platformSuperProperties,registrationType:this.registrationType==0?"Guest":"Registered"})}userRegisteredInThisSession(){return this.eventSignup.getSignupEndTime()>new Date(0)}async maybeIdentifyUser(){window.matrixclient&&(this.anonymity===2&&(this.setRegistrationType(window.matrixclient.isGuest()||window.passwordlessUser?0:1),this.identificationPromise=this.identifyUser(da.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...t},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,t,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{A.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){this.optInListener??(this.optInListener=KZ.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>A.log("Could not identify user"))}))}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};da.ANALYTICS_EVENT_TYPE="im.vector.analytics",da.internalInstance=null;let Et=da;const lNe=2*60*1e3;class cNe{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(t){A.debug(t)}}onEnd(e){switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipEnd(e);return}}get prevCall(){const e=localStorage.getItem("matrix-prev-call");if(e===null)return null;try{return JSON.parse(e)}catch(t){return A.warn("Invalid prev call data",e,"error:",t),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const t=this.prevCall,r=e.attributes["matrix.confId"];if(t!==null&&r===t.callId){const i=RD(e.startTime)-t.hangupTs;i<=lNe&&Et.instance.trackEvent({eventName:"Rejoin",callId:t.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:RD(e.endTime)}}onSummaryReportStart(e){const t=e.events.find(r=>r.name==="matrix.stats.summary");if(t!==void 0){const r=t.attributes;if(r){const i=`${r["matrix.stats.summary.percentageReceivedMedia"]}`,s=`${r["matrix.stats.summary.percentageReceivedVideoMedia"]}`,o=`${r["matrix.stats.summary.percentageReceivedAudioMedia"]}`,a=`${r["matrix.stats.summary.maxJitter"]}`,l=`${r["matrix.stats.summary.maxPacketLoss"]}`,c=`${r["matrix.stats.summary.peerConnections"]}`,u=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,f=`${r["matrix.stats.summary.opponentUsersInCall"]}`,p=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,m=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,v=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;Et.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:l,peerConnections:c,percentageConcealedAudio:u,opponentUsersInCall:f,opponentDevicesInCall:p,diffDevicesToPeerConnections:m,ratioPeerConnectionToDevices:v},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const zj=n=>Object.entries(n).map(([e,t])=>({key:e,type:typeof t,value:t}));class uNe{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,t=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=t.get(o);a===void 0&&(a=[],t.set(o,a)),a.push(s)}const r="p1",i={[r]:{serviceName:"element-call",tags:[]},warnings:null};return JSON.stringify({total:0,limit:0,offset:0,errors:null,data:[...t.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const l=a.spanContext(),c=VR(a.startTime),u=a.duration[0]===-1?e-c:VR(a.duration);return{traceID:s,spanID:l.spanId,operationName:a.name,processID:r,warnings:null,startTime:c,duration:u,references:a.parentSpanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanId}],tags:zj(a.attributes),logs:a.events.map(f=>({timestamp:VR(f.time),fields:[...zj(f.attributes??{}),{key:"event",type:"string",value:f.name}]}))}})}))})}async shutdown(){}}const dNe="element-call";let rd;class Dw{static globalInit(){(!rd||rd.isOtlpEnabled!==!1)&&(A.info("(Re)starting OpenTelemetry debug reporting"),rd==null||rd.dispose(),rd=new Dw(void 0,QZ()))}static get instance(){return rd}constructor(e,t){const r={resource:new Rx({[ROe.SERVICE_NAME]:dNe})};this._provider=new X6e(r),e?(A.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new G6e({url:e}),this._provider.addSpanProcessor(new $Le(this.otlpExporter))):A.info("OTLP collector disabled"),t&&(this.rageshakeProcessor=new uNe,this._provider.addSpanProcessor(this.rageshakeProcessor)),this._provider.addSpanProcessor(new cNe),$R.trace.setGlobalTracerProvider(this._provider),this._tracer=$R.trace.getTracer("my-element-call-otl-tracer")}dispose(){var e;$R.trace.disable(),(e=this._provider)==null||e.shutdown().catch(t=>{A.error("Failed to shutdown OpenTelemetry",t)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const Yj=async n=>{const{gzip:e}=await Cv(async()=>{const{gzip:r}=await import("./pako.esm-Bt8vjcgE.js");return{gzip:r}},[],import.meta.url),t=new TextEncoder().encode(n);return new Blob([e(t)])};async function fNe(n,e){e.append("crypto_version",n.getVersion());const t=await n.getOwnDeviceKeys(),r=[`curve25519:${t.curve25519}`,`ed25519:${t.ed25519}`];e.append("device_keys",r.join(", "));const i=await n.getCrossSigningStatus();e.append("cross_signing_ready",String(await n.isCrossSigningReady())),e.append("cross_signing_key",await n.getCrossSigningKeyId()??"n/a"),e.append("cross_signing_privkey_in_secret_storage",String(i.privateKeysInSecretStorage)),e.append("cross_signing_master_privkey_cached",String(i.privateKeysCachedLocally.masterKey)),e.append("cross_signing_self_signing_privkey_cached",String(i.privateKeysCachedLocally.selfSigningKey)),e.append("cross_signing_user_signing_privkey_cached",String(i.privateKeysCachedLocally.userSigningKey))}async function hNe(n,e,t){const r=n.secretStorage;t.append("secret_storage_ready",String(await e.isSecretStorageReady())),t.append("secret_storage_key_in_account",String(await r.hasKey())),t.append("session_backup_key_in_secret_storage",String(!!await n.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();t.append("session_backup_key_cached",String(!!i)),t.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function QZ(){return Yr().rageshakeSubmitUrl??void 0}function jw(n=QZ){const{client:e}=cf(),[{sending:t,sent:r,error:i},s]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async a=>{const l=n();if(!l)throw new Error("No rageshake URL is configured");if(!t)try{s({sending:!0,sent:!1,error:void 0});let c="UNKNOWN";window.navigator&&window.navigator.userAgent&&(c=window.navigator.userAgent);let u="UNKNOWN";try{u=String(window.matchMedia("(pointer: coarse)").matches)}catch(v){A.warn("Could not get coarse pointer for rageshake submit.",v)}let f=a.rageshakeRequestId?`Rageshake ${a.rageshakeRequestId}`:"";a.description&&(f+=`: ${a.description}`);const p=new FormData;if(p.append("text",f??"User did not supply any additional text."),p.append("app","matrix-video-chat"),p.append("version","embedded-v0.10.0-rc.1"),p.append("user_agent",c),p.append("installed_pwa","false"),p.append("touch_input",u),p.append("call_backend","livekit"),p.append("hostname",window.location.hostname),e){const v=e.getUserId(),g=e.getUser(v);p.append("display_name",(g==null?void 0:g.displayName)??""),p.append("user_id",e.credentials.userId??""),p.append("device_id",e.deviceId??""),a.roomId&&p.append("room_id",a.roomId);const S=e.getCrypto();S&&(await fNe(S,p),await hNe(e,S,p))}if(a.label&&p.append("label",a.label),navigator.storage&&navigator.storage.persisted)try{p.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(v){A.warn("coulr not get navigator peristed storage",v)}else if(document.hasStorageAccess)try{p.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(v){A.warn("could not get storage access",v)}if(navigator.storage&&navigator.storage.estimate)try{const v=await navigator.storage.estimate();p.append("storageManager_quota",String(v.quota)),p.append("storageManager_usage",String(v.usage)),v.usageDetails&&Object.keys(v.usageDetails).forEach(g=>{p.append(`storageManager_usage_${g}`,String(v.usageDetails[g]))})}catch(v){A.warn("could not obatain storage estimate",v)}if(a.sendLogs){const v=await N3e();for(const g of v)p.append("compressed-log",await Yj(g.lines),g.id);p.append("file",await Yj(Dw.instance.rageshakeProcessor.dump()),"traces.json.gz")}a.rageshakeRequestId&&p.append("group_call_rageshake_request_id",a.rageshakeRequestId);const m=await fetch(l,{method:"POST",body:p});if(m.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${m.status} ${m.statusText}`);s({sending:!1,sent:!0,error:void 0})}catch(c){s({sending:!1,sent:!1,error:c}),A.error(c)}},[e,t,n]),sending:t,sent:r,error:i,available:!!n()}}function pNe(){const{client:n}=cf();return _.useCallback((t,r)=>{n.sendEvent(t,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{A.error("Failed to send org.matrix.rageshake_request event",i)})},[n])}function mNe(n){const[e,t]=_.useState(!1),r=_.useCallback(()=>t(!1),[t]),{client:i}=cf(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=l=>{l.getType()==="org.matrix.rageshake_request"&&n===l.getRoomId()&&i.getUserId()!==l.getSender()&&(o(l.getContent().request_id),t(!0))};return i.on(Oe.Event,a),()=>{i.removeListener(Oe.Event,a)}},[t,n,i]),{rageshakeRequestId:s??"",roomId:n,open:e,onDismiss:r}}const gNe=({description:n})=>{var l;const{submitRageshake:e,sending:t,sent:r,error:i}=jw(),{t:s}=ze(),o=_.useCallback(()=>{e({description:n,sendLogs:!0}).catch(c=>{A.error("Failed to send rageshake",c)})},[e,n]);if(!((l=Ht.get().rageshake)!=null&&l.submit_url))return null;let a=null;if(t)a=E.jsx("span",{children:s("rageshake_sending")});else if(r)a=E.jsx("div",{children:s("rageshake_sent")});else{let c=s("rageshake_send_logs");i&&(c=s("rageshake_button_error_caption")),a=E.jsx(At,{onClick:o,className:bD.wideButton,disabled:t,children:c})}return E.jsx("div",{className:bD.rageshakeControl,children:a})},vNe="_error_19mk1_1",yNe="_icon_19mk1_9",p_={error:vNe,icon:yNe},_Ne="_endCall_bwclo_8",bNe={endCall:_Ne},eQ=({muted:n,...e})=>{const{t}=ze(),r=n?uJ:G6,i=t(n?"unmute_microphone_button_label":"mute_microphone_button_label");return E.jsx(li,{label:i,children:E.jsx(At,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},tQ=({muted:n,...e})=>{const{t}=ze(),r=n?lRe:LJ,i=t(n?"start_video_button_label":"stop_video_button_label");return E.jsx(li,{label:i,children:E.jsx(At,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},nQ=n=>{const{t:e}=ze();return E.jsx(li,{label:e("switch_camera"),children:E.jsx(At,{iconOnly:!0,Icon:sRe,kind:"secondary",...n})})},SNe=({enabled:n,...e})=>{const{t}=ze(),r=t(n?"stop_screenshare_button_label":"screenshare_button_label");return E.jsx(li,{label:r,children:E.jsx(At,{iconOnly:!0,Icon:nRe,kind:n?"primary":"secondary",...e})})},rQ=({className:n,...e})=>{const{t}=ze();return E.jsx(li,{label:t("hangup_button_label"),children:E.jsx(At,{className:Ae(n,bNe.endCall),iconOnly:!0,Icon:tJ,destructive:!0,...e})})},iQ=n=>{const{t:e}=ze();return E.jsx(li,{label:e("common.settings"),children:E.jsx(At,{iconOnly:!0,Icon:tRe,kind:"secondary",...n})})},ENe="_external_jhjdf_8",wNe={external:ENe};function sQ(n,e){const t=cq(n),r=_q(n,{state:e});return[t,r]}const ka=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=sQ(e,t);return E.jsx(ACe,{ref:i,...r,href:s,onClick:o})}),Pd=_.forwardRef(function({className:e,children:t,...r},i){return E.jsx("a",{ref:i,className:Ae(e,wNe.external),target:"_blank",rel:"noreferrer noopener",...r,children:t})}),R4=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=sQ(e,t);return E.jsx(At,{as:"a",ref:i,...r,href:s,onClick:o})});function oQ(n){const[e,t]=_.useState(n.memberships),r=_.useCallback(()=>{A.info(`Memberships changed for call in room ${n.room.roomId} (${n.memberships.length} members)`),t(n.memberships)},[n]);return _.useEffect(()=>(n.on(ar.MembershipsChanged,r),()=>{n.off(ar.MembershipsChanged,r)}),[n,r]),e}const aQ=_.createContext(void 0),I4=()=>{const n=_.useContext(aQ);if(!n)throw new Error("useReactions must be used within a ReactionsProvider");return n},CNe=({children:n,rtcSession:e,vm:t})=>{const r=oQ(e),i=nm(),s=(i==null?void 0:i.state)==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),l=o.client.getDeviceId(),c=`${a}:${l}`,u=_.useMemo(()=>{var b;return(b=r.find(w=>w.sender===a&&w.deviceId===l))==null?void 0:b.eventId},[r,a,l]),f=tt(t.reactions$),p=_.useMemo(()=>c!==void 0?f[c]:void 0,[c,f]),m=tt(t.handsRaised$),v=_.useMemo(()=>c!==void 0?m[c]:void 0,[c,m]),g=_.useCallback(async()=>{if(!c)return;const b=v==null?void 0:v.reactionEventId;if(b)try{await o.client.redactEvent(e.room.roomId,b),A.debug("Redacted raise hand event")}catch(w){throw A.error("Failed to redact reaction event",b,w),w}else try{if(!u)throw new Error("Cannot find own membership event");const w=await o.client.sendEvent(e.room.roomId,ee.Reaction,{"m.relates_to":{rel_type:un.Annotation,event_id:u,key:"🖐️"}});A.debug("Sent raise hand event",w.event_id)}catch(w){A.error("Failed to send raised hand",w)}},[u,c,v,e,o]),S=_.useCallback(async b=>{if(!(!c||p)){if(!u)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,m4,{"m.relates_to":{rel_type:un.Reference,event_id:u},emoji:b.emoji,name:b.name})}},[u,p,o,c,e]);return E.jsx(aQ.Provider,{value:{supportsReactions:s,toggleRaisedHand:g,sendReaction:S},children:n})},TNe="_raisedButton_unw54_1",RNe="_reactionPopupMenu_unw54_5",INe="_reactionPopupMenuRoot_unw54_21",kNe="_reactionPopupMenuModal_unw54_21",xNe="_reactionsMenuSection_unw54_47",PNe="_reactionsMenu_unw54_47",LNe="_reactionButton_unw54_81",ONe="_verticalSeperator_unw54_91",MNe="_alert_unw54_99",Eo={raisedButton:TNe,reactionPopupMenu:RNe,reactionPopupMenuRoot:INe,reactionPopupMenuModal:kNe,reactionsMenuSection:xNe,reactionsMenu:PNe,reactionButton:LNe,verticalSeperator:ONe,alert:MNe};var lQ=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(NNe);if(s){const o=s.props.children,a=i.map(l=>l===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:l);return E.jsx(iP,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return E.jsx(iP,{...r,ref:e,children:t})});lQ.displayName="Slot";var iP=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=jNe(t),s=DNe(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Fa(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});iP.displayName="SlotClone";var ANe=({children:n})=>E.jsx(E.Fragment,{children:n});function NNe(n){return _.isValidElement(n)&&n.type===ANe}function DNe(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function jNe(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var UNe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],FNe=UNe.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?lQ:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{}),$Ne="VisuallyHidden",sP=_.forwardRef((n,e)=>E.jsx(FNe.span,{...n,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...n.style}}));sP.displayName=$Ne;const HNe="_modal_lmgdq_8",BNe="_dialog_lmgdq_14",VNe="_content_lmgdq_21",qNe="_drawer_lmgdq_32",KNe="_close_lmgdq_59",GNe="_header_lmgdq_84",WNe="_body_lmgdq_114",zNe="_tabbed_lmgdq_129",YNe="_handle_lmgdq_133",Ui={modal:HNe,dialog:BNe,content:VNe,drawer:qNe,close:KNe,header:GNe,body:WNe,tabbed:zNe,handle:YNe},JNe="_bg_197ap_8",XNe="_animate_197ap_23",ZNe="_overlay_197ap_40",va={bg:JNe,animate:XNe,overlay:ZNe},lf=({title:n,hideHeader:e,children:t,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:l,...c})=>{const{t:u}=ze(),f=Ew("(hover: none) or (pointer: coarse)"),p=_.useCallback(m=>{m||a==null||a()},[a]);if(f)return E.jsx(Gi.Root,{open:o,onOpenChange:p,dismissible:a!==void 0,children:E.jsxs(Gi.Portal,{children:[E.jsx(Gi.Overlay,{className:Ae(va.bg)}),E.jsx(Gi.Content,{className:Ae(r,i,va.overlay,Ui.modal,Ui.drawer,{[Ui.tabbed]:l}),role:"dialog","aria-describedby":void 0,...c,children:E.jsxs("div",{className:Ui.content,children:[E.jsxs("div",{className:Ui.header,children:[E.jsx("div",{className:Ui.handle}),E.jsx(sP,{asChild:!0,children:E.jsx(Gi.Title,{children:n})})]}),E.jsx("div",{className:Ui.body,children:t})]})})]})});{const m=E.jsx(P6,{asChild:!0,children:E.jsx(Ru,{as:"h2",weight:"semibold",size:"md",children:n})}),v=E.jsxs("div",{className:Ui.header,children:[m,a!==void 0&&E.jsx(eY,{className:Ui.close,"data-testid":"modal_close","aria-label":u("action.close"),children:E.jsx(aw,{width:20,height:20})})]});return E.jsx(R6,{open:o,onOpenChange:p,children:E.jsxs(I6,{children:[E.jsx(k6,{className:Ae(va.bg,va.animate)}),E.jsx(x6,{asChild:!0,"aria-describedby":void 0,role:"dialog",...c,children:E.jsx(fY,{className:Ae(r,s,va.overlay,va.animate,Ui.modal,Ui.dialog,{[Ui.tabbed]:l}),children:E.jsxs("div",{className:Ui.content,children:[e?null:v,e?E.jsx(sP,{asChild:!0,children:m}):null,E.jsx("div",{className:Ui.body,children:t})]})})})]})})}},QNe=({raised:n,open:e,...t})=>{const{t:r}=ze();return E.jsx(li,{label:r("common.reactions"),children:E.jsx(At,{className:Ae(n&&Eo.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:n||e?"primary":"secondary",iconOnly:!0,Icon:n?yJ:eRe,...t})})};function e8e({sendReaction:n,toggleRaisedHand:e,isHandRaised:t,canReact:r,errorText:i}){const{t:s}=ze(),[o,a]=_.useState(!1),l=_.useMemo(()=>o?iy:iy.slice(0,5),[o]),c=s(t?"action.lower_hand":"action.raise_hand");return E.jsxs(E.Fragment,{children:[i&&E.jsx(Q_e,{className:Eo.alert,type:"critical",title:s("error.generic"),children:i}),E.jsxs("div",{className:Eo.reactionPopupMenu,children:[E.jsx("section",{className:Eo.handRaiseSection,children:E.jsx(li,{label:c,caption:"H",children:E.jsx(At,{kind:t?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":t,"aria-label":c,onClick:()=>e(),iconOnly:!0,Icon:yJ})})}),E.jsx("div",{className:Eo.verticalSeperator}),E.jsx("section",{className:Eo.reactionsMenuSection,children:E.jsx("menu",{className:Ae(o&&Eo.reactionsMenuExpanded,Eo.reactionsMenu),children:l.map((u,f)=>E.jsx("li",{children:E.jsx(li,{label:u.name,caption:f<eP?(f+1).toString():void 0,children:E.jsx(At,{kind:"secondary",className:Eo.reactionButton,disabled:!r,onClick:()=>n(u),"aria-keyshortcuts":f<eP?(f+1).toString():void 0,children:u.emoji})})},u.name))})}),E.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:E.jsx(li,{label:s(o?"action.show_less":"action.show_more"),children:E.jsx(At,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?V2e:p2e,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function t8e({identifier:n,vm:e,...t}){const{t:r}=ze(),{toggleRaisedHand:i,sendReaction:s}=I4(),[o,a]=_.useState(!1),[l,c]=_.useState(!1),[u,f]=_.useState(),p=ly(e.handsRaised$.pipe(Ne(S=>!!S[n]))),m=ly(e.reactions$.pipe(Ne(S=>!S[n])));_.useEffect(()=>{f(void 0)},[l]);const v=_.useCallback(async S=>{try{a(!0),await s(S),f(void 0),c(!1)}catch(b){f(b instanceof Error?b.message:"Unknown error"),A.error("Failed to send reaction",b)}finally{a(!1)}},[s]),g=_.useCallback(()=>{(async()=>{try{a(!0),await i(),c(!1)}catch(b){f(b instanceof Error?b.message:"Unknown error"),A.error("Failed to raise/lower hand",b)}finally{a(!1)}})()},[i]);return E.jsxs(E.Fragment,{children:[E.jsx(QNe,{disabled:o,onClick:()=>c(S=>!S),raised:!!p,open:l,...t}),E.jsx(lf,{open:l,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Eo.reactionPopupMenuModal,className:Eo.reactionPopupMenuRoot,onDismiss:()=>c(!1),children:E.jsx(e8e,{errorText:u,isHandRaised:!!p,canReact:!o&&!!m,sendReaction:S=>void v(S),toggleRaisedHand:g})})]})}const uy=({Icon:n,title:e,rageshake:t,fatal:r,children:i,widget:s})=>{const{t:o}=ze(),{confineToRoom:a}=ku(),l=_.useCallback(()=>{window.location.href="/"},[]),c=({widget:f})=>{const p=()=>{f.api.transport.send(Ar.Close,{}).catch(m=>{A.error("Failed to send close action",m)}).finally(()=>{f.api.transport.stop()})};return E.jsx(At,{kind:"primary",onClick:p,children:o("action.close")})},u=()=>r||location.pathname==="/"?E.jsx(At,{kind:"tertiary",className:p_.homeLink,onClick:l,children:o("return_home_button")}):E.jsx(R4,{kind:"tertiary",className:p_.homeLink,to:"/",children:o("return_home_button")});return E.jsxs("div",{className:p_.error,children:[E.jsx(l2e,{className:p_.icon,children:E.jsx(n,{})}),E.jsx(Ru,{as:"h1",weight:"semibold",size:"md",children:e}),i,t&&E.jsx(gNe,{description:`***Error View***: ${e}`}),s?E.jsx(c,{widget:s}):!a&&E.jsx(u,{})]})};class cQ extends Error{constructor(e,t){super(e),this.richMessage=t}}const n8e=()=>{const{t:n}=ze();return E.jsx(uy,{widget:Ge,Icon:gJ,title:n("error.open_elsewhere"),children:E.jsx("p",{children:n("error.open_elsewhere_description",{brand:"Element Call"})})})};class r8e extends cQ{constructor(){super("App opened in another tab",E.jsx(n8e,{}))}}const Qh=({className:n,children:e})=>{const{hideHeader:t}=ku();return E.jsxs("div",{className:Ae(OR.page,n),children:[!t&&E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(Vd,{})}),E.jsx(of,{})]}),E.jsx("div",{className:OR.container,children:E.jsx("div",{className:OR.content,children:e})})]})},dy=({error:n,widget:e})=>{const{t}=ze();return _.useEffect(()=>{A.error(n),nw(n)},[n]),E.jsx(Qh,{children:n instanceof cQ?n.richMessage:E.jsx(uy,{widget:e,Icon:ow,title:t("error.generic"),rageshake:!0,fatal:!0,children:E.jsx("p",{children:t("error.generic_description")})})})},Uw=()=>{const{t:n}=ze();return E.jsx(Qh,{children:E.jsx("h1",{children:n("common.loading")})})},k4=_.createContext(void 0);k4.Provider;const nm=()=>_.useContext(k4);function cf(){var r;let n,e;const t=nm();return(t==null?void 0:t.state)==="valid"&&(n=(r=t.authenticated)==null?void 0:r.client,e=t.setClient),{client:n,setClient:e}}function x4(){var l,c,u;const n=nm();let e,t,r=!1,i=!0,s,o=!1,a;return(n==null?void 0:n.state)==="valid"?(e=(l=n.authenticated)==null?void 0:l.client,t=n.setClient,r=((c=n.authenticated)==null?void 0:c.isPasswordlessUser)??!1,i=!1,o=e!==void 0,a=(u=n.authenticated)==null?void 0:u.logout):(n==null?void 0:n.state)==="error"&&(s=n.error,i=!1),{client:e,setClient:t,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const m_="BroadcastChannel"in window?new BroadcastChannel("load"):null,i8e=({children:n})=>{const e=Na(),[t,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,s8e().then(w=>{r(w),Et.instance.isEnabled()&&Et.instance.startListeningToSettingsChanges()}).catch(w=>A.error(w)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async w=>{const k=dQ();!(t!=null&&t.client)||!k||(await t.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:k.user_id},user:k.user_id,password:k.tempPassword},w),Jj({...k,passwordlessUser:!1}),r({...t,passwordlessUser:!1}))},[t]),o=_.useCallback((w,k)=>{const R=t==null?void 0:t.client;R&&R!==w&&R.stopClient(),Jj(k),r({widgetApi:null,client:w,passwordlessUser:k.passwordlessUser}),Et.instance.isEnabled()&&Et.instance.startListeningToSettingsChanges()},[t==null?void 0:t.client]),a=_.useCallback(async()=>{const w=t==null?void 0:t.client;w&&(await w.logout(!0),await w.clearStores(),uQ(),r(null),await e("/"),Et.instance.logout(),Et.instance.setRegistrationType(Nw.Guest))},[e,t==null?void 0:t.client]);_.useEffect(()=>{Ge||m_==null||m_.postMessage({})},[]);const[l,c]=_.useState(void 0);ov(m_,"message",_.useCallback(()=>{t==null||t.client.stopClient(),c(new r8e)},[t==null?void 0:t.client,c]));const[u,f]=_.useState(!1),[p,m]=_.useState(!1),[v,g]=_.useState(!1),S=_.useMemo(()=>l?{state:"error",error:l}:t===void 0?void 0:{state:"valid",authenticated:t===null?void 0:{client:t.client,isPasswordlessUser:t.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:u,supportedFeatures:{reactions:p,thumbnails:v}},[l,s,t,a,o,u,p,v]),b=_.useCallback((w,k,R)=>{f(o8e(w,R))},[]);return _.useEffect(()=>{if(t){if(window.matrixclient=t.client,window.passwordlessUser=t.passwordlessUser,Et.hasInstance()&&Et.instance.onLoginStatusChanged(),t.client&&t.client.on(Oe.Sync,b),t.widgetApi){g(!1);const w=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),k=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),R=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),I=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!w||!R||!k||!I?(A.warn("Widget does not support reactions"),m(!1)):m(!0)}else m(!0),g(!0);return()=>{t.client&&t.client.removeListener(Oe.Sync,b)}}},[t,b]),l?E.jsx(dy,{widget:Ge,error:l}):E.jsx(k4.Provider,{value:S,children:n})};async function s8e(){if(Ge){A.log("Using a matryoshka client");const n=await Ge.client;return{widgetApi:Ge.api,client:n,passwordlessUser:!1}}else{const{initSPA:n}=await Cv(async()=>{const{initSPA:e}=await import("./spa-DaNLMdaT.js");return{initSPA:e}},[],import.meta.url);return n(dQ,uQ)}}const uQ=()=>localStorage.removeItem("matrix-auth-store"),Jj=n=>localStorage.setItem("matrix-auth-store",JSON.stringify(n)),dQ=()=>{const n=localStorage.getItem("matrix-auth-store");if(n)return JSON.parse(n)},o8e=(n,e)=>{var t;return n==="ERROR"&&((t=e==null?void 0:e.error)==null?void 0:t.name)==="ConnectionError"};function Jy(n){const[{success:e,loading:t,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let l;return n&&(l=n.getUser(n.getUserId())??void 0),{success:!1,loading:!1,displayName:l==null?void 0:l.rawDisplayName,avatarUrl:l==null?void 0:l.avatarUrl,error:void 0}});_.useEffect(()=>{const l=(u,{displayName:f,avatarUrl:p})=>{o({success:!1,loading:!1,displayName:f,avatarUrl:p,error:void 0})};let c;if(n){const u=n.getUserId();c=n.getUser(u),c==null||c.on(qr.DisplayName,l),c==null||c.on(qr.AvatarUrl,l)}return()=>{c&&(c.removeListener(qr.DisplayName,l),c.removeListener(qr.AvatarUrl,l))}},[n]);const a=_.useCallback(async({displayName:l,avatar:c,removeAvatar:u})=>{if(n){o(f=>({...f,loading:!0,error:void 0,success:!1}));try{await n.setDisplayName(l);let f;u?await n.setAvatarUrl(""):c&&({content_uri:f}=await n.uploadContent(c),await n.setAvatarUrl(f)),o(p=>({...p,displayName:l,avatarUrl:u?void 0:f??p.avatarUrl,loading:!1,success:!0}))}catch(f){o(p=>({...p,loading:!1,error:f instanceof Error?f:Error(f),success:!1}))}}else A.error("Client not initialized before calling saveProfile")},[n]);return{loading:t,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const a8e="_settingsModal_1dkeq_8",l8e="_volumeSlider_1dkeq_20",Xj={settingsModal:a8e,volumeSlider:l8e},c8e="_tabContainer_1nnp9_8",u8e="_tabList_1nnp9_14",Zj={tabContainer:c8e,tabList:u8e};function d8e({label:n,tab:e,onTabChange:t,tabs:r}){const i=_.useId();return E.jsxs("div",{className:Zj.tabContainer,children:[E.jsx(c2e,{role:"tablist","aria-label":n,className:Zj.tabList,children:r.map(({key:s,name:o})=>E.jsx(h2e,{"aria-controls":`${i}[${s}]`,onClick:()=>t(s),active:s===e,children:o}))}),r.map(({key:s,content:o})=>E.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o}))]})}const f8e="_fieldRow_iwncy_8",h8e="_field_iwncy_8",p8e="_rightAlign_iwncy_21",m8e="_inputField_iwncy_33",g8e="_disabled_iwncy_52",v8e="_prefix_iwncy_110",y8e="_checkboxField_iwncy_131",_8e="_checkbox_iwncy_131",b8e="_description_iwncy_168",S8e="_errorMessage_iwncy_197",E8e="_noLabel_iwncy_210",As={fieldRow:f8e,field:h8e,rightAlign:p8e,inputField:m8e,disabled:g8e,prefix:v8e,checkboxField:y8e,checkbox:_8e,description:b8e,errorMessage:S8e,noLabel:E8e},w8e=(n,e)=>_.createElement("svg",{fill:"none",height:24,stroke:"#000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,viewBox:"0 0 24 24",width:24,xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"m20 6-11 11-5-5"})),C8e=_.forwardRef(w8e);class fQ extends Error{constructor(e,t){super(t(e,{lng:"en"})),this.translatedMessage=t(e)}}class T8e extends fQ{}const Qj=(n,e)=>new T8e(n,e);function vt({children:n,rightAlign:e,className:t}){return E.jsx("div",{className:Ae(As.fieldRow,{[As.rightAlign]:e},t),children:n})}function R8e({children:n,className:e}){return E.jsx("div",{className:Ae(As.field,e),children:n})}const _n=_.forwardRef(({id:n,label:e,className:t,type:r,checked:i,prefix:s,suffix:o,description:a,disabled:l,min:c,...u},f)=>{const p=_.useId();return E.jsxs(R8e,{className:Ae(r==="checkbox"?As.checkboxField:As.inputField,{[As.prefix]:!!s,[As.disabled]:l},t),children:[s&&E.jsx("span",{children:s}),r==="textarea"?E.jsx("textarea",{id:n,ref:f,disabled:l,"aria-describedby":p,...u}):E.jsx("input",{id:n,ref:f,type:r,checked:i,disabled:l,"aria-describedby":p,min:c,...u}),E.jsxs("label",{htmlFor:n,children:[r==="checkbox"&&E.jsx("div",{className:As.checkbox,children:E.jsx(C8e,{})}),e]}),o&&E.jsx("span",{children:o}),a&&E.jsx("p",{id:p,className:e?As.description:Ae(As.description,As.noLabel),children:a})]})});_n.displayName="InputField";const Pu=({error:n})=>E.jsx("p",{className:As.errorMessage,children:n instanceof fQ?n.translatedMessage:n.message}),I8e="_avatarInputField_1ep5q_8",k8e="_avatar_1ep5q_8",x8e="_fileInput_1ep5q_17",P8e="_edit_1ep5q_21",g_={avatarInputField:I8e,avatar:k8e,fileInput:x8e,edit:P8e},hQ=({id:n,label:e,className:t,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:l}=ze(),[c,u]=_.useState(!1),[f,p]=_.useState(void 0),[m,v]=_.useState(!1),g=_.useRef(null);_.useEffect(()=>{const w=g.current,k=R=>{const I=R;I.target.files&&I.target.files.length>0?(p(URL.createObjectURL(I.target.files[0])),u(!1)):p(void 0)};return w.addEventListener("change",k),()=>{w==null||w.removeEventListener("change",k)}});const S=_.useCallback(()=>{g.current.click()},[g]),b=_.useCallback(()=>{u(!0),o()},[o]);return E.jsxs("div",{className:Ae(g_.avatarInputField,t),children:[E.jsx(Zp,{id:i,className:g_.avatar,name:s,size:Xp.XL,src:c?void 0:f||r}),E.jsx("input",{id:n,accept:"image/*",ref:g,type:"file",className:g_.fileInput,role:"button","aria-label":e,...a}),E.jsx("div",{className:g_.edit,children:(r||f)&&!c?E.jsxs(D6,{title:l("action.edit"),showTitle:!1,open:m,onOpenChange:v,trigger:E.jsx(At,{iconOnly:!0,Icon:sD,kind:"tertiary",size:"sm","aria-label":l("action.edit")}),children:[E.jsx(Sp,{Icon:rRe,label:l("action.upload_file"),onSelect:S}),E.jsx(Sp,{Icon:K2e,label:l("action.remove"),kind:"critical",onSelect:b})]}):E.jsx(At,{type:"button",iconOnly:!0,Icon:sD,kind:"tertiary",size:"sm","aria-label":l("action.edit"),onClick:S})})]})};hQ.displayName="AvatarInputField";const L8e="_content_gj715_8",O8e="_avatarFieldRow_gj715_15",eU={content:L8e,avatarFieldRow:O8e},M8e=({client:n})=>{const{t:e}=ze(),{error:t,displayName:r,avatarUrl:i,saveProfile:s}=Jy(n),o=_.useMemo(()=>n.getUserId(),[n]),a=_.useRef(null),l=_.useRef(!1),c=_.useCallback(()=>{l.current=!0},[]),u=_.useRef(!1),f=_.useCallback(()=>{u.current=!0,l.current=!0},[]);return _.useEffect(()=>{const p=a.current;return()=>{if(l.current){const m=new FormData(p),v=m.get("displayName"),g=m.get("avatar"),S=typeof g=="string"?g.length:(g==null?void 0:g.size)??0,b=typeof v=="string"?v:(v==null?void 0:v.name)??null;if(!b)return;s({displayName:b,avatar:g&&S>0?g:void 0,removeAvatar:u.current&&(!g||S===0)}).catch(w=>{A.error("Failed to save profile",w)})}}},[s]),E.jsxs("form",{onChange:c,ref:a,className:eU.content,children:[E.jsx(vt,{className:eU.avatarFieldRow,children:o&&r&&E.jsx(hQ,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:f})}),E.jsx(vt,{children:E.jsx(_n,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:n.getUserId()})}),E.jsx(vt,{children:E.jsx(_n,{id:"displayName",name:"displayName",label:e("common.display_name"),type:"text",required:!0,autoComplete:"off",placeholder:e("common.display_name"),defaultValue:r,"data-testid":"profile_displayname"})}),t&&E.jsx(vt,{children:E.jsx(Pu,{error:t})})]})},A8e="_feedback_19yh9_8",pQ={feedback:A8e},mQ=()=>E.jsxs(Qi,{i18nKey:"analytics_notice",children:["By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our"," ",E.jsx(Pd,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",E.jsx(Pd,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),N8e=({roomId:n})=>{const{t:e}=ze(),{submitRageshake:t,sending:r,sent:i,error:s,available:o}=jw(),a=pNe(),l=_.useCallback(f=>{f.preventDefault();const p=new FormData(f.target),m=p.get("description"),v=typeof m=="string"?m:"",g=!!p.get("sendLogs"),S=bs(16);t({description:v,sendLogs:g,rageshakeRequestId:S,roomId:n}).catch(b=>{A.error("Failed to send feedback rageshake",b)}),n&&g&&a(n,S)},[t,n,a]);Aw();const c=null,u=o?E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:e("settings.feedback_tab_h4")}),E.jsx(Xt,{children:e("settings.feedback_tab_body")}),E.jsxs("form",{onSubmit:l,children:[E.jsx(vt,{children:E.jsx(_n,{className:pQ.feedback,id:"description",name:"description",label:e("settings.feedback_tab_description_label"),placeholder:e("settings.feedback_tab_description_label"),type:"textarea",disabled:r||i})}),!i&&E.jsxs(vt,{children:[E.jsx(_n,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),E.jsx(At,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),E.jsxs(vt,{children:[s&&E.jsx(Pu,{error:s}),i&&E.jsx(Xt,{children:e("settings.feedback_tab_thank_you")})]})]})]}):null;return E.jsxs("div",{children:[c,u]})};var Ob={exports:{}},D8e=Ob.exports,tU;function j8e(){return tU||(tU=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(D8e,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?l:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function f(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return c(g)||f.apply(this,arguments)}function m(g,S){var b=this,w,k,R,I="loglevel";typeof g=="string"?I+=":"+g:typeof g=="symbol"&&(I=void 0);function C(j){var U=(i[j]||"silent").toUpperCase();if(!(typeof window===t||!I)){try{window.localStorage[I]=U;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+U+";"}catch{}}}function x(){var j;if(!(typeof window===t||!I)){try{j=window.localStorage[I]}catch{}if(typeof j===t)try{var U=window.document.cookie,H=encodeURIComponent(I),K=U.indexOf(H+"=");K!==-1&&(j=/^([^;]+)/.exec(U.slice(K+H.length+1))[1])}catch{}return b.levels[j]===void 0&&(j=void 0),j}}function O(){if(!(typeof window===t||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(j){var U=j;if(typeof U=="string"&&b.levels[U.toUpperCase()]!==void 0&&(U=b.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=b.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+j)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return R??k??w},b.setLevel=function(j,U){return R=N(j),U!==!1&&C(R),u.call(b)},b.setDefaultLevel=function(j){k=N(j),x()||b.setLevel(j,!1)},b.resetLevel=function(){R=null,O(),u.call(b)},b.enableAll=function(j){b.setLevel(b.levels.TRACE,j)},b.disableAll=function(j){b.setLevel(b.levels.SILENT,j)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var j in s)s[j].rebuild()},w=N(o?o.getLevel():"WARN");var D=x();D!=null&&(R=N(D)),u.call(b)}o=new m,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[S];return b||(b=s[S]=new m(S,o.methodFactory)),b};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})}(Ob)),Ob.exports}var U8e=j8e();const F8e=qo(U8e);var $8e=(n,e,t)=>new Promise((r,i)=>{var s=l=>{try{a(t.next(l))}catch(c){i(c)}},o=l=>{try{a(t.throw(l))}catch(c){i(c)}},a=l=>l.done?r(l.value):Promise.resolve(l.value).then(s,o);a((t=t.apply(n,e)).next())}),H8e=[le.ConnectionStateChanged,le.RoomMetadataChanged,le.ActiveSpeakersChanged,le.ConnectionQualityChanged,le.ParticipantConnected,le.ParticipantDisconnected,le.ParticipantPermissionsChanged,le.ParticipantMetadataChanged,le.ParticipantNameChanged,le.ParticipantAttributesChanged,le.TrackMuted,le.TrackUnmuted,le.TrackPublished,le.TrackUnpublished,le.TrackStreamStateChanged,le.TrackSubscriptionFailed,le.TrackSubscriptionPermissionChanged,le.TrackSubscriptionStatusChanged],B8e=[...H8e,le.LocalTrackPublished,le.LocalTrackUnpublished];oe.TrackPublished,oe.TrackUnpublished,oe.TrackMuted,oe.TrackUnmuted,oe.TrackStreamStateChanged,oe.TrackSubscribed,oe.TrackUnsubscribed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionFailed,oe.LocalTrackPublished,oe.LocalTrackUnpublished;var V8e=[oe.ConnectionQualityChanged,oe.IsSpeakingChanged,oe.ParticipantMetadataChanged,oe.ParticipantPermissionsChanged,oe.TrackMuted,oe.TrackUnmuted,oe.TrackPublished,oe.TrackUnpublished,oe.TrackStreamStateChanged,oe.TrackSubscriptionFailed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionStatusChanged];[...V8e,oe.LocalTrackPublished,oe.LocalTrackUnpublished];var q8e=F8e.getLogger("lk-components-js");q8e.setDefaultLevel("WARN");function K8e(n,...e){return new jn(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(dn(n))}function G8e(n,e){return new jn(r=>{const i=(...o)=>{r.next(o)};return n.on(e,i),()=>{n.off(e,i)}})}function W8e(n,e,t=!0){var r;const i=()=>$8e(this,null,function*(){try{const a=yield Ol.getLocalDevices(n,t);s.next(a)}catch(a){e==null||e(a)}}),s=new Or,o=s.pipe(VZ(()=>{var a;(a=navigator==null?void 0:navigator.mediaDevices)==null||a.removeEventListener("devicechange",i)}));if(typeof window<"u"){if(!window.isSecureContext)throw new Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");(r=navigator==null?void 0:navigator.mediaDevices)==null||r.addEventListener("devicechange",i)}return nE(Ol.getLocalDevices(n,t).catch(a=>(e==null||e(a),[])),o)}function P4(n,...e){return new jn(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(dn(n))}function L4(n){return P4(n,oe.TrackMuted,oe.TrackUnmuted,oe.ParticipantPermissionsChanged,oe.TrackPublished,oe.TrackUnpublished,oe.LocalTrackPublished,oe.LocalTrackUnpublished,oe.MediaDevicesError,oe.TrackSubscriptionStatusChanged).pipe(Ne(t=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=t,o=t.getTrackPublication(ue.Source.Microphone),a=t.getTrackPublication(ue.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:t}}))}function z8e(n,e={}){var t;let r;const i=new jn(l=>(r=l,()=>a.unsubscribe())).pipe(dn(Array.from(n.remoteParticipants.values()))),s=(t=e.additionalRoomEvents)!=null?t:B8e,o=Array.from(new Set([le.ParticipantConnected,le.ParticipantDisconnected,le.ConnectionStateChanged,...s])),a=K8e(n,...o).subscribe(l=>r==null?void 0:r.next(Array.from(l.remoteParticipants.values())));return n.remoteParticipants.size>0&&(r==null||r.next(Array.from(n.remoteParticipants.values()))),i}new TextEncoder;new TextDecoder;function aI(n,e,t){const r=_.useRef(!1),i=t||r.current;r.current||(r.current=t);const s=_.useMemo(()=>W8e(n,()=>A.error("Error creating MediaDeviceObserver"),i).pipe(dn([])),[n,i]),o=tt(_.useMemo(()=>s.pipe(Ne(f=>{var m;let p=new Map(f.map((v,g)=>[v.deviceId,v.label?{type:"name",name:v.label}:{type:"number",number:g+1}]));return n==="audiooutput"&&p.size&&!p.has("")&&!p.has("default")&&(p=new Map([["",{type:"default",name:((m=f[0])==null?void 0:m.label)||null}],...p])),p})),[n,s])),[a,l]=Xn(e),c=_.useMemo(()=>{if(o.size)return a!==void 0&&o.has(a)||o.size===1&&o.has("")?a:o.keys().next().value},[o,a]),u=tt(_.useMemo(()=>s.pipe(Ne(f=>{var p;return(p=f.find(m=>m.deviceId===c))==null?void 0:p.groupId})),[s,c]));return _.useMemo(()=>({available:o,selectedId:c,selectedGroupId:u,select:l}),[o,c,u,l])}const lI={available:new Map,selectedId:void 0,selectedGroupId:void 0,select:()=>{}},Y8e={audioInput:lI,audioOutput:lI,videoInput:lI,startUsingDeviceNames:()=>{},stopUsingDeviceNames:()=>{}},gQ=_.createContext(Y8e),J8e=({children:n})=>{const[e,t]=_.useState(0),r=e>0,i=aI("audioinput",sNe,r),s=aI("audiooutput",oNe,r),o=aI("videoinput",aNe,r),a=_.useCallback(()=>t(u=>u+1),[t]),l=_.useCallback(()=>t(u=>u-1),[t]),c=_.useMemo(()=>({audioInput:i,audioOutput:s,videoInput:o,startUsingDeviceNames:a,stopUsingDeviceNames:l}),[i,s,o,a,l]);return E.jsx(gQ.Provider,{value:c,children:n})},uf=()=>_.useContext(gQ),X8e=(n,e=!0)=>_.useEffect(()=>{if(e)return n.startUsingDeviceNames(),n.stopUsingDeviceNames},[n,e]),Z8e=()=>{const{t:n}=ze(),[e,t]=Xn(YZ),[r,i]=Xn(JZ),[s,o]=Xn(C4),a=(u,f)=>{f(u.target.checked)},[l,c]=Xn(GZ);return E.jsxs("div",{children:[E.jsx(Xt,{children:n("settings.preferences_tab.introduction")}),E.jsx(vt,{children:E.jsx(_n,{id:"showHandRaisedTimer",label:n("settings.preferences_tab.show_hand_raised_timer_label"),description:n("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:u=>a(u,t)})}),E.jsx(vt,{children:E.jsx(_n,{id:"showReactions",label:n("settings.preferences_tab.reactions_show_label"),description:n("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:u=>a(u,i)})}),E.jsx(vt,{children:E.jsx(_n,{id:"playReactionSound",label:n("settings.preferences_tab.reactions_play_sound_label"),description:n("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:u=>a(u,o)})}),E.jsx(vt,{children:E.jsx(_n,{id:"developerSettingsTab",type:"checkbox",checked:l,label:n("settings.preferences_tab.developer_mode_label"),description:n("settings.preferences_tab.developer_mode_label_description"),onChange:u=>c(u.target.checked)})})]})};function vQ(n,[e,t]){return Math.min(t,Math.max(e,n))}function Q8e(n){const e=_.useRef({value:n,previous:n});return _.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var rE=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(t9e);if(s){const o=s.props.children,a=i.map(l=>l===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:l);return E.jsx(oP,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return E.jsx(oP,{...r,ref:e,children:t})});rE.displayName="Slot";var oP=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=r9e(t),s=n9e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Fa(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});oP.displayName="SlotClone";var e9e=({children:n})=>E.jsx(E.Fragment,{children:n});function t9e(n){return _.isValidElement(n)&&n.type===e9e}function n9e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function r9e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var i9e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Fw=i9e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?rE:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{});function s9e(n){const e=n+"CollectionProvider",[t,r]=Ua(e),[i,s]=t(e,{collectionRef:{current:null},itemMap:new Map}),o=m=>{const{scope:v,children:g}=m,S=Ce.useRef(null),b=Ce.useRef(new Map).current;return E.jsx(i,{scope:v,itemMap:b,collectionRef:S,children:g})};o.displayName=e;const a=n+"CollectionSlot",l=Ce.forwardRef((m,v)=>{const{scope:g,children:S}=m,b=s(a,g),w=nn(v,b.collectionRef);return E.jsx(rE,{ref:w,children:S})});l.displayName=a;const c=n+"CollectionItemSlot",u="data-radix-collection-item",f=Ce.forwardRef((m,v)=>{const{scope:g,children:S,...b}=m,w=Ce.useRef(null),k=nn(v,w),R=s(c,g);return Ce.useEffect(()=>(R.itemMap.set(w,{ref:w,...b}),()=>void R.itemMap.delete(w))),E.jsx(rE,{[u]:"",ref:k,children:S})});f.displayName=c;function p(m){const v=s(n+"CollectionConsumer",m);return Ce.useCallback(()=>{const S=v.collectionRef.current;if(!S)return[];const b=Array.from(S.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((R,I)=>b.indexOf(R.ref.current)-b.indexOf(I.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:l,ItemSlot:f},p,r]}var yQ=["PageUp","PageDown"],_Q=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],bQ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},rm="Slider",[aP,o9e,a9e]=s9e(rm),[SQ,hGe]=Ua(rm,[a9e]),[l9e,$w]=SQ(rm),EQ=_.forwardRef((n,e)=>{const{name:t,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:f=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:v,...g}=n,S=_.useRef(new Set),b=_.useRef(0),k=o==="horizontal"?c9e:u9e,[R=[],I]=fw({prop:u,defaultProp:c,onChange:j=>{var H;(H=[...S.current][b.current])==null||H.focus(),f(j)}}),C=_.useRef(R);function x(j){const U=m9e(R,j);D(j,U)}function O(j){D(j,b.current)}function N(){const j=C.current[b.current];R[b.current]!==j&&p(R)}function D(j,U,{commit:H}={commit:!1}){const K=_9e(s),B=b9e(Math.round((j-r)/s)*s+r,K),z=vQ(B,[r,i]);I((W=[])=>{const V=h9e(W,z,U);if(y9e(V,l*s)){b.current=V.indexOf(z);const q=String(V)!==String(W);return q&&H&&p(V),q?V:W}else return W})}return E.jsx(l9e,{scope:n.__scopeSlider,name:t,disabled:a,min:r,max:i,valueIndexToChangeRef:b,thumbs:S.current,values:R,orientation:o,form:v,children:E.jsx(aP.Provider,{scope:n.__scopeSlider,children:E.jsx(aP.Slot,{scope:n.__scopeSlider,children:E.jsx(k,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:e,onPointerDown:We(g.onPointerDown,()=>{a||(C.current=R)}),min:r,max:i,inverted:m,onSlideStart:a?void 0:x,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:N,onHomeKeyDown:()=>!a&&D(r,0,{commit:!0}),onEndKeyDown:()=>!a&&D(i,R.length-1,{commit:!0}),onStepKeyDown:({event:j,direction:U})=>{if(!a){const B=yQ.includes(j.key)||j.shiftKey&&_Q.includes(j.key)?10:1,z=b.current,W=R[z],V=s*B*U;D(W+V,z,{commit:!0})}}})})})})});EQ.displayName=rm;var[wQ,CQ]=SQ(rm,{startEdge:"left",endEdge:"right",size:"width",direction:1}),c9e=_.forwardRef((n,e)=>{const{min:t,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=n,[f,p]=_.useState(null),m=nn(e,k=>p(k)),v=_.useRef(void 0),g=i6(i),S=g==="ltr",b=S&&!s||!S&&s;function w(k){const R=v.current||f.getBoundingClientRect(),I=[0,R.width],x=O4(I,b?[t,r]:[r,t]);return v.current=R,x(k-R.left)}return E.jsx(wQ,{scope:n.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:E.jsx(TQ,{dir:g,"data-orientation":"horizontal",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const R=w(k.clientX);o==null||o(R)},onSlideMove:k=>{const R=w(k.clientX);a==null||a(R)},onSlideEnd:()=>{v.current=void 0,l==null||l()},onStepKeyDown:k=>{const I=bQ[b?"from-left":"from-right"].includes(k.key);c==null||c({event:k,direction:I?-1:1})}})})}),u9e=_.forwardRef((n,e)=>{const{min:t,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:l,...c}=n,u=_.useRef(null),f=nn(e,u),p=_.useRef(void 0),m=!i;function v(g){const S=p.current||u.current.getBoundingClientRect(),b=[0,S.height],k=O4(b,m?[r,t]:[t,r]);return p.current=S,k(g-S.top)}return E.jsx(wQ,{scope:n.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:E.jsx(TQ,{"data-orientation":"vertical",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const S=v(g.clientY);s==null||s(S)},onSlideMove:g=>{const S=v(g.clientY);o==null||o(S)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=bQ[m?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:b?-1:1})}})})}),TQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:l,...c}=n,u=$w(rm,t);return E.jsx(Fw.span,{...c,ref:e,onKeyDown:We(n.onKeyDown,f=>{f.key==="Home"?(o(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):yQ.concat(_Q).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:We(n.onPointerDown,f=>{const p=f.target;p.setPointerCapture(f.pointerId),f.preventDefault(),u.thumbs.has(p)?p.focus():r(f)}),onPointerMove:We(n.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&i(f)}),onPointerUp:We(n.onPointerUp,f=>{const p=f.target;p.hasPointerCapture(f.pointerId)&&(p.releasePointerCapture(f.pointerId),s(f))})})}),RQ="SliderTrack",IQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=$w(RQ,t);return E.jsx(Fw.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});IQ.displayName=RQ;var lP="SliderRange",kQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=$w(lP,t),s=CQ(lP,t),o=_.useRef(null),a=nn(e,o),l=i.values.length,c=i.values.map(p=>PQ(p,i.min,i.max)),u=l>1?Math.min(...c):0,f=100-Math.max(...c);return E.jsx(Fw.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...n.style,[s.startEdge]:u+"%",[s.endEdge]:f+"%"}})});kQ.displayName=lP;var cP="SliderThumb",xQ=_.forwardRef((n,e)=>{const t=o9e(n.__scopeSlider),[r,i]=_.useState(null),s=nn(e,a=>i(a)),o=_.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return E.jsx(d9e,{...n,ref:s,index:o})}),d9e=_.forwardRef((n,e)=>{const{__scopeSlider:t,index:r,name:i,...s}=n,o=$w(cP,t),a=CQ(cP,t),[l,c]=_.useState(null),u=nn(e,w=>c(w)),f=l?o.form||!!l.closest("form"):!0,p=HG(l),m=o.values[r],v=m===void 0?0:PQ(m,o.min,o.max),g=p9e(r,o.values.length),S=p==null?void 0:p[a.size],b=S?g9e(S,v,a.direction):0;return _.useEffect(()=>{if(l)return o.thumbs.add(l),()=>{o.thumbs.delete(l)}},[l,o.thumbs]),E.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${v}% + ${b}px)`},children:[E.jsx(aP.ItemSlot,{scope:n.__scopeSlider,children:E.jsx(Fw.span,{role:"slider","aria-label":n["aria-label"]||g,"aria-valuemin":o.min,"aria-valuenow":m,"aria-valuemax":o.max,"aria-orientation":o.orientation,"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,tabIndex:o.disabled?void 0:0,...s,ref:u,style:m===void 0?{display:"none"}:n.style,onFocus:We(n.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),f&&E.jsx(f9e,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:m},r)]})});xQ.displayName=cP;var f9e=n=>{const{value:e,...t}=n,r=_.useRef(null),i=Q8e(e);return _.useEffect(()=>{const s=r.current,o=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(o,"value").set;if(i!==e&&l){const c=new Event("input",{bubbles:!0});l.call(s,e),s.dispatchEvent(c)}},[i,e]),E.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:e})};function h9e(n=[],e,t){const r=[...n];return r[t]=e,r.sort((i,s)=>i-s)}function PQ(n,e,t){const s=100/(t-e)*(n-e);return vQ(s,[0,100])}function p9e(n,e){return e>2?`Value ${n+1} of ${e}`:e===2?["Minimum","Maximum"][n]:void 0}function m9e(n,e){if(n.length===1)return 0;const t=n.map(i=>Math.abs(i-e)),r=Math.min(...t);return t.indexOf(r)}function g9e(n,e,t){const r=n/2,s=O4([0,50],[0,r]);return(r-s(e)*t)*t}function v9e(n){return n.slice(0,-1).map((e,t)=>n[t+1]-e)}function y9e(n,e){if(e>0){const t=v9e(n);return Math.min(...t)>=e}return!0}function O4(n,e){return t=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(n[1]-n[0]);return e[0]+r*(t-n[0])}}function _9e(n){return(String(n).split(".")[1]||"").length}function b9e(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}var S9e=EQ,E9e=IQ,w9e=kQ,C9e=xQ;const T9e="_slider_15go1_8",R9e="_track_15go1_14",I9e="_highlight_15go1_31",k9e="_handle_15go1_43",v_={slider:T9e,track:R9e,highlight:I9e,handle:k9e},LQ=({className:n,label:e,value:t,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:l})=>{const c=_.useCallback(([f])=>r(f),[r]),u=_.useCallback(([f])=>i==null?void 0:i(f),[i]);return E.jsxs(S9e,{className:Ae(n,v_.slider),value:[t],onValueChange:c,onValueCommit:u,min:s,max:o,step:a,disabled:l,children:[E.jsx(E9e,{className:v_.track,children:E.jsx(w9e,{className:v_.highlight})}),E.jsx(li,{placement:"top",label:Math.round(t*100).toString()+"%",children:E.jsx(C9e,{className:v_.handle,"aria-label":e})})]})},x9e="_selection_1akwb_1",P9e="_title_1akwb_5",L9e="_separator_1akwb_10",O9e="_options_1akwb_14",M9e="_secondary_1akwb_20",_g={selection:x9e,title:P9e,separator:L9e,options:O9e,secondary:M9e},cI=({devices:n,title:e,numberedLabel:t})=>{const{t:r}=ze(),i=_.useId(),s=_.useCallback(o=>{n.select(o.target.value)},[n]);return n.available.size==0?null:E.jsxs("div",{className:_g.selection,children:[E.jsx(Ru,{type:"body",weight:"semibold",size:"sm",as:"h4",className:_g.title,children:e}),E.jsx(MY,{className:_g.separator}),E.jsx("div",{className:_g.options,children:[...n.available].map(([o,a])=>{let l;switch(a.type){case"name":l=a.name;break;case"number":l=t(a.number);break;case"default":l=a.name===null?r("settings.devices.default"):E.jsxs(Qi,{i18nKey:"settings.devices.default_named",name:a.name,children:["Default"," ",E.jsxs("span",{className:_g.secondary,children:["(",{name:a.name},")"]})]});break}return E.jsx(GTe,{name:i,control:E.jsx(i2e,{checked:o===n.selectedId,onChange:s,value:o}),children:E.jsx(DTe,{children:l})},o)})})]})},A9e={},N9e={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"embedded-v0.10.0-rc.1",VITE_PACKAGE:"embedded"},D9e=({client:n,livekitRoom:e})=>{var b;const{t}=ze(),[r,i]=Xn(WZ),[s,o]=Xn(w4),[a,l]=Xn(zZ),[c,u]=Xn(cy),[f,p]=Xn(ZZ),[m,v]=Xn(T4),g=ku(),S=_.useMemo(()=>{var w;if((w=e==null?void 0:e.engine.client.ws)!=null&&w.url){const k=new URL(e.engine.client.ws.url);return k.search="",k}return null},[e]);return E.jsxs(E.Fragment,{children:[E.jsx("p",{children:t("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),E.jsx("p",{children:t("version",{productName:"Element Call",version:"embedded-v0.10.0-rc.1"})}),E.jsx("p",{children:t("developer_mode.crypto_version",{version:((b=n.getCrypto())==null?void 0:b.getVersion())||"unknown"})}),E.jsx("p",{children:t("developer_mode.matrix_id",{id:n.getUserId()||"unknown"})}),E.jsx("p",{children:t("developer_mode.device_id",{id:n.getDeviceId()||"unknown"})}),E.jsx(vt,{children:E.jsx(_n,{id:"duplicateTiles",type:"number",label:t("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(w=>{const k=w.target.valueAsNumber;k<0||i(Number.isNaN(k)?0:k)},[i])})}),E.jsx(vt,{children:E.jsx(_n,{id:"debugTileLayout",type:"checkbox",checked:s,label:t("developer_mode.debug_tile_layout_label"),onChange:w=>o(w.target.checked)})}),E.jsx(vt,{children:E.jsx(_n,{id:"showNonMemberTiles",type:"checkbox",label:t("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(w=>{l(w.target.checked)},[l])})}),E.jsx(vt,{children:E.jsx(_n,{id:"showConnectionStats",type:"checkbox",label:t("developer_mode.show_connection_stats"),checked:!!c,onChange:_.useCallback(w=>{u(w.target.checked)},[u])})}),E.jsx(vt,{children:E.jsx(_n,{id:"useNewMembershipManager",type:"checkbox",label:t("developer_mode.use_new_membership_manager"),checked:!!f,onChange:_.useCallback(w=>{p(w.target.checked)},[p])})}),E.jsx(vt,{children:E.jsx(_n,{id:"useToDeviceKeyTransport",type:"checkbox",label:t("developer_mode.use_to_device_key_transport"),checked:!!m,onChange:_.useCallback(w=>{v(w.target.checked)},[v])})}),e?E.jsxs(E.Fragment,{children:[E.jsx("p",{children:t("developer_mode.livekit_sfu",{url:(S==null?void 0:S.href)||"unknown"})}),E.jsx("p",{children:t("developer_mode.livekit_server_info")}),E.jsxs("pre",{className:A9e.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null,E.jsx("p",{children:t("developer_mode.environment_variables")}),E.jsx("pre",{children:JSON.stringify(N9e,null,2)}),E.jsx("p",{children:t("developer_mode.url_params")}),E.jsx("pre",{children:JSON.stringify(g,null,2)})]})},M4="audio",A4=({open:n,onDismiss:e,tab:t,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=ze(),l=uf();X8e(l,n);const[c,u]=Xn(XZ),[f,p]=_.useState(c),[m]=Xn(GZ),{available:v}=jw(),g={key:"audio",name:a("common.audio"),content:E.jsx(E.Fragment,{children:E.jsxs(eD,{children:[E.jsx(cI,{devices:l.audioInput,title:a("settings.devices.microphone"),numberedLabel:C=>a("settings.devices.microphone_numbered",{n:C})}),E.jsx(cI,{devices:l.audioOutput,title:a("settings.devices.speaker"),numberedLabel:C=>a("settings.devices.speaker_numbered",{n:C})}),E.jsxs("div",{className:Xj.volumeSlider,children:[E.jsx("label",{children:a("settings.audio_tab.effect_volume_label")}),E.jsx("p",{children:a("settings.audio_tab.effect_volume_description")}),E.jsx(LQ,{label:a("video_tile.volume"),value:f,onValueChange:p,onValueCommit:u,min:0,max:1,step:.01})]})]})})},S={key:"video",name:a("common.video"),content:E.jsx(eD,{children:E.jsx(cI,{devices:l.videoInput,title:a("settings.devices.camera"),numberedLabel:C=>a("settings.devices.camera_numbered",{n:C})})})},b={key:"preferences",name:a("common.preferences"),content:E.jsx(Z8e,{})},w={key:"profile",name:a("common.profile"),content:E.jsx(M8e,{client:i})},k={key:"feedback",name:a("settings.feedback_tab_title"),content:E.jsx(N8e,{roomId:s})},R={key:"developer",name:a("settings.developer_tab_title"),content:E.jsx(D9e,{client:i,livekitRoom:o})},I=[g,S];return Ge===null&&I.push(w),I.push(b),v&&I.push(k),m&&I.push(R),E.jsx(lf,{title:a("common.settings"),className:Xj.settingsModal,open:n,onDismiss:e,tabbed:!0,children:E.jsx(d8e,{label:a("common.settings"),tab:t,onTabChange:r,tabs:I})})},j9e=(n,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("mask",{id:"path-1-inside-1_898_2641",fill:"white"},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z"})),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z",fill:"white"}),_.createElement("path",{d:"M17.1502 20.1214L17.9339 21.2814L17.1502 20.1214ZM4.4 19.8008L3.55919 20.9202H3.55919L4.4 19.8008ZM17.1197 17.3237L18.0934 18.3296L18.7717 17.6731L18.4173 16.7981L17.1197 17.3237ZM4.88028 17.3237L3.58268 16.7981L3.22829 17.6731L3.90659 18.3296L4.88028 17.3237ZM11 23.4C13.5662 23.4 15.9541 22.619 17.9339 21.2814L16.3665 18.9613C14.835 19.9959 12.9902 20.6 11 20.6V23.4ZM3.55919 20.9202C5.63176 22.477 8.21011 23.4 11 23.4V20.6C8.83723 20.6 6.84514 19.8865 5.24081 18.6814L3.55919 20.9202ZM-1.4 11C-1.4 15.0577 0.55052 18.6603 3.55919 20.9202L5.24081 18.6814C2.90591 16.9276 1.4 14.1399 1.4 11H-1.4ZM11 -1.4C4.15167 -1.4 -1.4 4.15167 -1.4 11H1.4C1.4 5.69807 5.69807 1.4 11 1.4V-1.4ZM23.4 11C23.4 4.15167 17.8483 -1.4 11 -1.4V1.4C16.3019 1.4 20.6 5.69807 20.6 11H23.4ZM17.9339 21.2814C21.2288 19.0554 23.4 15.2815 23.4 11H20.6C20.6 14.3124 18.9236 17.2337 16.3665 18.9613L17.9339 21.2814ZM12.9 7.975C12.9 9.28384 11.9459 10.15 11 10.15V12.95C13.6991 12.95 15.7 10.615 15.7 7.975H12.9ZM11 5.8C11.9459 5.8 12.9 6.66616 12.9 7.975H15.7C15.7 5.335 13.6991 3 11 3V5.8ZM9.1 7.975C9.1 6.66616 10.0541 5.8 11 5.8V3C8.30086 3 6.3 5.335 6.3 7.975H9.1ZM11 10.15C10.0541 10.15 9.1 9.28384 9.1 7.975H6.3C6.3 10.615 8.30086 12.95 11 12.95V10.15ZM16.146 16.3178C14.8129 17.6081 13.0004 18.4 11 18.4V21.2C13.756 21.2 16.2591 20.1051 18.0934 18.3296L16.146 16.3178ZM11 14.6C13.1797 14.6 15.0494 15.9415 15.8221 17.8493L18.4173 16.7981C17.2312 13.8697 14.359 11.8 11 11.8V14.6ZM6.17788 17.8493C6.95058 15.9415 8.8203 14.6 11 14.6V11.8C7.64102 11.8 4.7688 13.8697 3.58268 16.7981L6.17788 17.8493ZM11 18.4C8.99963 18.4 7.18709 17.6081 5.85397 16.3178L3.90659 18.3296C5.74088 20.1051 8.24402 21.2 11 21.2V18.4Z",fill:"white",mask:"url(#path-1-inside-1_898_2641)"})),nU=_.forwardRef(j9e),U9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.0988 9.01625C20.3188 9.59375 20.8825 9.97875 21.5013 9.97875C22.3263 9.97875 23 10.6525 23 11.4775V12.5225C23 13.3475 22.3263 14.0213 21.5013 14.0213C20.8825 14.0213 20.3188 14.4062 20.0988 14.9838C20.0806 15.0292 20.0624 15.0753 20.0441 15.1218C19.9792 15.2863 19.9125 15.4555 19.8375 15.6163C19.5763 16.18 19.7 16.84 20.14 17.28C20.7313 17.8575 20.7313 18.8062 20.14 19.3975L19.3975 20.14C18.82 20.7313 17.8713 20.7313 17.28 20.14C16.8538 19.7 16.18 19.5763 15.6163 19.8375C15.41 19.9338 15.2037 20.0163 14.9838 20.0988C14.4062 20.3188 14.0213 20.8825 14.0213 21.5013C14.0213 22.3263 13.3475 23 12.5225 23H11.4775C10.6525 23 9.97875 22.3263 9.97875 21.5013C9.97875 20.8825 9.59375 20.3188 9.01625 20.0988C8.97079 20.0806 8.92466 20.0624 8.87815 20.044C8.71368 19.9792 8.54454 19.9125 8.38375 19.8375C7.82 19.5763 7.16 19.7 6.72 20.14C6.1425 20.7313 5.19375 20.7313 4.6025 20.14L3.86 19.3975C3.26875 18.82 3.26875 17.8713 3.86 17.28C4.3 16.8538 4.42375 16.18 4.1625 15.6163C4.06625 15.41 3.98375 15.2037 3.90125 14.9838C3.68125 14.4062 3.1175 14.0213 2.49875 14.0213C1.67375 14.0213 1 13.3475 1 12.5225V11.4775C1 10.6525 1.67375 9.97875 2.49875 9.97875C3.1175 9.97875 3.68125 9.59375 3.90125 9.01625C3.94464 8.87742 3.99897 8.74406 4.0539 8.60926C4.086 8.53046 4.11831 8.45117 4.14875 8.37C4.41 7.80625 4.28625 7.14625 3.84625 6.70625C3.255 6.12875 3.255 5.18 3.84625 4.58875L4.6025 3.86C5.18 3.26875 6.12875 3.26875 6.72 3.86C7.14625 4.3 7.82 4.42375 8.38375 4.1625C8.59 4.06625 8.79625 3.97 9.01625 3.90125C9.59375 3.68125 9.97875 3.1175 9.97875 2.49875C9.97875 1.67375 10.6525 1 11.4775 1H12.5225C13.3475 1 14.0213 1.67375 14.0213 2.49875C14.0213 3.13125 14.4062 3.68125 14.9838 3.90125C15.0292 3.91943 15.0753 3.93762 15.1218 3.95595C15.2863 4.02079 15.4555 4.08746 15.6163 4.1625C16.18 4.42375 16.84 4.3 17.28 3.86C17.8575 3.26875 18.8062 3.26875 19.3975 3.86L20.14 4.6025C20.7313 5.18 20.7313 6.12875 20.14 6.72C19.7 7.14625 19.5763 7.82 19.8375 8.38375C19.9338 8.59 20.0163 8.79625 20.0988 9.01625ZM12 17.5C8.96125 17.5 6.5 15.0387 6.5 12C6.5 8.96125 8.96125 6.5 12 6.5C15.0387 6.5 17.5 8.96125 17.5 12C17.5 15.0387 15.0387 17.5 12 17.5Z",fill:"#ffffff"})),F9e=_.forwardRef(U9e),$9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.49966 2.38889C7.49966 1.89797 7.89763 1.5 8.38855 1.5H20.1108C20.6017 1.5 20.9997 1.89797 20.9997 2.38889V21.6111C20.9997 22.102 20.6017 22.5 20.1108 22.5H8.38855C7.89763 22.5 7.49966 22.102 7.49966 21.6111V12.6667H7.49089H7.4821H7.47331H7.46452H7.45573H7.44694H7.43815H7.42936H7.42057H7.41178H7.403H7.39421H7.38542H7.37663H7.36784H7.35905H7.35026H7.34147H7.33268H7.32389H7.3151H7.30632H7.29753H7.28874H7.27995H7.27116H7.26237H7.25358H7.24479H7.236H7.22721H7.21842H7.20964H7.20085H7.19206H7.18327H7.17448H7.16569H7.1569H7.14811H7.13932H7.13053H7.12175H7.11296H7.10417H7.09538H7.08659H7.0778H7.06901H7.06022H7.05143H7.04264H7.03385H7.02507H7.01628H7.00749H6.9987H6.98991H6.98112H6.97233H6.96354H6.95475H6.94596H6.93717H6.92839H6.9196H6.91081H6.90202H6.89323H6.88444H6.87565H6.86686H6.85807H6.84928H6.8405H6.83171H6.82292H6.81413H6.80534H6.79655H6.78776H6.77897H6.77018H6.76139H6.7526H6.74382H6.73503H6.72624H6.71745H6.70866H6.69987H6.69108H6.68229H6.6735H6.66471H6.65592H6.64714H6.63835H6.62956H6.62077H6.61198H6.60319H6.5944H6.58561H6.57682H6.56803H6.55925H6.55046H6.54167H6.53288H6.52409H6.5153H6.50651H6.49772H6.48893H6.48014H6.47135H6.46257H6.45378H6.44499H6.4362H6.42741H6.41862H6.40983H6.40104H6.39225H6.38346H6.37467H6.36589H6.3571H6.34831H6.33952H6.33073H6.32194H6.31315H6.30436H6.29557H6.28678H6.27799H6.26921H6.26042H6.25163H6.24284H6.23405H6.22526H6.21647H6.20768H6.19889H6.1901H6.18132H6.17253H6.16374H6.15495H6.14616H6.13737H6.12858H6.11979H6.111H6.10221H6.09342H6.08464H6.07585H6.06706H6.05827H6.04948H6.04069H6.0319H6.02311H6.01432H6.00553H5.99674H5.98796H5.97917H5.97038H5.96159H5.9528H5.94401H5.93522H5.92643H5.91764H5.90885H5.90007H5.89128H5.88249H5.8737H5.86491H5.85612H5.84733H5.83854H5.82975H5.82096H5.81217H5.80339H5.7946H5.78581H5.77702H5.76823H5.75944H5.75065H5.74186H5.73307H5.72428H5.71549H5.70671H5.69792H5.68913H5.68034H5.67155H5.66276H5.65397H5.64518H5.63639H5.6276H5.61882H5.61003H5.60124H5.59245H5.58366H5.57487H5.56608H5.55729H5.5485H5.53971H5.53092H5.52214H5.51335H5.50456H5.49577H5.48698H5.47819H5.4694H5.46061H5.45182H5.44303H5.43424H5.42546H5.41667H5.40788H5.39909H5.3903H5.38151H5.37272H5.36393H5.35514H5.34635H5.33757H5.32878H5.31999H5.3112H5.30241H5.29362H5.28483H5.27604H5.26725H5.25846H5.24967H5.24089H5.2321H5.22331H5.21452H5.20573H5.19694H5.18815H5.17936H5.17057H5.16178H5.15299H5.14421H5.13542H5.12663H5.11784H5.10905H5.10026H5.09147H5.08268H5.07389H5.0651H5.05632H5.04753H5.03874H5.02995H5.02116H5.01237H5.00358H4.99479H4.986H4.97721H4.96842H4.95964H4.95085H4.94206H4.93327H4.92448H4.91569H4.9069H4.89811H4.88932H4.88053H4.87174H4.86296H4.85417H4.84538H4.83659H4.8278H4.81901H4.81022H4.80143H4.79264H4.78385H4.77507H4.76628H4.75749H4.7487H4.73991H4.73112H4.72233H4.71354H4.70475H4.69596H4.68717H4.67839H4.6696H4.66081H4.65202H4.64323H4.63444H4.62565H4.61686H4.60807H4.59928H4.59049H4.58171H4.57292H4.56413H4.55534H4.54655H4.53776H4.52897H4.52018H4.51139H4.5026H4.49382H4.48503H4.47624H4.46745H4.45866H4.44987H4.44108H4.43229H4.4235H4.41471H4.40592H4.39714H4.38835H4.37956H4.37077H4.36198H4.35319H4.3444H4.33561H4.32682H4.31803H4.30924H4.30046H4.29167H4.28288H4.27409H4.2653H4.25651H4.24772H4.23893H4.23014H4.22135H4.21257H4.20378H4.19499H4.1862H4.17741H4.16862H4.15983H4.15104H4.14225H4.13346H4.12467H4.11589H4.1071H4.09831H4.08952H4.08073H4.07194H4.06315H4.05436H4.04557H4.03678H4.02799H4.01921H4.01042H4.00163H3.99284H3.98405H3.97526H3.96647H3.95768H3.94889H3.9401H3.93132H3.92253H3.91374H3.90495H3.89616H3.88737H3.87858H3.86979H3.861H3.85221H3.84342H3.83464H3.82585H3.81706H3.80827H3.79948H3.79069H3.7819H3.77311H3.76432H3.75553H3.74674H3.73796H3.72917H3.72038H3.71159H3.7028H3.69401H3.68522H3.67643H3.66764H3.65885H3.65007H3.64128H3.63249H3.6237H3.61491H3.60612H3.59733H3.58854H3.57975H3.57096H3.56217H3.55339H3.5446H3.53581H3.52702H3.51823H3.50944H3.50065H3.49186H3.48307H3.47428H3.46549H3.45671H3.44792H3.43913H3.43034H3.42155H3.41276H3.40397H3.39518H3.38639H3.3776H3.36882H3.36003H3.35124H3.34245H3.33366H3.32487H3.31608H3.30729H3.2985H3.28971H3.28092H3.27214H3.26335H3.25456H3.24577H3.23698H3.22819H3.2194H3.21061H3.20182H3.19303H3.18424H3.17546H3.16667H3.15788H3.14909H3.1403H3.13151H3.12272H3.11393H3.10514H3.09635H3.08757H3.07878H3.06999H3.0612H3.05241H3.04362H3.03483H3.02604H3.01725H3.00846H2.99967C2.63148 12.6667 2.33301 12.3682 2.33301 12C2.33301 11.6318 2.63148 11.3333 2.99967 11.3333H3.00846H3.01725H3.02604H3.03483H3.04362H3.05241H3.0612H3.06999H3.07878H3.08757H3.09635H3.10514H3.11393H3.12272H3.13151H3.1403H3.14909H3.15788H3.16667H3.17546H3.18424H3.19303H3.20182H3.21061H3.2194H3.22819H3.23698H3.24577H3.25456H3.26335H3.27214H3.28092H3.28971H3.2985H3.30729H3.31608H3.32487H3.33366H3.34245H3.35124H3.36003H3.36882H3.3776H3.38639H3.39518H3.40397H3.41276H3.42155H3.43034H3.43913H3.44792H3.45671H3.46549H3.47428H3.48307H3.49186H3.50065H3.50944H3.51823H3.52702H3.53581H3.5446H3.55339H3.56217H3.57096H3.57975H3.58854H3.59733H3.60612H3.61491H3.6237H3.63249H3.64128H3.65007H3.65885H3.66764H3.67643H3.68522H3.69401H3.7028H3.71159H3.72038H3.72917H3.73796H3.74674H3.75553H3.76432H3.77311H3.7819H3.79069H3.79948H3.80827H3.81706H3.82585H3.83464H3.84342H3.85221H3.861H3.86979H3.87858H3.88737H3.89616H3.90495H3.91374H3.92253H3.93132H3.9401H3.94889H3.95768H3.96647H3.97526H3.98405H3.99284H4.00163H4.01042H4.01921H4.02799H4.03678H4.04557H4.05436H4.06315H4.07194H4.08073H4.08952H4.09831H4.1071H4.11589H4.12467H4.13346H4.14225H4.15104H4.15983H4.16862H4.17741H4.1862H4.19499H4.20378H4.21257H4.22135H4.23014H4.23893H4.24772H4.25651H4.2653H4.27409H4.28288H4.29167H4.30046H4.30924H4.31803H4.32682H4.33561H4.3444H4.35319H4.36198H4.37077H4.37956H4.38835H4.39714H4.40592H4.41471H4.4235H4.43229H4.44108H4.44987H4.45866H4.46745H4.47624H4.48503H4.49382H4.5026H4.51139H4.52018H4.52897H4.53776H4.54655H4.55534H4.56413H4.57292H4.58171H4.59049H4.59928H4.60807H4.61686H4.62565H4.63444H4.64323H4.65202H4.66081H4.6696H4.67839H4.68717H4.69596H4.70475H4.71354H4.72233H4.73112H4.73991H4.7487H4.75749H4.76628H4.77507H4.78385H4.79264H4.80143H4.81022H4.81901H4.8278H4.83659H4.84538H4.85417H4.86296H4.87174H4.88053H4.88932H4.89811H4.9069H4.91569H4.92448H4.93327H4.94206H4.95085H4.95964H4.96842H4.97721H4.986H4.99479H5.00358H5.01237H5.02116H5.02995H5.03874H5.04753H5.05631H5.0651H5.07389H5.08268H5.09147H5.10026H5.10905H5.11784H5.12663H5.13542H5.14421H5.15299H5.16178H5.17057H5.17936H5.18815H5.19694H5.20573H5.21452H5.22331H5.2321H5.24089H5.24967H5.25846H5.26725H5.27604H5.28483H5.29362H5.30241H5.3112H5.31999H5.32878H5.33757H5.34635H5.35514H5.36393H5.37272H5.38151H5.3903H5.39909H5.40788H5.41667H5.42546H5.43424H5.44303H5.45182H5.46061H5.4694H5.47819H5.48698H5.49577H5.50456H5.51335H5.52214H5.53092H5.53971H5.5485H5.55729H5.56608H5.57487H5.58366H5.59245H5.60124H5.61003H5.61882H5.6276H5.63639H5.64518H5.65397H5.66276H5.67155H5.68034H5.68913H5.69792H5.70671H5.71549H5.72428H5.73307H5.74186H5.75065H5.75944H5.76823H5.77702H5.78581H5.7946H5.80339H5.81217H5.82096H5.82975H5.83854H5.84733H5.85612H5.86491H5.8737H5.88249H5.89128H5.90007H5.90885H5.91764H5.92643H5.93522H5.94401H5.9528H5.96159H5.97038H5.97917H5.98796H5.99674H6.00553H6.01432H6.02311H6.0319H6.04069H6.04948H6.05827H6.06706H6.07585H6.08464H6.09342H6.10221H6.111H6.11979H6.12858H6.13737H6.14616H6.15495H6.16374H6.17253H6.18132H6.1901H6.19889H6.20768H6.21647H6.22526H6.23405H6.24284H6.25163H6.26042H6.26921H6.27799H6.28678H6.29557H6.30436H6.31315H6.32194H6.33073H6.33952H6.34831H6.3571H6.36589H6.37467H6.38346H6.39225H6.40104H6.40983H6.41862H6.42741H6.4362H6.44499H6.45378H6.46257H6.47135H6.48014H6.48893H6.49772H6.50651H6.5153H6.52409H6.53288H6.54167H6.55046H6.55925H6.56803H6.57682H6.58561H6.5944H6.60319H6.61198H6.62077H6.62956H6.63835H6.64714H6.65592H6.66471H6.6735H6.68229H6.69108H6.69987H6.70866H6.71745H6.72624H6.73503H6.74382H6.7526H6.76139H6.77018H6.77897H6.78776H6.79655H6.80534H6.81413H6.82292H6.83171H6.8405H6.84928H6.85807H6.86686H6.87565H6.88444H6.89323H6.90202H6.91081H6.9196H6.92839H6.93717H6.94596H6.95475H6.96354H6.97233H6.98112H6.98991H6.9987H7.00749H7.01628H7.02507H7.03385H7.04264H7.05143H7.06022H7.06901H7.0778H7.08659H7.09538H7.10417H7.11296H7.12175H7.13053H7.13932H7.14811H7.1569H7.16569H7.17448H7.18327H7.19206H7.20085H7.20964H7.21842H7.22721H7.236H7.24479H7.25358H7.26237H7.27116H7.27995H7.28874H7.29753H7.30632H7.3151H7.32389H7.33268H7.34147H7.35026H7.35905H7.36784H7.37663H7.38542H7.39421H7.403H7.41178H7.42057H7.42936H7.43815H7.44694H7.45573H7.46452H7.47331H7.4821H7.49089H7.49966V2.38889ZM13.3687 6.24853C13.1172 5.9796 12.7095 5.9796 12.458 6.24853C12.2065 6.51747 12.2065 6.9535 12.458 7.22243L16.3022 11.3336L16.2894 11.3336L16.2726 11.3336L16.2558 11.3336L16.239 11.3335L16.2223 11.3335L16.2055 11.3335L16.1887 11.3335L16.1719 11.3335L16.1552 11.3334L16.1384 11.3334L16.1216 11.3334L16.1048 11.3334L16.088 11.3334L16.0713 11.3333L16.0545 11.3333L16.0377 11.3333L16.0209 11.3333L16.0041 11.3333L15.9874 11.3332L15.9706 11.3332L15.9538 11.3332L15.937 11.3332L15.9202 11.3332L15.9035 11.3331L15.8867 11.3331L15.8699 11.3331L15.8531 11.3331L15.8364 11.3331L15.8196 11.333L15.8028 11.333L15.786 11.333L15.7692 11.333L15.7525 11.333L15.7357 11.3329L15.7189 11.3329L15.7021 11.3329L15.6853 11.3329L15.6686 11.3329L15.6518 11.3328L15.635 11.3328L15.6182 11.3328L15.6014 11.3328L15.5847 11.3328L15.5679 11.3327L15.5511 11.3327L15.5343 11.3327L15.5175 11.3327L15.5008 11.3327L15.484 11.3326L15.4672 11.3326L15.4504 11.3326L15.4337 11.3326L15.4169 11.3326L15.4001 11.3325L15.3833 11.3325L15.3665 11.3325L15.3498 11.3325L15.333 11.3324L15.3162 11.3324L15.2994 11.3324L15.2826 11.3324L15.2659 11.3324L15.2491 11.3323L15.2323 11.3323L15.2155 11.3323L15.1987 11.3323L15.182 11.3323L15.1652 11.3322L15.1484 11.3322L15.1316 11.3322L15.1148 11.3322L15.0981 11.3322L15.0813 11.3321L15.0645 11.3321L15.0477 11.3321L15.031 11.3321L15.0142 11.3321L14.9974 11.332L14.9806 11.332L14.9638 11.332L14.9471 11.332L14.9303 11.332L14.9135 11.3319L14.8967 11.3319L14.8799 11.3319L14.8632 11.3319L14.8464 11.3319L14.8296 11.3318L14.8128 11.3318L14.796 11.3318L14.7793 11.3318L14.7625 11.3318L14.7457 11.3317L14.7289 11.3317L14.7122 11.3317L14.6954 11.3317L14.6786 11.3317L14.6618 11.3316L14.645 11.3316L14.6283 11.3316L14.6115 11.3316L14.5947 11.3316L14.5779 11.3315L14.5611 11.3315L14.5444 11.3315L14.5276 11.3315L14.5108 11.3315L14.494 11.3314L14.4772 11.3314L14.4605 11.3314L14.4437 11.3314L14.4269 11.3314L14.4101 11.3313L14.3933 11.3313L14.3766 11.3313L14.3598 11.3313L14.343 11.3313L14.3262 11.3312L14.3095 11.3312L14.2927 11.3312L14.2759 11.3312L14.2591 11.3312L14.2423 11.3311L14.2256 11.3311L14.2088 11.3311L14.192 11.3311L14.1752 11.3311L14.1584 11.331L14.1417 11.331L14.1249 11.331L14.1081 11.331L14.0913 11.331L14.0745 11.3309L14.0578 11.3309L14.041 11.3309L14.0242 11.3309L14.0074 11.3309L13.9906 11.3308L13.9739 11.3308L13.9571 11.3308L13.9403 11.3308L13.9235 11.3308L13.9068 11.3307L13.89 11.3307L13.8732 11.3307L13.8564 11.3307L13.8396 11.3307L13.8229 11.3306L13.8061 11.3306L13.7893 11.3306L13.7725 11.3306L13.7557 11.3306L13.739 11.3305L13.7222 11.3305L13.7054 11.3305L13.6886 11.3305L13.6718 11.3305L13.6551 11.3304L13.6383 11.3304L13.6215 11.3304L13.6047 11.3304L13.5879 11.3304L13.5712 11.3303L13.5544 11.3303L13.5376 11.3303L13.5208 11.3303L13.5041 11.3303L13.4873 11.3302L13.4705 11.3302L13.4537 11.3302L13.4369 11.3302L13.4202 11.3302L13.4034 11.3301L13.3866 11.3301L13.3698 11.3301L13.353 11.3301L13.3363 11.33L13.3195 11.33L13.3027 11.33L13.2859 11.33L13.2691 11.33L13.2524 11.3299L13.2356 11.3299L13.2188 11.3299L13.202 11.3299L13.1853 11.3299L13.1685 11.3298L13.1517 11.3298L13.1349 11.3298L13.1181 11.3298L13.1014 11.3298L13.0846 11.3297L13.0678 11.3297L13.051 11.3297L13.0342 11.3297L13.0175 11.3297L13.0007 11.3296L12.9839 11.3296L12.9671 11.3296L12.9503 11.3296L12.9336 11.3296L12.9168 11.3295L12.9 11.3295L12.8832 11.3295L12.8664 11.3295L12.8497 11.3295L12.8329 11.3294L12.8161 11.3294L12.7993 11.3294L12.7826 11.3294L12.7658 11.3294L12.749 11.3293L12.7322 11.3293L12.7154 11.3293L12.6987 11.3293L12.6819 11.3293L12.6651 11.3292L12.6483 11.3292L12.6315 11.3292L12.6148 11.3292L12.598 11.3292L12.5812 11.3291L12.5644 11.3291L12.5476 11.3291L12.5309 11.3291L12.5141 11.3291L12.4973 11.329L12.4805 11.329L12.4637 11.329L12.447 11.329L12.4302 11.329L12.4134 11.3289L12.3966 11.3289L12.3799 11.3289L12.3631 11.3289L12.3463 11.3289L12.3295 11.3288L12.3127 11.3288L12.296 11.3288L12.2792 11.3288L12.2624 11.3288L12.2456 11.3287L12.2288 11.3287L12.2121 11.3287L12.1953 11.3287L12.1785 11.3287L12.1617 11.3286L12.1449 11.3286L12.1282 11.3286L12.1114 11.3286L12.0946 11.3286L12.0778 11.3285L12.0611 11.3285L12.0443 11.3285L12.0275 11.3285L12.0107 11.3285L11.9939 11.3284L11.9772 11.3284L11.9604 11.3284L11.9436 11.3284L11.9268 11.3284L11.91 11.3283L11.8933 11.3283L11.8765 11.3283L11.8597 11.3283L11.8429 11.3283L11.8261 11.3282L11.8094 11.3282L11.7926 11.3282L11.7758 11.3282L11.759 11.3282L11.7422 11.3281L11.7255 11.3281L11.7087 11.3281L11.6919 11.3281L11.6751 11.3281L11.6583 11.328L11.6416 11.328L11.6248 11.328L11.608 11.328L11.5912 11.328L11.5745 11.3279L11.5577 11.3279L11.5409 11.3279L11.5241 11.3279L11.5073 11.3279L11.4906 11.3278L11.4738 11.3278L11.457 11.3278L11.4402 11.3278L11.4234 11.3278L11.4067 11.3277L11.3899 11.3277L11.3731 11.3277L11.3563 11.3277L11.3395 11.3277L11.3228 11.3276L11.306 11.3276L11.2892 11.3276L11.2724 11.3276L11.2557 11.3275L11.2389 11.3275L11.2221 11.3275L11.2053 11.3275L11.1885 11.3275L11.1718 11.3274L11.155 11.3274L11.1382 11.3274L11.1214 11.3274L11.1046 11.3274L11.0879 11.3273L11.0711 11.3273L11.0543 11.3273L11.0375 11.3273L11.0207 11.3273L11.004 11.3272L10.9872 11.3272L10.9704 11.3272L10.9536 11.3272L10.9368 11.3272L10.9201 11.3271L10.9033 11.3271L10.8865 11.3271L10.8697 11.3271L10.853 11.3271L10.8362 11.327L10.8194 11.327L10.8026 11.327L10.7858 11.327L10.7691 11.327L10.7523 11.3269L10.7355 11.3269L10.7187 11.3269L10.7019 11.3269L10.6852 11.3269L10.6684 11.3268L10.6516 11.3268L10.6348 11.3268L10.618 11.3268L10.6013 11.3268L10.5845 11.3267L10.5677 11.3267L10.5509 11.3267L10.5341 11.3267L10.5174 11.3267L10.5006 11.3266L10.4838 11.3266L10.467 11.3266L10.4503 11.3266L10.4335 11.3266L10.4167 11.3265L10.3999 11.3265L10.3831 11.3265L10.3664 11.3265L10.3496 11.3265L10.3328 11.3264L10.316 11.3264L10.2992 11.3264L10.2825 11.3264L10.2657 11.3264L10.2489 11.3263L10.2321 11.3263L10.2153 11.3263L10.1986 11.3263L10.1818 11.3263L10.165 11.3262L10.1482 11.3262L10.1315 11.3262L10.1147 11.3262L10.0979 11.3262L10.0811 11.3261L10.0643 11.3261L10.0476 11.3261L10.0308 11.3261L10.014 11.3261L9.99722 11.326L9.98044 11.326L9.96366 11.326L9.94688 11.326L9.9301 11.326L9.91332 11.3259L9.89654 11.3259L9.87977 11.3259L9.86299 11.3259L9.84621 11.3259L9.82943 11.3258L9.81265 11.3258L9.79587 11.3258L9.77909 11.3258L9.76231 11.3258L9.74553 11.3257L9.72875 11.3257L9.71197 11.3257L9.69519 11.3257L9.67841 11.3257L9.66163 11.3256L9.64486 11.3256L9.62808 11.3256L9.6113 11.3256L9.59452 11.3256L9.57774 11.3255L9.56096 11.3255L9.54418 11.3255L9.5274 11.3255L9.51062 11.3255L9.49384 11.3254L9.47706 11.3254L9.46029 11.3254L9.44351 11.3254L9.42673 11.3254L9.40995 11.3253L9.39317 11.3253L9.37639 11.3253L9.35961 11.3253L9.34283 11.3253L9.32605 11.3252L9.30927 11.3252L9.29249 11.3252L9.27572 11.3252L9.25894 11.3252L9.24216 11.3251L9.22538 11.3251L9.2086 11.3251L9.19182 11.3251L9.17504 11.325L9.15826 11.325L9.14148 11.325L9.1247 11.325L9.10792 11.325L9.09115 11.3249L9.07437 11.3249L9.05759 11.3249L9.04081 11.3249L9.02403 11.3249L9.00725 11.3248L8.99047 11.3248L8.97369 11.3248L8.95691 11.3248L8.94013 11.3248L8.92335 11.3247L8.90658 11.3247L8.8898 11.3247L8.87302 11.3247L8.85624 11.3247L8.83946 11.3246L8.82268 11.3246L8.8059 11.3246L8.78912 11.3246L8.77234 11.3246L8.75556 11.3245L8.73878 11.3245L8.722 11.3245L8.70523 11.3245L8.68845 11.3245L8.67167 11.3244L8.65489 11.3244L8.63811 11.3244L8.62133 11.3244L8.60455 11.3244L8.58777 11.3243L8.57099 11.3243L8.55421 11.3243L8.53743 11.3243L8.52066 11.3243L8.50388 11.3242L8.4871 11.3242L8.47032 11.3242L8.45354 11.3242L8.43676 11.3242L8.41998 11.3241L8.4032 11.3241L8.38642 11.3241L8.36964 11.3241L8.35286 11.3241L8.33608 11.324L8.31931 11.324L8.30253 11.324L8.28575 11.324L8.26897 11.324L8.25219 11.3239L8.23541 11.3239L8.21863 11.3239L8.20185 11.3239L8.18507 11.3239L8.16829 11.3238L8.15151 11.3238L8.13474 11.3238L8.11796 11.3238L8.10118 11.3238L8.0844 11.3237L8.06762 11.3237L8.05084 11.3237L8.03406 11.3237L8.01728 11.3237L8.0005 11.3236L7.99885 12.657L8.01563 12.657L8.03241 12.657L8.04919 12.657L8.06597 12.6571L8.08274 12.6571L8.09952 12.6571L8.1163 12.6571L8.13308 12.6571L8.14986 12.6572L8.16664 12.6572L8.18342 12.6572L8.2002 12.6572L8.21698 12.6572L8.23376 12.6573L8.25054 12.6573L8.26731 12.6573L8.28409 12.6573L8.30087 12.6573L8.31765 12.6574L8.33443 12.6574L8.35121 12.6574L8.36799 12.6574L8.38477 12.6574L8.40155 12.6575L8.41833 12.6575L8.43511 12.6575L8.45189 12.6575L8.46866 12.6575L8.48544 12.6576L8.50222 12.6576L8.519 12.6576L8.53578 12.6576L8.55256 12.6576L8.56934 12.6577L8.58612 12.6577L8.6029 12.6577L8.61968 12.6577L8.63646 12.6577L8.65323 12.6578L8.67001 12.6578L8.68679 12.6578L8.70357 12.6578L8.72035 12.6578L8.73713 12.6579L8.75391 12.6579L8.77069 12.6579L8.78747 12.6579L8.80425 12.6579L8.82103 12.658L8.83781 12.658L8.85458 12.658L8.87136 12.658L8.88814 12.658L8.90492 12.6581L8.9217 12.6581L8.93848 12.6581L8.95526 12.6581L8.97204 12.6581L8.98882 12.6582L9.0056 12.6582L9.02238 12.6582L9.03915 12.6582L9.05593 12.6582L9.07271 12.6583L9.08949 12.6583L9.10627 12.6583L9.12305 12.6583L9.13983 12.6583L9.15661 12.6584L9.17339 12.6584L9.19017 12.6584L9.20695 12.6584L9.22373 12.6584L9.2405 12.6585L9.25728 12.6585L9.27406 12.6585L9.29084 12.6585L9.30762 12.6585L9.3244 12.6586L9.34118 12.6586L9.35796 12.6586L9.37474 12.6586L9.39152 12.6586L9.4083 12.6587L9.42507 12.6587L9.44185 12.6587L9.45863 12.6587L9.47541 12.6587L9.49219 12.6588L9.50897 12.6588L9.52575 12.6588L9.54253 12.6588L9.55931 12.6588L9.57609 12.6589L9.59287 12.6589L9.60964 12.6589L9.62642 12.6589L9.6432 12.6589L9.65998 12.659L9.67676 12.659L9.69354 12.659L9.71032 12.659L9.7271 12.659L9.74388 12.6591L9.76066 12.6591L9.77744 12.6591L9.79421 12.6591L9.81099 12.6591L9.82777 12.6592L9.84455 12.6592L9.86133 12.6592L9.87811 12.6592L9.89489 12.6592L9.91167 12.6593L9.92845 12.6593L9.94523 12.6593L9.96201 12.6593L9.97879 12.6594L9.99556 12.6594L10.0123 12.6594L10.0291 12.6594L10.0459 12.6594L10.0627 12.6595L10.0795 12.6595L10.0962 12.6595L10.113 12.6595L10.1298 12.6595L10.1466 12.6596L10.1634 12.6596L10.1801 12.6596L10.1969 12.6596L10.2137 12.6596L10.2305 12.6597L10.2473 12.6597L10.264 12.6597L10.2808 12.6597L10.2976 12.6597L10.3144 12.6598L10.3311 12.6598L10.3479 12.6598L10.3647 12.6598L10.3815 12.6598L10.3983 12.6599L10.415 12.6599L10.4318 12.6599L10.4486 12.6599L10.4654 12.6599L10.4822 12.66L10.4989 12.66L10.5157 12.66L10.5325 12.66L10.5493 12.66L10.5661 12.6601L10.5828 12.6601L10.5996 12.6601L10.6164 12.6601L10.6332 12.6601L10.65 12.6602L10.6667 12.6602L10.6835 12.6602L10.7003 12.6602L10.7171 12.6602L10.7338 12.6603L10.7506 12.6603L10.7674 12.6603L10.7842 12.6603L10.801 12.6603L10.8177 12.6604L10.8345 12.6604L10.8513 12.6604L10.8681 12.6604L10.8849 12.6604L10.9016 12.6605L10.9184 12.6605L10.9352 12.6605L10.952 12.6605L10.9688 12.6605L10.9855 12.6606L11.0023 12.6606L11.0191 12.6606L11.0359 12.6606L11.0526 12.6606L11.0694 12.6607L11.0862 12.6607L11.103 12.6607L11.1198 12.6607L11.1365 12.6607L11.1533 12.6608L11.1701 12.6608L11.1869 12.6608L11.2037 12.6608L11.2204 12.6608L11.2372 12.6609L11.254 12.6609L11.2708 12.6609L11.2876 12.6609L11.3043 12.6609L11.3211 12.661L11.3379 12.661L11.3547 12.661L11.3715 12.661L11.3882 12.661L11.405 12.6611L11.4218 12.6611L11.4386 12.6611L11.4553 12.6611L11.4721 12.6611L11.4889 12.6612L11.5057 12.6612L11.5225 12.6612L11.5392 12.6612L11.556 12.6612L11.5728 12.6613L11.5896 12.6613L11.6064 12.6613L11.6231 12.6613L11.6399 12.6613L11.6567 12.6614L11.6735 12.6614L11.6903 12.6614L11.707 12.6614L11.7238 12.6614L11.7406 12.6615L11.7574 12.6615L11.7742 12.6615L11.7909 12.6615L11.8077 12.6615L11.8245 12.6616L11.8413 12.6616L11.858 12.6616L11.8748 12.6616L11.8916 12.6616L11.9084 12.6617L11.9252 12.6617L11.9419 12.6617L11.9587 12.6617L11.9755 12.6617L11.9923 12.6618L12.0091 12.6618L12.0258 12.6618L12.0426 12.6618L12.0594 12.6618L12.0762 12.6619L12.093 12.6619L12.1097 12.6619L12.1265 12.6619L12.1433 12.662L12.1601 12.662L12.1768 12.662L12.1936 12.662L12.2104 12.662L12.2272 12.6621L12.244 12.6621L12.2607 12.6621L12.2775 12.6621L12.2943 12.6621L12.3111 12.6622L12.3279 12.6622L12.3446 12.6622L12.3614 12.6622L12.3782 12.6622L12.395 12.6623L12.4118 12.6623L12.4285 12.6623L12.4453 12.6623L12.4621 12.6623L12.4789 12.6624L12.4957 12.6624L12.5124 12.6624L12.5292 12.6624L12.546 12.6624L12.5628 12.6625L12.5795 12.6625L12.5963 12.6625L12.6131 12.6625L12.6299 12.6625L12.6467 12.6626L12.6634 12.6626L12.6802 12.6626L12.697 12.6626L12.7138 12.6626L12.7306 12.6627L12.7473 12.6627L12.7641 12.6627L12.7809 12.6627L12.7977 12.6627L12.8145 12.6628L12.8312 12.6628L12.848 12.6628L12.8648 12.6628L12.8816 12.6628L12.8984 12.6629L12.9151 12.6629L12.9319 12.6629L12.9487 12.6629L12.9655 12.6629L12.9822 12.663L12.999 12.663L13.0158 12.663L13.0326 12.663L13.0494 12.663L13.0661 12.6631L13.0829 12.6631L13.0997 12.6631L13.1165 12.6631L13.1333 12.6631L13.15 12.6632L13.1668 12.6632L13.1836 12.6632L13.2004 12.6632L13.2172 12.6632L13.2339 12.6633L13.2507 12.6633L13.2675 12.6633L13.2843 12.6633L13.3011 12.6633L13.3178 12.6634L13.3346 12.6634L13.3514 12.6634L13.3682 12.6634L13.3849 12.6634L13.4017 12.6635L13.4185 12.6635L13.4353 12.6635L13.4521 12.6635L13.4688 12.6635L13.4856 12.6636L13.5024 12.6636L13.5192 12.6636L13.536 12.6636L13.5527 12.6636L13.5695 12.6637L13.5863 12.6637L13.6031 12.6637L13.6199 12.6637L13.6366 12.6637L13.6534 12.6638L13.6702 12.6638L13.687 12.6638L13.7038 12.6638L13.7205 12.6638L13.7373 12.6639L13.7541 12.6639L13.7709 12.6639L13.7876 12.6639L13.8044 12.6639L13.8212 12.664L13.838 12.664L13.8548 12.664L13.8715 12.664L13.8883 12.664L13.9051 12.6641L13.9219 12.6641L13.9387 12.6641L13.9554 12.6641L13.9722 12.6641L13.989 12.6642L14.0058 12.6642L14.0226 12.6642L14.0393 12.6642L14.0561 12.6642L14.0729 12.6643L14.0897 12.6643L14.1064 12.6643L14.1232 12.6643L14.14 12.6644L14.1568 12.6644L14.1736 12.6644L14.1903 12.6644L14.2071 12.6644L14.2239 12.6645L14.2407 12.6645L14.2575 12.6645L14.2742 12.6645L14.291 12.6645L14.3078 12.6646L14.3246 12.6646L14.3414 12.6646L14.3581 12.6646L14.3749 12.6646L14.3917 12.6647L14.4085 12.6647L14.4253 12.6647L14.442 12.6647L14.4588 12.6647L14.4756 12.6648L14.4924 12.6648L14.5091 12.6648L14.5259 12.6648L14.5427 12.6648L14.5595 12.6649L14.5763 12.6649L14.593 12.6649L14.6098 12.6649L14.6266 12.6649L14.6434 12.665L14.6602 12.665L14.6769 12.665L14.6937 12.665L14.7105 12.665L14.7273 12.6651L14.7441 12.6651L14.7608 12.6651L14.7776 12.6651L14.7944 12.6651L14.8112 12.6652L14.828 12.6652L14.8447 12.6652L14.8615 12.6652L14.8783 12.6652L14.8951 12.6653L14.9118 12.6653L14.9286 12.6653L14.9454 12.6653L14.9622 12.6653L14.979 12.6654L14.9957 12.6654L15.0125 12.6654L15.0293 12.6654L15.0461 12.6654L15.0629 12.6655L15.0796 12.6655L15.0964 12.6655L15.1132 12.6655L15.13 12.6655L15.1468 12.6656L15.1635 12.6656L15.1803 12.6656L15.1971 12.6656L15.2139 12.6656L15.2306 12.6657L15.2474 12.6657L15.2642 12.6657L15.281 12.6657L15.2978 12.6657L15.3145 12.6658L15.3313 12.6658L15.3481 12.6658L15.3649 12.6658L15.3817 12.6658L15.3984 12.6659L15.4152 12.6659L15.432 12.6659L15.4488 12.6659L15.4656 12.6659L15.4823 12.666L15.4991 12.666L15.5159 12.666L15.5327 12.666L15.5495 12.666L15.5662 12.6661L15.583 12.6661L15.5998 12.6661L15.6166 12.6661L15.6333 12.6661L15.6501 12.6662L15.6669 12.6662L15.6837 12.6662L15.7005 12.6662L15.7172 12.6662L15.734 12.6663L15.7508 12.6663L15.7676 12.6663L15.7844 12.6663L15.8011 12.6663L15.8179 12.6664L15.8347 12.6664L15.8515 12.6664L15.8683 12.6664L15.885 12.6664L15.9018 12.6665L15.9186 12.6665L15.9354 12.6665L15.9522 12.6665L15.9689 12.6665L15.9857 12.6666L16.0025 12.6666L16.0193 12.6666L16.036 12.6666L16.0528 12.6666L16.0696 12.6667L16.0864 12.6667L16.1032 12.6667L16.1199 12.6667L16.1367 12.6667L16.1535 12.6668L16.1703 12.6668L16.1871 12.6668L16.2038 12.6668L16.2206 12.6669L16.2374 12.6669L16.2542 12.6669L16.271 12.6669L16.2836 12.6669L12.458 16.7581C12.2065 17.0271 12.2065 17.4631 12.458 17.732C12.7095 18.001 13.1172 18.001 13.3687 17.732L18.2822 12.4772C18.5337 12.2083 18.5337 11.7723 18.2822 11.5033L13.3687 6.24853Z",fill:"white"})),H9e=_.forwardRef($9e),B9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M18.2139 2.44646L12 3.99992H5.4375C4.64359 3.99992 4 4.64352 4 5.43742V18.5624C4 19.3563 4.64359 19.9999 5.4375 19.9999H12L18.2139 21.5534C19.1211 21.7802 20 21.094 20 20.1588V3.84104C20 2.90584 19.1211 2.21964 18.2139 2.44646ZM12 17.9999V5.99992H6V17.9999H12Z",fill:"white"})),V9e=_.forwardRef(B9e),q9e="_userButton_t5z8t_15",K9e={userButton:q9e},G9e=({preventNavigation:n,isAuthenticated:e,isPasswordlessUser:t,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=ze(),l=ci(),c=_.useMemo(()=>{const p=[];return e&&(p.push({key:"user",icon:nU,label:i,dataTestid:"usermenu_user"}),p.push({key:"settings",icon:F9e,label:a("common.settings")}),t&&!n&&p.push({key:"login",label:a("action.sign_in"),icon:H9e,dataTestid:"usermenu_login"}),!t&&!n&&p.push({key:"logout",label:a("action.sign_out"),icon:V9e,dataTestid:"usermenu_logout"})),p},[e,t,i,n,a]),[u,f]=_.useState(!1);return e?E.jsx(D6,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:u,onOpenChange:f,trigger:E.jsx("button",{"aria-label":a("common.profile"),className:K9e.userButton,"data-testid":"usermenu_open",children:e&&(!t||s)?E.jsx(Zp,{id:r,name:i,size:Xp.SM,src:s}):E.jsx(nU,{})}),children:c.map(({key:p,icon:m,label:v,dataTestid:g})=>E.jsx(Sp,{Icon:m,label:v,"data-test-id":g,onSelect:()=>o(p)},p))}):E.jsx(R4,{to:{pathname:"/login"},state:{from:l},children:a("log_in")})},N4=({preventNavigation:n=!1})=>{const e=ci(),t=Na(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=x4(),{displayName:a,avatarUrl:l}=Jy(r),[c,u]=_.useState(!1),f=_.useCallback(()=>u(!1),[u]),[p,m]=_.useState(M4),v=_.useCallback(S=>{var b;switch(S){case"user":m("profile"),u(!0);break;case"settings":m("audio"),u(!0);break;case"logout":i==null||i();break;case"login":(b=t("/login",{state:{from:e}}))==null||b.catch(w=>A.error("Failed to navigate to login",w));break}},[t,e,i,u]),g=(r==null?void 0:r.getUserIdLocalpart())??"";return E.jsxs(E.Fragment,{children:[E.jsx(G9e,{preventNavigation:n,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:l,onAction:v,userId:(r==null?void 0:r.getUserId())??"",displayName:a||(g?g.replace("@",""):"")}),r&&E.jsx(A4,{client:r,open:c,onDismiss:f,tab:p,onTabChange:m})]})};function W9e(n){return new Worker(""+new URL("IndexedDBWorker-Cs0-RLNE.js",import.meta.url).href,{name:n==null?void 0:n.name})}const Mb=new LP,z9e=n=>{const[e,t]=_.useState(()=>localStorage.getItem(n));return _.useEffect(()=>(Mb.on(n,t),()=>{Mb.off(n,t)}),[n,t]),[e,_.useCallback(r=>{t(r),localStorage.setItem(n,r),Mb.emit(n,r)},[n,t])]},Y9e=(n,e)=>{localStorage.setItem(n,e),Mb.emit(n,e)};function OQ(n,e){Y9e(D4(n),e)}const D4=n=>`room-shared-key-${n}`,J9e=n=>{const e=D4(n);return z9e(e)[0]};function X9e(n){MQ(Yr());const e=D4(n);return localStorage.getItem(e)}function MQ(n){!n.password||!n.roomId||OQ(n.roomId,n.password)}const Z9e=()=>{const n=ku();return _.useEffect(()=>MQ(n),[n]),n.roomId&&n.password?[n.roomId,n.password]:[void 0,void 0]};function Hw(n){const{client:e}=cf(),[t,r]=Z9e(),i=J9e(n),s=e==null?void 0:e.getRoom(n);return _.useMemo(()=>s?i?{kind:Bt.SHARED_KEY,secret:i}:t===n?{kind:Bt.SHARED_KEY,secret:r}:s.hasEncryptionStateEvent()?{kind:Bt.PER_PARTICIPANT}:{kind:Bt.NONE}:{kind:Bt.NONE},[r,s,n,i,t])}const rU=!1,Q9e="element-call-sync";async function e7e(n){let e=!!await n.store.getSavedSyncToken();return new Promise((t,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(n.removeListener(Oe.Sync,i),t()):s==="ERROR"&&(n.removeListener(Oe.Sync,i),r(a==null?void 0:a.error))};n.on(Oe.Sync,i)})}async function AQ(n,e){var a;let t;try{t=window.indexedDB}catch(l){A.warn("Could not get indexDB from window.",l)}const r={fallbackICEServerAllowed:rU,isVoipWithNoMediaAllowed:(a=Ht.get().features)==null?void 0:a.feature_group_calls_without_video_and_audio};t&&localStorage?r.store=new rB({indexedDB:window.indexedDB,localStorage,dbName:Q9e,workerFactory:()=>new W9e}):localStorage&&(r.store=new Mv({localStorage}));const{e2eEnabled:i}=Yr();i||A.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=UE({...r,...n,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:rU});e||await s.clearStores();try{await s.store.startup()}catch(l){A.error("Error starting matrix client indexDB store. Falling back to memory store.",l),s.store=new Mv({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(l){A.warn(l,"Make sure to clear client stores before initializing the rust crypto.")}const o=e7e(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function Xy(n){return n.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function t7e(n,e){return`#${Xy(n)}:${e.getDomain()}`}function NQ(n){const e=n.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===Ht.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return n}async function DQ(n,e,t){A.log("Creating room for group call");const r=n.createRoom({visibility:bH.Private,preset:ME.PublicChat,name:e,room_alias_name:t?void 0:Xy(e),power_level_content_override:{invite:100,kick:100,ban:100,redact:50,state_default:0,events_default:0,users_default:0,events:{"m.room.power_levels":100,"m.room.history_visibility":100,"m.room.tombstone":100,"m.room.encryption":100,"m.room.name":50,"m.room.message":0,"m.room.encrypted":50,"m.sticker":50,"org.matrix.msc3401.call.member":0},users:{[n.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(u=>{a(u),c()});const l=u=>{r.then(f=>{u.roomId===f.room_id&&(o(u.roomId),c())},f=>{A.error("Failed to wait for the room to arrive",f)})},c=()=>{n.off(Oe.Room,l)};n.on(Oe.Room,l)});let s;return t==Bt.SHARED_KEY&&(s=gH(16),OQ(i,s)),{roomId:i,alias:t?void 0:t7e(e,n),password:s}}function jQ(n,e,t,r){return`${window.location.protocol}//${window.location.host}${Bw(n,e,t)}`}function Bw(n,e,t,r){return`/room/#${t?"/"+Xy(t):""}?${R3e(n,e).toString()}`}async function n7e(n){let e=0;for(;;)try{return await n()}catch(t){e++;const r=BP(t,e,!0);if(r<0)throw t;await nu(r)}}const j4=n=>{const[e,t]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=UE({baseUrl:Ht.defaultHomeserverUrl()})),_.useEffect(()=>{Ge||s.current.registerRequest({}).catch(a=>{var l,c,u,f,p,m,v;t((p=(f=(u=(c=(l=a.data)==null?void 0:l.params["m.login.terms"])==null?void 0:c.policies)==null?void 0:u.privacy_policy)==null?void 0:f.en)==null?void 0:p.url),i((v=(m=a.data)==null?void 0:m.params["m.login.recaptcha"])==null?void 0:v.public_key)})},[]);const o=_.useCallback(async(a,l,c,u,f)=>{const p=new aL({matrixClient:s.current,doRequest:async k=>s.current.registerRequest({username:a,password:l,auth:k||void 0}),stateUpdated:(k,R)=>{if(R.error)throw new Error(R.error);k==="m.login.terms"?p.submitAuthDict({type:"m.login.terms"}).catch(I=>{A.error(I)}):k==="m.login.recaptcha"&&p.submitAuthDict({type:"m.login.recaptcha",response:u}).catch(I=>{A.error(I)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:m,access_token:v,device_id:g}=await p.attemptAuth();await(n==null?void 0:n.logout(!0));const S=await AQ({baseUrl:Ht.defaultHomeserverUrl(),accessToken:v,userId:m,deviceId:g},!1);await S.setDisplayName(c);const b={user_id:m,device_id:g,access_token:v,passwordlessUser:f};f&&(b.tempPassword=l);const w=S.getUser(S.getUserId());return w.setRawDisplayName(c),w.setDisplayName(c),[S,b]},[n]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},r7e="_buttons_1arp2_8",i7e={buttons:r7e},UQ=({onJoin:n,open:e,onDismiss:t})=>{const{t:r}=ze();return E.jsxs(lf,{title:r("join_existing_call_modal.title"),open:e,onDismiss:t,children:[E.jsx("p",{children:r("join_existing_call_modal.text")}),E.jsxs(vt,{rightAlign:!0,className:i7e.buttons,children:[E.jsx(At,{onClick:t,children:r("action.no")}),E.jsx(At,{onClick:n,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},iU="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function U4(n){const{t:e}=ze(),[t]=_.useState(()=>bs(16)),r=_.useRef(void 0);_.useEffect(()=>{var a;if(!n)return;const o=()=>{document.getElementById(t)&&window.grecaptcha.render(t,{sitekey:n,size:"invisible",callback:l=>{var c;return(c=r.current)==null?void 0:c.resolve(l)},"error-callback":()=>{var l;return(l=r.current)==null?void 0:l.reject(new Error)}})};if(typeof((a=window.grecaptcha)==null?void 0:a.render)=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${iU}"]`)){const l=document.createElement("script");l.src=iU,l.async=!0,document.body.appendChild(l)}},[t,n]);const i=_.useCallback(async()=>n?window.grecaptcha?new Promise((o,a)=>{var u,f;const l=new MutationObserver(p=>{var m,v;for(const g of p)if(((v=(m=g.target)==null?void 0:m.style)==null?void 0:v.visibility)!=="visible"){a(Qj("recaptcha_dismissed",e)),l.disconnect();return}});r.current={resolve:p=>{o(p),l.disconnect()},reject:p=>{a(p),l.disconnect()}},window.grecaptcha.execute().then(()=>{},p=>{A.error("Recaptcha execution failed",p)});const c=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');(u=c==null?void 0:c.parentNode)!=null&&u.parentNode&&l.observe((f=c==null?void 0:c.parentNode)==null?void 0:f.parentNode,{attributes:!0})}):(A.log("Recaptcha not loaded"),Promise.reject(Qj("recaptcha_not_loaded",e))):Promise.resolve(""),[n,e]),s=_.useCallback(()=>{var o;(o=window.grecaptcha)==null||o.reset()},[]);return{execute:i,reset:s,recaptchaId:t}}const s7e="_form_jcuzc_8",o7e={form:s7e},Vw=_.forwardRef(({children:n,className:e,onSubmit:t},r)=>E.jsx("form",{onSubmit:t,className:Ae(o7e.form,e),ref:r,children:n}));Vw.displayName="Form";const a7e="_footer_106jg_8",l7e="_mobileLoginLink_106jg_19",c7e="_form_106jg_24",u7e="_notice_106jg_40",bg={footer:a7e,mobileLoginLink:l7e,form:c7e,notice:u7e},d7e="_container_dwllg_8",f7e="_main_dwllg_15",h7e="_logo_dwllg_23",ep={container:d7e,main:f7e,logo:h7e},sU=n=>{n=1831565813+(n|=0)|0;let e=Math.imul(n^n>>>15,1|n);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class p7e{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:t,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=t,this.style=s,this.seed=o}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
202
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function QS(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Gy=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=gu(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(Wt(u))try{u()}catch(g){s=g instanceof sI?g.errors:[g]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var p=gu(f),m=p.next();!m.done;m=p.next()){var v=m.value;try{Fj(v)}catch(g){s=s??[],g instanceof sI?s=Qs(Qs([],Zs(s)),Zs(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new sI(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Fj(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&QS(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&QS(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),CZ=Gy.EMPTY;function TZ(n){return n instanceof Gy||n&&"closed"in n&&Wt(n.remove)&&Wt(n.add)&&Wt(n.unsubscribe)}function Fj(n){Wt(n)?n():n.unsubscribe()}var NAe={Promise:void 0},DAe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Qs([n,e],Zs(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function RZ(n){DAe.setTimeout(function(){throw n})}function eE(){}function Lb(n){n()}var g4=function(n){no(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,TZ(t)&&t.add(r)):r.destination=FAe,r}return e.create=function(t,r,i){return new sy(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Gy),jAe=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){h_(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){h_(r)}else h_(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){h_(t)}},n}(),sy=function(n){no(e,n);function e(t,r,i){var s=n.call(this)||this,o;return Wt(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new jAe(o),s}return e}(g4);function h_(n){RZ(n)}function UAe(n){throw n}var FAe={closed:!0,next:eE,error:UAe,complete:eE},v4=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function xu(n){return n}function $Ae(n){return n.length===0?xu:n.length===1?n[0]:function(t){return n.reduce(function(r,i){return i(r)},t)}}var jn=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=BAe(e)?e:new sy(e,t,r);return Lb(function(){var o=i,a=o.operator,l=o.source;s.add(a?a.call(s,l):l?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=$j(t),new t(function(i,s){var o=new sy({next:function(a){try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[v4]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return $Ae(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=$j(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function $j(n){var e;return(e=n??NAe.Promise)!==null&&e!==void 0?e:Promise}function HAe(n){return n&&Wt(n.next)&&Wt(n.error)&&Wt(n.complete)}function BAe(n){return n&&n instanceof g4||HAe(n)&&TZ(n)}function VAe(n){return Wt(n==null?void 0:n.lift)}function jr(n){return function(e){if(VAe(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function er(n,e,t,r,i){return new qAe(n,e,t,r,i)}var qAe=function(n){no(e,n);function e(t,r,i,s,o,a){var l=n.call(this,t)||this;return l.onFinalize=o,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(u){t.error(u)}}:n.prototype._next,l._error=s?function(c){try{s(c)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,l._complete=i?function(){try{i()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(g4),KAe=wZ(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Or=function(n){no(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new Hj(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new KAe},e.prototype.next=function(t){var r=this;Lb(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=gu(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(t)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;Lb(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;Lb(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?CZ:(this.currentObservers=null,a.push(t),new Gy(function(){r.currentObservers=null,QS(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new jn;return t.source=this,t},e.create=function(t,r){return new Hj(t,r)},e}(jn),Hj=function(n){no(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:CZ},e}(Or),rs=function(n){no(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e}(Or),y4={now:function(){return(y4.delegate||Date).now()},delegate:void 0},GAe=function(n){no(e,n);function e(t,r,i){t===void 0&&(t=1/0),r===void 0&&(r=1/0),i===void 0&&(i=y4);var s=n.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=i,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(t){var r=this,i=r.isStopped,s=r._buffer,o=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;i||(s.push(t),!o&&s.push(a.now()+l)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),i=this,s=i._infiniteTimeWindow,o=i._buffer,a=o.slice(),l=0;l<a.length&&!t.closed;l+=s?1:2)t.next(a[l]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,i=t._timestampProvider,s=t._buffer,o=t._infiniteTimeWindow,a=(o?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!o){for(var l=i.now(),c=0,u=1;u<s.length&&s[u]<=l;u+=2)c=u;c&&s.splice(0,c+1)}},e}(Or),WAe=function(n){no(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Gy),Bj={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,Qs([n,e],Zs(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},zAe=function(n){no(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),Bj.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&Bj.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,QS(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(WAe),Vj=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=y4.now,n}(),YAe=function(n){no(e,n);function e(t,r){r===void 0&&(r=Vj.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(Vj),Mw=new YAe(zAe),JAe=Mw,tE=new jn(function(n){return n.complete()});function IZ(n){return n&&Wt(n.schedule)}function _4(n){return n[n.length-1]}function b4(n){return Wt(_4(n))?n.pop():void 0}function Wy(n){return IZ(_4(n))?n.pop():void 0}function XAe(n,e){return typeof _4(n)=="number"?n.pop():e}var S4=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function kZ(n){return Wt(n==null?void 0:n.then)}function xZ(n){return Wt(n[v4])}function PZ(n){return Symbol.asyncIterator&&Wt(n==null?void 0:n[Symbol.asyncIterator])}function LZ(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ZAe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var OZ=ZAe();function MZ(n){return Wt(n==null?void 0:n[OZ])}function AZ(n){return c6(this,arguments,function(){var t,r,i,s;return pw(this,function(o){switch(o.label){case 0:t=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Tl(t.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Tl(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Tl(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function NZ(n){return Wt(n==null?void 0:n.getReader)}function Sr(n){if(n instanceof jn)return n;if(n!=null){if(xZ(n))return QAe(n);if(S4(n))return e5e(n);if(kZ(n))return t5e(n);if(PZ(n))return DZ(n);if(MZ(n))return n5e(n);if(NZ(n))return r5e(n)}throw LZ(n)}function QAe(n){return new jn(function(e){var t=n[v4]();if(Wt(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function e5e(n){return new jn(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function t5e(n){return new jn(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,RZ)})}function n5e(n){return new jn(function(e){var t,r;try{for(var i=gu(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function DZ(n){return new jn(function(e){i5e(n,e).catch(function(t){return e.error(t)})})}function r5e(n){return DZ(AZ(n))}function i5e(n,e){var t,r,i,s;return l6(this,void 0,void 0,function(){var o,a;return pw(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=u6(n),l.label=1;case 1:return[4,t.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function eu(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function jZ(n,e){return e===void 0&&(e=0),jr(function(t,r){t.subscribe(er(r,function(i){return eu(r,n,function(){return r.next(i)},e)},function(){return eu(r,n,function(){return r.complete()},e)},function(i){return eu(r,n,function(){return r.error(i)},e)}))})}function UZ(n,e){return e===void 0&&(e=0),jr(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function s5e(n,e){return Sr(n).pipe(UZ(e),jZ(e))}function o5e(n,e){return Sr(n).pipe(UZ(e),jZ(e))}function a5e(n,e){return new jn(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function l5e(n,e){return new jn(function(t){var r;return eu(t,e,function(){r=n[OZ](),eu(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return Wt(r==null?void 0:r.return)&&r.return()}})}function FZ(n,e){if(!n)throw new Error("Iterable cannot be null");return new jn(function(t){eu(t,e,function(){var r=n[Symbol.asyncIterator]();eu(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function c5e(n,e){return FZ(AZ(n),e)}function u5e(n,e){if(n!=null){if(xZ(n))return s5e(n,e);if(S4(n))return a5e(n,e);if(kZ(n))return o5e(n,e);if(PZ(n))return FZ(n,e);if(MZ(n))return l5e(n,e);if(NZ(n))return c5e(n,e)}throw LZ(n)}function zy(n,e){return e?u5e(n,e):Sr(n)}function Ct(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n);return zy(n,t)}function d5e(n){return!!n&&(n instanceof jn||Wt(n.lift)&&Wt(n.subscribe))}function f5e(n){return n instanceof Date&&!isNaN(n)}function Ne(n,e){return jr(function(t,r){var i=0;t.subscribe(er(r,function(s){r.next(n.call(e,s,i++))}))})}var h5e=Array.isArray;function p5e(n,e){return h5e(e)?n.apply(void 0,Qs([],Zs(e))):n(e)}function E4(n){return Ne(function(e){return p5e(n,e)})}var m5e=Array.isArray,g5e=Object.getPrototypeOf,v5e=Object.prototype,y5e=Object.keys;function $Z(n){if(n.length===1){var e=n[0];if(m5e(e))return{args:e,keys:null};if(_5e(e)){var t=y5e(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function _5e(n){return n&&typeof n=="object"&&g5e(n)===v5e}function HZ(n,e){return n.reduce(function(t,r,i){return t[r]=e[i],t},{})}function Hn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n),r=b4(n),i=$Z(n),s=i.args,o=i.keys;if(s.length===0)return zy([],t);var a=new jn(b5e(s,t,o?function(l){return HZ(o,l)}:xu));return r?a.pipe(E4(r)):a}function b5e(n,e,t){return t===void 0&&(t=xu),function(r){qj(e,function(){for(var i=n.length,s=new Array(i),o=i,a=i,l=function(u){qj(e,function(){var f=zy(n[u],e),p=!1;f.subscribe(er(r,function(m){s[u]=m,p||(p=!0,a--),a||r.next(t(s.slice()))},function(){--o||r.complete()}))},r)},c=0;c<i;c++)l(c)},r)}}function qj(n,e,t){n?eu(t,n,e):e()}function S5e(n,e,t,r,i,s,o,a){var l=[],c=0,u=0,f=!1,p=function(){f&&!l.length&&!c&&e.complete()},m=function(g){return c<r?v(g):l.push(g)},v=function(g){c++;var S=!1;Sr(t(g,u++)).subscribe(er(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{c--;for(var b=function(){var w=l.shift();o||v(w)};l.length&&c<r;)b();p()}catch(w){e.error(w)}}))};return n.subscribe(er(e,m,function(){f=!0,p()})),function(){}}function Yy(n,e,t){return t===void 0&&(t=1/0),Wt(e)?Yy(function(r,i){return Ne(function(s,o){return e(r,s,i,o)})(Sr(n(r,i)))},t):(typeof e=="number"&&(t=e),jr(function(r,i){return S5e(r,i,n,t)}))}function BZ(n){return n===void 0&&(n=1/0),Yy(xu,n)}function E5e(){return BZ(1)}function nE(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return E5e()(zy(n,Wy(n)))}function w5e(n){return new jn(function(e){Sr(n()).subscribe(e)})}function C5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=b4(n),r=$Z(n),i=r.args,s=r.keys,o=new jn(function(a){var l=i.length;if(!l){a.complete();return}for(var c=new Array(l),u=l,f=l,p=function(v){var g=!1;Sr(i[v]).subscribe(er(a,function(S){g||(g=!0,f--),c[v]=S},function(){return u--},void 0,function(){(!u||!g)&&(f||a.next(s?HZ(s,c):c),a.complete())}))},m=0;m<l;m++)p(m)});return t?o.pipe(E4(t)):o}var T5e=["addListener","removeListener"],R5e=["addEventListener","removeEventListener"],I5e=["on","off"];function Ea(n,e,t,r){if(Wt(t)&&(r=t,t=void 0),r)return Ea(n,e,t).pipe(E4(r));var i=Zs(P5e(n)?R5e.map(function(a){return function(l){return n[a](e,l,t)}}):k5e(n)?T5e.map(Kj(n,e)):x5e(n)?I5e.map(Kj(n,e)):[],2),s=i[0],o=i[1];if(!s&&S4(n))return Yy(function(a){return Ea(a,e,t)})(Sr(n));if(!s)throw new TypeError("Invalid event target");return new jn(function(a){var l=function(){for(var c=[],u=0;u<arguments.length;u++)c[u]=arguments[u];return a.next(1<c.length?c:c[0])};return s(l),function(){return o(l)}})}function Kj(n,e){return function(t){return function(r){return n[t](e,r)}}}function k5e(n){return Wt(n.addListener)&&Wt(n.removeListener)}function x5e(n){return Wt(n.on)&&Wt(n.off)}function P5e(n){return Wt(n.addEventListener)&&Wt(n.removeEventListener)}function Bc(n,e,t){n===void 0&&(n=0),t===void 0&&(t=JAe);var r=-1;return e!=null&&(IZ(e)?t=e:r=e),new jn(function(i){var s=f5e(n)?+n-t.now():n;s<0&&(s=0);var o=0;return t.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function tP(n,e){return n===void 0&&(n=0),e===void 0&&(e=Mw),n<0&&(n=0),Bc(n,n,e)}function oy(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n),r=XAe(n,1/0),i=n;return i.length?i.length===1?Sr(i[0]):BZ(r)(zy(i,t)):tE}var L5e=Array.isArray;function O5e(n){return n.length===1&&L5e(n[0])?n[0]:n}function Uo(n,e){return jr(function(t,r){var i=0;t.subscribe(er(r,function(s){return n.call(e,s,i++)&&r.next(s)}))})}function M5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return n=O5e(n),n.length===1?Sr(n[0]):new jn(A5e(n))}function A5e(n){return function(e){for(var t=[],r=function(s){t.push(Sr(n[s]).subscribe(er(e,function(o){if(t){for(var a=0;a<t.length;a++)a!==s&&t[a].unsubscribe();t=null}e.next(o)})))},i=0;t&&!e.closed&&i<n.length;i++)r(i)}}function N5e(n){return jr(function(e,t){var r=!1,i=null,s=null,o=!1,a=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var c=i;i=null,t.next(c)}o&&t.complete()},l=function(){s=null,o&&t.complete()};e.subscribe(er(t,function(c){r=!0,i=c,s||Sr(n(c)).subscribe(s=er(t,a,l))},function(){o=!0,(!r||!s||s.closed)&&t.complete()}))})}function D5e(n,e,t,r,i){return function(s,o){var a=t,l=e,c=0;s.subscribe(er(o,function(u){var f=c++;l=a?n(l,u,f):(a=!0,u),o.next(l)},i))}}function nP(n){return n<=0?function(){return tE}:jr(function(e,t){var r=0;e.subscribe(er(t,function(i){++r<=n&&(t.next(i),n<=r&&t.complete())}))})}function j5e(n){return Ne(function(){return n})}function U5e(n,e){return Yy(function(t,r){return Sr(n(t,r)).pipe(nP(1),j5e(t))})}function F5e(n,e){e===void 0&&(e=Mw);var t=Bc(n,e);return U5e(function(){return t})}function ya(n,e){return e===void 0&&(e=xu),n=n??$5e,jr(function(t,r){var i,s=!0;t.subscribe(er(r,function(o){var a=e(o);(s||!n(i,a))&&(s=!1,i=a,r.next(o))}))})}function $5e(n,e){return n===e}function H5e(n,e){return ya(function(t,r){return t[n]===r[n]})}function VZ(n){return jr(function(e,t){try{e.subscribe(t)}finally{t.add(n)}})}function el(n,e){return jr(D5e(n,e,arguments.length>=2,!0))}function B5e(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Or}:e,r=n.resetOnError,i=r===void 0?!0:r,s=n.resetOnComplete,o=s===void 0?!0:s,a=n.resetOnRefCountZero,l=a===void 0?!0:a;return function(c){var u,f,p,m=0,v=!1,g=!1,S=function(){f==null||f.unsubscribe(),f=void 0},b=function(){S(),u=p=void 0,v=g=!1},w=function(){var k=u;b(),k==null||k.unsubscribe()};return jr(function(k,R){m++,!g&&!v&&S();var I=p=p??t();R.add(function(){m--,m===0&&!g&&!v&&(f=oI(w,l))}),I.subscribe(R),!u&&m>0&&(u=new sy({next:function(C){return I.next(C)},error:function(C){g=!0,S(),f=oI(b,i,C),I.error(C)},complete:function(){v=!0,S(),f=oI(b,o),I.complete()}}),Sr(k).subscribe(u))})(c)}}function oI(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var i=new sy({next:function(){i.unsubscribe(),n()}});return Sr(e.apply(void 0,Qs([],Zs(t)))).subscribe(i)}}function V5e(n,e,t){var r,i,s,o,a=!1;return n&&typeof n=="object"?(r=n.bufferSize,o=r===void 0?1/0:r,i=n.windowTime,e=i===void 0?1/0:i,s=n.refCount,a=s===void 0?!1:s,t=n.scheduler):o=n??1/0,B5e({connector:function(){return new GAe(o,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:a})}function q5e(n){return Uo(function(e,t){return n<=t})}function dn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=Wy(n);return jr(function(r,i){(t?nE(n,r,t):nE(n,r)).subscribe(i)})}function Pt(n,e){return jr(function(t,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};t.subscribe(er(r,function(l){i==null||i.unsubscribe();var c=0,u=s++;Sr(n(l,u)).subscribe(i=er(r,function(f){return r.next(e?e(l,f,u,c++):f)},function(){i=null,a()}))},function(){o=!0,a()}))})}function K5e(){return Pt(xu)}function G5e(n,e){return jr(function(t,r){var i=e;return Pt(function(s,o){return n(i,s,o)},function(s,o){return i=o,o})(t).subscribe(r),function(){i=null}})}function W5e(n){return jr(function(e,t){Sr(n).subscribe(er(t,function(){return t.complete()},eE)),!t.closed&&e.subscribe(t)})}function z5e(n,e,t){var r=Wt(n)||e||t?{next:n,error:e,complete:t}:n;return r?jr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(er(s,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),s.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),s.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),s.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):xu}function rP(n,e){return jr(function(t,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,l=a===void 0?!1:a,c=!1,u=null,f=null,p=!1,m=function(){f==null||f.unsubscribe(),f=null,l&&(S(),p&&r.complete())},v=function(){f=null,p&&r.complete()},g=function(b){return f=Sr(n(b)).subscribe(er(r,m,v))},S=function(){if(c){c=!1;var b=u;u=null,r.next(b),!p&&g(b)}};t.subscribe(er(r,function(b){c=!0,u=b,!(f&&!f.closed)&&(o?S():g(b))},function(){p=!0,!(l&&c&&f&&!f.closed)&&r.complete()}))})}function Y5e(n,e,t){e===void 0&&(e=Mw);var r=Bc(n,e);return rP(function(){return r},t)}function J5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=b4(n);return jr(function(r,i){for(var s=n.length,o=new Array(s),a=n.map(function(){return!1}),l=!1,c=function(f){Sr(n[f]).subscribe(er(i,function(p){o[f]=p,!l&&!a[f]&&(a[f]=!0,(l=a.every(xu))&&(a=null))},eE))},u=0;u<s;u++)c(u);r.subscribe(er(i,function(f){if(l){var p=Qs([f],Zs(o));i.next(t?t.apply(void 0,Qs([],Zs(p))):p)}}))})}function X5e(n,e,t){if(!t)return _.useState(e)[0];const[r]=_.useState(()=>new rs(t)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return n(()=>{if(s.current){s.current=!1;return}r.next(t)},t),i}function ay(n,e){return X5e(_.useEffect,n,e)}var Z5e=()=>new Or,Q5e=n=>n+1|0,eNe=()=>{const n=_.useState(0)[1];return _.useRef(()=>n(Q5e)).current},qZ=typeof window>"u"?_.useEffect:_.useLayoutEffect,Gj=n=>{var e;return(e=n[1])!=null&&e.next?n[1]:{next:n[1],error:n[2],complete:n[3]}};function tNe(n,e){const t=_.useRef(e),r=_.useRef(),i=_.useRef();return qZ(()=>{t.current=e,r.current=Gj(e)}),n(()=>{const s=t.current[0];r.current||(r.current=Gj(t.current));const o=s.subscribe({next:a=>{var l,c;s===t.current[0]&&((c=(l=r.current).next)==null||c.call(l,a))},error:a=>{s===t.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{var a,l;s===t.current[0]&&((l=(a=r.current).complete)==null||l.call(a))}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function nNe(n,e,t,r){return tNe(_.useEffect,[n,e,t,r])}function rNe(n,e,t){if(d5e(e)){const r=e,[i,s]=_.useState(()=>r instanceof rs||r.value!==void 0?r.value:t);return n(r,s),_.useDebugValue(i),i}else{const r=e,[i,s]=_.useState(t),[o]=_.useState(Z5e),[a]=_.useState(()=>r(o,i)),l=_.useRef(c=>o.next(c)).current;return n(a,s),_.useDebugValue(i),[i,l]}}function ly(n,e){return rNe(nNe,n,e)}function tt(n){const e=eNe(),t=_.useRef(n),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let l;return n.subscribe({next:c=>{s.current=!0,l=c},error:c=>{r.current=c}}).unsubscribe(),l});if(qZ(()=>{t.current=n}),_.useEffect(()=>{r.current=null;const l=t.current;let c=o;const u=l.subscribe({next:f=>{l===t.current&&(i.current?a(()=>f):c=f)},error:f=>{l===t.current&&(r.current=f,e())}});return i.current||c!==o&&a(()=>c),i.current=!0,()=>{u.unsubscribe()}},[n]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function iNe(n){const[e]=_.useState(()=>new rs(n)),[t]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[t,e]}class ui{constructor(e,t){this.defaultValue=t,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=t;if(r!==null)try{i=JSON.parse(r)}catch(s){A.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new rs(i),this.value$=this._value$}}function Xn(n){return[tt(n.value$),n.setValue]}const KZ=new ui("opt-in-analytics",null),Aw=()=>{const n=Xn(KZ);return Et.instance.isEnabled()?n:[!1,null]},GZ=new ui("developer-settings-tab",!1),WZ=new ui("duplicate-tiles",0),zZ=new ui("show-non-member-tiles",!1),w4=new ui("debug-tile-layout",!1),cy=new ui("show-connection-stats",!1),sNe=new ui("audio-input",void 0),oNe=new ui("audio-output",void 0),aNe=new ui("video-input",void 0),YZ=new ui("hand-raised-show-timer",!1),JZ=new ui("reactions-show",!0),C4=new ui("reactions-play-sound",!0),XZ=new ui("sound-effect-volume",.5),ZZ=new ui("new-membership-manager",!0),T4=new ui("experimental-to-device-transport",!0),Wj=new ui("always-show-self",!0);var Nw=(n=>(n[n.Guest=0]="Guest",n[n.Registered=1]="Registered",n))(Nw||{});const da=class da{constructor(e){this.posthog=e,this.enabled=!1,this.anonymity=0,this.platformSuperProperties={},this.registrationType=0,this.optInListener=null,this.sanitizeProperties=(i,s)=>(this.anonymity==1&&(i.$referrer=null,i.$referring_domain=null,i.$initial_referrer=null,i.$initial_referring_domain=null,i.$device_id=null),i.$current_url=i.$current_url.split("/").slice(0,3).join(""),i),this.eventCallEnded=new TAe,this.eventSignup=new IAe,this.eventCallStarted=new RAe,this.eventLogin=new kAe,this.eventMuteMicrophone=new xAe,this.eventMuteCamera=new PAe,this.eventUndecryptableToDevice=new LAe,this.eventQualitySurvey=new OAe,this.eventCallDisconnected=new MAe,this.eventCallConnectDuration=new AAe;let t,r;t=Yr().posthogApiKey??void 0,r=Yr().posthogApiHost??void 0,t&&r?(this.posthog.init(t,{api_host:r,autocapture:!1,mask_all_text:!0,mask_all_element_attributes:!0,capture_pageview:!1,sanitize_properties:this.sanitizeProperties,respect_dnt:!0,advanced_disable_decide:!0}),this.enabled=!0):(A.info("Posthog is not enabled because there is no api key or no host given in the config"),this.enabled=!1)}static hasInstance(){return!!this.internalInstance}static get instance(){return this.internalInstance||(this.internalInstance=new da(rAe)),this.internalInstance}static resetInstance(){this.internalInstance=null}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){var t,r;return{appVersion:"embedded-v0.10.0-release-test.2",matrixBackend:Ge?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:Ge||(r=(t=window.matrixclient)==null?void 0:t.getCrypto())==null?void 0:r.getVersion()}}capture(e,t,r){this.enabled&&this.posthog.capture(e,{...t},r)}isEnabled(){return this.enabled}setAnonymity(e){this.enabled&&(e==0||e==1)&&(this.posthog.reset(),this.updateSuperProperties()),this.anonymity=e}static getRandomAnalyticsId(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16)).join("")}async identifyUser(e){if(this.anonymity==2&&this.enabled){let t=await this.getAnalyticsId();try{if(!t&&!Ge){const r=e();await this.setAccountAnalyticsId(r),t=await this.hashedEcAnalyticsId(r)}}catch(r){A.log("Unable to identify user for tracking"+(r==null?void 0:r.toString()))}t?this.posthog.identify(t):A.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let t;if(Ge)t=Yr().posthogUserId;else{const r=await e.getAccountDataFromServer(da.ANALYTICS_EVENT_TYPE);t=(r==null?void 0:r.id)??null}return t?await this.hashedEcAnalyticsId(t):null}async hashedEcAnalyticsId(e){const t=window.matrixclient,r="ec"+e+t.getUserId(),i=await crypto.subtle.digest("sha-256",new TextEncoder().encode(r)),s=new Int32Array(i);return Array.from(s).map(o=>Math.abs(o).toString(16).padStart(2,"0")).join("")}async setAccountAnalyticsId(e){if(!Ge){const t=window.matrixclient,r=await t.getAccountDataFromServer(da.ANALYTICS_EVENT_TYPE);await t.setAccountData(da.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){var e;this.enabled&&this.posthog.reset(),(e=this.optInListener)==null||e.unsubscribe(),this.optInListener=null,this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>A.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=da.getPlatformProperties(),this.registerSuperProperties({...this.platformSuperProperties,registrationType:this.registrationType==0?"Guest":"Registered"})}userRegisteredInThisSession(){return this.eventSignup.getSignupEndTime()>new Date(0)}async maybeIdentifyUser(){window.matrixclient&&(this.anonymity===2&&(this.setRegistrationType(window.matrixclient.isGuest()||window.passwordlessUser?0:1),this.identificationPromise=this.identifyUser(da.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...t},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,t,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{A.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){this.optInListener??(this.optInListener=KZ.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>A.log("Could not identify user"))}))}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};da.ANALYTICS_EVENT_TYPE="im.vector.analytics",da.internalInstance=null;let Et=da;const lNe=2*60*1e3;class cNe{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(t){A.debug(t)}}onEnd(e){switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipEnd(e);return}}get prevCall(){const e=localStorage.getItem("matrix-prev-call");if(e===null)return null;try{return JSON.parse(e)}catch(t){return A.warn("Invalid prev call data",e,"error:",t),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const t=this.prevCall,r=e.attributes["matrix.confId"];if(t!==null&&r===t.callId){const i=RD(e.startTime)-t.hangupTs;i<=lNe&&Et.instance.trackEvent({eventName:"Rejoin",callId:t.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:RD(e.endTime)}}onSummaryReportStart(e){const t=e.events.find(r=>r.name==="matrix.stats.summary");if(t!==void 0){const r=t.attributes;if(r){const i=`${r["matrix.stats.summary.percentageReceivedMedia"]}`,s=`${r["matrix.stats.summary.percentageReceivedVideoMedia"]}`,o=`${r["matrix.stats.summary.percentageReceivedAudioMedia"]}`,a=`${r["matrix.stats.summary.maxJitter"]}`,l=`${r["matrix.stats.summary.maxPacketLoss"]}`,c=`${r["matrix.stats.summary.peerConnections"]}`,u=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,f=`${r["matrix.stats.summary.opponentUsersInCall"]}`,p=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,m=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,v=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;Et.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:l,peerConnections:c,percentageConcealedAudio:u,opponentUsersInCall:f,opponentDevicesInCall:p,diffDevicesToPeerConnections:m,ratioPeerConnectionToDevices:v},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const zj=n=>Object.entries(n).map(([e,t])=>({key:e,type:typeof t,value:t}));class uNe{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,t=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=t.get(o);a===void 0&&(a=[],t.set(o,a)),a.push(s)}const r="p1",i={[r]:{serviceName:"element-call",tags:[]},warnings:null};return JSON.stringify({total:0,limit:0,offset:0,errors:null,data:[...t.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const l=a.spanContext(),c=VR(a.startTime),u=a.duration[0]===-1?e-c:VR(a.duration);return{traceID:s,spanID:l.spanId,operationName:a.name,processID:r,warnings:null,startTime:c,duration:u,references:a.parentSpanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanId}],tags:zj(a.attributes),logs:a.events.map(f=>({timestamp:VR(f.time),fields:[...zj(f.attributes??{}),{key:"event",type:"string",value:f.name}]}))}})}))})}async shutdown(){}}const dNe="element-call";let rd;class Dw{static globalInit(){(!rd||rd.isOtlpEnabled!==!1)&&(A.info("(Re)starting OpenTelemetry debug reporting"),rd==null||rd.dispose(),rd=new Dw(void 0,QZ()))}static get instance(){return rd}constructor(e,t){const r={resource:new Rx({[ROe.SERVICE_NAME]:dNe})};this._provider=new X6e(r),e?(A.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new G6e({url:e}),this._provider.addSpanProcessor(new $Le(this.otlpExporter))):A.info("OTLP collector disabled"),t&&(this.rageshakeProcessor=new uNe,this._provider.addSpanProcessor(this.rageshakeProcessor)),this._provider.addSpanProcessor(new cNe),$R.trace.setGlobalTracerProvider(this._provider),this._tracer=$R.trace.getTracer("my-element-call-otl-tracer")}dispose(){var e;$R.trace.disable(),(e=this._provider)==null||e.shutdown().catch(t=>{A.error("Failed to shutdown OpenTelemetry",t)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const Yj=async n=>{const{gzip:e}=await Cv(async()=>{const{gzip:r}=await import("./pako.esm-Bt8vjcgE.js");return{gzip:r}},[],import.meta.url),t=new TextEncoder().encode(n);return new Blob([e(t)])};async function fNe(n,e){e.append("crypto_version",n.getVersion());const t=await n.getOwnDeviceKeys(),r=[`curve25519:${t.curve25519}`,`ed25519:${t.ed25519}`];e.append("device_keys",r.join(", "));const i=await n.getCrossSigningStatus();e.append("cross_signing_ready",String(await n.isCrossSigningReady())),e.append("cross_signing_key",await n.getCrossSigningKeyId()??"n/a"),e.append("cross_signing_privkey_in_secret_storage",String(i.privateKeysInSecretStorage)),e.append("cross_signing_master_privkey_cached",String(i.privateKeysCachedLocally.masterKey)),e.append("cross_signing_self_signing_privkey_cached",String(i.privateKeysCachedLocally.selfSigningKey)),e.append("cross_signing_user_signing_privkey_cached",String(i.privateKeysCachedLocally.userSigningKey))}async function hNe(n,e,t){const r=n.secretStorage;t.append("secret_storage_ready",String(await e.isSecretStorageReady())),t.append("secret_storage_key_in_account",String(await r.hasKey())),t.append("session_backup_key_in_secret_storage",String(!!await n.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();t.append("session_backup_key_cached",String(!!i)),t.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function QZ(){return Yr().rageshakeSubmitUrl??void 0}function jw(n=QZ){const{client:e}=cf(),[{sending:t,sent:r,error:i},s]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async a=>{const l=n();if(!l)throw new Error("No rageshake URL is configured");if(!t)try{s({sending:!0,sent:!1,error:void 0});let c="UNKNOWN";window.navigator&&window.navigator.userAgent&&(c=window.navigator.userAgent);let u="UNKNOWN";try{u=String(window.matchMedia("(pointer: coarse)").matches)}catch(v){A.warn("Could not get coarse pointer for rageshake submit.",v)}let f=a.rageshakeRequestId?`Rageshake ${a.rageshakeRequestId}`:"";a.description&&(f+=`: ${a.description}`);const p=new FormData;if(p.append("text",f??"User did not supply any additional text."),p.append("app","matrix-video-chat"),p.append("version","embedded-v0.10.0-release-test.2"),p.append("user_agent",c),p.append("installed_pwa","false"),p.append("touch_input",u),p.append("call_backend","livekit"),p.append("hostname",window.location.hostname),e){const v=e.getUserId(),g=e.getUser(v);p.append("display_name",(g==null?void 0:g.displayName)??""),p.append("user_id",e.credentials.userId??""),p.append("device_id",e.deviceId??""),a.roomId&&p.append("room_id",a.roomId);const S=e.getCrypto();S&&(await fNe(S,p),await hNe(e,S,p))}if(a.label&&p.append("label",a.label),navigator.storage&&navigator.storage.persisted)try{p.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(v){A.warn("coulr not get navigator peristed storage",v)}else if(document.hasStorageAccess)try{p.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(v){A.warn("could not get storage access",v)}if(navigator.storage&&navigator.storage.estimate)try{const v=await navigator.storage.estimate();p.append("storageManager_quota",String(v.quota)),p.append("storageManager_usage",String(v.usage)),v.usageDetails&&Object.keys(v.usageDetails).forEach(g=>{p.append(`storageManager_usage_${g}`,String(v.usageDetails[g]))})}catch(v){A.warn("could not obatain storage estimate",v)}if(a.sendLogs){const v=await N3e();for(const g of v)p.append("compressed-log",await Yj(g.lines),g.id);p.append("file",await Yj(Dw.instance.rageshakeProcessor.dump()),"traces.json.gz")}a.rageshakeRequestId&&p.append("group_call_rageshake_request_id",a.rageshakeRequestId);const m=await fetch(l,{method:"POST",body:p});if(m.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${m.status} ${m.statusText}`);s({sending:!1,sent:!0,error:void 0})}catch(c){s({sending:!1,sent:!1,error:c}),A.error(c)}},[e,t,n]),sending:t,sent:r,error:i,available:!!n()}}function pNe(){const{client:n}=cf();return _.useCallback((t,r)=>{n.sendEvent(t,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{A.error("Failed to send org.matrix.rageshake_request event",i)})},[n])}function mNe(n){const[e,t]=_.useState(!1),r=_.useCallback(()=>t(!1),[t]),{client:i}=cf(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=l=>{l.getType()==="org.matrix.rageshake_request"&&n===l.getRoomId()&&i.getUserId()!==l.getSender()&&(o(l.getContent().request_id),t(!0))};return i.on(Oe.Event,a),()=>{i.removeListener(Oe.Event,a)}},[t,n,i]),{rageshakeRequestId:s??"",roomId:n,open:e,onDismiss:r}}const gNe=({description:n})=>{var l;const{submitRageshake:e,sending:t,sent:r,error:i}=jw(),{t:s}=ze(),o=_.useCallback(()=>{e({description:n,sendLogs:!0}).catch(c=>{A.error("Failed to send rageshake",c)})},[e,n]);if(!((l=Ht.get().rageshake)!=null&&l.submit_url))return null;let a=null;if(t)a=E.jsx("span",{children:s("rageshake_sending")});else if(r)a=E.jsx("div",{children:s("rageshake_sent")});else{let c=s("rageshake_send_logs");i&&(c=s("rageshake_button_error_caption")),a=E.jsx(At,{onClick:o,className:bD.wideButton,disabled:t,children:c})}return E.jsx("div",{className:bD.rageshakeControl,children:a})},vNe="_error_19mk1_1",yNe="_icon_19mk1_9",p_={error:vNe,icon:yNe},_Ne="_endCall_bwclo_8",bNe={endCall:_Ne},eQ=({muted:n,...e})=>{const{t}=ze(),r=n?uJ:G6,i=t(n?"unmute_microphone_button_label":"mute_microphone_button_label");return E.jsx(li,{label:i,children:E.jsx(At,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},tQ=({muted:n,...e})=>{const{t}=ze(),r=n?lRe:LJ,i=t(n?"start_video_button_label":"stop_video_button_label");return E.jsx(li,{label:i,children:E.jsx(At,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},nQ=n=>{const{t:e}=ze();return E.jsx(li,{label:e("switch_camera"),children:E.jsx(At,{iconOnly:!0,Icon:sRe,kind:"secondary",...n})})},SNe=({enabled:n,...e})=>{const{t}=ze(),r=t(n?"stop_screenshare_button_label":"screenshare_button_label");return E.jsx(li,{label:r,children:E.jsx(At,{iconOnly:!0,Icon:nRe,kind:n?"primary":"secondary",...e})})},rQ=({className:n,...e})=>{const{t}=ze();return E.jsx(li,{label:t("hangup_button_label"),children:E.jsx(At,{className:Ae(n,bNe.endCall),iconOnly:!0,Icon:tJ,destructive:!0,...e})})},iQ=n=>{const{t:e}=ze();return E.jsx(li,{label:e("common.settings"),children:E.jsx(At,{iconOnly:!0,Icon:tRe,kind:"secondary",...n})})},ENe="_external_jhjdf_8",wNe={external:ENe};function sQ(n,e){const t=cq(n),r=_q(n,{state:e});return[t,r]}const ka=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=sQ(e,t);return E.jsx(ACe,{ref:i,...r,href:s,onClick:o})}),Pd=_.forwardRef(function({className:e,children:t,...r},i){return E.jsx("a",{ref:i,className:Ae(e,wNe.external),target:"_blank",rel:"noreferrer noopener",...r,children:t})}),R4=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=sQ(e,t);return E.jsx(At,{as:"a",ref:i,...r,href:s,onClick:o})});function oQ(n){const[e,t]=_.useState(n.memberships),r=_.useCallback(()=>{A.info(`Memberships changed for call in room ${n.room.roomId} (${n.memberships.length} members)`),t(n.memberships)},[n]);return _.useEffect(()=>(n.on(ar.MembershipsChanged,r),()=>{n.off(ar.MembershipsChanged,r)}),[n,r]),e}const aQ=_.createContext(void 0),I4=()=>{const n=_.useContext(aQ);if(!n)throw new Error("useReactions must be used within a ReactionsProvider");return n},CNe=({children:n,rtcSession:e,vm:t})=>{const r=oQ(e),i=nm(),s=(i==null?void 0:i.state)==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),l=o.client.getDeviceId(),c=`${a}:${l}`,u=_.useMemo(()=>{var b;return(b=r.find(w=>w.sender===a&&w.deviceId===l))==null?void 0:b.eventId},[r,a,l]),f=tt(t.reactions$),p=_.useMemo(()=>c!==void 0?f[c]:void 0,[c,f]),m=tt(t.handsRaised$),v=_.useMemo(()=>c!==void 0?m[c]:void 0,[c,m]),g=_.useCallback(async()=>{if(!c)return;const b=v==null?void 0:v.reactionEventId;if(b)try{await o.client.redactEvent(e.room.roomId,b),A.debug("Redacted raise hand event")}catch(w){throw A.error("Failed to redact reaction event",b,w),w}else try{if(!u)throw new Error("Cannot find own membership event");const w=await o.client.sendEvent(e.room.roomId,ee.Reaction,{"m.relates_to":{rel_type:un.Annotation,event_id:u,key:"🖐️"}});A.debug("Sent raise hand event",w.event_id)}catch(w){A.error("Failed to send raised hand",w)}},[u,c,v,e,o]),S=_.useCallback(async b=>{if(!(!c||p)){if(!u)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,m4,{"m.relates_to":{rel_type:un.Reference,event_id:u},emoji:b.emoji,name:b.name})}},[u,p,o,c,e]);return E.jsx(aQ.Provider,{value:{supportsReactions:s,toggleRaisedHand:g,sendReaction:S},children:n})},TNe="_raisedButton_unw54_1",RNe="_reactionPopupMenu_unw54_5",INe="_reactionPopupMenuRoot_unw54_21",kNe="_reactionPopupMenuModal_unw54_21",xNe="_reactionsMenuSection_unw54_47",PNe="_reactionsMenu_unw54_47",LNe="_reactionButton_unw54_81",ONe="_verticalSeperator_unw54_91",MNe="_alert_unw54_99",Eo={raisedButton:TNe,reactionPopupMenu:RNe,reactionPopupMenuRoot:INe,reactionPopupMenuModal:kNe,reactionsMenuSection:xNe,reactionsMenu:PNe,reactionButton:LNe,verticalSeperator:ONe,alert:MNe};var lQ=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(NNe);if(s){const o=s.props.children,a=i.map(l=>l===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:l);return E.jsx(iP,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return E.jsx(iP,{...r,ref:e,children:t})});lQ.displayName="Slot";var iP=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=jNe(t),s=DNe(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Fa(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});iP.displayName="SlotClone";var ANe=({children:n})=>E.jsx(E.Fragment,{children:n});function NNe(n){return _.isValidElement(n)&&n.type===ANe}function DNe(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function jNe(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var UNe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],FNe=UNe.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?lQ:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{}),$Ne="VisuallyHidden",sP=_.forwardRef((n,e)=>E.jsx(FNe.span,{...n,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...n.style}}));sP.displayName=$Ne;const HNe="_modal_lmgdq_8",BNe="_dialog_lmgdq_14",VNe="_content_lmgdq_21",qNe="_drawer_lmgdq_32",KNe="_close_lmgdq_59",GNe="_header_lmgdq_84",WNe="_body_lmgdq_114",zNe="_tabbed_lmgdq_129",YNe="_handle_lmgdq_133",Ui={modal:HNe,dialog:BNe,content:VNe,drawer:qNe,close:KNe,header:GNe,body:WNe,tabbed:zNe,handle:YNe},JNe="_bg_197ap_8",XNe="_animate_197ap_23",ZNe="_overlay_197ap_40",va={bg:JNe,animate:XNe,overlay:ZNe},lf=({title:n,hideHeader:e,children:t,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:l,...c})=>{const{t:u}=ze(),f=Ew("(hover: none) or (pointer: coarse)"),p=_.useCallback(m=>{m||a==null||a()},[a]);if(f)return E.jsx(Gi.Root,{open:o,onOpenChange:p,dismissible:a!==void 0,children:E.jsxs(Gi.Portal,{children:[E.jsx(Gi.Overlay,{className:Ae(va.bg)}),E.jsx(Gi.Content,{className:Ae(r,i,va.overlay,Ui.modal,Ui.drawer,{[Ui.tabbed]:l}),role:"dialog","aria-describedby":void 0,...c,children:E.jsxs("div",{className:Ui.content,children:[E.jsxs("div",{className:Ui.header,children:[E.jsx("div",{className:Ui.handle}),E.jsx(sP,{asChild:!0,children:E.jsx(Gi.Title,{children:n})})]}),E.jsx("div",{className:Ui.body,children:t})]})})]})});{const m=E.jsx(P6,{asChild:!0,children:E.jsx(Ru,{as:"h2",weight:"semibold",size:"md",children:n})}),v=E.jsxs("div",{className:Ui.header,children:[m,a!==void 0&&E.jsx(eY,{className:Ui.close,"data-testid":"modal_close","aria-label":u("action.close"),children:E.jsx(aw,{width:20,height:20})})]});return E.jsx(R6,{open:o,onOpenChange:p,children:E.jsxs(I6,{children:[E.jsx(k6,{className:Ae(va.bg,va.animate)}),E.jsx(x6,{asChild:!0,"aria-describedby":void 0,role:"dialog",...c,children:E.jsx(fY,{className:Ae(r,s,va.overlay,va.animate,Ui.modal,Ui.dialog,{[Ui.tabbed]:l}),children:E.jsxs("div",{className:Ui.content,children:[e?null:v,e?E.jsx(sP,{asChild:!0,children:m}):null,E.jsx("div",{className:Ui.body,children:t})]})})})]})})}},QNe=({raised:n,open:e,...t})=>{const{t:r}=ze();return E.jsx(li,{label:r("common.reactions"),children:E.jsx(At,{className:Ae(n&&Eo.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:n||e?"primary":"secondary",iconOnly:!0,Icon:n?yJ:eRe,...t})})};function e8e({sendReaction:n,toggleRaisedHand:e,isHandRaised:t,canReact:r,errorText:i}){const{t:s}=ze(),[o,a]=_.useState(!1),l=_.useMemo(()=>o?iy:iy.slice(0,5),[o]),c=s(t?"action.lower_hand":"action.raise_hand");return E.jsxs(E.Fragment,{children:[i&&E.jsx(Q_e,{className:Eo.alert,type:"critical",title:s("error.generic"),children:i}),E.jsxs("div",{className:Eo.reactionPopupMenu,children:[E.jsx("section",{className:Eo.handRaiseSection,children:E.jsx(li,{label:c,caption:"H",children:E.jsx(At,{kind:t?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":t,"aria-label":c,onClick:()=>e(),iconOnly:!0,Icon:yJ})})}),E.jsx("div",{className:Eo.verticalSeperator}),E.jsx("section",{className:Eo.reactionsMenuSection,children:E.jsx("menu",{className:Ae(o&&Eo.reactionsMenuExpanded,Eo.reactionsMenu),children:l.map((u,f)=>E.jsx("li",{children:E.jsx(li,{label:u.name,caption:f<eP?(f+1).toString():void 0,children:E.jsx(At,{kind:"secondary",className:Eo.reactionButton,disabled:!r,onClick:()=>n(u),"aria-keyshortcuts":f<eP?(f+1).toString():void 0,children:u.emoji})})},u.name))})}),E.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:E.jsx(li,{label:s(o?"action.show_less":"action.show_more"),children:E.jsx(At,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?V2e:p2e,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function t8e({identifier:n,vm:e,...t}){const{t:r}=ze(),{toggleRaisedHand:i,sendReaction:s}=I4(),[o,a]=_.useState(!1),[l,c]=_.useState(!1),[u,f]=_.useState(),p=ly(e.handsRaised$.pipe(Ne(S=>!!S[n]))),m=ly(e.reactions$.pipe(Ne(S=>!S[n])));_.useEffect(()=>{f(void 0)},[l]);const v=_.useCallback(async S=>{try{a(!0),await s(S),f(void 0),c(!1)}catch(b){f(b instanceof Error?b.message:"Unknown error"),A.error("Failed to send reaction",b)}finally{a(!1)}},[s]),g=_.useCallback(()=>{(async()=>{try{a(!0),await i(),c(!1)}catch(b){f(b instanceof Error?b.message:"Unknown error"),A.error("Failed to raise/lower hand",b)}finally{a(!1)}})()},[i]);return E.jsxs(E.Fragment,{children:[E.jsx(QNe,{disabled:o,onClick:()=>c(S=>!S),raised:!!p,open:l,...t}),E.jsx(lf,{open:l,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Eo.reactionPopupMenuModal,className:Eo.reactionPopupMenuRoot,onDismiss:()=>c(!1),children:E.jsx(e8e,{errorText:u,isHandRaised:!!p,canReact:!o&&!!m,sendReaction:S=>void v(S),toggleRaisedHand:g})})]})}const uy=({Icon:n,title:e,rageshake:t,fatal:r,children:i,widget:s})=>{const{t:o}=ze(),{confineToRoom:a}=ku(),l=_.useCallback(()=>{window.location.href="/"},[]),c=({widget:f})=>{const p=()=>{f.api.transport.send(Ar.Close,{}).catch(m=>{A.error("Failed to send close action",m)}).finally(()=>{f.api.transport.stop()})};return E.jsx(At,{kind:"primary",onClick:p,children:o("action.close")})},u=()=>r||location.pathname==="/"?E.jsx(At,{kind:"tertiary",className:p_.homeLink,onClick:l,children:o("return_home_button")}):E.jsx(R4,{kind:"tertiary",className:p_.homeLink,to:"/",children:o("return_home_button")});return E.jsxs("div",{className:p_.error,children:[E.jsx(l2e,{className:p_.icon,children:E.jsx(n,{})}),E.jsx(Ru,{as:"h1",weight:"semibold",size:"md",children:e}),i,t&&E.jsx(gNe,{description:`***Error View***: ${e}`}),s?E.jsx(c,{widget:s}):!a&&E.jsx(u,{})]})};class cQ extends Error{constructor(e,t){super(e),this.richMessage=t}}const n8e=()=>{const{t:n}=ze();return E.jsx(uy,{widget:Ge,Icon:gJ,title:n("error.open_elsewhere"),children:E.jsx("p",{children:n("error.open_elsewhere_description",{brand:"Element Call"})})})};class r8e extends cQ{constructor(){super("App opened in another tab",E.jsx(n8e,{}))}}const Qh=({className:n,children:e})=>{const{hideHeader:t}=ku();return E.jsxs("div",{className:Ae(OR.page,n),children:[!t&&E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(Vd,{})}),E.jsx(of,{})]}),E.jsx("div",{className:OR.container,children:E.jsx("div",{className:OR.content,children:e})})]})},dy=({error:n,widget:e})=>{const{t}=ze();return _.useEffect(()=>{A.error(n),nw(n)},[n]),E.jsx(Qh,{children:n instanceof cQ?n.richMessage:E.jsx(uy,{widget:e,Icon:ow,title:t("error.generic"),rageshake:!0,fatal:!0,children:E.jsx("p",{children:t("error.generic_description")})})})},Uw=()=>{const{t:n}=ze();return E.jsx(Qh,{children:E.jsx("h1",{children:n("common.loading")})})},k4=_.createContext(void 0);k4.Provider;const nm=()=>_.useContext(k4);function cf(){var r;let n,e;const t=nm();return(t==null?void 0:t.state)==="valid"&&(n=(r=t.authenticated)==null?void 0:r.client,e=t.setClient),{client:n,setClient:e}}function x4(){var l,c,u;const n=nm();let e,t,r=!1,i=!0,s,o=!1,a;return(n==null?void 0:n.state)==="valid"?(e=(l=n.authenticated)==null?void 0:l.client,t=n.setClient,r=((c=n.authenticated)==null?void 0:c.isPasswordlessUser)??!1,i=!1,o=e!==void 0,a=(u=n.authenticated)==null?void 0:u.logout):(n==null?void 0:n.state)==="error"&&(s=n.error,i=!1),{client:e,setClient:t,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const m_="BroadcastChannel"in window?new BroadcastChannel("load"):null,i8e=({children:n})=>{const e=Na(),[t,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,s8e().then(w=>{r(w),Et.instance.isEnabled()&&Et.instance.startListeningToSettingsChanges()}).catch(w=>A.error(w)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async w=>{const k=dQ();!(t!=null&&t.client)||!k||(await t.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:k.user_id},user:k.user_id,password:k.tempPassword},w),Jj({...k,passwordlessUser:!1}),r({...t,passwordlessUser:!1}))},[t]),o=_.useCallback((w,k)=>{const R=t==null?void 0:t.client;R&&R!==w&&R.stopClient(),Jj(k),r({widgetApi:null,client:w,passwordlessUser:k.passwordlessUser}),Et.instance.isEnabled()&&Et.instance.startListeningToSettingsChanges()},[t==null?void 0:t.client]),a=_.useCallback(async()=>{const w=t==null?void 0:t.client;w&&(await w.logout(!0),await w.clearStores(),uQ(),r(null),await e("/"),Et.instance.logout(),Et.instance.setRegistrationType(Nw.Guest))},[e,t==null?void 0:t.client]);_.useEffect(()=>{Ge||m_==null||m_.postMessage({})},[]);const[l,c]=_.useState(void 0);ov(m_,"message",_.useCallback(()=>{t==null||t.client.stopClient(),c(new r8e)},[t==null?void 0:t.client,c]));const[u,f]=_.useState(!1),[p,m]=_.useState(!1),[v,g]=_.useState(!1),S=_.useMemo(()=>l?{state:"error",error:l}:t===void 0?void 0:{state:"valid",authenticated:t===null?void 0:{client:t.client,isPasswordlessUser:t.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:u,supportedFeatures:{reactions:p,thumbnails:v}},[l,s,t,a,o,u,p,v]),b=_.useCallback((w,k,R)=>{f(o8e(w,R))},[]);return _.useEffect(()=>{if(t){if(window.matrixclient=t.client,window.passwordlessUser=t.passwordlessUser,Et.hasInstance()&&Et.instance.onLoginStatusChanged(),t.client&&t.client.on(Oe.Sync,b),t.widgetApi){g(!1);const w=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),k=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),R=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),I=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!w||!R||!k||!I?(A.warn("Widget does not support reactions"),m(!1)):m(!0)}else m(!0),g(!0);return()=>{t.client&&t.client.removeListener(Oe.Sync,b)}}},[t,b]),l?E.jsx(dy,{widget:Ge,error:l}):E.jsx(k4.Provider,{value:S,children:n})};async function s8e(){if(Ge){A.log("Using a matryoshka client");const n=await Ge.client;return{widgetApi:Ge.api,client:n,passwordlessUser:!1}}else{const{initSPA:n}=await Cv(async()=>{const{initSPA:e}=await import("./spa-YCKBK8Sn.js");return{initSPA:e}},[],import.meta.url);return n(dQ,uQ)}}const uQ=()=>localStorage.removeItem("matrix-auth-store"),Jj=n=>localStorage.setItem("matrix-auth-store",JSON.stringify(n)),dQ=()=>{const n=localStorage.getItem("matrix-auth-store");if(n)return JSON.parse(n)},o8e=(n,e)=>{var t;return n==="ERROR"&&((t=e==null?void 0:e.error)==null?void 0:t.name)==="ConnectionError"};function Jy(n){const[{success:e,loading:t,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let l;return n&&(l=n.getUser(n.getUserId())??void 0),{success:!1,loading:!1,displayName:l==null?void 0:l.rawDisplayName,avatarUrl:l==null?void 0:l.avatarUrl,error:void 0}});_.useEffect(()=>{const l=(u,{displayName:f,avatarUrl:p})=>{o({success:!1,loading:!1,displayName:f,avatarUrl:p,error:void 0})};let c;if(n){const u=n.getUserId();c=n.getUser(u),c==null||c.on(qr.DisplayName,l),c==null||c.on(qr.AvatarUrl,l)}return()=>{c&&(c.removeListener(qr.DisplayName,l),c.removeListener(qr.AvatarUrl,l))}},[n]);const a=_.useCallback(async({displayName:l,avatar:c,removeAvatar:u})=>{if(n){o(f=>({...f,loading:!0,error:void 0,success:!1}));try{await n.setDisplayName(l);let f;u?await n.setAvatarUrl(""):c&&({content_uri:f}=await n.uploadContent(c),await n.setAvatarUrl(f)),o(p=>({...p,displayName:l,avatarUrl:u?void 0:f??p.avatarUrl,loading:!1,success:!0}))}catch(f){o(p=>({...p,loading:!1,error:f instanceof Error?f:Error(f),success:!1}))}}else A.error("Client not initialized before calling saveProfile")},[n]);return{loading:t,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const a8e="_settingsModal_1dkeq_8",l8e="_volumeSlider_1dkeq_20",Xj={settingsModal:a8e,volumeSlider:l8e},c8e="_tabContainer_1nnp9_8",u8e="_tabList_1nnp9_14",Zj={tabContainer:c8e,tabList:u8e};function d8e({label:n,tab:e,onTabChange:t,tabs:r}){const i=_.useId();return E.jsxs("div",{className:Zj.tabContainer,children:[E.jsx(c2e,{role:"tablist","aria-label":n,className:Zj.tabList,children:r.map(({key:s,name:o})=>E.jsx(h2e,{"aria-controls":`${i}[${s}]`,onClick:()=>t(s),active:s===e,children:o}))}),r.map(({key:s,content:o})=>E.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o}))]})}const f8e="_fieldRow_iwncy_8",h8e="_field_iwncy_8",p8e="_rightAlign_iwncy_21",m8e="_inputField_iwncy_33",g8e="_disabled_iwncy_52",v8e="_prefix_iwncy_110",y8e="_checkboxField_iwncy_131",_8e="_checkbox_iwncy_131",b8e="_description_iwncy_168",S8e="_errorMessage_iwncy_197",E8e="_noLabel_iwncy_210",As={fieldRow:f8e,field:h8e,rightAlign:p8e,inputField:m8e,disabled:g8e,prefix:v8e,checkboxField:y8e,checkbox:_8e,description:b8e,errorMessage:S8e,noLabel:E8e},w8e=(n,e)=>_.createElement("svg",{fill:"none",height:24,stroke:"#000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,viewBox:"0 0 24 24",width:24,xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"m20 6-11 11-5-5"})),C8e=_.forwardRef(w8e);class fQ extends Error{constructor(e,t){super(t(e,{lng:"en"})),this.translatedMessage=t(e)}}class T8e extends fQ{}const Qj=(n,e)=>new T8e(n,e);function vt({children:n,rightAlign:e,className:t}){return E.jsx("div",{className:Ae(As.fieldRow,{[As.rightAlign]:e},t),children:n})}function R8e({children:n,className:e}){return E.jsx("div",{className:Ae(As.field,e),children:n})}const _n=_.forwardRef(({id:n,label:e,className:t,type:r,checked:i,prefix:s,suffix:o,description:a,disabled:l,min:c,...u},f)=>{const p=_.useId();return E.jsxs(R8e,{className:Ae(r==="checkbox"?As.checkboxField:As.inputField,{[As.prefix]:!!s,[As.disabled]:l},t),children:[s&&E.jsx("span",{children:s}),r==="textarea"?E.jsx("textarea",{id:n,ref:f,disabled:l,"aria-describedby":p,...u}):E.jsx("input",{id:n,ref:f,type:r,checked:i,disabled:l,"aria-describedby":p,min:c,...u}),E.jsxs("label",{htmlFor:n,children:[r==="checkbox"&&E.jsx("div",{className:As.checkbox,children:E.jsx(C8e,{})}),e]}),o&&E.jsx("span",{children:o}),a&&E.jsx("p",{id:p,className:e?As.description:Ae(As.description,As.noLabel),children:a})]})});_n.displayName="InputField";const Pu=({error:n})=>E.jsx("p",{className:As.errorMessage,children:n instanceof fQ?n.translatedMessage:n.message}),I8e="_avatarInputField_1ep5q_8",k8e="_avatar_1ep5q_8",x8e="_fileInput_1ep5q_17",P8e="_edit_1ep5q_21",g_={avatarInputField:I8e,avatar:k8e,fileInput:x8e,edit:P8e},hQ=({id:n,label:e,className:t,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:l}=ze(),[c,u]=_.useState(!1),[f,p]=_.useState(void 0),[m,v]=_.useState(!1),g=_.useRef(null);_.useEffect(()=>{const w=g.current,k=R=>{const I=R;I.target.files&&I.target.files.length>0?(p(URL.createObjectURL(I.target.files[0])),u(!1)):p(void 0)};return w.addEventListener("change",k),()=>{w==null||w.removeEventListener("change",k)}});const S=_.useCallback(()=>{g.current.click()},[g]),b=_.useCallback(()=>{u(!0),o()},[o]);return E.jsxs("div",{className:Ae(g_.avatarInputField,t),children:[E.jsx(Zp,{id:i,className:g_.avatar,name:s,size:Xp.XL,src:c?void 0:f||r}),E.jsx("input",{id:n,accept:"image/*",ref:g,type:"file",className:g_.fileInput,role:"button","aria-label":e,...a}),E.jsx("div",{className:g_.edit,children:(r||f)&&!c?E.jsxs(D6,{title:l("action.edit"),showTitle:!1,open:m,onOpenChange:v,trigger:E.jsx(At,{iconOnly:!0,Icon:sD,kind:"tertiary",size:"sm","aria-label":l("action.edit")}),children:[E.jsx(Sp,{Icon:rRe,label:l("action.upload_file"),onSelect:S}),E.jsx(Sp,{Icon:K2e,label:l("action.remove"),kind:"critical",onSelect:b})]}):E.jsx(At,{type:"button",iconOnly:!0,Icon:sD,kind:"tertiary",size:"sm","aria-label":l("action.edit"),onClick:S})})]})};hQ.displayName="AvatarInputField";const L8e="_content_gj715_8",O8e="_avatarFieldRow_gj715_15",eU={content:L8e,avatarFieldRow:O8e},M8e=({client:n})=>{const{t:e}=ze(),{error:t,displayName:r,avatarUrl:i,saveProfile:s}=Jy(n),o=_.useMemo(()=>n.getUserId(),[n]),a=_.useRef(null),l=_.useRef(!1),c=_.useCallback(()=>{l.current=!0},[]),u=_.useRef(!1),f=_.useCallback(()=>{u.current=!0,l.current=!0},[]);return _.useEffect(()=>{const p=a.current;return()=>{if(l.current){const m=new FormData(p),v=m.get("displayName"),g=m.get("avatar"),S=typeof g=="string"?g.length:(g==null?void 0:g.size)??0,b=typeof v=="string"?v:(v==null?void 0:v.name)??null;if(!b)return;s({displayName:b,avatar:g&&S>0?g:void 0,removeAvatar:u.current&&(!g||S===0)}).catch(w=>{A.error("Failed to save profile",w)})}}},[s]),E.jsxs("form",{onChange:c,ref:a,className:eU.content,children:[E.jsx(vt,{className:eU.avatarFieldRow,children:o&&r&&E.jsx(hQ,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:f})}),E.jsx(vt,{children:E.jsx(_n,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:n.getUserId()})}),E.jsx(vt,{children:E.jsx(_n,{id:"displayName",name:"displayName",label:e("common.display_name"),type:"text",required:!0,autoComplete:"off",placeholder:e("common.display_name"),defaultValue:r,"data-testid":"profile_displayname"})}),t&&E.jsx(vt,{children:E.jsx(Pu,{error:t})})]})},A8e="_feedback_19yh9_8",pQ={feedback:A8e},mQ=()=>E.jsxs(Qi,{i18nKey:"analytics_notice",children:["By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our"," ",E.jsx(Pd,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",E.jsx(Pd,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),N8e=({roomId:n})=>{const{t:e}=ze(),{submitRageshake:t,sending:r,sent:i,error:s,available:o}=jw(),a=pNe(),l=_.useCallback(f=>{f.preventDefault();const p=new FormData(f.target),m=p.get("description"),v=typeof m=="string"?m:"",g=!!p.get("sendLogs"),S=bs(16);t({description:v,sendLogs:g,rageshakeRequestId:S,roomId:n}).catch(b=>{A.error("Failed to send feedback rageshake",b)}),n&&g&&a(n,S)},[t,n,a]);Aw();const c=null,u=o?E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:e("settings.feedback_tab_h4")}),E.jsx(Xt,{children:e("settings.feedback_tab_body")}),E.jsxs("form",{onSubmit:l,children:[E.jsx(vt,{children:E.jsx(_n,{className:pQ.feedback,id:"description",name:"description",label:e("settings.feedback_tab_description_label"),placeholder:e("settings.feedback_tab_description_label"),type:"textarea",disabled:r||i})}),!i&&E.jsxs(vt,{children:[E.jsx(_n,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),E.jsx(At,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),E.jsxs(vt,{children:[s&&E.jsx(Pu,{error:s}),i&&E.jsx(Xt,{children:e("settings.feedback_tab_thank_you")})]})]})]}):null;return E.jsxs("div",{children:[c,u]})};var Ob={exports:{}},D8e=Ob.exports,tU;function j8e(){return tU||(tU=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(D8e,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?l:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function f(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return c(g)||f.apply(this,arguments)}function m(g,S){var b=this,w,k,R,I="loglevel";typeof g=="string"?I+=":"+g:typeof g=="symbol"&&(I=void 0);function C(j){var U=(i[j]||"silent").toUpperCase();if(!(typeof window===t||!I)){try{window.localStorage[I]=U;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+U+";"}catch{}}}function x(){var j;if(!(typeof window===t||!I)){try{j=window.localStorage[I]}catch{}if(typeof j===t)try{var U=window.document.cookie,H=encodeURIComponent(I),K=U.indexOf(H+"=");K!==-1&&(j=/^([^;]+)/.exec(U.slice(K+H.length+1))[1])}catch{}return b.levels[j]===void 0&&(j=void 0),j}}function O(){if(!(typeof window===t||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(j){var U=j;if(typeof U=="string"&&b.levels[U.toUpperCase()]!==void 0&&(U=b.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=b.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+j)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return R??k??w},b.setLevel=function(j,U){return R=N(j),U!==!1&&C(R),u.call(b)},b.setDefaultLevel=function(j){k=N(j),x()||b.setLevel(j,!1)},b.resetLevel=function(){R=null,O(),u.call(b)},b.enableAll=function(j){b.setLevel(b.levels.TRACE,j)},b.disableAll=function(j){b.setLevel(b.levels.SILENT,j)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var j in s)s[j].rebuild()},w=N(o?o.getLevel():"WARN");var D=x();D!=null&&(R=N(D)),u.call(b)}o=new m,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[S];return b||(b=s[S]=new m(S,o.methodFactory)),b};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})}(Ob)),Ob.exports}var U8e=j8e();const F8e=qo(U8e);var $8e=(n,e,t)=>new Promise((r,i)=>{var s=l=>{try{a(t.next(l))}catch(c){i(c)}},o=l=>{try{a(t.throw(l))}catch(c){i(c)}},a=l=>l.done?r(l.value):Promise.resolve(l.value).then(s,o);a((t=t.apply(n,e)).next())}),H8e=[le.ConnectionStateChanged,le.RoomMetadataChanged,le.ActiveSpeakersChanged,le.ConnectionQualityChanged,le.ParticipantConnected,le.ParticipantDisconnected,le.ParticipantPermissionsChanged,le.ParticipantMetadataChanged,le.ParticipantNameChanged,le.ParticipantAttributesChanged,le.TrackMuted,le.TrackUnmuted,le.TrackPublished,le.TrackUnpublished,le.TrackStreamStateChanged,le.TrackSubscriptionFailed,le.TrackSubscriptionPermissionChanged,le.TrackSubscriptionStatusChanged],B8e=[...H8e,le.LocalTrackPublished,le.LocalTrackUnpublished];oe.TrackPublished,oe.TrackUnpublished,oe.TrackMuted,oe.TrackUnmuted,oe.TrackStreamStateChanged,oe.TrackSubscribed,oe.TrackUnsubscribed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionFailed,oe.LocalTrackPublished,oe.LocalTrackUnpublished;var V8e=[oe.ConnectionQualityChanged,oe.IsSpeakingChanged,oe.ParticipantMetadataChanged,oe.ParticipantPermissionsChanged,oe.TrackMuted,oe.TrackUnmuted,oe.TrackPublished,oe.TrackUnpublished,oe.TrackStreamStateChanged,oe.TrackSubscriptionFailed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionStatusChanged];[...V8e,oe.LocalTrackPublished,oe.LocalTrackUnpublished];var q8e=F8e.getLogger("lk-components-js");q8e.setDefaultLevel("WARN");function K8e(n,...e){return new jn(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(dn(n))}function G8e(n,e){return new jn(r=>{const i=(...o)=>{r.next(o)};return n.on(e,i),()=>{n.off(e,i)}})}function W8e(n,e,t=!0){var r;const i=()=>$8e(this,null,function*(){try{const a=yield Ol.getLocalDevices(n,t);s.next(a)}catch(a){e==null||e(a)}}),s=new Or,o=s.pipe(VZ(()=>{var a;(a=navigator==null?void 0:navigator.mediaDevices)==null||a.removeEventListener("devicechange",i)}));if(typeof window<"u"){if(!window.isSecureContext)throw new Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");(r=navigator==null?void 0:navigator.mediaDevices)==null||r.addEventListener("devicechange",i)}return nE(Ol.getLocalDevices(n,t).catch(a=>(e==null||e(a),[])),o)}function P4(n,...e){return new jn(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(dn(n))}function L4(n){return P4(n,oe.TrackMuted,oe.TrackUnmuted,oe.ParticipantPermissionsChanged,oe.TrackPublished,oe.TrackUnpublished,oe.LocalTrackPublished,oe.LocalTrackUnpublished,oe.MediaDevicesError,oe.TrackSubscriptionStatusChanged).pipe(Ne(t=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=t,o=t.getTrackPublication(ue.Source.Microphone),a=t.getTrackPublication(ue.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:t}}))}function z8e(n,e={}){var t;let r;const i=new jn(l=>(r=l,()=>a.unsubscribe())).pipe(dn(Array.from(n.remoteParticipants.values()))),s=(t=e.additionalRoomEvents)!=null?t:B8e,o=Array.from(new Set([le.ParticipantConnected,le.ParticipantDisconnected,le.ConnectionStateChanged,...s])),a=K8e(n,...o).subscribe(l=>r==null?void 0:r.next(Array.from(l.remoteParticipants.values())));return n.remoteParticipants.size>0&&(r==null||r.next(Array.from(n.remoteParticipants.values()))),i}new TextEncoder;new TextDecoder;function aI(n,e,t){const r=_.useRef(!1),i=t||r.current;r.current||(r.current=t);const s=_.useMemo(()=>W8e(n,()=>A.error("Error creating MediaDeviceObserver"),i).pipe(dn([])),[n,i]),o=tt(_.useMemo(()=>s.pipe(Ne(f=>{var m;let p=new Map(f.map((v,g)=>[v.deviceId,v.label?{type:"name",name:v.label}:{type:"number",number:g+1}]));return n==="audiooutput"&&p.size&&!p.has("")&&!p.has("default")&&(p=new Map([["",{type:"default",name:((m=f[0])==null?void 0:m.label)||null}],...p])),p})),[n,s])),[a,l]=Xn(e),c=_.useMemo(()=>{if(o.size)return a!==void 0&&o.has(a)||o.size===1&&o.has("")?a:o.keys().next().value},[o,a]),u=tt(_.useMemo(()=>s.pipe(Ne(f=>{var p;return(p=f.find(m=>m.deviceId===c))==null?void 0:p.groupId})),[s,c]));return _.useMemo(()=>({available:o,selectedId:c,selectedGroupId:u,select:l}),[o,c,u,l])}const lI={available:new Map,selectedId:void 0,selectedGroupId:void 0,select:()=>{}},Y8e={audioInput:lI,audioOutput:lI,videoInput:lI,startUsingDeviceNames:()=>{},stopUsingDeviceNames:()=>{}},gQ=_.createContext(Y8e),J8e=({children:n})=>{const[e,t]=_.useState(0),r=e>0,i=aI("audioinput",sNe,r),s=aI("audiooutput",oNe,r),o=aI("videoinput",aNe,r),a=_.useCallback(()=>t(u=>u+1),[t]),l=_.useCallback(()=>t(u=>u-1),[t]),c=_.useMemo(()=>({audioInput:i,audioOutput:s,videoInput:o,startUsingDeviceNames:a,stopUsingDeviceNames:l}),[i,s,o,a,l]);return E.jsx(gQ.Provider,{value:c,children:n})},uf=()=>_.useContext(gQ),X8e=(n,e=!0)=>_.useEffect(()=>{if(e)return n.startUsingDeviceNames(),n.stopUsingDeviceNames},[n,e]),Z8e=()=>{const{t:n}=ze(),[e,t]=Xn(YZ),[r,i]=Xn(JZ),[s,o]=Xn(C4),a=(u,f)=>{f(u.target.checked)},[l,c]=Xn(GZ);return E.jsxs("div",{children:[E.jsx(Xt,{children:n("settings.preferences_tab.introduction")}),E.jsx(vt,{children:E.jsx(_n,{id:"showHandRaisedTimer",label:n("settings.preferences_tab.show_hand_raised_timer_label"),description:n("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:u=>a(u,t)})}),E.jsx(vt,{children:E.jsx(_n,{id:"showReactions",label:n("settings.preferences_tab.reactions_show_label"),description:n("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:u=>a(u,i)})}),E.jsx(vt,{children:E.jsx(_n,{id:"playReactionSound",label:n("settings.preferences_tab.reactions_play_sound_label"),description:n("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:u=>a(u,o)})}),E.jsx(vt,{children:E.jsx(_n,{id:"developerSettingsTab",type:"checkbox",checked:l,label:n("settings.preferences_tab.developer_mode_label"),description:n("settings.preferences_tab.developer_mode_label_description"),onChange:u=>c(u.target.checked)})})]})};function vQ(n,[e,t]){return Math.min(t,Math.max(e,n))}function Q8e(n){const e=_.useRef({value:n,previous:n});return _.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var rE=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(t9e);if(s){const o=s.props.children,a=i.map(l=>l===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:l);return E.jsx(oP,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return E.jsx(oP,{...r,ref:e,children:t})});rE.displayName="Slot";var oP=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=r9e(t),s=n9e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Fa(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});oP.displayName="SlotClone";var e9e=({children:n})=>E.jsx(E.Fragment,{children:n});function t9e(n){return _.isValidElement(n)&&n.type===e9e}function n9e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function r9e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var i9e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Fw=i9e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?rE:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{});function s9e(n){const e=n+"CollectionProvider",[t,r]=Ua(e),[i,s]=t(e,{collectionRef:{current:null},itemMap:new Map}),o=m=>{const{scope:v,children:g}=m,S=Ce.useRef(null),b=Ce.useRef(new Map).current;return E.jsx(i,{scope:v,itemMap:b,collectionRef:S,children:g})};o.displayName=e;const a=n+"CollectionSlot",l=Ce.forwardRef((m,v)=>{const{scope:g,children:S}=m,b=s(a,g),w=nn(v,b.collectionRef);return E.jsx(rE,{ref:w,children:S})});l.displayName=a;const c=n+"CollectionItemSlot",u="data-radix-collection-item",f=Ce.forwardRef((m,v)=>{const{scope:g,children:S,...b}=m,w=Ce.useRef(null),k=nn(v,w),R=s(c,g);return Ce.useEffect(()=>(R.itemMap.set(w,{ref:w,...b}),()=>void R.itemMap.delete(w))),E.jsx(rE,{[u]:"",ref:k,children:S})});f.displayName=c;function p(m){const v=s(n+"CollectionConsumer",m);return Ce.useCallback(()=>{const S=v.collectionRef.current;if(!S)return[];const b=Array.from(S.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((R,I)=>b.indexOf(R.ref.current)-b.indexOf(I.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:l,ItemSlot:f},p,r]}var yQ=["PageUp","PageDown"],_Q=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],bQ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},rm="Slider",[aP,o9e,a9e]=s9e(rm),[SQ,hGe]=Ua(rm,[a9e]),[l9e,$w]=SQ(rm),EQ=_.forwardRef((n,e)=>{const{name:t,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:f=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:v,...g}=n,S=_.useRef(new Set),b=_.useRef(0),k=o==="horizontal"?c9e:u9e,[R=[],I]=fw({prop:u,defaultProp:c,onChange:j=>{var H;(H=[...S.current][b.current])==null||H.focus(),f(j)}}),C=_.useRef(R);function x(j){const U=m9e(R,j);D(j,U)}function O(j){D(j,b.current)}function N(){const j=C.current[b.current];R[b.current]!==j&&p(R)}function D(j,U,{commit:H}={commit:!1}){const K=_9e(s),B=b9e(Math.round((j-r)/s)*s+r,K),z=vQ(B,[r,i]);I((W=[])=>{const V=h9e(W,z,U);if(y9e(V,l*s)){b.current=V.indexOf(z);const q=String(V)!==String(W);return q&&H&&p(V),q?V:W}else return W})}return E.jsx(l9e,{scope:n.__scopeSlider,name:t,disabled:a,min:r,max:i,valueIndexToChangeRef:b,thumbs:S.current,values:R,orientation:o,form:v,children:E.jsx(aP.Provider,{scope:n.__scopeSlider,children:E.jsx(aP.Slot,{scope:n.__scopeSlider,children:E.jsx(k,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:e,onPointerDown:We(g.onPointerDown,()=>{a||(C.current=R)}),min:r,max:i,inverted:m,onSlideStart:a?void 0:x,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:N,onHomeKeyDown:()=>!a&&D(r,0,{commit:!0}),onEndKeyDown:()=>!a&&D(i,R.length-1,{commit:!0}),onStepKeyDown:({event:j,direction:U})=>{if(!a){const B=yQ.includes(j.key)||j.shiftKey&&_Q.includes(j.key)?10:1,z=b.current,W=R[z],V=s*B*U;D(W+V,z,{commit:!0})}}})})})})});EQ.displayName=rm;var[wQ,CQ]=SQ(rm,{startEdge:"left",endEdge:"right",size:"width",direction:1}),c9e=_.forwardRef((n,e)=>{const{min:t,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=n,[f,p]=_.useState(null),m=nn(e,k=>p(k)),v=_.useRef(void 0),g=i6(i),S=g==="ltr",b=S&&!s||!S&&s;function w(k){const R=v.current||f.getBoundingClientRect(),I=[0,R.width],x=O4(I,b?[t,r]:[r,t]);return v.current=R,x(k-R.left)}return E.jsx(wQ,{scope:n.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:E.jsx(TQ,{dir:g,"data-orientation":"horizontal",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const R=w(k.clientX);o==null||o(R)},onSlideMove:k=>{const R=w(k.clientX);a==null||a(R)},onSlideEnd:()=>{v.current=void 0,l==null||l()},onStepKeyDown:k=>{const I=bQ[b?"from-left":"from-right"].includes(k.key);c==null||c({event:k,direction:I?-1:1})}})})}),u9e=_.forwardRef((n,e)=>{const{min:t,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:l,...c}=n,u=_.useRef(null),f=nn(e,u),p=_.useRef(void 0),m=!i;function v(g){const S=p.current||u.current.getBoundingClientRect(),b=[0,S.height],k=O4(b,m?[r,t]:[t,r]);return p.current=S,k(g-S.top)}return E.jsx(wQ,{scope:n.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:E.jsx(TQ,{"data-orientation":"vertical",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const S=v(g.clientY);s==null||s(S)},onSlideMove:g=>{const S=v(g.clientY);o==null||o(S)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=bQ[m?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:b?-1:1})}})})}),TQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:l,...c}=n,u=$w(rm,t);return E.jsx(Fw.span,{...c,ref:e,onKeyDown:We(n.onKeyDown,f=>{f.key==="Home"?(o(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):yQ.concat(_Q).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:We(n.onPointerDown,f=>{const p=f.target;p.setPointerCapture(f.pointerId),f.preventDefault(),u.thumbs.has(p)?p.focus():r(f)}),onPointerMove:We(n.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&i(f)}),onPointerUp:We(n.onPointerUp,f=>{const p=f.target;p.hasPointerCapture(f.pointerId)&&(p.releasePointerCapture(f.pointerId),s(f))})})}),RQ="SliderTrack",IQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=$w(RQ,t);return E.jsx(Fw.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});IQ.displayName=RQ;var lP="SliderRange",kQ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=$w(lP,t),s=CQ(lP,t),o=_.useRef(null),a=nn(e,o),l=i.values.length,c=i.values.map(p=>PQ(p,i.min,i.max)),u=l>1?Math.min(...c):0,f=100-Math.max(...c);return E.jsx(Fw.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...n.style,[s.startEdge]:u+"%",[s.endEdge]:f+"%"}})});kQ.displayName=lP;var cP="SliderThumb",xQ=_.forwardRef((n,e)=>{const t=o9e(n.__scopeSlider),[r,i]=_.useState(null),s=nn(e,a=>i(a)),o=_.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return E.jsx(d9e,{...n,ref:s,index:o})}),d9e=_.forwardRef((n,e)=>{const{__scopeSlider:t,index:r,name:i,...s}=n,o=$w(cP,t),a=CQ(cP,t),[l,c]=_.useState(null),u=nn(e,w=>c(w)),f=l?o.form||!!l.closest("form"):!0,p=HG(l),m=o.values[r],v=m===void 0?0:PQ(m,o.min,o.max),g=p9e(r,o.values.length),S=p==null?void 0:p[a.size],b=S?g9e(S,v,a.direction):0;return _.useEffect(()=>{if(l)return o.thumbs.add(l),()=>{o.thumbs.delete(l)}},[l,o.thumbs]),E.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${v}% + ${b}px)`},children:[E.jsx(aP.ItemSlot,{scope:n.__scopeSlider,children:E.jsx(Fw.span,{role:"slider","aria-label":n["aria-label"]||g,"aria-valuemin":o.min,"aria-valuenow":m,"aria-valuemax":o.max,"aria-orientation":o.orientation,"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,tabIndex:o.disabled?void 0:0,...s,ref:u,style:m===void 0?{display:"none"}:n.style,onFocus:We(n.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),f&&E.jsx(f9e,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:m},r)]})});xQ.displayName=cP;var f9e=n=>{const{value:e,...t}=n,r=_.useRef(null),i=Q8e(e);return _.useEffect(()=>{const s=r.current,o=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(o,"value").set;if(i!==e&&l){const c=new Event("input",{bubbles:!0});l.call(s,e),s.dispatchEvent(c)}},[i,e]),E.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:e})};function h9e(n=[],e,t){const r=[...n];return r[t]=e,r.sort((i,s)=>i-s)}function PQ(n,e,t){const s=100/(t-e)*(n-e);return vQ(s,[0,100])}function p9e(n,e){return e>2?`Value ${n+1} of ${e}`:e===2?["Minimum","Maximum"][n]:void 0}function m9e(n,e){if(n.length===1)return 0;const t=n.map(i=>Math.abs(i-e)),r=Math.min(...t);return t.indexOf(r)}function g9e(n,e,t){const r=n/2,s=O4([0,50],[0,r]);return(r-s(e)*t)*t}function v9e(n){return n.slice(0,-1).map((e,t)=>n[t+1]-e)}function y9e(n,e){if(e>0){const t=v9e(n);return Math.min(...t)>=e}return!0}function O4(n,e){return t=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(n[1]-n[0]);return e[0]+r*(t-n[0])}}function _9e(n){return(String(n).split(".")[1]||"").length}function b9e(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}var S9e=EQ,E9e=IQ,w9e=kQ,C9e=xQ;const T9e="_slider_15go1_8",R9e="_track_15go1_14",I9e="_highlight_15go1_31",k9e="_handle_15go1_43",v_={slider:T9e,track:R9e,highlight:I9e,handle:k9e},LQ=({className:n,label:e,value:t,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:l})=>{const c=_.useCallback(([f])=>r(f),[r]),u=_.useCallback(([f])=>i==null?void 0:i(f),[i]);return E.jsxs(S9e,{className:Ae(n,v_.slider),value:[t],onValueChange:c,onValueCommit:u,min:s,max:o,step:a,disabled:l,children:[E.jsx(E9e,{className:v_.track,children:E.jsx(w9e,{className:v_.highlight})}),E.jsx(li,{placement:"top",label:Math.round(t*100).toString()+"%",children:E.jsx(C9e,{className:v_.handle,"aria-label":e})})]})},x9e="_selection_1akwb_1",P9e="_title_1akwb_5",L9e="_separator_1akwb_10",O9e="_options_1akwb_14",M9e="_secondary_1akwb_20",_g={selection:x9e,title:P9e,separator:L9e,options:O9e,secondary:M9e},cI=({devices:n,title:e,numberedLabel:t})=>{const{t:r}=ze(),i=_.useId(),s=_.useCallback(o=>{n.select(o.target.value)},[n]);return n.available.size==0?null:E.jsxs("div",{className:_g.selection,children:[E.jsx(Ru,{type:"body",weight:"semibold",size:"sm",as:"h4",className:_g.title,children:e}),E.jsx(MY,{className:_g.separator}),E.jsx("div",{className:_g.options,children:[...n.available].map(([o,a])=>{let l;switch(a.type){case"name":l=a.name;break;case"number":l=t(a.number);break;case"default":l=a.name===null?r("settings.devices.default"):E.jsxs(Qi,{i18nKey:"settings.devices.default_named",name:a.name,children:["Default"," ",E.jsxs("span",{className:_g.secondary,children:["(",{name:a.name},")"]})]});break}return E.jsx(GTe,{name:i,control:E.jsx(i2e,{checked:o===n.selectedId,onChange:s,value:o}),children:E.jsx(DTe,{children:l})},o)})})]})},A9e={},N9e={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"embedded-v0.10.0-release-test.2",VITE_PACKAGE:"embedded"},D9e=({client:n,livekitRoom:e})=>{var b;const{t}=ze(),[r,i]=Xn(WZ),[s,o]=Xn(w4),[a,l]=Xn(zZ),[c,u]=Xn(cy),[f,p]=Xn(ZZ),[m,v]=Xn(T4),g=ku(),S=_.useMemo(()=>{var w;if((w=e==null?void 0:e.engine.client.ws)!=null&&w.url){const k=new URL(e.engine.client.ws.url);return k.search="",k}return null},[e]);return E.jsxs(E.Fragment,{children:[E.jsx("p",{children:t("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),E.jsx("p",{children:t("version",{productName:"Element Call",version:"embedded-v0.10.0-release-test.2"})}),E.jsx("p",{children:t("developer_mode.crypto_version",{version:((b=n.getCrypto())==null?void 0:b.getVersion())||"unknown"})}),E.jsx("p",{children:t("developer_mode.matrix_id",{id:n.getUserId()||"unknown"})}),E.jsx("p",{children:t("developer_mode.device_id",{id:n.getDeviceId()||"unknown"})}),E.jsx(vt,{children:E.jsx(_n,{id:"duplicateTiles",type:"number",label:t("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(w=>{const k=w.target.valueAsNumber;k<0||i(Number.isNaN(k)?0:k)},[i])})}),E.jsx(vt,{children:E.jsx(_n,{id:"debugTileLayout",type:"checkbox",checked:s,label:t("developer_mode.debug_tile_layout_label"),onChange:w=>o(w.target.checked)})}),E.jsx(vt,{children:E.jsx(_n,{id:"showNonMemberTiles",type:"checkbox",label:t("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(w=>{l(w.target.checked)},[l])})}),E.jsx(vt,{children:E.jsx(_n,{id:"showConnectionStats",type:"checkbox",label:t("developer_mode.show_connection_stats"),checked:!!c,onChange:_.useCallback(w=>{u(w.target.checked)},[u])})}),E.jsx(vt,{children:E.jsx(_n,{id:"useNewMembershipManager",type:"checkbox",label:t("developer_mode.use_new_membership_manager"),checked:!!f,onChange:_.useCallback(w=>{p(w.target.checked)},[p])})}),E.jsx(vt,{children:E.jsx(_n,{id:"useToDeviceKeyTransport",type:"checkbox",label:t("developer_mode.use_to_device_key_transport"),checked:!!m,onChange:_.useCallback(w=>{v(w.target.checked)},[v])})}),e?E.jsxs(E.Fragment,{children:[E.jsx("p",{children:t("developer_mode.livekit_sfu",{url:(S==null?void 0:S.href)||"unknown"})}),E.jsx("p",{children:t("developer_mode.livekit_server_info")}),E.jsxs("pre",{className:A9e.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null,E.jsx("p",{children:t("developer_mode.environment_variables")}),E.jsx("pre",{children:JSON.stringify(N9e,null,2)}),E.jsx("p",{children:t("developer_mode.url_params")}),E.jsx("pre",{children:JSON.stringify(g,null,2)})]})},M4="audio",A4=({open:n,onDismiss:e,tab:t,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=ze(),l=uf();X8e(l,n);const[c,u]=Xn(XZ),[f,p]=_.useState(c),[m]=Xn(GZ),{available:v}=jw(),g={key:"audio",name:a("common.audio"),content:E.jsx(E.Fragment,{children:E.jsxs(eD,{children:[E.jsx(cI,{devices:l.audioInput,title:a("settings.devices.microphone"),numberedLabel:C=>a("settings.devices.microphone_numbered",{n:C})}),E.jsx(cI,{devices:l.audioOutput,title:a("settings.devices.speaker"),numberedLabel:C=>a("settings.devices.speaker_numbered",{n:C})}),E.jsxs("div",{className:Xj.volumeSlider,children:[E.jsx("label",{children:a("settings.audio_tab.effect_volume_label")}),E.jsx("p",{children:a("settings.audio_tab.effect_volume_description")}),E.jsx(LQ,{label:a("video_tile.volume"),value:f,onValueChange:p,onValueCommit:u,min:0,max:1,step:.01})]})]})})},S={key:"video",name:a("common.video"),content:E.jsx(eD,{children:E.jsx(cI,{devices:l.videoInput,title:a("settings.devices.camera"),numberedLabel:C=>a("settings.devices.camera_numbered",{n:C})})})},b={key:"preferences",name:a("common.preferences"),content:E.jsx(Z8e,{})},w={key:"profile",name:a("common.profile"),content:E.jsx(M8e,{client:i})},k={key:"feedback",name:a("settings.feedback_tab_title"),content:E.jsx(N8e,{roomId:s})},R={key:"developer",name:a("settings.developer_tab_title"),content:E.jsx(D9e,{client:i,livekitRoom:o})},I=[g,S];return Ge===null&&I.push(w),I.push(b),v&&I.push(k),m&&I.push(R),E.jsx(lf,{title:a("common.settings"),className:Xj.settingsModal,open:n,onDismiss:e,tabbed:!0,children:E.jsx(d8e,{label:a("common.settings"),tab:t,onTabChange:r,tabs:I})})},j9e=(n,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("mask",{id:"path-1-inside-1_898_2641",fill:"white"},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z"})),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z",fill:"white"}),_.createElement("path",{d:"M17.1502 20.1214L17.9339 21.2814L17.1502 20.1214ZM4.4 19.8008L3.55919 20.9202H3.55919L4.4 19.8008ZM17.1197 17.3237L18.0934 18.3296L18.7717 17.6731L18.4173 16.7981L17.1197 17.3237ZM4.88028 17.3237L3.58268 16.7981L3.22829 17.6731L3.90659 18.3296L4.88028 17.3237ZM11 23.4C13.5662 23.4 15.9541 22.619 17.9339 21.2814L16.3665 18.9613C14.835 19.9959 12.9902 20.6 11 20.6V23.4ZM3.55919 20.9202C5.63176 22.477 8.21011 23.4 11 23.4V20.6C8.83723 20.6 6.84514 19.8865 5.24081 18.6814L3.55919 20.9202ZM-1.4 11C-1.4 15.0577 0.55052 18.6603 3.55919 20.9202L5.24081 18.6814C2.90591 16.9276 1.4 14.1399 1.4 11H-1.4ZM11 -1.4C4.15167 -1.4 -1.4 4.15167 -1.4 11H1.4C1.4 5.69807 5.69807 1.4 11 1.4V-1.4ZM23.4 11C23.4 4.15167 17.8483 -1.4 11 -1.4V1.4C16.3019 1.4 20.6 5.69807 20.6 11H23.4ZM17.9339 21.2814C21.2288 19.0554 23.4 15.2815 23.4 11H20.6C20.6 14.3124 18.9236 17.2337 16.3665 18.9613L17.9339 21.2814ZM12.9 7.975C12.9 9.28384 11.9459 10.15 11 10.15V12.95C13.6991 12.95 15.7 10.615 15.7 7.975H12.9ZM11 5.8C11.9459 5.8 12.9 6.66616 12.9 7.975H15.7C15.7 5.335 13.6991 3 11 3V5.8ZM9.1 7.975C9.1 6.66616 10.0541 5.8 11 5.8V3C8.30086 3 6.3 5.335 6.3 7.975H9.1ZM11 10.15C10.0541 10.15 9.1 9.28384 9.1 7.975H6.3C6.3 10.615 8.30086 12.95 11 12.95V10.15ZM16.146 16.3178C14.8129 17.6081 13.0004 18.4 11 18.4V21.2C13.756 21.2 16.2591 20.1051 18.0934 18.3296L16.146 16.3178ZM11 14.6C13.1797 14.6 15.0494 15.9415 15.8221 17.8493L18.4173 16.7981C17.2312 13.8697 14.359 11.8 11 11.8V14.6ZM6.17788 17.8493C6.95058 15.9415 8.8203 14.6 11 14.6V11.8C7.64102 11.8 4.7688 13.8697 3.58268 16.7981L6.17788 17.8493ZM11 18.4C8.99963 18.4 7.18709 17.6081 5.85397 16.3178L3.90659 18.3296C5.74088 20.1051 8.24402 21.2 11 21.2V18.4Z",fill:"white",mask:"url(#path-1-inside-1_898_2641)"})),nU=_.forwardRef(j9e),U9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.0988 9.01625C20.3188 9.59375 20.8825 9.97875 21.5013 9.97875C22.3263 9.97875 23 10.6525 23 11.4775V12.5225C23 13.3475 22.3263 14.0213 21.5013 14.0213C20.8825 14.0213 20.3188 14.4062 20.0988 14.9838C20.0806 15.0292 20.0624 15.0753 20.0441 15.1218C19.9792 15.2863 19.9125 15.4555 19.8375 15.6163C19.5763 16.18 19.7 16.84 20.14 17.28C20.7313 17.8575 20.7313 18.8062 20.14 19.3975L19.3975 20.14C18.82 20.7313 17.8713 20.7313 17.28 20.14C16.8538 19.7 16.18 19.5763 15.6163 19.8375C15.41 19.9338 15.2037 20.0163 14.9838 20.0988C14.4062 20.3188 14.0213 20.8825 14.0213 21.5013C14.0213 22.3263 13.3475 23 12.5225 23H11.4775C10.6525 23 9.97875 22.3263 9.97875 21.5013C9.97875 20.8825 9.59375 20.3188 9.01625 20.0988C8.97079 20.0806 8.92466 20.0624 8.87815 20.044C8.71368 19.9792 8.54454 19.9125 8.38375 19.8375C7.82 19.5763 7.16 19.7 6.72 20.14C6.1425 20.7313 5.19375 20.7313 4.6025 20.14L3.86 19.3975C3.26875 18.82 3.26875 17.8713 3.86 17.28C4.3 16.8538 4.42375 16.18 4.1625 15.6163C4.06625 15.41 3.98375 15.2037 3.90125 14.9838C3.68125 14.4062 3.1175 14.0213 2.49875 14.0213C1.67375 14.0213 1 13.3475 1 12.5225V11.4775C1 10.6525 1.67375 9.97875 2.49875 9.97875C3.1175 9.97875 3.68125 9.59375 3.90125 9.01625C3.94464 8.87742 3.99897 8.74406 4.0539 8.60926C4.086 8.53046 4.11831 8.45117 4.14875 8.37C4.41 7.80625 4.28625 7.14625 3.84625 6.70625C3.255 6.12875 3.255 5.18 3.84625 4.58875L4.6025 3.86C5.18 3.26875 6.12875 3.26875 6.72 3.86C7.14625 4.3 7.82 4.42375 8.38375 4.1625C8.59 4.06625 8.79625 3.97 9.01625 3.90125C9.59375 3.68125 9.97875 3.1175 9.97875 2.49875C9.97875 1.67375 10.6525 1 11.4775 1H12.5225C13.3475 1 14.0213 1.67375 14.0213 2.49875C14.0213 3.13125 14.4062 3.68125 14.9838 3.90125C15.0292 3.91943 15.0753 3.93762 15.1218 3.95595C15.2863 4.02079 15.4555 4.08746 15.6163 4.1625C16.18 4.42375 16.84 4.3 17.28 3.86C17.8575 3.26875 18.8062 3.26875 19.3975 3.86L20.14 4.6025C20.7313 5.18 20.7313 6.12875 20.14 6.72C19.7 7.14625 19.5763 7.82 19.8375 8.38375C19.9338 8.59 20.0163 8.79625 20.0988 9.01625ZM12 17.5C8.96125 17.5 6.5 15.0387 6.5 12C6.5 8.96125 8.96125 6.5 12 6.5C15.0387 6.5 17.5 8.96125 17.5 12C17.5 15.0387 15.0387 17.5 12 17.5Z",fill:"#ffffff"})),F9e=_.forwardRef(U9e),$9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.49966 2.38889C7.49966 1.89797 7.89763 1.5 8.38855 1.5H20.1108C20.6017 1.5 20.9997 1.89797 20.9997 2.38889V21.6111C20.9997 22.102 20.6017 22.5 20.1108 22.5H8.38855C7.89763 22.5 7.49966 22.102 7.49966 21.6111V12.6667H7.49089H7.4821H7.47331H7.46452H7.45573H7.44694H7.43815H7.42936H7.42057H7.41178H7.403H7.39421H7.38542H7.37663H7.36784H7.35905H7.35026H7.34147H7.33268H7.32389H7.3151H7.30632H7.29753H7.28874H7.27995H7.27116H7.26237H7.25358H7.24479H7.236H7.22721H7.21842H7.20964H7.20085H7.19206H7.18327H7.17448H7.16569H7.1569H7.14811H7.13932H7.13053H7.12175H7.11296H7.10417H7.09538H7.08659H7.0778H7.06901H7.06022H7.05143H7.04264H7.03385H7.02507H7.01628H7.00749H6.9987H6.98991H6.98112H6.97233H6.96354H6.95475H6.94596H6.93717H6.92839H6.9196H6.91081H6.90202H6.89323H6.88444H6.87565H6.86686H6.85807H6.84928H6.8405H6.83171H6.82292H6.81413H6.80534H6.79655H6.78776H6.77897H6.77018H6.76139H6.7526H6.74382H6.73503H6.72624H6.71745H6.70866H6.69987H6.69108H6.68229H6.6735H6.66471H6.65592H6.64714H6.63835H6.62956H6.62077H6.61198H6.60319H6.5944H6.58561H6.57682H6.56803H6.55925H6.55046H6.54167H6.53288H6.52409H6.5153H6.50651H6.49772H6.48893H6.48014H6.47135H6.46257H6.45378H6.44499H6.4362H6.42741H6.41862H6.40983H6.40104H6.39225H6.38346H6.37467H6.36589H6.3571H6.34831H6.33952H6.33073H6.32194H6.31315H6.30436H6.29557H6.28678H6.27799H6.26921H6.26042H6.25163H6.24284H6.23405H6.22526H6.21647H6.20768H6.19889H6.1901H6.18132H6.17253H6.16374H6.15495H6.14616H6.13737H6.12858H6.11979H6.111H6.10221H6.09342H6.08464H6.07585H6.06706H6.05827H6.04948H6.04069H6.0319H6.02311H6.01432H6.00553H5.99674H5.98796H5.97917H5.97038H5.96159H5.9528H5.94401H5.93522H5.92643H5.91764H5.90885H5.90007H5.89128H5.88249H5.8737H5.86491H5.85612H5.84733H5.83854H5.82975H5.82096H5.81217H5.80339H5.7946H5.78581H5.77702H5.76823H5.75944H5.75065H5.74186H5.73307H5.72428H5.71549H5.70671H5.69792H5.68913H5.68034H5.67155H5.66276H5.65397H5.64518H5.63639H5.6276H5.61882H5.61003H5.60124H5.59245H5.58366H5.57487H5.56608H5.55729H5.5485H5.53971H5.53092H5.52214H5.51335H5.50456H5.49577H5.48698H5.47819H5.4694H5.46061H5.45182H5.44303H5.43424H5.42546H5.41667H5.40788H5.39909H5.3903H5.38151H5.37272H5.36393H5.35514H5.34635H5.33757H5.32878H5.31999H5.3112H5.30241H5.29362H5.28483H5.27604H5.26725H5.25846H5.24967H5.24089H5.2321H5.22331H5.21452H5.20573H5.19694H5.18815H5.17936H5.17057H5.16178H5.15299H5.14421H5.13542H5.12663H5.11784H5.10905H5.10026H5.09147H5.08268H5.07389H5.0651H5.05632H5.04753H5.03874H5.02995H5.02116H5.01237H5.00358H4.99479H4.986H4.97721H4.96842H4.95964H4.95085H4.94206H4.93327H4.92448H4.91569H4.9069H4.89811H4.88932H4.88053H4.87174H4.86296H4.85417H4.84538H4.83659H4.8278H4.81901H4.81022H4.80143H4.79264H4.78385H4.77507H4.76628H4.75749H4.7487H4.73991H4.73112H4.72233H4.71354H4.70475H4.69596H4.68717H4.67839H4.6696H4.66081H4.65202H4.64323H4.63444H4.62565H4.61686H4.60807H4.59928H4.59049H4.58171H4.57292H4.56413H4.55534H4.54655H4.53776H4.52897H4.52018H4.51139H4.5026H4.49382H4.48503H4.47624H4.46745H4.45866H4.44987H4.44108H4.43229H4.4235H4.41471H4.40592H4.39714H4.38835H4.37956H4.37077H4.36198H4.35319H4.3444H4.33561H4.32682H4.31803H4.30924H4.30046H4.29167H4.28288H4.27409H4.2653H4.25651H4.24772H4.23893H4.23014H4.22135H4.21257H4.20378H4.19499H4.1862H4.17741H4.16862H4.15983H4.15104H4.14225H4.13346H4.12467H4.11589H4.1071H4.09831H4.08952H4.08073H4.07194H4.06315H4.05436H4.04557H4.03678H4.02799H4.01921H4.01042H4.00163H3.99284H3.98405H3.97526H3.96647H3.95768H3.94889H3.9401H3.93132H3.92253H3.91374H3.90495H3.89616H3.88737H3.87858H3.86979H3.861H3.85221H3.84342H3.83464H3.82585H3.81706H3.80827H3.79948H3.79069H3.7819H3.77311H3.76432H3.75553H3.74674H3.73796H3.72917H3.72038H3.71159H3.7028H3.69401H3.68522H3.67643H3.66764H3.65885H3.65007H3.64128H3.63249H3.6237H3.61491H3.60612H3.59733H3.58854H3.57975H3.57096H3.56217H3.55339H3.5446H3.53581H3.52702H3.51823H3.50944H3.50065H3.49186H3.48307H3.47428H3.46549H3.45671H3.44792H3.43913H3.43034H3.42155H3.41276H3.40397H3.39518H3.38639H3.3776H3.36882H3.36003H3.35124H3.34245H3.33366H3.32487H3.31608H3.30729H3.2985H3.28971H3.28092H3.27214H3.26335H3.25456H3.24577H3.23698H3.22819H3.2194H3.21061H3.20182H3.19303H3.18424H3.17546H3.16667H3.15788H3.14909H3.1403H3.13151H3.12272H3.11393H3.10514H3.09635H3.08757H3.07878H3.06999H3.0612H3.05241H3.04362H3.03483H3.02604H3.01725H3.00846H2.99967C2.63148 12.6667 2.33301 12.3682 2.33301 12C2.33301 11.6318 2.63148 11.3333 2.99967 11.3333H3.00846H3.01725H3.02604H3.03483H3.04362H3.05241H3.0612H3.06999H3.07878H3.08757H3.09635H3.10514H3.11393H3.12272H3.13151H3.1403H3.14909H3.15788H3.16667H3.17546H3.18424H3.19303H3.20182H3.21061H3.2194H3.22819H3.23698H3.24577H3.25456H3.26335H3.27214H3.28092H3.28971H3.2985H3.30729H3.31608H3.32487H3.33366H3.34245H3.35124H3.36003H3.36882H3.3776H3.38639H3.39518H3.40397H3.41276H3.42155H3.43034H3.43913H3.44792H3.45671H3.46549H3.47428H3.48307H3.49186H3.50065H3.50944H3.51823H3.52702H3.53581H3.5446H3.55339H3.56217H3.57096H3.57975H3.58854H3.59733H3.60612H3.61491H3.6237H3.63249H3.64128H3.65007H3.65885H3.66764H3.67643H3.68522H3.69401H3.7028H3.71159H3.72038H3.72917H3.73796H3.74674H3.75553H3.76432H3.77311H3.7819H3.79069H3.79948H3.80827H3.81706H3.82585H3.83464H3.84342H3.85221H3.861H3.86979H3.87858H3.88737H3.89616H3.90495H3.91374H3.92253H3.93132H3.9401H3.94889H3.95768H3.96647H3.97526H3.98405H3.99284H4.00163H4.01042H4.01921H4.02799H4.03678H4.04557H4.05436H4.06315H4.07194H4.08073H4.08952H4.09831H4.1071H4.11589H4.12467H4.13346H4.14225H4.15104H4.15983H4.16862H4.17741H4.1862H4.19499H4.20378H4.21257H4.22135H4.23014H4.23893H4.24772H4.25651H4.2653H4.27409H4.28288H4.29167H4.30046H4.30924H4.31803H4.32682H4.33561H4.3444H4.35319H4.36198H4.37077H4.37956H4.38835H4.39714H4.40592H4.41471H4.4235H4.43229H4.44108H4.44987H4.45866H4.46745H4.47624H4.48503H4.49382H4.5026H4.51139H4.52018H4.52897H4.53776H4.54655H4.55534H4.56413H4.57292H4.58171H4.59049H4.59928H4.60807H4.61686H4.62565H4.63444H4.64323H4.65202H4.66081H4.6696H4.67839H4.68717H4.69596H4.70475H4.71354H4.72233H4.73112H4.73991H4.7487H4.75749H4.76628H4.77507H4.78385H4.79264H4.80143H4.81022H4.81901H4.8278H4.83659H4.84538H4.85417H4.86296H4.87174H4.88053H4.88932H4.89811H4.9069H4.91569H4.92448H4.93327H4.94206H4.95085H4.95964H4.96842H4.97721H4.986H4.99479H5.00358H5.01237H5.02116H5.02995H5.03874H5.04753H5.05631H5.0651H5.07389H5.08268H5.09147H5.10026H5.10905H5.11784H5.12663H5.13542H5.14421H5.15299H5.16178H5.17057H5.17936H5.18815H5.19694H5.20573H5.21452H5.22331H5.2321H5.24089H5.24967H5.25846H5.26725H5.27604H5.28483H5.29362H5.30241H5.3112H5.31999H5.32878H5.33757H5.34635H5.35514H5.36393H5.37272H5.38151H5.3903H5.39909H5.40788H5.41667H5.42546H5.43424H5.44303H5.45182H5.46061H5.4694H5.47819H5.48698H5.49577H5.50456H5.51335H5.52214H5.53092H5.53971H5.5485H5.55729H5.56608H5.57487H5.58366H5.59245H5.60124H5.61003H5.61882H5.6276H5.63639H5.64518H5.65397H5.66276H5.67155H5.68034H5.68913H5.69792H5.70671H5.71549H5.72428H5.73307H5.74186H5.75065H5.75944H5.76823H5.77702H5.78581H5.7946H5.80339H5.81217H5.82096H5.82975H5.83854H5.84733H5.85612H5.86491H5.8737H5.88249H5.89128H5.90007H5.90885H5.91764H5.92643H5.93522H5.94401H5.9528H5.96159H5.97038H5.97917H5.98796H5.99674H6.00553H6.01432H6.02311H6.0319H6.04069H6.04948H6.05827H6.06706H6.07585H6.08464H6.09342H6.10221H6.111H6.11979H6.12858H6.13737H6.14616H6.15495H6.16374H6.17253H6.18132H6.1901H6.19889H6.20768H6.21647H6.22526H6.23405H6.24284H6.25163H6.26042H6.26921H6.27799H6.28678H6.29557H6.30436H6.31315H6.32194H6.33073H6.33952H6.34831H6.3571H6.36589H6.37467H6.38346H6.39225H6.40104H6.40983H6.41862H6.42741H6.4362H6.44499H6.45378H6.46257H6.47135H6.48014H6.48893H6.49772H6.50651H6.5153H6.52409H6.53288H6.54167H6.55046H6.55925H6.56803H6.57682H6.58561H6.5944H6.60319H6.61198H6.62077H6.62956H6.63835H6.64714H6.65592H6.66471H6.6735H6.68229H6.69108H6.69987H6.70866H6.71745H6.72624H6.73503H6.74382H6.7526H6.76139H6.77018H6.77897H6.78776H6.79655H6.80534H6.81413H6.82292H6.83171H6.8405H6.84928H6.85807H6.86686H6.87565H6.88444H6.89323H6.90202H6.91081H6.9196H6.92839H6.93717H6.94596H6.95475H6.96354H6.97233H6.98112H6.98991H6.9987H7.00749H7.01628H7.02507H7.03385H7.04264H7.05143H7.06022H7.06901H7.0778H7.08659H7.09538H7.10417H7.11296H7.12175H7.13053H7.13932H7.14811H7.1569H7.16569H7.17448H7.18327H7.19206H7.20085H7.20964H7.21842H7.22721H7.236H7.24479H7.25358H7.26237H7.27116H7.27995H7.28874H7.29753H7.30632H7.3151H7.32389H7.33268H7.34147H7.35026H7.35905H7.36784H7.37663H7.38542H7.39421H7.403H7.41178H7.42057H7.42936H7.43815H7.44694H7.45573H7.46452H7.47331H7.4821H7.49089H7.49966V2.38889ZM13.3687 6.24853C13.1172 5.9796 12.7095 5.9796 12.458 6.24853C12.2065 6.51747 12.2065 6.9535 12.458 7.22243L16.3022 11.3336L16.2894 11.3336L16.2726 11.3336L16.2558 11.3336L16.239 11.3335L16.2223 11.3335L16.2055 11.3335L16.1887 11.3335L16.1719 11.3335L16.1552 11.3334L16.1384 11.3334L16.1216 11.3334L16.1048 11.3334L16.088 11.3334L16.0713 11.3333L16.0545 11.3333L16.0377 11.3333L16.0209 11.3333L16.0041 11.3333L15.9874 11.3332L15.9706 11.3332L15.9538 11.3332L15.937 11.3332L15.9202 11.3332L15.9035 11.3331L15.8867 11.3331L15.8699 11.3331L15.8531 11.3331L15.8364 11.3331L15.8196 11.333L15.8028 11.333L15.786 11.333L15.7692 11.333L15.7525 11.333L15.7357 11.3329L15.7189 11.3329L15.7021 11.3329L15.6853 11.3329L15.6686 11.3329L15.6518 11.3328L15.635 11.3328L15.6182 11.3328L15.6014 11.3328L15.5847 11.3328L15.5679 11.3327L15.5511 11.3327L15.5343 11.3327L15.5175 11.3327L15.5008 11.3327L15.484 11.3326L15.4672 11.3326L15.4504 11.3326L15.4337 11.3326L15.4169 11.3326L15.4001 11.3325L15.3833 11.3325L15.3665 11.3325L15.3498 11.3325L15.333 11.3324L15.3162 11.3324L15.2994 11.3324L15.2826 11.3324L15.2659 11.3324L15.2491 11.3323L15.2323 11.3323L15.2155 11.3323L15.1987 11.3323L15.182 11.3323L15.1652 11.3322L15.1484 11.3322L15.1316 11.3322L15.1148 11.3322L15.0981 11.3322L15.0813 11.3321L15.0645 11.3321L15.0477 11.3321L15.031 11.3321L15.0142 11.3321L14.9974 11.332L14.9806 11.332L14.9638 11.332L14.9471 11.332L14.9303 11.332L14.9135 11.3319L14.8967 11.3319L14.8799 11.3319L14.8632 11.3319L14.8464 11.3319L14.8296 11.3318L14.8128 11.3318L14.796 11.3318L14.7793 11.3318L14.7625 11.3318L14.7457 11.3317L14.7289 11.3317L14.7122 11.3317L14.6954 11.3317L14.6786 11.3317L14.6618 11.3316L14.645 11.3316L14.6283 11.3316L14.6115 11.3316L14.5947 11.3316L14.5779 11.3315L14.5611 11.3315L14.5444 11.3315L14.5276 11.3315L14.5108 11.3315L14.494 11.3314L14.4772 11.3314L14.4605 11.3314L14.4437 11.3314L14.4269 11.3314L14.4101 11.3313L14.3933 11.3313L14.3766 11.3313L14.3598 11.3313L14.343 11.3313L14.3262 11.3312L14.3095 11.3312L14.2927 11.3312L14.2759 11.3312L14.2591 11.3312L14.2423 11.3311L14.2256 11.3311L14.2088 11.3311L14.192 11.3311L14.1752 11.3311L14.1584 11.331L14.1417 11.331L14.1249 11.331L14.1081 11.331L14.0913 11.331L14.0745 11.3309L14.0578 11.3309L14.041 11.3309L14.0242 11.3309L14.0074 11.3309L13.9906 11.3308L13.9739 11.3308L13.9571 11.3308L13.9403 11.3308L13.9235 11.3308L13.9068 11.3307L13.89 11.3307L13.8732 11.3307L13.8564 11.3307L13.8396 11.3307L13.8229 11.3306L13.8061 11.3306L13.7893 11.3306L13.7725 11.3306L13.7557 11.3306L13.739 11.3305L13.7222 11.3305L13.7054 11.3305L13.6886 11.3305L13.6718 11.3305L13.6551 11.3304L13.6383 11.3304L13.6215 11.3304L13.6047 11.3304L13.5879 11.3304L13.5712 11.3303L13.5544 11.3303L13.5376 11.3303L13.5208 11.3303L13.5041 11.3303L13.4873 11.3302L13.4705 11.3302L13.4537 11.3302L13.4369 11.3302L13.4202 11.3302L13.4034 11.3301L13.3866 11.3301L13.3698 11.3301L13.353 11.3301L13.3363 11.33L13.3195 11.33L13.3027 11.33L13.2859 11.33L13.2691 11.33L13.2524 11.3299L13.2356 11.3299L13.2188 11.3299L13.202 11.3299L13.1853 11.3299L13.1685 11.3298L13.1517 11.3298L13.1349 11.3298L13.1181 11.3298L13.1014 11.3298L13.0846 11.3297L13.0678 11.3297L13.051 11.3297L13.0342 11.3297L13.0175 11.3297L13.0007 11.3296L12.9839 11.3296L12.9671 11.3296L12.9503 11.3296L12.9336 11.3296L12.9168 11.3295L12.9 11.3295L12.8832 11.3295L12.8664 11.3295L12.8497 11.3295L12.8329 11.3294L12.8161 11.3294L12.7993 11.3294L12.7826 11.3294L12.7658 11.3294L12.749 11.3293L12.7322 11.3293L12.7154 11.3293L12.6987 11.3293L12.6819 11.3293L12.6651 11.3292L12.6483 11.3292L12.6315 11.3292L12.6148 11.3292L12.598 11.3292L12.5812 11.3291L12.5644 11.3291L12.5476 11.3291L12.5309 11.3291L12.5141 11.3291L12.4973 11.329L12.4805 11.329L12.4637 11.329L12.447 11.329L12.4302 11.329L12.4134 11.3289L12.3966 11.3289L12.3799 11.3289L12.3631 11.3289L12.3463 11.3289L12.3295 11.3288L12.3127 11.3288L12.296 11.3288L12.2792 11.3288L12.2624 11.3288L12.2456 11.3287L12.2288 11.3287L12.2121 11.3287L12.1953 11.3287L12.1785 11.3287L12.1617 11.3286L12.1449 11.3286L12.1282 11.3286L12.1114 11.3286L12.0946 11.3286L12.0778 11.3285L12.0611 11.3285L12.0443 11.3285L12.0275 11.3285L12.0107 11.3285L11.9939 11.3284L11.9772 11.3284L11.9604 11.3284L11.9436 11.3284L11.9268 11.3284L11.91 11.3283L11.8933 11.3283L11.8765 11.3283L11.8597 11.3283L11.8429 11.3283L11.8261 11.3282L11.8094 11.3282L11.7926 11.3282L11.7758 11.3282L11.759 11.3282L11.7422 11.3281L11.7255 11.3281L11.7087 11.3281L11.6919 11.3281L11.6751 11.3281L11.6583 11.328L11.6416 11.328L11.6248 11.328L11.608 11.328L11.5912 11.328L11.5745 11.3279L11.5577 11.3279L11.5409 11.3279L11.5241 11.3279L11.5073 11.3279L11.4906 11.3278L11.4738 11.3278L11.457 11.3278L11.4402 11.3278L11.4234 11.3278L11.4067 11.3277L11.3899 11.3277L11.3731 11.3277L11.3563 11.3277L11.3395 11.3277L11.3228 11.3276L11.306 11.3276L11.2892 11.3276L11.2724 11.3276L11.2557 11.3275L11.2389 11.3275L11.2221 11.3275L11.2053 11.3275L11.1885 11.3275L11.1718 11.3274L11.155 11.3274L11.1382 11.3274L11.1214 11.3274L11.1046 11.3274L11.0879 11.3273L11.0711 11.3273L11.0543 11.3273L11.0375 11.3273L11.0207 11.3273L11.004 11.3272L10.9872 11.3272L10.9704 11.3272L10.9536 11.3272L10.9368 11.3272L10.9201 11.3271L10.9033 11.3271L10.8865 11.3271L10.8697 11.3271L10.853 11.3271L10.8362 11.327L10.8194 11.327L10.8026 11.327L10.7858 11.327L10.7691 11.327L10.7523 11.3269L10.7355 11.3269L10.7187 11.3269L10.7019 11.3269L10.6852 11.3269L10.6684 11.3268L10.6516 11.3268L10.6348 11.3268L10.618 11.3268L10.6013 11.3268L10.5845 11.3267L10.5677 11.3267L10.5509 11.3267L10.5341 11.3267L10.5174 11.3267L10.5006 11.3266L10.4838 11.3266L10.467 11.3266L10.4503 11.3266L10.4335 11.3266L10.4167 11.3265L10.3999 11.3265L10.3831 11.3265L10.3664 11.3265L10.3496 11.3265L10.3328 11.3264L10.316 11.3264L10.2992 11.3264L10.2825 11.3264L10.2657 11.3264L10.2489 11.3263L10.2321 11.3263L10.2153 11.3263L10.1986 11.3263L10.1818 11.3263L10.165 11.3262L10.1482 11.3262L10.1315 11.3262L10.1147 11.3262L10.0979 11.3262L10.0811 11.3261L10.0643 11.3261L10.0476 11.3261L10.0308 11.3261L10.014 11.3261L9.99722 11.326L9.98044 11.326L9.96366 11.326L9.94688 11.326L9.9301 11.326L9.91332 11.3259L9.89654 11.3259L9.87977 11.3259L9.86299 11.3259L9.84621 11.3259L9.82943 11.3258L9.81265 11.3258L9.79587 11.3258L9.77909 11.3258L9.76231 11.3258L9.74553 11.3257L9.72875 11.3257L9.71197 11.3257L9.69519 11.3257L9.67841 11.3257L9.66163 11.3256L9.64486 11.3256L9.62808 11.3256L9.6113 11.3256L9.59452 11.3256L9.57774 11.3255L9.56096 11.3255L9.54418 11.3255L9.5274 11.3255L9.51062 11.3255L9.49384 11.3254L9.47706 11.3254L9.46029 11.3254L9.44351 11.3254L9.42673 11.3254L9.40995 11.3253L9.39317 11.3253L9.37639 11.3253L9.35961 11.3253L9.34283 11.3253L9.32605 11.3252L9.30927 11.3252L9.29249 11.3252L9.27572 11.3252L9.25894 11.3252L9.24216 11.3251L9.22538 11.3251L9.2086 11.3251L9.19182 11.3251L9.17504 11.325L9.15826 11.325L9.14148 11.325L9.1247 11.325L9.10792 11.325L9.09115 11.3249L9.07437 11.3249L9.05759 11.3249L9.04081 11.3249L9.02403 11.3249L9.00725 11.3248L8.99047 11.3248L8.97369 11.3248L8.95691 11.3248L8.94013 11.3248L8.92335 11.3247L8.90658 11.3247L8.8898 11.3247L8.87302 11.3247L8.85624 11.3247L8.83946 11.3246L8.82268 11.3246L8.8059 11.3246L8.78912 11.3246L8.77234 11.3246L8.75556 11.3245L8.73878 11.3245L8.722 11.3245L8.70523 11.3245L8.68845 11.3245L8.67167 11.3244L8.65489 11.3244L8.63811 11.3244L8.62133 11.3244L8.60455 11.3244L8.58777 11.3243L8.57099 11.3243L8.55421 11.3243L8.53743 11.3243L8.52066 11.3243L8.50388 11.3242L8.4871 11.3242L8.47032 11.3242L8.45354 11.3242L8.43676 11.3242L8.41998 11.3241L8.4032 11.3241L8.38642 11.3241L8.36964 11.3241L8.35286 11.3241L8.33608 11.324L8.31931 11.324L8.30253 11.324L8.28575 11.324L8.26897 11.324L8.25219 11.3239L8.23541 11.3239L8.21863 11.3239L8.20185 11.3239L8.18507 11.3239L8.16829 11.3238L8.15151 11.3238L8.13474 11.3238L8.11796 11.3238L8.10118 11.3238L8.0844 11.3237L8.06762 11.3237L8.05084 11.3237L8.03406 11.3237L8.01728 11.3237L8.0005 11.3236L7.99885 12.657L8.01563 12.657L8.03241 12.657L8.04919 12.657L8.06597 12.6571L8.08274 12.6571L8.09952 12.6571L8.1163 12.6571L8.13308 12.6571L8.14986 12.6572L8.16664 12.6572L8.18342 12.6572L8.2002 12.6572L8.21698 12.6572L8.23376 12.6573L8.25054 12.6573L8.26731 12.6573L8.28409 12.6573L8.30087 12.6573L8.31765 12.6574L8.33443 12.6574L8.35121 12.6574L8.36799 12.6574L8.38477 12.6574L8.40155 12.6575L8.41833 12.6575L8.43511 12.6575L8.45189 12.6575L8.46866 12.6575L8.48544 12.6576L8.50222 12.6576L8.519 12.6576L8.53578 12.6576L8.55256 12.6576L8.56934 12.6577L8.58612 12.6577L8.6029 12.6577L8.61968 12.6577L8.63646 12.6577L8.65323 12.6578L8.67001 12.6578L8.68679 12.6578L8.70357 12.6578L8.72035 12.6578L8.73713 12.6579L8.75391 12.6579L8.77069 12.6579L8.78747 12.6579L8.80425 12.6579L8.82103 12.658L8.83781 12.658L8.85458 12.658L8.87136 12.658L8.88814 12.658L8.90492 12.6581L8.9217 12.6581L8.93848 12.6581L8.95526 12.6581L8.97204 12.6581L8.98882 12.6582L9.0056 12.6582L9.02238 12.6582L9.03915 12.6582L9.05593 12.6582L9.07271 12.6583L9.08949 12.6583L9.10627 12.6583L9.12305 12.6583L9.13983 12.6583L9.15661 12.6584L9.17339 12.6584L9.19017 12.6584L9.20695 12.6584L9.22373 12.6584L9.2405 12.6585L9.25728 12.6585L9.27406 12.6585L9.29084 12.6585L9.30762 12.6585L9.3244 12.6586L9.34118 12.6586L9.35796 12.6586L9.37474 12.6586L9.39152 12.6586L9.4083 12.6587L9.42507 12.6587L9.44185 12.6587L9.45863 12.6587L9.47541 12.6587L9.49219 12.6588L9.50897 12.6588L9.52575 12.6588L9.54253 12.6588L9.55931 12.6588L9.57609 12.6589L9.59287 12.6589L9.60964 12.6589L9.62642 12.6589L9.6432 12.6589L9.65998 12.659L9.67676 12.659L9.69354 12.659L9.71032 12.659L9.7271 12.659L9.74388 12.6591L9.76066 12.6591L9.77744 12.6591L9.79421 12.6591L9.81099 12.6591L9.82777 12.6592L9.84455 12.6592L9.86133 12.6592L9.87811 12.6592L9.89489 12.6592L9.91167 12.6593L9.92845 12.6593L9.94523 12.6593L9.96201 12.6593L9.97879 12.6594L9.99556 12.6594L10.0123 12.6594L10.0291 12.6594L10.0459 12.6594L10.0627 12.6595L10.0795 12.6595L10.0962 12.6595L10.113 12.6595L10.1298 12.6595L10.1466 12.6596L10.1634 12.6596L10.1801 12.6596L10.1969 12.6596L10.2137 12.6596L10.2305 12.6597L10.2473 12.6597L10.264 12.6597L10.2808 12.6597L10.2976 12.6597L10.3144 12.6598L10.3311 12.6598L10.3479 12.6598L10.3647 12.6598L10.3815 12.6598L10.3983 12.6599L10.415 12.6599L10.4318 12.6599L10.4486 12.6599L10.4654 12.6599L10.4822 12.66L10.4989 12.66L10.5157 12.66L10.5325 12.66L10.5493 12.66L10.5661 12.6601L10.5828 12.6601L10.5996 12.6601L10.6164 12.6601L10.6332 12.6601L10.65 12.6602L10.6667 12.6602L10.6835 12.6602L10.7003 12.6602L10.7171 12.6602L10.7338 12.6603L10.7506 12.6603L10.7674 12.6603L10.7842 12.6603L10.801 12.6603L10.8177 12.6604L10.8345 12.6604L10.8513 12.6604L10.8681 12.6604L10.8849 12.6604L10.9016 12.6605L10.9184 12.6605L10.9352 12.6605L10.952 12.6605L10.9688 12.6605L10.9855 12.6606L11.0023 12.6606L11.0191 12.6606L11.0359 12.6606L11.0526 12.6606L11.0694 12.6607L11.0862 12.6607L11.103 12.6607L11.1198 12.6607L11.1365 12.6607L11.1533 12.6608L11.1701 12.6608L11.1869 12.6608L11.2037 12.6608L11.2204 12.6608L11.2372 12.6609L11.254 12.6609L11.2708 12.6609L11.2876 12.6609L11.3043 12.6609L11.3211 12.661L11.3379 12.661L11.3547 12.661L11.3715 12.661L11.3882 12.661L11.405 12.6611L11.4218 12.6611L11.4386 12.6611L11.4553 12.6611L11.4721 12.6611L11.4889 12.6612L11.5057 12.6612L11.5225 12.6612L11.5392 12.6612L11.556 12.6612L11.5728 12.6613L11.5896 12.6613L11.6064 12.6613L11.6231 12.6613L11.6399 12.6613L11.6567 12.6614L11.6735 12.6614L11.6903 12.6614L11.707 12.6614L11.7238 12.6614L11.7406 12.6615L11.7574 12.6615L11.7742 12.6615L11.7909 12.6615L11.8077 12.6615L11.8245 12.6616L11.8413 12.6616L11.858 12.6616L11.8748 12.6616L11.8916 12.6616L11.9084 12.6617L11.9252 12.6617L11.9419 12.6617L11.9587 12.6617L11.9755 12.6617L11.9923 12.6618L12.0091 12.6618L12.0258 12.6618L12.0426 12.6618L12.0594 12.6618L12.0762 12.6619L12.093 12.6619L12.1097 12.6619L12.1265 12.6619L12.1433 12.662L12.1601 12.662L12.1768 12.662L12.1936 12.662L12.2104 12.662L12.2272 12.6621L12.244 12.6621L12.2607 12.6621L12.2775 12.6621L12.2943 12.6621L12.3111 12.6622L12.3279 12.6622L12.3446 12.6622L12.3614 12.6622L12.3782 12.6622L12.395 12.6623L12.4118 12.6623L12.4285 12.6623L12.4453 12.6623L12.4621 12.6623L12.4789 12.6624L12.4957 12.6624L12.5124 12.6624L12.5292 12.6624L12.546 12.6624L12.5628 12.6625L12.5795 12.6625L12.5963 12.6625L12.6131 12.6625L12.6299 12.6625L12.6467 12.6626L12.6634 12.6626L12.6802 12.6626L12.697 12.6626L12.7138 12.6626L12.7306 12.6627L12.7473 12.6627L12.7641 12.6627L12.7809 12.6627L12.7977 12.6627L12.8145 12.6628L12.8312 12.6628L12.848 12.6628L12.8648 12.6628L12.8816 12.6628L12.8984 12.6629L12.9151 12.6629L12.9319 12.6629L12.9487 12.6629L12.9655 12.6629L12.9822 12.663L12.999 12.663L13.0158 12.663L13.0326 12.663L13.0494 12.663L13.0661 12.6631L13.0829 12.6631L13.0997 12.6631L13.1165 12.6631L13.1333 12.6631L13.15 12.6632L13.1668 12.6632L13.1836 12.6632L13.2004 12.6632L13.2172 12.6632L13.2339 12.6633L13.2507 12.6633L13.2675 12.6633L13.2843 12.6633L13.3011 12.6633L13.3178 12.6634L13.3346 12.6634L13.3514 12.6634L13.3682 12.6634L13.3849 12.6634L13.4017 12.6635L13.4185 12.6635L13.4353 12.6635L13.4521 12.6635L13.4688 12.6635L13.4856 12.6636L13.5024 12.6636L13.5192 12.6636L13.536 12.6636L13.5527 12.6636L13.5695 12.6637L13.5863 12.6637L13.6031 12.6637L13.6199 12.6637L13.6366 12.6637L13.6534 12.6638L13.6702 12.6638L13.687 12.6638L13.7038 12.6638L13.7205 12.6638L13.7373 12.6639L13.7541 12.6639L13.7709 12.6639L13.7876 12.6639L13.8044 12.6639L13.8212 12.664L13.838 12.664L13.8548 12.664L13.8715 12.664L13.8883 12.664L13.9051 12.6641L13.9219 12.6641L13.9387 12.6641L13.9554 12.6641L13.9722 12.6641L13.989 12.6642L14.0058 12.6642L14.0226 12.6642L14.0393 12.6642L14.0561 12.6642L14.0729 12.6643L14.0897 12.6643L14.1064 12.6643L14.1232 12.6643L14.14 12.6644L14.1568 12.6644L14.1736 12.6644L14.1903 12.6644L14.2071 12.6644L14.2239 12.6645L14.2407 12.6645L14.2575 12.6645L14.2742 12.6645L14.291 12.6645L14.3078 12.6646L14.3246 12.6646L14.3414 12.6646L14.3581 12.6646L14.3749 12.6646L14.3917 12.6647L14.4085 12.6647L14.4253 12.6647L14.442 12.6647L14.4588 12.6647L14.4756 12.6648L14.4924 12.6648L14.5091 12.6648L14.5259 12.6648L14.5427 12.6648L14.5595 12.6649L14.5763 12.6649L14.593 12.6649L14.6098 12.6649L14.6266 12.6649L14.6434 12.665L14.6602 12.665L14.6769 12.665L14.6937 12.665L14.7105 12.665L14.7273 12.6651L14.7441 12.6651L14.7608 12.6651L14.7776 12.6651L14.7944 12.6651L14.8112 12.6652L14.828 12.6652L14.8447 12.6652L14.8615 12.6652L14.8783 12.6652L14.8951 12.6653L14.9118 12.6653L14.9286 12.6653L14.9454 12.6653L14.9622 12.6653L14.979 12.6654L14.9957 12.6654L15.0125 12.6654L15.0293 12.6654L15.0461 12.6654L15.0629 12.6655L15.0796 12.6655L15.0964 12.6655L15.1132 12.6655L15.13 12.6655L15.1468 12.6656L15.1635 12.6656L15.1803 12.6656L15.1971 12.6656L15.2139 12.6656L15.2306 12.6657L15.2474 12.6657L15.2642 12.6657L15.281 12.6657L15.2978 12.6657L15.3145 12.6658L15.3313 12.6658L15.3481 12.6658L15.3649 12.6658L15.3817 12.6658L15.3984 12.6659L15.4152 12.6659L15.432 12.6659L15.4488 12.6659L15.4656 12.6659L15.4823 12.666L15.4991 12.666L15.5159 12.666L15.5327 12.666L15.5495 12.666L15.5662 12.6661L15.583 12.6661L15.5998 12.6661L15.6166 12.6661L15.6333 12.6661L15.6501 12.6662L15.6669 12.6662L15.6837 12.6662L15.7005 12.6662L15.7172 12.6662L15.734 12.6663L15.7508 12.6663L15.7676 12.6663L15.7844 12.6663L15.8011 12.6663L15.8179 12.6664L15.8347 12.6664L15.8515 12.6664L15.8683 12.6664L15.885 12.6664L15.9018 12.6665L15.9186 12.6665L15.9354 12.6665L15.9522 12.6665L15.9689 12.6665L15.9857 12.6666L16.0025 12.6666L16.0193 12.6666L16.036 12.6666L16.0528 12.6666L16.0696 12.6667L16.0864 12.6667L16.1032 12.6667L16.1199 12.6667L16.1367 12.6667L16.1535 12.6668L16.1703 12.6668L16.1871 12.6668L16.2038 12.6668L16.2206 12.6669L16.2374 12.6669L16.2542 12.6669L16.271 12.6669L16.2836 12.6669L12.458 16.7581C12.2065 17.0271 12.2065 17.4631 12.458 17.732C12.7095 18.001 13.1172 18.001 13.3687 17.732L18.2822 12.4772C18.5337 12.2083 18.5337 11.7723 18.2822 11.5033L13.3687 6.24853Z",fill:"white"})),H9e=_.forwardRef($9e),B9e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M18.2139 2.44646L12 3.99992H5.4375C4.64359 3.99992 4 4.64352 4 5.43742V18.5624C4 19.3563 4.64359 19.9999 5.4375 19.9999H12L18.2139 21.5534C19.1211 21.7802 20 21.094 20 20.1588V3.84104C20 2.90584 19.1211 2.21964 18.2139 2.44646ZM12 17.9999V5.99992H6V17.9999H12Z",fill:"white"})),V9e=_.forwardRef(B9e),q9e="_userButton_t5z8t_15",K9e={userButton:q9e},G9e=({preventNavigation:n,isAuthenticated:e,isPasswordlessUser:t,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=ze(),l=ci(),c=_.useMemo(()=>{const p=[];return e&&(p.push({key:"user",icon:nU,label:i,dataTestid:"usermenu_user"}),p.push({key:"settings",icon:F9e,label:a("common.settings")}),t&&!n&&p.push({key:"login",label:a("action.sign_in"),icon:H9e,dataTestid:"usermenu_login"}),!t&&!n&&p.push({key:"logout",label:a("action.sign_out"),icon:V9e,dataTestid:"usermenu_logout"})),p},[e,t,i,n,a]),[u,f]=_.useState(!1);return e?E.jsx(D6,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:u,onOpenChange:f,trigger:E.jsx("button",{"aria-label":a("common.profile"),className:K9e.userButton,"data-testid":"usermenu_open",children:e&&(!t||s)?E.jsx(Zp,{id:r,name:i,size:Xp.SM,src:s}):E.jsx(nU,{})}),children:c.map(({key:p,icon:m,label:v,dataTestid:g})=>E.jsx(Sp,{Icon:m,label:v,"data-test-id":g,onSelect:()=>o(p)},p))}):E.jsx(R4,{to:{pathname:"/login"},state:{from:l},children:a("log_in")})},N4=({preventNavigation:n=!1})=>{const e=ci(),t=Na(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=x4(),{displayName:a,avatarUrl:l}=Jy(r),[c,u]=_.useState(!1),f=_.useCallback(()=>u(!1),[u]),[p,m]=_.useState(M4),v=_.useCallback(S=>{var b;switch(S){case"user":m("profile"),u(!0);break;case"settings":m("audio"),u(!0);break;case"logout":i==null||i();break;case"login":(b=t("/login",{state:{from:e}}))==null||b.catch(w=>A.error("Failed to navigate to login",w));break}},[t,e,i,u]),g=(r==null?void 0:r.getUserIdLocalpart())??"";return E.jsxs(E.Fragment,{children:[E.jsx(G9e,{preventNavigation:n,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:l,onAction:v,userId:(r==null?void 0:r.getUserId())??"",displayName:a||(g?g.replace("@",""):"")}),r&&E.jsx(A4,{client:r,open:c,onDismiss:f,tab:p,onTabChange:m})]})};function W9e(n){return new Worker(""+new URL("IndexedDBWorker-Cs0-RLNE.js",import.meta.url).href,{name:n==null?void 0:n.name})}const Mb=new LP,z9e=n=>{const[e,t]=_.useState(()=>localStorage.getItem(n));return _.useEffect(()=>(Mb.on(n,t),()=>{Mb.off(n,t)}),[n,t]),[e,_.useCallback(r=>{t(r),localStorage.setItem(n,r),Mb.emit(n,r)},[n,t])]},Y9e=(n,e)=>{localStorage.setItem(n,e),Mb.emit(n,e)};function OQ(n,e){Y9e(D4(n),e)}const D4=n=>`room-shared-key-${n}`,J9e=n=>{const e=D4(n);return z9e(e)[0]};function X9e(n){MQ(Yr());const e=D4(n);return localStorage.getItem(e)}function MQ(n){!n.password||!n.roomId||OQ(n.roomId,n.password)}const Z9e=()=>{const n=ku();return _.useEffect(()=>MQ(n),[n]),n.roomId&&n.password?[n.roomId,n.password]:[void 0,void 0]};function Hw(n){const{client:e}=cf(),[t,r]=Z9e(),i=J9e(n),s=e==null?void 0:e.getRoom(n);return _.useMemo(()=>s?i?{kind:Bt.SHARED_KEY,secret:i}:t===n?{kind:Bt.SHARED_KEY,secret:r}:s.hasEncryptionStateEvent()?{kind:Bt.PER_PARTICIPANT}:{kind:Bt.NONE}:{kind:Bt.NONE},[r,s,n,i,t])}const rU=!1,Q9e="element-call-sync";async function e7e(n){let e=!!await n.store.getSavedSyncToken();return new Promise((t,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(n.removeListener(Oe.Sync,i),t()):s==="ERROR"&&(n.removeListener(Oe.Sync,i),r(a==null?void 0:a.error))};n.on(Oe.Sync,i)})}async function AQ(n,e){var a;let t;try{t=window.indexedDB}catch(l){A.warn("Could not get indexDB from window.",l)}const r={fallbackICEServerAllowed:rU,isVoipWithNoMediaAllowed:(a=Ht.get().features)==null?void 0:a.feature_group_calls_without_video_and_audio};t&&localStorage?r.store=new rB({indexedDB:window.indexedDB,localStorage,dbName:Q9e,workerFactory:()=>new W9e}):localStorage&&(r.store=new Mv({localStorage}));const{e2eEnabled:i}=Yr();i||A.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=UE({...r,...n,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:rU});e||await s.clearStores();try{await s.store.startup()}catch(l){A.error("Error starting matrix client indexDB store. Falling back to memory store.",l),s.store=new Mv({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(l){A.warn(l,"Make sure to clear client stores before initializing the rust crypto.")}const o=e7e(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function Xy(n){return n.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function t7e(n,e){return`#${Xy(n)}:${e.getDomain()}`}function NQ(n){const e=n.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===Ht.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return n}async function DQ(n,e,t){A.log("Creating room for group call");const r=n.createRoom({visibility:bH.Private,preset:ME.PublicChat,name:e,room_alias_name:t?void 0:Xy(e),power_level_content_override:{invite:100,kick:100,ban:100,redact:50,state_default:0,events_default:0,users_default:0,events:{"m.room.power_levels":100,"m.room.history_visibility":100,"m.room.tombstone":100,"m.room.encryption":100,"m.room.name":50,"m.room.message":0,"m.room.encrypted":50,"m.sticker":50,"org.matrix.msc3401.call.member":0},users:{[n.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(u=>{a(u),c()});const l=u=>{r.then(f=>{u.roomId===f.room_id&&(o(u.roomId),c())},f=>{A.error("Failed to wait for the room to arrive",f)})},c=()=>{n.off(Oe.Room,l)};n.on(Oe.Room,l)});let s;return t==Bt.SHARED_KEY&&(s=gH(16),OQ(i,s)),{roomId:i,alias:t?void 0:t7e(e,n),password:s}}function jQ(n,e,t,r){return`${window.location.protocol}//${window.location.host}${Bw(n,e,t)}`}function Bw(n,e,t,r){return`/room/#${t?"/"+Xy(t):""}?${R3e(n,e).toString()}`}async function n7e(n){let e=0;for(;;)try{return await n()}catch(t){e++;const r=BP(t,e,!0);if(r<0)throw t;await nu(r)}}const j4=n=>{const[e,t]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=UE({baseUrl:Ht.defaultHomeserverUrl()})),_.useEffect(()=>{Ge||s.current.registerRequest({}).catch(a=>{var l,c,u,f,p,m,v;t((p=(f=(u=(c=(l=a.data)==null?void 0:l.params["m.login.terms"])==null?void 0:c.policies)==null?void 0:u.privacy_policy)==null?void 0:f.en)==null?void 0:p.url),i((v=(m=a.data)==null?void 0:m.params["m.login.recaptcha"])==null?void 0:v.public_key)})},[]);const o=_.useCallback(async(a,l,c,u,f)=>{const p=new aL({matrixClient:s.current,doRequest:async k=>s.current.registerRequest({username:a,password:l,auth:k||void 0}),stateUpdated:(k,R)=>{if(R.error)throw new Error(R.error);k==="m.login.terms"?p.submitAuthDict({type:"m.login.terms"}).catch(I=>{A.error(I)}):k==="m.login.recaptcha"&&p.submitAuthDict({type:"m.login.recaptcha",response:u}).catch(I=>{A.error(I)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:m,access_token:v,device_id:g}=await p.attemptAuth();await(n==null?void 0:n.logout(!0));const S=await AQ({baseUrl:Ht.defaultHomeserverUrl(),accessToken:v,userId:m,deviceId:g},!1);await S.setDisplayName(c);const b={user_id:m,device_id:g,access_token:v,passwordlessUser:f};f&&(b.tempPassword=l);const w=S.getUser(S.getUserId());return w.setRawDisplayName(c),w.setDisplayName(c),[S,b]},[n]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},r7e="_buttons_1arp2_8",i7e={buttons:r7e},UQ=({onJoin:n,open:e,onDismiss:t})=>{const{t:r}=ze();return E.jsxs(lf,{title:r("join_existing_call_modal.title"),open:e,onDismiss:t,children:[E.jsx("p",{children:r("join_existing_call_modal.text")}),E.jsxs(vt,{rightAlign:!0,className:i7e.buttons,children:[E.jsx(At,{onClick:t,children:r("action.no")}),E.jsx(At,{onClick:n,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},iU="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function U4(n){const{t:e}=ze(),[t]=_.useState(()=>bs(16)),r=_.useRef(void 0);_.useEffect(()=>{var a;if(!n)return;const o=()=>{document.getElementById(t)&&window.grecaptcha.render(t,{sitekey:n,size:"invisible",callback:l=>{var c;return(c=r.current)==null?void 0:c.resolve(l)},"error-callback":()=>{var l;return(l=r.current)==null?void 0:l.reject(new Error)}})};if(typeof((a=window.grecaptcha)==null?void 0:a.render)=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${iU}"]`)){const l=document.createElement("script");l.src=iU,l.async=!0,document.body.appendChild(l)}},[t,n]);const i=_.useCallback(async()=>n?window.grecaptcha?new Promise((o,a)=>{var u,f;const l=new MutationObserver(p=>{var m,v;for(const g of p)if(((v=(m=g.target)==null?void 0:m.style)==null?void 0:v.visibility)!=="visible"){a(Qj("recaptcha_dismissed",e)),l.disconnect();return}});r.current={resolve:p=>{o(p),l.disconnect()},reject:p=>{a(p),l.disconnect()}},window.grecaptcha.execute().then(()=>{},p=>{A.error("Recaptcha execution failed",p)});const c=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');(u=c==null?void 0:c.parentNode)!=null&&u.parentNode&&l.observe((f=c==null?void 0:c.parentNode)==null?void 0:f.parentNode,{attributes:!0})}):(A.log("Recaptcha not loaded"),Promise.reject(Qj("recaptcha_not_loaded",e))):Promise.resolve(""),[n,e]),s=_.useCallback(()=>{var o;(o=window.grecaptcha)==null||o.reset()},[]);return{execute:i,reset:s,recaptchaId:t}}const s7e="_form_jcuzc_8",o7e={form:s7e},Vw=_.forwardRef(({children:n,className:e,onSubmit:t},r)=>E.jsx("form",{onSubmit:t,className:Ae(o7e.form,e),ref:r,children:n}));Vw.displayName="Form";const a7e="_footer_106jg_8",l7e="_mobileLoginLink_106jg_19",c7e="_form_106jg_24",u7e="_notice_106jg_40",bg={footer:a7e,mobileLoginLink:l7e,form:c7e,notice:u7e},d7e="_container_dwllg_8",f7e="_main_dwllg_15",h7e="_logo_dwllg_23",ep={container:d7e,main:f7e,logo:h7e},sU=n=>{n=1831565813+(n|=0)|0;let e=Math.imul(n^n>>>15,1|n);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class p7e{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:t,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=t,this.style=s,this.seed=o}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
203
203
  Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((t,r)=>{let i;e?(i=(o=>{if(typeof o=="string"){const a=o.split("").map(c=>c.charCodeAt(0)).reduce((c,u)=>c+u,1),l=Math.floor(Number(a));return sU(l)}return sU(o)})(e),e=4294967296*i):i=Math.random();let s=r[Math.floor(i*r.length)]||"";if(this.style==="lowerCase")s=s.toLowerCase();else if(this.style==="capital"){const[o,...a]=s.split("");s=o.toUpperCase()+a.join("")}else this.style==="upperCase"&&(s=s.toUpperCase());return t?`${t}${this.separator}${s}`:`${s}`},"")}}const oU={separator:"_",dictionaries:[]},m7e=n=>{const e=[...n&&n.dictionaries||oU.dictionaries],t={...oU,...n,length:n&&n.length||e.length,dictionaries:e};if(!n||!n.dictionaries||!n.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new p7e(t).generate()};var g7e=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blind","blonde","bloody","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","capitalist","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","christian","chronic","chubby","circular","civic","civil","civilian","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colonial","colorful","colossal","coloured","colourful","combative","combined","comfortable","coming","commercial","common","communist","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","conservative","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","crazy","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deaf","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disabled","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","drunk","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","ethnic","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fat","fatal","favourable","favourite","federal","fellow","female","feminist","few","fierce","filthy","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","gay","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handicapped","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homeless","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","imperial","implicit","important","impossible","impressed","impressive","improved","inadequate","inappropriate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","intimate","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","liberal","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","male","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","marxist","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mute","mutual","mysterious","naked","narrow","nasty","national","native","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","olympic","only","open","operational","opposite","optimistic","oral","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","political","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","primitive","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","protestant","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","sexual","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","socialist","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","soviet","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","stupid","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thirsty","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","tory","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xenophobic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],v7e=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","booby","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"],y7e=["amaranth","amber","amethyst","apricot","aqua","aquamarine","azure","beige","black","blue","blush","bronze","brown","chocolate","coffee","copper","coral","crimson","cyan","emerald","fuchsia","gold","gray","green","harlequin","indigo","ivory","jade","lavender","lime","magenta","maroon","moccasin","olive","orange","peach","pink","plum","purple","red","rose","salmon","sapphire","scarlet","silver","tan","teal","tomato","turquoise","violet","white","yellow"];const _7e=["hydrogen","helium","lithium","beryllium","boron","carbon","nitrogen","oxygen","fluorine","neon","sodium","magnesium","aluminum","silicon","phosphorus","sulfur","chlorine","argon","potassium","calcium","scandium","titanium","vanadium","chromium","manganese","iron","cobalt","nickel","copper","zinc","gallium","germanium","arsenic","selenium","bromine","krypton","rubidium","strontium","yttrium","zirconium","niobium","molybdenum","technetium","ruthenium","rhodium","palladium","silver","cadmium","indium","tin","antimony","tellurium","iodine","xenon","cesium","barium","lanthanum","cerium","praseodymium","neodymium","promethium","samarium","europium","gadolinium","terbium","dysprosium","holmium","erbium","thulium","ytterbium","lutetium","hafnium","tantalum","wolfram","rhenium","osmium","iridium","platinum","gold","mercury","thallium","lead","bismuth","polonium","astatine","radon","francium","radium","actinium","thorium","protactinium","uranium","neptunium","plutonium","americium","curium","berkelium","californium","einsteinium","fermium","mendelevium","nobelium","lawrencium","rutherfordium","dubnium","seaborgium","bohrium","hassium","meitnerium","darmstadtium","roentgenium","copernicium","nihonium","flerovium","moscovium","livermorium","tennessine","oganesson"];function FQ(){return m7e({dictionaries:[y7e,g7e,v7e,_7e],style:"lowerCase",length:3,separator:"-"})}const b7e=()=>{const{setClient:n}=cf(),[e,t]=_.useState(!1),[r,i]=_.useState(),[s]=Aw(),{recaptchaKey:o,register:a}=j4(),{execute:l,reset:c,recaptchaId:u}=U4(o),[f,p]=_.useState(!1),m=_.useCallback(()=>p(!1),[p]),[v,g]=_.useState(),S=Na(),{t:b}=ze(),w=_.useCallback(k=>{k.preventDefault();const R=new FormData(k.target),I=NQ(R.get("callName")),C=R.get("displayName");async function x(){i(void 0),t(!0);const O=await l(),N=FQ(),[D,j]=await a(N,bs(16),C,O,!0);let U;try{U=await DQ(D,I,Bt.SHARED_KEY)}catch(H){if(!n)throw H;if(H.errcode==="M_ROOM_IN_USE"){g(()=>{var B;n(D,j);const K=Xy(I);(B=S(`/${K}`))==null||B.catch(z=>{A.error("Failed to navigate to alias localpart",z)})}),t(!1),p(!0);return}else throw H}if(!n)throw new Error("setClient is undefined");if(!U.password)throw new Error("Failed to create room with shared secret");n(D,j),await S(Bw(U.roomId,{kind:Bt.SHARED_KEY,secret:U.password},I))}x().catch(O=>{A.error(O),t(!1),i(O),c()})},[a,c,l,S,p,n]);return E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:ep.container,children:[E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(Vd,{})}),E.jsx(of,{hideMobile:!0,children:E.jsx(N4,{})})]}),E.jsxs("main",{className:ep.main,children:[E.jsx(Vd,{className:ep.logo}),E.jsx(Ru,{size:"lg",weight:"semibold",children:b("start_new_call")}),E.jsxs(Vw,{className:bg.form,onSubmit:w,children:[E.jsx(vt,{children:E.jsx(_n,{id:"callName",name:"callName",label:b("call_name"),placeholder:b("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"})}),E.jsx(vt,{children:E.jsx(_n,{id:"displayName",name:"displayName",label:b("common.display_name"),placeholder:b("common.display_name"),type:"text",required:!0,"data-testid":"home_displayName",autoComplete:"off"})}),s===null&&E.jsx(Xt,{size:"sm",className:bg.notice,children:E.jsx(mQ,{})}),E.jsx(Xt,{size:"sm",className:bg.notice,children:E.jsxs(Qi,{i18nKey:"unauthenticated_view_ssla_caption",children:['By clicking "Go", you agree to our'," ",E.jsx(Pd,{href:Ht.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),r&&E.jsx(vt,{children:E.jsx(Pu,{error:r})}),E.jsx(At,{type:"submit",size:"lg",disabled:e,"data-testid":"home_go",children:b(e?"common.loading":"action.go")}),E.jsx("div",{id:u})]})]}),E.jsxs("footer",{className:bg.footer,children:[E.jsx(Xt,{className:bg.mobileLoginLink,children:E.jsx(ka,{to:"/login","data-testid":"home_login",children:b("unauthenticated_view_login_button")})}),E.jsx(Xt,{children:E.jsxs(Qi,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",E.jsx(ka,{to:"/register","data-testid":"home_register",children:"Create an account"})]})})]})]}),v&&E.jsx(UQ,{onJoin:v,open:f,onDismiss:m})]})},rh={};function aU(n,e){if(rh[e.roomId])return rh[e.roomId];if(!e||!e.timeline){const i=Number.MAX_SAFE_INTEGER;return rh[e.roomId]=i,i}const t=n.getUserId();if(e.getMyMembership()!==qe.Join){const i=e.currentState.getStateEvents("m.room.member",t);if(i&&!Array.isArray(i)){const s=i.getTs();return rh[e.roomId]=s,s}}for(let i=e.timeline.length-1;i>=0;--i){const o=e.timeline[i].getTs();if(o)return rh[e.roomId]=o,o}const r=Number.MAX_SAFE_INTEGER;return rh[e.roomId]=r,r}function S7e(n,e){return e.sort((t,r)=>aU(n,r)-aU(n,t))}const E7e=n=>{var e,t;if(!n.hasEncryptionStateEvent()&&!X9e(n.roomId))return!1;switch(n.getJoinRule()){case Wc.Public:return!0;case Wc.Knock:switch(n.getMyMembership()){case qe.Join:case qe.Knock:return!0;case qe.Invite:return((t=(e=n.getLiveTimeline().getState(Le.FORWARDS))==null?void 0:e.getStateEvents(ee.RoomMember,n.myUserId))==null?void 0:t.getPrevContent().membership)===Wc.Knock;default:return!1}default:return n.getMyMembership()===qe.Join}},w7e=n=>{var e,t;switch(n.getMyMembership()){case qe.Join:return!!((t=(e=n.getLiveTimeline().getState(Le.FORWARDS))==null?void 0:e.events)!=null&&t.get(ee.GroupCallMemberPrefix));case qe.Knock:return!0;default:return!1}};function C7e(n){const[e,t]=_.useState([]);return _.useEffect(()=>{function r(){const i=n.getRooms().filter(w7e).filter(E7e),o=S7e(n,i).map(a=>{const l=n.matrixRTC.getRoomSession(a);return{roomAlias:a.getCanonicalAlias()??void 0,roomName:a.name,avatarUrl:a.getMxcAvatarUrl(),room:a,session:l,participants:l.memberships.filter(c=>c.sender).map(c=>a.getMember(c.sender)).filter(c=>c)}});t(o)}return r(),n.matrixRTC.on(Qb.SessionStarted,r),n.on(ke.MyMembership,r),()=>{n.matrixRTC.off(Qb.SessionStarted,r),n.off(ke.MyMembership,r)}},[n]),e}const T7e="_form_1vjc2_8",R7e="_fieldRow_1vjc2_16",I7e="_button_1vjc2_24",k7e="_notice_1vjc2_32",Sg={form:T7e,fieldRow:R7e,button:I7e,notice:k7e},x7e="_callTileSpacer_l4ywf_8",P7e="_callTile_l4ywf_8",L7e="_callTileLink_l4ywf_28",O7e="_callInfo_l4ywf_40",M7e="_callName_l4ywf_53",A7e="_callList_l4ywf_63",N7e="_disabled_l4ywf_74",cl={callTileSpacer:x7e,callTile:P7e,callTileLink:L7e,callInfo:O7e,callName:M7e,callList:A7e,disabled:N7e},D7e=({rooms:n,client:e})=>E.jsx(E.Fragment,{children:E.jsxs("div",{className:cl.callList,children:[n.map(({room:t,roomName:r,avatarUrl:i,participants:s})=>E.jsx(j7e,{client:e,name:r,avatarUrl:i,room:t,participants:s},t.roomId)),n.length>3&&E.jsxs(E.Fragment,{children:[E.jsx("div",{className:cl.callTileSpacer}),E.jsx("div",{className:cl.callTileSpacer})]})]})}),j7e=({name:n,avatarUrl:e,room:t,client:r})=>{const{t:i}=ze(),s=Hw(t.roomId),[o,a]=_.useState(!1),l=_.useCallback(u=>{u.stopPropagation(),u.preventDefault(),a(!0),r.leave(t.roomId).catch(()=>a(!1))},[t,r]),c=E.jsxs(E.Fragment,{children:[E.jsx(Zp,{id:t.roomId,name:n,size:Xp.LG,src:e}),E.jsx("div",{className:cl.callInfo,children:E.jsx(Xt,{weight:"semibold",className:cl.callName,children:n})}),E.jsx(LG,{onClick:l,disabled:o,"aria-label":i("action.remove"),children:E.jsx(aw,{})})]});return E.jsx("div",{className:cl.callTile,children:o?E.jsx("span",{className:Ae(cl.callTileLink,cl.disabled),children:c}):E.jsx(WE,{to:Bw(t.roomId,s,t.name),className:cl.callTileLink,children:c})})},U7e=({client:n})=>{const[e,t]=_.useState(!1),[r,i]=_.useState(),[s]=Aw(),o=Na(),{t:a}=ze(),[l,c]=_.useState(!1),u=_.useCallback(()=>c(!1),[c]),f=_.useCallback(S=>{S.preventDefault();const w=new FormData(S.target).get("callName"),k=typeof w=="string"?NQ(w):"";async function R(){i(void 0),t(!0);const I=await DQ(n,k,Bt.SHARED_KEY);if(!I.password)throw new Error("Failed to create room with shared secret");await o(Bw(I.roomId,{kind:Bt.SHARED_KEY,secret:I.password},k))}R().catch(I=>{I.errcode==="M_ROOM_IN_USE"?(v(Xy(k)),t(!1),i(void 0),c(!0)):(A.error(I),t(!1),i(I))})},[n,o,c]),p=C7e(n),[m,v]=_.useState(),g=_.useCallback(()=>{var S;(S=o(`/${m}`))==null||S.catch(b=>{A.error("Failed to navigate to existing alias",b)})},[o,m]);return E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:ep.container,children:[E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(Vd,{})}),E.jsx(of,{children:E.jsx(N4,{})})]}),E.jsxs("main",{className:ep.main,children:[E.jsx(Vd,{className:ep.logo}),E.jsx(Ru,{size:"lg",weight:"semibold",children:a("start_new_call")}),E.jsxs(Vw,{className:Sg.form,onSubmit:f,children:[E.jsxs(vt,{className:Sg.fieldRow,children:[E.jsx(_n,{id:"callName",name:"callName",label:a("call_name"),placeholder:a("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"}),E.jsx(At,{type:"submit",size:"lg",className:Sg.button,disabled:e,"data-testid":"home_go",children:a(e?"common.loading":"action.go")})]}),s===null&&E.jsx(Xt,{size:"sm",className:Sg.notice,children:E.jsx(mQ,{})}),r&&E.jsx(vt,{className:Sg.fieldRow,children:E.jsx(Pu,{error:r})})]}),p.length>0&&E.jsx(D7e,{rooms:p,client:n})]})]}),E.jsx(UQ,{onJoin:g,open:l,onDismiss:u})]})};function Zy(n){_.useEffect(()=>{const e="Element Call";document.title=n?`${e} | ${n}`:e},[n])}const $Q=()=>{const{t:n}=ze();Zy(n("common.home"));const e=nm();return e?e.state==="error"?E.jsx(dy,{widget:Ge,error:e.error}):e.authenticated?E.jsx(U7e,{client:e.authenticated.client}):E.jsx(b7e,{}):E.jsx(Uw,{})},F7e=(n,e)=>_.createElement("svg",{width:300,height:66,viewBox:"0 0 300 66",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("circle",{cx:32.6901,cy:32.6904,r:23.496,fill:"white"}),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32.6137 65.2274C50.6257 65.2274 65.2274 50.6257 65.2274 32.6137C65.2274 14.6016 50.6257 0 32.6137 0C14.6016 0 0 14.6016 0 32.6137C0 50.6257 14.6016 65.2274 32.6137 65.2274ZM26.6511 15.1961C26.6511 13.8796 27.7205 12.8124 29.0397 12.8124C37.9808 12.8124 45.2291 20.0456 45.2291 28.9681C45.2291 30.2846 44.1596 31.3518 42.8405 31.3518C41.5213 31.3518 40.4519 30.2846 40.4519 28.9681C40.4519 22.6785 35.3425 17.5797 29.0397 17.5797C27.7205 17.5797 26.6511 16.5125 26.6511 15.1961ZM52.4139 28.9683C52.4139 27.6518 51.3445 26.5846 50.0253 26.5846C48.7061 26.5846 47.6367 27.6518 47.6367 28.9683C47.6367 35.2579 42.5274 40.3567 36.2246 40.3567C34.9054 40.3567 33.836 41.4239 33.836 42.7404C33.836 44.0568 34.9054 45.124 36.2246 45.124C45.1657 45.124 52.4139 37.8909 52.4139 28.9683ZM38.6134 50.031C38.6134 51.3475 37.544 52.4146 36.2248 52.4146C27.2837 52.4146 20.0355 45.1815 20.0355 36.2589C20.0355 34.9425 21.1049 33.8753 22.4241 33.8753C23.7432 33.8753 24.8127 34.9425 24.8127 36.2589C24.8127 42.5486 29.922 47.6474 36.2248 47.6474C37.544 47.6474 38.6134 48.7146 38.6134 50.031ZM12.8113 36.2589C12.8113 37.5754 13.8808 38.6426 15.1999 38.6426C16.5191 38.6426 17.5885 37.5754 17.5885 36.2589C17.5885 29.9693 22.6979 24.8705 29.0007 24.8705C30.3198 24.8705 31.3893 23.8033 31.3893 22.4869C31.3893 21.1704 30.3198 20.1032 29.0007 20.1032C20.0595 20.1032 12.8113 27.3364 12.8113 36.2589Z",fill:"#0DBD8B"}),_.createElement("path",{d:"M114.73 36.9816H91.7256C91.9974 39.3888 92.871 41.3107 94.3464 42.7472C95.8217 44.1449 97.763 44.8438 100.17 44.8438C101.762 44.8438 103.199 44.4555 104.48 43.679C105.761 42.9025 106.674 41.8542 107.217 40.5341H114.206C113.274 43.6014 111.527 46.0862 108.964 47.9887C106.441 49.8523 103.451 50.7842 99.9955 50.7842C95.4917 50.7842 91.8421 49.2894 89.0466 46.2998C86.29 43.3102 84.9117 39.5247 84.9117 34.9432C84.9117 30.4783 86.3094 26.7316 89.1049 23.7032C91.9003 20.6747 95.5111 19.1605 99.9373 19.1605C104.363 19.1605 107.935 20.6553 110.653 23.6449C113.41 26.5957 114.788 30.323 114.788 34.8267L114.73 36.9816ZM99.9373 24.8097C97.763 24.8097 95.9576 25.4503 94.5211 26.7316C93.0845 28.0128 92.1915 29.7212 91.8421 31.8566H107.916C107.605 29.7212 106.751 28.0128 105.353 26.7316C103.956 25.4503 102.15 24.8097 99.9373 24.8097Z",fill:"white"}),_.createElement("path",{d:"M119.557 41.0583V6.40625H126.488V41.1748C126.488 42.7278 127.342 43.5043 129.05 43.5043L130.273 43.4461V50.0271C129.613 50.1435 128.914 50.2018 128.177 50.2018C125.187 50.2018 122.993 49.4447 121.596 47.9305C120.237 46.4163 119.557 44.1255 119.557 41.0583Z",fill:"white"}),_.createElement("path",{d:"M162.549 36.9816H139.545C139.817 39.3888 140.69 41.3107 142.166 42.7472C143.641 44.1449 145.582 44.8438 147.99 44.8438C149.582 44.8438 151.018 44.4555 152.299 43.679C153.581 42.9025 154.493 41.8542 155.037 40.5341H162.025C161.093 43.6014 159.346 46.0862 156.784 47.9887C154.26 49.8523 151.27 50.7842 147.815 50.7842C143.311 50.7842 139.662 49.2894 136.866 46.2998C134.109 43.3102 132.731 39.5247 132.731 34.9432C132.731 30.4783 134.129 26.7316 136.924 23.7032C139.72 20.6747 143.331 19.1605 147.757 19.1605C152.183 19.1605 155.755 20.6553 158.473 23.6449C161.229 26.5957 162.608 30.323 162.608 34.8267L162.549 36.9816ZM147.757 24.8097C145.582 24.8097 143.777 25.4503 142.341 26.7316C140.904 28.0128 140.011 29.7212 139.662 31.8566H155.735C155.425 29.7212 154.571 28.0128 153.173 26.7316C151.775 25.4503 149.97 24.8097 147.757 24.8097Z",fill:"white"}),_.createElement("path",{d:"M193.817 32.7302V50.0853H186.887V31.973C186.887 27.3916 184.984 25.1009 181.179 25.1009C179.122 25.1009 177.471 25.7609 176.229 27.081C175.025 28.4011 174.424 30.2065 174.424 32.4972V50.0853H167.493V19.8594H173.9V23.8779C174.637 22.519 175.763 21.393 177.277 20.5C178.792 19.607 180.675 19.1605 182.927 19.1605C187.12 19.1605 190.148 20.7524 192.012 23.9361C194.574 20.7524 197.991 19.1605 202.262 19.1605C205.795 19.1605 208.513 20.2671 210.415 22.4801C212.318 24.6544 213.269 27.5275 213.269 31.0995V50.0853H206.338V31.973C206.338 27.3916 204.436 25.1009 200.631 25.1009C198.535 25.1009 196.865 25.7803 195.623 27.1392C194.419 28.4593 193.817 30.323 193.817 32.7302Z",fill:"white"}),_.createElement("path",{d:"M247.735 36.9816H224.731C225.002 39.3888 225.876 41.3107 227.351 42.7472C228.827 44.1449 230.768 44.8438 233.175 44.8438C234.767 44.8438 236.204 44.4555 237.485 43.679C238.766 42.9025 239.678 41.8542 240.222 40.5341H247.211C246.279 43.6014 244.532 46.0862 241.969 47.9887C239.446 49.8523 236.456 50.7842 233 50.7842C228.497 50.7842 224.847 49.2894 222.052 46.2998C219.295 43.3102 217.917 39.5247 217.917 34.9432C217.917 30.4783 219.314 26.7316 222.11 23.7032C224.905 20.6747 228.516 19.1605 232.942 19.1605C237.368 19.1605 240.94 20.6553 243.658 23.6449C246.415 26.5957 247.793 30.323 247.793 34.8267L247.735 36.9816ZM232.942 24.8097C230.768 24.8097 228.963 25.4503 227.526 26.7316C226.089 28.0128 225.196 29.7212 224.847 31.8566H240.921C240.61 29.7212 239.756 28.0128 238.358 26.7316C236.961 25.4503 235.155 24.8097 232.942 24.8097Z",fill:"white"}),_.createElement("path",{d:"M259.085 19.8594V23.8779C259.784 22.5578 260.929 21.4513 262.521 20.5583C264.152 19.6264 266.113 19.1605 268.403 19.1605C271.975 19.1605 274.732 20.2477 276.673 22.4219C278.653 24.5961 279.643 27.4887 279.643 31.0995V50.0853H272.713V31.973C272.713 29.8376 272.208 28.1681 271.199 26.9645C270.228 25.7221 268.733 25.1009 266.714 25.1009C264.501 25.1009 262.754 25.7609 261.473 27.081C260.23 28.4011 259.609 30.2259 259.609 32.5554V50.0853H252.679V19.8594H259.085Z",fill:"white"}),_.createElement("path",{d:"M299.884 43.912V49.9106C299.029 50.1435 297.826 50.26 296.273 50.26C290.371 50.26 287.42 47.2898 287.42 41.3495V25.3921H282.82V19.8594H287.42V11.9972H294.351V19.8594H300V25.3921H294.351V40.6506C294.351 43.019 295.477 44.2032 297.729 44.2032L299.884 43.912Z",fill:"white"})),HQ=_.forwardRef(F7e),$7e="_logo_1gx2r_8",H7e="_container_1gx2r_14",B7e="_content_1gx2r_22",V7e="_formContainer_1gx2r_30",q7e="_authLinks_1gx2r_62",_a={logo:$7e,container:H7e,content:B7e,formContainer:V7e,authLinks:q7e};function K7e(n){return _.useCallback(async(e,t,r)=>{const i=UE({baseUrl:e}),s=new aL({matrixClient:i,doRequest:async()=>i.login("m.login.password",{identifier:{type:"m.id.user",user:t},password:r}),stateUpdated:()=>{},requestEmailToken:async()=>Promise.resolve({sid:""})}),{user_id:o,access_token:a,device_id:l}=await s.attemptAuth(),c={user_id:o,access_token:a,device_id:l,passwordlessUser:!1};return await(n==null?void 0:n.logout(!0)),[await AQ({baseUrl:e,accessToken:a,userId:o,deviceId:l},!1),c]},[n])}const G7e=()=>{var g,S;const{t:n}=ze();Zy(n("login_title"));const{client:e,setClient:t}=cf(),r=K7e(e),i=Ht.defaultHomeserverUrl(),s=_.useRef(null),o=_.useRef(null),a=Na(),l=ci(),[c,u]=_.useState(!1),[f,p]=_.useState(),m=_.useCallback(b=>{if(b.preventDefault(),u(!0),!i||!s.current||!o.current){p(Error("Login parameters are undefined")),u(!1);return}r(i,s.current.value,o.current.value).then(async([w,k])=>{if(!t)return;t(w,k);const R=l.state;R&&R.from?await a(R.from):await a("/"),Et.instance.eventLogin.track()}).catch(w=>{p(w),u(!1)})},[r,l,a,i,t]);let v=(g=Ht.defaultServerName())==null?void 0:g.slice(0,25);return v=(v==null?void 0:v.length)!==((S=Ht.defaultServerName())==null?void 0:S.length)?v+"...":v,E.jsx(E.Fragment,{children:E.jsx("div",{className:_a.container,children:E.jsxs("div",{className:_a.content,children:[E.jsxs("div",{className:_a.formContainer,children:[E.jsx(HQ,{width:"auto",height:"auto",className:_a.logo}),E.jsx("h2",{children:n("log_in")}),E.jsx("h4",{children:n("login_subheading")}),E.jsxs("form",{onSubmit:m,children:[E.jsx(vt,{children:E.jsx(_n,{type:"text",ref:s,placeholder:n("common.username"),label:n("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${v}`,"data-testid":"login_username"})}),E.jsx(vt,{children:E.jsx(_n,{type:"password",ref:o,placeholder:n("common.password"),label:n("common.password"),"data-testid":"login_password"})}),f&&E.jsx(vt,{children:E.jsx(Pu,{error:f})}),E.jsx(vt,{children:E.jsx(At,{type:"submit",disabled:c,"data-testid":"login_login",children:n(c?"logging_in":"login_title")})})]})]}),E.jsxs("div",{className:_a.authLinks,children:[E.jsx("p",{children:n("login_auth_links_prompt")}),E.jsx("p",{children:E.jsxs(Qi,{i18nKey:"login_auth_links",children:[E.jsx(ka,{to:"/register",children:"Create an account"})," Or ",E.jsx(ka,{to:"/",children:"Access as a guest"})]})})]})]})})})},W7e=()=>{const{t:n}=ze();Zy(n("action.register"));const{loading:e,authenticated:t,passwordlessUser:r,client:i,setClient:s}=x4(),o=_.useRef(null),a=Na(),l=ci(),[c,u]=_.useState(!1),[f,p]=_.useState(),[m,v]=_.useState(""),[g,S]=_.useState(""),{recaptchaKey:b,register:w}=j4(i),{execute:k,reset:R,recaptchaId:I}=U4(b),C=_.useCallback(x=>{x.preventDefault();const O=new FormData(x.target),N=O.get("userName"),D=O.get("password"),j=O.get("passwordConfirmation");if(D!==j)return;(async()=>{u(!0);const H=await k(),[K,B]=await w(N,D,N,H,r);if(i&&(i!=null&&i.groupCallEventHandler)&&r)for(const z of i.groupCallEventHandler.groupCalls.values()){const W=z.room.roomId;try{await K.joinRoom(W)}catch(V){V.errcode==="M_LIMIT_EXCEEDED"?(await nu(V.data.retry_after_ms),await K.joinRoom(W)):(nw(V),A.error(`Couldn't join room ${W}`,V))}}s==null||s(K,B),Et.instance.eventSignup.cacheSignupEnd(new Date)})().then(async()=>{var H,K;(H=l.state)!=null&&H.from?await a((K=l.state)==null?void 0:K.from):await a("/")}).catch(H=>{p(H),u(!1),R()})},[w,l,a,r,R,k,i,s]);return _.useEffect(()=>{var x,O;m&&g&&m!==g?(x=o.current)==null||x.setCustomValidity(n("register.passwords_must_match")):(O=o.current)==null||O.setCustomValidity("")},[m,g,n]),_.useEffect(()=>{var x;!e&&t&&!r&&!c&&((x=a("/"))==null||x.catch(O=>{A.error("Failed to navigate to /",O)}))},[e,a,t,r,c]),e?E.jsx(Uw,{}):(Et.instance.eventSignup.cacheSignupStart(new Date),E.jsx(E.Fragment,{children:E.jsx("div",{className:_a.container,children:E.jsxs("div",{className:_a.content,children:[E.jsxs("div",{className:_a.formContainer,children:[E.jsx(HQ,{width:"auto",height:"auto",className:_a.logo}),E.jsx("h2",{children:n("register_heading")}),E.jsxs("form",{onSubmit:C,children:[E.jsx(vt,{children:E.jsx(_n,{type:"text",name:"userName",placeholder:n("common.username"),label:n("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${Ht.defaultServerName()}`,"data-testid":"register_username"})}),E.jsx(vt,{children:E.jsx(_n,{required:!0,name:"password",type:"password",onChange:x=>v(x.target.value),value:m,placeholder:n("common.password"),label:n("common.password"),"data-testid":"register_password"})}),E.jsx(vt,{children:E.jsx(_n,{required:!0,type:"password",name:"passwordConfirmation",onChange:x=>S(x.target.value),value:g,placeholder:n("register_confirm_password_label"),label:n("register_confirm_password_label"),ref:o,"data-testid":"register_confirm_password"})}),E.jsx(Xt,{size:"sm",children:E.jsxs(Qi,{i18nKey:"recaptcha_ssla_caption",children:["This site is protected by ReCAPTCHA and the Google"," ",E.jsx(Pd,{href:"https://www.google.com/policies/privacy/",children:"Privacy Policy"})," ","and"," ",E.jsx(Pd,{href:"https://policies.google.com/terms",children:"Terms of Service"})," ","apply.",E.jsx("br",{}),'By clicking "Register", you agree to our'," ",E.jsx(Pd,{href:Ht.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),f&&E.jsx(vt,{children:E.jsx(Pu,{error:f})}),E.jsx(vt,{children:E.jsx(At,{type:"submit",disabled:c,"data-testid":"register_register",children:n(c?"register.registering":"action.register")})}),E.jsx("div",{id:I})]})]}),E.jsx("div",{className:_a.authLinks,children:E.jsxs(Qi,{i18nKey:"register_auth_links",children:[E.jsx("p",{children:"Already have an account?"}),E.jsxs("p",{children:[E.jsx(ka,{to:"/login",children:"Log in"})," Or ",E.jsx(ka,{to:"/",children:"Access as a guest"})]})]})})]})})}))},z7e="_form_1wfyo_8",Y7e="_headline_1wfyo_18",J7e="_container_1wfyo_37",X7e="_main_1wfyo_45",Z7e="_footer_1wfyo_62",Eg={form:z7e,headline:Y7e,container:J7e,main:X7e,footer:Z7e};function BQ(){const{setClient:n}=cf(),{privacyPolicyUrl:e,recaptchaKey:t,register:r}=j4(),{execute:i,reset:s,recaptchaId:o}=U4(t),a=_.useCallback(async l=>{if(!n)throw new Error("No client context");if(Ge)throw new Error("Registration was skipped: We should never try to register password-less user in embedded mode.");try{const c=await i(),u=FQ(),[f,p]=await r(u,bs(16),l,c,!0);n(f,p)}catch(c){throw s(),c}},[i,s,r,n]);return{privacyPolicyUrl:e,registerPasswordlessUser:a,recaptchaId:o}}const Q7e=()=>{const[n,e]=_.useState(!1),[t,r]=_.useState(),{registerPasswordlessUser:i,recaptchaId:s}=BQ(),o=_.useCallback(c=>{c.preventDefault(),e(!0);const f=new FormData(c.target).get("displayName");i(typeof f=="string"?f:"").catch(m=>{A.error("Failed to register passwordless user",c),e(!1),r(m)})},[i]),{t:a}=ze(),l=ci();return E.jsxs(E.Fragment,{children:[E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(Vd,{})}),E.jsx(of,{children:E.jsx(N4,{preventNavigation:!0})})]}),E.jsxs("div",{className:Eg.container,children:[E.jsxs("main",{className:Eg.main,children:[E.jsx(Ru,{size:"xl",weight:"semibold",className:Eg.headline,children:a("lobby.join_as_guest")}),E.jsxs(Vw,{className:Eg.form,onSubmit:o,children:[E.jsx(vt,{children:E.jsx(_n,{id:"displayName",name:"displayName",label:a("common.display_name"),placeholder:a("common.display_name"),"data-testid":"joincall_displayName",type:"text",required:!0,autoComplete:"off"})}),E.jsx(Xt,{size:"sm",children:E.jsxs(Qi,{i18nKey:"room_auth_view_ssla_caption",children:['By clicking "Join call now", you agree to our'," ",E.jsx(Pd,{href:Ht.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),t&&E.jsx(vt,{children:E.jsx(Pu,{error:t})}),E.jsx(At,{type:"submit",size:"lg",disabled:n,"data-testid":"joincall_joincall",children:a(n?"common.loading":"room_auth_view_continue_button")}),E.jsx("div",{id:s})]})]}),E.jsx(Xt,{className:Eg.footer,children:E.jsxs(Qi,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",E.jsx(ka,{to:"/register",state:{from:l},children:"Create an account"})]})})]})]})};var Fg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function VQ(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var qQ={exports:{}};(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(Fg,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?l:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function f(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return c(g)||f.apply(this,arguments)}function m(g,S){var b=this,w,k,R,I="loglevel";typeof g=="string"?I+=":"+g:typeof g=="symbol"&&(I=void 0);function C(j){var U=(i[j]||"silent").toUpperCase();if(!(typeof window===t||!I)){try{window.localStorage[I]=U;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+U+";"}catch{}}}function x(){var j;if(!(typeof window===t||!I)){try{j=window.localStorage[I]}catch{}if(typeof j===t)try{var U=window.document.cookie,H=encodeURIComponent(I),K=U.indexOf(H+"=");K!==-1&&(j=/^([^;]+)/.exec(U.slice(K+H.length+1))[1])}catch{}return b.levels[j]===void 0&&(j=void 0),j}}function O(){if(!(typeof window===t||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(j){var U=j;if(typeof U=="string"&&b.levels[U.toUpperCase()]!==void 0&&(U=b.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=b.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+j)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return R??k??w},b.setLevel=function(j,U){return R=N(j),U!==!1&&C(R),u.call(b)},b.setDefaultLevel=function(j){k=N(j),x()||b.setLevel(j,!1)},b.resetLevel=function(){R=null,O(),u.call(b)},b.enableAll=function(j){b.setLevel(b.levels.TRACE,j)},b.disableAll=function(j){b.setLevel(b.levels.SILENT,j)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var j in s)s[j].rebuild()},w=N(o?o.getLevel():"WARN");var D=x();D!=null&&(R=N(D)),u.call(b)}o=new m,o.getLogger=function(g){if(typeof g!="symbol"&&typeof g!="string"||g==="")throw new TypeError("You must supply a name when creating a logger.");var S=s[g];return S||(S=s[g]=new m(g,o.methodFactory)),S};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})})(qQ);var eDe=qQ.exports;const tDe=VQ(eDe);var uP=function(n,e){return uP=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])},uP(n,e)};function Vl(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");uP(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function nDe(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(f){o(f)}}function l(u){try{c(r.throw(u))}catch(f){o(f)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,[])).next())})}function KQ(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],i=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Rp(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iE(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return s}function sE(n,e,t){if(arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function tp(n){return this instanceof tp?(this.v=n,this):new tp(n)}function rDe(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(m){return function(v){return Promise.resolve(v).then(m,f)}}function a(m,v){r[m]&&(i[m]=function(g){return new Promise(function(S,b){s.push([m,g,S,b])>1||l(m,g)})},v&&(i[m]=v(i[m])))}function l(m,v){try{c(r[m](v))}catch(g){p(s[0][3],g)}}function c(m){m.value instanceof tp?Promise.resolve(m.value.v).then(u,f):p(s[0][2],m)}function u(m){l("next",m)}function f(m){l("throw",m)}function p(m,v){m(v),s.shift(),s.length&&l(s[0][0],s[0][1])}}function iDe(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Rp=="function"?Rp(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),i(a,l,o.done,o.value)})}}function i(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},o)}}function br(n){return typeof n=="function"}function F4(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var uI=F4(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
204
204
  `+e.map(function(t,r){return r+1+") "+t.toString()}).join(`
205
205
  `):"",this.name="UnsubscriptionError",this.errors=e}});function oE(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Qy=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=Rp(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(br(u))try{u()}catch(g){s=g instanceof uI?g.errors:[g]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var p=Rp(f),m=p.next();!m.done;m=p.next()){var v=m.value;try{lU(v)}catch(g){s=s??[],g instanceof uI?s=sE(sE([],iE(s)),iE(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new uI(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)lU(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&oE(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&oE(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),GQ=Qy.EMPTY;function WQ(n){return n instanceof Qy||n&&"closed"in n&&br(n.remove)&&br(n.add)&&br(n.unsubscribe)}function lU(n){br(n)?n():n.unsubscribe()}var sDe={Promise:void 0},oDe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,sE([n,e],iE(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function zQ(n){oDe.setTimeout(function(){throw n})}function cU(){}function Ab(n){n()}var $4=function(n){Vl(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,WQ(t)&&t.add(r)):r.destination=cDe,r}return e.create=function(t,r,i){return new dP(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Qy),aDe=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){y_(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){y_(r)}else y_(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){y_(t)}},n}(),dP=function(n){Vl(e,n);function e(t,r,i){var s=n.call(this)||this,o;return br(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new aDe(o),s}return e}($4);function y_(n){zQ(n)}function lDe(n){throw n}var cDe={closed:!0,next:cU,error:lDe,complete:cU},H4=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function YQ(n){return n}function uDe(n){return n.length===0?YQ:n.length===1?n[0]:function(e){return n.reduce(function(t,r){return r(t)},e)}}var Cs=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=fDe(e)?e:new dP(e,t,r);return Ab(function(){var o=i,a=o.operator,l=o.source;s.add(a?a.call(s,l):l?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=uU(t),new t(function(i,s){var o=new dP({next:function(a){try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[H4]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return uDe(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=uU(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function uU(n){var e;return(e=n??sDe.Promise)!==null&&e!==void 0?e:Promise}function dDe(n){return n&&br(n.next)&&br(n.error)&&br(n.complete)}function fDe(n){return n&&n instanceof $4||dDe(n)&&WQ(n)}function hDe(n){return br(n==null?void 0:n.lift)}function e0(n){return function(e){if(hDe(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function aE(n,e,t,r,i){return new pDe(n,e,t,r,i)}var pDe=function(n){Vl(e,n);function e(t,r,i,s,o,a){var l=n.call(this,t)||this;return l.onFinalize=o,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(u){t.error(u)}}:n.prototype._next,l._error=s?function(c){try{s(c)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,l._complete=i?function(){try{i()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}($4),mDe=F4(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),JQ=function(n){Vl(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new dU(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new mDe},e.prototype.next=function(t){var r=this;Ab(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=Rp(r.currentObservers),a=o.next();!a.done;a=o.next()){var l=a.value;l.next(t)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;Ab(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;Ab(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?GQ:(this.currentObservers=null,a.push(t),new Qy(function(){r.currentObservers=null,oE(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new Cs;return t.source=this,t},e.create=function(t,r){return new dU(t,r)},e}(Cs),dU=function(n){Vl(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:GQ},e}(JQ);(function(n){Vl(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e})(JQ);var gDe={now:function(){return Date.now()}},vDe=function(n){Vl(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Qy),fU={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,sE([n,e],iE(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},yDe=function(n){Vl(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),fU.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&fU.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,oE(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(vDe),hU=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=gDe.now,n}(),_De=function(n){Vl(e,n);function e(t,r){r===void 0&&(r=hU.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(hU);new _De(yDe);function bDe(n){return n&&br(n.schedule)}function SDe(n){return n[n.length-1]}function XQ(n){return bDe(SDe(n))?n.pop():void 0}var ZQ=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function QQ(n){return br(n==null?void 0:n.then)}function eee(n){return br(n[H4])}function tee(n){return Symbol.asyncIterator&&br(n==null?void 0:n[Symbol.asyncIterator])}function nee(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function EDe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ree=EDe();function iee(n){return br(n==null?void 0:n[ree])}function see(n){return rDe(this,arguments,function(){var e,t,r,i;return KQ(this,function(s){switch(s.label){case 0:e=n.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,tp(e.read())];case 3:return t=s.sent(),r=t.value,i=t.done,i?[4,tp(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,tp(r)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function oee(n){return br(n==null?void 0:n.getReader)}function t0(n){if(n instanceof Cs)return n;if(n!=null){if(eee(n))return wDe(n);if(ZQ(n))return CDe(n);if(QQ(n))return TDe(n);if(tee(n))return aee(n);if(iee(n))return RDe(n);if(oee(n))return IDe(n)}throw nee(n)}function wDe(n){return new Cs(function(e){var t=n[H4]();if(br(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function CDe(n){return new Cs(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function TDe(n){return new Cs(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,zQ)})}function RDe(n){return new Cs(function(e){var t,r;try{for(var i=Rp(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function aee(n){return new Cs(function(e){kDe(n,e).catch(function(t){return e.error(t)})})}function IDe(n){return aee(see(n))}function kDe(n,e){var t,r,i,s;return nDe(this,void 0,void 0,function(){var o,a;return KQ(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=iDe(n),l.label=1;case 1:return[4,t.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ld(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function lee(n,e){return e===void 0&&(e=0),e0(function(t,r){t.subscribe(aE(r,function(i){return Ld(r,n,function(){return r.next(i)},e)},function(){return Ld(r,n,function(){return r.complete()},e)},function(i){return Ld(r,n,function(){return r.error(i)},e)}))})}function cee(n,e){return e===void 0&&(e=0),e0(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function xDe(n,e){return t0(n).pipe(cee(e),lee(e))}function PDe(n,e){return t0(n).pipe(cee(e),lee(e))}function LDe(n,e){return new Cs(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function ODe(n,e){return new Cs(function(t){var r;return Ld(t,e,function(){r=n[ree](),Ld(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return br(r==null?void 0:r.return)&&r.return()}})}function uee(n,e){if(!n)throw new Error("Iterable cannot be null");return new Cs(function(t){Ld(t,e,function(){var r=n[Symbol.asyncIterator]();Ld(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function MDe(n,e){return uee(see(n),e)}function ADe(n,e){if(n!=null){if(eee(n))return xDe(n,e);if(ZQ(n))return LDe(n,e);if(QQ(n))return PDe(n,e);if(tee(n))return uee(n,e);if(iee(n))return ODe(n,e);if(oee(n))return MDe(n,e)}throw nee(n)}function NDe(n,e){return e?ADe(n,e):t0(n)}F4(function(n){return function(e){e===void 0&&(e=null),n(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=e}});function qw(n,e){return e0(function(t,r){var i=0;t.subscribe(aE(r,function(s){r.next(n.call(e,s,i++))}))})}function DDe(n,e,t,r,i,s,o,a){var l=[],c=0,u=0,f=!1,p=function(){f&&!l.length&&!c&&e.complete()},m=function(g){return c<r?v(g):l.push(g)},v=function(g){c++;var S=!1;t0(t(g,u++)).subscribe(aE(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{c--;for(var b=function(){var w=l.shift();o||v(w)};l.length&&c<r;)b();p()}catch(w){e.error(w)}}))};return n.subscribe(aE(e,m,function(){f=!0,p()})),function(){}}function dee(n,e,t){return t===void 0&&(t=1/0),br(e)?dee(function(r,i){return qw(function(s,o){return e(r,s,i,o)})(t0(n(r,i)))},t):(typeof e=="number"&&(t=e),e0(function(r,i){return DDe(r,i,n,t)}))}function jDe(n){return dee(YQ,n)}function UDe(){return jDe(1)}function pU(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return UDe()(NDe(n,XQ(n)))}function Kw(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=XQ(n);return e0(function(r,i){(t?pU(n,r,t):pU(n,r)).subscribe(i)})}var FDe="lk";function B4(n){return typeof n>"u"?!1:$De(n)||HDe(n)}function $De(n){var e;return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&n.hasOwnProperty("track")&&typeof((e=n.publication)==null?void 0:e.track)<"u":!1}function HDe(n){return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&n.hasOwnProperty("publication")&&typeof n.publication<"u":!1}function BDe(n){return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&typeof n.publication>"u":!1}function VDe(n){if(typeof n=="string"||typeof n=="number")return`${n}`;if(BDe(n))return`${n.participant.identity}_${n.source}_placeholder`;if(B4(n))return`${n.participant.identity}_${n.publication.source}_${n.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${n}`)}var qDe=[le.ConnectionStateChanged,le.RoomMetadataChanged,le.ActiveSpeakersChanged,le.ConnectionQualityChanged,le.ParticipantConnected,le.ParticipantDisconnected,le.ParticipantPermissionsChanged,le.ParticipantMetadataChanged,le.ParticipantNameChanged,le.ParticipantAttributesChanged,le.TrackMuted,le.TrackUnmuted,le.TrackPublished,le.TrackUnpublished,le.TrackStreamStateChanged,le.TrackSubscriptionFailed,le.TrackSubscriptionPermissionChanged,le.TrackSubscriptionStatusChanged],KDe=[...qDe,le.LocalTrackPublished,le.LocalTrackUnpublished];oe.TrackPublished,oe.TrackUnpublished,oe.TrackMuted,oe.TrackUnmuted,oe.TrackStreamStateChanged,oe.TrackSubscribed,oe.TrackUnsubscribed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionFailed,oe.LocalTrackPublished,oe.LocalTrackUnpublished;var GDe=[oe.ConnectionQualityChanged,oe.IsSpeakingChanged,oe.ParticipantMetadataChanged,oe.ParticipantPermissionsChanged,oe.TrackMuted,oe.TrackUnmuted,oe.TrackPublished,oe.TrackUnpublished,oe.TrackStreamStateChanged,oe.TrackSubscriptionFailed,oe.TrackSubscriptionPermissionChanged,oe.TrackSubscriptionStatusChanged];[...GDe,oe.LocalTrackPublished,oe.LocalTrackUnpublished];var yu=tDe.getLogger("lk-components-js");yu.setDefaultLevel("WARN");function fee(n){return typeof n=="object"}function hee(n){return Array.isArray(n)&&n.filter(fee).length>0}function WDe(n){return`${FDe}-${n}`}function zDe(n){const e=fP(n),t=pee(n.participant).pipe(qw(()=>fP(n)),Kw(e));return{className:WDe(n.source===ue.Source.Camera||n.source===ue.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:t}}function fP(n){if(B4(n))return n.publication;{const{source:e,name:t,participant:r}=n;if(e&&t)return r.getTrackPublications().find(i=>i.source===e&&i.trackName===t);if(t)return r.getTrackPublicationByName(t);if(e)return r.getTrackPublication(e);throw new Error("At least one of source and name needs to be defined")}}function YDe(n,...e){return new Cs(t=>{const r=()=>{t.next(n)};return e.forEach(i=>{n.on(i,r)}),()=>{e.forEach(i=>{n.off(i,r)})}}).pipe(Kw(n))}function JDe(n,...e){return new Cs(t=>{const r=()=>{t.next(n)};return e.forEach(i=>{n.on(i,r)}),()=>{e.forEach(i=>{n.off(i,r)})}}).pipe(Kw(n))}function pee(n){return JDe(n,oe.TrackMuted,oe.TrackUnmuted,oe.ParticipantPermissionsChanged,oe.TrackPublished,oe.TrackUnpublished,oe.LocalTrackPublished,oe.LocalTrackUnpublished,oe.MediaDevicesError,oe.TrackSubscriptionStatusChanged).pipe(qw(e=>{const{isMicrophoneEnabled:t,isCameraEnabled:r,isScreenShareEnabled:i}=e,s=e.getTrackPublication(ue.Source.Microphone),o=e.getTrackPublication(ue.Source.Camera);return{isCameraEnabled:r,isMicrophoneEnabled:t,isScreenShareEnabled:i,cameraTrack:o,microphoneTrack:s,participant:e}}))}new TextEncoder;new TextDecoder;function mU(n,e,t=!0){const r=[n.localParticipant,...Array.from(n.remoteParticipants.values())],i=[];return r.forEach(s=>{e.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(l=>l.source===o&&(!t||l.track)).map(l=>({participant:s,publication:l,source:l.source}));i.push(...a)})}),{trackReferences:i,participants:r}}function XDe(n,e,t){var r,i;const s=(r=t.additionalRoomEvents)!=null?r:KDe,o=(i=t.onlySubscribed)!=null?i:!0,a=Array.from(new Set([le.ParticipantConnected,le.ParticipantDisconnected,le.ConnectionStateChanged,le.LocalTrackPublished,le.LocalTrackUnpublished,le.TrackPublished,le.TrackUnpublished,le.TrackSubscriptionStatusChanged,...s]).values());return YDe(n,...a).pipe(qw(l=>{const c=mU(l,e,o);return yu.debug(`TrackReference[] was updated. (length ${c.trackReferences.length})`,c),c}),Kw(mU(n,e,o)))}_.createContext(void 0);const ZDe=_.createContext(void 0);function QDe(){return _.useContext(ZDe)}function mee(n){const e=QDe(),t=n??e;if(!t)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return t}_.createContext(void 0);const gee=_.createContext(void 0);function eje(){return _.useContext(gee)}function vee(n){const e=eje(),t=n??e;if(!t)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return t}_.createContext(void 0);function yee(n){var e,t,r="";if(typeof n=="string"||typeof n=="number")r+=n;else if(typeof n=="object")if(Array.isArray(n)){var i=n.length;for(e=0;e<i;e++)n[e]&&(t=yee(n[e]))&&(r&&(r+=" "),r+=t)}else for(t in n)n[t]&&(r&&(r+=" "),r+=t);return r}function tje(){for(var n,e,t=0,r="",i=arguments.length;t<i;t++)(n=arguments[t])&&(e=yee(n))&&(r&&(r+=" "),r+=e);return r}function nje(...n){return(...e)=>{for(const t of n)if(typeof t=="function")try{t(...e)}catch(r){console.error(r)}}}function rje(...n){const e={...n[0]};for(let t=1;t<n.length;t++){const r=n[t];for(const i in r){const s=e[i],o=r[i];typeof s=="function"&&typeof o=="function"&&i[0]==="o"&&i[1]==="n"&&i.charCodeAt(2)>=65&&i.charCodeAt(2)<=90?e[i]=nje(s,o):(i==="className"||i==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?e[i]=tje(s,o):e[i]=o!==void 0?o:s}}return e}function ije(n){return n!==void 0}function sje(...n){return rje(...n.filter(ije))}function oje(n,e){return n==="processor"&&e&&typeof e=="object"&&"name"in e?e.name:n==="e2ee"&&e?"e2ee-enabled":e}function aje(n={}){const e=vee(n.room),[t,r]=_.useState(e.localParticipant),[i,s]=_.useState(t.isMicrophoneEnabled),[o,a]=_.useState(t.isMicrophoneEnabled),[l,c]=_.useState(t.lastMicrophoneError),[u,f]=_.useState(t.lastCameraError),[p,m]=_.useState(t.isMicrophoneEnabled),[v,g]=_.useState(void 0),[S,b]=_.useState(void 0),w=k=>{a(k.isCameraEnabled),s(k.isMicrophoneEnabled),m(k.isScreenShareEnabled),b(k.cameraTrack),g(k.microphoneTrack),c(k.participant.lastMicrophoneError),f(k.participant.lastCameraError),r(k.participant)};return _.useEffect(()=>{const k=pee(e.localParticipant).subscribe(w);return()=>k.unsubscribe()},[e]),{isMicrophoneEnabled:i,isScreenShareEnabled:p,isCameraEnabled:o,microphoneTrack:v,cameraTrack:S,lastMicrophoneError:l,lastCameraError:u,localParticipant:t}}function lje(n=[ue.Source.Camera,ue.Source.Microphone,ue.Source.ScreenShare,ue.Source.ScreenShareAudio,ue.Source.Unknown],e={}){const t=vee(e.room),[r,i]=_.useState([]),[s,o]=_.useState([]),a=_.useMemo(()=>n.map(l=>fee(l)?l.source:l),[JSON.stringify(n)]);return _.useEffect(()=>{const l=XDe(t,a,{additionalRoomEvents:e.updateOnlyOn,onlySubscribed:e.onlySubscribed}).subscribe(({trackReferences:c,participants:u})=>{yu.debug("setting track bundles",c,u),i(c),o(u)});return()=>l.unsubscribe()},[t,JSON.stringify(e.onlySubscribed),JSON.stringify(e.updateOnlyOn),JSON.stringify(n)]),_.useMemo(()=>{if(hee(n)){const l=uje(n,s),c=Array.from(r);return s.forEach(u=>{l.has(u.identity)&&(l.get(u.identity)??[]).forEach(f=>{if(r.find(({participant:m,publication:v})=>u.identity===m.identity&&v.source===f))return;yu.debug(`Add ${f} placeholder for participant ${u.identity}.`);const p={participant:u,source:f};c.push(p)})}),c}else return r},[r,s,n])}function cje(n,e){const t=new Set(n);for(const r of e)t.delete(r);return t}function uje(n,e){const t=new Map;if(hee(n)){const r=n.filter(i=>i.withPlaceholder).map(i=>i.source);e.forEach(i=>{const s=i.getTrackPublications().map(a=>{var l;return(l=a.track)==null?void 0:l.source}).filter(a=>a!==void 0),o=Array.from(cje(new Set(r),new Set(s)));o.length>0&&t.set(i.identity,o)})}return t}function _ee(n,e={}){const[t,r]=_.useState(fP(n)),[i,s]=_.useState(t==null?void 0:t.isMuted),[o,a]=_.useState(t==null?void 0:t.isSubscribed),[l,c]=_.useState(t==null?void 0:t.track),[u,f]=_.useState("landscape"),p=_.useRef(),{className:m,trackObserver:v}=_.useMemo(()=>zDe(n),[n.participant.sid??n.participant.identity,n.source,B4(n)&&n.publication.trackSid]);return _.useEffect(()=>{const g=v.subscribe(S=>{yu.debug("update track",S),r(S),s(S==null?void 0:S.isMuted),a(S==null?void 0:S.isSubscribed),c(S==null?void 0:S.track)});return()=>g==null?void 0:g.unsubscribe()},[v]),_.useEffect(()=>{var g,S;return l&&(p.current&&l.detach(p.current),(g=e.element)!=null&&g.current&&!(n.participant.isLocal&&(l==null?void 0:l.kind)==="audio")&&l.attach(e.element.current)),p.current=(S=e.element)==null?void 0:S.current,()=>{p.current&&(l==null||l.detach(p.current))}},[l,e.element]),_.useEffect(()=>{var g,S;if(typeof((g=t==null?void 0:t.dimensions)==null?void 0:g.width)=="number"&&typeof((S=t==null?void 0:t.dimensions)==null?void 0:S.height)=="number"){const b=t.dimensions.width>t.dimensions.height?"landscape":"portrait";f(b)}},[t]),{publication:t,isMuted:i,isSubscribed:o,track:l,elementProps:sje(e.props,{className:m,"data-lk-local-participant":n.participant.isLocal,"data-lk-source":t==null?void 0:t.source,...(t==null?void 0:t.kind)==="video"&&{"data-lk-orientation":u}})}}var dje="Expected a function",gU=NaN,fje="[object Symbol]",hje=/^\s+|\s+$/g,pje=/^[-+]0x[0-9a-f]+$/i,mje=/^0b[01]+$/i,gje=/^0o[0-7]+$/i,vje=parseInt,yje=typeof Fg=="object"&&Fg&&Fg.Object===Object&&Fg,_je=typeof self=="object"&&self&&self.Object===Object&&self,bje=yje||_je||Function("return this")(),Sje=Object.prototype,Eje=Sje.toString,wje=Math.max,Cje=Math.min,dI=function(){return bje.Date.now()};function Tje(n,e,t){var r,i,s,o,a,l,c=0,u=!1,f=!1,p=!0;if(typeof n!="function")throw new TypeError(dje);e=vU(e)||0,hP(t)&&(u=!!t.leading,f="maxWait"in t,s=f?wje(vU(t.maxWait)||0,e):s,p="trailing"in t?!!t.trailing:p);function m(C){var x=r,O=i;return r=i=void 0,c=C,o=n.apply(O,x),o}function v(C){return c=C,a=setTimeout(b,e),u?m(C):o}function g(C){var x=C-l,O=C-c,N=e-x;return f?Cje(N,s-O):N}function S(C){var x=C-l,O=C-c;return l===void 0||x>=e||x<0||f&&O>=s}function b(){var C=dI();if(S(C))return w(C);a=setTimeout(b,g(C))}function w(C){return a=void 0,p&&r?m(C):(r=i=void 0,o)}function k(){a!==void 0&&clearTimeout(a),c=0,r=l=i=a=void 0}function R(){return a===void 0?o:w(dI())}function I(){var C=dI(),x=S(C);if(r=arguments,i=this,l=C,x){if(a===void 0)return v(l);if(f)return a=setTimeout(b,e),m(l)}return a===void 0&&(a=setTimeout(b,e)),o}return I.cancel=k,I.flush=R,I}function hP(n){var e=typeof n;return!!n&&(e=="object"||e=="function")}function Rje(n){return!!n&&typeof n=="object"}function Ije(n){return typeof n=="symbol"||Rje(n)&&Eje.call(n)==fje}function vU(n){if(typeof n=="number")return n;if(Ije(n))return gU;if(hP(n)){var e=typeof n.valueOf=="function"?n.valueOf():n;n=hP(e)?e+"":e}if(typeof n!="string")return n===0?n:+n;n=n.replace(hje,"");var t=mje.test(n);return t||gje.test(n)?vje(n.slice(2),t?2:8):pje.test(n)?gU:+n}var kje=Tje;const yU=VQ(kje);function xje(n){const e=_.useRef(n);e.current=n,_.useEffect(()=>()=>{e.current()},[])}function Pje(n,e=500,t){const r=_.useRef();xje(()=>{r.current&&r.current.cancel()});const i=_.useMemo(()=>{const s=yU(n,e,t),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!r.current,o.flush=()=>s.flush(),o},[n,e,t]);return _.useEffect(()=>{r.current=yU(n,e,t)},[n,e,t]),i}function Lje(n,e,t){const r=(c,u)=>c===u,i=n instanceof Function?n():n,[s,o]=_.useState(i),a=_.useRef(i),l=Pje(o,e,t);return r(a.current,i)||(l(i),a.current=i),[s,l]}function Oje({threshold:n=0,root:e=null,rootMargin:t="0%",freezeOnceVisible:r=!1,initialIsIntersecting:i=!1,onChange:s}={}){var o;const[a,l]=_.useState(null),[c,u]=_.useState(()=>({isIntersecting:i,entry:void 0})),f=_.useRef();f.current=s;const p=((o=c.entry)==null?void 0:o.isIntersecting)&&r;_.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||p)return;const g=new IntersectionObserver(S=>{const b=Array.isArray(g.thresholds)?g.thresholds:[g.thresholds];S.forEach(w=>{const k=w.isIntersecting&&b.some(R=>w.intersectionRatio>=R);u({isIntersecting:k,entry:w}),f.current&&f.current(k,w)})},{threshold:n,root:e,rootMargin:t});return g.observe(a),()=>{g.disconnect()}},[a,JSON.stringify(n),e,t,p,r]);const m=_.useRef(null);_.useEffect(()=>{var g;!a&&(g=c.entry)!=null&&g.target&&!r&&!p&&m.current!==c.entry.target&&(m.current=c.entry.target,u({isIntersecting:i,entry:void 0}))},[a,c.entry,r,p,i]);const v=[l,!!c.isIntersecting,c.entry];return v.ref=v[0],v.isIntersecting=v[1],v.entry=v[2],v}const Mje=_.forwardRef(function({onTrackClick:n,onClick:e,onSubscriptionStatusChanged:t,trackRef:r,manageSubscription:i,...s},o){const a=mee(r),l=_.useRef(null);_.useImperativeHandle(o,()=>l.current);const c=Oje({root:l.current}),[u]=Lje(c,3e3);_.useEffect(()=>{i&&a.publication instanceof pS&&(u==null?void 0:u.isIntersecting)===!1&&(c==null?void 0:c.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,i]),_.useEffect(()=>{i&&a.publication instanceof pS&&(c==null?void 0:c.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[c,a,i]);const{elementProps:f,publication:p,isSubscribed:m}=_ee(a,{element:l,props:s});_.useEffect(()=>{t==null||t(!!m)},[m,t]);const v=g=>{e==null||e(g),n==null||n({participant:a==null?void 0:a.participant,track:p})};return _.createElement("video",{ref:l,...f,muted:!0,onClick:v})}),Aje=_.forwardRef(function({trackRef:n,onSubscriptionStatusChanged:e,volume:t,...r},i){const s=mee(n),o=_.useRef(null);_.useImperativeHandle(i,()=>o.current);const{elementProps:a,isSubscribed:l,track:c,publication:u}=_ee(s,{element:o,props:r});return _.useEffect(()=>{e==null||e(!!l)},[l,e]),_.useEffect(()=>{c===void 0||t===void 0||(c instanceof eq?c.setVolume(t):yu.warn("Volume can only be set on remote audio tracks."))},[t,c]),_.useEffect(()=>{u===void 0||r.muted===void 0||(u instanceof pS?u.setEnabled(!r.muted):yu.warn("Can only call setEnabled on remote track publications."))},[r.muted,u,c]),_.createElement("audio",{ref:o,...a})});function Nje({volume:n,muted:e}){const t=lje([ue.Source.Microphone,ue.Source.ScreenShareAudio,ue.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(r=>!r.participant.isLocal&&r.publication.kind===ue.Kind.Audio);return _.createElement("div",{style:{display:"none"}},t.map(r=>_.createElement(Aje,{key:VDe(r),trackRef:r,volume:n,muted:e})))}function Dje(n,e){const[t,r]=_.useState(),i=_.useMemo(()=>new Si,[]);return _.useEffect(()=>{let s=!1,o=[];return i.lock().then(async a=>{try{(n.audio||n.video)&&(o=await Iy(n),s?o.forEach(l=>l.stop()):r(o))}catch(l){e&&l instanceof Error?e(l):yu.error(l)}finally{a()}}),()=>{s=!0,o.forEach(a=>{a.stop()})}},[JSON.stringify(n,oje),e,i]),t}const jje="_inRoom_1a6xo_8",Uje="_header_1a6xo_17",Fje="_filler_1a6xo_29",$je="_footer_1a6xo_34",Hje="_hidden_1a6xo_53",Bje="_overlay_1a6xo_57",Vje="_logo_1a6xo_75",qje="_buttons_1a6xo_84",Kje="_layout_1a6xo_91",Gje="_raiseHand_1a6xo_111",Wje="_invite_1a6xo_117",zje="_switchCamera_1a6xo_118",Yje="_shareScreen_1a6xo_119",Jje="_fixedGrid_1a6xo_148",Xje="_scrollingGrid_1a6xo_154",Zje="_tile_1a6xo_173",Qje="_maximised_1a6xo_178",Mn={inRoom:jje,header:Uje,filler:Fje,footer:$je,hidden:Hje,overlay:Bje,logo:Vje,buttons:qje,layout:Kje,raiseHand:Gje,invite:Wje,switchCamera:zje,shareScreen:Yje,fixedGrid:Jje,scrollingGrid:Xje,tile:Zje,maximised:Qje},eUe="_content_1cy0f_8",tUe="_wait_1cy0f_19",nUe="_join_1cy0f_32",wg={content:eUe,wait:tUe,join:nUe};function _U(n,e){let t;return(...r)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...r),e)}}function pv({debounce:n,scroll:e,polyfill:t,offsetSize:r}={debounce:0,scroll:!1,offsetSize:!1}){const i=t||(typeof window>"u"?class{}:window.ResizeObserver);if(!i)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[s,o]=_.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),a=_.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:s,orientationHandler:null}),l=n?typeof n=="number"?n:n.scroll:null,c=n?typeof n=="number"?n:n.resize:null,u=_.useRef(!1);_.useEffect(()=>(u.current=!0,()=>void(u.current=!1)));const[f,p,m]=_.useMemo(()=>{const b=()=>{if(!a.current.element)return;const{left:w,top:k,width:R,height:I,bottom:C,right:x,x:O,y:N}=a.current.element.getBoundingClientRect(),D={left:w,top:k,width:R,height:I,bottom:C,right:x,x:O,y:N};a.current.element instanceof HTMLElement&&r&&(D.height=a.current.element.offsetHeight,D.width=a.current.element.offsetWidth),Object.freeze(D),u.current&&!oUe(a.current.lastBounds,D)&&o(a.current.lastBounds=D)};return[b,c?_U(b,c):b,l?_U(b,l):b]},[o,r,l,c]);function v(){a.current.scrollContainers&&(a.current.scrollContainers.forEach(b=>b.removeEventListener("scroll",m,!0)),a.current.scrollContainers=null),a.current.resizeObserver&&(a.current.resizeObserver.disconnect(),a.current.resizeObserver=null),a.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",a.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",a.current.orientationHandler))}function g(){a.current.element&&(a.current.resizeObserver=new i(m),a.current.resizeObserver.observe(a.current.element),e&&a.current.scrollContainers&&a.current.scrollContainers.forEach(b=>b.addEventListener("scroll",m,{capture:!0,passive:!0})),a.current.orientationHandler=()=>{m()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",a.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",a.current.orientationHandler))}const S=b=>{!b||b===a.current.element||(v(),a.current.element=b,a.current.scrollContainers=bee(b),g())};return iUe(m,!!e),rUe(p),_.useEffect(()=>{v(),g()},[e,m,p]),_.useEffect(()=>v,[]),[S,s,f]}function rUe(n){_.useEffect(()=>{const e=n;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[n])}function iUe(n,e){_.useEffect(()=>{if(e){const t=n;return window.addEventListener("scroll",t,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",t,!0)}},[n,e])}function bee(n){const e=[];if(!n||n===document.body)return e;const{overflow:t,overflowX:r,overflowY:i}=window.getComputedStyle(n);return[t,r,i].some(s=>s==="auto"||s==="scroll")&&e.push(n),[...e,...bee(n.parentElement)]}const sUe=["x","y","top","bottom","left","right","width","height"],oUe=(n,e)=>sUe.every(t=>n[t]===e[t]),aUe="_loading_14w06_8",lUe={loading:aUe},cUe=({size:n,loading:e,...t})=>E.jsxs("div",{children:[e&&E.jsx("div",{className:lUe.loading,children:E.jsx(JTe,{size:n/3})}),E.jsx(Zp,{size:n,...t})]}),uUe="_preview_1jjvr_8",dUe="_mirror_1jjvr_24",fUe="_cameraStarting_1jjvr_28",hUe="_avatarContainer_1jjvr_39",pUe="_buttonBar_1jjvr_51",Cg={preview:uUe,mirror:dUe,cameraStarting:fUe,avatarContainer:hUe,buttonBar:pUe},mUe=({matrixInfo:n,muteStates:e,videoTrack:t,children:r})=>{const{t:i}=ze(),[s,o]=pv(),a=_.useRef(null);_.useEffect(()=>(a.current&&(t==null||t.attach(a.current)),()=>{t==null||t.detach()}),[t]);const l=_.useMemo(()=>e.video.enabled&&!t,[e.video.enabled,t]);return E.jsxs("div",{className:Ae(Cg.preview),ref:s,children:[E.jsx("video",{className:t&&RL(t).facingMode==="user"?Cg.mirror:void 0,ref:a,muted:!0,playsInline:!0,tabIndex:-1,disablePictureInPicture:!0}),(!e.video.enabled||l)&&E.jsx(E.Fragment,{children:E.jsxs("div",{className:Cg.avatarContainer,children:[l&&E.jsx("div",{className:Cg.cameraStarting,role:"status",children:i("video_tile.camera_starting")}),E.jsx(cUe,{id:n.userId,name:n.displayName,size:Math.min(o.width,o.height)/2,src:n.avatarUrl,loading:l})]})}),E.jsx("div",{className:Cg.buttonBar,children:r})]})},See=n=>{const{t:e}=ze();return E.jsx(At,{kind:"secondary",size:"sm",Icon:aRe,...n,children:e("action.invite")})};function Ip(n){const e=_.useRef(void 0);return e.current??(e.current={value:n()}),e.current.value}let Od;/android/i.test(navigator.userAgent)?Od="android":/iPad|iPhone|iPod|Mac/.test(navigator.userAgent)&&"ontouchend"in document?Od="ios":Od="desktop";const gUe=()=>{const{userAgent:n}=navigator;return n.includes("Firefox")};function xl(n){const e=_.useRef(n);return e.current=n,e}function Eee(n){const e=uf(),t=xl(e.videoInput.select),r=ay(s=>s.pipe(Pt(([o])=>o),Pt(o=>o===null?Ct(null):oy(Ea(o,Re.Restarted).pipe(dn(null),Ne(()=>o)),Ea(o,Re.Muted).pipe(Ne(()=>null))))),[n]),i=ay(s=>Od==="desktop"?Ct(null):s.pipe(Pt(([o])=>o),Ne(o=>{if(o===null)return null;const a=RL(o).facingMode;return a!=="user"&&a!=="environment"?null:()=>void o.restartTrack({facingMode:a==="user"?"environment":"user"}).then(()=>{const l=o.mediaStreamTrack.getSettings().deviceId;l!==void 0&&t.current(l)}).catch(l=>A.error("Failed to switch camera",a,l))})),[r]);return tt(i)}const wee=({client:n,matrixInfo:e,muteStates:t,onEnter:r,enterLabel:i,confineToRoom:s,hideHeader:o,participantCount:a,onShareClick:l,waitingForInvite:c})=>{const{t:u}=ze();Zy(e.roomName);const f=_.useCallback(()=>{var K,B;return(B=(K=t.audio).setEnabled)==null?void 0:B.call(K,z=>!z)},[t]),p=_.useCallback(()=>{var K,B;return(B=(K=t.video).setEnabled)==null?void 0:B.call(K,z=>!z)},[t]),[m,v]=_.useState(!1),[g,S]=_.useState(M4),b=_.useCallback(()=>v(!0),[v]),w=_.useCallback(()=>v(!1),[v]),k=Na(),R=_.useCallback(()=>{var K;(K=k("/"))==null||K.catch(B=>{A.error("Failed to navigate to /",B)})},[k]),I=Ew("(max-height: 500px)"),C=!s&&E.jsx(ka,{className:wg.recents,to:"/",children:u("lobby.leave_button")}),x=uf(),O=Ip(()=>t.audio.enabled&&{deviceId:x.audioInput.selectedId}),N=_.useMemo(()=>({audio:Object.assign({},O),video:t.video.enabled&&{deviceId:x.videoInput.selectedId}}),[O,x.videoInput.selectedId,t.video.enabled]),D=_.useCallback(K=>{var B,z,W,V;A.error("Error while creating preview Tracks:",K),(z=(B=t.audio).setEnabled)==null||z.call(B,!1),(V=(W=t.video).setEnabled)==null||V.call(W,!1)},[t.audio,t.video]),j=Dje(N,D),U=_.useMemo(()=>(j==null?void 0:j.find(K=>K.kind===ue.Kind.Video))??null,[j]),H=Eee(ay(K=>K.pipe(Ne(([B])=>B)),[U]));return E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:Ae(wg.room,Mn.inRoom),children:[!o&&E.jsxs(Iu,{children:[E.jsx(sf,{children:E.jsx(DJ,{id:e.roomId,name:e.roomName,avatarUrl:e.roomAvatar,encrypted:e.e2eeSystem.kind!==Bt.NONE,participantCount:a})}),E.jsx(of,{children:l!==null&&E.jsx(See,{onClick:l})})]}),E.jsxs("div",{className:wg.content,children:[E.jsx(mUe,{matrixInfo:e,muteStates:t,videoTrack:U,children:E.jsx(At,{className:Ae(wg.join,{[wg.wait]:c}),size:c?"sm":"lg",onClick:()=>{c||r()},"data-testid":"lobby_joinCall",children:i??u("lobby.join_button")})}),!I&&C]}),E.jsxs("div",{className:Mn.footer,children:[I&&C,E.jsxs("div",{className:Mn.buttons,children:[E.jsx(eQ,{muted:!t.audio.enabled,onClick:f,disabled:t.audio.setEnabled===null}),E.jsx(tQ,{muted:!t.video.enabled,onClick:p,disabled:t.video.setEnabled===null}),H&&E.jsx(nQ,{onClick:H}),E.jsx(iQ,{onClick:b}),!s&&E.jsx(rQ,{onClick:R})]})]})]}),n&&E.jsx(A4,{client:n,open:m,onDismiss:w,tab:g,onTabChange:S})]})},vUe="_headline_1em2y_8",yUe="_callEndedContent_1em2y_15",_Ue="_callEndedButton_1em2y_35",bUe="_submitButton_1em2y_40",SUe="_container_1em2y_47",EUe="_main_1em2y_55",wUe="_footer_1em2y_72",_c={headline:vUe,callEndedContent:yUe,callEndedButton:_Ue,submitButton:bUe,container:SUe,main:EUe,footer:wUe},CUe="_starIcon_1m09w_8",TUe="_starRating_1m09w_12",RUe="_inputContainer_1m09w_18",IUe="_hideElement_1m09w_22",Tg={starIcon:CUe,starRating:TUe,inputContainer:RUe,hideElement:IUe},kUe=(n,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"M14 21.0267L22.24 26.0001L20.0533 16.6267L27.3333 10.3201L17.7466 9.50675L14 0.666748L10.2533 9.50675L0.666626 10.3201L7.94663 16.6267L5.75996 26.0001L14 21.0267Z",fill:"white"})),xUe=_.forwardRef(kUe),PUe=(n,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{id:"Vector",d:"M14 7.50675L15.2933 10.5601L15.92 12.0401L17.52 12.1734L20.8133 12.4534L18.3066 14.6267L17.0933 15.6801L17.4533 17.2534L18.2 20.4667L15.3733 18.7601L14 17.9067L12.6266 18.7334L9.79996 20.4401L10.5466 17.2267L10.9066 15.6534L9.69329 14.6001L7.18663 12.4267L10.48 12.1467L12.08 12.0134L12.7066 10.5334L14 7.50675M14 0.666748L10.2533 9.50675L0.666626 10.3201L7.94663 16.6267L5.75996 26.0001L14 21.0267L22.24 26.0001L20.0533 16.6267L27.3333 10.3201L17.7466 9.50675L14 0.666748Z",fill:"white"})),LUe=_.forwardRef(PUe);function OUe({starCount:n,onChange:e,required:t}){const[r,i]=_.useState(0),[s,o]=_.useState(0),{t:a}=ze();return E.jsx("div",{className:Tg.starRating,children:[...Array(n)].map((l,c)=>(c+=1,E.jsxs("div",{className:Tg.inputContainer,onMouseEnter:()=>o(c),onMouseLeave:()=>o(r),children:[E.jsx("input",{className:Tg.hideElement,type:"radio",id:"starInput"+String(c),value:String(c)+"Star",name:"star rating",onChange:u=>{i(c),e(c)},required:!0}),E.jsx("label",{className:Tg.hideElement,id:"starInvisibleLabel"+String(c),htmlFor:"starInput"+String(c),children:a("star_rating_input_label",{count:c})}),E.jsx("label",{className:Tg.starIcon,id:"starIcon"+String(c),htmlFor:"starInput"+String(c),children:c<=(s||r)?E.jsx(xUe,{}):E.jsx(LUe,{})})]},c)))})}const MUe=({client:n,isPasswordlessUser:e,confineToRoom:t,endedCallId:r})=>{const{t:i}=ze(),s=Na(),{displayName:o}=Jy(n),[a,l]=_.useState(!1),[c,u]=_.useState(0),[f,p]=_.useState(!1),[m,v]=_.useState(!1),g=_.useCallback(w=>{w.preventDefault();const R=new FormData(w.target).get("feedbackText");Et.instance.eventQualitySurvey.track(r,R,c),p(!0),setTimeout(()=>{v(!0),setTimeout(()=>{var I;e?l(!0):t||(I=s("/"))==null||I.catch(C=>{A.error("Failed to navigate to /",C)})},1e3)},1e3)},[r,s,e,t,c]),S=e&&E.jsxs("div",{className:_c.callEndedContent,children:[E.jsxs(Qi,{i18nKey:"call_ended_view.create_account_prompt",children:[E.jsx("p",{children:"Why not finish by setting up a password to keep your account?"}),E.jsx("p",{children:"You'll be able to keep your name and set an avatar for use on future calls"})]}),E.jsx(R4,{className:_c.callEndedButton,to:"/register",children:i("call_ended_view.create_account_button")})]}),b=E.jsxs("div",{className:_c.callEndedContent,children:[E.jsx(Qi,{i18nKey:"call_ended_view.feedback_prompt",children:E.jsx("p",{children:"We'd love to hear your feedback so we can improve your experience."})}),E.jsxs("form",{onSubmit:g,children:[E.jsx(vt,{children:E.jsx(OUe,{starCount:5,onChange:u,required:!0})}),E.jsx(vt,{children:E.jsx(_n,{className:pQ.feedback,id:"feedbackText",name:"feedbackText",label:i("settings.feedback_tab_description_label"),placeholder:i("settings.feedback_tab_description_label"),type:"textarea"})})," ",E.jsx(vt,{children:m?E.jsx(Qi,{i18nKey:"call_ended_view.feedback_done",children:E.jsx("p",{children:"Thanks for your feedback!"})}):E.jsx(At,{type:"submit",className:_c.submitButton,"data-testid":"home_go",children:i(f?"submitting":"action.submit")})})]})]});return E.jsxs(E.Fragment,{children:[E.jsxs(Iu,{children:[E.jsx(sf,{children:!t&&E.jsx(Vd,{})}),E.jsx(of,{})]}),E.jsxs("div",{className:_c.container,children:[E.jsxs("main",{className:_c.main,children:[E.jsx(Ru,{size:"xl",weight:"semibold",className:_c.headline,children:a?i("call_ended_view.headline",{displayName:o}):i("call_ended_view.headline",{displayName:o})+`
@@ -211,6 +211,6 @@ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},GI=t,G
211
211
  The chosen QR Code version cannot contain this amount of data.
212
212
  Minimum version required to store current data is: `+j+`.
213
213
  `);const U=k(x,O,D),H=n.getSymbolSize(x),K=new r(H);return m(K,x),v(K),g(K,x),b(K,O,0),x>=7&&S(K,x),w(K,U),isNaN(N)&&(N=o.getBestMask(K,b.bind(null,K,O))),o.applyMask(N,K),b(K,O,N),{modules:K,version:x,errorCorrectionLevel:O,maskPattern:N,segments:D}}return xI.create=function(x,O){if(typeof x>"u"||x==="")throw new Error("No input text");let N=e.M,D,j;return typeof O<"u"&&(N=e.from(O.errorCorrectionLevel,e.M),D=c.from(O.version),j=o.from(O.maskPattern),O.toSJISFunc&&n.setToSJISFunction(O.toSJISFunc)),I(x,D,N,j)},xI}var zI={},YI={},n$;function Bte(){return n$||(n$=1,function(n){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let r=t.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+t);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const i=parseInt(r.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+r.slice(0,6).join("")}}n.getOptions=function(r){r||(r={}),r.color||(r.color={});const i=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,o=r.scale||4;return{width:s,scale:s?4:o,margin:i,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},n.getScale=function(r,i){return i.width&&i.width>=r+i.margin*2?i.width/(r+i.margin*2):i.scale},n.getImageWidth=function(r,i){const s=n.getScale(r,i);return Math.floor((r+i.margin*2)*s)},n.qrToImageData=function(r,i,s){const o=i.modules.size,a=i.modules.data,l=n.getScale(o,s),c=Math.floor((o+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let m=0;m<c;m++){let v=(p*c+m)*4,g=s.color.light;if(p>=u&&m>=u&&p<c-u&&m<c-u){const S=Math.floor((p-u)/l),b=Math.floor((m-u)/l);g=f[a[S*o+b]?1:0]}r[v++]=g.r,r[v++]=g.g,r[v++]=g.b,r[v]=g.a}}}(YI)),YI}var r$;function Tqe(){return r$||(r$=1,function(n){const e=Bte();function t(i,s,o){i.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}n.render=function(s,o,a){let l=a,c=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(c=r()),l=e.getOptions(l);const u=e.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return e.qrToImageData(p.data,s,l),t(f,c,u),f.putImageData(p,0,0),c},n.renderToDataURL=function(s,o,a){let l=a;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const c=n.render(s,o,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}}(zI)),zI}var JI={},i$;function Rqe(){if(i$)return JI;i$=1;const n=Bte();function e(i,s){const o=i.a/255,a=s+'="'+i.hex+'"';return o<1?a+" "+s+'-opacity="'+o.toFixed(2).slice(1)+'"':a}function t(i,s,o){let a=i+s;return typeof o<"u"&&(a+=" "+o),a}function r(i,s,o){let a="",l=0,c=!1,u=0;for(let f=0;f<i.length;f++){const p=Math.floor(f%s),m=Math.floor(f/s);!p&&!c&&(c=!0),i[f]?(u++,f>0&&p>0&&i[f-1]||(a+=c?t("M",p+o,.5+m+o):t("m",l,0),l=0,c=!1),p+1<s&&i[f+1]||(a+=t("h",u),u=0)):l++}return a}return JI.render=function(s,o,a){const l=n.getOptions(o),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+e(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",m="<path "+e(l.color.dark,"stroke")+' d="'+r(u,c,l.margin)+'"/>',v='viewBox="0 0 '+f+" "+f+'"',S='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+v+' shape-rendering="crispEdges">'+p+m+`</svg>
214
- `;return typeof a=="function"&&a(null,S),S},JI}var s$;function Iqe(){if(s$)return lh;s$=1;const n=aqe(),e=Cqe(),t=Tqe(),r=Rqe();function i(s,o,a,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!n())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=a,a=o,o=l=void 0):f===3&&(o.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=o,o=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=o,o=l=void 0):f===2&&!o.getContext&&(l=a,a=o,o=void 0),new Promise(function(m,v){try{const g=e.create(a,l);m(s(g,o,l))}catch(g){v(g)}})}try{const m=e.create(a,l);c(null,s(m,o,l))}catch(m){c(m)}}return lh.create=e.create,lh.toCanvas=i.bind(null,t.render),lh.toDataURL=i.bind(null,t.renderToDataURL),lh.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),lh}var kqe=Iqe();const xqe="_qrCode_h54ia_8",Pqe={qrCode:xqe},Lqe=({data:n,className:e})=>{const[t,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return kqe.toDataURL(n,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[n]),E.jsx("div",{className:Ae(Pqe.qrCode,e),children:t&&E.jsx("img",{src:t,alt:Vo("qr_code")})})},Oqe=({room:n,open:e,onDismiss:t})=>{const{t:r}=ze(),i=Hw(n.roomId),s=_.useMemo(()=>jQ(n.roomId,i,n.name),[i,n.name,n.roomId]),[,o]=eqe(s),[a,l]=_.useState(!1),c=_.useCallback(()=>l(!1),[l]),u=_.useCallback(f=>{f.stopPropagation(),o(),t(),l(!0)},[o,t]);return E.jsxs(E.Fragment,{children:[E.jsxs(lf,{title:r("invite_modal.title"),open:e,onDismiss:t,children:[E.jsx(Lqe,{className:II.qrCode,data:s}),E.jsx(Xt,{className:II.url,size:"sm",weight:"semibold",children:s}),E.jsx(At,{className:II.button,Icon:z2e,onClick:u,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),E.jsx(oqe,{open:a,onDismiss:c,autoDismiss:2e3,Icon:UY,children:r("invite_modal.link_copied_toast")})]})},Mqe=({error:n,recoveryActionHandler:e,widget:t})=>{const{t:r}=ze();let i;switch(n.category){case jb.CONFIGURATION_ISSUE:i=W2e;break;case jb.NETWORK_CONNECTIVITY:i=Z2e;break;case jb.CLIENT_CONFIGURATION:i=fRe;break;default:i=ow}const s=[];return n instanceof hte&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>e("reconnect")}),E.jsx(Qh,{children:E.jsxs(uy,{Icon:i,title:n.localisedTitle,rageshake:n.code==iO.UNKNOWN_ERROR,widget:t,children:[E.jsx("p",{children:n.localisedMessage??E.jsx(Qi,{i18nKey:"error.unexpected_ec_error",components:[E.jsx("b",{}),E.jsx("code",{})],values:{errorCode:n.code}})}),s&&s.map((o,a)=>E.jsx("button",{onClick:o.onClick,children:o.label},`action${a}`))]})})},Aqe=({recoveryActionHandler:n,onError:e,children:t,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof $a?s:new sO(s instanceof Error?s:new Error);return E.jsx(Mqe,{widget:r??null,error:a,resetError:o,recoveryActionHandler:l=>{o(),n(l)}})},[n,r]);return E.jsx(sw,{fallback:i,onError:s=>e==null?void 0:e(s),children:t})},Nqe=({client:n,isPasswordlessUser:e,confineToRoom:t,preload:r,skipLobby:i,hideHeader:s,rtcSession:o,isJoined:a,muteStates:l,widget:c})=>{const[u,f]=_.useState(null),p=oQ(o),m=xl(lO({sounds:jte,latencyHint:"interactive"}));_.useEffect(()=>{var pe,ve;p.length>=FVe&&((ve=(pe=l.audio).setEnabled)==null||ve.call(pe,!1))},[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),Sw(o,ar.MembershipManagerError,pe=>{f(new rHe(iO.MEMBERSHIP_MANAGER_UNRECOVERABLE,pe.message??pe))}),_.useEffect(()=>{n.getRoom(o.room.roomId)!==o.room&&A.warn(`We've ended up with multiple rooms for the same ID (${o.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`)},[n,o.room]);const v=o.room,{displayName:g,avatarUrl:S}=Jy(n),b=zVe(v),w=WVe(v),{perParticipantE2EE:k,returnToLobby:R}=ku(),I=Hw(v.roomId),[C]=Xn(ZZ),[x]=Xn(T4);Zy(b);const O=_.useMemo(()=>({userId:n.getUserId(),displayName:g,avatarUrl:S,roomId:v.roomId,roomName:b,roomAlias:v.getCanonicalAlias(),roomAvatar:w,e2eeSystem:I}),[n,g,S,b,v,w,I]),N=_.useMemo(()=>new Set(p.map(pe=>pe.sender)).size,[p]),D=uf(),j=xl(D),U=xl(l),H=_.useCallback(async pe=>{try{await KVe(pe,k,C,x)}catch(ve){if(ve instanceof $a)f(ve);else{A.error("Unknown Error while entering RTC session",ve);const Ee=new sO(ve instanceof Error?ve:new Error("Unknown error",{cause:ve}));f(Ee)}}},[k,x,C]);_.useEffect(()=>{const pe=async({audioInput:ve,videoInput:Ee})=>{var zt,ln,Yt,Fe;const Ke=await Ol.getLocalDevices(void 0,!0);if(ve){const _t=bU(ve,"audioinput",Ke);_t?(A.debug(`Found audio input ID ${_t} for name ${ve}`),j.current.audioInput.select(_t)):(A.warn("Unknown audio input: "+ve),(ln=(zt=U.current.audio).setEnabled)==null||ln.call(zt,!1))}if(Ee){const _t=bU(Ee,"videoinput",Ke);_t?(A.debug(`Found video input ID ${_t} for name ${Ee}`),j.current.videoInput.select(_t)):(A.warn("Unknown video input: "+Ee),(Fe=(Yt=U.current.video).setEnabled)==null||Fe.call(Yt,!1))}};if(i)if(c)if(r){const ve=Ee=>{(async()=>{await pe(Ee.detail.data),await H(o),c.api.transport.reply(Ee.detail,{})})().catch(Ke=>{A.error("Error joining RTC session",Ke)})};return c.lazyActions.on(Ar.JoinCall,ve),()=>{c.lazyActions.off(Ar.JoinCall,ve)}}else(async()=>{await H(o)})().catch(ve=>{A.error("Error joining RTC session",ve)});else H(o)},[c,o,r,i,k,j,U,H,C]);const[K,B]=_.useState(!1),z=Na(),W=_.useCallback((pe="user")=>{var zt;const ve=(zt=m.current)==null?void 0:zt.playSound("left"),Ee=!!c;B(!0);const Ke=new Promise(ln=>{Et.instance.eventCallEnded.track(v.roomId,o.memberships.length,Ee,o),window.setTimeout(ln,10)});xF(o,pe,Promise.all([ve,Ke])).then(async()=>{!e&&!t&&!Et.instance.isEnabled()&&await z("/")}).catch(ln=>{A.error("Error leaving RTC session",ln)})},[m,c,o,v.roomId,e,t,z]);_.useEffect(()=>{if(c&&a){c.api.setAlwaysOnScreen(!0).catch(ve=>{A.error("Error calling setAlwaysOnScreen(true)",ve)});const pe=ve=>{c.api.transport.reply(ve.detail,{}),xF(o,"user").catch(Ee=>{A.error("Failed to leave RTC session",Ee)})};return c.lazyActions.once(Ar.HangupCall,pe),()=>{c.lazyActions.off(Ar.HangupCall,pe)}}},[c,a,o]);const V=YVe(v),[q,X]=_.useState(!1),G=_.useCallback(()=>X(!1),[X]),Q=_.useCallback(()=>X(!0),[X]),me=V===Wc.Public?Q:null;if(!DV()&&I.kind!==Bt.NONE)throw new iHe;const Se=E.jsx(Oqe,{room:v,open:q,onDismiss:G}),xe=E.jsxs(E.Fragment,{children:[Se,E.jsx(wee,{client:n,matrixInfo:O,muteStates:l,onEnter:()=>void H(o),confineToRoom:t,hideHeader:s,participantCount:N,onShareClick:me})]});let fe;if(u){const pe=()=>{throw u};fe=E.jsx(pe,{})}else a?fe=E.jsxs(E.Fragment,{children:[Se,E.jsx(jVe,{client:n,matrixInfo:O,rtcSession:o,participantCount:N,onLeave:W,hideHeader:s,muteStates:l,e2eeSystem:I,onShareClick:me})]}):K&&c===null?e||Et.instance.isEnabled()&&c===null?fe=E.jsx(MUe,{endedCallId:o.room.roomId,client:n,isPasswordlessUser:e,confineToRoom:t}):fe=null:K&&c!==null?fe=R?xe:null:r||i?fe=null:fe=xe;return E.jsx(Aqe,{widget:c,recoveryActionHandler:pe=>{pe=="reconnect"&&(B(!1),H(o).catch(ve=>{A.error("Error re-entering RTC session",ve)}))},onError:()=>{o.isJoined()&&W("error")},children:fe})},Dqe="_modal_1tnec_8",jqe={modal:Dqe},Uqe=({roomId:n})=>{const{t:e}=ze(),[t,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=Hw(n);s.kind===Bt.NONE&&A.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(n===null?window.location.href:jQ(n,s));a.hash=w3e(a.hash,c=>(c.set("appPrompt","false"),c.set("confineToRoom","true"),c));const l=new URL("io.element.call:/");return l.searchParams.set("url",a.toString()),l.toString()},[s,n]);return E.jsxs(lf,{className:jqe.modal,title:e("app_selection_modal.title"),open:t,children:[E.jsx(Xt,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),E.jsx(At,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),E.jsx(At,{as:"a",href:o,Icon:gJ,children:e("app_selection_modal.open_in_app")})]})},Fqe=3,$qe=3e3;async function Vte(n,e=0,...t){try{return await n.joinRoom(...t)}catch(r){if(r instanceof bn&&r.errcode==="M_FORBIDDEN"&&e<Fqe)return await new Promise(i=>setTimeout(i,$qe)),Vte(n,e+1,...t);throw r}}class $b extends Error{constructor(e,t,r,i){super(t),this.icon=e,this.messageBody=r,this.reason=i}}const Hqe=(n,e,t)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=ze(),a=_.useCallback(()=>new $b(B2e,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),u()),[o]),l=_.useCallback(()=>new $b(aw,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),u()),[o]),c=_.useCallback(()=>new $b(tJ,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),u()),[o]),u=()=>{var f,p,m;return(m=(p=s.current)==null?void 0:p.currentState.getStateEvents(ee.RoomMember,(f=s.current)==null?void 0:f.myUserId))==null?void 0:m.getContent().reason};return _.useEffect(()=>{if(!n||!e)return;const f=async b=>{let w=null;const k=await n.getRoomIdForAlias(b.toLowerCase());return A.info(`${b} resolved to ${k.room_id}`),w=n.getRoom(k.room_id),w?A.info(`Already in room ${k.room_id}, not rejoining.`):(A.info(`Room ${k.room_id} not found, joining.`),w=await n.joinRoom(k.room_id,{viaServers:k.servers})),w},p=async(b,w,k)=>(await n.knockRoom(b,{viaServers:w}),k(),await new Promise((R,I)=>{n.on(ke.MyMembership,(C,x,O)=>{b===C.roomId&&(s.current=C,x===qe.Invite&&O===qe.Knock&&Vte(n,0,C.roomId,{viaServers:w}).then(N=>{A.log("Auto-joined %s",N.roomId),R(N)},I),x===qe.Ban&&I(a()),x===qe.Leave&&I(l()))})})),m=async()=>{let b=null;if(e[0]==="#")b=await f(e),s.current=b;else{const w=e;b=n.getRoom(w),s.current=b??void 0;const k=b==null?void 0:b.getMyMembership();if(k===qe.Join)return b;if(Ge)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(k===qe.Ban)throw a();if(k===qe.Invite)b=await n.joinRoom(w,{viaServers:t});else{let R;try{R=await n.getRoomSummary(w,t)}catch(I){A.warn("Could not load room summary to decide whether we want to join or knock.\n EC will fallback to join as if this would be a public room.\n Reach out to your homeserver admin to ask them about supporting the `/summary` endpoint (im.nheko.summary):",I)}if(R===void 0||R.join_rule===Wc.Public)b=await n.joinRoom(w,{viaServers:t});else if(R.join_rule===Wc.Knock){const I=R;let C=()=>{};const x=new Promise(O=>{I.membership!==qe.Knock?C=O:O()});i({kind:"canKnock",roomSummary:I,knock:C}),await x,b=await p(R.room_id,t,()=>i({kind:"waitForInvite",roomSummary:I}))}else throw new Error(`Room ${R.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return A.info(`Joined ${e}, waiting room to be ready for group calls`),await n.waitUntilRoomReadyForGroupCalls(b.roomId),A.info(`${e}, is ready for group calls`),b},v=async()=>{const b=await m();return s.current=b,A.debug(`Fetched / joined room ${e}`),n.matrixRTC.getRoomSession(b)},g=async()=>{n.getSyncState()!==Dt.Syncing&&(A.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(b=>{const w=()=>{if(n.getSyncState()===Dt.Syncing)return n.off(Oe.Sync,w),b()};n.on(Oe.Sync,w)}),A.debug("useLoadGroupCall: client is now syncing."))},S=async()=>{await new Promise((b,w)=>{n.on(ke.MyMembership,(k,R)=>{R===qe.Leave&&w(c()),R===qe.Ban&&w(a())})})};r.kind==="loading"&&(A.log("Start loading group call"),g().then(v).then(b=>i({kind:"loaded",rtcSession:b})).then(S).catch(b=>i({kind:"failed",error:b})))},[a,n,l,c,e,r,o,t]),r};function Bqe(n){const[,e]=_.useState(0);return _.useEffect(()=>{if(n!==void 0){const t=r=>{A.info(`Session in room ${n.room.roomId} changed to ${r?"joined":"left"}`),e(i=>i+1)};return n.on(ar.JoinStateChanged,t),()=>{n.off(ar.JoinStateChanged,t)}}},[n]),(n==null?void 0:n.isJoined())??!1}const Vqe=()=>{const{confineToRoom:n,appPrompt:e,preload:t,hideHeader:r,displayName:i,skipLobby:s}=ku(),{t:o}=ze(),{roomAlias:a,roomId:l,viaServers:c}=T3e(),u=l??a;u||A.error("No room specified");const{registerPasswordlessUser:f}=BQ(),[p,m]=_.useState(!1),{loading:v,authenticated:g,client:S,error:b,passwordlessUser:w}=x4(),{avatarUrl:k,displayName:R}=Jy(S),I=Hqe(S,u,c),C=Bqe(I.kind==="loaded"?I.rtcSession:void 0),x=HVe(C);_.useEffect(()=>{!v&&!g&&i&&!Ge&&(m(!0),f(i).catch(H=>{A.error("Failed to register passwordless user",H)}).finally(()=>{m(!1)}))},[v,g,i,m,f]);const[O,N]=Aw();_.useEffect(()=>{O===null&&N&&N(!0)},[O,N]);const D=_.useRef(!1);_.useEffect(()=>{I.kind==="loaded"&&D.current&&A.log("Play join sound 'Not yet implemented'")},[I.kind]);const j=()=>{switch(I.kind){case"loaded":return E.jsx(Nqe,{widget:Ge,client:S,rtcSession:I.rtcSession,isJoined:C,isPasswordlessUser:w,confineToRoom:n,preload:t,skipLobby:s||D.current,hideHeader:r,muteStates:x});case"waitForInvite":case"canKnock":{D.current=D.current||I.kind==="waitForInvite";const H=I.kind==="canKnock"?I.knock:null,K=I.kind==="canKnock"?o("lobby.ask_to_join"):E.jsxs(E.Fragment,{children:[o("lobby.waiting_for_invite"),E.jsx(UY,{})]});return E.jsx(wee,{client:S,matrixInfo:{userId:S.getUserId()??"",displayName:R??"",avatarUrl:k??"",roomAlias:null,roomId:I.roomSummary.room_id,roomName:I.roomSummary.name??"",roomAvatar:I.roomSummary.avatar_url??null,e2eeSystem:{kind:I.roomSummary["im.nheko.summary.encryption"]?Bt.PER_PARTICIPANT:Bt.NONE}},onEnter:()=>H==null?void 0:H(),enterLabel:K,waitingForInvite:I.kind==="waitForInvite",confineToRoom:n,hideHeader:r,participantCount:null,muteStates:x,onShareClick:null})}case"loading":return E.jsx(Qh,{children:E.jsx("h1",{children:o("common.loading")})});case"failed":return D.current=!1,I.error.errcode==="M_NOT_FOUND"?E.jsx(Qh,{children:E.jsx(uy,{Icon:oRe,title:o("error.call_not_found"),widget:Ge,children:E.jsx(Qi,{i18nKey:"error.call_not_found_description",children:E.jsxs("p",{children:["That link doesn't appear to belong to any existing call. Check that you have the right link, or"," ",E.jsx(ka,{to:"/",children:"create a new one"}),"."]})})})}):I.error instanceof $b?E.jsx(Qh,{children:E.jsxs(uy,{Icon:I.error.icon,title:I.error.message,widget:Ge,children:[E.jsx("p",{children:I.error.messageBody}),I.error.reason&&E.jsx("p",{children:o("group_call_loader.reason",{reason:I.error.reason})})]})}):E.jsx(dy,{widget:Ge,error:I.error});default:return E.jsx(E.Fragment,{children:" "})}};let U;return v||p?U=E.jsx(Uw,{}):b?U=E.jsx(dy,{widget:Ge,error:b}):S?u?U=j():U=E.jsx($Q,{}):U=E.jsx(Q7e,{}),E.jsxs(E.Fragment,{children:[U,e&&Ht.get().app_prompt&&(Od==="android"||Od==="ios")&&l&&E.jsx(Uqe,{roomId:l})]})},qqe="_banner_sye6n_8",Kqe={banner:qqe},Gqe=({children:n,className:e,...t})=>{const{t:r}=ze(),i=nm();let s=!1;return(i==null?void 0:i.state)==="valid"&&(s=i.disconnected),E.jsx(E.Fragment,{children:s&&E.jsxs("div",{className:Ae(Kqe.banner,e),...t,children:[n,r("disconnected_banner")]})})},Wqe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQvNC10L3RjiIKICB9LAogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAi0JfQsNGC0LLQvtGA0LgiLAogICAgImNvcHlfbGluayI6ICLQmtC+0L/QuNGA0LDQvdC1INC90LAg0LLRgNGK0LfQutCw0YLQsCIsCiAgICAiZ28iOiAi0J3QsNC/0YDQtdC0IiwKICAgICJpbnZpdGUiOiAi0J/QvtC60LDQvdCwIiwKICAgICJubyI6ICLQndC1IiwKICAgICJyZWdpc3RlciI6ICLQoNC10LPQuNGB0YLRgNCw0YbQuNGPIiwKICAgICJyZW1vdmUiOiAi0J/RgNC10LzQsNGF0L3QuCIsCiAgICAic2lnbl9pbiI6ICLQktC70LXQtyIsCiAgICAic2lnbl9vdXQiOiAi0JjQt9C70LXQtyIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogItCh0YrQt9C00LDQuSDQsNC60LDRg9C90YIiLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD7Ql9Cw0YnQviDQvdC1INC90LDRgdGC0YDQvtC50YLQtSDQv9Cw0YDQvtC70LAg0LfQsCDQtNCwINC30LDQv9Cw0LfQuNGC0LUg0LDQutCw0YPQvdGC0LAg0YHQuD88LzA+PDE+0KnQtSDQvNC+0LbQtdGC0LUg0LTQsCDQt9Cw0L/QsNC30LjRgtC1INC40LzQtdGC0L4g0Lgg0LDQstCw0YLQsNGA0LAg0YHQuCDQt9CwINCx0YrQtNC10YnQuCDRgNCw0LfQs9C+0LLQvtGA0Lg8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLQndC1INGB0LXQs9CwLCDQstGK0YDQvdC4INGB0LUg0L3QsCDQvdCw0YfQsNC70L3QuNGPINC10LrRgNCw0L0iCiAgfSwKICAiY29tbW9uIjogewogICAgImF1ZGlvIjogItCX0LLRg9C6IiwKICAgICJhdmF0YXIiOiAi0JDQstCw0YLQsNGAIiwKICAgICJkaXNwbGF5X25hbWUiOiAi0JjQvNC1L9C/0YHQtdCy0LTQvtC90LjQvCIsCiAgICAiaG9tZSI6ICLQndCw0YfQsNC70L4iLAogICAgImxvYWRpbmciOiAi0JfQsNGA0LXQttC00LDQvdC14oCmIiwKICAgICJwYXNzd29yZCI6ICLQn9Cw0YDQvtC70LAiLAogICAgInByb2ZpbGUiOiAi0J/RgNC+0YTQuNC7IiwKICAgICJzZXR0aW5ncyI6ICLQndCw0YHRgtGA0L7QudC60LgiLAogICAgInVzZXJuYW1lIjogItCf0L7RgtGA0LXQsdC40YLQtdC70YHQutC+INC40LzQtSIsCiAgICAidmlkZW8iOiAi0JLQuNC00LXQviIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi0JTQsCwg0L/RgNC40YHRitC10LTQuNC90Lgg0YHQtSIsCiAgICAidGV4dCI6ICLQotC+0LfQuCDRgNCw0LfQs9C+0LLQvtGAINCy0LXRh9C1INGB0YrRidC10YHRgtCy0YPQstCwLCDQuNGB0LrQsNGC0LUg0LvQuCDQtNCwINGB0LUg0L/RgNC40YHRitC10LTQuNC90LjRgtC1PyIsCiAgICAidGl0bGUiOiAi0J/RgNC40YHRitC10LTQuNC90Y/QstCw0L3QtSDQutGK0Lwg0YHRitGJ0LXRgdGC0LLRg9Cy0LDRiSDRgNCw0LfQs9C+0LLQvtGAPyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItCf0YDQvtC20LXQutGC0L7RgCIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItCS0LvQtdC3INCyINGA0LDQt9Cz0L7QstC+0YDQsCIKICB9LAogICJsb2dnaW5nX2luIjogItCS0LvQuNC30LDQvdC14oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD7QodGK0LfQtNCw0LnRgtC1INCw0LrQsNGD0L3RgjwvMD4g0LjQu9C4IDwyPtCS0LvQtdC30YLQtSDQutCw0YLQviDQs9C+0YHRgjwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLQktC70LXQtyIsCiAgInJhZ2VzaGFrZV9yZXF1ZXN0X21vZGFsIjogewogICAgImJvZHkiOiAi0JTRgNGD0LMg0L/QvtGC0YDQtdCx0LjRgtC10Lsg0LIg0YLQvtC30Lgg0YDQsNC30LPQvtCy0L7RgCDQuNC80LAg0L/RgNC+0LHQu9C10LwuINCX0LAg0LTQsCDQtNC40LDQs9C90L7RgdGC0LjRhtC40YDQsNC80LUg0YLQvtC30Lgg0L/RgNC+0LHQu9C10Lwg0L/Qvi3QtNC+0LHRgNC1INC90Lgg0YHQtSDQuNGB0LrQsCDQtNCwINGB0YrQsdC10YDQtdC8IGRlYnVnINC70L7Qs9C+0LLQtS4iLAogICAgInRpdGxlIjogItCX0LDRj9Cy0LrQsCDQt9CwIGRlYnVnINC70L7Qs9C+0LLQtSIKICB9LAogICJyYWdlc2hha2Vfc2VuZF9sb2dzIjogItCY0LfQv9GA0LDRgtC10YLQtSBkZWJ1ZyDQu9C+0LPQvtCy0LUiLAogICJyYWdlc2hha2Vfc2VuZGluZyI6ICLQmNC30L/RgNCw0YnQsNC90LXigKYiLAogICJyZWNhcHRjaGFfZGlzbWlzc2VkIjogIlJlY2FwdGNoYSDQvtGC0YXQstGK0YDQu9C10L3QsCIsCiAgInJlY2FwdGNoYV9ub3RfbG9hZGVkIjogIlJlY2FwdGNoYSDQvdC1INC1INC30LDRgNC10LTQtdC90LAiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICLQn9Cw0YDQvtC70LjRgtC1INC90LUg0YHRitCy0L/QsNC00LDRgiIsCiAgICAicmVnaXN0ZXJpbmciOiAi0KDQtdCz0LjRgdGC0YDQuNGA0LDQvdC14oCmIgogIH0sCiAgInJlZ2lzdGVyX2F1dGhfbGlua3MiOiAiPDA+0JLQtdGH0LUg0LjQvNCw0YLQtSDQsNC60LDRg9C90YI/PC8wPjwxPjwwPtCS0LvQtdC30YLQtSDRgSDQvdC10LPQvjwvMD4g0LjQu9C4IDwyPtCS0LvQtdC30YLQtSDQutCw0YLQviDQs9C+0YHRgjwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLQn9C+0YLQstGK0YDQtNC4INC/0LDRgNC+0LvQsNGC0LAiLAogICJyZXR1cm5faG9tZV9idXR0b24iOiAi0JLRgNGK0YnQsNC90LUg0L3QsCDQvdCw0YfQsNC70L3QuNGPINC10LrRgNCw0L0iLAogICJzY3JlZW5zaGFyZV9idXR0b25fbGFiZWwiOiAi0KHQv9C+0LTQtdC70Lgg0LXQutGA0LDQvdCwIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLQoNCw0LfRgNCw0LHQvtGC0YfQuNC6IiwKICAgICJmZWVkYmFja190YWJfaDQiOiAi0JjQt9C/0YDQsNGC0Lgg0L7QsdGA0LDRgtC90LAg0LLRgNGK0LfQutCwIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogItCS0LrQu9GO0YfQuCBkZWJ1ZyDQu9C+0LPQvtCy0LUiCiAgfSwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfYm9keSI6ICLQktGB0LUg0L7RidC1INC90LUg0YHRgtC1INGA0LXQs9C40YHRgtGA0LjRgNCw0L3QuD8gPDI+0KHRitC30LTQsNC50YLQtSDQsNC60LDRg9C90YI8LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogItCS0LvQtdC30YLQtSDQsiDQsNC60LDRg9C90YLQsCDRgdC4IiwKICAidmVyc2lvbiI6ICLQktC10YDRgdC40Y86IHt7dmVyc2lvbn19Igp9Cg==",zqe=""+new URL("cs-app-BIDxiN50.json",import.meta.url).href,Yqe=""+new URL("de-app-Dn3BQmuZ.json",import.meta.url).href,Jqe=""+new URL("el-app-Bgiig2Nz.json",import.meta.url).href,Xqe=""+new URL("en-app-D0dSboZP.json",import.meta.url).href,Zqe=""+new URL("es-app-Q3c7lmEj.json",import.meta.url).href,Qqe=""+new URL("et-app-DPt7J6kw.json",import.meta.url).href,eKe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLZgdmH2LHYs9iqINqp2KfYsdio2LEiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogItio2LPYqtmGIiwKICAgICJnbyI6ICLYsdmB2KrZhiIsCiAgICAibm8iOiAi2K7bjNixIiwKICAgICJyZWdpc3RlciI6ICLYq9io2KrigIzZhtin2YUiLAogICAgInJlbW92ZSI6ICLYrdiw2YEiLAogICAgInNpZ25faW4iOiAi2YjYsdmI2K8iLAogICAgInNpZ25fb3V0IjogItiu2LHZiNisIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAi2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+2obYsdinINuM2qkg2LHZhdiyINi52KjZiNixINio2LHYp9uMINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2KrZhti424zZhSDZhtmF24zigIzaqdmG24zYr9ifPC8wPjwxPti02YXYpyDZhduM4oCM2KrZiNin2YbbjNivINmG2KfZhSDYrtmI2K8g2LHYpyDYrdmB2Lgg2qnZhtuM2K8g2Ygg24zaqSDYotmI2KfYqtin2LEg2KjYsdin24wg2KrZhdin2LPigIzZh9in24wg2KLbjNmG2K/ZhyDYqNiz2KfYstuM2K88LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLYp9mE2KfZhiDZhtmH2Iwg2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCDYqNix2q/Ysdiv24zYryIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi2LXYr9inIiwKICAgICJhdmF0YXIiOiAi2KLZiNin2KrYp9ixIiwKICAgICJkaXNwbGF5X25hbWUiOiAi2YbYp9mFINmG2YXYp9uM2LTbjCIsCiAgICAiaG9tZSI6ICLYrtin2YbZhyIsCiAgICAibG9hZGluZyI6ICLYqNin2LHar9iy2KfYsduM4oCmIiwKICAgICJwYXNzd29yZCI6ICLYsdmF2LIg2LnYqNmI2LEiLAogICAgInByb2ZpbGUiOiAi2b7YsdmI2YHYp9uM2YQiLAogICAgInNldHRpbmdzIjogItiq2YbYuNuM2YXYp9iqIiwKICAgICJ1c2VybmFtZSI6ICLZhtin2YUg2qnYp9ix2KjYsduMIiwKICAgICJ2aWRlbyI6ICLZiNuM2K/bjNmIIgogIH0sCiAgImhlYWRlcl9sYWJlbCI6ICLYrtin2YbZh9mUINiq2YXYp9izINin2YTZhdmG2KoiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi2KjZhNmH2Iwg2KjZhyDYqtmF2KfYsyDYqNm+24zZiNmG2K/bjNivIiwKICAgICJ0ZXh0IjogItin24zZhiDYqtmF2KfYsyDYp9iyINmC2KjZhCDZiNis2YjYryDYr9in2LHYr9iMINmF24zigIzYrtmI2KfZh9uM2K8g2KjZvtuM2YjZhtiv24zYr9ifIiwKICAgICJ0aXRsZSI6ICLZvtuM2YjYs9iqINio2Ycg2KrZhdin2LPYnyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItmG2YjYsSDYp9mB2qnZhiIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItm+24zZiNiz2KrZhiDYqNmHINiq2YXYp9izIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi2YjYsdmI2K/igKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPtiz2KfYrtiqINit2LPYp9ioINqp2KfYsdio2LHbjDwvMD4gT3IgPDI+2K/Ys9iq2LHYs9uMINio2Ycg2LnZhtmI2KfZhiDZhduM2YfZhdin2YY8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi2YjYsdmI2K8iLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItqp2KfYsdio2LEg2K/bjNqv2LHbjCDYr9ixINin24zZhiDYqtmF2KfYsyDZhdi02qnZhNuMINiv2KfYsdivLiDYqNix2KfbjCDYqti02K7bjNi1INio2YfYqtixINmF2LTaqdmE2Iwg2KjZh9iq2LEg2KfYs9iqINmF2Kcg2YTYp9qvINi524zYqOKAjNuM2KfYqNuMINix2Kcg2KzZhdi54oCM2KLZiNix24wg2qnZhtuM2YUuIiwKICAgICJ0aXRsZSI6ICLYr9ix2K7ZiNin2LPYqiDZhNin2q8g2LnbjNio4oCM24zYp9io24wiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLYp9ix2LPYp9mEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YTigKYiLAogICJyYWdlc2hha2Vfc2VuZGluZ19sb2dzIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YQg2KjYp9qv4oCM2YfYp9uMINi524zYqOKAjNuM2KfYqNuM4oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICLYsduM2qnZvtqG2Kcg2LHYryDYtNivIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAi2qnZvtqG2Kcg2KjYp9ix2q/bjNix24wg2YbYtNivIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi2LHZhdiyINi52KjZiNixINio2KfbjNivINmH2YXYrtmI2KfZhtuMINiv2KfYtNiq2Ycg2KjYp9i02K8iLAogICAgInJlZ2lzdGVyaW5nIjogItir2KjYquKAjNmG2KfZheKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtin2LIg2YLYqNmEINit2LPYp9ioINqp2KfYsdio2LHbjCDYr9in2LHbjNiv2J88LzA+PDE+PDA+2YjYsdmI2K88LzA+IE9yIDwyPtio2Ycg2LnZhtmI2KfZhiDbjNqpINmF24zZh9mF2KfZhiDZiNin2LHYryDYtNmI24zYrzwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLYqtin24zbjNivINix2YXYsti52KjZiNixIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItio2LHar9i02Kog2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCIsCiAgInNjcmVlbnNoYXJlX2J1dHRvbl9sYWJlbCI6ICLYp9i02KrYsdin2qkg2q/YsNin2LHbjCDYtdmB2K3ZhyDZhtmF2KfbjNi0IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLYqtmI2LPYudmHINiv2YfZhtiv2YciLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICLYqNin2LLYrtmI2LHYryDYp9ix2KfYptmHINiv2YfbjNivIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIti02KfZhdmEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogItmH2YbZiNiyINir2KjYquKAjNmG2KfZhSDZhtqp2LHYr9mH4oCM2KfbjNiv2J8gPDI+2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLYqNmHINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2YjYp9ix2K8g2LTZiNuM2K8iLAogICJ2ZXJzaW9uIjogItmG2LPYrtmHOiB7e9mG2LPYrtmHfX0iCn0K",tKe=""+new URL("fr-app-BxTYbDfK.json",import.meta.url).href,nKe=""+new URL("id-app-B-8jUQf1.json",import.meta.url).href,rKe=""+new URL("it-app-Cik25Qgd.json",import.meta.url).href,iKe=""+new URL("ja-app-Cp_00ujI.json",import.meta.url).href,sKe=""+new URL("lv-app-J9DGb4uv.json",import.meta.url).href,oKe=""+new URL("pl-app-CUkXVSZk.json",import.meta.url).href,aKe=""+new URL("ro-app-KHxgbZz-.json",import.meta.url).href,lKe=""+new URL("ru-app-eoBdfBL5.json",import.meta.url).href,cKe=""+new URL("sk-app-oyZEXyo9.json",import.meta.url).href,uKe=""+new URL("sv-app-D3UhBwmo.json",import.meta.url).href,dKe=""+new URL("tr-app-Dk--6BpP.json",import.meta.url).href,fKe=""+new URL("uk-app-8w2P6iQj.json",import.meta.url).href,hKe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAixJDDs25nIiwKICAgICJubyI6ICJLaMO0bmciLAogICAgInJlZ2lzdGVyIjogIsSQxINuZyBrw70iLAogICAgInNpZ25faW4iOiAixJDEg25nIG5o4bqtcCIsCiAgICAic2lnbl9vdXQiOiAixJDEg25nIHh14bqldCIsCiAgICAic3VibWl0IjogIkfhu61pIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAiVOG6oW8gdMOgaSBraG/huqNuIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+VOG6oWkgc2FvIGzhuqFpIGtow7RuZyBob8OgbiB0aGnhu4duIGLhurFuZyBjw6FjaCDEkeG6t3QgbeG6rXQga2jhuql1IMSR4buDIGdp4buvIHTDoGkga2hv4bqjbiBj4bunYSBi4bqhbj88LzA+PDE+QuG6oW4gc+G6vSBjw7MgdGjhu4MgZ2nhu68gdMOqbiB2w6AgxJHhurd0IOG6o25oIMSR4bqhaSBkaeG7h24gY2hvIG5o4buvbmcgY3Xhu5ljIGfhu41pIHRp4bq/cCB0aGVvLjwvMT4iLAogICAgImZlZWRiYWNrX2RvbmUiOiAiPDA+Q+G6o20gaMahbiB2w6wgxJHDoyBwaOG6o24gaOG7k2khPC8wPiIsCiAgICAiZmVlZGJhY2tfcHJvbXB0IjogIjwwPkNow7puZyB0w7RpIG114buRbiBuZ2hlIHBo4bqjbiBo4buTaSBj4bunYSBi4bqhbiDEkeG7gyBjw7JuIGPhuqNpIHRoaeG7h24gdHLhuqNpIG5naGnhu4dtIGNobyBi4bqhbi48LzA+IiwKICAgICJoZWFkbGluZSI6ICJ7e2Rpc3BsYXlOYW1lfX0sIGN14buZYyBn4buNaSDEkcOjIGvhur90IHRow7pjLiIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiw4JtIHRoYW5oIiwKICAgICJhdmF0YXIiOiAi4bqibmggxJHhuqFpIGRp4buHbiIsCiAgICAiZGlzcGxheV9uYW1lIjogIlTDqm4gaGnhu4NuIHRo4buLIiwKICAgICJsb2FkaW5nIjogIsSQYW5nIHThuqNp4oCmIiwKICAgICJwYXNzd29yZCI6ICJN4bqtdCBraOG6qXUiLAogICAgInByb2ZpbGUiOiAiSOG7kyBzxqEiLAogICAgInNldHRpbmdzIjogIkPDoGkgxJHhurd0IiwKICAgICJ1c2VybmFtZSI6ICJUw6puIG5nxrDhu51pIGTDuW5nIiwKICAgICJ2aWRlbyI6ICJUcnV54buBbiBow6xuaCIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAiVsOibmcsIHRoYW0gZ2lhIGN14buZYyBn4buNaSIsCiAgICAidGV4dCI6ICJDdeG7mWMgZ+G7jWkgxJHDoyB04buTbiB04bqhaSwgYuG6oW4gY8OzIG114buRbiB0aGFtIGdpYSBraMO0bmc/IiwKICAgICJ0aXRsZSI6ICJUaGFtIGdpYSBjdeG7mWMgZ+G7jWk/IgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAiVGnDqnUgxJFp4buDbSIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIlRoYW0gZ2lhIGN14buZYyBn4buNaSIKICB9LAogICJsb2dnaW5nX2luIjogIsSQYW5nIMSRxINuZyBuaOG6rXDigKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPlThuqFvIHTDoGkga2hv4bqjbjwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBraMOhYzwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLEkMSDbmcgbmjhuq1wIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJN4buZdCBuZ8aw4budaSBkw7luZyBraMOhYyB0cm9uZyBjdeG7mWMgZ+G7jWkgxJFhbmcgZ+G6t3AgduG6pW4gxJHhu4EuIMSQ4buDIGPDsyB0aOG7gyBjaOG6qW4gxJFvw6FuIHThu5F0IGjGoW4gY2jDum5nIHTDtGkgbXXhu5FuIHRodSB0aOG6rXAgbmjhuq10IGvDvSBn4buhIGzhu5dpLiIsCiAgICAidGl0bGUiOiAiWcOqdSBj4bqndSBuaOG6rXQga8O9IGfhu6EgbOG7l2kiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAixJBhbmcgZ+G7rWnigKYiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJDaMawYSB04bqjaSDEkcaw4bujYyBSZWNhcHRjaGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJN4bqtdCBraOG6qXUgcGjhuqNpIGto4bubcCIsCiAgICAicmVnaXN0ZXJpbmciOiAixJBhbmcgxJHEg25nIGvDveKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPsSQw6MgY8OzIHTDoGkga2hv4bqjbj88LzA+PDE+PDA+xJDEg25nIG5o4bqtcDwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBLaMOhY2g8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAiWMOhYyBuaOG6rW4gbeG6rXQga2jhuql1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkNoaWEgc+G6uyBtw6BuIGjDrG5oIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJOaMOgIHBow6F0IHRyaeG7g24iLAogICAgImZlZWRiYWNrX3RhYl9kZXNjcmlwdGlvbl9sYWJlbCI6ICJQaOG6o24gaOG7k2kgY+G7p2EgYuG6oW4iLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICJH4butaSBwaOG6o24gaOG7k2kiLAogICAgImZlZWRiYWNrX3RhYl9zZW5kX2xvZ3NfbGFiZWwiOiAiS8OobSB0aGVvIG5o4bqtdCBrw70gZ+G7oSBs4buXaSIsCiAgICAiZmVlZGJhY2tfdGFiX3RoYW5rX3lvdSI6ICJD4bqjbSDGoW4sIGNow7puZyB0w7RpIMSRw6Mgbmjhuq1uIMSRxrDhu6NjIHBo4bqjbiBo4buTaSEiLAogICAgImZlZWRiYWNrX3RhYl90aXRsZSI6ICJQaOG6o24gaOG7k2kiCiAgfSwKICAic3VibWl0dGluZyI6ICLEkGFuZyBn4butaeKApiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAiQ2jGsGEgxJHEg25nIGvDvT8gPDI+VOG6oW8gdMOgaSBraG/huqNuPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLEkMSDbmcgbmjhuq1wIHbDoG8gdMOgaSBraG/huqNuIGPhu6dhIGLhuqFuIiwKICAidmVyc2lvbiI6ICJQaGnDqm4gYuG6o246IHt7dmVyc2lvbn19Igp9Cg==",pKe=""+new URL("zh-Hans-app-8pDbXAOO.json",import.meta.url).href,mKe=""+new URL("zh-Hant-app-BV1LKS_j.json",import.meta.url).href,{slice:gKe,forEach:vKe}=[];function yKe(n){return vKe.call(gKe.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}const o$=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,_Ke=function(n,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${n}=${i}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!o$.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!o$.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s},a$={create(n,e,t,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+t*60*1e3)),r&&(i.domain=r),document.cookie=_Ke(n,encodeURIComponent(e),i)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let r=0;r<t.length;r++){let i=t[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(n){this.create(n,"",-1)}};var bKe={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return a$.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;t&&typeof document<"u"&&a$.create(t,n,r,i,s)}},SKe={name:"querystring",lookup(n){var r;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:i}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(i=window.location.hash.substring(window.location.hash.indexOf("?")));const o=i.substring(1).split("&");for(let a=0;a<o.length;a++){const l=o[a].indexOf("=");l>0&&o[a].substring(0,l)===e&&(t=o[a].substring(l+1))}}return t}};let ch=null;const l$=()=>{if(ch!==null)return ch;try{if(ch=typeof window<"u"&&window.localStorage!==null,!ch)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{ch=!1}return ch};var EKe={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&l$())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&l$()&&window.localStorage.setItem(t,n)}};let uh=null;const c$=()=>{if(uh!==null)return uh;try{if(uh=typeof window<"u"&&window.sessionStorage!==null,!uh)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{uh=!1}return uh};var wKe={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&c$())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&c$()&&window.sessionStorage.setItem(t,n)}},CKe={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:r,language:i}=navigator;if(t)for(let s=0;s<t.length;s++)e.push(t[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},TKe={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(t=r.getAttribute("lang")),t}},RKe={name:"path",lookup(n){var i;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(i=t[typeof e=="number"?e:0])==null?void 0:i.replace("/",""):void 0}},IKe={name:"subdomain",lookup(n){var i,s;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,r=typeof window<"u"&&((s=(i=window.location)==null?void 0:i.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[t]}};let qte=!1;try{document.cookie,qte=!0}catch{}const Kte=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];qte||Kte.splice(1,1);const kKe=()=>({order:Kte,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class Gte{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=yKe(t,this.options||{},kKe()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(bKe),this.addDetector(SKe),this.addDetector(EKe),this.addDetector(wKe),this.addDetector(CKe),this.addDetector(TKe),this.addDetector(RKe),this.addDetector(IKe)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(t=t.concat(i))}}),t=t.map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}Gte.type="languageDetector";var P_={},u$;function xKe(){if(u$)return P_;u$=1,Object.defineProperty(P_,"__esModule",{value:!0}),P_.shouldPolyfill=n;function n(){return!Intl.Segmenter}return P_}var PKe=xKe(),L_={},d$;function LKe(){if(d$)return L_;d$=1,Object.defineProperty(L_,"__esModule",{value:!0}),L_.shouldPolyfill=n;function n(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return L_}var OKe=LKe();const Wte=Object.assign({"../locales/bg/app.json":Wqe,"../locales/cs/app.json":zqe,"../locales/de/app.json":Yqe,"../locales/el/app.json":Jqe,"../locales/en/app.json":Xqe,"../locales/es/app.json":Zqe,"../locales/et/app.json":Qqe,"../locales/fa/app.json":eKe,"../locales/fr/app.json":tKe,"../locales/id/app.json":nKe,"../locales/it/app.json":rKe,"../locales/ja/app.json":iKe,"../locales/lv/app.json":sKe,"../locales/pl/app.json":oKe,"../locales/ro/app.json":aKe,"../locales/ru/app.json":lKe,"../locales/sk/app.json":cKe,"../locales/sv/app.json":uKe,"../locales/tr/app.json":dKe,"../locales/uk/app.json":fKe,"../locales/vi/app.json":hKe,"../locales/zh-Hans/app.json":pKe,"../locales/zh-Hant/app.json":mKe}),MKe=(n,e)=>Wte[`../locales/${n}/${e}.json`],AKe=[...new Set(Object.keys(Wte).map(n=>{var t;const e=(t=n.match(/\/([^/]+)\/[^/]+\.json$/))==null?void 0:t[1];if(!e)throw new Error(`Could not parse locale URL ${n}`);return e}))],NKe={type:"backend",init(){},read(n,e,t){(async()=>{const r=MKe(n,e);if(!r)throw new Error(`Namespace ${e} for locale ${n} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(X6(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>t(null,r),r=>t(r,null))}};class DKe{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class ms{constructor(){this.isInitialized=!1,this.loadStates=new DKe}static isInitialized(){var e;return!!((e=ms.internalInstance)!=null&&e.isInitialized)}static async initBeforeReact(){const e=[];PKe.shouldPolyfill()&&e.push(Cv(()=>import("./polyfill-force-D1fv9_K0.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),OKe.shouldPolyfill()&&e.push(Cv(()=>import("./polyfill-force-CykjiN0j.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const t=new Gte;t.addDetector({name:"urlFragment",lookup:()=>Yr().lang??void 0}),await di.use(NKe).use(t).use(U2e).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:AKe,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Yr();i!==null&&document.documentElement.style.setProperty("--font-scale",i.toString()),r.length>0&&document.documentElement.style.setProperty("--font-family",r.map(s=>`"${s}"`).join(", ")),document.body.setAttribute("data-platform",Od)}static init(){var e;return(e=ms==null?void 0:ms.internalInstance)!=null&&e.initPromise?null:(ms.internalInstance=new ms,ms.internalInstance.initPromise=new Promise(t=>{var r;(r=ms.internalInstance)==null||r.initStep(t)}),ms.internalInstance.initPromise)}static reset(){ms.internalInstance=void 0}initStep(e){if(this.loadStates.config===0&&(this.loadStates.config=1,Ht.init().then(()=>{this.loadStates.config=2,this.initStep(e)},t=>{A.error("Failed to load config",t)})),this.loadStates.sentry===0&&this.loadStates.config===2){let t,r;t=Yr().sentryDsn??void 0,r=Yr().sentryEnvironment??void 0,t&&_0e({dsn:t,environment:r,integrations:[U0e({useEffect:Ce.useEffect,useLocation:ci,useNavigationType:Ife,createRoutesFromChildren:vS,matchRoutes:IL})],tracesSampleRate:1}),this.loadStates.sentry=2}this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(Dw.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const jKe=()=>{const[n,e]=_.useState(()=>Yr().theme),t=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(Ge){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),Ge.api.transport.reply(i.detail,{})};return Ge.lazyActions.on(mr.ThemeChange,r),()=>{Ge.lazyActions.off(mr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=n!=null&&n.includes("light")?"light":"dark",i=n!=null&&n.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==t.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),t.current=s),document.body.classList.remove("no-theme")},[t,n])},O_=F0e(pq),UKe=({children:n})=>{const{pathname:e}=ci();return _.useEffect(()=>{let t="";!["/login","/register"].includes(e)&&!Ge&&(t="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=t},[e]),E.jsx(E.Fragment,{children:n})},FKe=({children:n})=>(jKe(),n),$Ke=()=>{const[n,e]=_.useState(!1);return _.useEffect(()=>{var t;(t=ms.init())==null||t.then(async()=>{n||(e(!0),await(Ge==null?void 0:Ge.api.sendContentLoaded()))}).catch(A.error)}),E.jsx(hhe,{children:E.jsx(UKe,{children:E.jsx(FKe,{children:E.jsx(PG,{children:n?E.jsx(_.Suspense,{fallback:null,children:E.jsx(i8e,{children:E.jsx(J8e,{children:E.jsxs(sw,{fallback:t=>E.jsx(dy,{error:t,widget:Ge}),children:[E.jsx(Gqe,{}),E.jsxs(Vfe,{children:[E.jsx(O_,{path:"/",element:E.jsx($Q,{})}),E.jsx(O_,{path:"/login",element:E.jsx(G7e,{})}),E.jsx(O_,{path:"/register",element:E.jsx(W7e,{})}),E.jsx(O_,{path:"*",element:E.jsx(Vqe,{})})]})]})})})}):E.jsx(Uw,{})})})})})};window.setLKLogLevel=nV;M3e().catch(n=>{A.error("Failed to initialize rageshake",n)});nV("warn");Zce((n,e,t)=>{global.mx_rage_logger.log(n,"livekit",e,t)});A.info("Element Call embedded-v0.10.0-rc.1");const kP=ble.createRoot(document.getElementById("root"));let bv=null;window.isSecureContext?navigator.mediaDevices||(bv=new Error("Your browser does not support WebRTC.")):bv=new Error(`This app cannot run in an insecure context. To fix this, access the app via a local loopback address, or serve it over HTTPS.
214
+ `;return typeof a=="function"&&a(null,S),S},JI}var s$;function Iqe(){if(s$)return lh;s$=1;const n=aqe(),e=Cqe(),t=Tqe(),r=Rqe();function i(s,o,a,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!n())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=a,a=o,o=l=void 0):f===3&&(o.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=o,o=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=o,o=l=void 0):f===2&&!o.getContext&&(l=a,a=o,o=void 0),new Promise(function(m,v){try{const g=e.create(a,l);m(s(g,o,l))}catch(g){v(g)}})}try{const m=e.create(a,l);c(null,s(m,o,l))}catch(m){c(m)}}return lh.create=e.create,lh.toCanvas=i.bind(null,t.render),lh.toDataURL=i.bind(null,t.renderToDataURL),lh.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),lh}var kqe=Iqe();const xqe="_qrCode_h54ia_8",Pqe={qrCode:xqe},Lqe=({data:n,className:e})=>{const[t,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return kqe.toDataURL(n,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[n]),E.jsx("div",{className:Ae(Pqe.qrCode,e),children:t&&E.jsx("img",{src:t,alt:Vo("qr_code")})})},Oqe=({room:n,open:e,onDismiss:t})=>{const{t:r}=ze(),i=Hw(n.roomId),s=_.useMemo(()=>jQ(n.roomId,i,n.name),[i,n.name,n.roomId]),[,o]=eqe(s),[a,l]=_.useState(!1),c=_.useCallback(()=>l(!1),[l]),u=_.useCallback(f=>{f.stopPropagation(),o(),t(),l(!0)},[o,t]);return E.jsxs(E.Fragment,{children:[E.jsxs(lf,{title:r("invite_modal.title"),open:e,onDismiss:t,children:[E.jsx(Lqe,{className:II.qrCode,data:s}),E.jsx(Xt,{className:II.url,size:"sm",weight:"semibold",children:s}),E.jsx(At,{className:II.button,Icon:z2e,onClick:u,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),E.jsx(oqe,{open:a,onDismiss:c,autoDismiss:2e3,Icon:UY,children:r("invite_modal.link_copied_toast")})]})},Mqe=({error:n,recoveryActionHandler:e,widget:t})=>{const{t:r}=ze();let i;switch(n.category){case jb.CONFIGURATION_ISSUE:i=W2e;break;case jb.NETWORK_CONNECTIVITY:i=Z2e;break;case jb.CLIENT_CONFIGURATION:i=fRe;break;default:i=ow}const s=[];return n instanceof hte&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>e("reconnect")}),E.jsx(Qh,{children:E.jsxs(uy,{Icon:i,title:n.localisedTitle,rageshake:n.code==iO.UNKNOWN_ERROR,widget:t,children:[E.jsx("p",{children:n.localisedMessage??E.jsx(Qi,{i18nKey:"error.unexpected_ec_error",components:[E.jsx("b",{}),E.jsx("code",{})],values:{errorCode:n.code}})}),s&&s.map((o,a)=>E.jsx("button",{onClick:o.onClick,children:o.label},`action${a}`))]})})},Aqe=({recoveryActionHandler:n,onError:e,children:t,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof $a?s:new sO(s instanceof Error?s:new Error);return E.jsx(Mqe,{widget:r??null,error:a,resetError:o,recoveryActionHandler:l=>{o(),n(l)}})},[n,r]);return E.jsx(sw,{fallback:i,onError:s=>e==null?void 0:e(s),children:t})},Nqe=({client:n,isPasswordlessUser:e,confineToRoom:t,preload:r,skipLobby:i,hideHeader:s,rtcSession:o,isJoined:a,muteStates:l,widget:c})=>{const[u,f]=_.useState(null),p=oQ(o),m=xl(lO({sounds:jte,latencyHint:"interactive"}));_.useEffect(()=>{var pe,ve;p.length>=FVe&&((ve=(pe=l.audio).setEnabled)==null||ve.call(pe,!1))},[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),Sw(o,ar.MembershipManagerError,pe=>{f(new rHe(iO.MEMBERSHIP_MANAGER_UNRECOVERABLE,pe.message??pe))}),_.useEffect(()=>{n.getRoom(o.room.roomId)!==o.room&&A.warn(`We've ended up with multiple rooms for the same ID (${o.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`)},[n,o.room]);const v=o.room,{displayName:g,avatarUrl:S}=Jy(n),b=zVe(v),w=WVe(v),{perParticipantE2EE:k,returnToLobby:R}=ku(),I=Hw(v.roomId),[C]=Xn(ZZ),[x]=Xn(T4);Zy(b);const O=_.useMemo(()=>({userId:n.getUserId(),displayName:g,avatarUrl:S,roomId:v.roomId,roomName:b,roomAlias:v.getCanonicalAlias(),roomAvatar:w,e2eeSystem:I}),[n,g,S,b,v,w,I]),N=_.useMemo(()=>new Set(p.map(pe=>pe.sender)).size,[p]),D=uf(),j=xl(D),U=xl(l),H=_.useCallback(async pe=>{try{await KVe(pe,k,C,x)}catch(ve){if(ve instanceof $a)f(ve);else{A.error("Unknown Error while entering RTC session",ve);const Ee=new sO(ve instanceof Error?ve:new Error("Unknown error",{cause:ve}));f(Ee)}}},[k,x,C]);_.useEffect(()=>{const pe=async({audioInput:ve,videoInput:Ee})=>{var zt,ln,Yt,Fe;const Ke=await Ol.getLocalDevices(void 0,!0);if(ve){const _t=bU(ve,"audioinput",Ke);_t?(A.debug(`Found audio input ID ${_t} for name ${ve}`),j.current.audioInput.select(_t)):(A.warn("Unknown audio input: "+ve),(ln=(zt=U.current.audio).setEnabled)==null||ln.call(zt,!1))}if(Ee){const _t=bU(Ee,"videoinput",Ke);_t?(A.debug(`Found video input ID ${_t} for name ${Ee}`),j.current.videoInput.select(_t)):(A.warn("Unknown video input: "+Ee),(Fe=(Yt=U.current.video).setEnabled)==null||Fe.call(Yt,!1))}};if(i)if(c)if(r){const ve=Ee=>{(async()=>{await pe(Ee.detail.data),await H(o),c.api.transport.reply(Ee.detail,{})})().catch(Ke=>{A.error("Error joining RTC session",Ke)})};return c.lazyActions.on(Ar.JoinCall,ve),()=>{c.lazyActions.off(Ar.JoinCall,ve)}}else(async()=>{await H(o)})().catch(ve=>{A.error("Error joining RTC session",ve)});else H(o)},[c,o,r,i,k,j,U,H,C]);const[K,B]=_.useState(!1),z=Na(),W=_.useCallback((pe="user")=>{var zt;const ve=(zt=m.current)==null?void 0:zt.playSound("left"),Ee=!!c;B(!0);const Ke=new Promise(ln=>{Et.instance.eventCallEnded.track(v.roomId,o.memberships.length,Ee,o),window.setTimeout(ln,10)});xF(o,pe,Promise.all([ve,Ke])).then(async()=>{!e&&!t&&!Et.instance.isEnabled()&&await z("/")}).catch(ln=>{A.error("Error leaving RTC session",ln)})},[m,c,o,v.roomId,e,t,z]);_.useEffect(()=>{if(c&&a){c.api.setAlwaysOnScreen(!0).catch(ve=>{A.error("Error calling setAlwaysOnScreen(true)",ve)});const pe=ve=>{c.api.transport.reply(ve.detail,{}),xF(o,"user").catch(Ee=>{A.error("Failed to leave RTC session",Ee)})};return c.lazyActions.once(Ar.HangupCall,pe),()=>{c.lazyActions.off(Ar.HangupCall,pe)}}},[c,a,o]);const V=YVe(v),[q,X]=_.useState(!1),G=_.useCallback(()=>X(!1),[X]),Q=_.useCallback(()=>X(!0),[X]),me=V===Wc.Public?Q:null;if(!DV()&&I.kind!==Bt.NONE)throw new iHe;const Se=E.jsx(Oqe,{room:v,open:q,onDismiss:G}),xe=E.jsxs(E.Fragment,{children:[Se,E.jsx(wee,{client:n,matrixInfo:O,muteStates:l,onEnter:()=>void H(o),confineToRoom:t,hideHeader:s,participantCount:N,onShareClick:me})]});let fe;if(u){const pe=()=>{throw u};fe=E.jsx(pe,{})}else a?fe=E.jsxs(E.Fragment,{children:[Se,E.jsx(jVe,{client:n,matrixInfo:O,rtcSession:o,participantCount:N,onLeave:W,hideHeader:s,muteStates:l,e2eeSystem:I,onShareClick:me})]}):K&&c===null?e||Et.instance.isEnabled()&&c===null?fe=E.jsx(MUe,{endedCallId:o.room.roomId,client:n,isPasswordlessUser:e,confineToRoom:t}):fe=null:K&&c!==null?fe=R?xe:null:r||i?fe=null:fe=xe;return E.jsx(Aqe,{widget:c,recoveryActionHandler:pe=>{pe=="reconnect"&&(B(!1),H(o).catch(ve=>{A.error("Error re-entering RTC session",ve)}))},onError:()=>{o.isJoined()&&W("error")},children:fe})},Dqe="_modal_1tnec_8",jqe={modal:Dqe},Uqe=({roomId:n})=>{const{t:e}=ze(),[t,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=Hw(n);s.kind===Bt.NONE&&A.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(n===null?window.location.href:jQ(n,s));a.hash=w3e(a.hash,c=>(c.set("appPrompt","false"),c.set("confineToRoom","true"),c));const l=new URL("io.element.call:/");return l.searchParams.set("url",a.toString()),l.toString()},[s,n]);return E.jsxs(lf,{className:jqe.modal,title:e("app_selection_modal.title"),open:t,children:[E.jsx(Xt,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),E.jsx(At,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),E.jsx(At,{as:"a",href:o,Icon:gJ,children:e("app_selection_modal.open_in_app")})]})},Fqe=3,$qe=3e3;async function Vte(n,e=0,...t){try{return await n.joinRoom(...t)}catch(r){if(r instanceof bn&&r.errcode==="M_FORBIDDEN"&&e<Fqe)return await new Promise(i=>setTimeout(i,$qe)),Vte(n,e+1,...t);throw r}}class $b extends Error{constructor(e,t,r,i){super(t),this.icon=e,this.messageBody=r,this.reason=i}}const Hqe=(n,e,t)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=ze(),a=_.useCallback(()=>new $b(B2e,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),u()),[o]),l=_.useCallback(()=>new $b(aw,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),u()),[o]),c=_.useCallback(()=>new $b(tJ,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),u()),[o]),u=()=>{var f,p,m;return(m=(p=s.current)==null?void 0:p.currentState.getStateEvents(ee.RoomMember,(f=s.current)==null?void 0:f.myUserId))==null?void 0:m.getContent().reason};return _.useEffect(()=>{if(!n||!e)return;const f=async b=>{let w=null;const k=await n.getRoomIdForAlias(b.toLowerCase());return A.info(`${b} resolved to ${k.room_id}`),w=n.getRoom(k.room_id),w?A.info(`Already in room ${k.room_id}, not rejoining.`):(A.info(`Room ${k.room_id} not found, joining.`),w=await n.joinRoom(k.room_id,{viaServers:k.servers})),w},p=async(b,w,k)=>(await n.knockRoom(b,{viaServers:w}),k(),await new Promise((R,I)=>{n.on(ke.MyMembership,(C,x,O)=>{b===C.roomId&&(s.current=C,x===qe.Invite&&O===qe.Knock&&Vte(n,0,C.roomId,{viaServers:w}).then(N=>{A.log("Auto-joined %s",N.roomId),R(N)},I),x===qe.Ban&&I(a()),x===qe.Leave&&I(l()))})})),m=async()=>{let b=null;if(e[0]==="#")b=await f(e),s.current=b;else{const w=e;b=n.getRoom(w),s.current=b??void 0;const k=b==null?void 0:b.getMyMembership();if(k===qe.Join)return b;if(Ge)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(k===qe.Ban)throw a();if(k===qe.Invite)b=await n.joinRoom(w,{viaServers:t});else{let R;try{R=await n.getRoomSummary(w,t)}catch(I){A.warn("Could not load room summary to decide whether we want to join or knock.\n EC will fallback to join as if this would be a public room.\n Reach out to your homeserver admin to ask them about supporting the `/summary` endpoint (im.nheko.summary):",I)}if(R===void 0||R.join_rule===Wc.Public)b=await n.joinRoom(w,{viaServers:t});else if(R.join_rule===Wc.Knock){const I=R;let C=()=>{};const x=new Promise(O=>{I.membership!==qe.Knock?C=O:O()});i({kind:"canKnock",roomSummary:I,knock:C}),await x,b=await p(R.room_id,t,()=>i({kind:"waitForInvite",roomSummary:I}))}else throw new Error(`Room ${R.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return A.info(`Joined ${e}, waiting room to be ready for group calls`),await n.waitUntilRoomReadyForGroupCalls(b.roomId),A.info(`${e}, is ready for group calls`),b},v=async()=>{const b=await m();return s.current=b,A.debug(`Fetched / joined room ${e}`),n.matrixRTC.getRoomSession(b)},g=async()=>{n.getSyncState()!==Dt.Syncing&&(A.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(b=>{const w=()=>{if(n.getSyncState()===Dt.Syncing)return n.off(Oe.Sync,w),b()};n.on(Oe.Sync,w)}),A.debug("useLoadGroupCall: client is now syncing."))},S=async()=>{await new Promise((b,w)=>{n.on(ke.MyMembership,(k,R)=>{R===qe.Leave&&w(c()),R===qe.Ban&&w(a())})})};r.kind==="loading"&&(A.log("Start loading group call"),g().then(v).then(b=>i({kind:"loaded",rtcSession:b})).then(S).catch(b=>i({kind:"failed",error:b})))},[a,n,l,c,e,r,o,t]),r};function Bqe(n){const[,e]=_.useState(0);return _.useEffect(()=>{if(n!==void 0){const t=r=>{A.info(`Session in room ${n.room.roomId} changed to ${r?"joined":"left"}`),e(i=>i+1)};return n.on(ar.JoinStateChanged,t),()=>{n.off(ar.JoinStateChanged,t)}}},[n]),(n==null?void 0:n.isJoined())??!1}const Vqe=()=>{const{confineToRoom:n,appPrompt:e,preload:t,hideHeader:r,displayName:i,skipLobby:s}=ku(),{t:o}=ze(),{roomAlias:a,roomId:l,viaServers:c}=T3e(),u=l??a;u||A.error("No room specified");const{registerPasswordlessUser:f}=BQ(),[p,m]=_.useState(!1),{loading:v,authenticated:g,client:S,error:b,passwordlessUser:w}=x4(),{avatarUrl:k,displayName:R}=Jy(S),I=Hqe(S,u,c),C=Bqe(I.kind==="loaded"?I.rtcSession:void 0),x=HVe(C);_.useEffect(()=>{!v&&!g&&i&&!Ge&&(m(!0),f(i).catch(H=>{A.error("Failed to register passwordless user",H)}).finally(()=>{m(!1)}))},[v,g,i,m,f]);const[O,N]=Aw();_.useEffect(()=>{O===null&&N&&N(!0)},[O,N]);const D=_.useRef(!1);_.useEffect(()=>{I.kind==="loaded"&&D.current&&A.log("Play join sound 'Not yet implemented'")},[I.kind]);const j=()=>{switch(I.kind){case"loaded":return E.jsx(Nqe,{widget:Ge,client:S,rtcSession:I.rtcSession,isJoined:C,isPasswordlessUser:w,confineToRoom:n,preload:t,skipLobby:s||D.current,hideHeader:r,muteStates:x});case"waitForInvite":case"canKnock":{D.current=D.current||I.kind==="waitForInvite";const H=I.kind==="canKnock"?I.knock:null,K=I.kind==="canKnock"?o("lobby.ask_to_join"):E.jsxs(E.Fragment,{children:[o("lobby.waiting_for_invite"),E.jsx(UY,{})]});return E.jsx(wee,{client:S,matrixInfo:{userId:S.getUserId()??"",displayName:R??"",avatarUrl:k??"",roomAlias:null,roomId:I.roomSummary.room_id,roomName:I.roomSummary.name??"",roomAvatar:I.roomSummary.avatar_url??null,e2eeSystem:{kind:I.roomSummary["im.nheko.summary.encryption"]?Bt.PER_PARTICIPANT:Bt.NONE}},onEnter:()=>H==null?void 0:H(),enterLabel:K,waitingForInvite:I.kind==="waitForInvite",confineToRoom:n,hideHeader:r,participantCount:null,muteStates:x,onShareClick:null})}case"loading":return E.jsx(Qh,{children:E.jsx("h1",{children:o("common.loading")})});case"failed":return D.current=!1,I.error.errcode==="M_NOT_FOUND"?E.jsx(Qh,{children:E.jsx(uy,{Icon:oRe,title:o("error.call_not_found"),widget:Ge,children:E.jsx(Qi,{i18nKey:"error.call_not_found_description",children:E.jsxs("p",{children:["That link doesn't appear to belong to any existing call. Check that you have the right link, or"," ",E.jsx(ka,{to:"/",children:"create a new one"}),"."]})})})}):I.error instanceof $b?E.jsx(Qh,{children:E.jsxs(uy,{Icon:I.error.icon,title:I.error.message,widget:Ge,children:[E.jsx("p",{children:I.error.messageBody}),I.error.reason&&E.jsx("p",{children:o("group_call_loader.reason",{reason:I.error.reason})})]})}):E.jsx(dy,{widget:Ge,error:I.error});default:return E.jsx(E.Fragment,{children:" "})}};let U;return v||p?U=E.jsx(Uw,{}):b?U=E.jsx(dy,{widget:Ge,error:b}):S?u?U=j():U=E.jsx($Q,{}):U=E.jsx(Q7e,{}),E.jsxs(E.Fragment,{children:[U,e&&Ht.get().app_prompt&&(Od==="android"||Od==="ios")&&l&&E.jsx(Uqe,{roomId:l})]})},qqe="_banner_sye6n_8",Kqe={banner:qqe},Gqe=({children:n,className:e,...t})=>{const{t:r}=ze(),i=nm();let s=!1;return(i==null?void 0:i.state)==="valid"&&(s=i.disconnected),E.jsx(E.Fragment,{children:s&&E.jsxs("div",{className:Ae(Kqe.banner,e),...t,children:[n,r("disconnected_banner")]})})},Wqe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQvNC10L3RjiIKICB9LAogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAi0JfQsNGC0LLQvtGA0LgiLAogICAgImNvcHlfbGluayI6ICLQmtC+0L/QuNGA0LDQvdC1INC90LAg0LLRgNGK0LfQutCw0YLQsCIsCiAgICAiZ28iOiAi0J3QsNC/0YDQtdC0IiwKICAgICJpbnZpdGUiOiAi0J/QvtC60LDQvdCwIiwKICAgICJubyI6ICLQndC1IiwKICAgICJyZWdpc3RlciI6ICLQoNC10LPQuNGB0YLRgNCw0YbQuNGPIiwKICAgICJyZW1vdmUiOiAi0J/RgNC10LzQsNGF0L3QuCIsCiAgICAic2lnbl9pbiI6ICLQktC70LXQtyIsCiAgICAic2lnbl9vdXQiOiAi0JjQt9C70LXQtyIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogItCh0YrQt9C00LDQuSDQsNC60LDRg9C90YIiLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD7Ql9Cw0YnQviDQvdC1INC90LDRgdGC0YDQvtC50YLQtSDQv9Cw0YDQvtC70LAg0LfQsCDQtNCwINC30LDQv9Cw0LfQuNGC0LUg0LDQutCw0YPQvdGC0LAg0YHQuD88LzA+PDE+0KnQtSDQvNC+0LbQtdGC0LUg0LTQsCDQt9Cw0L/QsNC30LjRgtC1INC40LzQtdGC0L4g0Lgg0LDQstCw0YLQsNGA0LAg0YHQuCDQt9CwINCx0YrQtNC10YnQuCDRgNCw0LfQs9C+0LLQvtGA0Lg8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLQndC1INGB0LXQs9CwLCDQstGK0YDQvdC4INGB0LUg0L3QsCDQvdCw0YfQsNC70L3QuNGPINC10LrRgNCw0L0iCiAgfSwKICAiY29tbW9uIjogewogICAgImF1ZGlvIjogItCX0LLRg9C6IiwKICAgICJhdmF0YXIiOiAi0JDQstCw0YLQsNGAIiwKICAgICJkaXNwbGF5X25hbWUiOiAi0JjQvNC1L9C/0YHQtdCy0LTQvtC90LjQvCIsCiAgICAiaG9tZSI6ICLQndCw0YfQsNC70L4iLAogICAgImxvYWRpbmciOiAi0JfQsNGA0LXQttC00LDQvdC14oCmIiwKICAgICJwYXNzd29yZCI6ICLQn9Cw0YDQvtC70LAiLAogICAgInByb2ZpbGUiOiAi0J/RgNC+0YTQuNC7IiwKICAgICJzZXR0aW5ncyI6ICLQndCw0YHRgtGA0L7QudC60LgiLAogICAgInVzZXJuYW1lIjogItCf0L7RgtGA0LXQsdC40YLQtdC70YHQutC+INC40LzQtSIsCiAgICAidmlkZW8iOiAi0JLQuNC00LXQviIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi0JTQsCwg0L/RgNC40YHRitC10LTQuNC90Lgg0YHQtSIsCiAgICAidGV4dCI6ICLQotC+0LfQuCDRgNCw0LfQs9C+0LLQvtGAINCy0LXRh9C1INGB0YrRidC10YHRgtCy0YPQstCwLCDQuNGB0LrQsNGC0LUg0LvQuCDQtNCwINGB0LUg0L/RgNC40YHRitC10LTQuNC90LjRgtC1PyIsCiAgICAidGl0bGUiOiAi0J/RgNC40YHRitC10LTQuNC90Y/QstCw0L3QtSDQutGK0Lwg0YHRitGJ0LXRgdGC0LLRg9Cy0LDRiSDRgNCw0LfQs9C+0LLQvtGAPyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItCf0YDQvtC20LXQutGC0L7RgCIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItCS0LvQtdC3INCyINGA0LDQt9Cz0L7QstC+0YDQsCIKICB9LAogICJsb2dnaW5nX2luIjogItCS0LvQuNC30LDQvdC14oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD7QodGK0LfQtNCw0LnRgtC1INCw0LrQsNGD0L3RgjwvMD4g0LjQu9C4IDwyPtCS0LvQtdC30YLQtSDQutCw0YLQviDQs9C+0YHRgjwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLQktC70LXQtyIsCiAgInJhZ2VzaGFrZV9yZXF1ZXN0X21vZGFsIjogewogICAgImJvZHkiOiAi0JTRgNGD0LMg0L/QvtGC0YDQtdCx0LjRgtC10Lsg0LIg0YLQvtC30Lgg0YDQsNC30LPQvtCy0L7RgCDQuNC80LAg0L/RgNC+0LHQu9C10LwuINCX0LAg0LTQsCDQtNC40LDQs9C90L7RgdGC0LjRhtC40YDQsNC80LUg0YLQvtC30Lgg0L/RgNC+0LHQu9C10Lwg0L/Qvi3QtNC+0LHRgNC1INC90Lgg0YHQtSDQuNGB0LrQsCDQtNCwINGB0YrQsdC10YDQtdC8IGRlYnVnINC70L7Qs9C+0LLQtS4iLAogICAgInRpdGxlIjogItCX0LDRj9Cy0LrQsCDQt9CwIGRlYnVnINC70L7Qs9C+0LLQtSIKICB9LAogICJyYWdlc2hha2Vfc2VuZF9sb2dzIjogItCY0LfQv9GA0LDRgtC10YLQtSBkZWJ1ZyDQu9C+0LPQvtCy0LUiLAogICJyYWdlc2hha2Vfc2VuZGluZyI6ICLQmNC30L/RgNCw0YnQsNC90LXigKYiLAogICJyZWNhcHRjaGFfZGlzbWlzc2VkIjogIlJlY2FwdGNoYSDQvtGC0YXQstGK0YDQu9C10L3QsCIsCiAgInJlY2FwdGNoYV9ub3RfbG9hZGVkIjogIlJlY2FwdGNoYSDQvdC1INC1INC30LDRgNC10LTQtdC90LAiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICLQn9Cw0YDQvtC70LjRgtC1INC90LUg0YHRitCy0L/QsNC00LDRgiIsCiAgICAicmVnaXN0ZXJpbmciOiAi0KDQtdCz0LjRgdGC0YDQuNGA0LDQvdC14oCmIgogIH0sCiAgInJlZ2lzdGVyX2F1dGhfbGlua3MiOiAiPDA+0JLQtdGH0LUg0LjQvNCw0YLQtSDQsNC60LDRg9C90YI/PC8wPjwxPjwwPtCS0LvQtdC30YLQtSDRgSDQvdC10LPQvjwvMD4g0LjQu9C4IDwyPtCS0LvQtdC30YLQtSDQutCw0YLQviDQs9C+0YHRgjwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLQn9C+0YLQstGK0YDQtNC4INC/0LDRgNC+0LvQsNGC0LAiLAogICJyZXR1cm5faG9tZV9idXR0b24iOiAi0JLRgNGK0YnQsNC90LUg0L3QsCDQvdCw0YfQsNC70L3QuNGPINC10LrRgNCw0L0iLAogICJzY3JlZW5zaGFyZV9idXR0b25fbGFiZWwiOiAi0KHQv9C+0LTQtdC70Lgg0LXQutGA0LDQvdCwIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLQoNCw0LfRgNCw0LHQvtGC0YfQuNC6IiwKICAgICJmZWVkYmFja190YWJfaDQiOiAi0JjQt9C/0YDQsNGC0Lgg0L7QsdGA0LDRgtC90LAg0LLRgNGK0LfQutCwIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogItCS0LrQu9GO0YfQuCBkZWJ1ZyDQu9C+0LPQvtCy0LUiCiAgfSwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfYm9keSI6ICLQktGB0LUg0L7RidC1INC90LUg0YHRgtC1INGA0LXQs9C40YHRgtGA0LjRgNCw0L3QuD8gPDI+0KHRitC30LTQsNC50YLQtSDQsNC60LDRg9C90YI8LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogItCS0LvQtdC30YLQtSDQsiDQsNC60LDRg9C90YLQsCDRgdC4IiwKICAidmVyc2lvbiI6ICLQktC10YDRgdC40Y86IHt7dmVyc2lvbn19Igp9Cg==",zqe=""+new URL("cs-app-BIDxiN50.json",import.meta.url).href,Yqe=""+new URL("de-app-Dn3BQmuZ.json",import.meta.url).href,Jqe=""+new URL("el-app-Bgiig2Nz.json",import.meta.url).href,Xqe=""+new URL("en-app-LL1Igtxp.json",import.meta.url).href,Zqe=""+new URL("es-app-Q3c7lmEj.json",import.meta.url).href,Qqe=""+new URL("et-app-DPt7J6kw.json",import.meta.url).href,eKe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLZgdmH2LHYs9iqINqp2KfYsdio2LEiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogItio2LPYqtmGIiwKICAgICJnbyI6ICLYsdmB2KrZhiIsCiAgICAibm8iOiAi2K7bjNixIiwKICAgICJyZWdpc3RlciI6ICLYq9io2KrigIzZhtin2YUiLAogICAgInJlbW92ZSI6ICLYrdiw2YEiLAogICAgInNpZ25faW4iOiAi2YjYsdmI2K8iLAogICAgInNpZ25fb3V0IjogItiu2LHZiNisIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAi2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+2obYsdinINuM2qkg2LHZhdiyINi52KjZiNixINio2LHYp9uMINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2KrZhti424zZhSDZhtmF24zigIzaqdmG24zYr9ifPC8wPjwxPti02YXYpyDZhduM4oCM2KrZiNin2YbbjNivINmG2KfZhSDYrtmI2K8g2LHYpyDYrdmB2Lgg2qnZhtuM2K8g2Ygg24zaqSDYotmI2KfYqtin2LEg2KjYsdin24wg2KrZhdin2LPigIzZh9in24wg2KLbjNmG2K/ZhyDYqNiz2KfYstuM2K88LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLYp9mE2KfZhiDZhtmH2Iwg2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCDYqNix2q/Ysdiv24zYryIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi2LXYr9inIiwKICAgICJhdmF0YXIiOiAi2KLZiNin2KrYp9ixIiwKICAgICJkaXNwbGF5X25hbWUiOiAi2YbYp9mFINmG2YXYp9uM2LTbjCIsCiAgICAiaG9tZSI6ICLYrtin2YbZhyIsCiAgICAibG9hZGluZyI6ICLYqNin2LHar9iy2KfYsduM4oCmIiwKICAgICJwYXNzd29yZCI6ICLYsdmF2LIg2LnYqNmI2LEiLAogICAgInByb2ZpbGUiOiAi2b7YsdmI2YHYp9uM2YQiLAogICAgInNldHRpbmdzIjogItiq2YbYuNuM2YXYp9iqIiwKICAgICJ1c2VybmFtZSI6ICLZhtin2YUg2qnYp9ix2KjYsduMIiwKICAgICJ2aWRlbyI6ICLZiNuM2K/bjNmIIgogIH0sCiAgImhlYWRlcl9sYWJlbCI6ICLYrtin2YbZh9mUINiq2YXYp9izINin2YTZhdmG2KoiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi2KjZhNmH2Iwg2KjZhyDYqtmF2KfYsyDYqNm+24zZiNmG2K/bjNivIiwKICAgICJ0ZXh0IjogItin24zZhiDYqtmF2KfYsyDYp9iyINmC2KjZhCDZiNis2YjYryDYr9in2LHYr9iMINmF24zigIzYrtmI2KfZh9uM2K8g2KjZvtuM2YjZhtiv24zYr9ifIiwKICAgICJ0aXRsZSI6ICLZvtuM2YjYs9iqINio2Ycg2KrZhdin2LPYnyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItmG2YjYsSDYp9mB2qnZhiIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItm+24zZiNiz2KrZhiDYqNmHINiq2YXYp9izIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi2YjYsdmI2K/igKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPtiz2KfYrtiqINit2LPYp9ioINqp2KfYsdio2LHbjDwvMD4gT3IgPDI+2K/Ys9iq2LHYs9uMINio2Ycg2LnZhtmI2KfZhiDZhduM2YfZhdin2YY8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi2YjYsdmI2K8iLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItqp2KfYsdio2LEg2K/bjNqv2LHbjCDYr9ixINin24zZhiDYqtmF2KfYsyDZhdi02qnZhNuMINiv2KfYsdivLiDYqNix2KfbjCDYqti02K7bjNi1INio2YfYqtixINmF2LTaqdmE2Iwg2KjZh9iq2LEg2KfYs9iqINmF2Kcg2YTYp9qvINi524zYqOKAjNuM2KfYqNuMINix2Kcg2KzZhdi54oCM2KLZiNix24wg2qnZhtuM2YUuIiwKICAgICJ0aXRsZSI6ICLYr9ix2K7ZiNin2LPYqiDZhNin2q8g2LnbjNio4oCM24zYp9io24wiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLYp9ix2LPYp9mEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YTigKYiLAogICJyYWdlc2hha2Vfc2VuZGluZ19sb2dzIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YQg2KjYp9qv4oCM2YfYp9uMINi524zYqOKAjNuM2KfYqNuM4oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICLYsduM2qnZvtqG2Kcg2LHYryDYtNivIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAi2qnZvtqG2Kcg2KjYp9ix2q/bjNix24wg2YbYtNivIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi2LHZhdiyINi52KjZiNixINio2KfbjNivINmH2YXYrtmI2KfZhtuMINiv2KfYtNiq2Ycg2KjYp9i02K8iLAogICAgInJlZ2lzdGVyaW5nIjogItir2KjYquKAjNmG2KfZheKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtin2LIg2YLYqNmEINit2LPYp9ioINqp2KfYsdio2LHbjCDYr9in2LHbjNiv2J88LzA+PDE+PDA+2YjYsdmI2K88LzA+IE9yIDwyPtio2Ycg2LnZhtmI2KfZhiDbjNqpINmF24zZh9mF2KfZhiDZiNin2LHYryDYtNmI24zYrzwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLYqtin24zbjNivINix2YXYsti52KjZiNixIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItio2LHar9i02Kog2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCIsCiAgInNjcmVlbnNoYXJlX2J1dHRvbl9sYWJlbCI6ICLYp9i02KrYsdin2qkg2q/YsNin2LHbjCDYtdmB2K3ZhyDZhtmF2KfbjNi0IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLYqtmI2LPYudmHINiv2YfZhtiv2YciLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICLYqNin2LLYrtmI2LHYryDYp9ix2KfYptmHINiv2YfbjNivIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIti02KfZhdmEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogItmH2YbZiNiyINir2KjYquKAjNmG2KfZhSDZhtqp2LHYr9mH4oCM2KfbjNiv2J8gPDI+2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLYqNmHINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2YjYp9ix2K8g2LTZiNuM2K8iLAogICJ2ZXJzaW9uIjogItmG2LPYrtmHOiB7e9mG2LPYrtmHfX0iCn0K",tKe=""+new URL("fr-app-BxTYbDfK.json",import.meta.url).href,nKe=""+new URL("id-app-B-8jUQf1.json",import.meta.url).href,rKe=""+new URL("it-app-Cik25Qgd.json",import.meta.url).href,iKe=""+new URL("ja-app-Cp_00ujI.json",import.meta.url).href,sKe=""+new URL("lv-app-J9DGb4uv.json",import.meta.url).href,oKe=""+new URL("pl-app-CUkXVSZk.json",import.meta.url).href,aKe=""+new URL("ro-app-KHxgbZz-.json",import.meta.url).href,lKe=""+new URL("ru-app-eoBdfBL5.json",import.meta.url).href,cKe=""+new URL("sk-app-oyZEXyo9.json",import.meta.url).href,uKe=""+new URL("sv-app-D3UhBwmo.json",import.meta.url).href,dKe=""+new URL("tr-app-Dk--6BpP.json",import.meta.url).href,fKe=""+new URL("uk-app-8w2P6iQj.json",import.meta.url).href,hKe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAixJDDs25nIiwKICAgICJubyI6ICJLaMO0bmciLAogICAgInJlZ2lzdGVyIjogIsSQxINuZyBrw70iLAogICAgInNpZ25faW4iOiAixJDEg25nIG5o4bqtcCIsCiAgICAic2lnbl9vdXQiOiAixJDEg25nIHh14bqldCIsCiAgICAic3VibWl0IjogIkfhu61pIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAiVOG6oW8gdMOgaSBraG/huqNuIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+VOG6oWkgc2FvIGzhuqFpIGtow7RuZyBob8OgbiB0aGnhu4duIGLhurFuZyBjw6FjaCDEkeG6t3QgbeG6rXQga2jhuql1IMSR4buDIGdp4buvIHTDoGkga2hv4bqjbiBj4bunYSBi4bqhbj88LzA+PDE+QuG6oW4gc+G6vSBjw7MgdGjhu4MgZ2nhu68gdMOqbiB2w6AgxJHhurd0IOG6o25oIMSR4bqhaSBkaeG7h24gY2hvIG5o4buvbmcgY3Xhu5ljIGfhu41pIHRp4bq/cCB0aGVvLjwvMT4iLAogICAgImZlZWRiYWNrX2RvbmUiOiAiPDA+Q+G6o20gaMahbiB2w6wgxJHDoyBwaOG6o24gaOG7k2khPC8wPiIsCiAgICAiZmVlZGJhY2tfcHJvbXB0IjogIjwwPkNow7puZyB0w7RpIG114buRbiBuZ2hlIHBo4bqjbiBo4buTaSBj4bunYSBi4bqhbiDEkeG7gyBjw7JuIGPhuqNpIHRoaeG7h24gdHLhuqNpIG5naGnhu4dtIGNobyBi4bqhbi48LzA+IiwKICAgICJoZWFkbGluZSI6ICJ7e2Rpc3BsYXlOYW1lfX0sIGN14buZYyBn4buNaSDEkcOjIGvhur90IHRow7pjLiIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiw4JtIHRoYW5oIiwKICAgICJhdmF0YXIiOiAi4bqibmggxJHhuqFpIGRp4buHbiIsCiAgICAiZGlzcGxheV9uYW1lIjogIlTDqm4gaGnhu4NuIHRo4buLIiwKICAgICJsb2FkaW5nIjogIsSQYW5nIHThuqNp4oCmIiwKICAgICJwYXNzd29yZCI6ICJN4bqtdCBraOG6qXUiLAogICAgInByb2ZpbGUiOiAiSOG7kyBzxqEiLAogICAgInNldHRpbmdzIjogIkPDoGkgxJHhurd0IiwKICAgICJ1c2VybmFtZSI6ICJUw6puIG5nxrDhu51pIGTDuW5nIiwKICAgICJ2aWRlbyI6ICJUcnV54buBbiBow6xuaCIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAiVsOibmcsIHRoYW0gZ2lhIGN14buZYyBn4buNaSIsCiAgICAidGV4dCI6ICJDdeG7mWMgZ+G7jWkgxJHDoyB04buTbiB04bqhaSwgYuG6oW4gY8OzIG114buRbiB0aGFtIGdpYSBraMO0bmc/IiwKICAgICJ0aXRsZSI6ICJUaGFtIGdpYSBjdeG7mWMgZ+G7jWk/IgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAiVGnDqnUgxJFp4buDbSIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIlRoYW0gZ2lhIGN14buZYyBn4buNaSIKICB9LAogICJsb2dnaW5nX2luIjogIsSQYW5nIMSRxINuZyBuaOG6rXDigKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPlThuqFvIHTDoGkga2hv4bqjbjwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBraMOhYzwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLEkMSDbmcgbmjhuq1wIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJN4buZdCBuZ8aw4budaSBkw7luZyBraMOhYyB0cm9uZyBjdeG7mWMgZ+G7jWkgxJFhbmcgZ+G6t3AgduG6pW4gxJHhu4EuIMSQ4buDIGPDsyB0aOG7gyBjaOG6qW4gxJFvw6FuIHThu5F0IGjGoW4gY2jDum5nIHTDtGkgbXXhu5FuIHRodSB0aOG6rXAgbmjhuq10IGvDvSBn4buhIGzhu5dpLiIsCiAgICAidGl0bGUiOiAiWcOqdSBj4bqndSBuaOG6rXQga8O9IGfhu6EgbOG7l2kiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAixJBhbmcgZ+G7rWnigKYiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJDaMawYSB04bqjaSDEkcaw4bujYyBSZWNhcHRjaGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJN4bqtdCBraOG6qXUgcGjhuqNpIGto4bubcCIsCiAgICAicmVnaXN0ZXJpbmciOiAixJBhbmcgxJHEg25nIGvDveKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPsSQw6MgY8OzIHTDoGkga2hv4bqjbj88LzA+PDE+PDA+xJDEg25nIG5o4bqtcDwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBLaMOhY2g8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAiWMOhYyBuaOG6rW4gbeG6rXQga2jhuql1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkNoaWEgc+G6uyBtw6BuIGjDrG5oIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJOaMOgIHBow6F0IHRyaeG7g24iLAogICAgImZlZWRiYWNrX3RhYl9kZXNjcmlwdGlvbl9sYWJlbCI6ICJQaOG6o24gaOG7k2kgY+G7p2EgYuG6oW4iLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICJH4butaSBwaOG6o24gaOG7k2kiLAogICAgImZlZWRiYWNrX3RhYl9zZW5kX2xvZ3NfbGFiZWwiOiAiS8OobSB0aGVvIG5o4bqtdCBrw70gZ+G7oSBs4buXaSIsCiAgICAiZmVlZGJhY2tfdGFiX3RoYW5rX3lvdSI6ICJD4bqjbSDGoW4sIGNow7puZyB0w7RpIMSRw6Mgbmjhuq1uIMSRxrDhu6NjIHBo4bqjbiBo4buTaSEiLAogICAgImZlZWRiYWNrX3RhYl90aXRsZSI6ICJQaOG6o24gaOG7k2kiCiAgfSwKICAic3VibWl0dGluZyI6ICLEkGFuZyBn4butaeKApiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAiQ2jGsGEgxJHEg25nIGvDvT8gPDI+VOG6oW8gdMOgaSBraG/huqNuPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLEkMSDbmcgbmjhuq1wIHbDoG8gdMOgaSBraG/huqNuIGPhu6dhIGLhuqFuIiwKICAidmVyc2lvbiI6ICJQaGnDqm4gYuG6o246IHt7dmVyc2lvbn19Igp9Cg==",pKe=""+new URL("zh-Hans-app-8pDbXAOO.json",import.meta.url).href,mKe=""+new URL("zh-Hant-app-BV1LKS_j.json",import.meta.url).href,{slice:gKe,forEach:vKe}=[];function yKe(n){return vKe.call(gKe.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}const o$=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,_Ke=function(n,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${n}=${i}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!o$.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!o$.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s},a$={create(n,e,t,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+t*60*1e3)),r&&(i.domain=r),document.cookie=_Ke(n,encodeURIComponent(e),i)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let r=0;r<t.length;r++){let i=t[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(n){this.create(n,"",-1)}};var bKe={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return a$.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;t&&typeof document<"u"&&a$.create(t,n,r,i,s)}},SKe={name:"querystring",lookup(n){var r;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:i}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(i=window.location.hash.substring(window.location.hash.indexOf("?")));const o=i.substring(1).split("&");for(let a=0;a<o.length;a++){const l=o[a].indexOf("=");l>0&&o[a].substring(0,l)===e&&(t=o[a].substring(l+1))}}return t}};let ch=null;const l$=()=>{if(ch!==null)return ch;try{if(ch=typeof window<"u"&&window.localStorage!==null,!ch)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{ch=!1}return ch};var EKe={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&l$())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&l$()&&window.localStorage.setItem(t,n)}};let uh=null;const c$=()=>{if(uh!==null)return uh;try{if(uh=typeof window<"u"&&window.sessionStorage!==null,!uh)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{uh=!1}return uh};var wKe={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&c$())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&c$()&&window.sessionStorage.setItem(t,n)}},CKe={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:r,language:i}=navigator;if(t)for(let s=0;s<t.length;s++)e.push(t[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},TKe={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(t=r.getAttribute("lang")),t}},RKe={name:"path",lookup(n){var i;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(i=t[typeof e=="number"?e:0])==null?void 0:i.replace("/",""):void 0}},IKe={name:"subdomain",lookup(n){var i,s;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,r=typeof window<"u"&&((s=(i=window.location)==null?void 0:i.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[t]}};let qte=!1;try{document.cookie,qte=!0}catch{}const Kte=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];qte||Kte.splice(1,1);const kKe=()=>({order:Kte,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class Gte{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=yKe(t,this.options||{},kKe()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(bKe),this.addDetector(SKe),this.addDetector(EKe),this.addDetector(wKe),this.addDetector(CKe),this.addDetector(TKe),this.addDetector(RKe),this.addDetector(IKe)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(t=t.concat(i))}}),t=t.map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}Gte.type="languageDetector";var P_={},u$;function xKe(){if(u$)return P_;u$=1,Object.defineProperty(P_,"__esModule",{value:!0}),P_.shouldPolyfill=n;function n(){return!Intl.Segmenter}return P_}var PKe=xKe(),L_={},d$;function LKe(){if(d$)return L_;d$=1,Object.defineProperty(L_,"__esModule",{value:!0}),L_.shouldPolyfill=n;function n(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return L_}var OKe=LKe();const Wte=Object.assign({"../locales/bg/app.json":Wqe,"../locales/cs/app.json":zqe,"../locales/de/app.json":Yqe,"../locales/el/app.json":Jqe,"../locales/en/app.json":Xqe,"../locales/es/app.json":Zqe,"../locales/et/app.json":Qqe,"../locales/fa/app.json":eKe,"../locales/fr/app.json":tKe,"../locales/id/app.json":nKe,"../locales/it/app.json":rKe,"../locales/ja/app.json":iKe,"../locales/lv/app.json":sKe,"../locales/pl/app.json":oKe,"../locales/ro/app.json":aKe,"../locales/ru/app.json":lKe,"../locales/sk/app.json":cKe,"../locales/sv/app.json":uKe,"../locales/tr/app.json":dKe,"../locales/uk/app.json":fKe,"../locales/vi/app.json":hKe,"../locales/zh-Hans/app.json":pKe,"../locales/zh-Hant/app.json":mKe}),MKe=(n,e)=>Wte[`../locales/${n}/${e}.json`],AKe=[...new Set(Object.keys(Wte).map(n=>{var t;const e=(t=n.match(/\/([^/]+)\/[^/]+\.json$/))==null?void 0:t[1];if(!e)throw new Error(`Could not parse locale URL ${n}`);return e}))],NKe={type:"backend",init(){},read(n,e,t){(async()=>{const r=MKe(n,e);if(!r)throw new Error(`Namespace ${e} for locale ${n} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(X6(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>t(null,r),r=>t(r,null))}};class DKe{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class ms{constructor(){this.isInitialized=!1,this.loadStates=new DKe}static isInitialized(){var e;return!!((e=ms.internalInstance)!=null&&e.isInitialized)}static async initBeforeReact(){const e=[];PKe.shouldPolyfill()&&e.push(Cv(()=>import("./polyfill-force-C4tXbxYu.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),OKe.shouldPolyfill()&&e.push(Cv(()=>import("./polyfill-force-49S7yrpS.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const t=new Gte;t.addDetector({name:"urlFragment",lookup:()=>Yr().lang??void 0}),await di.use(NKe).use(t).use(U2e).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:AKe,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Yr();i!==null&&document.documentElement.style.setProperty("--font-scale",i.toString()),r.length>0&&document.documentElement.style.setProperty("--font-family",r.map(s=>`"${s}"`).join(", ")),document.body.setAttribute("data-platform",Od)}static init(){var e;return(e=ms==null?void 0:ms.internalInstance)!=null&&e.initPromise?null:(ms.internalInstance=new ms,ms.internalInstance.initPromise=new Promise(t=>{var r;(r=ms.internalInstance)==null||r.initStep(t)}),ms.internalInstance.initPromise)}static reset(){ms.internalInstance=void 0}initStep(e){if(this.loadStates.config===0&&(this.loadStates.config=1,Ht.init().then(()=>{this.loadStates.config=2,this.initStep(e)},t=>{A.error("Failed to load config",t)})),this.loadStates.sentry===0&&this.loadStates.config===2){let t,r;t=Yr().sentryDsn??void 0,r=Yr().sentryEnvironment??void 0,t&&_0e({dsn:t,environment:r,integrations:[U0e({useEffect:Ce.useEffect,useLocation:ci,useNavigationType:Ife,createRoutesFromChildren:vS,matchRoutes:IL})],tracesSampleRate:1}),this.loadStates.sentry=2}this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(Dw.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const jKe=()=>{const[n,e]=_.useState(()=>Yr().theme),t=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(Ge){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),Ge.api.transport.reply(i.detail,{})};return Ge.lazyActions.on(mr.ThemeChange,r),()=>{Ge.lazyActions.off(mr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=n!=null&&n.includes("light")?"light":"dark",i=n!=null&&n.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==t.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),t.current=s),document.body.classList.remove("no-theme")},[t,n])},O_=F0e(pq),UKe=({children:n})=>{const{pathname:e}=ci();return _.useEffect(()=>{let t="";!["/login","/register"].includes(e)&&!Ge&&(t="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=t},[e]),E.jsx(E.Fragment,{children:n})},FKe=({children:n})=>(jKe(),n),$Ke=()=>{const[n,e]=_.useState(!1);return _.useEffect(()=>{var t;(t=ms.init())==null||t.then(async()=>{n||(e(!0),await(Ge==null?void 0:Ge.api.sendContentLoaded()))}).catch(A.error)}),E.jsx(hhe,{children:E.jsx(UKe,{children:E.jsx(FKe,{children:E.jsx(PG,{children:n?E.jsx(_.Suspense,{fallback:null,children:E.jsx(i8e,{children:E.jsx(J8e,{children:E.jsxs(sw,{fallback:t=>E.jsx(dy,{error:t,widget:Ge}),children:[E.jsx(Gqe,{}),E.jsxs(Vfe,{children:[E.jsx(O_,{path:"/",element:E.jsx($Q,{})}),E.jsx(O_,{path:"/login",element:E.jsx(G7e,{})}),E.jsx(O_,{path:"/register",element:E.jsx(W7e,{})}),E.jsx(O_,{path:"*",element:E.jsx(Vqe,{})})]})]})})})}):E.jsx(Uw,{})})})})})};window.setLKLogLevel=nV;M3e().catch(n=>{A.error("Failed to initialize rageshake",n)});nV("warn");Zce((n,e,t)=>{global.mx_rage_logger.log(n,"livekit",e,t)});A.info("Element Call embedded-v0.10.0-release-test.2");const kP=ble.createRoot(document.getElementById("root"));let bv=null;window.isSecureContext?navigator.mediaDevices||(bv=new Error("Your browser does not support WebRTC.")):bv=new Error(`This app cannot run in an insecure context. To fix this, access the app via a local loopback address, or serve it over HTTPS.
215
215
  https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts`);if(bv!==null)throw kP.render(bv.message),bv;ms.initBeforeReact().then(()=>{kP.render(E.jsx(_.StrictMode,{children:E.jsx($Ke,{})}))}).catch(n=>{A.error("Failed to initialize app",n),kP.render(n.message)});export{YKe as A,D_ as B,Ht as C,joe as D,ee as E,XKe as F,QKe as G,YP as H,ZKe as I,bs as J,qe as K,KKe as L,bn as M,Mt as N,_l as O,MN as P,bN as Q,eGe as R,ld as S,En as T,JKe as U,tGe as V,Lt as W,sp as X,Foe as Y,Qs as _,BKe as a,no as b,HKe as c,zKe as d,F as e,rU as f,qo as g,L as h,AQ as i,qKe as j,Rr as k,A as l,ae as m,Oh as n,Ie as o,IE as p,BP as q,ZH as r,nu as s,oGe as t,qae as u,Mp as v,La as w,ru as x,fr as y,qoe as z};
216
- //# sourceMappingURL=index-GrLQxVWo.js.map
216
+ //# sourceMappingURL=index-CWZmlDXk.js.map